2017-03-08 65 views
1

我有一個從docx文件中提取所有圖像的任務。我正在閱讀下面的代碼片段。我使用的是同樣的Apache POI API。JAVA:從docx文件提取頁腳圖像

`File file = new File(InputFileString); 
FileInputStream fs = new FileInputStream(file.getAbsolutePath()); 
//FileInputStream fs=new FileInputStream(src); 
    //create office word 2007+ document object to wrap the word file 
    XWPFDocument doc1x=new XWPFDocument(fs); 
    //get all images from the document and store them in the list piclist 
    List<XWPFPictureData> piclist=doc1x.getAllPictures(); 
    //traverse through the list and write each image to a file 
    Iterator<XWPFPictureData> iterator=piclist.iterator(); 
    int i=0; 
    while(iterator.hasNext()){ 
    XWPFPictureData pic=iterator.next(); 
    byte[] bytepic=pic.getData(); 
    BufferedImage imag=ImageIO.read(new ByteArrayInputStream(bytepic)); 
      ImageIO.write(imag, "jpg", new File("C:/imagefromword"+i+".jpg")); 
      i++; 
    }` 

但是,此代碼無法檢測到任何位於文檔的頁腳或頁眉部分的圖像。

我已經廣泛使用我的谷歌技能,並不能拿出任何有用的東西。

無論如何要捕獲 docx文件的頁腳部分中的圖像文件?

+0

您是否嘗試在頁眉和頁腳上調用[g​​etAllPictures](https://poi.apache.org/apidocs/org/apache/poi/xwpf/usermodel/XWPFHeaderFooter.html#getAllPictures())? – Gagravarr

回答

1

我對Apache POI問題專家,但一個簡單的搜索想出了this代碼:

package com.concretepage; 
import java.io.FileInputStream; 
import org.apache.poi.openxml4j.opc.OPCPackage; 
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy; 
import org.apache.poi.xwpf.usermodel.XWPFDocument; 
import org.apache.poi.xwpf.usermodel.XWPFFooter; 
import org.apache.poi.xwpf.usermodel.XWPFHeader; 
public class ReadDOCXHeaderFooter { 
    public static void main(String[] args) { 
    try { 
    FileInputStream fis = new FileInputStream("D:/docx/read-test.docx"); 
    XWPFDocument xdoc=new XWPFDocument(OPCPackage.open(fis)); 
    XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(xdoc); 
    //read header 
    XWPFHeader header = policy.getDefaultHeader(); 
    System.out.println(header.getText()); 
    //read footer 
    XWPFFooter footer = policy.getDefaultFooter(); 
    System.out.println(footer.getText()); 
    } catch(Exception ex) { 
    ex.printStackTrace(); 
    } 
    } 
} 

XWPFHeaderFooter的文檔頁面(這是直接的父類的XWPFFooter類中上面的示例...)顯示了用於迭代文檔正文中所有圖片的相同方法getAllPictures

我在手機上,所以我沒有真正測試過任何東西 - 但它看起來很簡單,足以工作。

祝你好運!