Google App脚本 - 将电子表格保存为Google云端硬盘保存的PDF格式

时间:2017-04-19 19:31:37

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

我正在尝试将我的电子表格中的所有工作表保存为google驱动器作为一个PDF(最终我也想让他们发送电子邮件)。我在保存超过其中一张床单时遇到了麻烦。我尝试了多种方式。下面的代码是我到目前为止找到的最佳方式。问题是它只将第一页保存为PDF,我无法弄清楚如何绕过删除冗余表。我看到的所有帖子只想保存1页,我有超过24页需要保存为一个PDF。在此先感谢您的帮助!

function PDF() {
  var sheetName = SpreadsheetApp.getActiveSpreadsheet();
  var folderID = "*** Google Drive ID***"; // Folder id to save in a Drive folder.
  var ss = SpreadsheetApp.openByUrl(
     'https://docs.google.com/spreadsheets/d/***Spreadsheet ID***'); 
  var pdfName = "MAR -  " + ss.getRange("A1:A1").getValue(); //Need to set the values to another sheet

  var sourceSpreadsheet = SpreadsheetApp.getActive();
  var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
  var folder = DriveApp.getFolderById(folderID);

  //Copy whole spreadsheet
  var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(sourceSpreadsheet.getId()).makeCopy("tmp_convert_to_pdf", folder))

  //delete redundant sheets
  var sheets = destSpreadsheet.getSheets();
  for (i = 0; i < sheets.length; i++) {
    if (sheets[i].getSheetName() != sheetName){
      destSpreadsheet.deleteSheet(sheets[i]);
    }
  }
  var destSheet = destSpreadsheet.getSheets()[0];

  //repace cell values with text (to avoid broken references) 
  var sourceRange = sourceSheet.getRange(1,1,sourceSheet.getMaxRows(),sourceSheet.getMaxColumns());
  var sourcevalues = sourceRange.getValues();
  var destRange = destSheet.getRange(1, 1, destSheet.getMaxRows(), destSheet.getMaxColumns());
  destRange.setValues(sourcevalues);

  //save to pdf
  var theBlob = destSpreadsheet.getBlob().getAs('application/pdf').setName(pdfName);
  var newFile = folder.createFile(theBlob);

  //Delete the temporary sheet
  DriveApp.getFileById(destSpreadsheet.getId()).setTrashed(true);
}

2 个答案:

答案 0 :(得分:0)

