代码:
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);
}
|
结果:
原pdf:
合成后pdf:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://www.cnblogs.com/hooly/p/8394859.html