Last updated on July 10, 2023
To generate a PDF file from an HTML template in an Express.js application, you can use a library like pdf-lib
or html-pdf
. Here’s an example using the pdf-lib
library.
Install the pdf-lib package
npm install pdf-lib
Create a new route in your Express.js application to handle the PDF generation:
const express = require('express');
const { PDFDocument } = require('pdf-lib');
const fs = require('fs');
const app = express();
app.get('/generate-pdf', async (req, res) => {
try {
const htmlTemplate = '<html><body><h1>Hello, PDF!</h1></body></html>'; // Replace with your HTML template
// Create a new PDF document
const pdfDoc = await PDFDocument.create();
// Embed the HTML content into a new page
const page = pdfDoc.addPage();
const { width, height } = page.getSize();
const htmlContent = await pdfDoc.embedHtml(htmlTemplate);
page.addFragment(htmlContent);
// Generate the PDF bytes
const pdfBytes = await pdfDoc.save();
// Set the response headers
res.setHeader('Content-Disposition', 'attachment; filename="generated-pdf.pdf"');
res.setHeader('Content-Type', 'application/pdf');
// Send the PDF as a response
res.send(pdfBytes);
} catch (error) {
console.error('Error generating PDF:', error);
res.status(500).send('Error generating PDF');
}
});
// Start the Express server
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Customize the htmlTemplate
variable with your own HTML content or dynamically generate the HTML based on your requirements.
When you access the /generate-pdf
route in your browser or make a request to it, the Express.js application will generate a PDF using the specified HTML template and return it as a downloadable file with the name generated-pdf.pdf
.
Note that this example generates a simple PDF from an HTML template using pdf-lib
. You can further customize and enhance the PDF generation process based on your specific needs, such as adding images, tables, or more complex styling to the HTML template.
Remember to handle any errors that may occur during the PDF generation process and set appropriate headers for the response to ensure proper file download.