简体   繁体   中英

How to get HEADER / FOOTER from docx using docx4j

I am trying to get the header footer from a word document and append them to a StringBuilder . I've come across some similar questions which have led me to below snippet:

    StringBuilder sb = new StringBuilder()
    RelationshipsPart rp = documentPart.getRelationshipsPart();
    for ( Relationship r : rp.getJaxbElement().getRelationship()  ) {
        if (r.getType().equals(Namespaces.HEADER)|| r.getType().equals(Namespaces.FOOTER)) {
            println ("Entered inside header / footer")
            //How do I append the values to sb??
        }
    }

The XML for my header / footer in my DOCx is like below:

   <w:p w:rsidR="00AA4A9B" w:rsidP="00AA4A9B" w:rsidRDefault="00AA4A9B" w14:paraId="76FE289B" w14:textId="0EA049BC">
        <w:pPr>
            <w:pStyle w:val="Header"/>
            <w:jc w:val="center"/>
        </w:pPr>
        <w:r>
            <w:t>SOME TEXT HERE</w:t>
        </w:r>
        <w:r w:rsidR="000671A8">
            <w:t xml:space="preserve"> </w:t>
        </w:r>
        <w:bookmarkStart w:name="_GoBack" w:id="0"/>
        <w:bookmarkEnd w:id="0"/>
        <w:r>
            <w:t>SOME MORE TEXT HERE</w:t>
        </w:r>
    </w:p>

Question

How can I get the values in <w:t> into the StringBuilder?

Easiest is to use TextUtils.getText: https://github.com/plutext/docx4j/blob/master/src/main/java/org/docx4j/TextUtils.java#L55

Something like:

  HeaderPart hp = rp.getPart(r);
  String headerText = TextUtils.getText(hp.getContents());

Note that there is also https://github.com/plutext/docx4j/blob/master/src/samples/docx4j/org/docx4j/samples/HeaderFooterList.java for higher level access to the Header and Footer parts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM