Upload Image in google sheet cell using google apps script? - html

I am looking to upload an image into google sheet cell using a google apps script, I found a script that uploads image into Google Drive folder and then gets the image url into sheet that can be manipulated to get the image:
Here is the first function:
Code.gs
function addImage() {
var filename = 'Row';
var htmlTemp = HtmlService.createTemplateFromFile('Index');
htmlTemp.fName = filename;
htmlTemp.position = 2;
var html = htmlTemp.evaluate().setHeight(96).setWidth(415);
var ui = SpreadsheetApp.getUi();
ui.showModalDialog(html, 'Upload');
}
Following is the return function:
Code.gs
function upload(obj) {
//Retrieve the input data of the Form object.
var newFileName = obj.fname;
var rowNum = obj.position;
var blob = obj.file;
var upFile = DriveApp.getFolderById('[folderid]').createFile(blob).setName(newFileName);
var fileUrl = upFile.getUrl();
var urlCell = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').getRange(rowNum,5);
urlCell.setValue('=HYPERLINK("' + fileUrl + '","View image")');
}
This is the html part:
Index.html
<!DOCTYPE html>
<html>
<head>
<base target="_center">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
</head>
<body>
<form id="myForm">
Please upload image below.<br /><br />
<input type="hidden" name="fname" id="fname" value="<?= fName ?>"/>
<input type="hidden" name="position" id="position" value="<?= position ?>"/>
<input type="file" name="file" id="file" accept="image/jpeg,.pdf" />
<input type="button" value="Submit" class="action" onclick="formData(this.parentNode)" />
<input type="button" value="Close" onclick="google.script.host.close()" />
</form>
<script>
//Disable the default submit action using “func1”
window.onload=func1;
function func1() {
document.getElementById('myForm').addEventListener('submit', function(event) {
event.preventDefault();
});
}
function formData(obj){
google.script.run.withSuccessHandler(closeIt).upload(obj);
}
function closeIt(e){
console.log(e);
google.script.host.close();
};
</script>
</body>
</html>
When I ran the addImage() function, a dialog box popped up in which I uploaded a jpeg image, but when I clicked on submit button, it did not do anything and stuck there, any help would be much appreciated. Thanks

