利用POI抽取word中的图片并保存在文件中
poi.apache.org/hwpf/quick-guide.html
1.抽取word doc中的图片
package parse; import java.io.*;
import java.util.*; 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 ReadImgDoc { public static void main(String[] args) throws Exception {
new ReadImgDoc().readPicture("E:\\上海项目测试\\文档\\模板.doc");
} private void readPicture(String path)throws Exception{
FileInputStream in=new FileInputStream(new File(path));
HWPFDocument doc=new HWPFDocument(in);
int length=doc.characterLength();
PicturesTable pTable=doc.getPicturesTable();
// int TitleLength=doc.getSummaryInformation().getTitle().length(); // System.out.println(TitleLength);
// System.out.println(length);
for (int i=0;i<length;i++){
Range range=new Range(i, i+1,doc); CharacterRun cr=range.getCharacterRun(0);
if(pTable.hasPicture(cr)){
Picture pic=pTable.extractPicture(cr, false);
String afileName=pic.suggestFullFileName();
OutputStream out=new FileOutputStream(new File("E:\\上海项目测试\\docImage\\"+UUID.randomUUID()+afileName));
pic.writeImageContent(out); }
} } }
2.抽取 word docx文件中的图片
package parse; import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List; import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFPictureData; public class GetPicsDocx {
public static void main(String[] args) {
String path ="E:\\上海项目测试\\文档\\35.docx";
File file = new File(path);
try {
FileInputStream fis = new FileInputStream(file);
XWPFDocument document = new XWPFDocument(fis);
XWPFWordExtractor xwpfWordExtractor = new XWPFWordExtractor(document);
String text = xwpfWordExtractor.getText();
System.out.println(text);
List<XWPFPictureData> picList = document.getAllPictures();
for (XWPFPictureData pic : picList) {
System.out.println(pic.getPictureType() + file.separator + pic.suggestFileExtension()
+file.separator+pic.getFileName());
byte[] bytev = pic.getData();
FileOutputStream fos = new FileOutputStream("E:\\上海项目测试\\docxImage\\"+pic.getFileName());
fos.write(bytev);
}
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}