Apache POI how to add a page number

2020-02-06 07:59发布

问题:

Just started to use POI 3.10 to create a Word document (XWPF). Most of the things are straight forward, but I don't understand how to add page numbers. I added the footer, but the text in the footer is the same on every page

回答1:

I created a page number in the footer on the right in LibreOffice and investigated the XML file (MS Word-Std-Objects are not supported in POI which is used there for page numbers).

This will enable to create more complex footers...

to set the number to other positions set another value for ctjc instead of STJc.RIGHT...

The result is the following:

// create footer
XWPFHeaderFooterPolicy policy = doc.getHeaderFooterPolicy();
CTP ctpFooter = CTP.Factory.newInstance();

XWPFParagraph[] parsFooter;

// add style (s.th.)
CTPPr ctppr = ctpFooter.addNewPPr();
CTString pst = ctppr.addNewPStyle();
pst.setVal("style21");
CTJc ctjc = ctppr.addNewJc();
ctjc.setVal(STJc.RIGHT);
ctppr.addNewRPr();

// Add in word "Page "   
CTR ctr = ctpFooter.addNewR();
CTText t = ctr.addNewT();
t.setStringValue("Page ");
t.setSpace(Space.PRESERVE);

// add everything from the footerXXX.xml you need
ctr = ctpFooter.addNewR();
ctr.addNewRPr();
CTFldChar fch = ctr.addNewFldChar();
fch.setFldCharType(STFldCharType.BEGIN);

ctr = ctpFooter.addNewR();
ctr.addNewInstrText().setStringValue(" PAGE ");

ctpFooter.addNewR().addNewFldChar().setFldCharType(STFldCharType.SEPARATE);

ctpFooter.addNewR().addNewT().setStringValue("1");

ctpFooter.addNewR().addNewFldChar().setFldCharType(STFldCharType.END);

XWPFParagraph footerParagraph = new XWPFParagraph(ctpFooter, doc);

parsFooter = new XWPFParagraph[1];

parsFooter[0] = footerParagraph;

policy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, parsFooter);


回答2:

CTP ctp = CTP.Factory.newInstance();
//this add page number incremental
ctp.addNewR().addNewPgNum();

XWPFParagraph codePara = new XWPFParagraph(ctp, document);
XWPFParagraph[] paragraphs = new XWPFParagraph[1];
paragraphs[0] = codePara;
//position of number
codePara.setAlignment(ParagraphAlignment.CENTER);

CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();

try {
    XWPFHeaderFooterPolicy headerFooterPolicy = new XWPFHeaderFooterPolicy(document, sectPr);
    headerFooterPolicy.createFooter(STHdrFtr.DEFAULT, paragraphs);
} catch (IOException | XmlException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}


回答3:

Hope this helps.

XWPFParagraph p1 = doc.createParagraph();
XWPFRun r1 = p1.createRun();
r1.setText("Page ");
r1.getCTR().addNewPgNum();
r1.setText(" of 9");
p1.setAlignment(ParagraphAlignment.RIGHT);


标签: apache-poi