javascriptgoogle-apps-scriptgoogle-drive-apiexport-to-pdf

email Google Doc as PDF attachment


abc@example.comAfter struggling for a while with this I am calling for help from the crowd.

I am trying to attach 2 Google Docs to an email as PDFs. I see many examples in regard to Google Sheets and have successfully been able to email copies of sheets as PDF, but I have not been able to port this over to Docs.

In multiple different scenarios, the PDF attachments are either a copy of my original template Doc or an image capture of "One Account. All of Google" sign in page. When I look at the links that are generated (Logger.log) and use them, a copy of the correct Doc is downloaded.

Below is an example of my scenario in which I am trying to create the email attachments. See function emailDocAsPDF() towards the bottom

Thanks in advance for any guidance on this issue.

function myFunctionUpdated() {

  var testTemplateId = searchDriveFile('Test Template');
  Logger.log('test template id = ' + testTemplateId);

  var fileName = 'Copy of Test Template'
  Logger.log(fileName);

  DriveApp.getFileById(testTemplateId).makeCopy(fileName);

  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var range = ss.getRange(1, 1, 3, 2).getValues();

  var copyNewTemplateId = searchDriveFile(fileName);

  var copyTemplate = DocumentApp.openById(copyNewTemplateId);
  var copyTemplateBody = copyTemplate.getBody().editAsText();

  for (i=0; i<range.length; i++) {
      copyTemplateBody.replaceText(range[i][0], range[i][1]);
  }

  copyTemplate.saveAndClose();

  emailDocAsPDF(fileName)
}


// Searched Google Drive for a file name and returns the file ID.
function searchDriveFile(fileName) {
  var files = DriveApp.searchFiles(
     'title = "'+ fileName +'"');
  while (files.hasNext()) {
    var file = files.next();
    var id = file.getId();
    return id;
  } 
}


// Send document in an email as PDF
function emailDocAsPDF(fileName) {

  var staticDoc = 'FILE-ID';

  var attachmentDoc = UrlFetchApp.fetch("https://docs.google.com/document/d/" + copyTemplateId + "/export?format=pdf");
  Logger.log("https://docs.google.com/document/d/" + copyTemplateId + "/export?format=pdf");

  var attachmentStaticDoc = UrlFetchApp.fetch("https://docs.google.com/document/d/" + staticDoc + "/export?format=pdf");
  Logger.log("https://docs.google.com/document/d/" + staticDoc + "/export?format=pdf");

  var fileBlob = [];

  fileBlob[0] = attachmentDoc.getBlob().getAs('application/pdf');
  fileBlob[1] = attachmentStaticDoc.getBlob().getAs('application/pdf');

  var body = "Bird is the WORD!! <br>" +
    "<a href='http://www.example.com'>Visit Example</a>";

   if (MailApp.getRemainingDailyQuota() > 0) 
    GmailApp.sendEmail("email@example.com", "Test Documents Email", body, {
      htmlBody: body,
      attachments:[fileBlob[0],fileBlob[1]]     
    });

}

EDIT -- Successful Updates with code provided by Sandwich.

// Send document in an email as PDF
function emailDocAsPDF(fileName) {

  var staticDoc = 'FILE-ID';

  var copyTemplateId = searchDriveFile(fileName);

  var blobs = [];

  var doc = DriveApp.getFileById(copyTemplateId);
  blobs[0] = doc.getBlob().getAs('application/pdf').setName('MyAttachment1.pdf');

  var doc = DriveApp.getFileById(staticDoc);
  blobs[1] = doc.getBlob().getAs('application/pdf').setName('MyAttachment2.pdf');

  var zipBlob = Utilities.zip(blobs).setName('Documents.zip');

  var recipient = 'abc@example.com';
  var subject = 'Test Email';
  var body = 'Bird is the WORD';
  MailApp.sendEmail(recipient, subject, body, {attachments: [zipBlob]});
}

Solution

  • To attach any kind of document as a PDF, call getBlob on the file, specify content type as with .getAs('application/pdf') and optionally set a name with setName. That's all:

    var doc = DriveApp.getFileById('ID_HERE');
    var blob = doc.getBlob().getAs('application/pdf').setName('MyAttachment.pdf');
    var recipient = 'user@example.com';
    var subject = 'Email subject';
    var body = 'Text here';
    MailApp.sendEmail(recipient, subject, body, {attachments: [blob]});
    

    You were trying to use "export as PDF via URL query", which is a poorly documented feature that is sometimes useful for Sheets (setting the boundaries of exported region), but is unnecessary for Docs, if it even exists for them. The above method should work for any kind of content stored in Google Drive.

    By the way, it is preferable to use MailApp instead of GmailApp when sending email, because it keeps the level of authorization to what you need: sending emails. With GmailApp, the script is also granted permission to access and delete all of your existing emails, which is unadvisable for scripts composed by trial, error, and copying code from the Internet.