/**
* 指派并生成新的PDF文檔
* @param templatePDF pdf模版路徑
* @param outFile 輸出的PDF 路徑
* @param hashMap templatePDF對應的資料
*/
public static void doSomeThing(String templatePDF,String outFile,HashMap<String,String> hashMap){
FileOutputStream fos = null;
PdfReader reader = null;
try {
//建立輸出流
fos = new FileOutputStream(outFile);
//讀取pdf模闆
reader = new PdfReader(templatePDF);
//将模闆資料放入輸出中,并進行操作
PdfStamper stamp = new PdfStamper(reader,fos);
//擷取模闆中的相關域資料
AcroFields form = stamp.getAcroFields();
//給相應域指派
form = setField(form,hashMap);
stamp.setFormFlattening(true);
//加水印
// int pageSize = reader.getNumberOfPages();
// Image img = Image.getInstance("d://2.jpg");// 插入水印
// for(int i = 1; i <= pageSize; i++) {
// PdfContentByte under = stamp.getOverContent(i);
// img.setAbsolutePosition(150, 200);
// under.addImage(img);
// }
stamp.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
finally
{
try {
if(null != fos)
{
fos.close();
}
if(null != reader)
{
reader.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@SuppressWarnings({ "unchecked", "unchecked" })
public static AcroFields setField(AcroFields form,HashMap<String,String> fieldMap) {
Map<String, Item> formMap = form.getFields();
try {
//使用中文字型
BaseFont bfChinese =
BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
// Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);
Set<String> it=formMap.keySet();
Iterator<String> itr=it.iterator();
while(itr.hasNext()){
String temp = itr.next();
form.setFieldProperty(temp, "textfont", bfChinese, null);
form.setField(temp, fieldMap.get(temp));
}
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
return form;
}
public static void main(String[] args) {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("username", "張三");
hashMap.put("datetime", "2015-09-10");
hashMap.put("area", "北京");
PdfTemplate.doSomeThing("d://moreXieyi.pdf","NewsPDF"+".pdf", hashMap);
}