How to assign values at specific positions in a PDF using Java?
To assign a value to a specific position in a PDF, you can utilize Java’s PDF libraries such as iText or Apache PDFBox. Here is an example code using the iText library for implementation.
Firstly, you need to add the dependency of the iText library. If using Maven, you can add the following dependency in the pom.xml file.
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.2</version>
</dependency>
Next, you can write Java code to open a PDF file and assign values at specified locations. Here is an example code:
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.*;
import java.io.FileOutputStream;
public class PdfFillExample {
public static void main(String[] args) {
try {
// 打开PDF文件
PdfReader reader = new PdfReader("input.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("output.pdf"));
// 获取指定页面的表单域
AcroFields form = stamper.getAcroFields();
// 在指定位置设置值
form.setField("field1", "Value1");
form.setField("field2", "Value2");
// 如果需要在指定位置插入图像,可以使用以下代码:
// form.setField("imageField", "path_to_image.jpg");
// 如果需要在指定位置插入条形码,可以使用以下代码:
// form.setField("barcodeField", "123456789");
// 更新表单域
stamper.setFormFlattening(true);
// 关闭PDF文件
stamper.close();
reader.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
In the example above, we utilized the PdfStamper class to open the input PDF file and create an output file. Afterwards, we used the getAcroFields() method to retrieve form fields, and setField() method to input values at specific locations. If inserting an image or barcode at a designated position, you can use the respective field name and value.
Finally, we use the setFormFlattening(true) method to ensure that the values of the form fields are fixed, and then we call the close() method to close the PDF file.
Please note that the above example assumes you already have an existing PDF file (input.pdf) containing one or more form fields. You will need to update the field names and values as needed.