SandA
SandA

Reputation: 47

Google Apps Script - Images not showing when creating PDF from HTML

I am trying to write a script that will output a PDF with values that have been inputted into a form. On this PDF, I would like to include a logo at the top of the page, which is an image in a Google Drive folder.

Based on this question (and others), the image needs to be converted to base64 and then added to the HTML.

My issue is that even when I do this, the image still does not show up in the PDF file.

Here is my current code, just trying to output a PDF with the image, and nothing else

function htmlToPDF() {
  var url = "https://drive.google.com/uc?export=view&id=1pHu-JPLA4Ml6R5Mc7pktLtqCAcGepLMG"
  var img = UrlFetchApp.fetch(url)
  var b64 = img.getBlob().getContentType() + ";base64," + Utilities.base64Encode(img.getBlob().getBytes());
  var html_img = "<img src=\"data:" + b64 + "\" >";

  var blob = Utilities.newBlob(html_img, "text/html", "text.html")
  var pdf = blob.getAs("application/pdf");
  DriveApp.getFolderById('1o-yYvlNmdRYsH-J6b31wrT2GYfkCQEGG').createFile(pdf).setName("text.pdf");
}

Here is what I get when I run this script Output of htmlToPDF

Thank you!

Upvotes: 3

Views: 1625

Answers (1)

iansedano
iansedano

Reputation: 6481

Modified Code

/**
 * Creates an HTML <img> tag from an image file ID
 */
function imgToHtmlTag(fileId) {
  let file = DriveApp.getFileById(fileId)
  let fileBlob = file.getBlob()
  let imgData = fileBlob.getContentType() + ';base64,' + Utilities.base64Encode(fileBlob.getBytes())

  return "<img src='data:" + imgData + "' />"
}

/**
 * Creates a pdf called "test" in your drive based on HTML input
 */
function createPdfFromHtml(html) {
  var blob = HtmlService.createHtmlOutput(html);
  blob = blob.getBlob();
  var pdf = blob.getAs("application/pdf");
  DriveApp.createFile(pdf).setName("test.pdf");
}

/**
 * Function to test above functions
 */
function test() {
  var fileId = "[IMG_DRIVE_FILE_ID]"
  let html = imgToHtmlTag(fileId)
  createPdfFromHtml(html)
}
}

I changed a couple things from your script:

  • Instead of using urlFetchApp to get the images, I just used the inbuilt DriveApp
  • I refactored it into separate functions to make it easier to follow.

This script works for me. I am not sure exactly why your script fails but if this doesn't work either, then try changing the image file.

Reference

Upvotes: 1

Related Questions