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

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.

JavaScript errors detected

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

If this problem persists, please contact our support.