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:\\d2p\\test.pdf";
String targetFilePath = "D:\\d2p\\testmodel.pdf";
Map<String, String> filedValueMap = new HashMap<String, String>();
filedValueMap.put("zhangs", "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);
}
}