The library helps you handle real-world table requirements such as text wrapping for long content, automatic column width calculations, and maintaining header visibility across page breaks.
It can be useful for generating reports, invoices, data exports, and any document that requires structured tabular data presentation.
auto, equal, and content.1. Install both jspdf and jspdf-table packages with NPM:
# NPM $ npm install jspdf @ikramrasheed/jspdf-table
2. Import them into your project.
import jsPDF from 'jspdf';
import { autoTable } from '@ikramrasheed/jspdf-table'; 3. Or directly load the UMD versions in the document.
<script src="/path/to/cdn/jspdf.umd.min.js"></script> <script src="/path/to/dist/index.umd.js"></script>
4. Initialize jsPDF, define your columns and tabular data, and then call the autoTable function.
const doc = new jsPDF();
// Define column headers and data keys
const columns = [
{ header: 'ID', dataKey: 'id', width: 50, align: 'center' },
{ header: 'Name', dataKey: 'name', minWidth: 80, align: 'left' },
{ header: 'Price', dataKey: 'price', align: 'right', headerAlign: 'center' },
{ header: 'Status', dataKey: 'status', width: '20%', align: 'center' }
]
// Provide the data as an array of objects
const data = [
{ id: 1, name: 'Laptop Computer', price: 1299.99, status: 'In Stock' },
{ id: 2, name: 'Mouse', price: 29.99, status: 'Low Stock' },
{ id: 3, name: 'Keyboard', price: 79.99, status: 'Out of Stock' },
{ id: 4, name: 'Monitor 27"', price: 349.99, status: 'In Stock' }
];
// Generate the table
const result = autoTable(doc, columns, data, {
startY: 30,
theme: 'grid',
headerStyles: {
fillColor: [52, 152, 219],
textColor: [255, 255, 255],
fontStyle: 'bold'
}
}); 5. Download the table as a PDF file.
doc.save('myTable.pdf'); 6. Available options to customize the table.
{ top, right, bottom, left }.'auto' (the default) adds a new page when content overflows, 'avoid' attempts to keep the table on a single page, and 'always' forces a page break before rendering the table.'striped', 'grid', 'plain', and 'minimal'.'80%'), or 'auto'.'auto' respects individual column settings, 'fixed' requires all widths to be explicitly set, 'content' sizes columns based on their content, and 'equal' distributes the available width evenly among columns.true or false) to control the visibility of the table header.true, applies the alternateRowStyles to every other row.fontSize, cellPadding, and font.styles.styles.alternateRowColors is enabled.top, bottom, horizontal, and vertical.'auto' to calculate height based on the cell content.'auto' to calculate its height based on content.const result = autoTable(doc, columns, data, {
startY?: number;
margin?: number | { top?: number; right?: number; bottom?: number; left?: number };
pageBreak?: 'auto' | 'avoid' | 'always';
theme?: 'striped' | 'grid' | 'plain' | 'minimal';
tableWidth?: number | 'auto' | string; // Fixed width, auto-fit, or percentage
columnWidthMode?: 'auto' | 'fixed' | 'content' | 'equal';
showHeader?: boolean;
showBorders?: boolean;
alternateRowColors?: boolean;
styles?: CellStyles;
headerStyles?: CellStyles & ColorStyles;
bodyStyles?: CellStyles & ColorStyles;
alternateRowStyles?: CellStyles & ColorStyles;
borderStyles?: BorderStyles;
rowHeight?: number | 'auto';
headerHeight?: number | 'auto';
}); 7. All Column configs:
100), a percentage string (e.g., '30%'), or 'auto' to let the library decide.'left', 'center', or 'right'.align property.wrap to control how wide a column gets.true or false) that determines if long text within a cell should wrap to multiple lines. This requires a width or maxWidth to be set.const columns = [
{
header: string;
dataKey: string;
width?: number | 'auto' | string; // Fixed width, auto-calculate, or percentage
align?: 'left' | 'center' | 'right';
headerAlign?: 'left' | 'center' | 'right';
minWidth?: number;
maxWidth?: number;
wrap?: boolean;
},
// ...
] 8. Here are the values returned by the autoTable function.
1 for tables that fit on a single page and more for tables that trigger page breaks.9. One aspect we appreciate is the library’s specific error handling. Instead of throwing generic errors, it provides distinct error classes that help you pinpoint the problem quickly. This is useful in complex applications where table data or options are generated dynamically.
import { ValidationError, RenderError } from '@ikramrasheed/jspdf-table';
try {
// Your autoTable call here
autoTable(doc, columns, data, options);
} catch (error) {
if (error instanceof ValidationError) {
// This catches issues with your input configuration.
console.error('Invalid input:', error.message);
} else if (error instanceof RenderError) {
// This catches problems during the PDF drawing process.
console.error('Rendering failed:', error.message);
} else {
// Catch any other unexpected errors.
console.error('An unexpected error occurred:', error);
}
} Q: How do I add content after the table?
A: The autoTable function returns an object containing finalY. This value is the Y-coordinate right below the last row of the table. Use it as the starting Y for your next element, like doc.text('This comes after the table', 20, result.finalY + 10);.
Q: Can I use custom fonts in the table?
A: Yes. You first need to load the custom font into your jsPDF instance. Once the font is registered in the document, you can specify it by name in any of the style objects, for example: styles: { font: 'MyCustomFont' }.
Q: What happens if my table is wider than the page?
A: The library will attempt to render the table at the specified tableWidth (which defaults to the page width minus margins). If your column widths exceed this, the content may be clipped or overlap. It’s your responsibility to ensure your column width, minWidth, and maxWidth properties are set appropriately to fit within the page boundaries. The library manages vertical overflow (page breaks), not horizontal.
Q: How is jspdf-table different from jspdf-autotable?
A: While both serve a similar purpose, jspdf-table is a newer library written in TypeScript, offering strong typing out of the box. jspdf-autotable is more established and has a larger community.
The post Generate Professional & Beautiful PDF Tables with jsPDF-Table appeared first on CSS Script.
Images showing the long-awaited LEGO Lord of the Rings Minas Tirith set have leaked online,…
Bungie’s limited-edition Marathon DualSense controller has dropped in price far quicker than expected, and it’s…
Chief Meteorologist Ahmad Bajjey in CBS Detroit’s new AR/VR studio CBS O&O WWJ Detroit (CBS…
The post EVS Launches Choreon Robotic Control Solution appeared first on TV News Check.
The post Heidi Steffen To Become President Of TitanTV appeared first on TV News Check.
The post Refreshed NAB Show Reflects An Industry In Flux appeared first on TV News…
This website uses cookies.