Print headings of a word document (docx)

Viewed 28

In an docx document i want to be able to get a list with all Headings (chapters) in the file. Every text that has 'Heading 1', 'Heading 2' etc. This is the word file:

enter image description here

I am using apache POI to read into the file. However when i try to get the style from a paragraph or a run it always returns NULL.

        File f=new File("src/TestFile.docx");
        FileInputStream fis = new FileInputStream(f);
        XWPFDocument xdoc=new XWPFDocument(OPCPackage.open(fis));
        
        XWPFStyles styles = xdoc.getStyles();
        java.util.List<XWPFParagraph> xwpfparagraphs  = new ArrayList<XWPFParagraph>();
        xwpfparagraphs = xdoc.getParagraphs();

        System.out.println("Styleid paragraph: " +xwpfparagraphs.get(0).getStyleID());
        
        XWPFParagraph paragraph = xwpfparagraphs.get(0);
        
        for (XWPFRun run : paragraph.getRuns()) {
            System.out.println("Styleid run: " + run.getStyle());
        }

Output:

        Styleid paragraph: null
        Styleid run: 
        Styleid run: 
        Styleid run:

So the problem is, how can i recognize the headings if i can't trace back the style of the text? How to do this correctly?

1 Answers

This is the code i ended up with. This worked.

        FileInputStream file =  FileInputStream(*pathToFileWithFileNameAndExtenstion*);
        XWPFDocument xdoc = new XWPFDocument(OPCPackage.open(file));

        XWPFStyles styles = xdoc.getStyles();
        java.util.List<XWPFParagraph> xwpfparagraphs = xdoc.getParagraphs();

        for (int i = 0; i < xwpfparagraphs.size(); i++) {
            XWPFParagraph paragraph = xwpfparagraphs.get(i);
            
            if(paragraph.getStyleID() != null) {
                headings.add(paragraph.getText());
            }
        }

After this, printing the ArrayList 'headings' shows all the headings in the designated document (docx).

Related