1

I'm fairly new to the world of aumating sheets with scripts and ma still firmly in the 'cobble other peoples code together' phase of writing scripts.

I have a schedule in Google Sheets that display's different department overviews based on the contents of a cell ('B1'). I'm attempting to iterate a list of values through that cell and in each instance export the resulting sheet to pdf.

So far I've got it working, my next hurdle is getting it to export the pdf in landscape rather than portrait. I can see implementations using url export but I'm not confident enough (read keep breaking everything) to implement that in to the script below.

Any help greatly appreciated!

  function PrintPDF(){
  
  var df = DriveApp.getFolderById("folderID");
  var arr = new Array();
  var files = df.getFiles();
  while( files.hasNext() ) {
    var f = files.next();
    arr.push( [ [ f.getId() ] , [ f.getLastUpdated() ] ] );
  }
  arr.sort( sortFunction );

  function sortFunction( a , b ) {
  var aDate = new Date(a[1]);
  var bDate = new Date(b[1]);
  if ( aDate === bDate ) return 0;
  else if ( aDate < bDate ) return 1;
  else return -1;
};
  
  for( var i=0 ; i<arr.length ; i++ )
    DriveApp.getFileById( arr[i][0] ).setTrashed( true );


//Create array of show codes
var Dss = SpreadsheetApp.getActive().getSheetByName('Value Lists')
var Tss = SpreadsheetApp.getActive().getSheetByName('PrintSheet')
var Shows = Dss.getRange('K3:K11').getValues()
var Count = Shows.length
var Code = Tss.getRange('B1')

Logger.log(Count)
Logger.log(Shows)

for (i=0;i<Count;i++){

Code.setValue(Shows[i])
HideBlankRows ()
  const folderName = `foldername`;
  var ss =SpreadsheetApp.getActiveSpreadsheet()
  var name = "Department - "+ss.getRange('B1').getValue()
  Logger.log(name)

  DriveApp.getFoldersByName(folderName)
    .next()
    .createFile(ss
                  .getBlob()
                  .getAs(`application/pdf`)
                  .setName(name)
    );  
}
Code.setValue('')
}

function HideBlankRows() {
  var ss = SpreadsheetApp.getActive();
  var sheets = ss.getSheets(); // array of all sheet objects in ss
  var numSheets = ss.getNumSheets(); // count of sheets
for(sheet in sheets) {
  if(sheets[sheet].getSheetName() == "AA") continue;
//show all the rows
  sheets[sheet].showRows(1, sheets[sheet].getMaxRows());

//get data from column A
  var data = sheets[sheet].getRange('A:A').getValues();
Logger.log(data)
//iterate over all rows
  for(var i=0; i< data.length; i++){
//compare column, if no, then hide row
    if(data[i][0] == 'Yes'){
      sheets[sheet].hideRows(i+1);
  }
 }
 }
}
  • What keeps breaking? - What are you trying to do and what are you getting? Any errors? misformed PDFs? – Rafa Guillermo Jun 07 '21 at 07:30
  • Please include what you have tried doing and what the results were. Any extra information you can provide will help you get a better answer. – Centijo Jun 07 '21 at 17:35

1 Answers1

1

Your code looks a bit cryptic to me. I don't understand why do you need the arr array if you nowhere use it. Etc.

But whatever. Suppose the code works fine and all you need is to save a PDF file with landscape orientation. In this case you need to replace these lines in your code:

  DriveApp.getFoldersByName(folderName)
    .next()
    .createFile(ss
                  .getBlob()
                  .getAs(`application/pdf`)
                  .setName(name)
    );  

With this:

savePDFs(name);

And add at the end of your script the function savePDFs():

function savePDFs(name) {
  SpreadsheetApp.flush();

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();

  var url = ss.getUrl();

  //remove the trailing 'edit' from the url
  url = url.replace(/edit$/, '');

  //additional parameters for exporting the sheet as a pdf
  var url_ext = 'export?exportFormat=pdf&format=pdf' + //export as pdf
    //below parameters are optional...
    '&size=a4' +         //paper size
    '&portrait=false' +  //orientation, false for landscape, true for portrait
    '&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
    '&gid=' + sheet.getSheetId(); //the sheet's Id

  var token = ScriptApp.getOAuthToken();

  var response = UrlFetchApp.fetch(url + url_ext, {
    headers: { 'Authorization': 'Bearer ' + token }
  });

  var blob = response.getBlob().setName(name + '.pdf');

  DriveApp.createFile(blob);
}

This function was taken from here: Change document orientation when exporting to PDF

Yuri Khristich
  • 13,448
  • 2
  • 8
  • 23
  • Thanks! Yes I have to say my script is a mess. I'd been attempting to cobble it togtether like a bit a frankenstein! But your solution has worked perfectly! – Jack Preston Jun 08 '21 at 05:48
  • This is working well with the daily trigger to! I have noticed this created the files in my root drive rather than a defined folder. Am I right in thinking this is inherent to the .createFile() function? – Jack Preston Jun 09 '21 at 23:30
  • Yep. As far as I can remember, new file always go in root folder. You need to move them in another folder with additional step. Something like like this: `var file = DriveApp.createFile(blob); file.moveTo(folder)` https://stackoverflow.com/questions/38808875/moving-files-in-google-drive-using-google-script – Yuri Khristich Jun 10 '21 at 07:45
  • Thanks again Yuri, that's exactly what I needed! – Jack Preston Jun 11 '21 at 01:28