Generate Pdf Reports/Invoices in MERN Stack App.
Table of contents
To make pdf files sure there are a lot of different ways one can achieve the problem statement Some of the popular ones are pdfmake, pdfkit, and more. but these kinds of libraries don't have that much style control(that is what I believe and ad-hoc design on them is a nightmare.) and I prefer the new way I found we could use some templating engine(ejs, pug, etc…) for this demo I used pug.js. and with that, I have a compiler to compile it down to plain HTML.
This is a sample pug template and for data, you can pass it when compiling, and to compile it and render you can make a route in express backend and return the response as "res.render("view",{data});"
Note: Remember to put this pug file in views and in the root file of your server you have declared the templating engine.
Now to get the view you can go to the express endpoint route you've declared and see if the view is perfect or not. and to test it in a robust environment you can also install the pug-cli compiler and watch the file while testing and designing this was a major feature I had. I simply used the following command. "pug - obj views/data.json views/index.pug -w" while the flags described are (double dash ) - obj for the data that needs to be passed along. and second, being -w as in watch for changes.
Now as we have our template complete and we can move to the front end and in it, I used a library called react-to-print and react-iframe to render the pug view.
for implementation, I used a form for data to send to the backend and process the view, and when I received the response than frontend open up a modal with two elements in it 1. button to trigger print and 2. the iframe with the URL of the view preview previously made in express to render the view. (you can have this view dynamic by receiving some IDs from the backend when you submit your form data). mine looks like this
and for button onclick you can call the hook mentioned in the image and pass on the data required(see docs what can you pass and how can you manipulate). and if everything works fine then viola! you will get a prompt to the print dialog.
Subscribe to my newsletter
Read articles from hrithik prasad directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by