How to handle page breaks for a long table for html to pdf conversion using java

881 views Asked by At

I have a thymeleaf template which I'm using to convert to pdf in java using flying saucer. The pdf that is getting generated has a long table and during page breaks the table is getting continued on new page but the table headers are not appearing on the new page. If I open the html(thymeleaf with data) in browser and print it then table headers are appearing on new pages. Below is the code which I'm using to convert to pdf.

import org.xhtmlrenderer.pdf.ITextRenderer;
import com.lowagie.text.DocumentException;

private byte[] generatePdfFromHtml(String html) throws IOException, DocumentException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocumentFromString(html);
        renderer.layout();
        renderer.createPDF(byteArrayOutputStream);
        return  byteArrayOutputStream.toByteArray();
    }

Even it is working normally in browser but I still tried the below css, but it didn't work.

    table { page-break-inside:auto }
    tr    { page-break-inside:avoid; page-break-after:auto }
    thead { display:table-header-group }
    tfoot { display:table-footer-group }

My requirement is, the table should get closed on page breaks and on new page the table headers should appear.

Thank you.

2

There are 2 answers

3
tulak.hord On

You need to set CSS properties for printing, can you try using the below css:

 String css = "@page { size: auto; margin: 2cm; }"
        + "thead { display: table-header-group; }"
        + "tfoot { display: table-footer-group; }";
 //input document to the renderer 
 renderer.getSharedContext().setUserCSS(new StringReader(css));
0
obourgain On

You can use the following CSS, that will repeat the thead at the top of each page.

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