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?

31st May 2016

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 this link if you want to see how to answer this question in iText 5.


Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now