javascriptpuppeteerheadless-browser

How to point Puppeteer to local images/fonts?


I want to generate images from the HTML string using Puppeteer. For now I have something like this:

const html = _.template(`
<html>
<body>
  <div class="testing">
    <h1>Hello {{ test }}!</h1>
    <img src="./1.jpg" alt="alt text" />
  </div>
</body>
</html>
`)

const browser = await puppeteer.launch()
const page = await browser.newPage()
const data = html({
  test: 'World'
})
await page.setContent(data)
const take = await page.$('.testing')
await take.screenshot({
  path: 'screenshot.png',
  omitBackground: true
})

The problem is, Puppeteer doesn't load image, and I am not sure how to point it to him? The image is located in the same directory as a script.

Beside image, I want to load custom font, how to do that?


Solution

  • The page URL is about:blank and Chrome does not allow to load local resources in non-local pages.

    So maybe something like this?

    'use strict';
    
    const { readFileSync } = require('fs');
    const puppeteer = require('puppeteer');
    
    (async function main() {
      try {
        const browser = await puppeteer.launch({ headless: false });
        const [page] = await browser.pages();
    
        const html = `
          <html>
          <body>
            <div class="testing">
              <h1>Hello World!</h1>
              <img src="data:image/jpeg;base64,${
                readFileSync('1.jpg').toString('base64')
              }" alt="alt text" />
            </div>
          </body>
          </html>
        `;
    
        await page.setContent(html);
        const take = await page.$('.testing');
        await take.screenshot({
          path: 'screenshot.png',
          omitBackground: true
        });
    
        // await browser.close();
      } catch (err) {
        console.error(err);
      }
    })();