Flying Saucers, BREAKING tables and more!!! in PDF

Flying Saucers, BREAKING tables and more!!! in PDF

For the past month I've been working on creating html templates to be converted in pdf so they can be printed later.

It's a bit better than writing email templates but it still has challenges.

One of the challenges were: "how do we break the tables from page to page that are filled with dynamic content"?

We needed to split the table from page 1 to page 2 (3, 4, 5...) by repeating the header on each page.

Here is where The Flying Saucer project came VERY handy.

I just needed to add on the tables the following css code to the table:

.dynamic-table {
   -fs-table-paginate: paginate;
}

But, the html also needs to have the following structure: (note that I'm using thymeleaf for the actual data template)

 <table>
  <thead>
     <tr><th>head 1</th><th>head 2</th></tr>
  </thead>
  <tbody>
     <tr th:each="${row: myRowData}">
         <td><span th:text="${row.col1}"></span></td>
         <td><span th:text="${row.col1}"></span></td>
     </tr>
  </tbody>
</table>

So, you will nead a thead that will make sure the header repeats on each new page.

But with just this code, you will see that sometimes the table row will break and you will have the row going from one page to the other. And this just looks bad.

To fix this, you need to add the following css:

.dynamic-table tr {
    page-break-inside: avoid;
}

Some gotchas

I also had a headless table with an empty rectangle in one of its tds which also needed to avoid breaking inside. But for some reason, I had this issue or this issue or this issue or this... well, you get the idea. The damn rectangle kept on breaking when going to a new page and I needed it to be whole on one of the pages. The rectangle had a width, position relative, everything you might think of, but it still broke.

After trying all of the solutions I could find on stackoverflow or other forums, I had a crazy idea which actually made it work.

What is did was the following:

  1. I added an thead with tr and th that had some dummy text in it

  2. I filled the empty rectangle with text

And to my surprise, this actually worked!

<table>
  <thead>
  <tr>
    <th>a</th>
    <th>b</th>
  </tr>
  </thead>
  <tbody>
  <tr>
    <td>
      <strong>SIGNATURE</strong>
    </td>
    <td class="signature-box">
      <div>this is some signature this is some signature this is some signature this is some signature this is some signature
      </div>
    </td>
  </tr>
  </tbody>
</table>

The .signature-box is the rectangle.

After, I just made the text #ffffff and the th with height: 0 and problem solved!

Good luck!