实现思路:将原pdf复制一份到目标pdf,在目标pdf上进行操作,复制的原因是:原pdf需要获取其pdf读入流(PdfReader),如果还在原pdf上继续宁操作,就会出现一下一下异常
java.io.FileNotFoundException: D:\testtest1\test.pdf (请求的操作无法在使用用户映射区域打开的文件上执行。)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:270)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
at priv.lgq.filesysspringboot.utils.pdf.PdfUtils.addPageNum(PdfUtils.java:146)
at priv.lgq.filesysspringboot.business.DemoTest.main(DemoTest.java:28)
源码如下:
1 /**
2 * 添加页码
3 *
4 * @author 龙谷情
5 * @date 2020/11/12 14:25
6 * @param pdfPath 原pdf路径
7 * @param outFilePath 目标pdf路径
8 * @param positionX 页数位置X
9 * @param positionY 页数位置Y
10 * @param fontSize 字体大小
11 * @return java.io.File[返回类型说明]
12 * @exception/throws [异常类型] [异常说明]
13 * @since [v1.0]
14 */
15 public static File addPageNum(String pdfPath, String outFilePath, int positionX, int positionY, int fontSize) {
16 PdfReader reader = null;
17 PdfStamper stamper = null;
18 FileOutputStream outputStream = null;
19 try {
20 // 创建一个pdf读入流
21 reader = new PdfReader(pdfPath);
22 // 根据一个pdfreader创建一个pdfStamper.用来生成新的pdf.
23 outputStream = new FileOutputStream(outFilePath);
24 stamper = new PdfStamper(reader, outputStream);
25 // 这个字体是itext-asian.jar中自带的 所以不用考虑操作系统环境问题.
26 BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
27 // baseFont不支持字体样式设定.但是font字体要求操作系统支持此字体会带来移植问题.
28 Font font = new Font(bf, 10);
29 font.setStyle(Font.BOLD);
30 font.getBaseFont();
31 // 获取页码
32 int num = reader.getNumberOfPages();
33 for (int i = 1; i <= num; i++) {
34 PdfContentByte over = stamper.getOverContent(i);
35 over.beginText();
36 over.setFontAndSize(font.getBaseFont(), fontSize);
37 over.setColorFill(BaseColor.BLACK);
38 // 设置页码在页面中的坐标
39 over.setTextMatrix(positionX, positionY);
40 over.showText("第" + i + "页");
41 over.endText();
42 over.stroke();
43 }
44 stamper.close();
45 } catch (Exception e) {
46 e.printStackTrace();
47 } finally {
48 if (outputStream != null) {
49 try {
50 outputStream.close();
51 } catch (IOException e) {
52 e.printStackTrace();
53 }
54 }
55 if (reader != null) {
56 reader.close();
57 }
58 if (stamper != null) {
59 try {
60 stamper.close();
61 } catch (DocumentException e) {
62 e.printStackTrace();
63 } catch (IOException e) {
64 e.printStackTrace();
65 }
66 }
67 }
68 File file = new File(outFilePath);
69 return file;
70 }