javascriptformsgoogle-apps-scriptgoogle-sheetsdoc

How do I script a photo from Google Form upload and set its size to 1 inch for display in a template?


I am trying to make an application that requires the applicant's photos to be attached. How do I script a photo from Google Form upload and set its size to 1 inch for display in a template? Thank you so much :) enter image description here

My code

function onFormSubmit(e){
  var fullname = e.values[1];
  var address = e.values[2];
  var phone = e.values[3];
  var email = e.values[4];
  var photo = e.values[5];
  
  var copyId = DriveApp.getFileById('1tO7L1tWbwMvMyfJGCQB2cONOCyai_ZCIYt_VnDBBnBo')
  .makeCopy('Application'+'_2020-'+fullname)
  .getId();

  var copyDoc = DocumentApp.openById(copyId);

  copyDoc.getBody()
  var copyBody = copyDoc.getActiveSection();

  copyBody.replaceText('keyfullName', fullname);
  copyBody.replaceText('keyaddress', address);
  copyBody.replaceText('keyphone', phone);
  copyBody.replaceText('keyemail', email);
  copyBody.replaceText('keyphoto', photo);
  
  copyDoc.saveAndClose();
  
} 


Solution

  • This requires a few pre-steps as you are not replacing text but entering an actual image. You will need to get the image from the id in the url of e.values(5), then find the position of your placeholder text in the doc, add it and format it. As said in the comments, you can only set size by pixels not inch.

    I wrote only the code parts necessary for that and left out your other replacements. There might be cleaner ways to do this, but this one worked for me.

    function onFormSubmit(e) {
      var photo = e.values[5]
      // get the actual image based on the trimmed drive url
      var image = DriveApp.getFileById(photo.replace('https://drive.google.com/open?id=', ''))
      .getBlob();
      
      var copyId = DriveApp.getFileById('1tO7L1tWbwMvMyfJGCQB2cONOCyai_ZCIYt_VnDBBnBo')
      .makeCopy('Application'+'_2020-'+fullname)
      .getId();
    
      // you can get the body in one go
      var copyBody = DocumentApp.openById(copyId).getBody();
    
      // find the position where to add the image
      var position = copyBody.findText('keyphoto').getElement()
      var offset = copyBody.getChildIndex(position.getParent())
      
      // add the image below and resize it
      var insertedImage = copyBody.insertImage(offset +1,image).setHeight(100).setWidth(100)
    
      // align it to the right 
      var styles = {};
      styles[DocumentApp.Attribute.HORIZONTAL_ALIGNMENT] = DocumentApp.HorizontalAlignment.RIGHT;
      insertedImage.getParent().setAttributes(styles)
      
      // remove the keyphoto placeholder text
      position.removeFromParent()
    }
    

    Further resources on the methods: Inserting a Google Drive image into a document using Google Apps Script Google apps script: How to horizontally align an inlineImage