How to generate document with Node.js or Express.js REST API?
Last Updated :
24 Apr, 2025
Generating documents with Node and Express REST API is an important feature in the application development which is helpful in many use cases.
In this article, we will discuss two approaches to generating documents with Node.js or Express.js REST API.
Prerequisites:
Setting up the Project and install dependencies.
Step 1: Create a directory for the project and move to that folder.
mkdir document-generator-app
cd document-generator-app
Step 2: Create a node.js application
npm init -y
Step 3: Install the required dependencies.
npm install express
Project Structure:
Project StructureApproach 1: Document Generation using PdfKit library
To start building documents using PdfKit library, we first need to install PdfKit package.
npm install pdfkit
The updated dependencies in package.json file will look like:
"dependencies": {
"express": "^4.18.2",
"pdfkit": "^0.14.0"
}
Example: Now, write the following code into the index.js file.
JavaScript
// index.js
const express = require('express');
const PDFDocument = require('pdfkit');
const app = express();
const port = 3000;
app.use(express.json());
// Define a route for generating and serving PDF
app.post('/generate-pdf', (req, res) => {
const { content } = req.body;
const stream = res.writeHead(200, {
'content-type': 'application/pdf',
'content-disposition': 'attachment;filename=doc.pdf'
});
// Call the function to build the PDF, providing
// callbacks for data and end events
buildPdf(
(chunk) => stream.write(chunk),
() => stream.end()
);
// Function to build the PDF
function buildPdf(dataCallback, endCallback) {
const doc = new PDFDocument();
doc.on('data', dataCallback);
doc.on('end', endCallback);
doc.fontSize(25).text(content);
doc.end();
}
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Step to run the application:
Step 1: Run the following command in the terminal to start the server.
node index.js
Step 2: Open the Postman app and make a post request with the following route and add the content in the body which you want to print on the pdf.
http://localhost:3000/generate-pdf
{
"content": "This is my first PDF generated with PdfKit"
}
Output:
.jpg)
Approach 2: Document Generation using Puppeteer library:
To have a build-in function of generating pdf from HTML, we can make the use of puppeteer library over the express server. To have the things setup, we first make sure that we have the puppeteer library installed.
you can install puppeteer by opening the terminal and commanding:
npm install puppeteer
The updated dependencies in package.json file will look like:
"dependencies": {
"express": "^4.18.2",
"puppeteer": "^21.6.1"
}
With puppeteer being installed in the system. Paste the following code in index.js file.
JavaScript
//index.js
const express = require('express');
const puppeteer = require('puppeteer')
const app = express();
const port = 3000;
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Define a route for document generation
app.post('/generate-document', async (req, res) => {
try {
const browser = await puppeteer.launch();
const page = await browser.newPage();
// Generate HTML content
const htmlContent =
`<html>
<body>
<h1>${req.body.title}</h1>
<p>${req.body.content}</p>
</body>
</html>`;
await page.setContent(htmlContent, { waitUntil: 'domcontentloaded' });
const pdfBuffer = await page.pdf();
await browser.close();
res.contentType('application/pdf');
res.send(pdfBuffer);
} catch (error) {
console.error('Error generating document:', error);
res.status(500).send('Error generating document');
}
});
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
});
Step to run the application
Step 1: Run the following command in the terminal to start the server.
node index.js
Step 2: Open the Postman app and make a post request with the following route and add the content in the body which you want to print on the pdf.
http://localhost:3000/generate-document
{
"title": "PDF generated with Express + Pippeteer",
"content": "This is my first PDF generated with Pippeteer"
}
Output:

Similar Reads
QR Code Generator Service with Node.js and Express.js
Nowadays, Quick Response (QR) codes have become an integral tool for transferring information quickly and conveniently. This project aims to develop a QR code generation API service using Node.js and Express.js. In addition, it goes further and extends the former by providing more customization opti
5 min read
Build a document generator with Express using REST API
In the digital age, the need for dynamic and automated document generation has become increasingly prevalent. Whether you're creating reports, invoices, or any other type of document, having a reliable system in place can streamline your workflow. In this article, we'll explore how to build a Docume
2 min read
How to Generate or Send JSON Data at the Server Side using Node.js ?
In modern web development, JSON (JavaScript Object Notation) is the most commonly used format for data exchange between a server and a client. Node.js, with its powerful runtime and extensive ecosystem, provides robust tools for generating and sending JSON data on the server side. This guide will wa
3 min read
Filtering MongoDB Documents by ID in Node.js with Express.js
Filtering is a very basic feature that an API must possess to serve data to the client application efficiently. By handling these operations on the server side, we can reduce the amount of processing that has to be done on the client application, thereby increasing its performance. In this article,
4 min read
How to Send Response From Server to Client using Node.js and Express.js ?
In web development, sending responses from the server to the client is a fundamental aspect of building interactive and dynamic applications. Express.js, a popular framework for Node.js, simplifies this process, making it easy to send various types of responses such as HTML, JSON, files, and more. T
4 min read
How to use TypeScript to build Node.js API with Express ?
TypeScript is a powerful version of JavaScript that incorporates static typing and other features, making it easy to build and maintain large applications. Combined with Node.js and Express, TypeScript can enhance your development experience by providing better type safety and tools. This guide will
4 min read
How to generate API documentation using Postman?
Postman is a popular API testing tool that is used to simplify the process of developing and testing APIs (Application Programming Interface). API acts as a bridge between two software applications which enables them to communicate and share data. In this article, you will learn how to generate API
2 min read
How to test API Endpoints with Postman and Express ?
Postman, a popular API development and testing tool allowing developers to interact with APIs. In this guide, we'll explore the basics of testing API endpoints using Postman and Express, providing clear steps and examples.Prerequisites:Basics of Express JS and Node JS.Postman should be installed.Ste
2 min read
How To Make A GET Request using Postman and Express JS
Postman is an API(application programming interface) development tool that helps to build, test and modify APIs. In this tutorial, we will see how To Make A GET Request using Postman and Express JS PrerequisitesNode JSExpress JSPostmanTable of Content What is GET Request?Steps to make a GET Request
3 min read
Document Management System with React and Express.js
This project is a Document Management System (DMS) developed with a combination of NodeJS, ExpressJS for the server side and React for the client side. The system allows users to view, add, and filter documents. The server provides a basic API to retrieve document data, while the React application o
7 min read