簡體   English   中英

如何使用Apache Poi獲取a.docx文件的一頁內容?

[英]How to get content of a page of a .docx file using Apache Poi?

我正在嘗試使用 Apache Poi 讀取帶有樣式信息的 .docx 文件,這是我通過遍歷每個 XWPFParagraph 並使用段落內運行的所有 XWPFRun 來完成的。 現在我想獲取每個頁面的內容。 那么有沒有辦法獲取每個頁面的內容,或者是否有可能知道一個段落當前在哪個頁面?

這是一個 function,它采用 docx 文件的絕對路徑並返回一個字符串數組

        FileInputStream fis = new FileInputStream(absolutePath);

        XWPFDocument document = new XWPFDocument(fis);

        List<IBodyElement> bodyElements = document.getBodyElements();

        List<String> textList = new ArrayList<>();

        /*  I want to add some kind of outer loop here for each page
            and at the end of that loop I want to add a "<hr/>" tag in the textList
        */
        for (IBodyElement bodyElement : bodyElements) {                 // Looping through paragraphs
           if (bodyElement.getElementType() == BodyElementType.PARAGRAPH) {
                XWPFParagraph paragraph = (XWPFParagraph) bodyElement;
                
                String textToAdd = parseParagraph(paragraph); //custom funtion to handle paragraphs


                textList.add(textToAdd);

            } 
        }
        document.close();
        return textList.toArray(new String[0]);

如您所見,我的目標是在每個頁面后添加一個<hr/>標記。 所以,如果我能以某種方式獲得段落的頁碼或循環瀏覽頁面,我將能夠做到這一點。
如果您知道任何其他可能有幫助的方法,請提及。

要從XWPFDocument獲取頁數(對於您的外循環),您可以執行以下操作:

XWPFDocument docx = new XWPFDocument(POIXMLDocument.openPackage(YOUR_FILE_PATH));

int numOfPages = docx.getProperties().getExtendedProperties().getUnderlyingProperties().getPages();

對於您的段落文本,

for (XWPFParagraph p : document.getParagraphs()) {
    System.out.println(p.getParagraphText()); // YOUR PARAGRAPH TEXT
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM