How to get text from textbox of MS word document using Apache POI

apache-poidocumentms-word

I want to get information written in Textbox in an MS word document. I am using Apache POI to parse word document.

Currently I am iterating through all the Paragraph objects but this Paragraph list does not contain information from TextBox so I am missing this information in output.

e.g.

paragraph in plain text

**<some information in text box>**

one more paragraph in plain text

what i want to extract :

<para>paragraph in plain text</para>

<text_box>some information in text box</text_box>

<para>one more paragraph in plain text</para>

what I am getting currently :

paragraph in plain text

one more paragraph in plain text

Anyone knows how to extract information from text box using Apache POI?

Best Answer

This worked for me,

    private void printContentsOfTextBox(XWPFParagraph paragraph) {

        XmlObject[] textBoxObjects =  paragraph.getCTP().selectPath("
            declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' 
            declare namespace wps='http://schemas.microsoft.com/office/word/2010/wordprocessingShape' 
            declare namespace v='urn:schemas-microsoft-com:vml'
            .//*/wps:txbx/w:txbxContent | .//*/v:textbox/w:txbxContent");

        for (int i =0; i < textBoxObjects.length; i++) {
            XWPFParagraph embeddedPara = null;
            try {
            XmlObject[] paraObjects = textBoxObjects[i].
                selectChildren(
                new QName("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "p"));

            for (int j=0; j<paraObjects.length; j++) {
                embeddedPara = new XWPFParagraph(
                    CTP.Factory.parse(paraObjects[j].xmlText()), paragraph.getBody());
                //Here you have your paragraph; 
                System.out.println(embeddedPara.getText());
            } 

            } catch (XmlException e) {
            //handle
            }
        }

     } 
Related Topic