javascript 如何在NodeJs中对PDF进行密码加密

ogsagwnx  于 2023-04-10  发布在  Java
关注(0)|答案(1)|浏览(391)

我目前正在生成一个pdf从html和返回在Base64使用puppeteer,但我试图添加一个密码安全打开它,我还没有找到如何做到这一点。
我已经看到你可以使用pdf-lib或pdfKit,但我没有成功(似乎这些功能被删除,因为我看到的例子返回错误加密不是一个函数和其他错误)
我附上生成代码

//const pdf = require('html-pdf');
// var { Base64Encode } = require('base64-stream');
// const { PDFDocument, StandardFonts } = require('pdf-lib');
// const { JSDOM } = require('jsdom');
// const generatorPdf = require('jspdf');
//const base64 = require('base-64');
// require('jspdf-autotable'); 
const { PDFNet } = require('@pdftron/pdfnet-node');

const handlebars = require('handlebars');
const puppeteer = require('puppeteer');
const Buffer = require('buffer').Buffer;
const moment = require('moment'); 

handlebars.registerHelper('formatDate', function (dateString) {
   return new handlebars.SafeString(
       moment(dateString).format("DD/MM/YYYY").toUpperCase()
   );
});
async function middleware(context, res) { 
    let template = context.body.template || context.body.Template;
    const data = context.body.data || context.body.Data;
    let htmlContent = handlebars.compile(template, data)(data);

    const password = context.body.password || context.body.Password;
    return (async () => {
        const browser = await puppeteer.launch();
        const page = await browser.newPage();

        await page.setContent(htmlContent);

        const pdf = await page.pdf({
            format: 'A4',
            printBackground: true 
        }); 
     
        await browser.close();   
       
        let result = { html: Buffer.from(pdf).toString('base64') } 
        res.json(result);
    })();
}

module.exports = middleware;

我希望你能给予我一个指引,谢谢
我已经看了几个选项,并使用不同的库,如jspdf,pdf-lib,pdfkit,相同的puppeteer和我没有成功的例子中找到的网络
我希望能够加密的pdf与自定义密码,一切都在内存中完成,因为它是一个蔚蓝色功能的思想

fzwojiic

fzwojiic1#

您可以使用hummus-recipe库,它构建在hummus库之上。下面是如何使用它的示例:

const puppeteer = require('puppeteer');
const muhammara = require('muhammara');
const fs = require('fs');

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    await page.setContent(htmlContent);

    const pdfBuffer = await page.pdf({
        format: 'A4',
        printBackground: true
    });

    await browser.close();

    const reader = new muhammara.PDFRStreamForBuffer(pdfBuffer);
    const writer = new muhammara.PDFRWStreamForBuffer();
    const pdfWriter = muhammara.createWriterToModify(reader, writer);

    const password = 'your-password';
    const options = {
        userPassword: password,
        ownerPassword: password,
        userProtectionFlag: 4
    };
    pdfWriter.encrypt(options);

    pdfWriter.end();
    const encryptedPdfBuffer = writer.toBuffer();

    // Save the encrypted PDF to a file (optional)
    fs.writeFileSync('encrypted.pdf', encryptedPdfBuffer);

    let result = { html: encryptedPdfBuffer.toString('base64') };
    res.json(result);
})();

相关问题