Search code examples
javaitext

Cannot write a paragraph to a pdf file using iText pdf


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


Solution

  • 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.".