Show images inside a pdf created with Gloogle Apps

2020-02-16 02:25发布

问题:

I am creating PDF files using blobs in Google Apps Script from a HTML code, but the problem is that HTML code has an image (referenced by "http") but the created pdf can't show it.

This is my code

function createBlobPDF(myMessage,myTitle){
var blobHTML = Utilities.newBlob(myMessage, "text/html", myTitle+ ".html");
var myPDF = blobHTML.getAs("application/pdf");
return myPDF;
}

Any solution? thanks!!

回答1:

If the images in HTML are loaded from URLs, the converted PDF file doesn't include the images. If you want to include the images in the converted PDF file, please put the images to HTML as base64 data.

In order to confirm this situation, please see the following sample script. This sample script puts an image as URL and base64 data. The result is displayed them to a dialog and created a PDF file.

When you use this script, please copy and paste to the script editor of Spreadsheet.

Sample script :

function myFunction() {
  // image
  var url = "https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a";
  var blob = UrlFetchApp.fetch(url).getBlob();
  var b64 = blob.getContentType() + ';base64,'+ Utilities.base64Encode(blob.getBytes());
  var html = "URL<img src=\"" + url + "\">Base64<img src=\"data:" + b64 + "\">";
  var h = HtmlService.createHtmlOutput(html);

  // Open dialog with the images.
  SpreadsheetApp.getUi().showModalDialog(h.setWidth(500).setHeight(200), 'Sample');

  // Create from HTML to PDF file.
  DriveApp.createFile(h.getAs("application/pdf").setName("text.pdf"));
}

Result of dialog :

Both images can be seen.

Result of PDF file :

Only the image of base64 can be seen.

Note :

  • This is a simple script. So please modify this to your environment.

References :

  • How to display Base64 images in HTML?

If I misunderstand your question, I'm sorry.