-1

I am using Java 17 and the iText pdf library (5.5.4), I'm currently attempting to write a paragraph on an existing pdf file inside a rectangular area, however I seem to have a NullPointerExeption when invoking the go() method, I'm not sure exactly why. I have included my code, any help would be appreciated.

public class Main {
    public static void main(String[] args) {
        try {

            PdfReader reader = new PdfReader("src/main/resources/test_file.pdf");


            PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("src/main/resources/output.pdf"));

            PdfContentByte cb = stamper.getOverContent(1);
            ColumnText ct = new ColumnText(cb);
            ct.setSimpleColumn(new Rectangle(36, 600, 200, 800));
            ct.addElement(new Paragraph("I want to add this text in a rectangle defined by the coordinates llx = 36, lly = 600, urx = 200, ury = 800"));
            int status = ct.go();



        } catch (DocumentException | IOException e) {
            throw new RuntimeException(e);
        }
    }
}

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "com.itextpdf.text.pdf.PdfStructureElement.getAttribute(com.itextpdf.text.pdf.PdfName)" because "this.parent" is null

  • The exception text does sound like the PDF is tagged and iText attempts to add tags for the new paragraph . While doing so, though, it runs into the NPE. So either there is an issue in the tagging/structure tree of the source PDF or there is an issue with the PDF. For a true analysis we'd need the document in question. – mkl Jun 02 '23 at 09:28
  • there you go: https://drive.google.com/file/d/1d2PKbf1pqXwZTboLZOJr69KJTJtAKYUx/view This is just a simple test file created with Microsoft Word in 10 seconds – François Vinckel Jun 02 '23 at 09:35
  • 1
    Please post the full exception stacktrace and provide a [mre]. – Mark Rotteveel Jun 02 '23 at 10:14

1 Answers1

1

I could reproduce your issue using your example file with iText 5.5.4. Then I tried again with the current 5.5.13.3. There was no issue. Thus, please update.

Comparing the 5.5.4 code (where the exception occurs) with the corrsponding 5.5.13.3 code, one sees that there indeed was an unconditional call of a method of a parent object but that now there is a call to a helper method that first checks the parent and only calls its method if it isn't null.

This fix has been applied in early 2015, the commit comment was "Fixed NPE when modifying content of TaggedPDF document.".

mkl
  • 90,588
  • 15
  • 125
  • 265