Mar
21
2012

Merge info from Google Forms to PDF Document and Send via Email

Today we needed a way to easily take information submitted from Google Form and create a form letter so administrators can sign and send it home with a student. I went through several mail merge scripts but nothing fit exactly what I needed so I took some of the best ideas from all of them (especially the employee of the month script) and created a system that works for us. This method of utilizing Google Apps script can be used for certificates for PD sessions, creating awards, or any other documents in which you need to get information that is submitted via a Google form.

Note, this is an advanced walkthrough but if you need help, please just ask! I am more than willing to work through it with you!

 

This is what our final document looks like:

Here is our workflow:

 

To get started create your Google form and get all of the information that you need to record. It is worth noting that we record more information on our form than actually goes on our final product. You can find a copy of the form we use here: http://bit.ly/mergetutform

 

After you create your form its time to create the template for what your end result will look like. Create a new blank Google doc and setup your letter. For our example, the bus conduct report, we have fields such as “Students Name” “Date of incident” “Explanation” etc. You can find a copy of our template here: http://bit.ly/mergetemplate notice in the area where information from our form needs to be we type the word “key” before it. This is important as our script searches the document for what we define here.

When your template is created its time to add the script to our spreadsheet. When you create a Google form all of  the information that user’s input is saved in a Google Spreadsheet. This spreadsheet is where we are going to add our script.

The way the Google scripts work is based on triggers. Triggers are a way to answer the question “What do I do when X happens?  In our case we want to create a PDF with the information from our form and send it to a pre-defined user (The building Administrator and Transportation Director).

 

To get started click “Tools” and then click “Script Editor”.

 

When you do you will see an untitled project come up. It looks like this:

Delete everything in the editor so we have a blank slate.

Step one is to pull in the template that we created earlier. We do this by defining our template variable:

 var docTemplate = ;

We need to tell the script what document ID is. We find this by opening our template and copying the long code in the url. You only want to copy what is pictured below:

 So your code should look like this:

 

 var docTemplate = "1sbsvGkJCmkN-NDkKLpZcZUy8h9x2YHkVmYOg9jJwYrI";

Next we name our template by entering

 var docName = "BusConductReport";

Now its time to create our trigger for when the user hits submit on the form. For this we create a function or trigger. We do this by entering:

 function onFormSubmit(e) {}

All of our code will go in between the ” { } “.

The first thing we want to do in the trigger is create our variables or holders. These will be the pieces of information that we need to put into our template.

 

We do this by entering:

 var  variablename = "static entry or form value"

Here is an example of the ones I used:

  var email_address = "thouston@huron-city.k12.oh.us";
  var full_name = e.values[2];
  var incident_date = e.values[5];
  var grade_level = e.values[4];
  var bus_number = e.values[6];
  var violations = e.values[10];
  var explanation = e.values[11];
  var drivers_coa = e.values[12];

*Note: e.values[x] is taking the value from the form in numerical order as seen below,

Now we need to grab the template we defined earlier and make a working copy. As you can see in the code we make a new copy and combine our document name and the name from the form:
 var copyId = DocsList.getFileById(docTemplate)
.makeCopy(docName+' for '+full_name)
.getId();

Next we open the temporary document that we just created:

var copyDoc = DocumentApp.openById(copyId);

Now we need to tell the script to go into the body of our document :

var copyBody = copyDoc.getActiveSection();

So we can replace our placeholder keys that we put in our template earlier:

copyBody.replaceText('keyFullName', full_name);
copyBody.replaceText('keyTodaysDate', incident_date);
copyBody.replaceText('keyGradeLevel', grade_level);
copyBody.replaceText('keyBusNumber', bus_number);
copyBody.replaceText('keyViolations', violations);
copyBody.replaceText('keyExplanation',explanation);
copyBody.replaceText('keyDriverCOA', drivers_coa);
 After we replace our variables we need to save and close our document:
copyDoc.saveAndClose();

