Directly Update Doc Template from Form - google-apps-script

Is it possible to submit a form and update a Doc template from the form contents? The only way I have seen for doing anything similar was submitting the form to a spreadsheet and having an onFormsubmit function within the spreadsheet update the template.
Is this not possible via forms and a container bound script?
Thanks

yes it's possible, but it's not easy (essentially using doc as template, there is no evident tools for that)

I have initially gotten this to work replacing a few lines in my document template, but now nothing is working for some reason. I did edit the text in the template at one point so I am not sure if that changes the file ID. It creates the copy, but the replaceText is not working. Code attached:
`function onFormSubmit(e) {
var dt = Utilities.formatDate(new Date(), 'GMT', "MM/dd/yyyy")
var submitter = Session.getActiveUser().getEmail();
var copyDoc = DriveApp.getFileById('1t5r8IxLgunJ17J2tXkHfw3LRfuXQeTlP5MZURC-23e0').makeCopy('tmpAddress').getId();
var newDoc = DocumentApp.openById(copyDoc);
var body = newDoc.getBody();
var itemResponse = e.response;
var name = itemResponse.getItemResponses()[0].getResponse();
var email = itemResponse.getItemResponses()[1].getResponse();
var pphone = itemResponse.getItemResponses()[2].getResponse();
var paddress = itemResponse.getItemResponses()[3].getResponse();
var palot = itemResponse.getItemResponses()[4].getResponse();
var pcity = itemResponse.getItemResponses()[5].getResponse();
var pstate = itemResponse.getItemResponses()[6].getResponse();
var pzip = itemResponse.getItemResponses()[7].getResponse();
var nphone = itemResponse.getItemResponses()[8].getResponse();
var naddress = itemResponse.getItemResponses()[9].getResponse();
var nalot = itemResponse.getItemResponses()[10].getResponse();
var ncity = itemResponse.getItemResponses()[11].getResponse();
var nstate = itemResponse.getItemResponses()[12].getResponse();
var nzip = itemResponse.getItemResponses()[13].getResponse();
body.replaceText('#{name}', name);
body.replaceText('#{email}', email);
body.replaceText('#{pphone}', pphone);
body.replaceText('#{paddress}', paddress);
body.replaceText('#{palot}', palot);
body.replaceText('#{pcity}', pcity);
body.replaceText('#{pstate}', pstate);
body.replaceText('#{pzip}', pzip);
body.replaceText('#{nphone}', nphone);
body.replaceText('#{naddress}', naddress);
body.replaceText('#{nalot}', nalot);
body.replaceText('#{ncity}', ncity);
body.replaceText('#{nstate}', nstate);
body.replaceText('#{nzip}', nzip);
body.replaceText('#{dt}', dt)
body.replaceText('#{submitter}',submitter)
newDoc.saveAndClose();
}
`

Related

replaceText working in one instance but not in another

The script is triggered when a Google form is submitted and then auto-fills a Google doc.
It worked perfectly before I added var servicesPTY = e.values[117]; and replaced all the placeholders perfectly. But as soon as I add it then the executions indicator show completed but no documents are produced anymore. The document has placeholders that look like this: {{servicesPTY}} {{regNumberPTY}} {{tradingNamePTY}}
And the code looks like this:
function myFormSubmitPTY(e) {
var regNumberPTY = e.values[112];
var taxNumberPTY = e.values[111];
var tradingNamePTY = e.values[113];
var servicesPTY = e.values[117];
var file = DriveApp.getFileById("16OwyBIZAD2pwkuUXZnYSj-9WB6ObGGRXiEjDLa1tcjw");
var folder = DriveApp.getFolderById("1kogpJdxHLwuEhbVyh2oiIgTPH0SNac2m");
var copy = file.makeCopy(tradingNamePTY, folder);
var doc = DocumentApp.openById(copy.getId());
var body = doc.getBody();
if (type == "PTY (LTD)") {
body.replaceText("{{servicesPTY}}",servicesPTY);
body.replaceText("{{regNumberPTY}}", regNumberPTY);
body.replaceText("{{tradingNamePTY}}", tradingNamePTY);
doc.saveAndClose();
}
}
This works for me:
function testmyFormSubmit() {
var e={values:["one","two","three","four"]};
myFormSubmitPTY(e);
}
var type="PTY (LTD)";//global
function myFormSubmitPTY(e) {
var regNumberPTY = e.values[0];
var taxNumberPTY = e.values[1];
var tradingNamePTY = e.values[2];
var servicesPTY = e.values[3];
var file = DriveApp.getFileById("fileid");
var folder = DriveApp.getFolderById("folderid");
var copy = file.makeCopy(tradingNamePTY, folder);
var doc = DocumentApp.openById(copy.getId());
var body = doc.getBody();
if (type=="PTY (LTD)") {
body.replaceText("{{servicesPTY}}",servicesPTY);
body.replaceText("{{regNumberPTY}}", regNumberPTY);
body.replaceText("{{tradingNamePTY}}", tradingNamePTY);
doc.saveAndClose();
}
}
file name: three
pattern order:
{{servicesPTY}}
{{regNumberPTY}}
{{tradingNamePTY}}
output order:
four
one
three
I must have deselected the trigger for PTY. When I looked at the stackdriver logs I noticed PTY had none. Must have happened in the early hours of the morning. Thanks though. You guys put me on the right track

