UNPKG

12.2 kBMarkdownView Raw
1# jsPDF-AutoTable - Table plugin for jsPDF
2
3**Generate PDF tables with Javascript**
4
5This jsPDF plugin adds the ability to generate PDF tables either by parsing HTML tables or by using Javascript data directly. Check out the [demo](https://simonbengtsson.github.io/jsPDF-AutoTable/) or [examples](https://github.com/simonbengtsson/jsPDF-AutoTable/tree/master/examples).
6
7![sample javascript table pdf](samples.png)
8
9## Installation
10
11Get jsPDF and this plugin by doing one of these things:
12
13- `npm install jspdf jspdf-autotable`
14- Download [jspdf](https://raw.githubusercontent.com/MrRio/jsPDF/master/dist/jspdf.umd.min.js) and [jspdf-autotable](https://raw.githubusercontent.com/simonbengtsson/jsPDF-AutoTable/master/dist/jspdf.plugin.autotable.js) from github
15- Use a CDN, for example: [https://unpkg.com/jspdf](https://unpkg.com/jspdf) and [https://unpkg.com/jspdf-autotable](https://unpkg.com/jspdf-autotable)
16
17## Usage
18
19```js
20import jsPDF from 'jspdf'
21import autoTable from 'jspdf-autotable'
22
23const doc = new jsPDF()
24
25// It can parse html:
26// <table id="my-table"><!-- ... --></table>
27autoTable(doc, { html: '#my-table' })
28
29// Or use javascript directly:
30autoTable(doc, {
31 head: [['Name', 'Email', 'Country']],
32 body: [
33 ['David', 'david@example.com', 'Sweden'],
34 ['Castille', 'castille@example.com', 'Spain'],
35 // ...
36 ],
37})
38
39// Sometimes you might have to call the default function on the export (for example in Deno)
40autoTable.default(doc, { html: '#my-table' })
41
42doc.save('table.pdf')
43```
44
45You can also use the plugin methods directly on the jsPDF documents:
46
47```js
48import jsPDF from 'jspdf'
49import 'jspdf-autotable'
50
51const doc = new jsPDF()
52doc.autoTable({ html: '#my-table' })
53doc.save('table.pdf')
54```
55
56The third usage option is with downloaded or CDN dist files
57
58```html
59<script src="jspdf.min.js"></script>
60<script src="jspdf.plugin.autotable.min.js"></script>
61<script>
62 var doc = new jsPDF()
63 doc.autoTable({ html: '#my-table' })
64 doc.save('table.pdf')
65</script>
66```
67
68Checkout more examples in [examples.js](examples) which is also the source code for the [demo](https://simonbengtsson.github.io/jsPDF-AutoTable/) documents.
69
70## Options
71
72Below is a list of all options supported in the plugin. All of them are used in the [examples](examples).
73
74#### Content options
75
76The only thing required is either the html or body option. If you want more control over the columns you can specify the columns property. If columns are not set they will be automatically computed based on the content of the html content or head, body and foot.
77
78- `html: string|HTMLTableElement` A css selector (for example "#table") or an html table element.
79- `head: CellDef[][]` For example [['ID', 'Name', 'Country']]
80- `body: CellDef[][]` For example [['1', 'Simon', 'Sweden'], ['2', 'Karl', 'Norway']]
81- `foot: CellDef[][]` For example [['ID', 'Name', 'Country']]
82- `columns: ColumnDef[]` For example [{header: 'ID', dataKey: 'id'}, {header: 'Name', dataKey: 'name'}]. Only use this option if you want more control over the columns. If not specified the columns will be automatically generated based on the content in html or head/body/foot
83- `includeHiddenHtml: boolean = false` If hidden html with `display: none` should be included or not when the content comes from an html table
84
85`CellDef: string|{content: string, rowSpan: number, colSpan: number, styles: StyleDef}`
86Note that cell styles can also be set dynamically with hooks.
87
88`ColumnDef: string|{header?: string, dataKey: string}`
89The header property is optional and the values of any content in `head` will be used if not set. Normally it's easier to use the html or head/body/foot style of initiating a table, but columns can be useful if your body content comes directly from an api or if you would like to specify a dataKey on each column to make it more readable to style specific columns in the hooks or columnStyles.
90
91Usage with colspan, rowspan and inline cell styles:
92
93```js
94autoTable(doc, {
95 body: [
96 [{ content: 'Text', colSpan: 2, rowSpan: 2, styles: { halign: 'center' } }],
97 ],
98})
99```
100
101#### Styling options
102
103- `theme: 'striped'|'grid'|'plain' = 'striped'`
104- `styles: StyleDef`
105- `headStyles: StyleDef`
106- `bodyStyles: StyleDef`
107- `footStyles: StyleDef`
108- `alternateRowStyles: StyleDef`
109- `columnStyles: {&columnDataKey: StyleDef}` Note that the columnDataKey is normally the index of the column, but could also be the `dataKey` of a column if content initialized with the columns property
110
111`StyleDef`:
112
113- `font: 'helvetica'|'times'|'courier' = 'helvetica'`
114- `fontStyle: 'normal'|'bold'|'italic'|'bolditalic' = 'normal'`
115- `overflow: 'linebreak'|'ellipsize'|'visible'|'hidden' = 'linebreak'`
116- `fillColor: Color? = null`
117- `textColor: Color? = 20`
118- `cellWidth: 'auto'|'wrap'|number = 'auto'`
119- `minCellWidth: number? = 10`
120- `minCellHeight: number = 0`
121- `halign: 'left'|'center'|'right' = 'left'`
122- `valign: 'top'|'middle'|'bottom' = 'top'`
123- `fontSize: number = 10`
124- `cellPadding: Padding = 10`
125- `lineColor: Color = 10`
126- `lineWidth: border = 0` // If 0, no border is drawn
127
128`Color`:
129Either false for transparent, hex string, gray level 0-255 or rbg array e.g. [255, 0, 0]
130false|string|number|[number, number, number]
131
132`Padding`:
133Either a number or object `{top: number, right: number, bottom: number, left: number}`
134
135`border`:
136Either a number or object `{top: number, right: number, bottom: number, left: number}`
137
138Styles work similar to css and can be overridden by more specific styles. Overriding order:
139
1401. Theme styles
1412. `styles`
1423. `headStyles`, `bodyStyles` and `footStyles`
1434. `alternateRowStyles`
1445. `columnStyles`
145
146Styles for specific cells can also be applied using either the hooks (see hooks section above) or the `styles` property on the cell definition object (see content section above).
147
148Example usage of column styles (note that the 0 in the columnStyles below should be dataKey if columns option used)
149
150```js
151// Example usage with columnStyles,
152autoTable(doc, {
153 styles: { fillColor: [255, 0, 0] },
154 columnStyles: { 0: { halign: 'center', fillColor: [0, 255, 0] } }, // Cells in first column centered and green
155 margin: { top: 10 },
156 body: [
157 ['Sweden', 'Japan', 'Canada'],
158 ['Norway', 'China', 'USA'],
159 ['Denmark', 'China', 'Mexico'],
160 ],
161})
162
163// Example usage of columns property. Note that America will not be included even though it exist in the body since there is no column specified for it.
164autoTable(doc, {
165 columnStyles: { europe: { halign: 'center' } }, // European countries centered
166 body: [
167 { europe: 'Sweden', america: 'Canada', asia: 'China' },
168 { europe: 'Norway', america: 'Mexico', asia: 'Japan' },
169 ],
170 columns: [
171 { header: 'Europe', dataKey: 'europe' },
172 { header: 'Asia', dataKey: 'asia' },
173 ],
174})
175```
176
177#### Other options
178
179- `useCss: boolean = false`
180- `startY: number = null` Where the table should start to be printed (basically a margin top value only for the first page)
181- `margin: Margin = 40`
182- `pageBreak: 'auto'|'avoid'|'always'` If set to `avoid` the plugin will only split a table onto multiple pages if table height is larger than page height.
183- `rowPageBreak: 'auto'|'avoid' = 'auto'` If set to `avoid` the plugin will only split a row onto multiple pages if row height is larger than page height.
184- `tableWidth: 'auto'|'wrap'|number = 'auto'`
185- `showHead: 'everyPage'|'firstPage'|'never' = 'everyPage''`
186- `showFoot: 'everyPage'|'lastPage'|'never' = 'everyPage''`
187- `tableLineWidth: number = 0`
188- `tableLineColor: Color = 200` The table line/border color
189- `horizontalPageBreak: boolean = false` To split/break the table into multiple pages if the given table width exceeds the page width
190- `horizontalPageBreakRepeat: string|number|string[]|number[]` To repeat the given column in the split pages, works when `horizontalPageBreak = true`. The accepted values are column dataKeys, such as `'id'`, `recordId` or column indexes, such as `0`, `1` or array for multiple columns.
191- `horizontalPageBreakBehaviour: 'immediately'|'afterAllRows' = 'afterAllRows'` How the horizontal page breaks behave, works when `horizontalPageBreak = true`
192
193`Margin`:
194Either a number or object `{top: number, right: number, bottom: number, left: number}`
195
196### Hooks
197
198You can customize the content and styling of the table by using the hooks. See the custom styles example for usage of the hooks.
199
200- `didParseCell: (HookData) => {}` - Called when the plugin finished parsing cell content. Can be used to override content or styles for a specific cell.
201- `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.
202- `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.
203- `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.
204- `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.
205
206All 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.
207
208`HookData`:
209
210- `table: Table`
211- `pageNumber: number` The page number specific to this table
212- `settings: object` Parsed user supplied options
213- `doc` The jsPDF document instance of this table
214- `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.
215
216For cell hooks these properties are also passed:
217
218- `cell: Cell`
219- `row: Row`
220- `column: Column`
221- `section: 'head'|'body'|'foot'`
222
223To 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`
224
225```js
226// Example with an image drawn in each cell in the first column
227autoTable(doc, {
228 didDrawCell: (data) => {
229 if (data.section === 'body' && data.column.index === 0) {
230 var base64Img = 'data:image/jpeg;base64,iVBORw0KGgoAAAANS...'
231 doc.addImage(base64Img, 'JPEG', data.cell.x + 2, data.cell.y + 2, 10, 10)
232 }
233 },
234})
235```
236
237## API
238
239- `doc.autoTable({ /* options */ })`
240- `autoTable(doc, { /* options */ })`
241- `jsPDF.autoTableSetDefaults({ /* ... */ })` Use for setting global defaults which will be applied for all tables
242
243If 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.
244
245In addition to the exported autoTable(doc, options) method you can also use applyPlugin to add the autoTable api to any jsPDF instance.
246
247```
248import jsPDF from 'jspdf/dist/jspdf.node.debug'
249import { applyPlugin } from 'jspdf-autotable'
250applyPlugin(jsPDF)
251```
252
253## Contributions
254
255Contributions are always welcome, especially on open issues. If you have something major you want to add or change, please post an issue about it first to discuss it further. The workflow for contributing would be something like this:
256
257- Start watcher with `npm start`
258- Make code changes
259- Make sure all examples works
260- Commit and submit pull request
261
262**If you don't use [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) on autosave, please run `yarn run format-all` before opening your PR**
263
264### Release workflow
265
266- Run Release workflow on github (or run `npm version <semver>` and npm run deploy)
267- Verify release at https://simonbengtsson.github.io/jsPDF-AutoTable
268
269### Pull requests locally
270
271- `PR=472 npm run checkout-pr`
272
273### Release prerelease
274
275- `npm version prerelease`
276- `git push && git push --tags && npm publish --tag alpha`