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.