Rectangular header and footer block on every page of PDF using OpenPDF

2.4k views Asked by At

I am generating a PDF invoice report using OpenPDF. On the PDF, I have to set a rectangular block for header/footer on every page. I have used the HeaderFooter class to add header/footer on every page but this works only for a Phrase.

HeaderFooter header = new HeaderFooter(new Phrase("This is a Header."), false);

Is there any way to set a rectangular block with height and width for header/footer using HeaderFooter class?

This is what I am expecting on every page:

expected output

1

There are 1 answers

5
Matt On

You can do this by creating your custom PdfPageEvent where you add the elements whenever a new page is finished (onEndPage-event). The simplest way of doing this is by extending PdfPageEventHelper in a standalone class or in an anonymous class. First, define and style your rectangles. Second, add them to the page using the PdfWriter inside the callback.

Here is a demo showing how to do it:

Document document = new Document(PageSize.A4, 40, 40, 200, 200);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("output.pdf"));

// footer
final Rectangle footer = new Rectangle(30, 30, PageSize.A4.getRight(30), 180);
footer.setBorder(Rectangle.BOX);
footer.setBorderColor(Color.BLACK);
footer.setBorderWidth(2);

// header
final Rectangle header = new Rectangle(footer);
header.setTop(PageSize.A4.getTop(30));
header.setBottom(PageSize.A4.getTop(180));

// content-box
final Rectangle box = new Rectangle(footer);
box.setTop(document.top());
box.setBottom(document.bottom());

// create and register page event to add the rectangles
writer.setPageEvent(new PdfPageEventHelper() {
    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        PdfContentByte cb = writer.getDirectContent();
        cb.rectangle(header);
        cb.rectangle(footer);
        cb.rectangle(box);
    }
});

document.open();
document.add(new Paragraph(LOREM_IPSUM)); // just some constant filler text
document.close();

The result looks like this:

result