Skip to content

Latest commit

 

History

History

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 

README.md

pdfkit-table — example-server

Express + TypeScript server that demonstrates how to use pdfkit-table to generate PDF files on the server side.


Requirements

  • Node.js >= 18
  • npm >= 9

Install

cd example-server
npm install

Run

Development (no build step)

npm run dev

Production

npm run build
npm start

The server starts on http://localhost:3030


Endpoints

Method URL Description
GET /pdf/simple Array-based table — 4 rows with padding
GET /pdf/full Object-based table — product list with renderers, alignment and header colors

Open either URL in the browser to view the PDF inline.
A copy is also saved to disk inside example-server/pdf/.


Project structure

example-server/
├── src/
│   └── server.ts      ← Express server with PDF endpoints
├── pdf/               ← generated PDF files (created at runtime)
├── dist/              ← compiled output (generated by `npm run build`)
├── package.json
├── tsconfig.json
└── README.md

How it works

pdfkit is imported once at the top and wrapped with createPdfDocumentWithTables.
The resulting PDFDocument class is shared across all routes.

import PDFKitBase from "pdfkit";
import { createPdfDocumentWithTables } from "pdfkit-table";

const PDFDocument = createPdfDocumentWithTables(PDFKitBase);

Array-based table (/pdf/simple)

const doc = new PDFDocument({ margin: 30, size: "A4" });
doc.pipe(res);

await doc.table(
  {
    headers: ["Country", "Conversion rate", "Trend"],
    rows: [
      ["Switzerland", "12%", "+1.12%"],
      ["France",      "67%", "-0.98%"],
      ["England",     "33%", "+4.44%"],
      ["Brazil",      "45%", "+2.30%"],
    ],
  },
  {
    width: 400,
    padding: [8, 10, 8, 10],
    prepareHeader: () => doc.font("Helvetica-Bold").fontSize(10),
    prepareRow:    () => doc.font("Helvetica").fontSize(9),
  },
);

doc.end();

Object-based table (/pdf/full)

await doc.table(
  {
    headers: [
      { label: "Product",    property: "name",        width: 120 },
      { label: "Description",property: "description", width: 200 },
      {
        label: "Unit Price", property: "price", width: 90,
        align: "right",
        renderer: (value) => `$ ${Number(value).toFixed(2)}`,
      },
      { label: "Stock", property: "stock", width: 60, align: "center" },
    ],
    data: [
      { name: "Laptop Pro",          price: 1299.99, stock: 42,  description: "..." },
      { name: "Wireless Mouse",      price: 39.90,   stock: 150, description: "..." },
      { name: "Mechanical Keyboard", price: 89.00,   stock: 73,  description: "..." },
    ],
  },
  {
    padding: [10, 8, 10, 8],
    columnSpacing: 4,
    prepareHeader: () => doc.font("Helvetica-Bold").fontSize(9).fillColor("#ffffff"),
    prepareRow:    () => doc.font("Helvetica").fontSize(9).fillColor("#000000"),
  },
);

Links