【java】使用iText实现pdf文件增加水印功能

maven依赖

bash 复制代码
<dependencies>
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itext7-core</artifactId>
        <version>7.2.5</version>
        <type>pom</type>
    </dependency>
</dependencies>

实现代码

前端代码

bash 复制代码
window.open(url + "/docinf/doc/docFile/addWatermarkItextStream.do?fileName=test.pdf"+"#toolbar=0",'_blank', "toolbar=no");

在你需要下载的地方,增加点击事件,里面增加window.open方法

这里面有两个toolbar的设置,第一个toolbar=0,是拼接在url后面的,这个是禁用浏览器pdf的下载功能,第二个"toolbar=no",是禁用新窗口浏览器的工具栏,让页面更清爽一些

后端代码

bash 复制代码
@RequestMapping("/addWatermarkItextStream")
    public void addWatermarkItextStream( HttpServletRequest request, HttpServletResponse response) {
        try {
            String inputPdfPath = "你的pdf路径";
            // 水印文本
            String watermarkText = "马仔水印";

            // 设置响应头
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "inline; filename=watermarked.pdf");

            // 获取响应输出流
            OutputStream out = response.getOutputStream();

            // 创建 PDF 阅读器和写入器
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(inputPdfPath), new PdfWriter(out));

            // 加载支持中文的字体,这里以宋体为例,需要确保字体文件存在
            // 注意,这个路径是我服务器上字体的路径,引号里面必须加上",0",否则中文字体无法显示
            PdfFont font = PdfFontFactory.createFont("C:\\Windows\\Fonts\\simsun.ttc,0");
            //PdfFont font = PdfFontFactory.createFont();
            // 遍历每一页
            for (int i = 1; i <= pdfDoc.getNumberOfPages(); i++) {
                // 获取当前页面
                PdfCanvas pdfCanvas = new PdfCanvas(pdfDoc.getPage(i).newContentStreamBefore(), pdfDoc.getPage(i).getResources(), pdfDoc);

                // 设置透明度
                PdfExtGState gs1 = new PdfExtGState();
                gs1.setFillOpacity(0.3f);
                pdfCanvas.setExtGState(gs1);

                // 创建画布
                Canvas canvas = new Canvas(pdfCanvas, pdfDoc.getPage(i).getPageSize());
                canvas.setFont(font).setFontSize(50);
                // 定义水印之间的间距
                float xSpacing = 300;
                float ySpacing = 400;

                // 计算水平和垂直方向的水印数量
                int numX = (int) Math.ceil(PageSize.A4.getWidth() / xSpacing) * 2;
                int numY = (int) Math.ceil(PageSize.A4.getHeight() / ySpacing) * 3;

                // 循环添加水印
                for (int x = 0; x < numX; x++) {
                    for (int y = 0; y < numY; y++) {
                        float xPos = x * xSpacing;
                        float yPos = y * ySpacing;
                        canvas.showTextAligned(new Paragraph(watermarkText),
                                xPos, yPos,
                                i, TextAlignment.CENTER, VerticalAlignment.MIDDLE, 45);
                    }
                }
            }

            // 关闭 PDF 文档
            pdfDoc.close();

            // 刷新并关闭输出流
            out.flush();
            out.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

实现效果

相关推荐
Fireworkitte4 小时前
Apache POI 详解 - Java 操作 Excel/Word/PPT
java·apache·excel
weixin-a153003083164 小时前
【playwright篇】教程(十七)[html元素知识]
java·前端·html
DCTANT4 小时前
【原创】国产化适配-全量迁移MySQL数据到OpenGauss数据库
java·数据库·spring boot·mysql·opengauss
Touper.5 小时前
SpringBoot -- 自动配置原理
java·spring boot·后端
黄雪超5 小时前
JVM——函数式语法糖:如何使用Function、Stream来编写函数式程序?
java·开发语言·jvm
ThetaarSofVenice5 小时前
对象的finalization机制Test
java·开发语言·jvm
思则变5 小时前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
lijingguang5 小时前
在C#中根据URL下载文件并保存到本地,可以使用以下方法(推荐使用现代异步方式)
开发语言·c#
¥-oriented6 小时前
【C#中路径相关的概念】
开发语言·c#
CoderCodingNo6 小时前
【GESP】C++四级考试大纲知识点梳理, (7) 排序算法基本概念
开发语言·c++·排序算法