How to insert header and footer in documeto docx using Apache Poi

Asked

Viewed 172 times

0

I am trying to insert header and footer in an automatically generated docx file, the image loads but it is not visible in the file.

Just follow my code:

XWPFDocument doc = new XWPFDocument();

CTSectPr sectPr = doc.getDocument().getBody().addNewSectPr();
XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(doc,sectPr);
CTP ctpHeader = CTP.Factory.newInstance();

XWPFParagraph headerParagraph = new XWPFParagraph(ctpHeader, doc);

XWPFRun headerRun= headerParagraph.createRun();
String imgFile="ImagemCabecalho3.png";
headerRun.addPicture(new FileInputStream(imgFile),XWPFDocument.PICTURE_TYPE_PNG, imgFile, Units.toEMU(450), Units.toEMU(60));

headerParagraph.setAlignment(ParagraphAlignment.CENTER);

XWPFParagraph[] parsHeader = new XWPFParagraph[1];
parsHeader[0] = headerParagraph;
policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT, parsHeader);

Como aparece no arquivo

1 answer

0

I was able to upload the header and footer images. Follow the code below:

XWPFDocument doc = new XWPFDocument();

CTSectPr sectPr = doc.getDocument().getBody().addNewSectPr();
XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(doc,sectPr);

//Criando Header
XWPFHeader header = policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT);

XWPFParagraph paragraph = header.getParagraphArray(0);
if (paragraph == null) paragraph = header.createParagraph();

paragraph.setAlignment(ParagraphAlignment.CENTER);

XWPFRun headerRun= paragraph.createRun();
String imgFileHeader ="ImagemCabecalho3.png";
headerRun.addPicture(new FileInputStream(imgFileHeader), XWPFDocument.PICTURE_TYPE_PNG, imgFileHeader, Units.toEMU(520), Units.toEMU(60));
headerRun.addBreak();

//Criando Footer
XWPFFooter footer = policy.createFooter(XWPFHeaderFooterPolicy.DEFAULT);
paragraph = footer.getParagraphArray(0);
if (paragraph == null) paragraph = footer.createParagraph();

paragraph.setAlignment(ParagraphAlignment.CENTER);

XWPFRun footerRun= paragraph.createRun();
String imgFileFooter ="ImagemRodape3.png";
footerRun.addPicture(new FileInputStream(imgFileFooter), XWPFDocument.PICTURE_TYPE_PNG, imgFileFooter, Units.toEMU(520), Units.toEMU(60));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.