How to adjust the page height to the content height?

I'm using iTextPDF + FreeMarker for my project. Basically I load and fill an HTML template with FreeMarker and then render it to pdf with iTextPDF's XMLWorker. The code works fine, but I have a pro

I'm using iTextPDF + FreeMarker for my project. Basically I load and fill an HTML template with FreeMarker and then render it to pdf with iTextPDF's XMLWorker. The code works fine, but I have a problem with variable heights.

Let's say that we have data like this:

errorId = "ERROR-01"; systemId = "SYSTEM-01";
description = "A SHORT DESCRIPTION OF THE ISSUE"
Then the produced document looks like this:

Data fits the page

But if the data looks like this:

errorId = "ERROR-01"; systemId = "SYSTEM-01";
description = "A SHORT DESCRIPTION OF THE ISSUE.
THIS IS MULTILINE AND IT SHOULD STAY ALL IN THE SAME PDF PAGE."
The produced document is:

Data doesn't fit the page

As you can see, I now have two pages. I would like to have only one page that changes its height according to the content height.

Posted on StackOverflow on Nov 28, 2014 by BackSlash

You can not change the page size after you have added content to that page. One way to work around this, would be to create the document in two passes: first create a document to add the content, then manipulate the document to change the page size. That would have been my first reply if I had time to answer immediately.

Now that I've taken more time to think about it, I've found a better solution that doesn't require two passes. Please take a look at HtmlAdjustPageSize

For testing purposes, I used static String values for HTML and CSS:

public static final String HTML = "" +
""" +
TIMESTAMP2014-11-28 11:06:09


Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial
Contact

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