0.1.88 • Published 2 years ago

natancabral-pdfkit-table v0.1.88

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

natancabral-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 natancabral-pdfkit-table

Use

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

  // create document
  let doc = new PDFDocument({ margin: 30, size: 'A4' });
  // file name
  doc.pipe(fs.createWriteStream("./document.pdf"));
  
  // table
  const table = { 
    title: '',
    headers: [],
    datas: [ /* complex data */ ],
    rows: [ /* or simple data */ ],
  }
  // the magic
  doc.table( table, { /* options */ }, () => { /* callback */ } );
  // doc.table() is a Promise to async/await function 

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

  // done!
  doc.end();

Server response

server example

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

Example 1 - Simple Array

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

Example 2 - Table

  // require
  // A4 595.28 x 841.89 (portrait) (about width sizes)
  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) => { 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",
      ],
      // [...],
    ],
  };

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

Example 3 - Json

// 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
  }
}';
doc.table( tableJson );

Example 4 - Json file (many tables)

const json = require('./table.json');
// if json file is array
Array.isArray(json) ? 
// any tables
json.forEach( table => doc.table( table, table.options || {} ) ) : 
// one table
doc.table( json, json.options || {} ) ;

Table

  • Array.<object> | JSON
    • headers Array.<object> | Array.[]
      • label String
      • property String
      • width Number
      • align String
      • valign String
      • headerColor String
      • headerOpacity Number
      • headerAlign String
      • columnColor or backgroundColor String
      • columnOpacity or backgroundOpacity: Number
      • renderer Function function( value, indexColumn, indexRow, row, rectRow, rectCell ) { return value }
    • datas Array.<object>
    • rows Array.[]
    • title String || Object
    • subtitle String || Object

Headers

