pdf-lib-draw-table-beta

Beta - pdf-lib-draw-table

codecovTests TypeScript MIT License

A library for drawing tables in PDFs using pdf-lib.

Table of Contents

Installation

npm install pdf-lib-draw-table-beta

If you don't already have pdf-lib then

npm install pdf-lib pdf-lib-draw-table

Example

This is a very simple example (server side as we are using fs). Exactly the same code (minus fs!) will also work client side for example in a react component. The options are fairly extensive for formatting and styling, we just show a couple here. You can also pass us a JSON table if you prefer, either that or array as below is fine. Either can contain any of the following within each cell: string - As in the example below. This is drawn as wrapped text, no word splitting. Image, Link, CustomSyledText OR AN ARRAY OF ANY COMBO OF THE ABOVE If you provide an array we automatically put each item on its own line, as such if you need to manually new line text, this is a way of doing that.

import { PDFDocument } from 'pdf-lib';
import { drawTable } from 'pdf-lib-draw-table';
import fs from 'fs';

(async () => {
// Create a new PDFDocument
const pdfDoc = await PDFDocument.create();

// Add a new page
const page = pdfDoc.addPage([600, 800]);

// Define the table data
const tableData = [
['Name', 'Age', 'City'],
['Alice', '24', 'New York'],
['Bob', '30', 'San Francisco'],
['Charlie', '22', 'Los Angeles'],
];

// Set the starting X and Y coordinates for the table
const startX = 50;
const startY = 750;

// Set the table options
const options = {
header: {
hasHeaderRow: true,
backgroundColor: rgb(0.9, 0.9, 0.9),
},
};

try {
// Draw the table
const tableDimensions = await drawTable(pdfDoc, page, tableData, startX, startY, options);

console.log('Table dimensions:', tableDimensions);

// Serialize the PDF to bytes and write to a file
const pdfBytes = await pdfDoc.save();
fs.writeFileSync('table-example.pdf', pdfBytes);
} catch (error) {
console.error('Error drawing table:', error);
}
})();

Massive thanks to PDF lib for creating a powerful PDF manipulation library.

Also, big thanks to Typedoc for providing the amazing documentation generator tool that makes /docs: https://github.com/TypeStrong/typedoc

Generated using TypeDoc