如何使用 NodeJS 使用密码保护现有的 PDF 文件?

问题描述 投票:0回答:1

如何使用nodejs使用密码保护PDF文件?不使用 pdfq 或任何 CLI 命令,这可能吗?

我使用 pdf-creator-node 生成 pdf 的 html 模板。它的输出,我想用密码保护它。

这是初始代码:

const fs = require("fs");
const pdfCreator = require("pdf-creator-node");
const data = require("./utils/data");

// Read the HTML template
const htmlTemplate = fs.readFileSync(
  "./templates/html/template.html",
  "utf8"
);

// Define the options for the PDF generation
const options = {
  format: "A4",
  orientation: "portrait",
};

// Compile the HTML template and generate the PDF
const document = {
  html: htmlTemplate,
  data, // Optional data to pass to the template
  path: "output.pdf", // Specify the output file path
};

pdfCreator
  .create(document, options)
  .then((result) => {
    console.log("PDF created successfully");
  })
  .catch((error) => {
    console.error("Error creating PDF:", error);
  });
javascript node.js pdf encryption
1个回答
0
投票
const coherentpdf = require('coherentpdf');

   public async createPdf(htmlString, password) {
    try {
      const tempPath = '/tmp/result.pdf';
      const tempPdfOutput = '/tmp/PdfOutput.pdf';

      
      const browser = await puppeteer.launch({
        args: chromium.args,
        defaultViewport: chromium.defaultViewport,
        executablePath: await chromium.executablePath(),
        headless: chromium.headless,
        ignoreHTTPSErrors: true
      });

      const page = await browser.newPage();
      await page.setContent(htmlString);
      await page.pdf({ format: 'A4', path: tempPath });


      let pdfe = coherentpdf.fromFile(tempPath, '');
      var permissions = [coherentpdf.noEdit];
      coherentpdf.toFileEncrypted(pdfe, coherentpdf.pdf40bit, permissions, 'owner', password, false, false, tempPdfOutput);

      return tempPath;

    } catch (error) {
      console.error('Error createPdf:', error);
      throw error;
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.