Export (or print) with a google script new version of google spreadsheets to pdf file, using pdf options

后端 未结 3 942
悲&欢浪女
悲&欢浪女 2020-11-27 18:54

I\'m trying to make a google script for exporting (or printing) a new version of google spreadsheet (or sheet) to pdf, with page parameters (portrait/landscape, ...)

相关标签:
3条回答
  • 2020-11-27 19:18

    Thank you!

    Variant 2 works with me with options:

    var requestData = {
      "oAuthServiceName": "spreadsheets",
      "oAuthUseToken": "always"
    };
    

    Then:

    var ssID = ss.getId();
    var sID = ss.getSheetByName(name).getSheetId();
    
    //creating pdf  
    var pdf = UrlFetchApp.fetch("https://docs.google.com/spreadsheets/d/" + ssID + "/export?gid=" + sID + "&portrait=false&size=A4&format=pdf", requestData).getBlob();
    
    //folder to created pdf in
    var folder = DriveApp.getFolderById(id);
    
    //creating pdf in this folder with given name
    folder.createFile(pdf).setName(name);

    I can change image size, orientation etc. with listed parameters perfectly.

    0 讨论(0)
  • 2020-11-27 19:30

    (Copied from this answer.)

    This function is an adaptation of a script provided by "ianshedd..." here.

    It:

    • Generates PDFs of ALL sheets in a spreadsheet, and stores them in the same folder containing the spreadsheet. (It assumes there's just one folder doing that, although Drive does allow multiple containment.)
    • Names pdf files with Spreadsheet & Sheet names.
    • Uses the Drive service (DocsList is deprecated.)
    • Can use an optional Spreadsheet ID to operate on any sheet. By default, it expects to work on the "active spreadsheet" containing the script.
    • Needs only "normal" authorization to operate; no need to activate advanced services or fiddle with oAuthConfig.

    With a bit of research and effort, you could hook up to an online PDF Merge API, to generate a single PDF file. Barring that, and until Google provides a way to export all sheets in one PDF, you're stuck with separate files.

    Script:

    /**
     * Export one or all sheets in a spreadsheet as PDF files on user's Google Drive,
     * in same folder that contained original spreadsheet.
     *
     * Adapted from https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579#c25
     *
     * @param {String}  optSSId       (optional) ID of spreadsheet to export.
     *                                If not provided, script assumes it is
     *                                sheet-bound and opens the active spreadsheet.
     * @param {String}  optSheetId    (optional) ID of single sheet to export.
     *                                If not provided, all sheets will export.
     */
    function savePDFs( optSSId, optSheetId ) {
    
      // If a sheet ID was provided, open that sheet, otherwise assume script is
      // sheet-bound, and open the active spreadsheet.
      var ss = (optSSId) ? SpreadsheetApp.openById(optSSId) : SpreadsheetApp.getActiveSpreadsheet();
    
      // Get URL of spreadsheet, and remove the trailing 'edit'
      var url = ss.getUrl().replace(/edit$/,'');
    
      // Get folder containing spreadsheet, for later export
      var parents = DriveApp.getFileById(ss.getId()).getParents();
      if (parents.hasNext()) {
        var folder = parents.next();
      }
      else {
        folder = DriveApp.getRootFolder();
      }
    
      // Get array of all sheets in spreadsheet
      var sheets = ss.getSheets();
    
      // Loop through all sheets, generating PDF files.
      for (var i=0; i<sheets.length; i++) {
        var sheet = sheets[i];
    
        // If provided a optSheetId, only save it.
        if (optSheetId && optSheetId !== sheet.getSheetId()) continue; 
    
        //additional parameters for exporting the sheet as a pdf
        var url_ext = 'export?exportFormat=pdf&format=pdf'   //export as pdf
            + '&gid=' + sheet.getSheetId()   //the sheet's Id
            // following 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
    
        var options = {
          headers: {
            'Authorization': 'Bearer ' +  ScriptApp.getOAuthToken()
          }
        }
    
        var response = UrlFetchApp.fetch(url + url_ext, options);
    
        var blob = response.getBlob().setName(ss.getName() + ' - ' + 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
        folder.createFile(blob);
      }
    }
    
    0 讨论(0)
  • 2020-11-27 19:31

    Here is my spreadsheet-to-pdf script. It works with the new Google Spreadsheet API.

    // Convert spreadsheet to PDF file.
    function spreadsheetToPDF(id,index,url,name)
    {
      SpreadsheetApp.flush();
    
      //define usefull vars
      var oauthConfig = UrlFetchApp.addOAuthService("google");
      var scope = "https://docs.google.com/feeds/";
    
      //make OAuth connection
      oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
      oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
      oauthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
      oauthConfig.setConsumerKey("anonymous");
      oauthConfig.setConsumerSecret("anonymous");
    
      //get request
      var request = {
        "method": "GET",
        "oAuthServiceName": "google",
        "oAuthUseToken": "always",
        "muteHttpExceptions": true
      };
    
      //define the params URL to fetch
      var params = '?gid='+index+'&fitw=true&exportFormat=pdf&format=pdf&size=A4&portrait=true&sheetnames=false&printtitle=false&gridlines=false';
    
      //fetching file url
      var blob = UrlFetchApp.fetch("https://docs.google.com/a/"+url+"/spreadsheets/d/"+id+"/export"+params, request);
      blob = blob.getBlob().setName(name);
    
      //return file
      return blob;
    }
    

    I've had to use the "muteHttpExceptions" parameter to know exactly the new URL. With this parameter, I downloaded my file with the HTML extension to get a "Moved permanently" page with my final url ("https://docs.google.com/a/"+url+"/spreadsheets/d/"+id+"/export"+params").

    And note that I am in an organization. So I've had to specify its domain name ("url" parameter, ie "mydomain.com").

    0 讨论(0)
提交回复
热议问题