How to create a header/footer in new docx document?

故事扮演 提交于 2019-12-24 02:18:59

问题


I would like to create a header and footer on a docx document (a new one and not existing one) with XWPF jars (apache poi).

When I use XWPFHeaderFooterPolicy policy = document.getHeaderFooterPolicy(); policy is null, so I would know how to create it in a new document.

CustomXWPFDocument document = new CustomXWPFDocument();
XWPFHeaderFooterPolicy policy = document.getHeaderFooterPolicy();
XWPFHeader head = policy.createHeader(policy.DEFAULT);
head.getListParagraph().get(0).createRun().setText("Hello Header World!");
CTP ctP1 = CTP.Factory.newInstance();
CTR ctR1 = ctP1.addNewR();
CTText t = ctR1.addNewT();
t.setStringValue("Paragraph in header");
XWPFParagraph p1 = new XWPFParagraph(ctP1, document);
XWPFParagraph[] pars = new XWPFParagraph[1];
pars[0] = p1;
policy.createHeader(policy.FIRST, pars);

回答1:


You must add a section property to the XWPFDocument doc if not already present by using following code

CTBody body = doc.getDocument().getBody();
CTSectPr sectPr = body.isSetSectPr()? body.getSectPr() : body.addNewSectPr();



回答2:


I had the same problem but didn't find any solution. In this case I created template docx file with header and footer and than change them. This practice I found in Apache mail archives.




回答3:


public static void setFooter(XWPFDocument document, String footerText) {
    CTP ctpFooter = CTP.Factory.newInstance();
    ctpFooter.addNewR().addNewT();

    XWPFParagraph footerParagraph = new XWPFParagraph(ctpFooter, document);
    XWPFRun footerRun = createFormattedRun(footerParagraph);
    footerRun.setFontSize(6);
    footerRun.setText(footerText);
    XWPFParagraph[] parsFooter = new XWPFParagraph[1];
    parsFooter[0] = footerParagraph;

    CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
    XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(document, sectPr);
    policy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, parsFooter);
}


来源:https://stackoverflow.com/questions/27128317/how-to-create-a-header-footer-in-new-docx-document

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!