I am creating an application in node.js
utilizing the sails framework. I want to create a report in PDF format. The report needs to contain a chart generated using chart.js
. The data is fetched from mongodb and displayed on a canvas
. How can I create a PDF file of this chart using node.js?
PDFKit
.
Installation:
npm install pdfkit
Example:
var PDFDocument = require('pdfkit');
doc = new PDFDocument;
doc.pipe(fs.createWriteStream('output.pdf'));
doc.font('fonts/PalatinoBold.ttf').fontSize(25).text(100, 100);
You can use pdf-creator-node package to create PDF
Following are the steps to create PDF in Node Application
npm i pdf-creator-node
//Required package
var pdf = require("pdf-creator-node")
var fs = require('fs')
// Read HTML Template
var html = fs.readFileSync('template.html', 'utf8')
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Hello world!</title>
</head>
<body>
<h1>User List</h1>
<ul>
{{#each users}}
<li>Name: {{this.name}}</li>
<li>Age: {{this.age}}</li>
<br>
{{/each}}
</ul>
</body>
</html>
"height": "10.5in", // allowed units: mm, cm, in, px
"width": "8in", // allowed units: mm, cm, in, px
or -
"format": "Letter", // allowed units: A3, A4, A5, Legal, Letter, Tabloid "orientation": "portrait", // portrait or landscape
var options = { format: "A3", orientation: "portrait", border: "10mm" };
var users = [
{
name:"Shyam",
age:"26"
},
{
name:"Navjot",
age:"26"
},
{
name:"Vitthal",
age:"26"
}
]
var document = {
html: html,
data: {
users: users
},
path: "./output.pdf"
};
pdf.create(document, options)
.then(res => {
console.log(res)
})
.catch(error => {
console.error(error)
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With