您的位置:首页 > 其它

itext:根据模板生成新的pdf

2015-10-16 16:54 471 查看
/**
* 赋值并生成新的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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  pdf itext field 动态模板