The Easiest Way to Print Documents With Javascript  -  Print.js

A teeny-tiny javascript library that made printing from the web incredibly simple.

Print.js was primarily written to help us print PDF files directly within our apps, without leaving the interface, and no use of embeds. For unique situations where there is no need for users to open or download the PDF files, and instead, they just need to print them. One scenario where this is useful, for example, is when users request to print reports that are generated on the server-side. These reports are sent back as PDF files. There is no need to open these files before printing them. Print.js offers a quick way to print these files within our apps.

1) Download and Install

You can either download the latest version(v1.2.0) of Print.js from the GitHub releases or use one of the two steps given below depending on your package manager.

  • To install using npm:

npm install print-js --save
  • To install using yarn:

yarn add print-js

After installing via npm or yarn, you should import the library into your project, as shown below, prior to starting using it.

import print from 'print-js'

2) Getting Started

  • First, we need to include the Print.js library on the page:

<script src="print.js"></script>
  • If you will use the modal feature, also include Print.css on the page:

<link rel="stylesheet" type="text/css" href="print.css">

That’s it. You can now use Print.js on your pages.

When writing your javascript code, remember that the library occupies a global variable of printJS.

3) Using Print.js

Now, that we have correctly installed and imported the library let’s start using it.

The 4 types of documents you can print using Print.js:

i) PDF (Default)

Its basic usage is to call printJS() and just pass in a PDF document URL:

printJS('docs/PrintJS.pdf')

ii) HTML

To print HTML elements, in a similar way, pass in the element id and type:

printJS('myElementId', 'html')

iii) IMAGE

For image files, the idea is the same, but you need to pass a second argument:

printJS('images/PrintJS.jpg', 'image')

iv) JSON

When printing JSON data, pass in the data, type, and the data properties that you want to print:

 printJS(  
      {  
          printable: myData,   
          type: 'json',   
          properties: ['prop1', 'prop2', 'prop3']  
      }  
 );  

4) Examples

Enough of the theory, let’s now look at some useful illustrations on how we can use this library to get some good printing work done on our webpage:

1. Print an HTML Form

Print.js accepts an object with arguments. Let’s print an HTML form with a customized heading now :

JS Code

function printForm() {
   printJS({
       printable: 'form1',
       type: 'html',
       targetStyles: ['*'],
       header: 'PrintJS - Print Form With Customized Header'
   })
}

HTML Code

<h3>Contact Form</h3>

<div class="container">
  <form action="#" id="form1">
    <label for="fname">First Name</label>
    <input type="text" id="fname" name="firstname" placeholder="Your name..">

    <label for="lname">Last Name</label>
    <input type="text" id="lname" name="lastname" placeholder="Your last name..">

    <label for="country">Country</label>
    <select id="country" name="country">
      <option value="australia">Australia</option>
      <option value="canada">Canada</option>
      <option value="usa">USA</option>
    </select>

    <label for="subject">Subject</label>
    <textarea id="subject" name="subject" placeholder="Write something.." style="height:200px"></textarea>

    <button type="button" onClick=printForm()>Print Form</button>
  </form>
</div>

Checkout the Complete JSFiddle here.

2. Print Images

To print multiple images together, we can pass an array of images. We can also pass the style to be applied to each image :

JS Code

function printImages() {
  printJS({
    printable:    ['https://cdn.shopify.com/s/files/1/0284/4946/products/IMG_8999_720x.jpg?v=1580507812',  'https://bloomex.ca/components/com_virtuemart/shop_image/produc t/Make-a-Wish-LF102-53.png',  'https://s3.amazonaws.com/cdn.brecksbulbs.ca/images/500/60053.jpg'],
    type: 'image',
    header: 'Multiple Images',
    imageStyle: 'width:50%;margin-bottom:20px;'
  })
}

HTML Code

<button type="button" onClick=printImages()>
  Print Images
</button>

Checkout the Complete JSFiddle here.

3. Print JSON Data

JS Code

 someJSONdata = [
    {
       name: 'John Doe',
       email: 'john@doe.com',
       phone: '111-111-1111'
    },
    {
       name: 'Barry Allen',
       email: 'barry@flash.com',
       phone: '222-222-2222'
    },
    {
       name: 'Cool Dude',
       email: 'cool@dude.com',
       phone: '333-333-3333'
    }
 ]

HTML Code

<button type="button" onclick="printJS({
	    printable: someJSONdata,
            properties: [ 'name', 'email', 'phone' ],
	    type: 'json' })">
  Print JSON
</button>

Checkout the Complete JSFiddle here.

4. Print Styled JSON Data

We can now add custom styles to our data table as well as customize the table header text by sending an object array :

JS Code

 someJSONdata = [
    {
       name: 'John Doe',
       email: 'john@doe.com',
       phone: '111-111-1111'
    },
    {
       name: 'Barry Allen',
       email: 'barry@flash.com',
       phone: '222-222-2222'
    },
    {
       name: 'Cool Dude',
       email: 'cool@dude.com',
       phone: '333-333-3333'
    }
 ]

HTML Code

<button type="button" onclick="printJS({
	    printable: someJSONdata,
            properties: [
                { field: 'name', displayName: 'Full Name'},
                { field: 'email', displayName: 'E-mail'},
                { field: 'phone', displayName: 'Phone'}
	    ],
	    type: 'json',
            gridHeaderStyle: 'color: green;  border: 2px solid #3971A5;',
	    gridStyle: 'border: 2px solid #3971A5;'
  })">
  Print Styled JSON
</button>

Checkout the Complete JSFiddle here.

5. Handle Error while Printing PDF 

You could also handle errors using the onError() method provided by print.js and display them to the users using alerts as shown in the example below:

JS Code

function printPdfError() {
    printJS({
  	printable:  'https://printjs.crabbly.com/notavalidpdfdocument.pdf',
  	type: 'pdf',
        onError: function  (error) {
             alert('Error found => ' + error.message)
        }
    })
}

HTML Code

<h1>
  Print.js Error handling
</h1>

<button id="test1" onclick=printPdfError()>
  Print PDF
</button>

Checkout the Complete JSFiddle here.

5) Browser Compatibility

Since print.js is a fairly new library, therefore, currently, not all library features are working between browsers. However, most of the leading browsers support all of the document types that this amazing library allows us to print. Below are the results of tests done with these major browsers, using their latest versions:

The tests were done using a cross-browser testing tool provided by BrowserStack.

So, that’s it about this useful Javascript library. I hope the information provided in this article provides value to you and helps you simplify and optimize the future printing tasks on your web app.

References: