更新后的文档未在Gmail中附加为PDF [英] Updated doc not attaching as PDF in Gmail

查看:63
本文介绍了更新后的文档未在Gmail中附加为PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Google Apps脚本创建doc文件的副本,并将电子表格中的数据保存到新文件中,然后将其作为PDF附件发送到电子邮件中.一切正常,除了pdf文件显示的是源文件中的默认值,而不是更新后的值.

I'm using Google Apps Script to create a copy of a doc file and save data from spreadsheet to the new file, then send it to email as a PDF attachment. Everything is working as it should except the pdf file is showing the default values which was from the source file instead of updated values.

这是我的密码,

var lr = dataSheet.getLastRow();
var dataRange = dataSheet.getRange(lr, 1, 1, 3).getValues();

var firstName = dataRange[0][1];
var lastName = dataRange[0][2];
var email = dataRange[0][3];

var emailText = "Hi "+firstName+",\n\nThank you for signing up.";
var emailSubject = "Test PDF";

var fileTemplate = DriveApp.getFileById("FILE_ID");  // Get Template File Id
var fileCopied = fileTemplate.makeCopy("Doc Copy-"+new Date()).getId();  // Make a copy of the template and get the id of the new file.

var doc = DocumentApp.openById(fileCopied);  // Get destination doc
var dbody = doc.getBody();  // get destination doc's body

// Replace the fields with values from sheet.

dbody.replaceText("First Name", firstName);
dbody.replaceText("Last Name", lastName);
dbody.replaceText("EmailAddress", email);

Utilities.sleep(1000);

// Send Email with PDF attachment
MailApp.sendEmail(email, emailSubject, emailText, {
    attachments: [doc.getAs(MimeType.PDF)]
});

如何在邮件中以PDF附件的形式获取更新的文档?

How can I get the updated doc in the mail as a PDF attachment?

推荐答案

我认为,如果我们将文件"视为斑点",那就可以做到,这就是Google对待Google Docs文件的方式.请参阅此示例,该示例将Google Spreadsheets转换为PDF文件并将其发送.

I think, it can be done if we consider the 'files' as 'blobs', that is how Google treats the Google Docs files. Please see this example which converts and sends Google Spreadsheets as PDF files.

/* Send Spreadsheet in an email as PDF, automatically */
function emailSpreadsheetAsPDF() {

  // Send the PDF of the spreadsheet to this email address
  var email = "amit@labnol.org"; 

  // Subject of email message
  // The date time string can be formatted in your timezone using Utilities.formatDate method
  var subject = "PDF Reports - " + (new Date()).toString(); 

  // Get the currently active spreadsheet URL (link)
  // Or use SpreadsheetApp.openByUrl("<<SPREADSHEET URL>>");
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  // Email Body can  be HTML too with your logo image - see ctrlq.org/html-mail
  var body = "PDF generated using code at ctrlq.org from sheet " + ss.getName(); 

  var url = ss.getUrl();
  url = url.replace(/edit$/,'');

  /* Specify PDF export parameters
  // From: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579
    exportFormat = pdf / csv / xls / xlsx
    gridlines = true / false
    printtitle = true (1) / false (0)
    size = legal / letter/ A4
    fzr (repeat frozen rows) = true / false
    portrait = true (1) / false (0)
    fitw (fit to page width) = true (1) / false (0)
    add gid if to export a particular sheet - 0, 1, 2,..
  */

  var url_ext = 'export?exportFormat=pdf&format=pdf'   // export as pdf
                + '&size=letter'                       // paper size
                + '&portrait=false'                    // orientation, false for landscape
                + '&fitw=true&source=labnol'           // fit to width, false for actual size
                + '&sheetnames=false&printtitle=false' // hide optional headers and footers
                + '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
                + '&fzr=false'                         // do not repeat row headers (frozen rows) on each page
                + '&gid=';                             // the sheet's Id

  var token = ScriptApp.getOAuthToken();
  var sheets = ss.getSheets(); 

  //make an empty array to hold your fetched blobs  
  var blobs = [];

  for (var i=0; i<sheets.length; i++) {

    // Convert individual worksheets to PDF
    var response = UrlFetchApp.fetch(url + url_ext + sheets[i].getSheetId(), {
      headers: {
        'Authorization': 'Bearer ' +  token
      }
    });

    //convert the response to a blob and store in our array
    blobs[i] = response.getBlob().setName(sheets[i].getName() + '.pdf');

  }

  //create new blob that is a zip file containing our blob array
  var zipBlob = Utilities.zip(blobs).setName(ss.getName() + '.zip'); 

  //optional: save the file to the root folder of Google Drive
  DriveApp.createFile(zipBlob);

  // Define the scope
  Logger.log("Storage Space used: " + DriveApp.getStorageUsed());

  // If allowed to send emails, send the email with the PDF attachment
  if (MailApp.getRemainingDailyQuota() > 0) 
     GmailApp.sendEmail(email, subject, body, {attachments:[zipBlob]});

}

此处的更多信息:将Google电子表格转换并通过电子邮件发送为PDF文件

这篇关于更新后的文档未在Gmail中附加为PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