google-sheetsgoogle-apps-scriptpdf-generation

How to adjust as custom size margins and paper size in script to save google spreadsheet in PDF?


I have a script that saves my spreadsheet in pdf, but I can't edit the margins and paper size I want.


function Testando() {
  var spreadsheet = SpreadsheetApp.getActive();

SpreadsheetApp.flush();
      //make pdf
      var theurl = 'https://docs.google.com/a/mydomain.org/spreadsheets/d/'
      + 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'  //the file ID
      + '/export?exportFormat=pdf&format=pdf'
      + '&size=LETTER'
      + '&portrait=true'
      + '&fitw=true'       
      + '&top_margin=0.50'              
      + '&bottom_margin=0.50'          
      + '&left_margin=0.50'             
      + '&right_margin=0.50'           
      + '&sheetnames=false&printtitle=false'
      + '&pagenum=false'
      + '&gridlines=false'
      + '&fzr=FALSE'      
      + '&gid='
      + 'XXXXXXXXXXXXXXXXXXXXXX';       //the sheet's Id

      var token = ScriptApp.getOAuthToken();

      var docurl = UrlFetchApp.fetch(theurl, { headers: { 'Authorization': 'Bearer ' +  token } });
      var fileid = DriveApp.createFile(docurl.getBlob()).setName('Teste.pdf').getId();

      var pdf = docurl.getBlob().setName('Teste.pdf');
    //  var pdf = docurl.getBlob().getAs('application/pdf').setName('testss.pdf'); 
     var filetodel = DriveApp.getFileById(fileid);
     DriveApp.getRootFolder().createFolder("Teste");  //comment if folder exists
     // if folder exists use next 
  if (DriveApp.getFoldersByName("Teste").hasNext()){
    var folder = DriveApp.getFoldersByName("Teste").next();
    filetodel.makeCopy(folder);
   }
   DriveApp.removeFile(filetodel);
}

I need the PDF to have the custom paper size for → Height: 38 centimeters and Width: 40 centimeters

Page orientation → Landscape

Scale → Fit Width

Margins → Custom Numbers: 0 Left, 0 Right, 0 Start and 0 End.

Could someone help me please?


Solution

  • '&size=AxB' //A = Width you gonna use (inch); B = Height you gonna use (inch) //Don't use mayus and space. Put both together with the "x" Example: '&size=2.8363636363x5.9055118110' equivalent to 7.2cm and 15cm