【问题标题】:Handlebars + puppeteer using base64 to display a local png imageHandlebars + puppeteer 使用 base64 显示本地 png 图片
【发布时间】:2020-03-26 15:52:09
【问题描述】:

我有一个项目,我正在构建一个带有把手的 html,并使用 puppeteer 将其转换为 pdf。我遇到了一个问题,即我的 base64 编码图像在呈现 pdf 后不显示图像。对于额外的上下文,一旦生成 pdf 并且我们的图像位于本地资产目录中,我们会将其存储在我们的数据库中。我能够将图像加载到代码沙箱中,但这不包括 puppeteer,所以我认为这是问题所在。

// takes the handlebars template and compiles it
const compile = async (templateName, data) => {
  const filePath = path.join(__dirname, "templates", `${templateName}.hbs`);
  if (!filePath) {
    throw new Error(`Could not find ${templateName}.hbs in generatePDF`);
  }
  const html = await fs.readFile(filePath, "utf-8");
  return hbs.compile(html)(data);
};

// use puppeteer to take in compiled hbs doc and create a pdf
const generatePDF = async (fileName, data) => {
  const preparedData = prepareDataForPDF(data);
  const browser = await puppeteer.launch({
    args: ["--no-sandbox"],
    headless: true,
  });
  const page = await browser.newPage();
  const content = await compile(fileName, preparedData);
  await page.goto(`data: text/html;charset=UTF-8, ${content}`, {
    waitUntil: "networkidle0",
  });
  await page.setContent(content);
  await page.emulateMedia("screen");
  await page.waitFor(100);

  const pdf = await page.pdf({
    format: "A4",
    printBackground: true,
  });
  browser.close();
  return pdf;
};

// the helper to convert my image to base64
hbs.registerHelper("getIntro", async (context, idx) => {
  let bitmap = await fs.readFile(
    path.join(__dirname, "assets", `${context}_intro_${idx}.png`),
  );
  const buff = await Buffer(bitmap).toString("base64");

  let imgSrcString = `data:image/png;base64,${buff}`;
  console.log(imgSrcString);
  return imgSrcString;
});
<!-- for context "this" is just an index number as this gets iterated over for multiple images -->
<img src="{{getIntro "Leadership" this}}">

【问题讨论】:

    标签: javascript base64 handlebars.js puppeteer


    【解决方案1】:

    我没有将此标记为答案,而只是作为我用来解决此问题的解决方法。我有一个反应 FE,我的应用程序位于一个联合部署到 Heroku 的单一存储库中。所以我决定将图像放在我的 client/public 目录中,然后在我的车把代码中,我引用了它的 url 和文件的名称。这让我以一种更易于管理的方式托管我自己的图像,而不必强迫客户处理另一个工具,如 s3 存储桶。此解决方案并不理想,但目前可以使用。

    【讨论】:

      猜你喜欢
      • 2012-04-01
      • 2023-02-01
      • 1970-01-01
      • 2012-12-20
      • 2015-07-29
      • 2016-04-24
      • 1970-01-01
      • 2014-11-11
      • 1970-01-01
      相关资源
      最近更新 更多