Legacy notice!

iText 5 is the previous major version of iText's leading PDF SDK. iText 5 has been EOL, and is no longer developed. Switch your project to iText 7, integrating the latest developments.
Check related iText 7 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.