gpt4 book ai didi

puppeteer - 如何将Puppeteer指向本地镜像/字体?

转载 作者:行者123 更新时间:2023-12-03 13:33:14 58 4
gpt4 key购买 nike

我想使用Puppeteer从HTML字符串生成图像。现在我有这样的事情:

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
})

问题是,Puppeteer无法加载图像,并且我不确定如何将其指向他?该图像与脚本位于同一目录中。

除了图像,我想加载自定义字体,该怎么做?

最佳答案

页面网址为about:blank,Chrome浏览器不允许在非本地页面中加载本地资源。

所以也许是这样的?

'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);
}
})();

关于puppeteer - 如何将Puppeteer指向本地镜像/字体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55078896/

58 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com