使用pdfbox 为 PDF 增加水印

使用pdfbox 为 PDF增加水印https://www.jylt.cc/#/detail?activityIndex=2&id=bd410851b0a72dad3105f9d50787f914

引入依赖

XML 复制代码
<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>3.0.1</version>
</dependency>
<!--下面操作图片的时候需要用到该工具类-->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-core</artifactId>
    <version>5.8.25</version>
</dependency>

具体代码实现

java 复制代码
public static void main(String[] args) throws Exception {
        // 读取原始 PDF 文件
        PDDocument document = PDDocument.load(new File("/Users/a58/Downloads/test.pdf"));

        File file = new File("/Users/picture/Downloads/waterMark.png");
        BufferedOutputStream outputStream = FileUtil.getOutputStream(file);
        FileImageOutputStream fileImageOutputStream = new FileImageOutputStream(file);

	// 创建文字图片
	Font font = new Font("宋体", Font.PLAIN, 12);
        Color fontColor = new Color(100, 100, 100, 60);
        ImgUtil.createImage("水印", font, null, fontColor, fileImageOutputStream);
	// 旋转图片,使水印倾斜
        ImgUtil.rotate(file, -20, file);

        // 遍历 PDF 中的所有页面
        for (int i = 0; i < document.getNumberOfPages(); i++) {
            PDPage page = document.getPage(i);
            PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, true);

	    // PDF页面宽度
            float pageWidth = page.getMediaBox().getWidth();
	    // PDF页面高度
            float pageHeight = page.getMediaBox().getHeight();

	    // 4:每页有4列水印
            int xBegin = (int) (pageWidth / 4);
	    // 8:每页有8行水印
            int yBegin = (int) (pageHeight / 8);
	  
	    // 加载图片
            PDImageXObject pdImageXObject = PDImageXObject.createFromFile(file.getAbsolutePath(), document);
            float width = pdImageXObject.getWidth();
            float height = pdImageXObject.getHeight();

            for (int yIndex = 0; yIndex < 8; yIndex++) {
                for (int xIndex = 0; xIndex < 4; xIndex++) {
                    contentStream.drawImage(pdImageXObject, (xBegin * xIndex) + 5, (yBegin * yIndex), width, height);
                }
                yIndex++;
            }

            contentStream.close();
        }

        // 保存修改后的 PDF 文件
        document.save(new File("/Users/picture/Downloads/testout.pdf"));
        document.close();
        System.out.println("完成");
    }
相关推荐
s:10338 分钟前
【框架】参考 Spring Security 安全框架设计出,轻量化高可扩展的身份认证与授权架构
java·开发语言
南山十一少4 小时前
Spring Security+JWT+Redis实现项目级前后端分离认证授权
java·spring·bootstrap
427724005 小时前
IDEA使用git不提示账号密码登录,而是输入token问题解决
java·git·intellij-idea
chengooooooo6 小时前
苍穹外卖day8 地址上传 用户下单 订单支付
java·服务器·数据库
李长渊哦6 小时前
常用的 JVM 参数:配置与优化指南
java·jvm
计算机小白一个6 小时前
蓝桥杯 Java B 组之设计 LRU 缓存
java·算法·蓝桥杯
南宫生8 小时前
力扣每日一题【算法学习day.132】
java·学习·算法·leetcode
计算机毕设定制辅导-无忧学长9 小时前
Maven 基础环境搭建与配置(一)
java·maven
风与沙的较量丶10 小时前
Java中的局部变量和成员变量在内存中的位置
java·开发语言
m0_7482517210 小时前
SpringBoot3 升级介绍
java