当我尝试将 PDF 保存在磁盘上时,Puppeteer 不渲染颜色、背景颜色 [英] Puppeteer not rendering color, background color when I try to save PDF on disk

查看:99
本文介绍了当我尝试将 PDF 保存在磁盘上时,Puppeteer 不渲染颜色、背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 node.js 和 HTML 模板代码,它从 HTML 模板创建 PDF.它没有加入颜色.

This is my node.js and HTML template code which creates a PDF from an HTML template. It's not putting in the colors.

const puppeteer = require('puppeteer');

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto("file:///D:/pdf_export/template/template.html");
    await page.pdf({
        path: 'output.pdf',
        printBackground: true
    });
    await browser.close();
})()

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    </head>

    <body>
        <p style="color: red;">Hello World</p>
    </body>
</html>

当我打开 output.pdf 时,它只显示黑色而不是红色的Hello world".

When I open the output.pdf, it only shows 'Hello world' in black not in red.

推荐答案

Puppeteer 只是一个驱动 Chrome/Chromium 的库,所以如果在使用它时出现任何问题,我们最好的办法是使用 puppeteer 打开 Chromium.启动({headless:false}) 并在那里调试.

Puppeteer is just a library to drive Chrome/Chromium, so if anything goes wrong while using it, our best bet is to open Chromium with puppeteer.launch({headless:false}) and debug there.

<style></style> 标签中设置页面 css.

Set your page css in <style></style> tag.

您可以使用以下 CSS 代码解决此问题:

You can solve the issue with the following CSS code:

html {
  -webkit-print-color-adjust: exact;
}
p {
  color: #FF0000; 
}

这篇关于当我尝试将 PDF 保存在磁盘上时,Puppeteer 不渲染颜色、背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