itextpdf添加表格元素_使用iText填充pdf表单
最近項目中用到了下載pdf回單的功能。需要把內容動態的填入pdf并打印,覺得這個功能挺實用的,所以決定用博客記錄一下方便以后使用。
一、首先我們需要安裝Adoble Acrobat XI Pro,因為Adodle Reader沒有表單編輯功能。
1、先用word只做好模板,另存為pdf格式,然后用pdf打開,啟用表單編輯功能,設置好表單域。效果如圖:
2、將項目src下講一個template文件夾,將這個模板放入template文件夾中。
3、下載兩個jar包iText.jar和iTextAsian.jar包放入lib中
二編寫代碼如下:
public class CreatePDF {
@Test
public void testCreatePDF() throws Exception{
Map map=new HashMap();
List list=new ArrayList();
map.put("UserName", "張三");
map.put("Account","657676767766727272");
map.put("Date", "1997-09-18");
map.put("Balance", "1000");
list.add(map);
convertTransData(list);
System.out.println("執行完畢");
}
/**
* 將數據轉換為輸入字節流
* */
protected InputStream convertTransData(List input)
throws Exception {
if (input == null || input.isEmpty() || input.get(0) == null)
return null;
String template="/template/FinanceBuy.pdf";
try {
InputStream in =
this.getClass().getResourceAsStream(template);
ByteArrayOutputStream out =
(ByteArrayOutputStream)generate(
new PdfReader(in),
(Map) input.get(0));
ByteArrayInputStream ret =
new ByteArrayInputStream(out.toByteArray());
//將pdf字節流輸出到文件流
OutputStream fos = new FileOutputStream("D:/FinanceBuy.pdf");
fos.write(out.toByteArray());
fos.close();
out.close();
return ret;
} catch (Exception e) {
throw new Exception(e);
}
}
/**
* 將數據,填入pdf表單域
*
* */
public static OutputStream generate(PdfReader template, Map data)
throws Exception {
BaseFont bfChinese = BaseFont.createFont("STSong-Light",
"UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
PdfStamper stamp = new PdfStamper(template, out);
AcroFields form = stamp.getAcroFields();
// set the field values in the pdf form
for (Iterator it = data.keySet().iterator(); it.hasNext();) {
String key = (String) it.next();
String value = (String) data.get(key);
form.setFieldProperty(key, "textfont", bfChinese, null);
form.setField(key, value);
}
stamp.setFormFlattening(true);
stamp.close();
template.close();
return out;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
運行test,在D盤中可看到pdf文件打開效果如下:
總結
以上是生活随笔為你收集整理的itextpdf添加表格元素_使用iText填充pdf表单的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: nbiot开发需要掌握什么_包装设计需要
- 下一篇: vse职位的全称_吉利汽车VSE岗(SE