14

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?

1
  • @MihaiIorga I tries pdfkit. But problem is how i can include the chart data(pie diagrom) which is generated using chart.js ? rest is working well. Commented Aug 6, 2016 at 9:38

3 Answers 3

11

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

Sign up to request clarification or add additional context in comments.

2 Comments

Hi, efkah you can add dynamic content in HTML. please check README file npmjs.com/package/pdf-creator-node
I think he did provide dynamic content over here in example in answer, look at the users parameter in document object. I don't think anything more is needed, unless one wants him to write even the application logic.
7

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);

3 Comments

where i should write this code? In controller or in js file @Nick Bull?
I tries this one. But problem is how i can include the chart data(pie diagrom) which is generated using chart.js ? rest is working well.
How does this answer the question of how to include the output of chart.js?
1

Disclaimer: the author of this post is the author of the module being recommended in the post.

The simplest way to generate PDFs using NodeJS is to use the pdf-master package. You can generate static and dynamic PDFs using HTML with one function call.

Installation

npm install pdf-master

Example

Step 1 - Add required packages and generate a PDF

const express = require("express");
const pdfMaster = require("pdf-master");
const app = express();

app.get("", async (req, res) => {

  var PDF = await pdfMaster.generatePdf("template.hbs");

  res.contentType("application/pdf");
  res.status(200).send(PDF);
});

generatePdf() syntax and parameters

generatePdf(
  templatePath, //<string>
  data, //<object>   Pass data to template(optional)
  options //<object>   PDF format options(optional)
);

Step 2 - Create your HTML Template (save the template with .hbs extension instead of .html)

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8" />
      </head>
      <body>
        <h1>Hello World</h1>
      </body>
    </html>

Render dynamic data in template and PDF format options

const express = require("express");
const pdfMaster = require("pdf-master");

const app = express();

app.get("", async (req, res) => {

  var students = {
      {
          id: 1,
          name: "Sam",
          age: 21
      },
      {
          id: 2,
          name: "Jhon",
          age: 20
      },
      {
          id: 3,
          name: "Jim",
          age: 24
      }
  }

  let options = {
    displayHeaderFooter: true,
    format: "A4",
    headerTemplate: `<h3> Header </h3>`,
    footerTemplate: `<h3> Copyright 2023 </h3>`,
    margin: { top: "80px", bottom: "100px" },
  };

  let PDF = await pdfMaster.generatePdf("template.hbs", students, options);
  res.contentType("application/pdf");
  res.status(200).send(PDF);
});

To learn more about pdf-master visit

1 Comment

Where is the PDF file created? Is it possible to specify a path?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.