如何解决Google Apps Script 如何创建代码将现有的 PDF 文件下载到 PC 上的本地下载文件夹,而无需 HTML? 您可以将 base 64 编码的字符串发送到网络应用index.html代码.gs演练参考资料
所以,我有下面显示的代码,它工作正常!。 有问题的 pdf 文件名为“targetfile.pdf,该文件已存在。
问题是:
如何获取pdf文件并将其移动/复制到本地计算机中的浏览器下载文件。我只需要代码。 这个想法是代码将运行并且pdf文件会自动发送到PC中的“下载”文件夹。
我尝试了几种编码,但都无济于事。这是我用尽所有其他动作后的求助请求。请帮忙。非常感谢任何帮助。提前致谢。
function starthere(){
var doc = SpreadsheetApp.getActiveSpreadsheet();
var key = doc.getId();
var folder = DriveApp.getFolderById(key); // testFormSheet
var folderid = folder.getParents().next().getId(); // id of folder
var folder = DriveApp.getFolderById(folderid); // testFormSheet
Logger.log(folder);
Logger.log(folderid);
Logger.log(folder);
Logger.log(doc.getName()); //testdownload
// for this test,the target file to download is 'targetfile.pdf'.
// we must find a way to download the file.
var dfile = folder.getFilesByName("targetfile.pdf");
while(dfile.hasNext()){
var currfile = dfile.next();
};
Logger.log(currfile.getName()); // targetfile.pdf
Logger.log(currfile.getId()); // file id of targetfile.pdf
解决方法
您可以将 base 64 编码的字符串发送到网络应用
这将允许您隐藏 id
和 URL。
看下面的例子:
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<button id="button">download pdf</button>
</body>
<script>
const button = document.getElementById("button")
button.addEventListener("click",downloadPdf)
// Will send a request to the back-end to get the base 64 encoded string
function downloadPdf(){
google.script.run.withSuccessHandler(serverResponseHandler).getPdfBlob()
}
// Will create a hidden download link with the pdf and download it.
function serverResponseHandler(base64String){
const linkSource = `data:application/pdf;base64,${base64String}`;
const downloadLink = document.createElement("a");
const fileName = "abc.pdf";
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
}
</script>
</html>
代码.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile("index")
}
// Converts a pdf to a base 64 encoded string
function getPdfBlob(){
const file = DriveApp.getFileById("[FILE_ID]")
const blob = file.getBlob()
const bytes = blob.getBytes()
const b64 = Utilities.base64Encode(bytes)
return b64
}
演练
- HTML 包含一个带有点击处理程序的按钮。
- 按下按钮后,它会向
Code.gs
文件发送请求以获取 base 64 编码的 pdf。 - 使用 base 64 字符串,它将创建一个指向带有 base 64 编码字符串的 pdf 的链接。这样,您在任何时候都不需要透露文件的 ID 或 URL。
请务必将 [FILE_ID]
替换为您想要的那个。
参考资料
,所以我的代码中有这个“全局变量”: global variables
在 doGet(request) 函数中,我为这些变量赋值。 Assigning values
我在 code.gs 中创建了 2 个函数以供“download.html”文件访问。此外,没有使用 2 个额外的功能。它们是:functions
然后在 download.html 文件中我有以下 JavaScript 代码: javascript in download.html
我知道。可以看出我是新手。但它有效,这才是最重要的。而且这样写的代码让我更容易理解。至少现在我的 GAS 项目可以向前推进。
感谢所有帮助过我的人。我很欣赏这一点。 谢谢 X 100。:)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。