Home > Back-end >  How to Generate and email a PDF of an image response submitted in Google form
How to Generate and email a PDF of an image response submitted in Google form

Time:10-16

I am developing a google form which have some text field and image field. Now after submission I am able to generate pdf of text responses. Also the pdf is sent to the respondent email also. I want to know some solution of how to add image in the PDF.

Similar problem is also asked here

i have referred to this Video Tutorial.

The code is as follows:

function afterFormSubmit(e) {
  const info = e.namedValues;
  const pdfFile=createPDF(info);
  const entryRow=e.range.getRow();
  SpreadsheetApp.getActiveSpreadsheet().getSheetByName("People").getRange(entryRow,6).setValue(pdfFile.getUrl());
  sendEmail(e.namedValues["Email"], pdfFile);    
}
function sendEmail(email, pdfFile){

  GmailApp.sendEmail(email, "Succesfuly filled the form ", {attachments:[pdfFile],name:"Test Case" });
}

function createPDF(info){
const pdfFolder= DriveApp.getFolderById("pdfFolderID");
const tempFolder=DriveApp.getFolderById("tempFolderID");
const templateDoc=DriveApp.getFileById("TemplateDOc");
const newTempFile= templateDoc.makeCopy(tempFolder);
const openDoc= DocumentApp.openById(newTempFile.getId());
const body=openDoc.getBody();
body.replaceText("{Fn}", info['Name'][0]);

openDoc.saveAndClose();
const blobPDF= newTempFile.getAs(MimeType.PDF);
const pdfFile= pdfFolder.createFile(blobPDF).setName(info['Name'][0]   "_Application for the post" );
tempFolder.removeFile(newTempFile);
return pdfFile;    
}

CodePudding user response:

Create a placeholder for the image and replace it through an actual image blob retrieved from the url of the uploaded image

Assuming that the URL to the image is contained in the response to the question "Image" and that the placeholder in the template is called "{Image}", modify function createPdf as following:

function createPDF(info){
    ...
    const body=openDoc.getBody();
    body.replaceText("{Fn}", info['Name'][0]);

    var imageUrl = info['Image'][0];
    var imagePlaceholder = "{Image}";
    var id = imageUrl.match(/[\w\_\-]{25,}/)[0];
    var img = DriveApp.getFileById(id);
    var position = body.findText(imagePlaceholder);
    var element = position.getElement();
    element.asText().setText("");
    element.getParent().asParagraph().insertInlineImage(0, img.getBlob());

    openDoc.saveAndClose();
    ...   
}

What this code does is:

  • Localize the named value correponding to the uploaded image URL
  • Obtain the image blob from the URL by opening it with DriveApp
  • Find in your template the placeholder reserved for the image
  • Replace the text by an empty string
  • Retrieve the element that contains the placeholder
  • Get the element's parent paragraph
  • Insert the image blob into the parent paragraph

In other words, a text placeholder gets replaced by an image.

  • Related