Skip to content
Advertisement

How to get page size of pdf document iText 7

I have a java program in iText 7 that receive JSON data and generate a PDF document (with header and footer) that works fine with data in variable clientData in comment, but when use the variable in no comments clientData doesn’t works, i’m getting this error java.lang.NullPointerException, the error appears when build the header and footer (in this line Rectangle pageSize = document.getPdfDocument().getPage(i).getPageSize();), but don’t know what data is null, because the JSON data and the structure of the PDF is the same, what am i doing wrong?

This is all the code:

JavaScript

Advertisement

Answer

In short

The problem is due to your code accessing pages which iText already has flushed out of memory to the target file. You can instruct iText not to flush pages early by using the three-parameter Document constructor and setting the immediateFlush parameter to false, i.e. by replacing

JavaScript

by

JavaScript

Some explanations

iText is designed to be usable in contexts in which huge PDFs (or many PDFs concurrently) can be generated without requiring a correspondingly huge amount of memory. It lowers its memory footprint by writing finished parts of the PDF to its output target and removing them from memory. In particular when creating multi-page documents, usually only the current and the previous page remain in memory while pages before that are flushed and have the contents of the remaining page object set to null.

So when you eventually iterate over all the pages of your PDF, all but the most recent ones indeed don’t have their MediaBox entries anymore, so you get a NullPointerException when trying to access the page size.

For use cases like yours in which early flushing is not appropriate, iText offers the flag used above to keep it from flushing pages early.

As an aside…

… if you wonder why your question has not been answered earlier: You posted a gigantic piece of code which one couldn’t even execute to reproduce the issue as you did not provide a JSON string for the data parameter. To be able to reproduce the issue, therefore, I had to cut down your code to the essential core that reproduces the issue:

JavaScript

If you had done so yourself, you would have had your question answered much earlier.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement