You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为Puppeteer生成的PDF添加密码保护(NestJS+Node.js场景)

在NestJS + Puppeteer生成的PDF中添加密码保护

Puppeteer本身没有内置PDF加密功能,要给生成的PDF添加密码保护,需借助第三方PDF处理库,这里推荐pdf-lib——它轻量且API易用,适配Node.js环境。

步骤1:安装依赖

先安装pdf-lib:

npm install pdf-lib

步骤2:修改PDF生成代码

在原有generatePdf方法中,生成原始PDF后用pdf-lib进行加密处理,以下是完整修改后的代码:

import { PDFDocument } from 'pdf-lib';

async generatePdf(body: IPdf, functions?: void, password?: string) {
  let pdf: Buffer;
  const browser = await puppeteer.launch({
    args: ["--no-sandbox", "--disable-setuid-sandbox"],
    ignoreDefaultArgs: ["--disable-extensions"],
  });

  try {
    const page = await browser.newPage();

    functions;
    this.formatDate();
    this.numerosLetras();
    this.formatCurrency();
    this.formatSpecialty();
    this.toUpperCase();
    const content = await this.compile(body.templateName, body.data);

    await page.setContent(content);
    
    // 生成未加密的原始PDF Buffer
    const rawPdfBuffer = await page.pdf({
      format: "a4",
      printBackground: true,
      margin: { bottom: 30, left: 20, right: 20, top: 20 },
    });

    // 若传入密码,则执行加密逻辑
    if (password) {
      const pdfDoc = await PDFDocument.load(rawPdfBuffer);
      // 设置加密规则:用户密码(打开需输入)、所有者密码(拥有全权限,可自定义)
      pdfDoc.encrypt({
        userPassword: password,
        ownerPassword: `${password}_owner`,
        permissions: {
          print: false,
          modify: false,
          copy: false,
          annotate: false,
        },
      });
      pdf = Buffer.from(await pdfDoc.save());
    } else {
      pdf = rawPdfBuffer;
    }
  } catch (error) {
    console.error('PDF生成/加密失败:', error);
    throw error; // 建议抛出错误交由上层处理,而非仅打印
  } finally {
    await browser.close();
  }
  return pdf;
}

关键说明

  • 密码可通过方法参数传入,也可从配置文件/环境变量读取,避免硬编码
  • permissions配置可按需调整,比如允许打印就将print设为true
  • 用finally块确保浏览器资源无论成功失败都会被释放
  • 抛出错误能让调用方及时捕获并处理异常场景

内容的提问来源于stack exchange,提问作者christian alvarez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 05:04:54