iText pdf library
Website search

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

If you create a PdfPTable and if you define the width of the table, for instance like this:

table.TotalWidth = 400f;
table.LockedWidth = true;

Then you can use ask the table for its height like this:

Float h = table.TotalHeight;

You can use h to define your page size, for instance:

Document document = new Document(400, h, 0, 0, 0, 0);

Note that all measurements are done in user units and that one user unit equals 1 pt by default. The getTotalHeight() method will return 0 if you don't define the width, because the height depends on the width and the table doesn't know the width before it is rendered.


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