Apache POI how to add a page number

2020-02-06 08:20发布

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

标签: apache-poi
3条回答
时光不老,我们不散
2楼-- · 2020-02-06 08:39

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);
查看更多
\"骚年 ilove
3楼-- · 2020-02-06 08:54

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);
查看更多
可以哭但决不认输i
4楼-- · 2020-02-06 08:54
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();
}
查看更多
登录 后发表回答