日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

itextpdf添加表格元素_使用iText填充pdf表单

發布時間:2025/3/21 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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表单的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。