Next, create a PDF of our temporary document:

var pdf = DocsList.getFileById(copyId).getAs("application/pdf");

Than, send an email to our recipient we defined earlier (remember this does not have to be a static entry like our example, you could pull from your form if you are creating certificates etc) :

var subject = "Bus Conduct Report";
var body = "Here is the Bus Conduct form for " + full_name + "";
MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: pdf});

The final step is to get rid of the temporary document we have been working with. If you do not do this your Google Docs account will become filled with your temporary documents.

DocsList.getFileById(copyId).setTrashed(true); }

Whole Script:

// TJ Houston tjhouston.com (tj@tjhouston.com)
// Bus Conduct Report
// Get template from Google Docs and name it
var docTemplate = "1sbsvGkJCmkN-NDkKLpZcZUy8h9x2YHkVmYOg9jJwYrI"; // *** replace with your template ID ***
var docName = "BusConductReport";

// When Form Gets submitted
function onFormSubmit(e) {
//Get information from form and set as variables
var email_address = "tvonthron@huron-city.k12.oh.us, thouston@huron-city.k12.oh.us";
var full_name = e.values[2];
var grade_level = e.values[3];
var incident_date = e.values[4];
var bus_number = e.values[5];
var violations = e.values[9];
var explanation = e.values[10];
var drivers_coa = e.values[11];

// Get document template, copy it as a new temp doc, and save the Doc’s id
var copyId = DocsList.getFileById(docTemplate)
.makeCopy(docName+' for '+full_name)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document’s body section
var copyBody = copyDoc.getActiveSection();

// Replace place holder keys,in our google doc template
copyBody.replaceText('keyFullName', full_name);
copyBody.replaceText('keyTodaysDate', incident_date);
copyBody.replaceText('keyGradeLevel', grade_level);
copyBody.replaceText('keyBusNumber', bus_number);
copyBody.replaceText('keyViolations', violations);
copyBody.replaceText('keyExplanation',explanation);
copyBody.replaceText('keyDriverCOA', drivers_coa);

// Save and close the temporary document
copyDoc.saveAndClose();

// Convert temporary document to PDF
var pdf = DocsList.getFileById(copyId).getAs("application/pdf");

// Attach PDF and send the email
var subject = "Bus Conduct Report";
var body = "Here is the Bus Conduct form for " + full_name + "";
MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: pdf});

// Delete temp file
DocsList.getFileById(copyId).setTrashed(true);
}

You can find a copy of our template here: http://bit.ly/mergetemplate

You can find a copy of the spreadsheet that we used here: http://bit.ly/mergetut

You can find a copy of the form we use here: http://bit.ly/mergetutform

You can find the script here: http://pastie.org/3587263 or as text here: http://bit.ly/mergescripttext

Related Posts

About the Author: TJ Houston

