Node.js
PDF & Excel Export
Generate and stream PDF files with PDFKit, Excel workbooks with ExcelJS, and CSV exports with json2csv directly from an Express response.
PDFKit Install: Install PDFKit for PDF generation in Node.js.
terminal
JS
npm install pdfkit
PDFKit – Stream PDF to Response: Pipe a PDFKit document directly to the HTTP response so the browser triggers a download.
controllers/exportController.js
JS
const PDFDocument = require('pdfkit');
exports.downloadPdf = (req, res) => {
const doc = new PDFDocument({ margin: 40 });
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', 'attachment; filename="report.pdf"');
doc.pipe(res); // stream directly to response
// Title
doc.fontSize(20).text('Monthly Report', { align: 'center' });
doc.moveDown();
// Simple table row
doc.fontSize(12).text('User: John Doe');
doc.text('Date: 2025-06-08');
doc.moveDown();
// Horizontal line
doc.moveTo(40, doc.y).lineTo(560, doc.y).stroke();
doc.moveDown();
doc.text('Total Sales: $4,200');
doc.end(); // finalise and flush
};
PDFKit – Create PDF Buffer: Collect PDF output into a Buffer for saving to disk or uploading to cloud storage.
helpers/pdfHelper.js
JS
const PDFDocument = require('pdfkit');
const buildPdfBuffer = (data) => {
return new Promise((resolve, reject) => {
const doc = new PDFDocument();
const chunks = [];
doc.on('data', chunk => chunks.push(chunk));
doc.on('end', () => resolve(Buffer.concat(chunks)));
doc.on('error', reject);
doc.fontSize(16).text(`Invoice #${data.invoiceNo}`);
doc.text(`Amount: $${data.amount}`);
doc.end();
});
};
module.exports = buildPdfBuffer;
// Usage
// const buf = await buildPdfBuffer({ invoiceNo: '001', amount: 150 });
// await fs.promises.writeFile('invoice.pdf', buf);
ExcelJS Install: Install ExcelJS to create, read, and write Excel
.xlsx files.terminal
JS
npm install exceljs
ExcelJS – Workbook & Stream to Response: Build an Excel workbook with headers and data rows, then stream it directly to the browser as a download.
controllers/exportController.js
JS
const ExcelJS = require('exceljs');
exports.downloadExcel = async (req, res) => {
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('Users');
// Define columns / headers
worksheet.columns = [
{ header: 'ID', key: 'id', width: 10 },
{ header: 'Name', key: 'name', width: 25 },
{ header: 'Email', key: 'email', width: 35 },
{ header: 'Role', key: 'role', width: 15 },
];
// Style header row
worksheet.getRow(1).font = { bold: true };
// Add data rows
const users = await User.find().lean();
users.forEach(u => worksheet.addRow({ id: u._id, name: u.name, email: u.email, role: u.role }));
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader('Content-Disposition', 'attachment; filename="users.xlsx"');
await workbook.xlsx.write(res);
res.end();
};
CSV Export with
json2csv: Convert a JSON array to CSV format and stream it as a downloadable file. Install with npm install json2csv.controllers/exportController.js
JS
const { Parser } = require('json2csv');
exports.downloadCsv = async (req, res) => {
try {
const users = await User.find().lean();
const fields = [
{ label: 'ID', value: '_id' },
{ label: 'Name', value: 'name' },
{ label: 'Email', value: 'email' },
];
const parser = new Parser({ fields });
const csv = parser.parse(users);
res.setHeader('Content-Type', 'text/csv');
res.setHeader('Content-Disposition', 'attachment; filename="users.csv"');
res.status(200).end(csv);
} catch (err) {
res.status(500).json({ message: err.message });
}
};