服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - java PDF添加图层的方法 支持多页图层添加

java PDF添加图层的方法 支持多页图层添加

2021-03-29 10:44漂流的老妖怪 Java教程

这篇文章主要为大家详细介绍了java PDF添加图层的方法,支持多页图层添加,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

 java 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import java.io.file;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.util.list;
 
import com.itextpdf.text.documentexception;
import com.itextpdf.text.image;
import com.itextpdf.text.pdf.pdfcontentbyte;
import com.itextpdf.text.pdf.pdfreader;
import com.itextpdf.text.pdf.pdfstamper;
 
public class pdfutils {
 
 /**
  * pdf添加图层
  *
  * @param srcpdf
  *   原pdf文件路径
  * @param distpdf
  *   合成pdf输出路径
  * @param layerpatharr
  *   图层路径列表,图层名称需为数字(按照图片名称数字顺序合成在pdf对应页数上)
  * @return
  * @throws ioexception
  * @throws documentexception
  */
 public static string marklocalimage42dist(string srcpdf, string distpdf, list<string> layerpatharr)
   throws ioexception, documentexception {
   file srcpdffile = new file(srcpdf);
   if (!srcpdffile.exists()) {
    throw new illegalargumentexception("找不到需要添加图层的pdf文件");
   }
 
   pdfreader reader = new pdfreader(srcpdf);
   int n = reader.getnumberofpages(); // pdf页数
 
   pdfstamper stamp = new pdfstamper(reader, new fileoutputstream(distpdf));
   pdfcontentbyte over;
 
   for (string layerpath : layerpatharr) {
    file layerfile = new file(layerpath);
    string currentpageno = layerfile.getname().substring(0, layerfile.getname().lastindexof(".")); // 图片名称(对应页数)
 
    boolean isnum = currentpageno.matches("[0-9]+");
    if (!isnum) {
     throw new illegalargumentexception("图层名称是不是数字");
    }
 
    image img = image.getinstance(layerpath);
    img.setabsoluteposition(0, 0);
    if (n > 0 && n >= integer.parseint(currentpageno)) {
     over = stamp.getovercontent(integer.parseint(currentpageno));
     over.addimage(img);
    }
   }
   stamp.close();
   reader.close();
  return distpdf;
 }
 
}

测试:

?
1
2
3
4
5
6
7
8
public static void main(string[] args) throws ioexception, documentexception {
  list<string> imgurllist = new arraylist<>();
  imgurllist.add("d:/ts/testpdf/1.png");
  //imgurllist.add("d:/ts/testpdf/2.png");
  imgurllist.add("d:/ts/testpdf/3.png");
 
  marklocalimage42dist("d:/ts/testpdf/testpdf.pdf", "d:/ts/testpdf/testpdf2.pdf", imgurllist);
 }

结果:

java PDF添加图层的方法 支持多页图层添加 java PDF添加图层的方法 支持多页图层添加

原pdf:

java PDF添加图层的方法 支持多页图层添加java PDF添加图层的方法 支持多页图层添加java PDF添加图层的方法 支持多页图层添加

合成后pdf:

java PDF添加图层的方法 支持多页图层添加java PDF添加图层的方法 支持多页图层添加java PDF添加图层的方法 支持多页图层添加

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/hooly/p/8394859.html

延伸 · 阅读

精彩推荐