TJ Houston is the Director of Technology at Huron City Schools. TJ leads professional development in all areas of technology and loves developing ways to make teachers, students, and staff's lives easier with the use of technology. TJ also loves photography and his portfolio can be found at http://www.tjshots.com. All of the views on this site are his own.

  • Keith Gonzalez

    This worked great, but I noticed one quirk when the PDF is created. It makes a double-space in the replacement when there’s just a carriage return in the form field and also shows carriage return in the Google spreadsheet. Is there a way around this? Thanks!!!

    • http://www.tjhouston.com/ TJ Houston

      Not as far as I know. What I would do in this case is put directions in the help field that tell users not to hit enter. Does that answer your question? Let me know!

      Thanks
      TJ

  • Balanand

    TypeError:
    Cannot read property “Values” from undefined. (line 10).. this is error I am facing.. Please help

    • http://www.tjhouston.com/ TJ Houston

      Are you still having this issue?

      • Matthew Newberry

        I’m getting this error. 

        • http://www.tjhouston.com/ TJ Houston

          Please send a copy of your code to tj at tjhouston.com and we can chat. Its much easier to converse via email than in comments :)  

      • Linda

        I am getting the same error. ? please help

      • Kalyn Brewer

        I am getting the error also.

  • Richard Forster

    Thanks TJ,

    A very good tutorial.  I needed a mail merge to generate snail mail for those members of our club who don’t use email. Using the various Document API’s in the way you describe  has given this to me.  Much appreciated.

    • http://www.tjhouston.com/ TJ Houston

      No problem! Let me know if you need anything else!

      Thanks
      TJ

  • plnaugle

    Hi TJ. Thanks for sharing the link to this post in the backchannel of the Simple K12 webinar today. Great to learn about this option. 

    • http://www.tjhouston.com/ TJ Houston

      Not a problem! Let me know if you or any of the educators you work with need help setting it up 

      Thanks
      TJ

  • Pingback: Merge info from Google Forms to PDF Document and Send via Email | Using Google Docs in the classroom | Scoop.it

  • Pingback: Mail Merge from Google Forms to PDF Document and Send via Email | iGeneration - 21st Century Education | Scoop.it

  • Ed Neuhaus

    Hi Tj,  Great instructions, This is very useful.  I would like to expand on the email that is sent and add in another attachment.  It is already a PDF and loaded into google docs.  I tried a few different ways of adding it as an attachment with no luck.  Any ideas how I could do that?

    • http://www.tjhouston.com/ TJ Houston

      I havent tried it but you should be able to create another PDF Variable

      var pdf2 = DocsList.getFileById(2ndGoogleAppID).getAs(“application/pdf”);And than add it to the attachements call  ”attachments: pdf,pdf2″I will test when I get some time. Let me know if you are successful. ThanksTJ

      • Ed Neuhaus

        JT, I can get the document set up as a variable and get it to out put correctly.  The problem I am having is getting both document to show up as attachments.  I tried various ways to reverence both files but can’t figure out the correct way.  Any ideas?

        • http://www.tjhouston.com/ TJ Houston

          So only one shows? Or none show?

      • Ed Neuhaus

        So I figured it out and thought I would share incase anyone else has the same problem.  If you make an array of the files that need to be sent it works well.

        // Convert temporary document to PDFvar pdf = DocsList.getFileById(copyId).getAs(“application/pdf”);var pdf2 = DocsList.getFileById(docId).getAs(“application/pdf”);  // Create an Array for attachmentsvar pdfArray=new Array( pdf, pdf2);

        // Then call the array in the mail app function

        MailApp.sendEmail(myEmail, subject, body, {htmlBody: body, attachments: pdfArray });

  • Andy MALO

    Hi ! Really good tuto ! But I got this error :
    Cannot read property “Values” from undefined. (line 7) :(

    It’s on this line : var full_name = e.values[2];
    I don’t know how to resolve it :/ Can you help me please ?

    • http://www.tjhouston.com/ TJ Houston

      Did you setup your triggers for “On Form Submit”? Here is the link to do that: http://tjhouston.com/2012/07/setting-up-triggers-in-google-apps-for-debugging/

      Let me know!
      Thanks
      TJ

      • Andy MALO

        Well I did what you said :) I already setup the triggers and the notifications :

        Début

        Fonction

        Message d’erreur

        Déclencheur

        Fin

        01/08/12 13:21

        onFormSubmit

        TypeError: Cannot read property “3″ from undefined. (ligne 21)

        formSubmit

        01/08/12 13:21

        That’s what it reported me I think the script doesn’t want to initialize my var with the datas from the form :/

        • Andy MALO

          Well I resolved my problem :
          I didn’t use = e.values[x] but e.namedValues["x"]
          It works great :)

          Thank you for your help

          Andy MALO

  • Pingback: Setting up Triggers in Google Apps for Debugging « TJ Houston.com

  • Lori

    I am getting the following error.

    TypeError:
    Cannot read property “Values” from undefined. (line 5)

    I see that other people have had the same issue.  I made sure my triggers were set up and tried the change that Andy made, but still no luck.  Any ideas?

    TIA,
    Lori Klooz

  • Eric Pabst

    This looks very helpful.  Thank you!

  • Maia

    I am getting the same error messages telling me that “values” is undefined.  I have tried everything that has been suggested in the comments below, but have not been able to fix the problems.  I would appreciate any advice to get this code working! 

    • http://www.tjhouston.com/ TJ Houston

      Are you getting the errors when you hit play in the code editor or when you submit? Make sure you set your triggers to get debug info: http://tjhouston.com/2012/07/setting-up-triggers-in-google-apps-for-debugging/

      Let me know!
      Thanks
      TJ

    • Lila

      I am also facing same problem, TypeError: Cannot read property “namedValues” from undefined. I tried all solutions below, is it any way to contact you via email for help? Thanks in advance. /Lila

      • http://www.tjhouston.com/ TJ Houston

        sure! Email is tj at tjhouston.com

      • Tfoley1

        I don’t know a lot about scripts, but I changed the number in the e.values[1] and e.values[2], etc… and it worked great for me.

        TJ, this is awesome and definitely helped me solve a huge issue at my school with event registration.

        • Tfoley1

           Ah, value [1] in TJ’s example is the user ID, since his form automatically collects it.  If your form is not set up to do that, then your first question’s value whoudl be [1].

          • http://www.tjhouston.com/ TJ Houston

            Thanks for pointing that out. Work is super busy havent had time to respond.

  • Pedro Rodrigues

    Another challenge: I’d like to have 2 fields appearing on the generated PDF, but not exactly submitted by the form, just with the form.

    i) Issue date: I’d like to generate the current date (no time) and insert it on the copyDoc PDF
    ii) Expiry date: I’d like to sum one year to the Issue Date and add this as well to the PDF (e.g. if current date, i.e., issue_date is 30-Aug-2012, expiry date should be 30-Aug-2013).
    Currently, I have both variables being manually submitted by users, which often leads to errors.
    var issue_date = e.values[5];var expiry_date = e.values[6];

    How could the script be edited so that I get those dates instantly?
    And could they be added to the spreadsheet as well?

    • Pedro Rodrigues

      Check follow-up here: https://productforums.google.com/forum/#!msg/docs/-PKHodzUDn8/90omfIQ8uYgJ

  • Vbignacio

    thanks for this. what should i change if i want to attach a doc copy instead of a pdf?

    • http://www.tjhouston.com/ TJ Houston

      At this time I do not believe it is possible :( You could however not delete the doc in your docs account and export it that way.

      Thanks
      TJ

  • Jonathan Braley

    Hey TJ not sure if Google Docs has this functionality, but I have a .pdf that has several checkboxes in it.  I’m trying to implement this functionality on a Google form, but have not found a solution.  Any ideas?

    • http://www.tjhouston.com/ TJ Houston

      Are you looking to have the checkboxes in the final PDF or the form?

      • Jonathan Braley

         We already have them in the form, but are looking to see how those checkboxes on the form get dumped into the .pdf as a checked box on the .pdf.  Would you suggest using drop downs instead?

        • http://www.tjhouston.com/ TJ Houston

          I think dropdowns would be much easier.

  • Edd

    Thank you – this is exactly what I’ve been looking for – however, nothing seems to be happening, and I don’t know where to start tweaking.

    Would you be able to advise?

    At the moment I set up template and form exactly as I like them, the script reports no bugs, but nothing seems to happen – no mails get sent anywhere…

    • Sanjay Mathew

      You might have made the same mistake I made, I copied his script and changed this line
      var full_name = e.values[2];to var empname = e.values[2];However I forgot to change it here:makeCopy(docName+’ for ‘+full_name)so what happens is that the file is never created and no email is sent

      • Edd

        This isn’t making sense to me at all. Let me try and then get back to you.

      • Nicole

        HI Edd, 
        I actually made the exact same mistake that you mentioned above. I went and changed that line but I still did not receive an email with a pdf!  Thanks for the comment – it was helpful!

        • Nicole

          Sorry, Thanks so much Sanjay!

        • Sanjay Mathew

          Here is another reason why it could fail. After saving the
          script, Click on Run and Choose onFormSubmit. It will ask you to authorize the
          script. After you click Authorize, it will say:

          Authorization
          Status

          Now
          you can run the script.

          Click
          the Close button

          Back
          in the Script Windows. Click on Resources and Choose Current Project’s triggers

          It
          will show a link

          No triggers set up. Click here to add one now.

          Click on the link and then choose onFormSubmit, from spreadsheet,
          on form submit

          Click Save

          Click Authorize

          Click Close.

      • Edd Turner

        So I’m back now and I think my questions are clear:

        1. I’m making this for someone else – they need a Google account, right, & access to the spreadsheet – correct?

        2. The line which says ‘MailApp.sendEmail’ – does that mean Mail.app on OS X? Am I only going to have success if the user’s on a Mac?

        More questions to come!

        • http://www.tjhouston.com TJ Houston

          It has been best to create the script on the users account also mail.app is referring to the gmail app. Anyone else had success sharing scripts with others? It seems like permissions are locked down to original creator.

          Thanks
          TJ

  • Sanjay Mathew

    Awesome post. Worked perfectly. Is there a way to tell the field numbers? I had to guesstimate it.

  • Nicole

    Hi TJ, 
    I built the script step by step. It saved without error (I think because I didn’t get an error message) but when I did a sample form, I did not receive a copy of my document as a pdf.  Can you suggest some troubleshooting ideas so I can try again?  Any help that you can provide (or the community for that matter) is greatly appreciated!

    Nicole

  • Pingback: Llenar plantilla en pdf a partir de correo entrante en gmail y más.. | Stringmander – Tips computines

  • http://webloggerz.com/ Webloggerz

    i was looking for this from last 2 days.. thnx mate…much acknowledged tut frm ur end…

  • mail

    Thank you so much for this! This is exactly what I was looking for! This script it amazing, can be customized and it WORKS!

  • raju

    Thanks for the script. However i keep getting following error at the code:

    I see document exists and it copies perfectly fine, however for editing
    var copyId = DocsList.getFileById(docTemplate).makeCopy(docName).getId();

    “Document is missing (perhaps it was deleted?) ”

    Any help would be appriciated

  • Sona Kashyap

    Thanks for the script. However i keep getting following error at the code:

    I see document exists and it copies perfectly fine, however for editing
    var copyId = DocsList.getFileById(docTemplate).makeCopy(docName).getId();

    “Document is missing (perhaps it was deleted?) ”
    Any help that you can provide (or the community for that matter) is greatly appreciated!

    • http://www.tjhouston.com/ TJ Houston

      Are you trying to edit the document after it is created?

  • http://twitter.com/ro_betzy B de la Betzyshor

    is it possible to make two pdf”s and mail them at once to the same email ?

    • http://www.tjhouston.com/ TJ Houston

      You would be able to copy the code and paste it again with a different variable name for the title of the attachement. What is your end goal?

      Thanks
      TJ

      • http://twitter.com/ro_betzy B de la Betzyshor

        i want to take data from one form (excel) an complete two different doc template, export them as pdf an mail them togheter to the same email

      • http://twitter.com/ro_betzy B de la Betzyshor

        well, i did what u`ve said and it`s working only half way, now it generates the second pdf and send it to email, but it doesn`t send the first :( (( any others sugestions ?

        • http://www.tjhouston.com/ TJ Houston

          Did you also add your second PDF to the send mail like so:
          MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: pdf,pdf2});

          Let me know
          Thanks
          TJ

  • http://twitter.com/ro_betzy B de la Betzyshor

    well my new code looks like this

    // Get template from Google Docs and name it

    var docTemplate = “1HEhRZUmdWhMzqpg5cvb2g1B5q-0vNFS2ctU6hA5PFJw”;

    var docName = “TemplateCerereLegitimareClub”;

    // When Form Gets submitted

    function onFormSubmit(e) {

    //Get information from form and set as variables

    var email_address = “mailu_lu_betzy@yahoo.com”;

    var nume_prenume = e.values[1];

    var data_nasterii = e.values[2];

    var cnp = e.values[3];

    var nationalitate = e.values[9];

    var serie_nr_buletin = e.values[10];

    var adresa = e.values[4];

    var localitate = e.values[5];

    var judet = e.values[6];

    var nr_telefon = e.values[7];

    var email = e.values[8];

    // Get document template, copy it as a new temp doc, and save the Doc’s id

    var copyId = DocsList.getFileById(docTemplate)

    .makeCopy(docName+’ for ‘+nume_prenume)

    .getId();

    // Open the temporary document

    var copyDoc = DocumentApp.openById(copyId);

    // Get the document’s body section

    var copyBody = copyDoc.getActiveSection();

    // Replace place holder keys,in our google doc template

    copyBody.replaceText(‘keyNumePrenume’, nume_prenume);

    copyBody.replaceText(‘keyDataNasterii’, data_nasterii);

    copyBody.replaceText(‘keyCNP’, cnp);

    copyBody.replaceText(‘keyNationalitate’, nationalitate);

    copyBody.replaceText(‘keySerieNrBuletin’, serie_nr_buletin);

    copyBody.replaceText(‘keyAdresa’, adresa);

    copyBody.replaceText(‘keyLocalitate’, localitate);

    copyBody.replaceText(‘keyJudet’, judet);

    copyBody.replaceText(‘keyTelefon’, nr_telefon);

    copyBody.replaceText(‘keyEmail’, email);

    // Save and close the temporary document

    copyDoc.saveAndClose();

    // Convert temporary document to PDF

    var pdf = DocsList.getFileById(copyId).getAs(“application/pdf”);

    //al doilea pdf

    // Get template from Google Docs and name it

    var docTemplate = “1Ocvf9YRip-PWv3dSAaB7p3Y2P0r-NpBtbvztkypywqU”;

    var docName = “TemplateAdeziune”;

    // Get document template, copy it as a new temp doc, and save the Doc’s id

    var copyId = DocsList.getFileById(docTemplate)

    .makeCopy(docName+’ for ‘+nume_prenume)

    .getId();

    // Open the temporary document

    var copyDoc = DocumentApp.openById(copyId);

    // Get the document’s body section

    var copyBody = copyDoc.getActiveSection();

    // Replace place holder keys,in our google doc template

    copyBody.replaceText(‘keyNumePrenume’, nume_prenume);

    copyBody.replaceText(‘keyCNP’, cnp);

    // Attach PDF and send the email

    var subject = “Cerere Legitimare Club”;

    var body = “Atasamentul contine cererea de legitimare pentru ” + nume_prenume + “”;

    MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: pdf, pdf2});

    // Delete temp file

    DocsList.getFileById(copyId).setTrashed(true); }

    i get: missing: after property ID. (line 76, fille “code”), the line 76 is the one with

    MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: pdf, pdf2});

    and it`s not sending mail

    • D

      Is there anyway to make it read and email only the latest data in spreadsheet? or everytime the form is submitted?

  • http://www.facebook.com/cavedonzinho Felipe Eduardo Cavedon

    Hey, guys. I’ve managed to write something with a similar result as TJ’s code by changing the approach in his code.

    As you can figure it out, I’m not form USA or some other native english spoken language, but I don’t think that a couple of names might get you lost. Hope it helps you!

    //================================================================================================

    //

    // I must give the credits of this development to TJ Huston, from the site

    // http://tjhouston.com/2012/03/merge-info-from-google-forms-to-pdf-document-and-send-via-email/

    // His work has been the core of this script and I’m sure it shall help many, many others!

    //

    // So I got this code from TJ Huston. I’ve managed to find another way to

    // do the same, but instead using the e.values[x], I’ve used an specific cell to read and copy to

    // template. However, the trick is the “delete line” at the end of this code. It’s the soul of

    // this entire code. As the response comes to the spreadsheet, it is read and the deleted, so all

    // the other responses will be lifted up by the the spread sheet. Hope it helps you.

    //

    //================================================================================================

    // Get template from Google Docs and name it

    var docTemplate = “1w3wPMJ8_qbwkDuZbRdWq1xWzyvWNigw5eBHmZQ9Tycc”; // this is what you want to change for your version

    var docName = “Solicitação para “;

    var ss = SpreadsheetApp.getActiveSheet();

    // For future uses

    var cell = ss.getDataRange();

    // When Form Gets submitted

    function onFormSubmit(e) {

    //Get information from form and set our variable

    var email_address = “felipe.cavedon@laboris.com.br, cavedon.felipe@gmail.com, denise.bersot@laboris.com.br“; // People who should get PDF

    var cargo = ss.getRange(“B2:B2″).getValues(); //=====================================================================================================

    var idade = ss.getRange(“C2:C2″).getValues(); // For each cell, a field from the form. Couldn’t manage to find another way to get this thing working.

    var sexo = ss.getRange(“D2:D2″).getValues(); //=====================================================================================================

    var nivel = ss.getRange(“E2:E2″).getValues();

    var inicio = ss.getRange(“F2:F2″).getValues();

    var situacao = ss.getRange(“G2:G2″).getValues();

    var contrato = ss.getRange(“H2:H2″).getValues();

    var salario = ss.getRange(“I2:I2″).getValues();

    var duracao = ss.getRange(“J2:J2″).getValues();

    var tempo = ss.getRange(“K2:K2″).getValues();

    var cliente = ss.getRange(“L2:L2″).getValues();

    var projeto = ss.getRange(“M2:M2″).getValues();

    var status = ss.getRange(“N2:N2″).getValues();

    var curso = ss.getRange(“O2:O2″).getValues();

    var necessidade = ss.getRange(“P2:P2″).getValues();

    var substituicao = ss.getRange(“Q2:Q2″).getValues();

    var atividades = ss.getRange(“R2:R2″).getValues();

    var dominio = ss.getRange(“S2:S2″).getValues();

    var desejaveis = ss.getRange(“T2:T2″).getValues();

    var experiencia = ss.getRange(“U2:U2″).getValues();

    var caracteristicas = ss.getRange(“V2:V2″).getValues();

    var equipamentos = ss.getRange(“W2:W2″).getValues();

    var observacoes = ss.getRange(“X2:X2″).getValues();

    var diretor = ss.getRange(“Y2:Y2″).getValues();

    var data = ss.getRange(“Z2:Z2″).getValues();

    // Get document template, copy it as a new temp doc, and save the Doc’s id

    var copyId = DocsList.getFileById(docTemplate)

    .makeCopy(docName+’ for ‘+cargo)

    .getId();

    // Open the temporary document

    var copyDoc = DocumentApp.openById(copyId);

    // Get the document’s body section

    var copyBody = copyDoc.getActiveSection();

    // Replace place holder keys,in our google doc template

    copyBody.replaceText(‘keyCargo’, cargo);

    copyBody.replaceText(‘keyIdade’, idade);

    copyBody.replaceText(‘keySexo’, sexo);

    copyBody.replaceText(‘keyNivel’, nivel);

    copyBody.replaceText(‘keyIni’, inicio);

    copyBody.replaceText(‘keySituacao’, situacao);

    copyBody.replaceText(‘keyContrato’, contrato);

    copyBody.replaceText(‘keySalario’, salario);

    copyBody.replaceText(‘keyDuracao’, duracao);

    copyBody.replaceText(‘keyTempo’, tempo);

    copyBody.replaceText(‘keyProjeto’, projeto);

    copyBody.replaceText(‘keyCliente’, cliente);

    copyBody.replaceText(‘keyStatus’, status);

    copyBody.replaceText(‘keyCurso’, curso);

    copyBody.replaceText(‘keyNecessidade’, necessidade);

    copyBody.replaceText(‘keySubstituicao’, substituicao);

    copyBody.replaceText(‘keyAtividades’, atividades);

    copyBody.replaceText(‘keyDominio’, dominio);

    copyBody.replaceText(‘keyDesejaveis’, desejaveis);

    copyBody.replaceText(‘keyExperiencia’, experiencia);

    copyBody.replaceText(‘keyCaracteristicas’, caracteristicas);

    copyBody.replaceText(‘keyObservacoes’, observacoes);

    copyBody.replaceText(‘keyEquipamentos’, equipamentos);

    copyBody.replaceText(‘keyData’, data);

    copyBody.replaceText(‘keyDiretor’, diretor);

    // Save and close the temporary document

    copyDoc.saveAndClose();

    // Convert document to PDF

    var pdf = DocsList.getFileById(copyId).getAs(“application/pdf”);

    // Attach PDF and send the email and name it

    var docName = “Solicitação para ” + cargo;

    var subject = “Nova Solicitação de Vaga: ” + cargo;

    var body = “Solicitação do cargo ” + cargo + ” para o(a) diretor(a) ” + diretor;

    MailApp.sendEmail(email_address, subject, body, {htmlBody: body, attachments: pdf});

    // Delete temp file

    DocsList.getFileById(copyId).setTrashed(true);

    // Ok, this line is used to prevent the code from getting stuck,

    // as deleting the second row will bring up all the rows bellow,

    // forcing it to read and execute the other lines as new docs.

    // Again, I couldn’t find another way to solve this, as e.values[x]

    // returned “undefined” each time that I’ve tried to run;

    ss.deleteRow(2);

    }

    • D

      I tried to do this but for some reason it pulls some data from the spreadsheet but not when the form is submitted. Can you please let me know how i can change that.

  • Sergio Pena

    Mr. Houston,

    I would like some guidance regarding this script of yours. I am trying to make a registration form for a church seminary (in Spanish). Please email me at sergio[at]penatechnologies[.com] at your earliest convenience.

    Much obliged!

    Sergio

  • D

    Hi, I’m trying to do exactly what you’ve described here..Collect data from form and email it as attached PDF file.

    I can’t seem to move past
    var prname = e.values[2];
    var desc = e.values[3];

    In the template I have it as;

    Project Name: keyPrName
    Project Description : keyDesc

    I’m getting the following error

    TypeError: Cannot read property “values” from undefined. (line 14, file “generateScript”)

    Please help! :(

  • Bhaskar M

    Hi Houston,

    I am trying something exactly like what u showed in the example. But i am not able to succeed.

    When i submit the form i am getting the data into the spreadsheet. But i dont receive any email. :( I suspect that i am doing something wrong with the templates part and i am badly struck, I am trying to resolve it since last night.

    Plz help me out. Thanks in advance.

    Regards,
    Bhaskar M.

Find Me Online:

By PDGACO payday loans uk

About Me:

My name is TJ Houston.
I am the Director of Technology at Huron City Schools. I love integrating technology into the classroom and helping teachers find the way on the information super highway. Things I love: My family, My awesome Girlfriend, Technology, Education, and Photography.

I run PD sessions twice a week and run community training the first Saturday of the month. I love teaching people new things.

Best School Admin Blog

Nominated for Best School Admin Blog

Facebook Friends

Sponsers

Classroom 2.0

Presentations

Presenter Badge
diigo education pioneer

Friends