To create a PDF document in Node.js using the pdf-creator-node
library, follow these steps:
Step 1: Set up a new Node.js project.
Create a new directory for your project, navigate to it in a terminal, and run the following commands:
npm init -y
npm i pdf-creator-node
Step 2: Create a template HTML file.
Create a new HTML file (e.g., template.html
) and add the content you want to include in the PDF. You can use HTML tags, CSS styles, and placeholders for dynamic data. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<!DOCTYPE html> <html> <head> <title>PDF Document</title> <style> body { font-family: Arial, sans-serif; } </style> </head> <body> <h1>{{ title }}</h1> <p>{{ content }}</p> </body> </html> |
In the above code, we have a simple HTML template with placeholders ({{ title }} and {{ content }}) that we can replace with dynamic data when generating the PDF.
Step 3: Create a Node.js script to generate the PDF.
Create a new JavaScript file (e.g., pdfGenerator.js) in the same directory as your project files and add the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
const fs = require('fs'); const PDFCreator = require('pdf-creator-node'); // Read the template HTML file const templateHtml = fs.readFileSync('template.html', 'utf8'); // Define the dynamic data const data = { title: 'My PDF Document', content: 'This is the content of my PDF document.', }; // Compile the template const compiledHtml = PDFCreator(templateHtml).compile(data); // Generate the PDF const options = { format: 'A4', orientation: 'portrait', border: '10mm', }; PDFCreator(compiledHtml, options) .toFile('./output.pdf', (err, res) => { if (err) { console.error(err); } else { console.log('PDF created:', res.filename); } }); |
In the code above, we require the fs
module to read the template HTML file and the pdf-creator-node
library. We then read the template HTML file using fs.readFileSync()
and store it in the templateHtml
variable.
We define the dynamic data that will replace the placeholders in the template HTML.
Next, we compile the template HTML using PDFCreator(templateHtml).compile(data)
, which replaces the placeholders with the actual data.
Finally, we generate the PDF using PDFCreator(compiledHtml, options).toFile('./output.pdf', callback)
, where options
specify the PDF format, orientation, and border. The PDF is saved as output.pdf
, and the callback function receives an error (if any) and the response containing the filename of the generated PDF.
Step 4: Run the Node.js script.
Save the files and run the Node.js script by executing the following command in the terminal: