natancabral / pdfkit-table

Helps to draw informations in simple tables using pdfkit. #server-side. Generate pdf tables with javascript (PDFKIT plugin)
MIT License
93 stars 59 forks source link
javascript json nodejs pdf pdf-table pdfkit pdfkit-table server-side



pdfkit-table (Natan Cabral)

pdfkit-table

Generate pdf tables with javascript (PDFKIT plugin)

Helps to draw informations in simple tables using pdfkit. #server-side.

Examples

view pdf example | color pdf | full code example | server example | json example | all

Install

NPM

npm install pdfkit-table

Use

  // requires
  const fs = require("fs");
  const PDFDocument = require("pdfkit-table");

  // init document
  let doc = new PDFDocument({ margin: 30, size: 'A4' });
  // save document
  doc.pipe(fs.createWriteStream("./document.pdf"));

  ;(async function createTable(){
    // table
    const table = { 
      title: '',
      headers: [],
      datas: [ /* complex data */ ],
      rows: [ /* or simple data */ ],
    };

    // the magic (async/await)
    await doc.table(table, { /* options */ });
    // -- or --
    // doc.table(table).then(() => { doc.end() }).catch((err) => { })

    // if your run express.js server
    // to show PDF on navigator
    // doc.pipe(res);

    // done!
    doc.end();
  })();

Examples

Server response

server example

  // router - Node + Express.js
  app.get('/create-pdf', async (req, res) => {
    // ...await table code
    // if your run express.js server
    // to show PDF on navigator
    doc.pipe(res);
    // done!
    doc.end();
  });

Example 1 - Simple Array

  ;(async function(){
    // table 
    const table = {
      title: "Title",
      subtitle: "Subtitle",
      headers: [ "Country", "Conversion rate", "Trend" ],
      rows: [
        [ "Switzerland", "12%", "+1.12%" ],
        [ "France", "67%", "-0.98%" ],
        [ "England", "33%", "+4.44%" ],
      ],
    };
    // A4 595.28 x 841.89 (portrait) (about width sizes)
    // width
    await doc.table(table, { 
      width: 300,
    });
    // or columnsSize
    await doc.table(table, { 
      columnsSize: [ 200, 100, 100 ],
    });
    // done!
    doc.end();
  })();

Example 2 - Table

  ;(async function(){
    // table
    const table = {
      title: "Title",
      subtitle: "Subtitle",
      headers: [
        { label: "Name", property: 'name', width: 60, renderer: null },
        { label: "Description", property: 'description', width: 150, renderer: null }, 
        { label: "Price 1", property: 'price1', width: 100, renderer: null }, 
        { label: "Price 2", property: 'price2', width: 100, renderer: null }, 
        { label: "Price 3", property: 'price3', width: 80, renderer: null }, 
        { label: "Price 4", property: 'price4', width: 43, 
          renderer: (value, indexColumn, indexRow, row, rectRow, rectCell) => { return `U$ ${Number(value).toFixed(2)}` } 
        },
      ],
      // complex data
      datas: [
        { 
          name: 'Name 1', 
          description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean mattis ante in laoreet egestas. ', 
          price1: '$1', 
          price3: '$ 3', 
          price2: '$2', 
          price4: '4', 
        },
        { 
          options: { fontSize: 10, separation: true},
          name: 'bold:Name 2', 
          description: 'bold:Lorem ipsum dolor.', 
          price1: 'bold:$1', 
          price3: { 
            label: 'PRICE $3', options: { fontSize: 12 } 
          }, 
          price2: '$2', 
          price4: '4', 
        },
        // {...},
      ],
      // simeple data
      rows: [
        [
          "Apple",
          "Nullam ut facilisis mi. Nunc dignissim ex ac vulputate facilisis.",
          "$ 105,99",
          "$ 105,99",
          "$ 105,99",
          "105.99",
        ],
        // [...],
      ],
    };
    // the magic
    doc.table(table, {
      prepareHeader: () => doc.font("Helvetica-Bold").fontSize(8),
      prepareRow: (row, indexColumn, indexRow, rectRow, rectCell) => {
        doc.font("Helvetica").fontSize(8);
        indexColumn === 0 && doc.addBackground(rectRow, 'blue', 0.15);
      },
    });
    // done!
    doc.end();
  })();

Example 3 - Json

  ;(async function(){
    // renderer function inside json file
    const tableJson = '{ 
      "headers": [
        { "label":"Name", "property":"name", "width":100 },
        { "label":"Age", "property":"age", "width":100 },
        { "label":"Year", "property":"year", "width":100 }
      ],
      "datas": [
        { "name":"bold:Name 1", "age":"Age 1", "year":"Year 1" },
        { "name":"Name 2", "age":"Age 2", "year":"Year 2" },
        { "name":"Name 3", "age":"Age 3", "year":"Year 3",
          "renderer": "function(value, i, irow){ return value + `(${(1+irow)})`; }"
        }
      ],
      "rows": [
        [ "Name 4", "Age 4", "Year 4" ]
      ],
      "options": {
        "width": 300
      }
    }';
    // the magic
    doc.table(tableJson);
    // done!
    doc.end();
  })();

