Creating PDF from HTML background color in the PDF

2019-07-19 03:39发布

I have seen several similar questions regarding creating PDF from Blob with examples of colored backgrounds, but none of the answers address the "Background color issue" and I can't get the resulting PDF to have any background color.

I followed this example (Create PDF from HTML in Google Apps Script and include images - Images not showing up) and got the image to be included in the pdf, but the background colors are not in the 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});
}

Font colors are correct, but no background color

1条回答
萌系小妹纸
2楼-- · 2019-07-19 03:57

The answer was quite simple... found this surfing the net and added...

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

This is the code that now works...

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});
}
查看更多
登录 后发表回答