google-apps-script - 如何将(PDF,二进制)文件从 GAS Web 服务到浏览器?
问题描述
我的 Google 应用程序脚本创建 PDF 文件。我想让用户下载它。我想让每个人都更容易,所以我认为 Web 应用程序将是一个不错的选择。所以我开始用谷歌搜索解决方案,但我找不到任何有用的东西。
理想情况下,我希望网络用户输入触发 PDF 文件创建的代码(该部分已准备好 - PDF 位于 Google Drive 中),然后通过网络浏览器将文件下载到最终用户计算机。
这可以通过在 Google 应用程序脚本中创建的网络实现吗?
从这个答案中我发现我正在寻找的东西是不可能的https://stackoverflow.com/a/36701196/250422
我找到的最接近的解决方案是google-web-app-script-to-auto-download-from-google-drive
解决方案
我相信你的目标如下。
- 您想让用户使用用户的浏览器下载 PDF 文件。
- 您想使用由 Google Apps 脚本创建的 Web 应用程序来实现此目的。
在这种情况下,下面的示例脚本怎么样?在此示例脚本中,PDF 文件被转换为数据 URL,并让用户使用浏览器下载为 PDF 文件。
示例脚本:
Google Apps 脚本方面:Code.gs
请将以下脚本复制并粘贴到脚本编辑器中Code.gs
。并且,请设置 PDF 文件的文件 ID。并且,请部署 Web Apps。
function doGet() {
return HtmlService.createHtmlOutputFromFile("index");
}
function createDataUrl() {
const fileId = "###"; // Please set the file ID of the PDF file you want to make user download.
const file = DriveApp.getFileById(fileId);
return {
data: `data:${file.getMimeType()};base64,${Utilities.base64Encode(file.getBlob().getBytes())}`,
filename: file.getName(),
};
}
HTML&Javascript 方面:index.html
请将以下脚本复制并粘贴到脚本编辑器中index.html
。
<input type="button" value="download" onclick="download()" />
<script>
function download() {
google.script.run
.withSuccessHandler(({ data, filename }) => {
if (data && filename) {
const a = document.createElement("a");
document.body.appendChild(a);
a.download = filename;
a.href = data;
a.click();
}
})
.createDataUrl();
}
</script>
- 在这种情况下,当您使用浏览器访问已部署的 Web 应用程序并单击“下载”按钮时,PDF 文件将下载到您的本地 PC。
笔记:
- 这是一个简单的示例脚本。所以,请根据您的实际情况进行修改。
- 当您修改 Google Apps 脚本时,请将部署修改为新版本。这样,修改后的脚本就会反映到 Web 应用程序中。请注意这一点。
- 您可以在“在不更改新 IDE 的 Web 应用程序 URL 的情况下重新部署 Web 应用程序”的报告中查看详细信息。
参考:
- 网络应用
- 通过单击按钮将 Google 电子表格中的活动工作表下载为 CSV 和 PDF 文件
- 此答案中的此示例脚本来自上面的帖子。
推荐阅读
- azure - Azure 中的安全存储服务是什么?
- azure - 在 Azure Function 中接收服务总线消息
- python - django,角度,csrf,rest_framework,403,
- c++ - 如何在 MFC 应用程序中添加文档菜单?
- java - 为什么我没有得到任何输出?并且有一个 InputMismatchException
- sql - 从列值中选择条件
- java - 使用 SharedPreferences 从图库中保存图像
- powershell - 使用 Powershell 使用证书加密 csv 文件
- php - 如何在php的欢迎页面登录后将登录按钮替换为注销按钮?
- javascript - 管理在 div 行内动态生成的元素的 onclick 事件