通过使用Drive API,您可以将电子表格转换为包含电子表格中所有工作表的PDF。要使用此功能,请按以下步骤在Google API控制台上启用Drive API。

  1. 在脚本编辑器中,选择Resources&gt;云平台项目

  2. 在对话框底部,点击Google API控制台的链接。

  3. 在控制台中,点击过滤器框并输入API“Drive API”名称的一部分,然后在看到后点击该名称。

  4. 在下一个屏幕上,单击“启用API”。

  5. 关闭开发人员控制台并返回脚本编辑器。在对话框中单击“确定”。

  6. 我准备了一个用于从电子表格创建PDF文件的示例脚本。请将此用于您的脚本。

    脚本:

    var spreadsheetId = "#####";
    var folderId = "#####";
    var outputFilename = "#####";
    
    var url = "https://www.googleapis.com/drive/v3/files/" + spreadsheetId + "/export?mimeType=application/pdf";
    var options = {
        method: "GET",
        headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()},
        muteHttpExceptions: true
    };
    var response = UrlFetchApp.fetch(url, options).getBlob();
    DriveApp.getFolderById(folderId).createFile(response).setName(outputFilename);
    

    关于这个脚本,虽然我确认这个工作正常,如果它在您的环境中不起作用,请告诉我。如果我误解了你的问题,我很抱歉。

    已添加1:

    function PDF() {
      var sheetName = SpreadsheetApp.getActiveSpreadsheet();
      var folderID = "*** Google Drive ID***"; // Folder id to save in a Drive folder.
      var ss = SpreadsheetApp.openByUrl(
         'https://docs.google.com/spreadsheets/d/***Spreadsheet ID***'); 
      var pdfName = "MAR -  " + ss.getRange("A1:A1").getValue(); //Need to set the values to another sheet
    
      var sourceSpreadsheet = SpreadsheetApp.getActive();
      var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
      var folder = DriveApp.getFolderById(folderID);
    
      //Copy whole spreadsheet
      var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(sourceSpreadsheet.getId()).makeCopy("tmp_convert_to_pdf", folder))
    
      //delete redundant sheets
      var sheets = destSpreadsheet.getSheets();
      for (i = 0; i < sheets.length; i++) {
        if (sheets[i].getSheetName() != sheetName){
          destSpreadsheet.deleteSheet(sheets[i]);
        }
      }
      var destSheet = destSpreadsheet.getSheets()[0];
    
      //repace cell values with text (to avoid broken references) 
      var sourceRange = sourceSheet.getRange(1,1,sourceSheet.getMaxRows(),sourceSheet.getMaxColumns());
      var sourcevalues = sourceRange.getValues();
      var destRange = destSheet.getRange(1, 1, destSheet.getMaxRows(), destSheet.getMaxColumns());
      destRange.setValues(sourcevalues);
    
      //save to pdf
    //  var theBlob = destSpreadsheet.getBlob().getAs('application/pdf').setName(pdfName);
    //  var newFile = folder.createFile(theBlob);
    
    
      // A sample script was added here.
      var url = "https://www.googleapis.com/drive/v3/files/" + destSpreadsheet.getId() + "/export?mimeType=application/pdf";
      var options = {
          method: "GET",
          headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()},
          muteHttpExceptions: true
      };
      var response = UrlFetchApp.fetch(url, options).getBlob();
      DriveApp.getFolderById(folderID).createFile(response).setName(pdfName);
    
    
      //Delete the temporary sheet
      DriveApp.getFileById(destSpreadsheet.getId()).setTrashed(true);
    }
    

    已添加2:

    function PDF() {
      var folderID = "*** Google Drive ID***"; // Folder id to save in a Drive folder.
      var ss = SpreadsheetApp.openByUrl(
         'https://docs.google.com/spreadsheets/d/***Spreadsheet ID***'); 
      var pdfName = "MAR -  " + ss.getRange("A1:A1").getValue(); //Need to set the values to another sheet
      var sourceSpreadsheet = SpreadsheetApp.getActive();
      var folder = DriveApp.getFolderById(folderID);
    
      // A sample script was added here.
      var url = "https://www.googleapis.com/drive/v3/files/" + sourceSpreadsheet.getId() + "/export?mimeType=application/pdf";
      var options = {
          method: "GET",
          headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()},
          muteHttpExceptions: true
      };
      var response = UrlFetchApp.fetch(url, options).getBlob();
      DriveApp.getFolderById(folderID).createFile(response).setName(pdfName);
    }
    

答案 1 :(得分:0)

这是从Google工作表创建PDF文件的函数,并且是将新创建的文件移动到您为函数参数指定的ID的文件夹中的函数。

function downloadPDF(fileId, folderId) {
  var file = Drive.Files.get(fileId);
  var url = file.exportLinks[MimeType.PDF];

  var options = {
    headers: {
      Authorization:"Bearer " + ScriptApp.getOAuthToken()
    },
    muteHttpExceptions : true 
  }

  var response = UrlFetchApp.fetch(url, options);
  var status = response.getResponseCode();
  var result = response.getContentText();
  if (status != 200) {
    // Get additional error message info, depending on format
    if (result.toUpperCase().indexOf("<HTML") !== -1) {
      var message = strip_tags(result);
    }
    else if (result.indexOf('errors') != -1) {
      message = JSON.parse(result).error.message;
    }
    throw new Error('Error (' + status + ") " + message );
  }

  var doc = response.getBlob();
  var newFileid = DriveApp.createFile(doc).setName(file.title + '.pdf').getId();
  let id = moveFileTo(newFileid, folderId);
 
  return id;
}


function moveFileTo(sourceId, folderId){
  let file = DriveApp.getFileById(sourceId)
  let blob = file.getBlob();
  let id = DriveApp.getFolderById(folderId).createFile(blob).getId();
      file.setTrashed(true)
      return id;
}