Getting started with chrome.printing API

Send a print job

Task 4

20 minutes

In the previous step, you created a button for each printer within the printers table. Now, you need to add a function in printers.js to handle print button click events.

The following code will:

Copy the following code into printers.js:

function onPrintButtonClicked(printerId, dpi, performTrim) {
  let ticket = {
    version: '1.0',
    print: {
      color: { type: 'STANDARD_MONOCHROME' },
      duplex: { type: 'NO_DUPLEX' },
      page_orientation: { type: 'LANDSCAPE' },
      copies: { copies: 1 },
      dpi: {
        horizontal_dpi: dpi.horizontal_dpi,
        vertical_dpi: dpi.vertical_dpi
      },
      collate: { collate: false },
      media_size: {
        width_microns: 72320,
        /* Note that this value needs to be between min_height_microns and
        max_height_microns.  Usually this matches the height of the document
        being printed. */
        height_microns: 110000
      },
      vendor_ticket_item: [{ id: 'finishings', value: 'trim' }]
    }
  };

  filename = 'test-rollprinting.pdf';
  fetch(filename)
    .then((response) => response.arrayBuffer())
    .then((arrayBuffer) => {
      const request = {
        job: {
          printerId: printerId,
          title: 'test job',
          ticket: ticket,
          contentType: 'application/pdf',
          document: new Blob([new Uint8Array(arrayBuffer)], {
            type: 'application/pdf'
          })
        }
      };
      chrome.printing.submitJob(request).then((response) => {
        if (response !== undefined) {
          console.log(response.status);
        }
        if (chrome.runtime.lastError !== undefined) {
          console.log(chrome.runtime.lastError.message);
        }
        window.scrollTo(0, document.body.scrollHeight);
      });
    });
}

When submitting a print job, a dialog box will ask the user to confirm printing. In some cases, you will want to bypass this dialog box (e.g. users cannot confirm a dialog on a self-service Kiosk machine).

Bypassing the dialog box confirmation requires that the ChromeOS device be a managed device. Further, you must configure the PrintingAPIExtensionsAllowList policy in Google Enterprise Admin Console.

Note: We are using a pre-generated PDF file to print a receipt. To print to a regular paper size, you can replace the media_size with another option exposed in the printer capabilities:

json
ticket.print.media_size = {
  width_microns: 210000,
  height_microns: 297000,
  vendor_id: 'iso_a4_210x297mm'
};

Your turn