Elliot Elliot - 1 month ago 8
Java Question

IText7 only creates form/widgets on new documents

When running this code with the PdfDocument not having a read source, it works properly. When I try reading from a premade pdf it stops creating the form/widgets, but still adds the paragraph as expected. There is no error given. Does anyone understand why this is happening?

Here is the code I'm running:

public class HelloWorld {

public static final String DEST = "sampleOutput.pdf";
public static final String SRC = "sample.pdf";
public static void main(String args[]) throws IOException {
File file = new File(DEST);

new HelloWorld().createPdf(SRC, DEST);
}

public void createPdf(String src, String dest) throws IOException {
//Initialize PDF reader and writer
PdfReader reader = new PdfReader(src);
PdfWriter writer = new PdfWriter(dest);

//Initialize PDF document
PdfDocument pdf = new PdfDocument(writer); //if i do (reader, writer) the widget isn't added to the first page anymore.

// Initialize document
Document document = new Document(pdf);

HelloWorld.addAcroForm(pdf, document);

//Close document
document.close();
}

public static PdfAcroForm addAcroForm(PdfDocument pdf, Document doc) throws IOException {
Paragraph title = new Paragraph("Test Form")
.setTextAlignment(TextAlignment.CENTER)
.setFontSize(16);
doc.add(title);
doc.add(new Paragraph("Full name:").setFontSize(12));

//Add acroform
PdfAcroForm form = PdfAcroForm.getAcroForm(doc.getPdfDocument(), true);
//Create text field
PdfTextFormField nameField = PdfFormField.createText(doc.getPdfDocument(),
new Rectangle(99, 753, 425, 15), "name", "");

form.addField(nameField);
return form;

}
}

Answer

I adapted your code like this:

public static PdfAcroForm addAcroForm(PdfDocument pdf, Document doc) throws IOException {
    Paragraph title = new Paragraph("Test Form")
            .setTextAlignment(TextAlignment.CENTER)
            .setFontSize(16);
    doc.add(title);
    doc.add(new Paragraph("Full name:").setFontSize(12));

    PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, true);
    PdfTextFormField nameField = PdfFormField.createText(pdf,
            new Rectangle(99, 525, 425, 15), "name", "");
    form.addField(nameField, pdf.getPage(1));
    return form;
}

You'll notice two changes:

  1. I change the Y offset of the field (525 instead of 753). Now the field is added inside the visible area of the page. In your code, the field was added, but it wasn't visible.
  2. I defined to which page the fields needs to be added by adding pdf.getPage(1) as second parameter for the addField() method.
Comments