Search code examples
javapdfitext

Is there a way to create a container for elements in itextpdf 7


I want to create a kind of container, so that I can evaluate a page break for the document in itext for multiple elements. This is what I would do in HTML:

<div style={{page-break-inside: avoid}}>
   <p>Row 1</p>
   <p>Row 2</p>
</div>

How would I do that in itextpdf?


Solution

  • You can achieve page-break-inside: avoid with the setKeepTogether method applied on a div.

    Div div = new Div()
    .setKeepTogether(true);
    

    to add elements to your div simply use .add as in:

    div.add(new Paragraph("Hello World");
    

    This is featured on the iText knowledge base in chapter 4 of iText 7 Building Blocks ebook under the section "Grouping elements with the Div class".

    If you on the other hand want a page break you can add it anywhere in your document with document.add(new AreaBreak());