UNPKG

11.3 kBMarkdownView Raw
1Take the [developer survey](https://forms.gle/PRTF4byf39HtatBu9)!
2
3# AutoTable - Table plugin for jsPDF
4
5**Generate PDF tables with Javascript**
6
7This jsPDF plugin aims at making it easy to generate pdf tables either from HTML or directly from Javascript. Check out the [demo](https://simonbengtsson.github.io/jsPDF-AutoTable/) or [examples](https://github.com/simonbengtsson/jsPDF-AutoTable/tree/master/examples).
8
9![sample javascript table pdf](samples.png)
10
11## Installation
12
13Get the library by doing one of these things:
14
15- `npm install jspdf jspdf-autotable`
16- Download [jspdf](https://raw.githubusercontent.com/MrRio/jsPDF/master/dist/jspdf.min.js) and [jspdf-autotable](https://raw.githubusercontent.com/simonbengtsson/jsPDF-AutoTable/master/dist/jspdf.plugin.autotable.js) from github
17- Use a CDN, for example: [https://unpkg.com/jspdf](https://unpkg.com/jspdf) and [https://unpkg.com/jspdf-autotable](https://unpkg.com/jspdf-autotable)
18
19## Usage
20
21```html
22<table id="my-table">
23 <!-- ... -->
24</table>
25
26<script src="jspdf.min.js"></script>
27<script src="jspdf.plugin.autotable.min.js"></script>
28
29<script>
30 var doc = new jsPDF()
31 // It can parse html:
32 doc.autoTable({ html: '#my-table' })
33
34 // Or use javascript directly:
35 doc.autoTable({
36 head: [['Name', 'Email', 'Country']],
37 body: [
38 ['David', 'david@example.com', 'Sweden'],
39 ['Castille', 'castille@example.com', 'Norway'],
40 // ...
41 ],
42 })
43
44 doc.save('table.pdf')
45</script>
46```
47
48Or if using javascript modules and es6:
49
50```js
51import jsPDF from 'jspdf'
52import 'jspdf-autotable'
53
54const doc = new jsPDF()
55doc.autoTable({ html: '#my-table' })
56doc.save('table.pdf')
57```
58
59Checkout [this example](examples/nodejs/index.js) for nodejs usage
60
61Checkout more examples in [examples.js](examples) which is also the source code for the [demo](https://simonbengtsson.github.io/jsPDF-AutoTable/) documents.
62
63## API
64
65- `doc.autoTable({ /* options */ })`
66- `doc.autoTableSetDefaults({ /* ... */ })` Use for setting default options for all tables in the specific document. Settings and styles will be overridden in the following order `global` < `document` < `table`. Hooks will be added and not overridden.
67- `jsPDF.autoTableSetDefaults({ /* ... */ })` Use for setting global defaults which will be applied for all document and tabels.
68
69If 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.
70
71If you for example are using nodejs and want to use the nodejs jspdf dist files you can apply the plugin to any
72jsPDF class like this
73
74```
75import jsPDF from 'jspdf/dist/jspdf.node.debug'
76import { applyPlugin } from 'jspdf-autotable'
77applyPlugin(jsPDF)
78```
79
80## Options
81
82Below is a list of all options supported in the plugin. All of them are used in the [examples](examples).
83
84#### Content options
85
86The only thing required is either the html or body option. If you want more control over the columns you can specify the columns property. It is not needed however and if not set the columns will be automatically computed based on the content of the html content or head, body and foot.
87
88- `html: string|HTMLTableElement` A css selector (for example "#table") or an html table element.
89- `head: CellDef[][]` For example [['ID', 'Name', 'Country']]
90- `body: CellDef[][]` For example [['1', 'Simon', 'Sweden'], ['2', 'Karl', 'Norway']]
91- `foot: CellDef[][]` For example [['ID', 'Name', 'Country']]
92- `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
93- `includeHiddenHtml: boolean = false` If hidden html with `display: none` should be included or not when the content comes from an html table
94
95`CellDef: string|{content: string, rowSpan: number, colSpan: number, styles: StyleDef}`
96Note that cell styles can also be set dynamically with hooks.
97
98`ColumnDef: string|{header?: string, dataKey: string}`
99The 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.
100
101Usage with colspan, rowspan and inline cell styles:
102
103```js
104doc.autoTable({
105 body: [
106 [{ content: 'Text', colSpan: 2, rowSpan: 2, styles: { halign: 'center' } }],
107 ],
108})
109```
110
111#### Styling options
112
113- `theme: 'striped'|'grid'|'plain'|'css' = 'striped'`
114- `styles: StyleDef`
115- `headStyles: StyleDef`
116- `bodyStyles: StyleDef`
117- `footStyles: StyleDef`
118- `alternateRowStyles: StyleDef`
119- `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
120
121`StyleDef`:
122
123- `font: 'helvetica'|'times'|'courier' = 'helvetica'`
124- `fontStyle: 'normal'|'bold'|'italic'|'bolditalic' = 'normal'`
125- `overflow: 'linebreak'|'ellipsize'|'visible'|'hidden' = 'normal'`
126- `fillColor: Color? = null`
127- `textColor: Color? = 20`
128- `cellWidth: 'auto'|'wrap'|number = 'auto'`
129- `minCellWidth: number? = 10`
130- `minCellHeight: number = 0`
131- `halign: 'left'|'center'|'right' = 'left'`
132- `valign: 'top'|'middle'|'bottom' = 'top'`
133- `fontSize: number = 10`
134- `cellPadding: Padding = 10`
135- `lineColor: Color = 10`
136- `lineWidth: number = 0` // If 0, no border is drawn
137
138`Color`:
139Either false for transparent, rbg array e.g. [255, 0, 0] or gray level e.g 200
140
141`Padding`:
142Either a number or object `{top: number, right: number, bottom: number, left: number}`
143
144Styles work similar to css and can be overridden by more specific styles. Overriding order:
145
1461. Theme styles
1472. `styles`
1483. `headStyles`, `bodyStyles` and `footStyles`
1494. `alternateRowStyles`
1505. `columnStyles`
151
152Styles 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).
153
154Example usage of column styles (note that the 0 in the columnStyles below should be dataKey if )
155
156```js
157// Example usage with columnStyles,
158doc.autoTable({
159 styles: { fillColor: [255, 0, 0] },
160 columnStyles: { 0: { halign: 'center', fillColor: [0, 255, 0] } }, // Cells in first column centered and green
161 margin: { top: 10 },
162 body: [
163 ['Sweden', 'Japan', 'Canada'],
164 ['Norway', 'China', 'USA'],
165 ['Denmark', 'China', 'Mexico'],
166 ],
167})
168
169// 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.
170doc.autoTable({
171 columnStyles: { europe: { halign: 'center' } }, // European countries centered
172 body: [
173 { europe: 'Sweden', america: 'Canada', asia: 'China' },
174 { europe: 'Norway', america: 'Mexico', asia: 'Japan' },
175 ],
176 columns: [
177 { header: 'Europe', dataKey: 'europe' },
178 { header: 'Asia', dataKey: 'asia' },
179 ],
180})
181```
182
183#### Other options
184
185- `startY: number = null` Where the table should start to be printed (basically a margin top value only for the first page)
186- `margin: Margin = 40`
187- `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.
188- `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.
189- `tableWidth: 'auto'|'wrap'|number = 'auto'`
190- `showHead: 'everyPage'|'firstPage'|'never' = 'everyPage''`
191- `showFoot: 'everyPage'|'lastPage'|'never' = 'everyPage''`
192- `tableLineWidth: number = 0`
193- `tableLineColor: Color = 200` The table line/border color
194
195`Margin`:
196Either a number or object `{top: number, right: number, bottom: number, left: number}`
197
198### Hooks
199
200You can customize the content and styling of the table by using the hooks. See the custom styles example for usage of the hooks.
201
202- `didParseCell: (HookData) => {}` - Called when the plugin finished parsing cell content. Can be used to override content or styles for a specific cell.
203- `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.
204- `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.
205- `didDrawPage: (HookData) => {}` - Called after the plugin has finished drawing everything on a page. Can be used to add headers and footers with page numbers or any other content that you want on each page there is an autotable.
206
207All 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.
208
209`HookData`:
210
211- `table: Table`
212- `pageNumber: number` The page number specific to this table
213- `settings: object` Parsed user supplied options
214- `doc` The jsPDF document instance of this table
215- `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.
216
217For cell hooks these properties are also passed:
218
219- `cell: Cell`
220- `row: Row`
221- `column: Column`
222- `section: 'head'|'body'|'foot'`
223
224To 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`
225
226```js
227// Example with an image drawn in each cell in the first column
228doc.autoTable({
229 didDrawCell: data => {
230 if (data.section === 'body' && data.column.index === 0) {
231 var base64Img = 'data:image/jpeg;base64,iVBORw0KGgoAAAANS...'
232 doc.addImage(base64Img, 'JPEG', data.cell.x + 2, data.cell.y + 2, 10, 10)
233 }
234 },
235})
236```
237
238## Contributions
239
240Contributions 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:
241
242- Start watcher with `npm start`
243- Make code changes
244- Make sure all examples works
245- Commit and submit pull request
246
247**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**
248
249### Release workflow (write access required)
250
251- `npm version <semver|major|minor|patch>`
252- `npm run deploy`
253- Verify release at https://simonbengtsson.github.io/jsPDF-AutoTable
254
255### Pull requests locally
256
257- `git fetch origin pull/478/head:pr478`
258- `git checkout pr478`
259
260### Release prerelease
261
262- `npm version prerelease`
263- `git push && git push --tags && npm publish --tag alpha`