// Load the pdfTemplate pdfTemplate = PDDocument.load(file); PDDocumentCatalog docCatalog = pdfTemplate.getDocumentCatalog(); PDAcroForm acroForm = docCatalog.getAcroForm(); // Get field names List<PDField> fieldList = acroForm.getFields(); // String the object array String[] fieldArray = new String[fieldList.size()]; int i = 0; for (PDField sField : fieldList) { fieldArray[i] = sField.getFullyQualifiedName(); i++; } // Loop through each field in the array and do something for (String f : fieldArray) { PDField field = acroForm.getField(f); System.out.println("f is: " + f); if (f.contains("EXAMPLE FORM FIELD NAME")) { DO SOMETHING String value = "example value"; field.setValue(value); System.out.println("printed: " + value + " to: " + f); } } // Save edited file pdfTemplate.save(sPdfTemplate); pdfTemplate.close();
private void setFieldValueAndFlatten(PDAcroForm form, String fieldName, String fieldValue) throws IOException { PDField field = form.getField(fieldName); if(field != null){ field.setValue(fieldValue); field.setReadonly(true); } }
field.setValue(values.get(partialName));
public class PDFBOX { public static void main(String[] args) throws IOException { PDDocument fdeb = null; File pdfFile = new File("C:\\Users\\pc\\Desktop\\Req-form.pdf"); fdeb = PDDocument.load(pdfFile); PDDocumentCatalog pdCatalog = fdeb.getDocumentCatalog(); PDAcroForm pdAcroForm = pdCatalog.getAcroForm(); // Text fields PDField firstName = pdAcroForm.getField("firstName"); firstName.setValue("firstName"); fdeb.save("C:\\Users\\Desktop\\Test.pdf"); fdeb.close(); } }
byte[] template = generateSimpleTemplate(); Files.write(new File(RESULT_FOLDER, "template.pdf").toPath(), template); try ( PDDocument finalDoc = new PDDocument(); ) { List<PDField> fields = new ArrayList<PDField>(); int i = 0; for (String value : new String[]{"eins", "zwei"}) { PDDocument doc = new PDDocument().load(new ByteArrayInputStream(template)); PDDocumentCatalog docCatalog = doc.getDocumentCatalog(); PDAcroForm acroForm = docCatalog.getAcroForm(); PDField field = acroForm.getField("SampleField"); field.setValue(value); field.setPartialName("SampleField" + i++); List<PDPage> pages = docCatalog.getAllPages(); finalDoc.addPage(pages.get(0)); fields.add(field); } PDAcroForm finalForm = new PDAcroForm(finalDoc); finalDoc.getDocumentCatalog().setAcroForm(finalForm); finalForm.setFields(fields); finalDoc.save(new File(RESULT_FOLDER, "form-two-templates.pdf")); }