使用apache/pdfbox 进行PDF 表单填充

场景说明:在某个项目中,需要开发一个在线填写W8/W9 税表,并且保存成新PDF文件的功能。其中W8/W9 税表是一个带交互式表单的PDF文件。

涉及工具:apache/pdfbox(https://pdfbox.apache.org/index.html)、Adobe Acrobat

实现方式:

1.首先得知道PDF中的表单域名称,此时使用Adobe Acrobat 的表单 “导出数据”功能,导出XML文件,可从中得知表单域名称。

以W8 为例:

<?xml version=”1.0″ encoding=”utf-8″?>

<topmostSubform>
<Pg1Header xmlns:xfa=”http://www.xfa.org/schema/xfa-data/1.0/” xfa:dataNode=”dataGroup”></Pg1Header>
<DoNotUseChart xmlns:xfa=”http://www.xfa.org/schema/xfa-data/1.0/” xfa:dataNode=”dataGroup”></DoNotUseChart>
<PartI xmlns:xfa=”http://www.xfa.org/schema/xfa-data/1.0/” xfa:dataNode=”dataGroup”></PartI>
<p1-t1/>
<p1-t2/>
<p1-t3/>
<p1-t4/>
<p1-t5/>
<p1-t6/>
<p1-t7/>
<p1-t8/>
<p1-t9/>
<p1-t10/>
<p1-t11/>
<p1-t12/>
<PartII xmlns:xfa=”http://www.xfa.org/schema/xfa-data/1.0/” xfa:dataNode=”dataGroup”></PartII>
<p1-t13/>
<p1-t16/>
<p1-t15/>
<p1-t17/>
<p1-t18/>
<p1-t19/>
<p1-t20/>
<PartIII xmlns:xfa=”http://www.xfa.org/schema/xfa-data/1.0/” xfa:dataNode=”dataGroup”></PartIII>
<p1-t21/>
<p1-t22/>
</topmostSubform>

 

2.使用pdfbox 进行表单填充,demo如下:

/**
* Example to show filling form fields.
*
*/
public final class FillFormField
{
private FillFormField()
{
}

public static void main(String[] args) throws IOException
{
String formTemplate = “src/main/resources/org/apache/pdfbox/examples/interactive/form/FillFormField.pdf”;

// load the document
PDDocument pdfDocument = PDDocument.load(new File(formTemplate));

// get the document catalog
PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm();

// as there might not be an AcroForm entry a null check is necessary
if (acroForm != null)
{
// Retrieve an individual field and set its value.
PDTextField field = (PDTextField) acroForm.getField( “sampleField” );
field.setValue(“Text Entry”);

// If a field is nested within the form tree a fully qualified name
// might be provided to access the field.
field = (PDTextField) acroForm.getField( “fieldsContainer.nestedSampleField” );
field.setValue(“Text Entry”);
}

// Save and close the filled out form.
pdfDocument.save(“target/FillFormField.pdf”);
pdfDocument.close();
}

}


Leave a Reply