本文實例為大家分享了java在pdf模板的指定位置插入圖片的具體代碼,供大家參考,具體內容如下
java操作pdf有個非常好用的庫itextpdf,maven:
1
2
3
4
5
6
7
8
9
10
11
|
<dependency> <groupid>com.itextpdf</groupid> <artifactid>itextpdf</artifactid> <version> 5.5 . 6 </version> </dependency> <!-- itextpdf的亞洲字體支持 --> <dependency> <groupid>com.itextpdf</groupid> <artifactid>itext-asian</artifactid> <version> 5.2 . 0 </version> </dependency> |
思路:
- adobe的acrobat可以對pdf進行編輯,在文檔中插入域,這個插入的域就是圖片的位置。這兒有關于域的介紹,但是這不重要,我們只是把域作為一個占位符用;
- 利用itextpdf得到目標域所在的頁面、位置、大小;
- 利用域的坐標,把圖片以絕對位置的方式插入到pdf中。
代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
public static void main(string[] args) throws exception { // 模板文件路徑 string templatepath = "template.pdf" ; // 生成的文件路徑 string targetpath = "target.pdf" ; // 書簽名 string fieldname = "field" ; // 圖片路徑 string imagepath = "image.jpg" ; // 讀取模板文件 inputstream input = new fileinputstream( new file(templatepath)); pdfreader reader = new pdfreader(input); pdfstamper stamper = new pdfstamper(reader, new fileoutputstream(targetpath)); // 提取pdf中的表單 acrofields form = stamper.getacrofields(); form.addsubstitutionfont(basefont.createfont( "stsong-light" , "unigb-ucs2-h" , basefont.not_embedded)); // 通過域名獲取所在頁和坐標,左下角為起點 int pageno = form.getfieldpositions(fieldname).get( 0 ).page; rectangle signrect = form.getfieldpositions(fieldname).get( 0 ).position; float x = signrect.getleft(); float y = signrect.getbottom(); // 讀圖片 image image = image.getinstance(imagepath); // 獲取操作的頁面 pdfcontentbyte under = stamper.getovercontent(pageno); // 根據域的大小縮放圖片 image.scaletofit(signrect.getwidth(), signrect.getheight()); // 添加圖片 image.setabsoluteposition(x, y); under.addimage(image); stamper.close(); reader.close(); } |
參考
how to show an image at a text field position?
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/SOME___ONE/article/details/52562740?utm_source=blogxgwz1