Skip to main content
Skip table of contents

How to define the page size based on the content?

I'm generating a PDF document with iTextSharp. This document must have only one page. In other words the content must fit the page size. Is it possible to achieve this with iTextSharp?

I tried to get the height of the content before adding it to the document, so I can calculate the total size before creating the document, but some content types (tables for example) don't have height until they are added to the document.

Posted on StackOverflow on Oct 18, 2015 by Boanerge

To receive the height of the table in iText7 you should work with IRenderer. We can receive the height of the table , but firstly we should determine the necessary width of our table. It will look like this:

float necessaryWidth = 523f;
IRenderer tableRenderer = table.createRendererSubTree().setParent(doc.getRenderer());
LayoutResult tableLayoutResult = tableRenderer.layout(new LayoutContext(new LayoutArea(0, new Rectangle(necessaryWidth, 1000))));
float tableHeightTotal = tableLayoutResult.getOccupiedArea().getBBox().getHeight();

And then we can use received tableHeightTotal in creating a new document and setting zero margins to our document:

Document doc2 = new Document(pdfDoc2,  new PageSize(tableWidthTotal, tableHeightTotal));

Note that all measurements are done in user units and that one user unit equals 1 pt by default.

Click How to define the page size based on the content? if you want to see how to answer this question in iText 5.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.