The Printjs library is awesome

The first point to make is this library is / was / will be a life saver when it comes to printing from the web. “But why?” you ask? Well, for me, it was the ability to preview a PDF report and print this directly to a locally installed printer without having to download the file first (a pain for end users).

Take a look at their site and try the demos https://printjs.crabbly.com/

But there are other ways to do this?

That there might be, but can you beat this for a flow?

  • include print-js using yarn/npm
  • import this into your component
  • use it in a single line of code

My use case

The almost part here is because by default printjs expects to be given the path of a PDF file that it will handle for you and open the print dialogue, but this wasn’t going to cut it for my project. The PDF I needed access to requires an Authorization header setting in order to get at the resource so I needed to download the file, then blob the response, and get a URL for the blob resource in order for printjs to handle the file, which it did extremely easily.

All of this fits into a small code snippet:

const res = await fetch(u, {
	credentials: "include",
	headers: {
		Authorization: `Basic ${window.config.reportAuth}`,
	},
});
if (!res.ok) {
	// do something with the error
}
const blob = await res.blob();
const uri = URL.createObjectURL(blob);
print({ printable: uri, type: "pdf" });
URL.revokeObjectURL(uri);

That’s it, I can download my resource with whatever authentication method I need, get a URL for the blob response, use it to print the file, then revoke the URL. Always ensure to revoke the URL once done with it as this will continue to hold memory whilst the page is active, not a problem for a few files but can soon build up.

The example here uses basic auth but it could be anything specific to your use case. In my case basic auth was an ok fit as the report is generated via SSRS and is only accessible internally using TLS, eventually this will be migrated to Azure AD and will use Kerberos, but that’s for another blog post :)

Closing remarks

The printjs library was a doddle to implement and it really did save the day for me. It also ships with the ability to print JSON data directly as a table, and to print a div element by id directly to the printer. Even printing a higher resolution image than the one displayed on your site. Very handy features with many of use cases.