0

I would like to create an invoice PDF using OpenPDF. It needs a header and footer on each page. I'm using Thymeleaf to generate the content for the pdf. My question is then how to add a header and/or footer to each page.

I have found a related post (Rectangular header and footer block on every page of PDF using OpenPDF), but then I would like the ability to define the header/footer using a html template string. Is that possible? Or would you recommend an other approach?

// create and register page event to add header and footer to each page
writer.setPageEvent(new PdfPageEventHelper() {
    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        PdfContentByte cb = writer.getDirectContent();
        cb.rectangle(header); // <- header should be a html template
        cb.rectangle(footer); // <- footer should be a html template
    }
});
Matt
  • 12,848
  • 2
  • 31
  • 53
  • Why are you not generating the header and the footer directly with OpenPDF instead of using Thymeleaf? If you would do this, you could add the required elements in the *onEndPage* hook instead of the rectangles. I suggest to use `ColumnText` for the absolute placement of these elements. – Matt Aug 04 '21 at 12:51
  • The idea I'm trying to achieve is to have these three files: content.html, header.html and footer.html. Use Thymeleaf to populate it with content and then use OpenPDF to stitch them together. – Lars Bak Aug 05 '21 at 07:32
  • Your question is not about header/footer, otherwise you would show us working code that already transforms your 3 HTML snippets into something the OpenPDF-API understands. Instead you are asking how to convert HTML to PDF. OpenPDF only supports the most basic HTML and if you have such basic HTML it would be much better to implement this directly instead of relying on the transformation. Depending on the HTML, you could use [*Flying Saucer*](https://github.com/flyingsaucerproject/flyingsaucer) and specify the *flying-saucer-pdf-openpdf* dependency to generate a PDF with OpenPDF under the hood. – Matt Aug 06 '21 at 05:39

0 Answers0