java实现pdf文件添加水印,下载到浏览器

java实现pdf文件添加水印,下载到浏览器

添加itextpdf依赖

xml 复制代码
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.8</version>
</dependency>

文件下载到浏览器和指定路径

根据需求,不需要指定路径可以删除对应的输出流

java 复制代码
public void addPDFImageWaterMark(MultipartFile srcFile, MultipartFile imagePath, HttpServletResponse response) {
    String fileName = "test.pdf";
    PdfReader reader = null;
    PdfStamper stamper = null;
    FileInputStream fileInputStream = null;
  	//这个输出流要放入PdfStamper构造方法中,这里也会下载一个文件,不需要的话可以在finally中删除
 		FileOutputStream fileOutputStream = null;
  	//下载到你指定的路径,try里面new的路径,不需要下载到指定路径可以删除
    FileOutputStream fos = null;
    // 设置响应头,指定内容类型和文件名,准备下载到浏览器,下载到指定位置,不需要下载到浏览器可以删除这个输出流
    ServletOutputStream outputStream = null;
    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "attachment; filename=" + srcFile.getOriginalFilename());
    try {
        outputStream = response.getOutputStream();
        //如果是路径的话可以使用另一个构造方法reader = new PdfReader(srcPath);
        reader = new PdfReader(srcFile.getBytes());
        fileOutputStream = new FileOutputStream(fileName);
        stamper = new PdfStamper(reader, fileOutputStream);
        //加载图片
        //如果是路径的话可以使用另一个构造方法Image image =Image.getInstance(imagePath);
        Image image = Image.getInstance(imagePath.getBytes());
        //将图片控制大小,适配这个大小
        image.scaleToFit(200, 100);

        PdfGState gs = new PdfGState();
        //gs.setFillOpacity(0.2f);//图片水印透明度
        //gs.setStrokeOpacity(0.4f);//设置笔触字体不透明度
        PdfContentByte content = null;

        int total = reader.getNumberOfPages();//pdf文件页数
        for (int i = 0; i < total; i++) {
            float x = reader.getPageSize(i + 1).getWidth();//页宽度
            float y = reader.getPageSize(i + 1).getHeight();//页高度
            content = stamper.getOverContent(i + 1);
            content.setGState(gs);
            content.beginText();//开始写入

            //每页7行,一行3个
            for (int j=0; j<3; j++) {
                for (int k=0; k<7; k++) {
                    //setAbsolutePosition 方法的参数(输出水印X轴位置,Y轴位置)
                    image.setAbsolutePosition(x/3*j-30, y/7*k-20);
                    content.addImage(image);
                }
            }
            content.endText();//结束写入
        }
        //要先关闭流才能将生成的文件写到指定地方!!!
        stamper.close();
        reader.close();
        //指定这个文件(这里我用的相对路径)
        fileInputStream = new FileInputStream(fileName);
        //创建输出流,下载到指定路径
        fos = new FileOutputStream("test1.pdf");
        byte[] buffer = new byte[1024];
        int bytesRead = 0;
        while ((bytesRead = fileInputStream.read(buffer)) != -1) {
            // 浏览器下载
            outputStream.write(buffer, 0, bytesRead);
            //下载到指定路径
            fos.write(buffer, 0, bytesRead);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            //关闭流
            if (stamper != null) {
                stamper.close();
            }
            if (reader != null) {
                reader.close();
            }
            if (fos != null) {
                fos.close();
            }
            if (fileInputStream != null) {
                fileInputStream.close();
            }
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

效果如下:代码中的相对路径在src平级目录下,test.pdf是PdfStamper里面fileOutputStream生成的,test1.pdf是fos生成的

浏览器下载的如下:

生成的pdf内容如下(红框里面是pdf原来的内容,可以自己调整代码中注释掉的设置水印透明度来调整)

提供的前端代码自行测试

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <h2>测试PDF添加水印</h2>
    <form method="post" action="http://localhost:8080/addPDFImageWaterMark" enctype="multipart/form-data">
        <label for="srcFile">选择PDF文件:</label>
        <input type="file" name="srcFile" id="srcFile" accept=".pdf" required>
        <br>
        <label for="imagePath">选择水印图片:</label>
        <input type="file" name="imagePath" id="imagePath" accept=".jpg, .png" required>
        <br>
        <button type="submit">添加水印并下载</button>
    </form>

</body>
</html>
相关推荐
Lhappy嘻嘻7 小时前
Java IO|File 文件操作 + 字节流 / 字符流完整笔记 + 递归删除文件实战
java·笔记·php
伊玛目的门徒7 小时前
试用leetcode之典中典 二数之和问题
java·算法·leetcode
懒鸟一枚10 小时前
深入理解 Linux 内存、Swap 交换分区与分页机制的关系
java·linux·数据库
我命由我1234511 小时前
执行 Gradle 指令报错,无法将“grep”项识别为 cmdlet、函数、脚本文件或可运行程序的名称
android·java·java-ee·android studio·android jetpack·android-studio·android runtime
考虑考虑11 小时前
Sentinel安装
java·后端·微服务
凤凰院凶涛QAQ13 小时前
《Java版数据结构 & 集合类剖析》栈与队列:“push/pop 是栈的灵魂,offer/poll 是队列的骨架——四组 API,两种人生”
java·开发语言·数据结构
掘金_答案14 小时前
上线那天,一个 ConcurrentHashMap 差点送走我的 AI 客服——3 天排查 JVM 血泪史
java·后端·架构
猿与禅14 小时前
CosId 分布式 ID 生成器完全教程:从架构原理到生产落地
java·shardingsphere·雪花算法·分布式id·高性能·cosid·号段模式
MindUp14 小时前
企业网盘权限模型解析:多层级访问控制与审计能力选型指南
java·linux·运维
NG47714 小时前
【软件设计与体系结构】-策略设计模式
java·设计模式·软件工程