Generating a PDF with Node.Js & Express + Cloudinary

Blessing Krofegha
Jan 8 · 6 min read

Hello world!! The need to build a Platform for generating documents on fly such as PDF’s, Excelsheets etc is increasingly on demand, and that’s why this tutorial is made!

Grab a cup of coffee and enjoy the ride!

What we will build?

In this article we are going to create a RESTful API that takes a post request, and our aim will be to store the incoming pdf to Cloudinary, using Node.Js/Express and PDFKit.

We will be using the Model View Controller (MVC) approach and also will be using express.js which is a Nodejs framework that will help us setup the routes easily.

Hence, before you dive into this tutorial, i recommend that you should have a knowledge in Nodejs.

This article will span through three steps:

  • Step One: Creating a sample project, initialization and Installation of all Dependencies for the project
  • Step Two: Setup Server, Express, PdfKit, and Cloudinary.
  • Step Three: Create Controllers and Route.

Getting Started

Before you continue, install the following on your system if you don’t already have

Project Setup

  • Create a new project directory on your system, you can call itpdfGenerator
  • Change working directly to the project and run npm init on your terminal or command prompt if you're using a window system - Running npm init will prompt you with some questions to help set up your project

When that is done, you should see package.json file in your project and it contains basic information about your project.

{"name": "pdfgenerator","version": "1.0.0","description": "pdf generator with nodejs and cloudinary","main": "server.js","scripts": {"test": "echo \"Error: no test specified\" && exit 1"},"author": "Blessing Krofegha","license": "ISC"}

Next, let’s install all the package dependencies that we’ll need to build the project

Installation of all dependencies for the project:

  • expressjs — Expressjs is a nodejs web application framework that gives us the ability to create quick and easy APIs.
  • Pdfkit — PDFKit is a PDF document generation library for Node and the browser that makes creating complex, multi-page, printable documents easy.
  • Cloudinary — Cloudinary is the market leader in providing a comprehensive cloud-based image and video management platform.
  • Body Parser — Parse incoming request bodies in a middleware before your handlers, available under the req.body property.

Run the following command to install all the above packages

$ npm install --save express pdfkit cloudinary body-parser
If all went well, you should see something similar to this

You’ll notice that express and pdfkit, cloudinary and body-parseris under dependencies, that is because those are needed by the time we deploy our code to production.
You should also see a new folder called node_modules in the project root directory - This folder contains the source code of the package we downloaded.

Project Structure

Set up your project structure using the following format

-pdfGenerator
|-package.json
|-.babelrc
|-server.js
|-src
|-controllers
|-pdf.js
|-cloudinary.js
|-routes
|-pdf.js

Server SetUp

Add the following code to server.js

From the code above, we imported express and set up a new express instance const app = express(). We set up a new express.json() middleware - this is needed to get access to request body. Lastly, we set up a sample endpoint to test if the server is working.

Don’t worry, you’re getting the error because nodejs runtime cannot understand some of the ES6 features we used — e.g import. Babel will help us compile the code to ES5 that nodejs runtime can understand. To set up Babel please quickly go through the Tutorial

Set up Cloudinary Controller

To begin with, we would setup our cloudinary controller. Ensure you login into your cloudinary dashborad in other to get access to your api_key and api_secret.

Open controller/cloudinary.js and add the following code

The piece of code above can be explained as follows;

We imported the Cloudinary Package that was earlier installed either through npm or yarn, then we define the Cloudinary cloud_name, api_key and api_secret as given to us by Cloudinary after registeration. To follow best practices you may want to put all config variables in a .env file, that will be fine, but in this tutorial we would focus on the subject matter.

The second part of our cloudinary controller is a standard upload API for uploading PDF files, the api gives us the both the pdf Url and the pdf Id as responses. This off course you may want to send to the client side to foster easy downloads.

Still on the controller folder create a file called pdf.js and add the following codes to controller/pdf.js

In the code above we import fs and path which are Nodejs core module we also import cloud from controller/cloudinary. we went ahead to import PDFkit which is a PDF document generation library for Node and the browser, that makes creating complex, multi-page, printable documents easy.

Furthermore, we defined a name for our pdf, create a folder called data, this folder saves the pdf created on the server on our file systems. We make that possible using Nodejs path module.

Your folder structure should now look like this

We also set the appropriate headers, pipe the document created and pass the pdf created into the text method, and end the process when done using PDFDoc.end() as it were in our case.

Lastly, we need to define our route in our routes folder and ensure that we can now generate the pdf. create a routes folder and make a new file called pdf.js and add the following codes to routes/pdf.js

Now move over to server.js and update the file, if you update the file it should look like this

pat yourself at the back, if you have gotten thus far!

Now lets test our Api using Postman.

Lets now check our data/pdf folder to see if the pdf was generated and see if it was uploaded to Cloudinary.

Our pdf uploaded to Cloudinary
pdf in our filesystem and the cloudinary link
That’s the Pdf we generated when we visit the link.

You may want to go a bit advance and add some styles and feel to your pdf, please visit PDFKit documentation for more info.

Thanks for reading, if you enjoyed reading this, please clap, share and don’t forget to follow me on twitter @beveloper.

Thanks

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade