How to print pdf without opening the file in Reactjs

Generating pdf and printing the html elements are one of the most complex things mostly in case where you have a large document. In this article we will gonna learn how to use printJS library to print pdf as well as the html elements in Reactjs.

What is Print.js ?

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.

PDF files must be served from the same domain as your app is hosted under. Print.js uses iframe to load files before printing them, therefore, it is limited by the Same Origin Policy. This helps preventing Cross-site scripting (XSS) attacks.

Installation and Usage

Like any other package you can simply install it from npm using below command.

npm install print-js --save

After that import the print function from the library.

import print from 'print-js';

Printing pdf

To print a pdf just pass the path of pdf file.

printJS('docs/printjs.pdf')

In case you have a large pdf you can also show a loading to the user.

printJS({printable:'docs/xx_large_printjs.pdf', type:'pdf', showModal:true})

Printing Html Elements

For printing the html elements you just need to pass the id and the type of printing.

printJS('printJS-form', 'html')

In above example it will gonna print the element with id printJS-form.

If you want to add a custom header then add this header key as well with your custom html as header value.

printJS({ printable: 'printJS-form', type: 'html', header: 'PrintJS - Form Element Selection' })

I hope you have learned something new. Feel free to comment your valuable thoughts.

Checkout full docs here.

How to generate PDF from DOM elements in React

Categories: Reactjs

1 Comment

How to make custom tooltip component in React - Blog React · November 5, 2020 at 3:51 am

[…] How to print pdf without opening the file in Reactjs […]

Comments are closed.