为了生成目标PDF文件,如报表。可以使用Adobe Acrobat软件对PDF进行编辑,在需要填充的地方编写text域,然后通过代码进行遍历填充。
Adobe Acrobat PDF编辑步骤
1.安装Adobe Acrobat软件
2.使用Adobe Acrobat软件打开需要编辑的PDF,在右侧点击 button tool 按钮,选择Text Field Tool,然后在页面上进行编辑,如下图,三个TextFile,t0、t1、t2。
3.对textFiled进行编辑,命名不要重复,可以编辑文字格式,默认值,如下图
java代码
package pdf;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.AcroFields.Item;
/**
* 由pdf模板生成目标pdf文件
*
*
*/
public class FillToPdfTemplate {
public static boolean fillPdfTemplate(String tempFilePath,String targetFilePath, Map<String, String> fieldValueMap) {
boolean isNewTargetFile = true;
try {
File tempFile = new File(tempFilePath);
if (!tempFile.exists()) {
throw new FileNotFoundException(tempFilePath + " 不存在...");
}
// 删除已有文件
File targetFile = new File(targetFilePath);
if (targetFile.exists()) {
targetFile.delete();
}
PdfReader reader = new PdfReader(tempFilePath);// 模版文件目录
PdfStamper ps = new PdfStamper(reader, new FileOutputStream(targetFilePath)); // 生成的输出流
AcroFields s = ps.getAcroFields();// 获取pdf模板中所有的文本域
BaseFont bfChinese = BaseFont.createFont("STSong-Light",
"UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
for (Object key : fieldValueMap.keySet()) {
System.out.println("[name]:" + key);
s.setFieldProperty(key.toString(), "textfont", bfChinese, null);// 设置中文字符集
s.setField(key.toString(), fieldValueMap.get(key));
}
ps.setFormFlattening(true);// 这句不能少
ps.close();
reader.close();
} catch (FileNotFoundException e) {
isNewTargetFile = false;
e.printStackTrace();
} catch (IOException e) {
isNewTargetFile = false;
e.printStackTrace();
} catch (DocumentException e) {
isNewTargetFile = false;
e.printStackTrace();
}finally{
}
return isNewTargetFile;
}
public static void main(String[] args) throws IOException,
DocumentException {
String tempFilePath = "d:/FirstPdf0.pdf";
String targetFilePath = "d:/FirstPdf1.pdf";
Map<String, String> filedValueMap = new HashMap<String, String>();
filedValueMap.put("t0", "this is t0 好好");
filedValueMap.put("t1", "this is t1 测试");
filedValueMap.put("t2", "this is t2 成功");
long begTime = System.currentTimeMillis();
boolean isSucc = fillPdfTemplate(tempFilePath, targetFilePath, filedValueMap);
System.out.println("run time:"+(System.currentTimeMillis()-begTime));
System.out.println(isSucc);
}
}
效果图
(模板pdf)
(生成的PDF)
本文介绍如何使用Java和iText库来填充PDF模板。首先通过Adobe Acrobat创建包含文本字段的PDF模板,接着利用Java代码读取该模板并填充指定的数据,最终生成带有实际内容的新PDF文件。
1578

被折叠的 条评论
为什么被折叠?



