当前位置: 首页 > article >正文

PDF下载添加水印和访问密码

下载接口

@ApiOperation(value = "下载文件-pdf", notes = "下载文件pdf版", httpMethod = "GET", response = WebResult.class)
    @RequestMapping(value = "/downloadPdf", method = RequestMethod.GET)
    public void downloadFilePdf(@RequestParam(name = "id") String id,
                             @RequestParam(name = "fileExt", defaultValue = "", required = false) String fileExt,
                             @RequestParam(name = "fileName", defaultValue = "", required = false) String fileName,
                             @RequestParam(name = "userName", defaultValue = "", required = false) String userName,
                                @RequestParam(name = "key", defaultValue = "", required = false) String key,
                             HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileId = fileInfoService.getFileIdByMainId(id, fileExt);
        GridFSFile gfsfile = mongoDbFileService.getFSFile(fileId);
        String realFileName = gfsfile.getFilename().replace(",", "");
        if (StrUtil.isEmpty2(fileName)) {
            fileName = realFileName;
        } else {
            fileName = fileName.concat(".").concat(FileUtil.getFileExt(realFileName));
        }
        //处理中文文件名乱码
        if (request.getHeader("User-Agent").toUpperCase().contains("MSIE") ||
                request.getHeader("User-Agent").toUpperCase().contains("TRIDENT")
                || request.getHeader("User-Agent").toUpperCase().contains("EDGE")) {
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        } else {
            //非IE浏览器的处理:
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }
        // 通知浏览器进行文件下载
        int lastDotIndex = fileName.lastIndexOf('.');
        String fileNameWithoutExtension = fileName.substring(0, lastDotIndex);
        response.setHeader("Content-Disposition", "attachment;filename=\"" + fileNameWithoutExtension +".pdf" + "\"");

        // 获取pdf文件,并添加水印在返回pdf
        // todo 获取用户名,解决中文水印报错bug
        String watermark = "";
        DateTime date = DateUtil.date();
        String time = DateUtil.format(date, "yyyy-MM-dd");
        watermark = watermark + time+ "" + userName;
        OutputStream out = response.getOutputStream();
        PdfUtil.two(tempPathPdf+id+".pdf",out,key,watermark);
    }

工具类

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.util.Matrix;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author csb
 * @description: TODO
 * @date 2023/11/20 17:05
 */
public class PdfUtil {

	//加密和加水印
    public static void two (String in, OutputStream out, String password, String watermark) throws IOException {
        // 加载PDF文件
        PDDocument document = PDDocument.load(new File(in));

        // 创建访问权限对象
        AccessPermission accessPermission = new AccessPermission();
        accessPermission.setCanPrint(true);
        accessPermission.setCanModify(false);
        accessPermission.setCanFillInForm(false);
        accessPermission.setCanExtractContent(false);

        // 创建保护策略对象
        StandardProtectionPolicy protectionPolicy = new StandardProtectionPolicy("password", password, accessPermission);

        // 应用保护策略到文档
        document.protect(protectionPolicy);

        //加载本地字体文件,解决中文bug 
        PDType0Font font = PDType0Font.load(document, new File("D:\\11.ttf"));

        // 加水印 遍历每一页
        for (PDPage page : document.getPages()) {
            // 创建内容流以在页面上绘制文本
            PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true);

            // 设置字体、颜色和透明度
            contentStream.setFont(font, 36);
            contentStream.setNonStrokingColor(200, 200, 200); // 灰色
            contentStream.setLineWidth(5);

            // 计算水印位置(居中)
            float pageHeight = page.getMediaBox().getHeight();
            float pageWidth = page.getMediaBox().getWidth();

            // 添加水印文本
            contentStream.beginText();

            for (int h = 10; h < pageHeight; h = h + 300) {
                for (int w = -10; w < pageWidth; w = w + 300) {
                    contentStream.setTextMatrix(Matrix.getRotateInstance(0.4, w, h));
                    contentStream.showText(watermark);
                }
            }
            contentStream.endText();
            contentStream.restoreGraphicsState();

            // 关闭内容流并保存更改
            contentStream.close();
        }

        // 保存加密后的PDF文件
        document.save(out);

        // 关闭文档
        document.close();
        out.close();
    }

    public static void WatermarkPDF(String in) throws IOException {
        // 加载PDF文档
        PDDocument document = PDDocument.load(new File("input.pdf"));

        // 遍历每一页
        for (PDPage page : document.getPages()) {
            // 创建内容流以在页面上绘制文本
            PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true);

            // 设置字体、颜色和透明度
            contentStream.setFont(PDType1Font.HELVETICA_BOLD, 36);
            contentStream.setNonStrokingColor(200, 200, 200); // 灰色
            contentStream.setLineWidth(5);

            // 计算水印位置(居中)
            float x = page.getMediaBox().getWidth() / 2;
            float y = page.getMediaBox().getHeight() / 2;

            // 添加水印文本
            contentStream.beginText();
            contentStream.newLineAtOffset(x, y);
            contentStream.showText("水印");
            contentStream.endText();

            // 关闭内容流并保存更改
            contentStream.close();
        }

        // 保存带有水印的PDF文档
        document.save("output.pdf");

        // 关闭文档
        document.close();
    }

    public static void SetPdfPassword (String in){
        try {
            // 加载PDF文件
            PDDocument document = PDDocument.load(new File(in));

            // 创建访问权限对象
            AccessPermission accessPermission = new AccessPermission();
            accessPermission.setCanPrint(true);
            accessPermission.setCanModify(false);
            accessPermission.setCanFillInForm(false);
            accessPermission.setCanExtractContent(false);

            // 创建保护策略对象
            StandardProtectionPolicy protectionPolicy = new StandardProtectionPolicy("password", "123456", accessPermission);

            // 应用保护策略到文档
            document.protect(protectionPolicy);

//            // 保存加密后的PDF文件
            document.save("D:\\test\\pdf\\2.pdf");

            // 关闭文档
            document.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

maven

<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.6</version>
</dependency>

<dependency>
    <groupId>com.artofsolving</groupId>
    <artifactId>jodconverter</artifactId>
    <version>2.2.1</version>
</dependency>

http://www.kler.cn/a/228390.html

相关文章:

  • Hive与PrestoSQL中的并列列转行
  • 【C++历练之路】二叉搜索树的学习应用及其实现
  • flask_django_python五金电商网络营销的可视化分析研究
  • 使用 PyTorch 构建 NLP 聊天机器人
  • 详解SkyWalking前端监控的性能指标
  • 【MySQL】- 09 Select Count
  • 惠普公司也要注销了?
  • JAVA Web 学习(五)Nginx、RPC、JWT
  • WordPress Plugin HTML5 Video Player SQL注入漏洞复现(CVE-2024-1061)
  • 设转电源线、转接线设计
  • Chrome扩展开发纪要
  • 2024年【广东省安全员C证第四批(专职安全生产管理人员)】考试题库及广东省安全员C证第四批(专职安全生产管理人员)考试资料
  • 2024年【T电梯修理】考试及T电梯修理免费试题
  • sqli-labs-master靶场训练笔记(21-38|精英级)
  • 深度学习系列56:使用whisper进行语音转文字
  • 【Java 数据结构】优先级队列(堆)
  • 重写Sylar基于协程的服务器(7、TcpServer HttpServer的设计与实现)
  • 【Linux】信号-上
  • 【C++】C++入门 — 类和对象初步介绍
  • 【微信小程序】微信小程序开发:从入门到精通