Quantcast
Channel: Java Programming Forum - Learn Java Programming - Apache POI
Viewing all articles
Browse latest Browse all 120

add a logo in header

$
0
0
hi,
can any body please help me to add a logo in header of docx.
Code:

public static void main(String[] args) {
        try {
            //XWPFDocument docx = new XWPFDocument();
            CustomXWPFDocument docx = new CustomXWPFDocument();
            CTSectPr sectPr = docx.getDocument().getBody().addNewSectPr();
            XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(docx, sectPr);
            File imgFile = new File("D:\\test.jpg");
            //write header content
            CTP ctpHeader = CTP.Factory.newInstance();
            CTR ctrHeader = ctpHeader.addNewR();
            CTText ctHeader = ctrHeader.addNewT();
            String headerText = "This is header";
            ctHeader.setStringValue(headerText);

            XWPFParagraph headerParagraph = new XWPFParagraph(ctpHeader, docx);

            headerParagraph.setAlignment(ParagraphAlignment.CENTER);
            XWPFParagraph[] parsHeader = new XWPFParagraph[1];
            String blipId = headerParagraph.getDocument().addPictureData(
                    new FileInputStream(imgFile),
                    Document.PICTURE_TYPE_JPEG);

            docx.createPicture(blipId,
                    docx.getNextPicNameNumber(Document.PICTURE_TYPE_JPEG),
                    252, 200);

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

            //write footer content
            CTP ctpFooter = CTP.Factory.newInstance();
            CTR ctrFooter = ctpFooter.addNewR();
            CTText ctFooter = ctrFooter.addNewT();
            String footerText = "This is footer";
            ctFooter.setStringValue(footerText);
            XWPFParagraph footerParagraph = new XWPFParagraph(ctpFooter, docx);
            XWPFParagraph[] parsFooter = new XWPFParagraph[1];
            parsFooter[0] = footerParagraph;
            policy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, parsFooter);

            //write body content
            XWPFParagraph bodyParagraph = docx.createParagraph();
            bodyParagraph.setAlignment(ParagraphAlignment.CENTER);
            XWPFRun r = bodyParagraph.createRun();
            r.setBold(true);
            r.setText("This is body content.");

            FileOutputStream out = new FileOutputStream("D:/a/test.docx");
            docx.write(out);
            out.close();
            System.out.println("Done");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

please check what is the issue ,the image is added in doc not in header ,
please help me

thanks in advance

Viewing all articles
Browse latest Browse all 120

Latest Images

Trending Articles



Latest Images