好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

java实现在pdf模板的指定位置插入图片

本文实例为大家分享了 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

查看更多关于java实现在pdf模板的指定位置插入图片的详细内容...

  阅读:29次