How to create a PDF file in Node.js

Today we will show you how to create a PDF file in Node.js. In this article, we will show you two different methods for PDF creation.

The first approach creates a PDF file and saves it in the folder, whereas the second way creates a PDF file and sends it to the API response.

Steps to create a PDF file in Node.js

  1. Setup node project using express
  2. Install the package
  3. Generate a PDF and store it in folder
  4. Create a PDF and send it to the response
  5. Output

1. Setup node project using express

To construct a REST API, we’ll use the express framework in Node.js. If you don’t know how to design a REST API in Node.js using the express framework, please see the link below.

Create REST API in Node.js

server.js

2. Install the package

Here, we will use the PDFKit npm package to create a PDF. Run the following command to install the package.

3. Generate a PDF and store it in folder

Make sure you have an image file named sample.jpg in the upload folder before use the following code.

4. Create a PDF and send it to the response

In this method, we will create a PDF and just have to pipe res to the document instance.

5. Output

Let’s combine all the code together and see how it looks.

server.js

Run the following command and hit two different end points (http://localhost:4000/generate-pdf & http://localhost:4000/view-pdf) in the browser to create a PDF file.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂

Demo & Source Code

GitHub Repository
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *