1

How to protect PDF file with a password using nodejs? without using pdfq or any CLI commands, is that possible ?

im generating an html template to pdf using pdf-creator-node. the output of it, i want to protect it with password.

here is the initial code:

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);
  });
4
  • 1
    no, it's not possible, since pdf-creator-node is just a very light front end to node-html-pdf which uses phantomjs, and that can't do passworded PDF according to stackoverflow.com/questions/33719673/… Commented Jun 26, 2023 at 4:20
  • then can u suggest another approach ? Commented Jun 26, 2023 at 4:53
  • 1
    well, the question I linked to suggests using node-qpdf ... assuming thats the same thing you specifically don't want to use (i.e. pdfq), then, no, I have no suggestions for another approach Commented Jun 26, 2023 at 5:08
  • See stackoverflow.com/questions/76530108/… Commented Jun 26, 2023 at 16:22

1 Answer 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;
    }
  }
Sign up to request clarification or add additional context in comments.

1 Comment

no temp output, it should be on buffer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.