如何根据特定单元格值在Google云端硬盘中生成PDF

时间:2015-04-10 06:43:07

标签: google-apps-script google-sheets pdf-generation

我一直在尝试创建一个脚本,以便根据Google电子表格中的特定值生成PDF。电子表格由另一个电子表格填充,该电子表格填写在Google表单中。

以下是包含要在PDF上显示的数据的[电子表格]。1

每当电子表格中的信息从表单更新时,我想自动生成PDF。

如果该行符合以下条件,PDF将显示每行的两条信息。如果“需要的数量”中的整数大于或等于0,我希望PDF显示项目名称,然后显示该行所需的数量的整数。循环将继续,直到它到达最后一个项目。

我试图确定查询是否最适合完成此操作,或者将数据放入数组中是否更好。

我有以下代码来生成PDF:



function savePDFs() {
  SpreadsheetApp.flush();
  
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  
  var url = ss.getUrl();
  
  //remove the trailing 'edit' from the url
  url = url.replace(/edit$/,'');
  
  //additional parameters for exporting the sheet as a pdf
  var url_ext = 'export?exportFormat=pdf&format=pdf' + //export as pdf
  //below parameters are optional...
  '&size=letter' + //paper size
  '&portrait=true' + //orientation, false for landscape
  '&fitw=true' + //fit to width, false for actual size
  '&sheetnames=false&printtitle=false&pagenumbers=false' + //hide optional headers and footers
  '&gridlines=false' + //hide gridlines
  '&fzr=false' + //do not repeat row headers (frozen rows) on each page
  '&gid=' + sheet.getSheetId(); //the sheet's Id
  
  var token = ScriptApp.getOAuthToken();

  var response = UrlFetchApp.fetch(url + url_ext, {
      headers: {
        'Authorization': 'Bearer ' +  token
      }
    });
    
  var blob = response.getBlob().setName(sheet.getName() + '.pdf');

  //from here you should be able to use and manipulate the blob to send and email or create a file per usual.
  //In this example, I save the pdf to drive
  
  DocsList.createFile(blob);
  //OR DriveApp.createFile(blob);
}




我很难理解如何实际创建脚本来执行查询或数组,然后将这些结果打印到PDF。

非常感谢。

1 个答案:

答案 0 :(得分:1)

此代码将为您完成(有一个演示和更多信息here):

// Replace this with ID of your template document.
var TEMPLATE_ID = '';

// var TEMPLATE_ID = '1wtGEp27HNEVwImeh2as7bRNw-tO4HkwPGcAsTrSNTPc'; // Demo template
// Demo script - http://bit.ly/createPDF

/**
 * Eventhandler for spreadsheet opening - add a menu.
 */

function onOpen() {

  SpreadsheetApp
    .getUi()
    .createMenu('Create PDF')
    .addItem('Create PDF', 'createPdf')
    .addToUi();

} // onOpen()

/**  
 * Take the fields from the active row in the active sheet
 * and, using a Google Doc template, create a PDF doc with these
 * fields replacing the keys in the template. The keys are identified
 * by having a % either side, e.g. %Name%.
 *
 * @return {Object} the completed PDF file
 */

function createPdf() {

  if (TEMPLATE_ID === '') {

    SpreadsheetApp.getUi().alert('TEMPLATE_ID needs to be defined in code.gs');
    return;
  }

  // Set up the docs and the spreadsheet access

  var copyFile = DriveApp.getFileById(TEMPLATE_ID).makeCopy(),
      copyId = copyFile.getId(),
      copyDoc = DocumentApp.openById(copyId),
      copyBody = copyDoc.getBody(),
      activeSheet = SpreadsheetApp.getActiveSheet(),
      numberOfColumns = activeSheet.getLastColumn(),
      activeRowIndex = activeSheet.getActiveRange().getRowIndex(),
      activeRow = activeSheet.getRange(activeRowIndex, 1, 1, numberOfColumns).getValues(),
      headerRow = activeSheet.getRange(1, 1, 1, numberOfColumns).getValues(),
      columnIndex = 0,
      pdfFile;

  // Replace the keys with the spreadsheet values

  for (;columnIndex < headerRow[0].length; columnIndex++) {

    copyBody.replaceText('%' + headerRow[0][columnIndex] + '%', 
                         activeRow[0][columnIndex]);                         
  }

  // Create the PDF file and delete the doc copy

  copyDoc.saveAndClose();

  pdfFile = DriveApp.createFile(copyFile.getAs("application/pdf"));  

  copyFile.setTrashed(true);

  return pdfFile;

} // createPdf()