How to get page size of pdf document iText 7

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

try (Document document = new Document(pdf)) {

by

try (Document document = new Document(pdf, pdf.getDefaultPageSize(), false)) {

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:

public void createPdf(String dest) throws IOException {

    PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
    try (Document document = new Document(pdf)) {

        document.setMargins(120, 36, 120, 36);

        document.add(new Paragraph("some content"));
        document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
        document.add(new Paragraph("some more content"));
        document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
        document.add(new Paragraph("still more content"));

        for (int i = 1; i <= document.getPdfDocument().getNumberOfPages(); i++) {

            System.out.println("PAGINA DEL PDF" + i);
            try {
                Rectangle pageSize = document.getPdfDocument().getPage(i).getPageSize();
                // Rectangle pageSize = document.getPdfDocument().getPage(i).getMediaBox();
                System.out.println("RECTANGLE....." + pageSize);
            } catch (Exception e) {
                // TODO: handle exception
                System.out.println("EXCEPCION RECTANGULO..." + e);
            }
        }
    }
}

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

Tags:

Java

Itext7