I am unable to automate the population of footers in google docs

I am trying to automate the population of the footer of a google doc that I have with the values that a pop up dialogue gathers from the users when they open the document. The code that I am using can be seen below, however it only works with the footer of the first page, when and only when I activate the option "Different first page". If I de-activate it (because I want the footer to be consistent within the whole document) nothing changes (not even the first page of the document) when I run the script.
The footer looks like this:
Blablbla / ##value1##
Title: “##value2##” - blablabla
The script to substitute value1 and value2 looks like this:
function myFunction() {
// Display a dialog box for each field you need information for.
var ui = DocumentApp.getUi();
var value1Response = ui.prompt('Enter the value1');
var value2Response = ui.prompt('Enter the value2');
var date = new Date();
//Make a copy of the template file
var documentId = DriveApp.getFileById('google document Id').makeCopy().getId();
//Rename the copied file
DriveApp.getFileById(documentId).setName(value2Response.getResponseText() + date);
//Get the document footer as a variable
var footer = DocumentApp.openById(documentId).getFooter();
footer.replaceText('##value1##', value1Response.getResponseText());
footer.replaceText('##value2##', value2Response.getResponseText());
}
This works for me.
function myFunction() {
var doc=DocumentApp.getActiveDocument();
var ui = DocumentApp.getUi();
var value1Response = ui.prompt('Enter the value1');
var value2Response = ui.prompt('Enter the value2');
var value3Response = ui.prompt('Enter FileName');
var date = new Date();
var documentId = doc.getId();
var footer = doc.getFooter();
footer.replaceText('##value1##', value1Response.getResponseText());
footer.replaceText('##value2##', value2Response.getResponseText());
var doc=DocumentApp.openById("Doc Id");
var footer=doc.getFooter();
doc.setName(value3Response.getResponseText());
footer.replaceText('##value1##', value1Response.getResponseText());
footer.replaceText('##value2##', value2Response.getResponseText());
}

Adding page number in every page of pdf using google apps script

var doc = DocumentApp.create("Text");
var body = doc.getBody();
doc.addHeader().appendParagraph("This is a header");
body.appendParagraph('text');
function addTable("dynamicTable parameters",doc);
var footer = doc.addFooter();
var table = footer.appendTable();
var tr = table.appendTableRow();
var count = 1;
var td = tr.appendTableCell();
td.appendParagraph('this is a document.');
td.setWidth(203);
var td1 = tr.appendTableCell();
td1.setWidth(260);
var table1x2 = td1.appendTable();
var tr1x2 = table1x2.appendTableRow();
tr1x2.appendTableCell("Document Type")
.appendParagraph("").appendText("Notes");
tr1x2.appendTableCell("Author")
.appendParagraph("").appendText("Text");
var table1x4 = td1.appendTable();
var tr1x4 = table1x4.appendTableRow();
tr1x4.appendTableCell("Document No.")
.appendParagraph("").appendText(count++);
var date = Utilities.formatDate(new Date(), "GMT"+5.5, "dd-MM-yyyy");
tr1x4.appendTableCell("Date")
.appendParagraph("").appendText(date);
tr1x4.appendTableCell("Volume No.");
tr1x4.appendTableCell("Page No.")
.appendParagraph("").appendText(PageNo);
The above is sample code I am using to generate footer in every page of pdf.I am trying to add page no in the last code shown above. But unable to increment it dynamically. Is there a way I can display the current page in the page No. column.Kindly let me know if there is any other way I can add page no while converting doc to pdf or any work around is also accepted.

