【问题标题】:Google Apps Script: Send PDF instead of .zip file in emailGoogle Apps 脚本:在电子邮件中发送 PDF 而不是 .zip 文件
【发布时间】:2021-01-21 20:23:42
【问题描述】:

我有这段代码可以从 Google 电子表格生成 PDF 文件并将其作为电子邮件附件发送。问题是它使用const zipBlob = Utilities.zip(blobs).setName('${ss.getName()}.zip'); 压缩文件。

我想更改它,使附件是 PDF 而不是 .zip 文件。

/* Send Spreadsheet in an email as PDF, automatically */
function emailSpreadsheetAsPDF() {
  // Send the PDF of the spreadsheet to this email address
  const email = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Árajánlat - EKOL Hungary').getRange('E3').getValue().toString();

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

  // Subject of email message
  const subject = `EKOL Hungary - ${ss.getName()}`;

  // Email Body can  be HTML too with your logo image - see ctrlq.org/html-mail
  const body = "Ide majd kell valami szöveg";

  // Base URL
  const url = 'https://docs.google.com/spreadsheets/d/SS_ID/export?'.replace('SS_ID', ss.getId());

  const exportOptions =
    'exportFormat=pdf&format=pdf' + // export as pdf / csv / xls / xlsx
    '&size=A4' + // paper size legal / letter / A4
    '&portrait=true' + // orientation, false for landscape
    '&fitw=true&source=labnol' + // fit to page 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

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

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

  for (let i = 0; i < sheets.length; i += 1) {
    // Convert individual worksheets to PDF
    const response = UrlFetchApp.fetch(url + exportOptions + 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
  const zipBlob = Utilities.zip(blobs).setName(`${ss.getName()}.zip`);

  // 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, {
      htmlBody: body,
      attachments: [zipBlob]
    });
}

我也尝试过这种方式,但它发送的 PDF 已损坏。

function emailSpreadsheetAsPDF() {
  const sheetToPrint = "Árajánlat - EKOL Hungary"; // name of the sheet to print
  const ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1XTJF_-qYFvE4IVkA77YsOg3yfO_PX46z8z0_AtYg_Go/edit#gid=0");
  const ssID = ss.getId();
  const email = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Árajánlat - EKOL Hungary').getRange('E3').getValue().toString();
  const subject = `EKOL Hungary - ${ss.getName()}`;
  const body = "Kicsit szépítettem rajta. Viszont, ide majd kéne valami szöveg. Mi legyen?";
  const shID = ss.getSheetByName(sheetToPrint).getSheetId();
  const url = 'https://docs.google.com/spreadsheets/d/SS_ID/export?'.replace('SS_ID', ss.getId());
  const exportOptions =
    '&size=A4'+
    '&portrait=true'+
    '&fitw=true'+
    '&sheetnames=false&printtitle=false'+
    '&pagenumbers=false&gridlines=false'+
    '&fzr=false'+
    '&gid='+shID; 
  var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
  
  var response = UrlFetchApp.fetch(url+exportOptions, params).getBlob();
  
    GmailApp.sendEmail(email, subject, body, {
      htmlBody: body,
      attachments: [{
            fileName: `EKOL Hungary - Árajánlat` + ".pdf",
            content: response.getBytes(),
            mimeType: "application/pdf"
        }]
    });
}

非常感谢您能给我的任何帮助,因为我是编码新手。

【问题讨论】:

标签: email pdf google-apps-script google-sheets spreadsheet


【解决方案1】:

不要使用UrlFetchApp,而是使用ss.getAs('application/pdf') (See here)

function emailSpreadsheetAsPDF() {
  // Send the PDF of the spreadsheet to this email address
  var email = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Árajánlat - EKOL Hungary').getRange('E3').getValue().toString();

  // Get the currently active spreadsheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  // Subject of email message
  const subject = `EKOL Hungary - ${ss.getName()}`;

  // Get blob
  var blob = ss.getAs('application/pdf');

  // Send email
  GmailApp.sendEmail(email, subject, body, {
    htmlBody: body,
    attachments: [blob]
  });

【讨论】:

  • 非常感谢您的回答,它仅适用于发送 PDF。虽然这样我不能添加 exportOptions 来删除网格线并将 PDF 格式化为 A4 大小。你对如何做到这两点有什么建议吗?
【解决方案2】:

经过多次尝试,下面的代码成功了。

// Generate a PDF file from a Google spreadsheet and send it to a specified email address
function emailSpreadsheetAsPDF() {
  const sheetToPrint = "Árajánlat - EKOL Hungary"; // name of the sheet to print
  const ss = SpreadsheetApp.getActiveSpreadsheet(); // the sheets to use
  const email = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Árajánlat - EKOL Hungary').getRange('E3').getValue().toString(); // grab the email address from the specified cell 
  const subject = `EKOL Hungary - ${ss.getName()}`; // the subject of the email
  const body = "Kicsit szépítettem rajta. Viszont, ide majd kéne valami szöveg. Mi legyen?"; // body of the email
  const shID = ss.getSheetByName(sheetToPrint).getSheetId(); // the ID of the sheet
  const url = 'https://docs.google.com/spreadsheets/d/SS_ID/export?'.replace('SS_ID', ss.getId()); // url of the spreadsheet
  const exportOptions =
    'exportFormat=pdf&format=pdf' + // export as pdf / csv / xls / xlsx
    '&size=A4'+ // size of the PDF (legal / A4 / letter)
    '&portrait=true'+ // orientation of the PDF (false for landscape)
    '&fitw=true'+ // fit to page 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='+shID; // the sheet's Id
  var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
  
  // generate the PDF file
  var response = UrlFetchApp.fetch(url+exportOptions, params).getBlob();
  
  // send the email to the specified address with the specified body text and attached PDF file
    GmailApp.sendEmail(email, subject, body, {
      htmlBody: body,
      attachments: [{
            fileName: `EKOL Hungary - ${ss.getName()}` + ".pdf",
            content: response.getBytes(),
            mimeType: "application/pdf"
        }]
    });
}

【讨论】:

  • 您不想将完整的电子表格(所有工作表)添加到您的 PDF 中吗?这只会添加一张纸。
  • 我只需要导出一张工作表,但整个电子表格只有一张。
猜你喜欢
  • 2013-08-15
  • 1970-01-01
  • 2021-11-21
  • 1970-01-01
  • 2020-05-10
  • 2020-12-15
  • 2017-11-01
  • 2016-05-05
  • 2013-08-30
相关资源
最近更新 更多