[英]Download a created Google Doc from a deployed web app (Google Apps Script)
I've created a script that, when deployed as a web app, asks the user for some input, and creates and writes to a google doc.我创建了一个脚本,当部署为 Web 应用程序时,它会询问用户一些输入,然后创建并写入 google 文档。
Apparently, downloading the google doc from the script is not possible, and the next best thing seems to convert the doc and save it in my drive.显然,从脚本下载谷歌文档是不可能的,接下来最好的事情似乎是转换文档并将其保存在我的驱动器中。
I have tried this very simple approach, inspired by Convert Google Doc to PDF using Google Script Editior我尝试过这种非常简单的方法,其灵感来自于使用 Google Script Editor 将 Google Doc 转换为 PDF
Project is deployed as a web app项目部署为 Web 应用程序
Code.gs:代码.gs:
function doGet() {
return HtmlService.createHtmlOutputFromFile('Index');
}
function editDoc(data) {
let doc = DocumentApp.create("Title");
let body = doc.getBody();
body.setText(data);
docblob = doc.getAs('application/pdf');
docblob.setName(doc.getName() + ".pdf");
let file = DriveApp.createFile(docblob);
}
Index.html:索引.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form onsubmit="edit()">
<input type="text" id="input">
<input type="submit" id="sub" value="Submit">
</form>
<script>
function edit() {
google.script.run.editDoc(document.getElementById("input").value);
}
</script>
</body>
</html>
As a result, this adds a pdf to my google drive, which should be the pdf form of the created google doc, however it is blank.结果,这会在我的 google 驱动器中添加一个 pdf,它应该是创建的 google doc 的 pdf 形式,但是它是空白的。
I believe your goal as follows.我相信你的目标如下。
however it is blank
is that the Document is not saved.however it is blank
的原因是没有保存文档。 When above points are reflected to your script, it becomes as follows.当以上几点反映到你的脚本中时,它变成如下。
Code.gs
Code.gs
function doGet() { return HtmlService.createHtmlOutputFromFile('Index'); } function editDoc(data) { let doc = DocumentApp.create("Title"); let body = doc.getBody(); body.setText(data); doc.saveAndClose(); return { data: "data:application/pdf;base64," + Utilities.base64Encode(doc.getBlob().getBytes()), filename: doc.getName() + ".pdf" }; }
HTML & Javascript side: Index.html
Index.html
<!DOCTYPE html> <html> <head> <base target="_top"> </head> <body> <form onsubmit="event.preventDefault(); edit();"> <input type="text" id="input"> <input type="submit" id="sub" value="Submit"> </form> <script> function edit() { google.script.run.withSuccessHandler(({data, filename}) => { const a = document.createElement("a"); document.body.appendChild(a); a.download = filename; a.href = data; a.click(); }).editDoc(document.getElementById("input").value); } </script> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.