title: Google Apps Script - Create PDf from Spreadsheet produces pdf of Google sign in page
body: <p>Need some help, am somewhat confused!</p>
  
  <p>I have written a google apps script for a spreadsheet, accessed from a custom menu, that should create a pdf of the spreadsheet page, and save it in my google drive. The code executes OK and a pdf is created, but all I get is a pdf of a google sign in page (for sheets). I am the owner of the spreadsheet and the drive folder and working in my Google Apps for Education account. If I try the full url (theurl) in a browser, I get the pdf I am after, so that works OK, so must be something to do with the blob or authorisation, but I can't see why? I must be missing something obvious. I have tried some of the authorisation code blocks I have seen but these just freeze the script. Any help much appreaciated. Tim</p>
  
  <p>See attached for pdf output  <a href="http://tsah.co.uk/tsah/Order-0004---2015-04-06-1227.pdf" rel="nofollow">Order</a></p>
  
  <p>Here is my code:</p>
  
  <pre><code>function spreadsheetToPDF(){
  
    var key = '14vZzkfMj9XSk4pgbQc78s1pBmsakHABJk7_MSX6j7xs';  //docid
  
    var index = 0;  //sheet gid / number
  
  
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var ActiveSheet = ss.getSheetByName('Order Form');
  
    var timestamp = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd'-'HHmm");
    var supp_name = ActiveSheet.getRange("C12").getValue();  //supplier
    var plainonum = ActiveSheet.getRange("C5").getValue();  //order number
    var onum = ('0000' + plainonum ).slice(-4);  //sets leading zeros to order number
    var description = ActiveSheet.getRange("C18").getValue();  //description
  
    var name = 'Order-' + onum +'-' + supp_name + '-' + description + '-' + timestamp + '.pdf';  //makes pdf filename
  
    SpreadsheetApp.flush();  //ensures everything on spreadsheet is "done"
  
    //make the pdf from the sheet
    var theurl = 'https://docs.google.com/a/mydomain.org/spreadsheets/d/'
    + key 
    + '/export?exportFormat=pdf&amp;format=pdf'
    + '&amp;size=A4'
    + '&amp;portrait=true'
    + '&amp;fitw=true'       // fit to width, false for actual size
    + '&amp;sheetnames=false&amp;printtitle=false&amp;pagenumbers=false'
    + '&amp;gridlines=false'
    + '&amp;fzr=false'      // do not repeat frozen rows on each page
    + '&amp;gid='
    + index;       //the sheet's Id
  
    var docurl = UrlFetchApp.fetch(theurl);
    var pdf = docurl.getBlob().setName(name).getAs('application/pdf');
  
    //save the pdf to the folder on drive
    try {
        folder = DocsList.getFolder('Orders');
      } 
    catch (e) {
         folder = DocsList.createFolder('Orders');
      }
    folder.createFile(pdf);
  
  }
  </code></pre>