Google Apps 脚本 如何创建代码以将现有 PDF 文件下载到没有 HTML 的 PC 上的本地下载文件夹?



所以,我有下面显示的代码,它工作正常! 有问题的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 编码的字符串发送到 Web 应用

这将允许您隐藏id和 URL。

请参阅以下示例:

索引.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>

Code.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]替换为所需的。

引用

  • blob.getBytes
  • Utilities.base64encodedata
  • 基地 64

所以我的代码中有这个"全局变量": 全局变量

在doGet(request)函数中,我为这些变量分配了值。 赋值

我在 code.gs 创建了 2 个函数,可通过"下载.html"文件访问。此外,未使用2个额外的功能。它们是:函数

然后在下载.html文件中,我有以下JavaScript代码: 正在下载的JavaScript.html

我知道。你可以看到我是一个新手。但它有效,这才是最重要的。以这种方式编写的代码使我更容易理解。至少现在我的 GAS 项目可以向前推进。

感谢所有帮助过我的人。我非常感谢这一点。 谢谢X 100。:)