Reputation: 47
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
Thank you!
Upvotes: 3
Views: 1625
Reputation: 6481
/**
* 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:
urlFetchApp
to get the images, I just used the inbuilt DriveApp
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.
Upvotes: 1