Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create pdf file in node js

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?

like image 336
Ritz Avatar asked Aug 04 '16 12:08

Ritz


2 Answers

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);
like image 179
Nick Bull Avatar answered Nov 10 '22 07:11

Nick Bull


You can use pdf-creator-node package to create PDF

Following are the steps to create PDF in Node Application

  1. Installation install the pdf creator package by the following command

npm i pdf-creator-node

  1. Add required packages and read HTML template

//Required package
var pdf = require("pdf-creator-node")
var fs = require('fs')

// Read HTML Template
var html = fs.readFileSync('template.html', 'utf8')

  1. Create your HTML Template

<!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>                                        
  1. Provide Format and Orientation as per your need

"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" };

  1. Provide HTML, User data and pdf path for the output

var users = [
    {
        name:"Shyam",
        age:"26"
    },
    {
        name:"Navjot",
        age:"26"
    },
    {
        name:"Vitthal",
        age:"26"
    }
]
var document = {
    html: html,
    data: {
        users: users
    },
    path: "./output.pdf"
};
  1. After setting all parameters just pass document and options to pdf.create method.

pdf.create(document, options)
    .then(res => {
        console.log(res)
    })
    .catch(error => {
        console.error(error)
    });
like image 10
Shyam Hajare Avatar answered Nov 10 '22 06:11

Shyam Hajare