无头 Chrome 未检测网页的 css 和背景图像 [英] Headless Chrome not detecting css and Background image of the webpage
问题描述
我的 pdf 页面不带背景图片和页面的任何 CSS.你能告诉我如何解决这个问题吗?
My pdf page don't take background image and any CSS of the page. Can you please tell me how to resolve this issue?
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://sigview.sigmoid.io/app/#/signIn',
{waitUntil: 'networkidle2', timeout: 0});
await page.waitFor(20000);
await page.pdf({path: 'sigview.pdf', format: 'A4'});
await browser.close();
})();
它应该需要带有所有 CSS 的完整网页布局
It should take complete web page layout with all CSS
推荐答案
默认情况下,将页面另存为 PDF Puppeteer 会使用 print
样式,而您大多缺少这些样式(我见过有很多,但没有什么可以设计登录页面的样式,AFAIK).但是有一个解决方案.一、在puppeteer中强制模拟屏幕
By default, when saving your page as PDF Puppeteer would use print
styles, which you're mostly missing (I've seen there's bunch of them, but nothing that would style the login page, AFAIK). But there's a solution to this. First, force screen emulation in puppeteer
await page.emulateMedia('screen');
然后将一些 printBackground: true
属性添加到您的 pdf 方法调用中.没有它 Puppeteer 将忽略背景图像(这是默认行为)
and then add some printBackground: true
property to your pdf method call. Without it Puppeteer will ignore background images (that's default behaviour)
await page.pdf({path: 'sigview.pdf', format: 'A4', printBackground: true});
结果,你会得到这样的结果:
As a result, you would have something like that:
await page.emulateMedia("screen");
await page.pdf({
path: "sigview.pdf",
format: "A4",
printBackground: true
});
有关 PDF 选项的更多阅读docs
More reading on PDF options docs
顺便说一句,是否有任何理由将 20000
设置为 waitFor
的值?
BTW, is there any reason why set 20000
as value of waitFor
?
这篇关于无头 Chrome 未检测网页的 css 和背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!