### Draw Image in Cell using didDrawCell Hook
Source: https://github.com/simonbengtsson/jspdf-autotable/blob/main/README.md
Use the `didDrawCell` hook to add custom content like images to cells after they are drawn. This example adds a JPEG image to the first column of body cells.
```javascript
autoTable(doc, {
didDrawCell: (data) => {
if (data.section === 'body' && data.column.index === 0) {
const base64Img = 'data:image/jpeg;base64,iVBORw0KGgoAAAANS...'
doc.addImage(base64Img, 'JPEG', data.cell.x + 2, data.cell.y + 2, 10, 10)
}
},
})
```
--------------------------------
### Image Loading and PDF Update
Source: https://github.com/simonbengtsson/jspdf-autotable/blob/main/index.html
This code snippet demonstrates loading two images ('document.jpg' and 'coin.png') into Base64 format and then calling the update function to generate the initial PDF.
```javascript
let base64Img, coinBase64Img;
imgToBase64('examples/assets/document.jpg', function (base64) {
base64Img = base64;
imgToBase64('examples/assets/coin.png', function (base64) {
coinBase64Img = base64;
update();
});
});
```
--------------------------------
### Core API Methods
Source: https://github.com/simonbengtsson/jspdf-autotable/blob/main/README.md
This section outlines the primary methods available for using the jsPDF-AutoTable plugin, including how to initialize tables, set global defaults, and apply the plugin.
```APIDOC
## API
- `doc.autoTable({ /* options */ })` - Initializes and draws an autoTable on the jsPDF document instance.
- `autoTable(doc, { /* options */ })` - An alternative way to initialize and draw an autoTable, passing the document instance as the first argument.
- `jsPDF.autoTableSetDefaults({ /* ... */ })` - Use for setting global defaults which will be applied for all tables created with this jsPDF instance.
- `applyPlugin(jsPDF)` - Use for adding the autoTable API to any jsPDF instance.
If you want to know something about the last table that was drawn you can use `doc.lastAutoTable`. It has a `doc.lastAutoTable.finalY` property among other things that has the value of the last printed y coordinate on a page. This can be used to draw text, multiple tables or other content after a table.
```
--------------------------------
### Initialize jsPDF and AutoTable
Source: https://github.com/simonbengtsson/jspdf-autotable/blob/main/index.html
This code initializes jsPDF and ensures Promise support for IE. It sets up the onhashchange event to update the PDF based on the URL hash and handles the download button click event.
```javascript
if (!window.Promise) window.Promise = { prototype: null }; // Needed for jspdf IE support
if (!window.jsPDF) window.jsPDF = window.jspdf.jsPDF
window.onhashchange = function () { update(); };
document.getElementById('download-btn').onclick = function () { update(true); };
document.getElementById('download-link').onclick = function () { update(true); };
```
--------------------------------
### Import and Use jsPDF-AutoTable
Source: https://github.com/simonbengtsson/jspdf-autotable/blob/main/README.md
Import the necessary modules and use the autoTable function to generate tables from HTML or JavaScript data. Save the document afterwards.
```javascript
import { jsPDF } from 'jspdf'
import { autoTable } from 'jspdf-autotable'
const doc = new jsPDF()
// It can parse html:
//
autoTable(doc, { html: '#my-table' })
// Or use javascript directly:
autoTable(doc, {
head: [['Name', 'Email', 'Country']],
body: [
['David', 'david@example.com', 'Sweden'],
['Castille', 'castille@example.com', 'Spain'],
// ...
],
})
doc.save('table.pdf')
```
--------------------------------
### Table with Colspan, Rowspan, and Inline Styles
Source: https://github.com/simonbengtsson/jspdf-autotable/blob/main/README.md
Demonstrates advanced cell styling within the table body, including colspan, rowspan, and inline style definitions.
```javascript
autoTable(doc, {
body: [
[{ content: 'Text', colSpan: 2, rowSpan: 2, styles: { halign: 'center' } }],
],
})
```
--------------------------------
### Usage with CDN Files
Source: https://github.com/simonbengtsson/jspdf-autotable/blob/main/README.md
Include jsPDF and the autotable plugin via CDN links in your HTML. Then, use the autoTable method directly on the jsPDF object.
```html
```
--------------------------------
### Apply Column Styles with jsPDF-AutoTable
Source: https://github.com/simonbengtsson/jspdf-autotable/blob/main/README.md
Demonstrates how to apply specific styles to columns, such as alignment and background color. The first column (index 0) is targeted for centering and a green background.
```javascript
autoTable(doc, {
styles: { fillColor: [255, 0, 0] },
columnStyles: { 0: { halign: 'center', fillColor: [0, 255, 0] } }, // Cells in first column centered and green
margin: { top: 10 },
body: [
['Sweden', 'Japan', 'Canada'],
['Norway', 'China', 'USA'],
['Denmark', 'China', 'Mexico'],
],
})
```
--------------------------------
### Create PDF Table from HTML Element
Source: https://github.com/simonbengtsson/jspdf-autotable/blob/main/examples/simple.html
This snippet shows how to generate a PDF table directly from an HTML table element using its ID. The '#table' selector targets the HTML element.
```javascript
doc.autoTable({ html: '#table' })
```
--------------------------------
### jsPDF-AutoTable Styling Options
Source: https://github.com/simonbengtsson/jspdf-autotable/blob/main/README.md
This section outlines the various styling options available for customizing tables, including themes, styles for different parts of the table (head, body, foot), alternate row styles, and column-specific styles.
```APIDOC
## Styling Options
### Description
Customize the appearance of your tables using a variety of styling options.
### Options
- `theme`: 'striped' | 'grid' | 'plain' (default: 'striped')
- `styles`: StyleDef - Global styles for the table.
- `headStyles`: StyleDef - Styles for the table header.
- `bodyStyles`: StyleDef - Styles for the table body.
- `footStyles`: StyleDef - Styles for the table footer.
- `alternateRowStyles`: StyleDef - Styles for alternating rows in the table body.
- `columnStyles`: { [columnDataKey: string | number]: StyleDef } - Styles specific to columns. `columnDataKey` can be the column index or its `dataKey` if defined.
### Style Definition (`StyleDef`)
- `font`: 'helvetica' | 'times' | 'courier' (default: 'helvetica')
- `fontStyle`: 'normal' | 'bold' | 'italic' | 'bolditalic' (default: 'normal')
- `overflow`: 'linebreak' | 'ellipsize' | 'visible' | 'hidden' (default: 'linebreak')
- `fillColor`: Color | null (default: null)
- `textColor`: Color | number (default: 20)
- `cellWidth`: 'auto' | 'wrap' | number (default: 'auto')
- `minCellWidth`: number (default: 10)
- `minCellHeight`: number (default: 0)
- `halign`: 'left' | 'center' | 'right' (default: 'left')
- `valign`: 'top' | 'middle' | 'bottom' (default: 'top')
- `fontSize`: number (default: 10)
- `cellPadding`: Padding | number (default: 10)
- `lineColor`: Color (default: 20)
- `lineWidth`: border | number (default: 0)
### Color Definition (`Color`)
- `false` (transparent)
- Hex string (e.g., '#FFFFFF')
- Gray level (0-255)
- RGB array (e.g., [255, 0, 0])
### Padding Definition (`Padding`)
- Number (uniform padding for all sides)
- Object: `{top: number, right: number, bottom: number, left: number}`
### Border Definition (`border`)
- Number (uniform border width for all sides)
- Object: `{top: number, right: number, bottom: number, left: number}`
### Style Overriding Order
1. Theme styles
2. `styles`
3. `headStyles`, `bodyStyles`, `footStyles`
4. `alternateRowStyles`
5. `columnStyles`
### Example Usage
```javascript
// Example with columnStyles
autoTable(doc, {
styles: { fillColor: [255, 0, 0] },
columnStyles: { 0: { halign: 'center', fillColor: [0, 255, 0] } }, // First column centered and green
margin: { top: 10 },
body: [
['Sweden', 'Japan', 'Canada'],
['Norway', 'China', 'USA'],
['Denmark', 'China', 'Mexico'],
],
});
// Example with columns property and columnStyles
autoTable(doc, {
columnStyles: { europe: { halign: 'center' } }, // European countries centered
body: [
{ europe: 'Sweden', america: 'Canada', asia: 'China' },
{ europe: 'Norway', america: 'Mexico', asia: 'Japan' },
],
columns: [
{ header: 'Europe', dataKey: 'europe' },
{ header: 'Asia', dataKey: 'asia' },
],
});
```
```
--------------------------------
### Define Columns and Apply Styles in jsPDF-AutoTable
Source: https://github.com/simonbengtsson/jspdf-autotable/blob/main/README.md
Shows how to use the 'columns' property to define specific data keys and apply styles to columns based on these keys. The 'europe' column is centered.
```javascript
autoTable(doc, {
columnStyles: { europe: { halign: 'center' } }, // European countries centered
body: [
{ europe: 'Sweden', america: 'Canada', asia: 'China' },
{ europe: 'Norway', america: 'Mexico', asia: 'Japan' },
],
columns: [
{ header: 'Europe', dataKey: 'europe' },
{ header: 'Asia', dataKey: 'asia' },
],
})
```
--------------------------------
### Create PDF Table from JavaScript Data
Source: https://github.com/simonbengtsson/jspdf-autotable/blob/main/examples/simple.html
Use this snippet to generate a PDF table from a JavaScript array of data. Ensure jspdf and jspdf-autotable are included in your project.
```javascript
document.getElementById('create-btn').addEventListener('click', function () {
const doc = new jspdf.jsPDF()
// Simple data example
const head = [['ID', 'Country', 'Rank', 'Capital']]
const body = [
[1, 'Denmark', 7.526, 'Copenhagen'],
[2, 'Switzerland', 7.509, 'Bern'],
[3, 'Iceland', 7.501, 'Reykjavík'],
]
doc.autoTable({ head: head, body: body })
// Simple html example
doc.autoTable({ html: '#table' })
doc.save('table.pdf')
})
```
--------------------------------
### Update PDF Content
Source: https://github.com/simonbengtsson/jspdf-autotable/blob/main/index.html
This function updates the PDF content based on the current URL hash. It generates a PDF using the specified function (e.g., 'basic', 'minimal') and either saves it as a PDF file or sets it as the data for an iframe.
```javascript
function update(shouldDownload) {
const funcStr = window.location.hash.replace(/#/g, '') || 'basic';
const doc = window.examples[funcStr]();
doc.setProperties({
title: 'Example: ' + funcStr,
subject: 'A jspdf-autotable example pdf (' + funcStr + ')'
});
if (shouldDownload) {
doc.save('table.pdf');
} else {
//document.getElementById("output").src = doc.output('datauristring');
document.getElementById("output").data = doc.output('datauristring');
}
}
```
--------------------------------
### jsPDF-AutoTable Other Options
Source: https://github.com/simonbengtsson/jspdf-autotable/blob/main/README.md
This section covers additional configuration options for jsPDF-AutoTable, including layout, page breaking, and display preferences.
```APIDOC
## Other Options
### Description
Configure various aspects of table generation, including layout, page breaks, and display behavior.
### Options
- `useCss`: boolean (default: false) - Whether to use CSS styles (experimental).
- `startY`: number | null (default: null) - The Y-coordinate where the table should start on the first page.
- `margin`: Margin | number (default: 40) - Margin around the table. Can be a number or an object `{top, right, bottom, left}`.
- `pageBreak`: 'auto' | 'avoid' | 'always' (default: 'auto') - Controls how the table breaks across pages.
- `rowPageBreak`: 'auto' | 'avoid' (default: 'auto') - Controls how rows break across pages.
- `tableWidth`: 'auto' | 'wrap' | number (default: 'auto') - The width of the table.
- `showHead`: 'everyPage' | 'firstPage' | 'never' (default: 'everyPage') - When to display the table header.
- `showFoot`: 'everyPage' | 'lastPage' | 'never' (default: 'everyPage') - When to display the table footer.
- `tableLineWidth`: number (default: 0) - Line width for the table border.
- `tableLineColor`: Color (default: 200) - Color of the table border.
- `horizontalPageBreak`: boolean (default: false) - Enables splitting the table horizontally if it exceeds page width.
- `horizontalPageBreakRepeat`: string | number | string[] | number[] - Columns to repeat on horizontally split pages (requires `horizontalPageBreak: true`). Accepts column dataKeys or indexes.
- `horizontalPageBreakBehaviour`: 'immediately' | 'afterAllRows' (default: 'afterAllRows') - Behavior of horizontal page breaks.
### Margin Definition (`Margin`)
- Number (uniform margin for all sides)
- Object: `{top: number, right: number, bottom: number, left: number}`
### Color Definition (`Color`)
- `false` (transparent)
- Hex string (e.g., '#FFFFFF')
- Gray level (0-255)
- RGB array (e.g., [255, 0, 0])
```
--------------------------------
### Image to Base64 Conversion
Source: https://github.com/simonbengtsson/jspdf-autotable/blob/main/index.html
This utility function converts an image from a given source URL into a Base64 data URI. It handles both JPEG and PNG formats and is used for embedding images within the PDF.
```javascript
function imgToBase64(src, callback) {
const outputFormat = src.substr(-3) === 'png' ? 'image/png' : 'image/jpeg';
const img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function () {
const canvas = document.createElement('CANVAS');
const ctx = canvas.getContext('2d');
let dataURL;
canvas.height = this.naturalHeight;
canvas.width = this.naturalWidth;
ctx.drawImage(this, 0, 0);
dataURL = ctx.toDataURL(outputFormat);
callback(dataURL);
};
img.src = src;
if (img.complete || img.complete === undefined) {
img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
img.src = src;
}
}
```
--------------------------------
### Apply jsPDF-AutoTable Plugin Directly
Source: https://github.com/simonbengtsson/jspdf-autotable/blob/main/README.md
Apply the plugin to the jsPDF object to use the autoTable method directly on jsPDF instances. This is an alternative to the standalone autoTable function.
```javascript
import { jsPDF } from 'jspdf'
import { applyPlugin } from 'jspdf-autotable'
applyPlugin(jsPDF)
const doc = new jsPDF()
doc.autoTable({ html: '#my-table' })
doc.save('table.pdf')
```
--------------------------------
### Hooks for Customizing Table Drawing
Source: https://github.com/simonbengtsson/jspdf-autotable/blob/main/README.md
jsPDF-AutoTable provides several hooks that allow you to customize the content and styling of the table during the drawing process. These hooks are called at specific stages of cell and page rendering.
```APIDOC
## Hooks
You can customize the content and styling of the table by using the hooks. See the custom styles example for usage of the hooks.
- `didParseCell: (HookData) => {}` - Called when the plugin finished parsing cell content. Can be used to override content or styles for a specific cell.
- `willDrawCell: (HookData) => {}` - Called before a cell or row is drawn. Can be used to call native jspdf styling functions such as `doc.setTextColor` or change position of text etc before it is drawn.
- `didDrawCell: (HookData) => {}` - Called after a cell has been added to the page. Can be used to draw additional cell content such as images with `doc.addImage`, additional text with `doc.addText` or other jspdf shapes.
- `willDrawPage: (HookData) => {}` - Called before starting to draw on a page. Can be used to add headers or any other content that you want on each page there is an autotable.
- `didDrawPage: (HookData) => {}` - Called after the plugin has finished drawing everything on a page. Can be used to add footers with page numbers or any other content that you want on each page there is an autotable.
All hooks functions get passed an HookData object with information about the state of the table and cell. For example the position on the page, which page it is on etc.
`HookData`:
- `table: Table`
- `pageNumber: number` The page number specific to this table
- `settings: object` Parsed user supplied options
- `doc` The jsPDF document instance of this table
- `cursor: { x: number, y: number }` To draw each table this plugin keeps a cursor state where the next cell/row should be drawn. You can assign new values to this cursor to dynamically change how the cells and rows are drawn.
For cell hooks these properties are also passed:
- `cell: Cell`
- `row: Row`
- `column: Column`
- `section: 'head'|'body'|'foot'`
To see what is included in the `Table`, `Row`, `Column` and `Cell` types, either log them to the console or take a look at `src/models.ts`
```js
// Example with an image drawn in each cell in the first column
autoTable(doc, {
didDrawCell: (data) => {
if (data.section === 'body' && data.column.index === 0) {
const base64Img = 'data:image/jpeg;base64,iVBORw0KGgoAAAANS...' // Replace with actual base64 image
doc.addImage(base64Img, 'JPEG', data.cell.x + 2, data.cell.y + 2, 10, 10)
}
},
})
```
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.