google-sheetsgoogle-apps-scriptgoogle-drive-apipdf-generation

exporting spreadsheet to pdf then saving the file in google drive


I'm having problems saving to google drive after printing a google spreadsheet to pdf. If i just put the "printurl" string into a browser, it will automatically give me the file. But I want it to be saved to google drive automatically. I've tried this code by borrowing code from other posts that emails a spreadsheet as PDF. But this produces a pdf that is unable to be opened. What am I doing wrong?

function printpdf() {
var spreadsheet_id="0Aiy1DTQRndx6dDRidXoxNzlXZFhxd2FITTlBbnUybnc";
var settings = '&fitw=true&portrait=false&exportFormat=pdf&gid=0&gridlines=false';
var printurl = 'https://spreadsheets.google.com/feeds/download/spreadsheets/Export?   key=' + spreadsheet_id + settings;
var result=UrlFetchApp.fetch(printurl);
var content=result.getContent();
var file=DocsList.createFile("temp",content,"application/pdf");
}

Here is an update to this question under the new oauth2 format.

Printing spreadsheet to PDF then saving file in Drive using OAuth2


Solution

  • You can do it in a much simpler fashion

    function printpdf(){
    
      var spreadsheet_id="0Aiy1DTQRndx6dDRidXoxNzlXZFhxd2FITTlBbnUybnc";
      var spreadsheetFile = DocsList.getFileById(spreadsheet_id); 
      var blob = spreadsheetFile.getAs('application/pdf'); 
      DocsList.createFile(blob);
    }
    

    Note that the DocsList.createFile(blob) works only with Google Apps accounts.