Print selected cells across entire workbook

115 views
Skip to first unread message

Kevin IT

unread,
Sep 4, 2022, 9:07:30 PM9/4/22
to Google Apps Script Community
Hey guys,

I am completely new to coding and I need some help. I got a code from somewhere that allows me to print a selected area in google sheet. After spending some time studying the code a bit I manage to set the print area to the range I want on the current spreadsheet. The workbook contains multiple pages of spreadsheets and I'm trying to figure out if it is possible to apply the selected print area across the entire workbook?

I'll post the codes I got online below in case you guys ask.

var PRINT_OPTIONS = {
  'size': 7,               // paper size. 0=letter, 1=tabloid, 2=Legal, 3=statement, 4=executive, 5=folio, 6=A3, 7=A4, 8=A5, 9=B4, 10=B
  'fzr': false,            // repeat row headers
  'portrait': false,        // false=landscape
  'fitw': true,            // fit window or actual size
  'gridlines': false,      // show gridlines
  'printtitle': false,
  'sheetnames': false,
  'pagenum': 'UNDEFINED',  // CENTER = show page numbers / UNDEFINED = do not show
  'attachment': false
}

var PDF_OPTS = objectToQueryString(PRINT_OPTIONS);

function onOpen(e) {
  SpreadsheetApp.getUi().createMenu('Print...').addItem('Print selected range', 'printSelectedRange').addToUi();
}

function printSelectedRange() {
  SpreadsheetApp.flush();
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var range = sheet.getActiveRange();

  var gid = sheet.getSheetId();
  var printRange = objectToQueryString({
    
    'c1': range.getColumn() - 1,
    'r1': range.getRow() - 1,
    'c2': range.getColumn() + range.getWidth() + 3,
    'r2': range.getRow() + range.getHeight() + 47
   
  });

  var url = ss.getUrl().replace(/edit$/, '') + 'export?format=pdf' + PDF_OPTS + printRange + "&gid=" + gid;

  var htmlTemplate = HtmlService.createTemplateFromFile('js');
  htmlTemplate.url = url;
  SpreadsheetApp.getUi().showModalDialog(htmlTemplate.evaluate().setHeight(10).setWidth(100), 'Print range');
}

function objectToQueryString(obj) {
  return Object.keys(obj).map(function(key) {
    return Utilities.formatString('&%s=%s', key, obj[key]);
  }).join('');
}

Andrew Roberts

unread,
Sep 5, 2022, 5:46:29 AM9/5/22
to google-apps-sc...@googlegroups.com
Building on the shoulders of giants (Thanks Spencer), this is all the options I've found for PDF conversion.

--
You received this message because you are subscribed to the Google Groups "Google Apps Script Community" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-apps-script-c...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-apps-script-community/96c27f44-abea-410c-9ee5-29005d61027cn%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages