
[英]Create PDF from HTML in Google Apps Script and include images - Images not showing up
[英]Google Apps Script - Images not showing when creating PDF from HTML
我正在尝试编写一个脚本,它将 output 和 PDF 的值输入到表单中。 在此 PDF 上,我想在页面顶部包含一个徽标,该徽标是 Google Drive 文件夹中的图像。
基于这个问题(和其他问题),需要将图像转换为 base64,然后添加到 HTML。
我的问题是,即使我这样做,图像仍然没有出现在 PDF 文件中。
这是我当前的代码,只是尝试使用图像 output 和 PDF ,仅此而已
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");
}
谢谢!
/**
* 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)
}
}
我从您的脚本中更改了几件事:
urlFetchApp
来获取图像,而是使用了内置的DriveApp
这个脚本对我有用。 我不确定您的脚本失败的确切原因,但如果这也不起作用,请尝试更改图像文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.