How to use Document App to create a file with chosen template - google-apps-script

I need to create a app to automatically create a google doc, with our company's template (it have saved in G-suite). Here is my question, how to use the DocumentApp to create a doc with the template.
I spent some time inenter link description here, but can not find any.
Any reference or document will be appreciated, thanks!

It is quite simple to do! Here is an example what I have put together for you!
function makeDoc() {
var fileId = DriveApp.getFileById("<<FILEID>>");
var copyId = fileId.makeCopy("<<NEWFILENAME>>").getId();
var copyDoc = DocumentApp.openById(copyId);
var copyBody = copyDoc.getBody();
var doclink = copyDoc.getUrl();
// If it finds <<SOMETHING_IN_TEMPLATE>> it will replace it with "replace in doc"
copyBody.replaceText("<<SOMETHING_IN_TEMPLATE>>", "Replace in doc");
// Save and close the temporary document
copyDoc.saveAndClose();
//Move the new doc to the Unsigned Contracts folder and get a URL for it
var folder = DriveApp.getFolderById("<<WHERE TO SAVE IT>>");
var file = DriveApp.getFileById(copyId);
folder.addFile(file);
// Delete temp file
var doclink = file.getUrl();
DriveApp.getFileById(copyId).setTrashed(true);
//CTRL + Enter to get the link
Logger.log(doclink)
P.s. just noticed this is an old post! Hope this helps someone!

After researching around, I think Google dose not provide the way I could select the template while creating the doc through API. Even they might have, it probably is not the straight shot.

Related

Insert hyperlink with variable into google docs using google scripts

I have a google Form, and the responses populate a response google Sheet, which has a google Script function to generate a google Document using a template.
I am trying to get the address entered in the Form (stored in the response Sheet) to become a hyperlink in the generated Doc.
I have been using the body.replaceText() to replace all the fields I need in the Doc:
body.replaceText("{{Date}}", date);
and its working well, but the address field I would like to become a hyperlink.
I have been trying to do it this way:
body.replaceText("{{Location}}", =HYPERLINK("http://www.google.com/maps/place/'+location+'"));
But that does not become a usable hyperlink, resulting with this in the Doc (please note while it becomes a hyperlink on this page it does not become a hyperlink in Docs):
=HYPERLINK("http://www.google.com/maps/place/myplacenotyours")
I have also tried:
body.replaceText("{{Location}}", location = HYPERLINK("http://www.google.com/maps/place/"+location+));
But this throws up syntax errors.
I have this var:
var location = e.values[2];
So perhaps it better to use that to create another var as a hypertext?
I am now trying:
var loclink = 'Hyperlink("http://www.google.com/maps/place/'+location+'","'+location+'")';
but that doesnt do it either... I'm now starting to think that one can't insert a hyperlink using replace method?
Sorry for the noob question, but I can't figure this out. Can you help me find a solution and put a var into a hypertext link and put that into the Doc as a link?!
Cheers.
Something like this:
function insertLink() {
var pattern = '{{Location}}';
var url = 'https://stackoverflow.com/a/69143679/14265469';
var text = 'how to paste a link';
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var next = body.findText(pattern);
if (!next) return;
var start = next.getStartOffset();
body.replaceText(pattern, text);
body.editAsText().setLinkUrl(start, start+text.length-1, url);
}

Get URL of a file in Google Drive thanks to its name

First of all, sorry for my English (I'm learning ^^).
I want to have a script to find a file's url thanks to the name of the file, and then put the URL in my sheet called 'Suivi-des-devis!' in the range 'O2'
The files are always called "FAC_quote number", and the quote number is in sheet 'DEVIS!' in 'E6'.
I really tried to create the script alone, but it doesn't work. Can someone help me to correct the script please ?
function testenregistrement() {
const doc = SpreadsheetApp.getActive();
var f2 = doc.getSheetByName('Suivi-des-devis');
var dossier2 = DriveApp.getFolderById("1WNyBdexfylgflnDeKtMcdIN-eS578dlH")
var nom = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('DEVIS').getRange('E6').getValue();
var files = dossier2.getFilesByName("FAC_" + nom).getUrl(); f2.getRange('O2').setValue(files);
}
The Folder.getFilesByName() method gets a FileIterator object. Use the FileIterator.next() method to get a file, like this:
var files = dossier2.getFilesByName("FAC_" + nom).next().getUrl();

Google Apps Script to automatically open copied document after creating it?

We are using sheets for our mom & pop store as our invoice. However, my mother-in-law keeps saving over our invoice and we're always having to go back and delete the filled in sections. She cannot seem to remember the steps of making a copy and then opening that. I am using a script (button) to create a copy of the original and it is renamed as the customer name & date into a specific folder. However, once we do that, we still have to navigate to the folder and open the new document. Is there there a way to do this after I click the button on our original document to open of the copy that was made? Here is the script that I am using.
function saveAsSpreadsheet()
{
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var range = sheet.getRange('Carolina Fireworks Order Form!C8');
sheet.setNamedRange('TestRange', range);
var TestRange = sheet.getRangeByName('Carolina Fireworks Order Form!C8').getValues();
Logger.log(TestRange);
var destFolder = DriveApp.getFolderById("1UdK90fEs3gkP4KZuUbmZbvvyVAW5ZMGw");
let name = SpreadsheetApp.getActiveSheet().getRange('C8').getValue();
const ds = Utilities.formatDate(new Date(),SpreadsheetApp.getActive().getSpreadsheetTimeZone(),"MM.dd.yy");
DriveApp.getFileById(sheet.getId()).makeCopy('TestRange', destFolder).setName(`${name}.${ds}`);
}
In your situation, how about the following modification?
From:
DriveApp.getFileById(sheet.getId()).makeCopy('TestRange', destFolder).setName(`${name}.${ds}`);
To:
const file = DriveApp.getFileById(sheet.getId()).makeCopy('TestRange', destFolder).setName(`${name}.${ds}`);
var js = `<script>window.open('${file.getUrl()}');google.script.host.close();</script>`;
var html = HtmlService.createHtmlOutput(js);
SpreadsheetApp.getUi().showModalDialog(html, 'Now loading.');
In this script, the URL is opened using Javascript on the dialog.
This is from this post
Note:
From MetaMan's comment
If you want this to work you will have to disable popup blocking
References:
showModalDialog(userInterface, title)
Window.open()

Google Code (Drive) createFile in parent folder/overwrite existing file in parent folder

so i created a simple google code that exports sheet to json, and I'm wondering if there's a simple way to:
Export the file to the same folder where the sheet that script running it is in,
Overwrite the file if it already exists (also in the same folder the sheet script is in)
cheers
There's no easy way, but here's how (I assume you're using Apps Script):
Get the file id of your spreadsheet https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#getId()
Get its parent folders - there can be more than one - https://developers.google.com/apps-script/reference/drive/file#getParents()
See if there are existing files with the name - there can be more than one - https://developers.google.com/apps-script/reference/drive/folder#getFilesByName(String)
If it exists set its content https://developers.google.com/apps-script/reference/drive/file#setcontentcontent
If it doesn't exist create it - https://developers.google.com/apps-script/reference/drive/folder#createfilename-content
thanx to Ian for research links, made it work :)
here's the snippet if anyone else is needing the same thing
var _ID = SpreadsheetApp.getActiveSpreadsheet().getId();
var _sheet = SpreadsheetApp.getActiveSpreadsheet();
var _file = DriveApp.getFolderById(_ID);
var _folder = _file.getParents().next();
var _parentFolder = _file.getParents().next();
var _existingJsons = _parentFolder.getFilesByName(sheet.getName()+".json");
// if .json with the same name already exists in this directory, just overwrite content
if (_existingJsons.hasNext()){
while (_existingJsons.hasNext() ){
var _json = _existingJsons.next();
_json.setContent(output);
Logger.log(_json.getName());
}
}
// if not, create new one, and move it in the same folder sheet is in
else {
var _json = DriveApp.createFile(sheet.getName()+".json", output, MimeType.PLAIN_TEXT);
_json.makeCopy(_parentFolder);
_json.setTrashed(true);
}

Google App Script- Docs/images in tables?

I have searched and searched for the syntax to place an image in a table cell with Google App Script in a Google Doc (not Sheet). This is what I am trying to do:
var resp01 = UrlFetchApp.fetch("http://www.example.com/image01.png");
var resp02 = UrlFetchApp.fetch("http://www.example.com/image02.png");
var cells = [[resp01.getBlob()], [resp02.getBlob()]];
copyBody.appendTable(cells);
This yields simply the word "Blob" in my table.
I can do this all day long with a paragraph:
Body.getChild(x).asParagraph().appendInlineImage(resp01.getBlob());
But for some reason, the "parallel" syntax in a table won't cut it? Does anyone know what I am missing?
Thank You
You need to call TableCell's insertImage() method and provide the child index and the blob source of the image as parameters.
Hope that helps!
Thank You for the input KRR.
I was able to get my project where I wanted it to go, part of which involved inserting images in a table in a Google Doc using Google App Script. After much reading, I settled on the syntax that follows. I hope this helps anyone else trying to learn:
function createDoc() {
var doc = DocumentApp.create('Sample Document');
var body = doc.getBody();
var resp01 = UrlFetchApp.fetch("http://www.cincinnati-oh.gov/cityofcincinnati/assets/Image/Logos/cityofcincinnati.png");
var rowsData = [["City of Cincinnati IMAGE:", ""]];
table = body.insertTable(1, rowsData);
var row = table.getRow(0);
var cell = row.getCell(1);
cell.appendImage(resp01.getBlob());
}