lucifer
lucifer

Reputation: 2327

How to add an image header in word using Apache POI

I am generating a word document using Apache POI now what i need, i need to attach an image header to that document how i can do that.This is what i have done.

  public class SimpleDocument {

public static void main(String[] args) throws Exception {
    XWPFDocument doc = new XWPFDocument();

    XWPFParagraph p1 = doc.createParagraph();
    p1.setAlignment(ParagraphAlignment.CENTER);
    p1.setBorderBottom(Borders.DOUBLE);
    p1.setBorderTop(Borders.DOUBLE);

    p1.setBorderRight(Borders.DOUBLE);
    p1.setBorderLeft(Borders.DOUBLE);
    p1.setBorderBetween(Borders.SINGLE);

    p1.setVerticalAlignment(TextAlignment.TOP);

    XWPFRun r1 = p1.createRun();
    r1.setBold(true);
    r1.setText("The quick brown fox");
    r1.setBold(true);
    r1.setFontFamily("Courier");
    r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH);
    r1.setTextPosition(100);

    XWPFParagraph p2 = doc.createParagraph();
    p2.setAlignment(ParagraphAlignment.RIGHT);

    //BORDERS
    p2.setBorderBottom(Borders.DOUBLE);
    p2.setBorderTop(Borders.DOUBLE);
    p2.setBorderRight(Borders.DOUBLE);
    p2.setBorderLeft(Borders.DOUBLE);
    p2.setBorderBetween(Borders.SINGLE);

    XWPFRun r2 = p2.createRun();
    r2.setText("jumped over the lazy dog");
    r2.setStrike(true);
    r2.setFontSize(20);

    XWPFRun r3 = p2.createRun();
    r3.setText("and went away");
    r3.setStrike(true);
    r3.setFontSize(20);
    r3.setSubscript(VerticalAlign.SUPERSCRIPT);


    XWPFParagraph p3 = doc.createParagraph();
    p3.setWordWrap(true);
    p3.setPageBreak(true);

    //p3.setAlignment(ParagraphAlignment.DISTRIBUTE);
    p3.setAlignment(ParagraphAlignment.BOTH);
    p3.setSpacingLineRule(LineSpacingRule.EXACT);

    p3.setIndentationFirstLine(600);


    XWPFRun r4 = p3.createRun();
    r4.setTextPosition(20);
    r4.setText("To be, or not to be: that is the question: "
            + "Whether 'tis nobler in the mind to suffer "
            + "The slings and arrows of outrageous fortune, "
            + "Or to take arms against a sea of troubles, "
            + "And by opposing end them? To die: to sleep; ");
    r4.addBreak(BreakType.PAGE);
    r4.setText("No more; and by a sleep to say we end "
            + "The heart-ache and the thousand natural shocks "
            + "That flesh is heir to, 'tis a consummation "
            + "Devoutly to be wish'd. To die, to sleep; "
            + "To sleep: perchance to dream: ay, there's the rub; "
            + ".......");
    r4.setItalic(true);
//This would imply that this break shall be treated as a simple line break, and break the line    after that word:

    XWPFRun r5 = p3.createRun();
    r5.setTextPosition(-10);
    r5.setText("For in that sleep of death what dreams may come");
    r5.addCarriageReturn();
    r5.setText("When we have shuffled off this mortal coil,"
            + "Must give us pause: there's the respect"
            + "That makes calamity of so long life;");
    r5.addBreak();
    r5.setText("For who would bear the whips and scorns of time,"
            + "The oppressor's wrong, the proud man's contumely,");

    r5.addBreak(BreakClear.ALL);
    r5.setText("The pangs of despised love, the law's delay,"
            + "The insolence of office and the spurns" + ".......");

    FileOutputStream out = new FileOutputStream("F://simple.docx");
    doc.write(out);
    out.close();
    System.out.println("Doc Created");
    }
}

I want to attach an image in three pages which is generating.But can not use the header footer policy properly.Somebody please help

Upvotes: 1

Views: 2888

Answers (1)

Vanja Lee
Vanja Lee

Reputation: 263

Here's how I did that... I don't know if adding image to header from scratch works in new version, but I know for a fact that "templating" works just perfectly. I created the template document in word, adapted the header the way I needed it to be, and left the rest of the document empty. When creating XWPFDocument, don't call the default constructor, but:

XWPFDocument doc = new XWPFDocument(new FileInputStream("pathTo/template.docx"));

Than just fill your new XWPFDocument instance with your content, and if you need to update the header contents for different exports like I did, implement a method similar to this:

public void updateHeader() throws InvalidFormatException, IOException {
        // load the header policy from template and update the paragraph text
        XWPFHeaderFooterPolicy headerFooterPolicy = document
                .getHeaderFooterPolicy();
        XWPFHeader defaultHeader = headerFooterPolicy.getDefaultHeader();
        defaultHeader.getParagraphs().get(0).getRuns().get(0)
                .setText("New Text", 0);
        // this is only to put some space between the content in the header and the real content
        defaultHeader.getParagraphs()
                .get(defaultHeader.getParagraphs().size() - 1)
                .setSpacingAfter(300);
    }

This works since 3.10, and if you stumble upon some java security issues, try the current nightly version where many of these security issues were resolved. For me it even worked on Google App Engine.

Upvotes: 1

Related Questions