Issue and workaround:
From [Fixed] Google Apps Script Web App HTML form file-input fields not in blob compatible format, in the current stage, when Web Apps is used, the file object in the form object can be parsed by google.script.run. But, unfortunately, it seems that when a dialog and sidebar are used, this cannot be parsed. So, in the current stage, as the current workaround, it is required to parse the file object on the Javascript side. When this is reflected in your script, how about the following modification?
Google Apps Script side: Code.gs
Please `upload as follows.
function upload(obj, rowNum) {
var newFileName = obj[2];
var blob = Utilities.newBlob(...obj);
var upFile = DriveApp.getFolderById('[folderid]').createFile(blob).setName(newFileName);
var fileUrl = upFile.getUrl();
var urlCell = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').getRange(rowNum, 5);
urlCell.setValue('=HYPERLINK("' + fileUrl + '","View image")');
return "Done.";
}
HTML & Javascript side: Index.html
Please formData as follows.
function formData(obj) {
const file = obj.file.files[0];
const fr = new FileReader();
fr.readAsArrayBuffer(file);
fr.onload = f =>
google.script.run.withSuccessHandler(closeIt).upload([[...new Int8Array(f.target.result)], file.type, obj.fname.value], obj.position.value);
}

Related

Only the else condition works in my google apps script Twilio Fax sending web app

I'm having an issue with my If statement.
Basically I set up a fax app with Twilio and Google apps script.
I give the user a choice to upload a document or send out one that stored on my Google drive.
If I upload a file it works. But if I check the checkbox to send a pre-set document, which I'm trying to accomplish by using the If statement it doesn't send.
I troubleshooted, and found that the If statements is getting a TRUE and FALSE value.
I think the problem is that when there is no file passed into the function it doesn't work. The thing is I'm avoiding the file by the If statement so why is it not working.
Below is my HTML file and server side apps script.
Any suggestions?
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(blob, name, number, test) {
//get destination number
var num = number;
var prefix = "+1";
var removeDashes = num.replace(/-/g,"");
var fullNumber = prefix + removeDashes;
var output;
if (test){
output = "APPLICATION SENT!";
}else{
output = "FAX SENT!";
}
var url;
if (test) {
var appl = DriveApp.getFileById('xxxxxxxxx');
var appurl = appl.getDownloadUrl();
url = appurl;
} else {
var folder = DriveApp.getFolderById('xxxxxxxxxxx');
var blob = blob.split(",");
var blob = Utilities.newBlob(Utilities.base64Decode(blob[1]), 'application/pdf');
var fileName = blob.setName(name).getName();
var file = folder.createFile(blob);
//allow access to Twilio
file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
//get file url
var id = file.getId();
var getfile = DriveApp.getFileById(id);
var getnewurl = getfile.getDownloadUrl();
var url = getnewurl;
}
//send fax
var faxUrl = "https://fax.twilio.com/v1/Faxes";
var payload = {
"From" : "+1888888888",
"To": fullNumber,
"MediaUrl" : url,
"Method" : "POST",
};
var options = {
"method" : "post",
"payload" : payload
};
options.headers = {
"Authorization" : "Basic " + Utilities.base64Encode("ACxxxxxxxxxxxxxxxxxx:xxxxxxxxxxxxxxxxxxxxxxx")
};
UrlFetchApp.fetch(faxUrl, options);
return "succes" + output;
}
Here is the HTML file: (I removed the <style> in order to shorten)
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
function upload() {
var file = document.getElementsByName('myFile')[0].files[0];
var number = document.getElementsByName('Pnumber')[0].value;
var test = document.getElementsByName("entered")[0].checked;
var reader = new FileReader();
reader.onload = function (e) {
var content = reader.result;
google.script.run.withSuccessHandler(fileUploaded).uploadFiles(content, file.name, number, test);
return false;
}
reader.readAsDataURL(file);
}
function fileUploaded(status) {
document.getElementById("myForm").reset();
document.getElementById('output').innerHTML = status;
}
</script>
</head>
<body>
<div align="center">
<h1 align="center" style="color:darkblue">FAX APP</h1>
<h2 align="center">SEND OUTGOING FAX</h2>
<hr>
<form id="myForm" align="center">
<label for="pdf">Choose a PDF file to upload -- <b>OR</b>-- Check "SEND APPLICATION" </label>
<br>
<input id="pdf" type="file" name="myFile" >
<br><br>
<input type="checkbox" style="width:25px ; height:25px" name="entered">
<label for="entered" style="font-size:30px" > SEND APPLICATION</label>
<br><br>
<label for="phonenumber">Enter Destination Number</label>
<br>
<input id="phonenumber" type="text" name="Pnumber" placeholder="Phone Number" >
<br>
<input type="submit" value="SEND FAX" onclick="upload()" >
</form>
<p><b>FAX DELIVERY STATUS:</b></p>
<div id="output"align="center"><b></b></div>
<br>
<a href="https://drive.google.com/drive/folders/xxxxxxxxxxxxxxxxxxx?usp=sharing"
target="_blank">SENT FAX DOCUMENTS</a>
</div>
</body>
</html>
BELOW IS THE NOW WORKING CODE OF GOOGLE SCRIPT SIDE AND HTML
THANKS TO #Tanaike's HELP
CURRENT GOOGLE SCRIPT SIDE CODE:
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(blob, name, number, test) {
//get destination number
var num = number;
var prefix = "+1";
var removeDashes = num.replace(/-/g,"");
var fullNumber = prefix + removeDashes;
var output;
if (test){
output = "APPLICATION SENT!";
}else{
output = "FAX SENT!";
}
var url;
if (test) {
var appl = DriveApp.getFileById('xxxxxxxxxxxxxxxxxxxxxxx');
var appurl = appl.getDownloadUrl();
url = appurl;
} else {
var folder = DriveApp.getFolderById('xxxxxxxxxxxxxxxxxxxxxxxxxxx');
var blob = blob.split(",");
var blob = Utilities.newBlob(Utilities.base64Decode(blob[1]), 'application/pdf', name);
var file = folder.createFile(blob);
//allow access to Twilio
file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
//get file url
var id = file.getId();
var getfile = DriveApp.getFileById(id);
var getnewurl = getfile.getDownloadUrl();
url = getnewurl;
}
//send fax
var faxUrl = "https://fax.twilio.com/v1/Faxes";
var payload = {
"From" : "+188888888888",
"To": fullNumber,
"MediaUrl" : url,
"Method" : "POST",
};
var options = {
"method" : "post",
"payload" : payload
};
options.headers = {
"Authorization" : "Basic " + Utilities.base64Encode("ACxxxxxxxxxxxxxxxxxx:xxxxxxxxxxxxxxxxxxx")
};
UrlFetchApp.fetch(faxUrl, options);
return "Success - " + output;
}
CURRENT HTML SIDE CODE:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
function upload() {
var file = document.getElementsByName('myFile')[0].files[0];
var number = document.getElementsByName('Pnumber')[0].value;
var test = document.getElementsByName("entered")[0].checked;
if(!test){
var reader = new FileReader();
reader.onload = function (e) {
var content = reader.result;
google.script.run.withSuccessHandler(fileUploaded).uploadFiles(content, file.name, number, null);
return false;
}
reader.readAsDataURL(file);
}else{
google.script.run.withSuccessHandler(fileUploaded).uploadFiles(null, null, number, test);
return false;
}
}
function fileUploaded(status) {
document.getElementById("myForm").reset();
document.getElementById('output').innerHTML = status;
}
</script>
</head>
<body>
<div align="center">
<h1 align="center" style="color:darkblue">FAX APP</h1>
<h2 align="center">SEND OUTGOING FAX</h2>
<hr>
<form id="myForm" align="center">
<label for="pdf">Choose a PDF file to upload -- <b>OR</b>-- Check "SEND APPLICATION" </label>
<br>
<input id="pdf" type="file" name="myFile" >
<br><br>
<input type="checkbox" style="width:25px ; height:25px" name="entered">
<label for="entered" style="font-size:30px" > SEND APPLICATION</label>
<br><br>
<label for="phonenumber">Enter Destination Number</label>
<br>
<input id="phonenumber" type="text" name="Pnumber" placeholder="Phone Number" >
<br>
<input type="submit" value="SEND FAX" onclick="upload()" >
</form>
<p><b>FAX DELIVERY STATUS:</b></p>
<div id="output"align="center"><b></b></div>
<br>
<a href="https://drive.google.com/drive/folders/xxxxxxxxxxxxxxxx?usp=sharing"
target="_blank">SENT FAX DOCUMENTS</a>
</div>
</body>
</html>
I believe your goal as follows.
You want to remove the error when SEND APPLICATION is checked without selecting a file.
Modification points:
When the file is not selected, an error occurs at FileReader because file is undefined. I think that this might be the reason of your issue.
In this case, I would like to propose the function upload() at Javascript side as follows.
if (file && !test) {}else{} is used. By this,
When the file is selected AND SEND APPLICATION is not checked, the selected file is used.
When the file is not selected OR SEND APPLICATION is checked, the file of var appl = DriveApp.getFileById('xxxxxxxxx') is used.
About this, please modify the if statement for your actual situation.
Modified script:
When your script is modified, please modify upload() at Javascript side as follows.
function upload() {
var file = document.getElementsByName('myFile')[0].files[0];
var number = document.getElementsByName('Pnumber')[0].value;
var test = document.getElementsByName("entered")[0].checked;
// I modified below script.
if (file && !test) {
var reader = new FileReader();
reader.onload = function(e) {
var content = reader.result;
google.script.run.withSuccessHandler(fileUploaded).uploadFiles(content, file.name, number, test);
return false;
}
reader.readAsDataURL(file);
} else {
google.script.run.withSuccessHandler(fileUploaded).uploadFiles(null, null, number, test);
}
}
In this modification, Google Apps Script side is not modified.
Added:
I think that your current issue is due to that you changed Google Apps Script from the script in the initial question. In the current script, name is removed at Google Apps Script and Javascript. By this, an error occurs at createFile. Please use name as follows.
From:
var blob = Utilities.newBlob(Utilities.base64Decode(blob[1]), 'application/pdf');
To:
var blob = Utilities.newBlob(Utilities.base64Decode(blob[1]), 'application/pdf', "sample");
In this case, the filename is a temploral. So you can use various name like "sample", "temp" and so on.
And when you modified the script of Web Apps, please redeploy the Web Apps as new version. By this, the latest script is reflected to the Web Apps. Please be careful this.
And in your current script, if (!test) { is used. In this case, when the button is cliced without selecting file and cheking the checkbox, an error occrurs. Please be careful this.

the eSignature dilemma

I have a form that needs an eSignature collected via mobile. I need it to be free with unlimited responses. I have a working jSignature HTML code for Google Sheets, but I cannot get it to work on mobile.
Ideally, I'd like to stick with Google, though I've been experimenting outside of it with things like Wix (doesn't do exactly what I need it to) or Android Studio (beyond my ability). My ability beyond that isn't great by any means so I'm not sure where to begin, though I have a suspicion it isn't about what I can do so much as what google sheets can do, as in, I've read a bit about how scripting doesn't work well on mobile.
HTML
<!DOCTYPE html>
<html>
<head><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/></head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/willowsystems/jSignature/master/libs/jSignature.min.js"></script>
<body>
<form id="customerForm">
Please sign your name in the pad below: <br>
Full Name: <input type="text" name="username"><br>
Employee Number: <input type="employeenumber" name="useremployeenumber"><br><br>
Signature:
<div id="signature"></div><br>
<img id="rendered" src="" style="display:none">
<input type="button" value="Save" onclick="renderSignature();saveImage();"/>
</form>
</body>
<script>
document.getElementById("signature").style.border = "1px solid black";
$("#signature").jSignature({
'background-color': 'transparent',
'decor-color': 'transparent'
});
function renderSignature(){
$("img#rendered").attr("src",$('#signature').jSignature('getData','default'));
}
function saveImage(e){ //This sends the image src to saveImages function
var bytes = document.getElementById('rendered').src;
console.log(bytes);
var sign = {
username: document.getElementsByName('username')[0].value,
useremployeenumber: document.getElementsByName('useremployeenumber')[0].value
};
google.script.run.saveImage(bytes, sign);
return
}
window.onload=function(){
google.script.run
.withSuccessHandler(function(){google.script.host.close();})
.saveImage(bytes, sign);
}
</script>
</html>
CODE.GS
function showDialog() {
var html = HtmlService.createHtmlOutputFromFile('jSignature')
.setWidth(400)
.setHeight(300);
SpreadsheetApp.getUi()
.showModalDialog(html, 'Your Signature is Required');
}
function doGet() {
return HtmlService
.createTemplateFromFile('jSignature')
.evaluate();
}
function saveImage(bytes, sign){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('my page name');
var dateObj = Date.now();
var bytes = bytes.split(",")
var blob = Utilities.newBlob(Utilities.base64Decode(bytes[1]), 'image/png');
var fileName = blob.setName("Signature "+dateObj).getName();
var sigFolder = DriveApp.getFolderById("my folder id");
var url = sigFolder.createFile(blob).getId();
Logger.log(url)
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Register');
var name = sign.username;
var employeenumber = sign.useremployeenumber;
var signature = ss.insertImage(blob,4,ss.getLastRow()+1);
signature.setWidth(500);
signature.setHeight(20);
signature
var imageCell = ss.getRange(ss.getLastRow()+1, 1, 1, 3).setValues([[Date(), name,employeenumber]]);
}
What I've been thinking about is having the user open the form responses google sheet first, to a page with a link to the form. They would follow that link, fill out the form then be taken back to the google sheets form where an onFormSubmit trigger would bring up the jSignature pad. They would sign and all the information would be collected on one line in the form responses.
How do I make jSignature work for Google Sheets mobile? Is it even possible?

Instead of OnFormSubmit, is there a way to take a row from Google Sheets to merge with a Google Doc using AppsScript?

I know how to merge data from a Google Form submission to a Google Sheet to a Google Document using the trigger OnFormSubmit.
What I want to know is there a way to take a Row of data from a Google Sheet and merge with the same or similar Google Document without going through the Form?
I'm still learning about AppScripts and it seems like it would be easy, but I can't find anything through google searches.
I know that I need to specify the active row, etc and then I need to figure out how to get my e.values or other variables from the active row.
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var getActiveRow = [{name: "getActiveRow", functionName: "fetchActiveRow"}];
ss.addMenu("customMenu", getActiveRow);
};
function fetchActiveRow(e){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var row = ss.getActiveSheet().getActiveRange().getRow();
I expect to take row data and merge with a Google Document so it fills out the "paper form" in the appropriate spaces.
Any help would be greatly appreciated.
A Simple Google Doc Envelope Printer
Well here's a simple number 10 Envelope Printer. The code is in a Google Document but it accesses a Spreadsheet to store addresses. You can enter the addresses in the sidebar or simply type them into the spreadsheet which I personally find much easier.
EnvelopePrinter.gs:
var DSSID=getDSSID();
function onOpen(e)
{
makeEnvelopeMenu()
}
function onInstall(e){
setupEnvelopeApp();
setupDocument();
onOpen(e);
}
function makeEnvelopeMenu()//Rename this to onOpen if this is all you have in this document
{
DocumentApp.getUi().createMenu('Envelope Printer')
.addItem('Show Envelope Sidebar', 'displayEnvelopeSidebar')
.addSubMenu(DocumentApp.getUi().createMenu('Initial Setup')
.addItem('Initialize Spreadsheet Id for Email Address', 'setupEnvelopeApp')
.addItem('Setup Document', 'setupDocument') )
.addToUi();
}
function setupEnvelopeApp()//To make the connection between this document and the spreadsheet you created to store mailing addresses run this script from Script Editor
{
var resp=DocumentApp.getUi().prompt('Mailing Address SpreadsheetId', 'Create a spreadsheet to store mailing address and enter the id of that spreadsheet here', DocumentApp.getUi().ButtonSet.OK);
var dssid=resp.getResponseText();
var props=PropertiesService.getScriptProperties();
props.setProperty('DSSID', dssid);
var ss=SpreadsheetApp.openById(getDSSID());
var sh=ss.getSheetByName('Addresses');
if(!sh) {
var sh=ss.insertSheet('Addresses');
}
sh.appendRow(['Line 1','Line 2','Line 3','Line 4']);
sh.getRange(1,1,1,4).setFontWeight("Bold");
}
function displayDSSID(){
DocumentApp.getUi().alert('The Id of the spreadsheet that stores emails is ' + getDSSID());
}
function resetDSSID() {
PropertiesService.getScriptProperties().setProperty('DSSID', '');
}
function getDSSID(){
return PropertiesService.getScriptProperties().getProperty('DSSID');
}
function setupDocument(){
var doc=DocumentApp.getActiveDocument();
var envelope10={};
envelope10[DocumentApp.Attribute.PAGE_HEIGHT]=296;
envelope10[DocumentApp.Attribute.PAGE_WIDTH]=684;
envelope10[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
envelope10[DocumentApp.Attribute.FONT_SIZE] = 14;
envelope10[DocumentApp.Attribute.BOLD] = true;
envelope10[DocumentApp.Attribute.LINE_SPACING]=1;
envelope10[DocumentApp.Attribute.MARGIN_LEFT]=36;
envelope10[DocumentApp.Attribute.MARGIN_RIGHT]=36;
envelope10[DocumentApp.Attribute.MARGIN_TOP]=36;
envelope10[DocumentApp.Attribute.MARGIN_BOTTOM]=36;
doc.getBody().clear().setAttributes(envelope10);
}
function insertReturnAddress(retaddr){
var retaddr=(typeof(retaddr)!='undefined')?retaddr:'No return address selected.';
var retAddrStyle={};
retAddrStyle[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
retAddrStyle[DocumentApp.Attribute.FONT_SIZE] = 14;
retAddrStyle[DocumentApp.Attribute.BOLD] = true;
retAddrStyle[DocumentApp.Attribute.LINE_SPACING]=1;
retAddrStyle[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT]=DocumentApp.HorizontalAlignment.LEFT;
retAddrStyle[DocumentApp.Attribute.MARGIN_TOP]=0;
var doc=DocumentApp.getActiveDocument();
doc.getBody().getChild(0).asParagraph().setAttributes(retAddrStyle).setText(retaddr);
}
function insertRecipientAddress(recaddr){
var recaddr=(typeof(recaddr)!='undefined')?recaddr:'No Recipient Address selected.';
var retAddrStyle={};
retAddrStyle[DocumentApp.Attribute.FONT_FAMILY] = 'Calibri';
retAddrStyle[DocumentApp.Attribute.FONT_SIZE] = 14;
retAddrStyle[DocumentApp.Attribute.BOLD] = true;
retAddrStyle[DocumentApp.Attribute.LINE_SPACING]=1;
retAddrStyle[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT]=DocumentApp.HorizontalAlignment.CENTER;
retAddrStyle[DocumentApp.Attribute.MARGIN_TOP]=0;
var doc=DocumentApp.getActiveDocument();
doc.getBody().appendParagraph('').setAttributes(retAddrStyle);
doc.getBody().appendParagraph('').setAttributes(retAddrStyle);
doc.getBody().appendParagraph('').setAttributes(retAddrStyle);
doc.getBody().appendParagraph('').setAttributes(retAddrStyle);
doc.getBody().appendParagraph(recaddr).setAttributes(retAddrStyle);
}
function prepareEnvelope(retaddr,recaddr){
setupDocument();
insertReturnAddress(retaddr);
insertRecipientAddress(recaddr)
}
function displayEnvelopeSidebar(){
var userInterface=HtmlService.createHtmlOutputFromFile('Envelope').setWidth(300).setHeight(500).setTitle('Printing Envelopes');
DocumentApp.getUi().showSidebar(userInterface);
}
function savAddress(addr){
var ss=SpreadsheetApp.openById(DSSID);
var sh=ss.getSheetByName('Addresses');
if(sh.appendRow(addr))
{
return true;
}
else
{
return false;
}
}
function getAllAddresses(){
var ss=SpreadsheetApp.openById(DSSID);
var sh=ss.getSheetByName('Addresses');
var rg=sh.getRange(2,1,sh.getLastRow(),sh.getLastColumn());
var vA=rg.getValues();
return vA;
}
Envelope.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<style>
#Instructions{padding:4px;}
</style>
<script>
$(function() {
clearAddressFields();
google.script.run
.withSuccessHandler(putNamesAndAddresses)
.getAllAddresses();
google.script.run
.withSuccessHandler(function(ssid){
document.getElementById('Instructions').innerHTML='Insert Envelope into Printer with front facing up and top facing to the left when printer is in front of you. Folded portion down. Use the Com-10 setting for page size.<br /><span style="font-size:8px;"><strong>SSID:</strong>'+ ssid +'</span>'
})
.getDSSID();
});
function putNamesAndAddresses(data)
{
var select1=document.getElementById("sel1");
var select2=document.getElementById("sel2");
var lf='\n';
select1.options.length=0;
select2.options.length=0;
for(var i=0;i<data.length;i++)
{
var name=data[i][0];
var addr='';
for(var j=0;j<data[i].length;j++)
{
if(j>0 && data[i][j]){addr+=lf;}
addr+=data[i][j];
}
select1.options[i]=new Option(name,addr);
select2.options[i]=new Option(name,addr);
}
}
function saveAddress()
{
$('.addrinp').css('background-color','#ffff00');
var line0=$('#adr0').val();
var line1=$('#adr1').val();
var line2=$('#adr2').val();
var line3=$('#adr3').val();
var addr=[line0,line1,line2,line3];
google.script.run
.withSuccessHandler(clearAddressFields)
.savAddress(addr)
}
function clearAddressFields()
{
$('.addrinp').css('background-color','#ffffff');
$('#adr0').val('');
$('#adr1').val('');
$('#adr2').val('');
$('#adr3').val('');
google.script.run
.withSuccessHandler(putNamesAndAddresses)
.getAllAddresses();
}
function prepareEnvelope()
{
var recaddr=$('#sel1').val();
var retaddr=$('#sel2').val();
google.script.run.prepareEnvelope(retaddr,recaddr);
}
console.log('My Code');
</script>
</head>
<body>
<div id="Instructions"></div>
<div id="envprep" style="border-style: double;padding:0 0 0 10px;">
<h3>Recipient Address:</h3>
<select id="sel1" size="5">
</select>
<h3>Return Address:</h3>
<select id="sel2" size="5">
</select>
<br /><br /><input type="button" id="btn2" value="Address Envelope" onClick="prepareEnvelope();" />
</div>
<div id="newaddr" style="border-style: double;padding:0 0 0 10px;">
<h3>Add Address:</h3>
<input class="addrinp" id="adr0" type="text" size="30" placeholder="1st Line of Address" />
<br /><input class="addrinp" id="adr1" type="text" size="30" placeholder="2nd Line of Address" />
<br /><input class="addrinp" id="adr2" type="text" size="30" placeholder="3rd Line of Address" />
<br /><input class="addrinp" id="adr3" type="text" size="30" placeholder="4th Line of Address" />
<br /><br /><input id="btn1" type="button" value="Save Address" onClick="saveAddress();" />
</div>
<br /><br /><br /><input id="btn0" type="button" value="Close" onClick="google.script.host.close();" />
</body>
</html>
Run the initial setup steps. One of them is to provide the file id for a spreadsheet when it will get mailing addresses. It will open the Spreadsheet based upon the ID you provide and it will create an Addresses sheet and write the Header Line. All you have to do is enter address into that page via the side bar or directly on the Spreadsheet.
Image of Envelope Printer Google Document
Spend some time reading the Google Apps Script reference to figure out what's going on in the code.
Have fun.

How would I go about displaying HTML of a user-inputted URL using Google Apps Script?

I can't seem to get the HTML portion of the webapp and the code.gs portion to communicate with each other. Here is my code so far:
Code.gs:
function doGet() {
//var url = Browser.inputBox('Enter URL', Browser.Buttons.OK);
return HtmlService.createHtmlOutputFromFile('search');
}
function sbox(url) {
//var url = form.url;
var response = UrlFetchApp.fetch(url);
return HtmlService.createHtmlOutput(response);
}
search.html:
<form>
URL:
<input type="text" id="url" name="url" value=""><br>
<input type="button" onClick="formSubmit()" value="Search1" />
<script>
function formSubmit() {
var url = document.getElementById("url").value;
google.script.run.sbox(url);
}
</script>
</form>
function formSubmit() {
var url = document.getElementById("url").value;
google.script.run.withSuccessHandler(closeIt).sbox(url);
}
function closeIt(){
google.script.host.close()
};
However, instead of sending url to code.gs, you can just use window.open(url, "_self");
and open the window from the javascript as the apps script won't be able to do it.

Create spreadsheet alongside file upload with Google App Script

I'm having a surprisingly hard time finding basic examples of setting something like this up. I'm pouring through the documentation, but the basic functions simply will not work. Could really use some advice.
I have file upload working thanks to another tutorial, but I would like to create a spreadsheet as well (or simply OPEN the spreadsheet if it already exists) to store additional info such as the name of the uploader, a URL of the file, etc. No dice!
SERVER.GS:
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('form.html');
}
function uploadFiles(form) {
try {
var ss = SpreadsheetApp.create("TEST123");
var sheet = ss.getSheets()[0];
// Appends a new row with 2 columns to the bottom of the
// spreadsheet containing the values in the array
sheet.appendRow(["Jackson Jones", "jJones#email.com"]);
var dropbox = "Student Files";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var blob = form.myFile;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName);
return "File uploaded successfully " + file.getUrl();
} catch (error) {
return error.toString();
}
}
FORM.HTML:
<form id="myForm">
<input type="text" name="myName" placeholder="Your full name...">
<input type="file" name="myFile">
<input type="submit" value="Upload File"
onclick="this.value='Uploading..';
google.script.run.withSuccessHandler(fileUploaded)
.uploadFiles(this.parentNode);
return false;">
</form>
<div id="output"></div>
<script>
function fileUploaded(status) {
document.getElementById('myForm').style.display = 'none';
document.getElementById('output').innerHTML = status;
}
</script>
<style>
input { display:block; margin: 20px; }
</style>
Of course eventually I would use form.myName and such to populate the spreadsheet, but I can't even get their example code to run.
It looks like you have some problems with your form syntax. Here is a version that will do what you are after -- it a modified version of the code tutorial present the Apps Script HTMLService documentation.
Note I am using IDs to identify the drop folder and log spreadsheet for convenience (note that more than one file/folder can have the same name in Drive, so use of IDs is generally preferable to finding files by name).
Code.gs:
var dropBoxId = "012345679abcdefg"; // Drive ID of 'dropbox' folder
var logSheetId = "abcdefghijklmnopqrstu123"; // Drive ID of log spreadsheet
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('InputForm.html');
}
function uploadFiles(formObject) {
try {
// Create a file in Drive from the one provided in the form
var folder = DriveApp.getFolderById(dropBoxId);
var blob = formObject.myFile;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + formObject.myName);
// Open the log and record the new file name, URL and name from form
var ss = SpreadsheetApp.openById(logSheetId);
var sheet = ss.getSheets()[0];
sheet.appendRow([file.getName(), file.getUrl(), formObject.myName]);
// Return the new file Drive URL so it can be put in the web app output
return file.getUrl();
} catch (error) {
return error.toString();
}
}
InputForm.html:
<form id="myForm">
<input type="text" name="myName" placeholder="Your full name..."/>
<input name="myFile" type="file" />
<input type="button" value="Submit"
onclick="google.script.run
.withSuccessHandler(updateUrl)
.withFailureHandler(onFailure)
.uploadFiles(this.parentNode)" />
</form>
<div id="output"></div>
<script>
function updateUrl(url) {
var div = document.getElementById('output');
div.innerHTML = 'Got it!';
}
function onFailure(error) {
alert(error.message);
}
</script>
<style>
input { display:block; margin: 20px; }
</style>
5 Suggestion to Ryan Roth's Script:
1. "Timestamp" column is not created when somebody fills out form.
2. "required" field attribute not working.
3. The uploaded file should be submitted to google drive with folder created with uploader's name.
4. After submitting the form, the fields doesn't not refresh leaving the entered data as it is.
5. The standalone app is not embeddable in website.
If anyone have the updated script please do share below.