最近有个加水印的需求,因为使用了免费的插件,有些限制。采用了将页数多的pdf文件进行拆分,但是使用itextpdf合并成一个文件的时候,删除有水印的文件提示文件被占用,真的很蛋Teng。

解决方法

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
public static void mergePdfs(List<String> pdfPaths, String outFilePath) {
Document document = null;
PdfReader reader1 = null;
PdfReader reader2 = null;
PdfCopy copy = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(outFilePath);
reader2 = new PdfReader(pdfPaths.get(0));
document = new Document(reader2.getPageSize(1));
copy = new PdfCopy(document, fos);
document.open();
for (int i = 0; i < pdfPaths.size(); i++) {
reader1 = new PdfReader(pdfPaths.get(i));
int n = reader1.getNumberOfPages();
for (int j = 1; j <= n; j++) {
document.newPage();
PdfImportedPage page = copy.getImportedPage(reader1, j);
copy.addPage(page);
}
reader1.close();
reader1 = null;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader1 != null) reader1.close();
if (reader2 != null) reader2.close();
if (document != null) document.close();
if (copy != null) {
copy.flush();
copy.close();
}
try {
if (fos != null) {
fos.flush();
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}