如何将pdf文件转换为base64

时间:2020-09-28 04:28:38

标签: javascript node.js handlebars.js puppeteer

我正在尝试将pdf转换为base64并作为附件发送给电子邮件,但我无法转换为base64而不是创建文件,我想将其转换为base64以便可以作为附件发送。是代码

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();
})();

在这里,我不想创建html.pdf,而是希望将其转换为base64,以便我可以发送电子邮件。

1 个答案:

答案 0 :(得分:0)

尝试一下:

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();
})();