Print single or multiple files with Print.js and PDF.js

Vipin Sharma
3 min readApr 10, 2022

Ever wondered if we can print almost every format file through our JS code.

Not only just printing, we can also merge multiple pdf files & save them in one single PDF file.

To achieve this task we need two JS libraries:

  1. Print.js: https://printjs.crabbly.com/
  2. PDF.js: https://mozilla.github.io/pdf.js/

First, add both library’s CDN in your index.html file

We will perform printing in different categories:

  1. Print single PDF file
  2. Print Multiple Images
  3. Print HTML Content
  4. Merge different PDF file & save or print as one single PDF file

Print single PDF file

To print single pdf file. We don’t need PDF.js. It can be done with Print.js i.e. we can use global ‘printJS’ method which can accept both pdf file Url or base64 pdf data.

Print single PDF base64 file

Print Multiple Images

Print multiple images with Print.js is very easy. All you need to do is to pass your image file Urls in printable key in array in printJS method

Print Multiple Images

Print HTML Content

For printing HTML content all you need is valid html code and pass it in printJS method

Merge different PDF file & save or print as one single PDF file

Now comes the most interesting part i.e. to merge multiple pdf files and then provide option to either save or print one single file. We need PDF.js here to convert multiple base64 PDF files to multiple base64 PNG files. Iterate all base64 PDF files and continuously add in one variable multiple base64 PNG files.

So far we have all our base64 PNG files. Now only thing left to do is to merge them and save or print them as single PDF file. With the help of PDF.js here i.e. render multiple base64 PNG files in image tag in one HTML file and print it in one single PDF file. Once print popup opens then we can simply either print or save pdf file.

We can check how we can achieve results for all above categories via https://stackblitz.com/edit/js-yp4nmr?file=index.html

So these are one of the few things we can achieve with these two libraries. We can even print Json data or render multiple pages of multiple PDF files independently to convert each page of PDF in PNG and perform action as per requirement. To explore more follow their documentation.

Reference:

  1. Print.js: https://printjs.crabbly.com/
  2. PDF.js: https://mozilla.github.io/pdf.js/

--

--