Trying to automatically open a document that is created by a script - google-apps-script

I have a spreadsheet that keeps track of a series of documents. Inside the spreadsheet I have a button which, upon being pressed, locates a particular template file from my drive and makes a copy of it. That script looks like this:
function myFunction() {
var file = DriveApp.getFileById("<template doc id goes here>");
var folder = DriveApp.getFolderById("<folder where new file will go>");
var newfile = "<newly created file name goes here>";
file.makeCopy(newfile, folder);
}
Is there a way I can force the newly created document to open in a new tab once it is created? This way once the new doc is created, I do not need to navigate back to the folder and open in manually for editing.

If you are using HTML Service for the original button, you can simply add a window.open function.
<script>
function openTheUrl() {
window.open("http://www.stackoverflow.com");
};
</script>
The URL to the new document can be returned with the getUrl() method of the File Class:
Google Documentation - getUrl()
There are multiple steps to this process.
Call Apps Script gs function with google.script.run in HTML
Google server side code creates the new document and returns a value
The onSuccess callback function opens the new document
HTML Script tag to call apps script code, and define the success function:
<script>
window.callServerCode = function() {
google.script.run
.withSuccessHandler(openTheUrl)
.myFunction();
}
function openTheUrl(argNewUrl) {
Logger.log('argNewUrl: ' + argNewUrl);
window.open(argNewUrl);
};
</script>
The Apps Script code needs to return a value:
function myFunction() {
var file = DriveApp.getFileById("<template doc id goes here>");
var folder = DriveApp.getFolderById("<folder where new file will go>");
var newfile = "<newly created file name goes here>";
var newFile = file.makeCopy(newfile, folder);
var newDocURL = newFile.getUrl();
return newDocURL;
}
The google.script.run withSuccessHandler function automatically receives the return value.

As mentioned in this question How to open a URL link from JavaScript inside a Google Apps Script HTML Google Site Gadget calling window.open won't work because of caja sanitization.
however you can add the url to a cel, or create a link in the HTML. The user will have to click on it to open the new sheet which may be not the solution you wanted, but it would save the time to look into drive for that new file.

Related

Using Google Apps Script HTML file (from sheets) as a template for a google DOC

What I am trying to do is use an HTML file (that exists within Apps Scripts of a Google sheet) to populate the body of an auto generated Doc.
Process goes like this:
Drop down menu in sheets > click button
Scripts locates a Doc template with no body content > copies it, renames it, saves it to the same folder that the template is in
Closes the Doc.
I can't figure out how to populate the Doc body with the HTML file.
This is what I have right now: (htmlTemplate() is called when drop down button in sheets is clicked)
My HTML file is called practice-template.HTML
function htmlTemplate() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var sheetTemplate = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('template')
var DOC_ID = '1I5q7BnAdj-KcF10Q6N9TgemMZt0Vkq15ipUfhA_iJTI'
// opens Doc Template in Drive
// var template = DocumentApp.openById(DOC_ID)
// open in Docs when you're saving/creating a new doc
var temploc = DriveApp.getFileById(DOC_ID);
var dataRange = sheetTemplate.getRange('A1:H1').getValues();
//get data from cells
for (i in dataRange) {
var rowData = dataRange[i]
var dataOne = rowData[0]
var dataTwo = rowData[1]
var dataThree = rowData[2]
}
// Get ID of Active sheet
var ssloc = DriveApp.getFileById(sheet.getId());
// Get root directory of active workbook
var ssfolder = ssloc.getParents().next();
// makes a new google doc based on the template and named appropriately, in the same folder as the template
var newcopy = temploc.makeCopy(dataOne,ssfolder);
var newcopyurl = newcopy.getUrl();
var doc = DocumentApp.openByUrl(newcopyurl);
var docBody = doc.getBody()
var htmlBody = HtmlService.createTemplateFromFile('practice-template')
var data = {
data_one: dataOne,
data_two: dataTwo,
data_three: dataThree,
}
htmlBody.data = data;
var content = htmlBody.evaluate().getContent();
docBody.replaceText("{{body}}",content)
doc.saveAndClose()
}
When I run the above code I get a new google Doc in the appropriate folder, and the document is populated with the HTML from the practice-html.html file. The problem is that the text in the new google doc is in html syntax and not plain text.
The google Doc template file only has {{body}} as content.
The code in the question is using DocumentApp.Body.replaceText but it passed only one parameter while this method requires two, both parameters should be string. By the way, the content variable have assigned a HtmlOutput object, not a string.
You could use HTML to create a file in Google Drive, then convert that file to Google Docs format, but it's very likely that the best approach is to use a Google document as template, or if you need to create the content programmatically, then use Documents Service (Class DocumentApp), the Advanced Google Docs Service or the Google Docs API.
Related
Render HTML to a Google Doc using app script?
Importing a HTML table into a google doc using google app script

