Add empty form field to an existing page

Viewed 45

I tried to use the "CreateEmptySignatureForm.java" example in PDFBox GitHub, and it is only working if I have a new page on my document. If I want to use the first page of the document, the empty signature form field does not appear in Adobe Reader.

This is the code that works for a new page:

PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);

PDAcroForm acroForm = new PDAcroForm(document);
document.getDocumentCatalog().setAcroForm(acroForm);

String defaultAppearanceString = "/Helv 0 Tf 0 g";
acroForm.setDefaultAppearance(defaultAppearanceString);

PDTextField textBox = new PDTextField(acroForm);
textBox.setPartialName("SampleField");

defaultAppearanceString = "/Helv 12 Tf 0 0 1 rg";
textBox.setDefaultAppearance(defaultAppearanceString);

acroForm.getFields().add(textBox);

PDSignatureField signatureField = new PDSignatureField(acroForm);
PDAnnotationWidget widget = signatureField.getWidgets().get(0);
PDRectangle rect = new PDRectangle(50, 100, 200, 50);
widget.setRectangle(rect);

widget.setPage(page);

widget.setPrinted(true);

page.getAnnotations().add(widget);

acroForm.getFields().add(signatureField);

ByteArrayOutputStream out = new ByteArrayOutputStream();

document.save(out);

This is my code:

PDPage page =  document.getPages().get(0);

PDAcroForm acroForm = new PDAcroForm(document);
document.getDocumentCatalog().setAcroForm(acroForm);

String defaultAppearanceString = "/Helv 0 Tf 0 g";
acroForm.setDefaultAppearance(defaultAppearanceString);

PDTextField textBox = new PDTextField(acroForm);
textBox.setPartialName("SampleField");

defaultAppearanceString = "/Helv 12 Tf 0 0 1 rg";
textBox.setDefaultAppearance(defaultAppearanceString);

acroForm.getFields().add(textBox);

PDSignatureField signatureField = new PDSignatureField(acroForm);
PDAnnotationWidget widget = signatureField.getWidgets().get(0);
PDRectangle rect = new PDRectangle(50, 100, 200, 50);
widget.setRectangle(rect);

widget.setPage(page);

widget.setPrinted(true);

page.getAnnotations().add(widget);

acroForm.getFields().add(signatureField);

ByteArrayOutputStream out = new ByteArrayOutputStream();

document.save(out);
    

Can anybody help me out?

1 Answers

I figured out the problem :

I need to add this line code :

page.getCOSObject().setNeedToBeUpdated(true);
Related