UNPKG

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