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?
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.
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);
}
})();
Found a relevant issue on their github. To sum up, currently the options seem to be as follows:
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With