Reputation: 71
Trying to use pdfbox to create pdf with form fields that can be filled in by user or computer. So far my code looks like this:
PDDocument doc = new PDDDocument();
PDPage page = new PDPage();
doc.addPage(page)
PDAcroForm = new PDAcroForm(doc)
doc.documentCatalog.setAcroForm(acroForm)
COSDictionary cosDict = new COSDictionary()
PDTextbox textField = new PDTextbox(acroForm, cosDict)
PDRectangle rect = new PDRectangle()
rect.setLowerLeftX((float) 250)
rect.setLowerLeftY((float) 125)
rect.setUpperRightX((float) 500)
rect.setUpperRightY((float) 75)
textField.getWidget().setRectangle(rect)
acroForm.getFields.add(textField)
page.getAnnotations().add(textField)
page.getAnnotations().add(textField.getWidget())
Upvotes: 3
Views: 4769
Reputation: 82461
I had almost the same problem. I tried to add Fields to a existing document that includes a form. I came up with the following solution:
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage(page);
PDAcroForm acroForm = new PDAcroForm(doc);
doc.getDocumentCatalog().setAcroForm(acroForm);
COSDictionary cosDict = new COSDictionary();
COSArray rect = new COSArray();
rect.add(new COSFloat(250f)); // lower x boundary
rect.add(new COSFloat(75f)); // lower y boundary
rect.add(new COSFloat(500f)); // upper x boundary
rect.add(new COSFloat(125f)); // upper y boundary
cosDict.setItem(COSName.RECT, rect);
cosDict.setItem(COSName.FT, COSName.getPDFName("Tx")); // Field Type
cosDict.setItem(COSName.TYPE, COSName.ANNOT);
cosDict.setItem(COSName.SUBTYPE, COSName.getPDFName("Widget"));
cosDict.setItem(COSName.T, new COSString("yourFieldName"));
PDTextbox textField = new PDTextbox(acroForm, cosDict);
acroForm.getFields().add(textField);
page.getAnnotations().add(textField.getWidget());
I think the problem is that the widget doesn't write to the dictionary of the textField.
Upvotes: 7