True Worth

Many of us are still looking for a sense of worth, love, identity and validation in all the wrong places. We rely on our possessions, job titles, labels and even love, approval and praise from others…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




How to Generate Dynamic PDFs Using React and NodeJS

Finished Product

In this article, you will learn how to generate dynamic PDFs using HTML code as a template.

For this particular example, we are going to create a simple receipt that will have dynamic data coming from React’s state object.

Generate PDFs using Java

Along with writing this article, I have also created a YouTube video!
You can follow along and code while watching. I advise you to first glance over the article, code along with the video and then read the article.

The client side of this project for generating dynamic PDFs is going to be straight forward.

First import the dependencies:

At the top, initialize the state:

Delete the JSX that create-react-app generated for us and paste the following
these few inputs with a button that will submit values to the state:

Create the handleChange method that is going to update the state of our input fields:

Now that this is done we can finally move on to generating PDFs.

Inside of createAndDownloadPdf we will create a post request that will send the data to our server:

Before we move any further with the client side, we need to set up the routes on the backend. We can provide them with the necessary information, generate PDFs and finally request generated PDFs back to the client.

The client side of this project for generating dynamic PDFs is going to include only two routes. One for generating PDFs. One for sending them back.

First import all the necessary dependencies:

Initialize app using express and set up the port:

Setup body parser so we can parse incoming request bodies available under the req.body property. Setup cors so we don’t get blocked by cross-origin: Cross-Origin Request Blocked.

Finally:

Now we can start creating the logic behind PDF creation.

We need to create the HTML template for our PDF file. The possibilities are endless. Everything that you can create with pure HTML and CSS can be represented as PDF. So let’s create a new directory with index.js inside of it:

Inside of index.js we will simply export one arrow function that is going to return all of the HTML code. In here we can use the parameters we will pass in when we actually call this function.

In the end, don’t forget to require it inside of server/index.js:

We are going to have two routes:
POST route is going to fetch the data and generate a PDF.
GET route is going to send the generated PDF to the client.

Inside of this /create-pdf post route we are using to usepdf.create() that we imported from the module html-pdf.

Then, as the first parameter to the pdf.create method, we will pass the template along with all the information coming from the client inside of req.body.

Immediately after, we call another method, toFile() and pass the desired name of our pdf document, as well as a callback arrow function that will return Promise.reject() if it encounters an error, or Promise.resolve() if everything finishes smoothly.

While we’re here, we can also create a get request that will be called after the previous one finishes. In here we will simply retrieve the document and send it to the client using res.sendFile().

Finally, we can get back to the client and use axios to make those requests:

After we make a post request, our PDF will be generated and we need to call get request that will send the file to the client.

We chain .then()onto our axios.post() request.
We can do that since we returned either resolved or rejected promise.

Above, we can see the use of responseType that is equal to blob, before we move any further, we need to explain what blobs are.

One sentence explanation of what blobs are without any technical terms that I could come up with: Blobs are immutable objects that represent raw data.

They are often used for representing data that isn’t necessarily in a JavaScript format. A blob object represents a chunk of bytes that hold the data of a file.
Although it may seem like blob is a reference to an actual file, it is not.

Blobs allow you to construct file-like objects on the client that you can pass to API’s that expect URLs instead of requiring the server to provide the files.

Now that we know what blobs are we can move on and actually create one, which will be a representation of our PDF file.

Know that we know what blobs are, we can chain one last .then(res) along with the response to the previous one like this:

Finally, we can create a blob using Blob constructor:

Here we simply create a pdfBlob, by passing res.data that is coming from our server and we set the type to application/pdf.

After we have created a blob, we can use saveAs(), that we imported from file-saver module to download the newly generated PDF.

saveAs takes in the newly created pdfBlob as the first parameter, and name of the file as the second one:

microverse.org

Add a comment

Related posts:

The Pillars of Management

Often when coaching managers, I’m asked about prioritization and focus. For newer managers, it can be difficult to understand all the aspects of your new role. Where do you put your time? What skills…

The question of confidence in writing

Confidence. Whether you’re aware or not, confidence or lack of it plays a significant role in your writing at work. From my experience, this is true across all demographics, and I don’t care how…

Should you want to rank your website with guest posting or Link building?

Guest posting is one of the important things to help you get some authority and traffic. If you want to share the content on someone else’s blog. You should know the qualification of the sites before…