To generate PDF files from an HTML template in a Node.js Express application, we can use the Express PDF library, which is built on top of the PhantomJS headless browser.
Here is an example code for generating PDF files from an HTML template using Express PDF and PhantomJS library:
- First, we need to install the required libraries:
npm install express express-pdf phantomjs-prebuilt
- Next, we create a simple HTML template file called
template.html
:
1 2 3 4 5 6 7 8 9 10 |
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>PDF Document</title> </head> <body> <h1>Hello, World!</h1> </body> </html> |
- Then, we create a new Node.js Express application and configure the Express PDF middleware:
1 2 3 4 5 |
const express = require('express'); const app = express(); const pdf = require('express-pdf'); app.use(pdf); |
- We then define a route for generating PDF files. This route loads the HTML template file and converts it to a PDF document using the Express PDF middleware:
1 2 3 4 5 6 7 8 9 10 11 12 |
app.get('/pdf', (req, res) => { const options = { format: 'A4', orientation: 'portrait', border: '10mm' }; res.pdfFromHTML({ filename: 'document.pdf', html: __dirname + '/template.html', options: options }); }); |
- Finally, we start the server and listen for incoming requests:
1 2 3 |
app.listen(3000, () => { console.log('Server started on port 3000'); }); |
Now, when we visit http://localhost:3000/pdf
, the server will generate a PDF file based on the template.html
file and return it to the client.