导出图片,将图片替换为标签,与导处图片对应
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.model.PicturesTable;
import org.apache.poi.hwpf.usermodel.CharacterRun;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.Range;
public class ReplaceDocPicToIndex {
public static String writeStr="";
public static int picIndex=0;
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
File srcFile = new File("f://美术类_色彩.doc");
File desFile = new File("f://aaa/aaa.doc");
String picsDir="f://aaa/pic";
InputStream is = new FileInputStream(srcFile);
replacePicToindex(is, picsDir, desFile);
}
//将图片替换为${index}
public static void replacePicToindex(InputStream is,String picsDir,File desFile) throws Exception{
HWPFDocument doc = new HWPFDocument(is);
int length = doc.characterLength();
PicturesTable picTable = doc.getPicturesTable();
for(int i=0;i<length-1;i++){
Range range = new Range(i,i+1,doc);
CharacterRun charRun = range.getCharacterRun(0);
if(picTable.hasPicture(charRun)){
readPic(picTable, charRun,picsDir);
}else{
writeStr+=charRun.text();
};
}
System.out.println(writeStr);
// FileUtils.writeStringToFile(desFile, writeStr, "utf-8");
}
//导出图片
public static void readPic(PicturesTable picTable,CharacterRun charRun,String picsDir) throws Exception{
DecimalFormat fmt = new DecimalFormat("0000");
String index = fmt.format((++picIndex));
Picture pic = picTable.extractPicture(charRun, false);
OutputStream out = new FileOutputStream(new File(picsDir+"/" + index + ".png"));
pic.writeImageContent(out);
writeStr += "${" + index + "}";
}
}