PropertiesTypeDefaultDescription
labelStringundefineddescription
propertyStringundefinedid
widthNumberundefinedwidth of column
alignStringleftalignment
valignStringundefinedvertical alignment. ex: valign: "center"
headerColorStringgrey or #BEBEBEcolor of header
headerOpacityNumber0.5opacity of header
headerAlignStringleftonly header
columnColor or backgroundColorStringundefinedcolor of column
columnOpacity or backgroundOpacityNumberundefinedopacity of column
rendererFunctionFunctionfunction( 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

PropertiesTypeDefaultDescription
titleStringObjectundefinedtitle
subtitleStringObjectundefinedsubtitle
widthNumberundefinedwidth of table
xNumberundefined / doc.xposition x (left)
yNumberundefined / doc.yposition y (top)
dividerObjectundefineddefine divider lines
columnsSizeArrayundefineddefine sizes
columnSpacingNumber5
addPageBooleanfalseadd table on new page
hideHeaderBooleanfalsehide header
prepareHeaderFunctionFunction()
prepareRowFunctionFunction(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 | doc.x
  y: 0, // {Number} default: undefined | doc.y
  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, 
  // functions
  prepareHeader: () => doc.font("Helvetica-Bold").fontSize(8), // {Function} 
  prepareRow: (row, indexColumn, indexRow, rectRow, rectCell) => doc.font("Helvetica").fontSize(8), // {Function} 
}

Options Row

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

Options Cell

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

Fonts Family

  • Courier
    • Courier-Bold
    • Courier-Oblique
    • Courier-BoldOblique
  • Helvetica
    • Helvetica-Bold
    • Helvetica-Oblique
    • Helvetica-BoldOblique
  • Symbol
  • Times-Roman
    • Times-Bold
    • Times-Italic
    • Times-BoldItalic
  • ZapfDingbats

ToDo

  • Suggestions / Issues / Fixes
  • striped {Boolean} (corsimcornao)
  • colspan - the colspan attribute defines the number of columns a table cell should span.
  • sample with database
  • margin: marginBottom before, marginTop after

Changelogs

0.1.88

  • Fix header font family or title object
    • Thanks @RastaGrzywa
let localType = "./font/Montserrat-Regular.ttf";
const table = {
  title: { label: 'Title Object 2', fontSize: 30, color: 'blue', fontFamily: localType },
}

0.1.87

  • Add options hideHeader
    • Thanks Ville @VilleKoo
  options: {
    hideHeader: true,
  }

0.1.83

  • Avoid a table title appearing alone
    • Thanks Alexis Arriola @AlexisArriola
  • Problem with long text in cell spreading on several pages
    • Thanks Ed @MeMineToMe

0.1.72

  • Add Divider Lines on options
  options: {
    // divider lines
    divider: {
      header: {disabled: false, width: 0.5, opacity: 0.5},
      horizontal: {disabled: true, width: 0.5, opacity: 0.5},
    },
  }
  • Thanks Luc Swart @lucswart

0.1.70

  • Fix y position.
    • Thanks Nabil Tahmidul Karim @nabiltkarim

0.1.68

  • Added Promise. table is a Promise();
    • Async/Await function
;(async function(){
  // create document
  const doc = new PDFDocument({ margin: 30, });
  // to save on server
  doc.pipe(fs.createWriteStream("./my-table.pdf"));
  // tables
  await doc.table(table, options);
  await doc.table(table, options);
  await doc.table(table, options);
  // done
  doc.end();
})();
  • Added callback.
  doc.table(table, options, callback);

0.1.63

  • Added valign on headers options. (ex: valign:"center")
  • Added headerAlign, alignment only to header.
    headers: [
      {label:"Name", property:"name", valign: "center", headerAlign:"right", headerColor:"#FF0000", headerOpacity:0.5 }
    ]
    • Thanks @DPCLive

0.1.60

  • Add callback on addBackground function, add .save() and .restore() style.
  • Header font color
    • Thanks @dev-fema

0.1.59

  • Add padding

0.1.57

  • Header color and opacity
    headers: [
      {label:"Name", property:"name", headerColor:"#FF0000", headerOpacity:0.5 }
    ]
    • Thanks Albert Taveras @itsalb3rt

0.1.55

  • Align on headers
    headers: [
      {label:"Name", property:"name", align:"center"}
    ]
    • Thanks Andrea Fucci

0.1.49

  • Max size page

0.1.48

  • Header height size
  • Separate line width

0.1.47

  • addHeader() function on all add pages
    • Thanks Anders Wasen @QAnders

0.1.46

  • addBackground() function to node 8
    • Thanks @mehmetunubol

0.1.45

  • Add rectCell on renderer
    • renderer = ( value, indexColumn, indexRow, row, rectRow, rectCell ) => {}
    • Thanks Eduardo Miranda

0.1.44

  • Fix paddings and distances

0.1.43

  • Remove rowSpacing
  • Fix columnSpacing

0.1.41

0.1.39

  • addBackground {Function} - Add background peer line.
    • doc.addBackground( {x, y, width, height}, fillColor, opacity, callback );
  • prepareRow {Function}
    • const options = { prepareRow: (row, indexColumn, indexRow, rectRow, rectCell) => { indexColumn === 0 && doc.addBackground(rectRow, 'red', 0.5) } }

0.1.38

0.1.37

  • addPage {Boolean} - Add table on new page.
    • const options = { addPage: true, };

0.1.36

  • Fix position x, y of title
  • options.x: null | -1 // reset position to margins.left

0.1.35

  • add title {String}
    • const table = { title: "", };
    • const options = { title: "", };
  • add subtitle {String}
    • const table = { subtitle: "", };
    • const options = { subtitle: "", };

0.1.34

  • add columnsSize on options = {} // only to simple table

0.1.33

  • Function tableToJson
    • import {tableToJson} from 'natancabral-pdfkit-table';
    • const table = tableToJson('#id_table'); {Object}
  • Function allTablesToJson
    • import {allTablesToJson} from 'natancabral-pdfkit-table';
    • const tables = allTablesToJson(); {Array}

0.1.32

  • spacing cell and header alignment
  • Thank you, contributors!

0.1.31

  • renderer function on json file. { "renderer": "function(value, icol, irow, row){ return (value+1) + (${(irow+2)}); }" }
  • fix width table and separation lines size

License

The MIT License.

Author

Thank you

0.1.88

2 years ago

0.1.83

2 years ago

0.1.79

2 years ago

0.1.72

2 years ago

0.1.70

2 years ago

0.1.63

2 years ago

0.1.64

2 years ago

0.1.68

2 years ago

0.1.61

2 years ago

0.1.55

3 years ago

0.1.56

3 years ago

0.1.57

3 years ago

0.1.54

3 years ago

0.1.52

3 years ago

0.1.51

3 years ago

0.1.49

3 years ago

0.1.47

3 years ago

0.1.46

3 years ago

0.1.45

3 years ago

0.1.41

3 years ago

0.1.42

3 years ago

0.1.43

3 years ago

0.1.44

3 years ago

0.1.40

3 years ago

0.1.39

3 years ago

0.1.34

3 years ago

0.1.36

3 years ago

0.1.37

3 years ago

0.1.31

3 years ago

0.1.32

3 years ago

0.1.28

3 years ago

0.1.29

3 years ago

0.1.3

3 years ago

0.1.27

3 years ago

0.1.23

3 years ago

0.1.24

3 years ago

0.1.25

3 years ago

0.1.26

3 years ago

0.1.22

3 years ago

0.1.21

3 years ago

0.1.2

3 years ago

0.0.68

3 years ago

0.0.67

3 years ago

0.0.66

3 years ago

0.0.65

3 years ago

0.0.64

3 years ago

0.0.63

3 years ago

0.0.62

3 years ago

0.0.61

3 years ago

0.0.59

3 years ago

0.0.58

3 years ago

0.0.57

3 years ago

0.0.56

3 years ago

0.0.55

3 years ago

0.0.54

3 years ago

0.0.53

3 years ago

0.0.52

3 years ago

0.0.49

3 years ago

0.0.48

3 years ago

0.0.47

3 years ago

0.0.46

3 years ago

0.0.45

3 years ago

0.0.44

3 years ago

0.0.43

3 years ago

0.0.42

3 years ago

0.0.41

3 years ago

0.0.4

3 years ago