2

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.

Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165
Boanerge
  • 369
  • 2
  • 15
  • 1
    If you add all the content to a `ColumnText` object in simulation mode, you can ask the `ColumnText` for the height that was "consumed". Use that height to define your page height. See [Adjust page height to content height](http://stackoverflow.com/questions/27186661/adjust-page-height-to-content-height). Another option is to use a `PdfPTable` as is done here: [How to resize a PdfPTable to fit the page?](http://stackoverflow.com/questions/14958396/how-to-resize-a-pdfptable-to-fit-the-page) – Bruno Lowagie Oct 18 '15 at 23:31
  • Thank you for your answer, but I already did the job creating a temporary document and adding a PdfPTable with all the content to it. Doing that, I get the total size and then use it in a new document with the same size of the table. – Boanerge Oct 25 '15 at 01:08
  • The second option doesn't apply in my context because I don't want that the table fits to the size of the page, I need that the page fits to the size of the table. – Boanerge Oct 25 '15 at 01:19
  • You don't need to create a temporary document. If you define the width of the table, you can also define its total height and use that to define the page size. – Bruno Lowagie Oct 25 '15 at 01:20
  • I've added an answer to show you how it's done without creating a temporary document. That will save you time and CPU. – Bruno Lowagie Oct 25 '15 at 01:46

1 Answers1

2

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.

Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165