Example 4 - Json file (many tables)

  ;(async function(){
    // json file
    const json = require('./table.json');
    // if json file is array
    Array.isArray(json) ? 
    // any tables - array
    await doc.tables(json) : 
    // one table - string
    await doc.table(json) ;
    // done!
    doc.end();
  })();

Table

Headers

Properties Type Default Description
label String undefined description
property String undefined id
width Number undefined width of column
align String left alignment
valign String undefined vertical alignment. ex: valign: "center"
headerColor String grey or #BEBEBE color of header
headerOpacity Number 0.5 opacity of header
headerAlign String left only header
columnColor or backgroundColor String undefined color of column
columnOpacity or backgroundOpacity Number undefined opacity of column
renderer Function Function function( value, indexColumn, indexRow, row, rectRow, rectCell ) { return value }

Simple headers example

const table = {
  // simple headers only with ROWS (not DATAS)  
  headers: ['Name', 'Age'],
  // simple content
  rows: [
    ['Jack', '32'], // row 1
    ['Maria', '30'], // row 2
  ]
};

Complex headers example

const table = {
  // complex headers work with ROWS and DATAS  
  headers: [
    { label:"Name", property: 'name', width: 100, renderer: null },
    { label:"Age", property: 'age', width: 100, renderer: (value) => `U$ ${Number(value).toFixed(1)}` },
  ],
  // complex content
  datas: [
    { name: 'bold:Jack', age: 32, },
    // age is object value with style options
    { name: 'Maria', age: { label: 30 , options: { fontSize: 12 }}, },
  ],
  // simple content (works fine!)
  rows: [
    ['Jack', '32'], // row 1
    ['Maria', '30'], // row 2
  ]
};

Options

Properties Type Default Description
title String Object undefined title
subtitle String Object undefined subtitle
width Number undefined width of table
x Number undefined position x (left). To reset x position set "x: null"
y Number undefined position y (top)
divider Object undefined define divider lines
columnsSize Array undefined define sizes
columnSpacing Number 5
padding Number Array 1 or [1, 5]
addPage Boolean false add table on new page
hideHeader Boolean false hide header
minRowHeight Number 0 min row height
prepareHeader Function Function ()
prepareRow Function Function (row, indexColumn, indexRow, rectRow, rectCell) => {}

Options example

const options = {
  // properties
  title: "Title", // { label: 'Title', fontSize: 30, color: 'blue', fontFamily: "./fonts/type.ttf" },
  subtitle: "Subtitle", // { label: 'Subtitle', fontSize: 20, color: 'green', fontFamily: "./fonts/type.ttf" },
  width: 500, // {Number} default: undefined // A4 595.28 x 841.89 (portrait) (about width sizes)
  x: 0, // {Number} default: undefined | To reset x position set "x: null"
  y: 0, // {Number} default: undefined | 
  divider: {
    header: { disabled: false, width: 2, opacity: 1 },
    horizontal: { disabled: false, width: 0.5, opacity: 0.5 },
  },
  padding: 5, // {Number} default: 0
  columnSpacing: 5, // {Number} default: 5
  hideHeader: false, 
  minRowHeight: 0,
  // functions
  prepareHeader: () => doc.font("Helvetica-Bold").fontSize(8), // {Function} 
  prepareRow: (row, indexColumn, indexRow, rectRow, rectCell) => doc.font("Helvetica").fontSize(8), // {Function} 
}

Options Row

datas: [
  // options row
  { name: 'Jack', options: { fontSize: 10, fontFamily: 'Courier-Bold', separation: true } },
]
datas: [
  // bold
  { name: 'bold:Jack' },
  // size{n}
  { name: 'size20:Maria' },
  { name: 'size8:Will' },
  // normal
  { name: 'San' },
]

Options Cell

datas: [
  // options cell | value is object | label is string
  { name: { label: 'Jack', options: { fontSize: 10, fontFamily: 'Courier-Bold' } },
]

Fonts Family

ToDo

Changelogs

0.1.90

0.1.89

0.1.88

0.1.87

0.1.86

0.1.83

0.1.72

0.1.70

0.1.68

0.1.63

0.1.60

0.1.59

0.1.57

0.1.55

0.1.49

0.1.48

0.1.47

0.1.46

0.1.45

0.1.44

0.1.43

0.1.41

0.1.39

0.1.38

0.1.37

0.1.36

0.1.35

0.1.34

0.1.33

0.1.32

0.1.31

License

The MIT License.

Author

Natan Cabral
natancabral@hotmail.com
https://github.com/natancabral/

Thank you