8

I am trying to create a script in Google Sheets that select a range and print it. I am trying to print some information based on some parameters. I have the following script that sets the desired range, but I do not see a way to print it using script.

function printInvoice() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var range = sheet.getRange("A1:H46");

  range.activate();
}

Any suggestions? Thanks!

carlesgg97
  • 4,184
  • 1
  • 8
  • 24
relez
  • 750
  • 2
  • 13
  • 28

1 Answers1

12

You can use the following script:

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': true,        // 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() - 1,
    'r2': range.getRow() + range.getHeight() - 1
  });
  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('');
}

You will also need to create an html file in your project (File>New>HTML File) with the name js, and paste in the following code:

<script>
  window.open('<?=url?>', '_blank', 'width=800, height=600');
  google.script.host.close();
</script>

This will create a button in your Sheets menu that will open a PDF with the selected range. You can modify some settings such as the print orientation, its size, or whether to show the gridlines or not on top of the script. If you still want to automatically print the ranges without having to manually go through the print dialog, you can either:

carlesgg97
  • 4,184
  • 1
  • 8
  • 24
  • 2
    Thank you for the anwser. How would you go about printing a custom size paper? – user2375263 Mar 06 '21 at 21:27
  • Google Cloud Print is not supported as of December 31, 2020. Also, the “Save to Drive” option isn't available for Windows, MacOS, and Linux devices but you can save documents to Google Drive from print preview. In terms of an equivalent to Cloud Print, Google suggests "printing with a printing partner", such as Directprint.io, LRS, NT-ware, PaperCut, Pharos, PrinterLogic, Printix, Y Soft. [Doc ref](https://support.google.com/chrome/a/answer/9633006#zippy=%2Cprinting-partners) – Tedinoz Nov 08 '21 at 22:00
  • I stumbled on your code quite by chance and have been trying it out but it falls over at the line in your sample `var htmlTemplate = HtmlService.createTemplateFromFile('js');` where the service cannot find 'js'. Afraid I do not understand what an html template is anyway - are you able to explain? –  Nov 05 '19 at 12:07
  • Hey Mervyn, thanks for your contribution. I just realised that my code was missing this `js` part as you properly described - so I edited the question. Hopefully that works for you now! :) Regarding the HTML Templates, it allows you to create a HTML skeleton and insert variables and expressions through placeholders. You can read more about this feature [here](https://developers.google.com/apps-script/guides/html/templates). – carlesgg97 Nov 15 '19 at 09:19