javascriptnode.jshandlebars.jspuppeteer

How to convert a pdf file into base64


I am trying to convert the pdf into base64 and send as an attachment to the email but i am unable to convert into the base64 instead of creating a file i want to convert it into base64 so i can send as an attachment.here is the code

const fs = require("fs");
const path = require("path");
const utils = require("util");
const puppeteer = require("puppeteer");
const hb = require("handlebars");
const readFile = utils.promisify(fs.readFile);
(async () => {
const A = "invoice";
const htmlContent = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h2>Approve Page ,${A}</h2>
</body>
</html>
`;
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.setContent(htmlContent);
  await page.pdf({ path: "html.pdf", format: "A4" });

  await browser.close();
})();

here instead of creating a html.pdf i wanted to convert it into a base64 so i can send the email.


Solution

  • Try this:

    const puppeteer = require("puppeteer");
    
    (async () => {
      const A = "invoice";
      const htmlContent = `<!DOCTYPE html>
      <html lang="en">
      <head>
      <meta charset="UTF-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>Document</title>
      </head>
      <body>
      <h2>Approve Page ,${A}</h2>
      </body>
      </html>
      `;
      const browser = await puppeteer.launch();
      const page = await browser.newPage();
      await page.setContent(htmlContent);
    
      const buffer = await page.pdf({ format: "A4" });
      const base64 = buffer.toString('base64');
      console.log(`data:application/pdf;base64,${base64}`); // Test it in a browser.
    
      await browser.close();
    })();