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 document.
Apparently, downloading the Google document 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
Project is deployed as a web app
Code.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:
<!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.
I believe your goal as follows.
however it is blank
is that the Document is not saved.When above points are reflected to your script, it becomes as follows.
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
<!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>