1
votes

We need to fill out a form for our customers and get a PDF, which they can print, sign & send back. As the PDF has to change frequently, we use PDF templates with form fields, which are fill by our tool (pdftk). For various reasons I would like to switch to PDFBox (one is, that it required us to split the templates in individual pages and save them to disk, fill them and then merged them together again). So far everything works fine.

But I struggle with the page numbering. As the form is combined out of multiple templates, I have to fix the page number with PDFBox. So far, we used a styled input field page_num on every page. But since they all have the same name, I can't fill them individually.

Can I somehow split or clone the fields and give them individual names, so I can fill them individually? Of course, the styling should stay like it is.

1

1 Answers

2
votes

With the help of the PDFBox guys I've got it to work. My solution is using JRuby, but I think you could pretty easily translate it to Java (remove the Java::OrgApachePdfbox... namespace).

doc = Java::OrgApachePdfboxPdmodel::PDDocument.load("input.pdf")

form = doc.getDocumentCatalog.getAcroForm
pages = doc.getDocumentCatalog.getAllPages.toArray.to_a
page_num = form.getField("page_num")
string = page_num.getDictionary
  .getDictionaryObject(Java::OrgApachePdfboxCos::COSName::DA)

page_num.getKids.to_array.each do |widget|
  widget_dict = widget.getDictionary
  widget_dict.setString(Java::OrgApachePdfboxCos::COSName::DA, string.getString)
  field = Java::OrgApachePdfboxPdmodelInteractiveForm::PDTextbox.new(
    form,
    widget_dict
  )

  field.setParent(page_num)

  page = (pages.index(widget.getPage) + 1).to_s
  field.setPartialName("page_num_#{page}")
  field.setValue(page)
end

doc.save("output.pdf")