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

时间:2019-04-05 16:42:27

标签: html css pdf google-apps-script

我看到了一些有关从Blob创建带有彩色背景示例的PDF的类似问题,但是没有一个答案解决“背景色问题”,并且我无法使生成的PDF具有任何背景色。

我遵循了这个示例(Create PDF from HTML in Google Apps Script and include images - Images not showing up),并且将图像包含在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});
}

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

1 个答案:

答案 0 :(得分:2)

答案很简单...发现了这个网上冲浪并添加了...

    html { -webkit-print-color-adjust: exact; }

这是现在可以使用的代码...

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