How to display data URI image in email generated by Google App Script?

How to display data URI image in email generated by Google App Script?
var recipient = Session.getActiveUser().getEmail();
var subject = 'SP500 chart';
var page = UrlFetchApp.fetch('http://www.barchart.com/chart.php?sym=%24SPX&style=technical&template=&p=MO&d=M&sd=&ed=&size=M&log=0&t=CANDLE&v=0&g=1&evnt=1&late=1&o1=&o2=&o3=&sh=100&indicators=&addindicator=&submitted=1&fpage=&txtDate=#jump').getContentText();
var tag_begin = page.indexOf('data:image');
var tag_end = page.indexOf('>', tag_begin);
var content = page.substring(tag_begin, tag_end);
MailApp.sendEmail(recipient, subject, '', {'htmlBody': content});
Somehow the Apps script compiler is not recognizing the string.indexOf() method.
Modified the code to retrieve the required value.
function testurl(){
var page = UrlFetchApp.fetch('http://www.barchart.com/chart.php?sym=%24SPX&style=technical&template=&p=MO&d=M&sd=&ed=&size=M&log=0&t=CANDLE&v=0&g=1&evnt=1&late=1&o1=&o2=&o3=&sh=100&indicators=&addindicator=&submitted=1&fpage=&txtDate=#jump').getContentText();
var tag_begin = page.search('data:image');
var searchString = page.substring(tag_begin);
var tag_end = searchString.search('/>');
var tag_endpage = tag_begin + tag_end;
var content = page.substring(tag_begin, tag_endpage);
}
Hope that helps!

Google Script Error - Cannot find method add

I have been puzzled by this error. I have not been able to figure out what I am missing. Without the calls to headPanel the UI was working but would not insert the title or text label so I added the Horizontal panel in hopes of adding the text, but alas error. Please help me with this problem and I need to know what I am messing up.
function doGet(e){
var app = UiApp.createApplication();
var headPanel = app.createHorizontalPanel().setId('headPanel');
var header = app.setTitle('Detention Attendance');
var label = app.createLabel("Please enter attendance for Detention by clicking the checkbox next to the student's name if they were present. Then click Sumbit.");
headPanel.add(header); //* ERROR OCCURS HERE
headPanel.add(label);
app.add(pane);
var panel = app.createVerticalPanel();
var flexTable = app.createFlexTable().setStyleAttribute('border', '2px solid black')
.setStyleAttribute('borderCollapse','collapse')
.setBorderWidth(2);
//Get Data from spreadsheet
var spreadsheetId = 'xxxxxxxxxxxxxxxxxxxxxxxx';//Change it to your Spreadsheet ID
var dataArray = getData(spreadsheetId);
//Load data into table cells
Logger.log(dataArray);
for (var row = 0; row<dataArray.length; row++){
if (row > 0) {
var ticketDate = dataArray[row] [0];
var dateStamp = Utilities.formatDate(ticketDate, "America/Chicago", "MM/dd/yyyy");
Logger.log("dateStamp = " +dateStamp);
dataArray[row] [0] = dateStamp;
var ticketDate2 = dataArray[row] [16];
var dateStamp2 = Utilities.formatDate(ticketDate2, "America/Chicago", "MM/dd/yyyy");
dataArray[row] [16] = dateStamp2;
Logger.log("DateStamp = " +dateStamp2);
}
flexTable.setStyleAttribute("color", "purple").setText(row, 2, dataArray[row][2].toString()).setWidth('300px');
flexTable.setText(row, 0, dataArray[row][0].toString()).setWidth('600px');
flexTable.setText(row, 4, dataArray[row][16].toString()).setWidth('300px');
}
panel.add(flexTable);
app.add(panel);
return app;
}
function getData(spreadsheetId){
var ss = SpreadsheetApp.openById(spreadsheetId);
var sheet = ss.getSheets()[0].getDataRange();
Logger.log(sheet);
return sheet.getValues();
}
Your header var is a UiInstance - in fact it's the same instance as app, returned as a convenience for chaining by the call to .setTitle().
The .add() method is looking for a Widget as a parameter, and not finding it.
You don't need to keep that header var - it's only causing you trouble. In fact, you could set the Title as you create the UiApp instance:
var app = UiApp.createApplication().setTitle('Detention Attendance');