简体   繁体   中英

Fit iText 7 Table to Single Page with Images using JPype

I am attempting to fit all the content of a table to a single A4 PDF.

I found another SO article linked to the itextpdf page here on the same topic

However, I am not certain how it is supposed to be implemented. I have the above code converted to JPype and it seems to run. But I do not get the desired effect.

I want to be able to add images to this table, and have it size appropriately so that it maintains a single A4 page.

Source and example on my github page here: https://github.com/krowvin/jpypeitext7example

Example PDF

Source

Suppose that this is the table to be fully fit into an A4 page:

    Table table = new Table(2);
    for (int i = 0; i < 100; i++) {
        table.addCell(new Cell().add(new Paragraph(i + " Hello")));
        table.addCell(new Cell().add(new Paragraph(i + " World")));
    }

Since it's too long to be fully fit via usual layout flow (eg Document#add ), we should somehow scale it. But first of all, let us find how much space this table occupies if the page to be placed upon is boundless:

    LayoutResult result = table.createRendererSubTree().setParent(doc.getRenderer())
            .layout(new LayoutContext(new LayoutArea(1, new Rectangle(10000, 10000))));
    Rectangle occupiedRectangle = result.getOccupiedArea().getBBox();

Now let's create a form xobject of this table, which we will scale a few lines below:

    PdfFormXObject xObject = new PdfFormXObject(new Rectangle(occupiedRectangle.getWidth(), occupiedRectangle.getHeight()));
    new Canvas(xObject, pdfDoc).add(table).close();

So now we have the xObject of the table, the only question is how to fit it, eg which scale coefficients to apply:

   double coefficient = Math.min(PageSize.A4.getWidth() / occupiedRectangle.getWidth(), 
            PageSize.A4.getHeight() / occupiedRectangle.getHeight());

We're almost done: now let's add the scaled version of the table to the document's page:

        new PdfCanvas(pdfDoc.addNewPage())
            .saveState()
            .concatMatrix(coefficient, 0, 0, coefficient, 0, 0)
            .addXObject(xObject)
            .restoreState();

And that's it: 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM