Sling Academy
Home/Node.js/Node.js + Express: How to Return PDF Files

Node.js + Express: How to Return PDF Files

Last updated: December 30, 2023

Overview

Building web applications with Node.js often requires the ability to deliver content in various formats. One common requirement is returning PDF files to clients, catering to reports, receipts, or other documents. This tutorial will guide you through several methods to accomplish this task using Express.js, the popular web framework for Node.js.

Before diving into the code examples, make sure you have the following installed on your machine:

  • Node.js and npm (Node Package Manager).
  • Express.js, which can be installed via npm.
  • A PDF file to serve in our examples, stored in a known directory.

Serving a Static PDF File

express.static is the simplest middleware to serve static files including PDFs:

import express from 'express';
const app = express();
app.use('/pdf', express.static('path/to/pdf'));
app.listen(3000, () => console.log('Server started on port 3000'));

Sending a PDF File Directly

With the response.sendFile method, you can send a specific PDF file in response to a request:

import express from 'express';
import path from 'path';
const app = express();
app.get('/download-pdf', (req, res) => {
  const filePath = path.join(__dirname, 'your-file.pdf');
  res.sendFile(filePath);
});
app.listen(3000);

Streaming PDF Files

For larger PDFs, streaming is a better approach. This can reduce memory overhead and allow the client to start processing data before the entire file is transmitted:

import fs from 'fs';
import express from 'express';
const app = express();
app.get('/stream-pdf', (req, res) => {
  const filePath = 'path/to/large-file.pdf';
  fs.createReadStream(filePath).pipe(res);
});
app.listen(3000);

Generating and Sending PDFs Dynamically

To create a PDF on-the-fly and send it to the client, we can use libraries like pdfkit:

import PDFDocument from 'pdfkit';
import express from 'express';
const app = express();
app.get('/generate-pdf', (req, res) => {
  const doc = new PDFDocument();
  doc.text('Hello World!', 100, 50);
  res.setHeader('Content-Type', 'application/pdf');
  doc.pipe(res);
  doc.end();
});
app.listen(3000);

Error Handling

It is also important to handle errors properly when dealing with file operations to avoid server crashes:

app.get('/safe-download-pdf', async (req, res) => {
  try {
    const filePath = path.join(__dirname, 'secure-file.pdf');
    res.sendFile(filePath);
  } catch (err) {
    res.status(500).send('Error occurred while downloading the PDF');
  }
});

Conclusion

This tutorial offered a glimpse into various techniques for returning PDF files in a Node.js + Express application. From serving static files to streaming and generating PDFs dynamically, we explored practical examples to handle common use cases. Always consider the most efficient method based on your application’s needs and remember to implement proper error handling to create robust web services.

Next Article: How to generate Excel (xlsx) files using Node.js

Previous Article: Node.js + Express: How to create an XML sitemap

Series: Node.js & Express Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates