简体   繁体   English

如何将pdf文件转换为base64

[英]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我正在尝试将 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();
})();

here instead of creating a html.pdf i wanted to convert it into a base64 so i can send the email.在这里,我想将其转换为 base64,而不是创建 html.pdf,以便我可以发送电子邮件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM