2013-06-07 2 views
0

Как читать изображения в файле .doc ms-office с помощью Apache poi? Я пробовал использовать следующий код, но он не работает.Как читать изображения в файле .doc

try { 
    POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("C:\\DATASTORE\\ImageDocument.doc")); 
    Document document = new Document(); 
    OutputStream fileOutput = new FileOutputStream(new File("C:/DATASTORE/ImageDocumentPDF.pdf")); 
    PdfWriter.getInstance(document, fileOutput); 
    document.open(); 

    HWPFDocument hdocument=new HWPFDocument(fs); 
    Range range=hdocument.getOverallRange(); 
    PdfPTable createTable; 
    CharacterRun run; 
    PicturesTable picture=hdocument.getPicturesTable(); 
    int picoffset=run.getPicOffset(); 
    for(int i=0;i<range.numParagraphs();i++) { 
     run =range.getCharacterRun(i); 
     if(picture.hasPicture(run)) { 
      Picture pic=picture.extractPicture(run, true); 
      byte[] picturearray=pic.getContent(); 
      com.itextpdf.text.Image image=com.itextpdf.text.Image.getInstance(picturearray); 
      document.add(image); 
     } 
    } 
} 

Когда я выполнить приведенный выше код и выводит значение смещения изображений отображает -1 и при печати picture.hasPicture (бег) возвращает ложных хотя входной файл имеет образ.

Пожалуйста, помогите найти решение проблемы. Спасибо

ответ

0

он работал для меня, если picOffset возвращает -1, это означает, что нет изображений для текущего CharacterRun

2
public static List<byte[]> extractImagesFromWord(File file) { 
    if (file.exists()) { 
     try { 
      List<byte[]> result = new ArrayList<byte[]>(); 
      if ("docx".equals(getMimeType(file).getExtension())) { 
       org.apache.poi.xwpf.usermodel.XWPFDocument doc = new XWPFDocument(new FileInputStream(file)); 
       for (org.apache.poi.xwpf.usermodel.XWPFPictureData picture : doc.getAllPictures()) { 
        result.add(picture.getData()); 
       } 
      } else if ("doc".equals(getMimeType(file).getExtension())) { 
       org.apache.poi.hwpf.HWPFDocument doc = new HWPFDocument(new FileInputStream(file)); 
       for (org.apache.poi.hwpf.usermodel.Picture picture : doc.getPicturesTable().getAllPictures()) { 
        result.add(picture.getContent()); 
       } 
      } 
      return result; 
     } catch (Exception e) { 
      throw new RuntimeException(e); 
     } 
    } 
    return null; 
} 
Смежные вопросы