How to Create PDF with recurring logo using iText, HTML and thymeleaf

489 Views Asked by At

I am making use of HTML, thymeleaf and flying-saucer-pdf

I have the code at following link to convert html to pdf: https://github.com/Naresh-Chaurasia/html-pdf-generation-1x

HTML: https://github.com/Naresh-Chaurasia/html-pdf-generation-1x/blob/main/src/main/resources/pdf-templates/order-template.html

Java To Convert HTML to PDF using iText: https://github.com/Naresh-Chaurasia/html-pdf-generation-1x/blob/main/src/main/java/in/connect2tech/html/pdf/HtmlToPdfMain.java

Everything works fine and below is the sample PDF generated.

enter image description here


Problem Statement: The problem arises when the record spans more than 1 page. I am not able to create the header in all the pages, as can be seen in the screenshot below, the records start without the header and logo.

Question:How can I repeat the header logo on all the generated pdfs.

Thanks for any pointers/help in advance.


enter image description here

1

There are 1 best solutions below

0
obourgain On

You have to use CSS 2.0 paged media to define a header on your HTML document.

  • Create a div which contains the content to be repeated as header
<div id="header">
    <table>
        <tr>
            <td>
                <img width="80" src="https://simplesolution.dev/images/Logo_S_v1.png" />
            </td>
            <td>
                <h1>Supply Order Form</h1>
            </td>
        </tr>
    </table>

    <div>
        <table>
            <tr>
                <td th:text="'Date: ' + ${#dates.format(order.date, 'dd/MM/yyyy')}"></td>
            </tr>
           (...)
        </table>
    </div>
</div>
  • Add the following CSS to repeat this content on each page
@page {
    @top-center {  content: element(header);  }
    margin-top:10cm; /* Adjust this value to the size of the element */
                     /* you want to repeat on each page              */
}
#header {
    position: running(header);
}

You will also probably want to repeat the header of the table.

For that, you need to put the first line in a <thead> and the content in a <tbody>.

<table class="order">
    <thead>
    <tr>
        <th>Item #</th>
        <th>Description</th>
        <th>Quantity</th>
        <th>Unit Price</th>
        <th>Total</th>
    </tr>
    </thead>
    <tbody>
        (...)
    </tbody>
</table>

And then add the following CSS on the table

.order {
    -fs-table-paginate: paginate;
    border-spacing: 0;
}