从 PDF 中的 HTML 背景颜色创建 PDF

JBr*_*uce 2 html css pdf google-apps-script

我已经看到了几个关于从 Blob 创建带有彩色背景示例的 PDF 的类似问题,但没有一个答案解决“背景颜色问题”,而且我无法让生成的 PDF 具有任何背景颜色。

我按照这个例子(在 Google Apps Script 中从 HTML 创建 PDF 并包含图像 - 图像未显示)并将图像包含在 pdf 中,但背景颜色不在 pdf 中。

function htmlToPDF() {

  var html = "<h1>Hello world</h1>"
       + "<p>This is just a paragraph"
       + "<p style='color:red;'>I am red</p>"
       + "<p style='color:blue;'>I am blue</p>"
       + "<p style='font-size:50px;'>I am big</p>"
       + "<table style='border-collapse: collapse; width: 698px; height: 115px; background-color: #C5D9F1;' border='0' cellpadding='10'>"
       + "<tbody>"
       + "<tr>"
       + "<td style='padding: 5px;background-color:powderblue;' nowrap='nowrap'><strong>Bold with background-color:</strong></td>"
       + "</tr>"
       + "</tbody>"
       + "</table>";

  var blob = Utilities.newBlob(html, "text/html", "text.html");
  var pdf = blob.getAs("application/pdf");

  DriveApp.createFile(pdf).setName("text.pdf");

  MailApp.sendEmail("[your email here ]", "PDF File", "", 
     {htmlBody: html, attachments: pdf});
}
Run Code Online (Sandbox Code Playgroud)

字体颜色正确,但没有背景颜色

JBr*_*uce 7

答案很简单......在网上找到了这个并添加......

    html { -webkit-print-color-adjust: exact; }
Run Code Online (Sandbox Code Playgroud)

这是现在有效的代码......

function htmlToPDF() {

  var html = 
      "<style> html { -webkit-print-color-adjust: exact; } </style>"
      + "<h1>Hello world</h1>"
      + "<p>This is just a paragraph"
      + "<p style='color:red;'>I am red</p>"
      + "<p style='color:blue;'>I am blue</p>"
      + "<p style='font-size:50px;'>I am big</p>"
      + "<table style='border-collapse: collapse; width: 698px; height: 115px; background-color: #C5D9F1;' border='0' cellpadding='10'>"
      + "<tbody>"
      + "<tr>"
      + "<td style='padding: 5px;background-color:powderblue;' nowrap='nowrap'><strong>Bold with background-color:</strong></td>"
      + "</tr>"
      + "</tbody>"
      + "</table>";

   var blob = Utilities.newBlob(html, "text/html", "text.html");
   var pdf = blob.getAs("application/pdf");

   DriveApp.createFile(pdf).setName("text.pdf");

   MailApp.sendEmail("[your email here ]", "PDF File", "", {htmlBody: html, attachments: pdf});
}
Run Code Online (Sandbox Code Playgroud)