I would like to create a header for docx document using apache poi but I have difficulties. I have no working code to show. I would like to ask for some piece of code as sta
Based on the previous answer, just copy and paste:
public void test1() throws IOException{
XWPFDocument sampleDoc = new XWPFDocument();
XWPFHeaderFooterPolicy policy = sampleDoc.getHeaderFooterPolicy();
//in an empty document always will be null
if(policy==null){
CTSectPr sectPr = sampleDoc.getDocument().getBody().addNewSectPr();
policy = new XWPFHeaderFooterPolicy( sampleDoc, sectPr );
}
if (policy.getDefaultHeader() == null && policy.getFirstPageHeader() == null
&& policy.getDefaultFooter() == null) {
XWPFHeader headerD = policy.createHeader(policy.DEFAULT);
headerD.getParagraphs().get(0).createRun().setText("Hello Header World!");
}
FileOutputStream out = new FileOutputStream(System.currentTimeMillis()+"_test1_header.docx");
sampleDoc.write(out);
out.close();
sampleDoc.close();
}