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
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 (e.g. 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, e.g. 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();