mobiw
mobiw

Reputation: 103

Paragraph height is incorrectly calculated itext 7

if i calculate height of each element and compare with page height then only 4 elements intervene

 PdfDocument pdf = new PdfDocument(new PdfWriter(DEST));
        Document document = new Document(pdf);
        pdf.setDefaultPageSize(PageSize.A5);
    document.setMargins(0, 25, 25, 25);
    float maxHeight =  document.getPdfDocument().getDefaultPageSize().getWidth() ;/* (mainPdf_model.getLeftMargin() +mainPdf_model.getRightMargin());*/
    float height = 0;
    String line = "Hello! Welcome to iTextPdf";
    Div div = new Div();
    for (int i = 0; i < 30; i++) {
        Paragraph element = new Paragraph();

        element.add(line + " " + i);
        element.setMargin(0);
        element.setPadding(0);
        element.setFixedLeading(100);
        div.add(element);
        IRenderer rendererSubTree = element.createRendererSubTree();
        LayoutResult result = rendererSubTree.setParent(document.getRenderer()).
                layout(new LayoutContext(new LayoutArea(1, new Rectangle(10000, 1000))));
        height+=result.getOccupiedArea().getBBox().getHeight();

        if(height<maxHeight) {
            System.out.println(element);
        }else {

        }


    }
  document.add(div);
        document.close();

System.out.println:

com.itextpdf.layout.element.Paragraph@319b92f3

com.itextpdf.layout.element.Paragraph@fcd6521

com.itextpdf.layout.element.Paragraph@27d415d9

com.itextpdf.layout.element.Paragraph@5c18298f

In pdf i have 6 elements:

enter image description here

Upvotes: 0

Views: 391

Answers (1)

Alexey Subach
Alexey Subach

Reputation: 12312

First of all, you have a bug in your code:

float maxHeight =  document.getPdfDocument().getDefaultPageSize().getWidth();

should be replaced with

float maxHeight =  document.getPdfDocument().getDefaultPageSize().getHeight();

When you do so, your console output will have 5 lines instead of 4 already. This is still not the 6 lines you have on your page. The difference comes from the fact that paragraph placement logic on a document does additional calculations and shifts of the first paragraph. To make sure there is not a lot of empty space at the start of the page, the first paragraph will use roughly half of the leading instead of the full leading. If you want to get precise calculations you'd better add elements to your Div and calculate the height of a Div with several Paragraph elements inside. To make the code more optimal you can use binary search on the number of elements that would fit on a single page.

Upvotes: 1

Related Questions