Google Form Script to create new folder and move images to it

I am looking for a script that, once a new image file(s) is uploaded to my Google Drive (via Google Form image upload, the script will create a folder based off one of these Google Form fields (for example Name), and then move all of the images to that folder.
This is what I've cobbled together so far, but because the folder will be generated based off a field I'm not sure how this would work.
function moveFiles() {
var sourceFolder = DriveApp.getFolderById("Creative Upload (File responses)")
var targetFolder = DriveApp.getFolderById("yyyyyyy") //what should this be?
var files = sourceFolder.getFilesByType(MimeType.JPEG);
while (files.hasNext()) {
var file = files.next();
targetFolder.addFile(file);
file.getParents().next().removeFile(file);
}
}
Any suggestions would be greatly appreciated.
You need to incorporate FormApp
Create a bound script attached to your form and retrieve the latest form submission.
Retrieve the response of interest (e.g. name) and use it to create a folder with this name.
Retrieve the Id of the folder.
Retrieve the Id of the uploaded image and add the image by its Id to the newly created folder.
Sample:
function myFunction() {
var form=FormApp.getActiveForm();
var length=form.getResponses().length;
var name=form.getResponses()[length-1].getItemResponses()[0].getResponse();
var uploadedImageId=form.getResponses()[length-1].getItemResponses()[1].getResponse();
Logger.log(id);
var file=DriveApp.getFileById(uploadedImageId);
var folderId=DriveApp.createFolder(name).getId();
DriveApp.getFolderById(folderId).addFile(file);
}
To run the script automatically on every form submission - bind your function to an installable trigger onFormSubmit.

Open Google sheet with script

I would like to open each file in a folder via script. Below is what I have tried. This is my first shot at any script in sheets.
This code runs but does not open file, I could be a mile off on this but I can't figure out how to make it open the files. Thanks for your help
function myFunction() {
var dApp = DriveApp;
var folder = dApp.getFoldersByName("test").next();
var filesIter = folder.getFiles();
while(filesIter.hasNext()) {
var files = filesIter.next();
var ss = SpreadsheetApp.open(files);
}
}
I simply want it to open all the files in a folder in this case "test". there are currently two google sheets in the folder.
Google Apps Script server-side code can't do actions on the client side like opening a spreadsheet on the user web browser but you could use HTML Service to use client side code to achieve your goal.
Related
Open a URL in a new tab (and not a new window) using JavaScript
Open URL in same window and in same tab
You can read open files from Scripts but not in the way that users can open files. You can open them on the server and read and/or write data but the file doesn't open up in edit mode like it does when you open it as a user.
Here's a script that opens up spreadsheets and reads their name and id and returns it to a webapp.
HTML:
<html>
<head><title></title>
</head>
<body>
<div id="data"></div>
<script>
window.onload=function(){
google.script.run
.withSuccessHandler(function(ssA){
var html='';
for(var i=0;i<ssA.length;i++) {
html+='<br />' + 'Name: ' + ssA[i].name + ' Id: ' + ssA[i].id;
}
document.getElementById('data').innerHTML=html;
})
.readSpreadsheetsInAFolder();
}
</script>
</body>
</html>
CODE.gs:
function readSpreadsheetsInAFolder() {
var ssA=[];
var folders=DriveApp.getFoldersByName("LinkedSpreadsheets");
while(folders.hasNext()){
var folder=folders.next();
var files=folder.getFilesByType(MimeType.GOOGLE_SHEETS);
while(files.hasNext()) {
var file=files.next();
var ss=SpreadsheetApp.openById(file.getId());
ssA.push({name:file.getName(),id:file.getId()});
}
}
return ssA;
}
This function was written for my account so you may have to modify the Folder Name to get it to work on your account.

How do I convert jpg or png image to Blob via a Google Apps Script Web App?

I want to http post an image from html form to google apps script web app, and then add that image to google drive.
my apps script is below.
function doPost(e){
var date = new Date();
var timestamp = date.toString()
var adress = e.parameter.adress;
var cost = e.parameter.cost;
var item = e.parameter.item;
var check = e.parameter.image;
//add file to drive
var destination_id = "some ID"
var destination = DriveApp.getFolderById(destination_id);
destination.createFile(check);
};
when I execute, it returns a error ; cannot find method: createFile(String)
I think this is because "check" is a string, and I want to convert the submitted image to Blob.
How can I do this?
How about following sample? Added "getAs()". https://developers.google.com/apps-script/reference/drive/file#getAs(String)
These are very simple html and gas script I used for this test.
HTML: This file name is "form.html".
<form>
<input type="file" name="imageFile">
<input type="button" value="ok" onclick="google.script.run.upload(this.parentNode)">
</form>
GAS script:
function doGet() {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function upload(e) {
var destination_id = "some ID";
var img = e.imageFile;
var contentType = "image/jpeg";
var destination = DriveApp.getFolderById(destination_id);
var img = img.getAs(contentType);
destination.createFile(img);
}
For this sample script, if you want to save as a jpeg file, please change 'contentType' from 'image/png' to 'image/jpeg'. When you upload png file for contentType of 'image/jpeg', the png file is converted to jpeg file by 'getAs()'.
Updated: March 19, 2020
When V8 is enabled, it seems that this.parentNode cannot be sent to Google Apps Script side. I'm not sure whether this is a bug or the specification. I think that this might be resolved in the future update. But as the current workaround, I would like to add one more sample script for uploading the file using Web Apps, dialog and sidebar.
In this case, the file is sent to Google Apps Script side as the byte array. And the file is created from the byte array at Google Apps Script side.
HTML & Javascript: index.html
<input id="file" type="file" onchange="saveFile(this)" />
<script>
function saveFile(f) {
const file = f.files[0];
const fr = new FileReader();
fr.onload = function(e) {
const obj = {
filename: file.name,
mimeType: file.type,
bytes: [...new Int8Array(e.target.result)]
};
google.script.run.withSuccessHandler(e => console.log(e)).saveFile(obj);
};
fr.readAsArrayBuffer(file);
}
</script>
Google Apps Script: Code.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile('index.html');
}
function saveFile(e) {
var blob = Utilities.newBlob(e.bytes, e.mimeType, e.filename);
DriveApp.createFile(blob);
return "Done.";
}
Updated: December 9, 2021
After V8 runtime was released, there was a bug that when the file is sent from HTML form to Google Apps Script side using google.script.run, the file blob was the invalid data.
From Apps Script Pulse by Martin Hawksey, it was found that the invalid blob of sending the file of HTML form to Google Apps Script side using google.script.run has finally been resolved. In this case, this script can be used with V8 runtime.
HTML & Javascript side: index.html
<form>
<input type="file" name="file" onchange="google.script.run.withSuccessHandler(console.log).upload(this.parentNode)">
</form>
Google Apps Script side: Code.gs
const doGet = _ => HtmlService.createHtmlOutputFromFile('index.html');
const upload = ({file}) => DriveApp.createFile(file).getId();
IMPORTANT:
As an important point, in the current stage, when the above HTML is accessed as Web Apps (doGet), this script works. But when the above HTML is accessed as a dialog and a sidebar, file at the Google Apps Script side is undefined. By this, it seems that in the current stage, this HTML can be used with only Web Apps. Please be careful about this. I would like to believe that this situation is resolved in the future update.

Google Apps Script : Making an A Function Execute on Open

I found a script that will move my spreadsheet to a folder. How can I make it so that the functions runs when the spreadsheet is open. I will be applying this to a template so that everytime the template is opened, the "Copy of " spreadsheet file will automatically be moved to my Packing Lists folder.
Here's the code I have....
function MoveFileTo()
{
var docs=DocsList.find('Save Test');
var doc=docs[0]; /*Since we assume there is only one file with the name "Hello World", we take the index 0 */
var folders = doc.getParents();
var newFolder=DocsList.getFolder('Packing Lists');
doc.addToFolder(newFolder); // This will add the document to its new location.
var docParentFolder=folders[0];
doc.removeFromFolder(docParentFolder); // This will remove the document from its original location.
}
EDIT: I tried changing function MoveFileTo to onOpen() and onEdit() but it doesn't seem to work properly. Is there something I am missing?
Try use driveapp instead of doclist (it's deprecated). the impinball comment is really usefull, you should have a look at it.
Anyway here a working code:
function myFunction() {
var destFolder = DriveApp.getFolderById("FOLDER_ID_WHERE8YOU_WANT_TO_MOVE_YOUR_FILES");
var fileList = DriveApp.searchFiles("mimeType = 'application/vnd.google-apps.spreadsheet' and title contains 'FILE_TITLE'"); // change this search if necessary
var originalFileId="THE_ID_OF_THE_ACTUAL_SPREADSHEET_TO_BE_EXCLUDED_FROM_THE_SCRIPT_TREATMENT";
while(fileList.hasNext()){
var fileToMove = fileList.next();
if(fileToMove.getId()==originalFileId){
continue; // don't do anything if it's the original file
}
var papas = fileToMove.getParents();
destFolder.addFile(fileToMove); // do the job
while(papas.hasNext()){
papas.next().removeFile(fileToMove); // remove the actuals parents (can be more than one)
}
}
}