Contents
Intro
The PDF template file for testing link here : test_template.pdf
Effect Screenshots
The left "test1111.pdf" is a pdf template before filling text.
The right "test2222.pdf" is result pdf file after filling text.
Paste below dependencies to your pom.xml
com.itextpdf
itext-asian
5.2.0
com.itextpdf
itextpdf
5.5.4
The complete Java code example
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
public class PDFTest {
public static void main(String[] args) {
// pdf template path (you can get an online file here : https://blog.zhouzhipeng.com/wp-content/uploads/2019/07/test_template.pdf)
String templatePath = "/Users/zhouzhipeng/Downloads/test1111.pdf";
// new pdf path
String newPDFPath = "/Users/zhouzhipeng/Downloads/test2222.pdf";
try {
FileOutputStream out = new FileOutputStream(newPDFPath);
PdfReader reader = new PdfReader(templatePath);
PdfStamper stamper = new PdfStamper(reader, out);
AcroFields form = stamper.getAcroFields();
Map map = new HashMap<>();
map.put("Anticipated monthly number of transactions outgoing", "aaaaa");
map.put("Description of how the individual interacts with digital assets", "bbbbb");
map.put("Nature / Purpose of the Account", "cccccc");
map.put("Anticipated monthly volume in USD", "10000");
map.put("Anticipated Trading Patterns", "online");
map.put("Anticipated monthly number of transactions incoming", "10");
map.put("Date", "2019/07/10");
map.put("Please list any associations the individual has with previous or current accounts with Prime Trust", "no");
map.put("Anticipated types of assets deposited into account", "btc");
map.put("TItle or Position", "test title");
map.put("Referred By Or Prime Trust Representative", "i don't know");
map.put("Long hand Signature", "zhouzhipeng");
map.put("Signature", "xiaozhou");
map.put("Sources of assets income", "salary");
for (String name : form.getFields().keySet()) {
form.setField(name, map.get(name));
}
//true means the new PDF is uneditable
stamper.setFormFlattening(true);
stamper.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Debug the code for getting the Placeholders
debugging the javacode ,and watch on the variable "form".
Comments