簡體   English   中英

Handlebars + puppeteer 使用 base64 顯示本地 png 圖像

[英]Handlebars + puppeteer using base64 to display a local png image

我有一個項目,我正在構建一個帶有把手的 html 並使用 puppeteer 將其轉換為 pdf。 我遇到了一個問題,即我的 base64 編碼圖像在呈現 pdf 后不顯示圖像。 對於額外的上下文,我們將在生成 pdf 后將其存儲在我們的數據庫中,並且我們的圖像位於本地資產目錄中。 我能夠將圖像加載到 codeandbox 中,但這不包括 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}}">

我沒有將此標記為答案,而只是作為我用來解決此問題的解決方法。 我有一個 React FE,我的應用程序位於一個聯合部署到 Heroku 的單一存儲庫中。 所以我決定將圖像放在我的客戶端/公共目錄中,然后在我的把手代碼中,我引用了它的 url 和文件名。 這讓我可以以更易於管理的方式托管自己的圖像,而不必強迫客戶使用另一種工具,例如 s3 存儲桶。 此解決方案並不理想,但目前有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM