Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 687
bdrtsky Avatar asked Mar 09 '19 15:03

bdrtsky


People also ask

What is headless mode in puppeteer?

Advertisements. By default, Puppeteer executes the test in headless Chromium. This means if we are running a test using Puppeteer, then we won't be able to view the execution in the browser. To enable execution in the headed mode, we have to add the parameter: headless:false in the code.


2 Answers

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);
  }
})();
like image 159
vsemozhebuty Avatar answered Oct 19 '22 01:10

vsemozhebuty


Found a relevant issue on their github. To sum up, currently the options seem to be as follows:

  1. Serve your content to yourself through localhost or 3rd party server.
  2. Inline everything into HTML (base64 encode where required).
  3. When applicable, probably worth trying goto('file://...') instead of setContent(). Maybe there are chances it will work with the following:
puppeteer.launch({ args: ['--allow-file-access-from-files', '--enable-local-file-accesses'] });

But I can't confirm whether the last one would work or not. In my env, goto('file://...') constantly gives net::ERR_ABORTED.

like image 36
volvpavl Avatar answered Oct 19 '22 00:10

volvpavl