Konrad Zdeb
Konrad Zdeb

Reputation: 21

Why am I getting NullPointterException using PDField.setValue() from PDFBox 2.0.19?

I am trying to change text in a field of a PDF file but keep getting NullPointerException. I'm using PDFBox 2.0.19.

The file is loading fine, I'm able to for example add a page and save a new one on Desktop, but setting filed's value keeps crashing.

Can you help me please? What am I doing wrong?

public static void main(String args[]) throws IOException {
    File file = new File("C:/Users/Bondi/Desktop/karta.pdf");
    PDDocument pdDocument = PDDocument.load(file);
    PDDocumentCatalog pdDocumentCatalog = pdDocument.getDocumentCatalog();
    PDAcroForm pdAcroForm = pdDocumentCatalog.getAcroForm();
    if (pdAcroForm != null) {
        PDField pdField = (PDField) pdAcroForm.getField("imie_badacza");
        pdField.setValue("Badacz");
    }
    pdDocument.save("C:/Users/Bondi/Desktop/karta2.pdf");
    pdDocument.close();
}

Error Screenshot:

My pdf's fields hierarchy:

Upvotes: 2

Views: 628

Answers (1)

mkl
mkl

Reputation: 95918

You should use the fully qualified field name. I.e. instead of

PDField pdField = (PDField) pdAcroForm.getField("imie_badacza");

use

PDField pdField = (PDField) pdAcroForm.getField("topmostSubform.Page1.imie_badacza");

Upvotes: 1

Related Questions