@marcusumn/html2pdf.js 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License
2
+
3
+ Copyright (c) 2017 Erik Koopmans
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,304 @@
1
+ # html2pdf.js
2
+
3
+ html2pdf.js converts any webpage or element into a printable PDF entirely client-side using [html2canvas](https://github.com/niklasvh/html2canvas) and [jsPDF](https://github.com/MrRio/jsPDF).
4
+
5
+ ## Table of contents
6
+
7
+ - [Getting started](#getting-started)
8
+ - [CDN](#cdn)
9
+ - [Raw JS](#raw-js)
10
+ - [NPM](#npm)
11
+ - [Bower](#bower)
12
+ - [Console](#console)
13
+ - [Usage](#usage)
14
+ - [Advanced usage](#advanced-usage)
15
+ - [Workflow](#workflow)
16
+ - [Worker API](#worker-api)
17
+ - [Options](#options)
18
+ - [Page-breaks](#page-breaks)
19
+ - [Page-break settings](#page-break-settings)
20
+ - [Page-break modes](#page-break-modes)
21
+ - [Example usage](#example-usage)
22
+ - [Image type and quality](#image-type-and-quality)
23
+ - [Progress tracking](#progress-tracking)
24
+ - [Dependencies](#dependencies)
25
+ - [Contributing](#contributing)
26
+ - [Issues](#issues)
27
+ - [Tests](#tests)
28
+ - [Pull requests](#pull-requests)
29
+ - [Credits](#credits)
30
+ - [License](#license)
31
+
32
+ ## Getting started
33
+
34
+ #### CDN
35
+
36
+ The simplest way to use html2pdf.js is to include it as a script in your HTML by using cdnjs:
37
+
38
+ ```html
39
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js" integrity="sha512-GsLlZN/3F2ErC5ifS5QtgpiJtWd43JWSuIgh7mbzZ8zBps+dvLusV+eNQATqgA/HdeKFVgA5v3S/cIrLF7QnIg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
40
+ ```
41
+
42
+ Using a CDN URL will lock you to a specific version, which should ensure stability and give you control over when to change versions. cdnjs gives you access to [all past versions of html2pdf.js](https://cdnjs.com/libraries/html2pdf.js).
43
+
44
+ *Note: [Read about dependencies](#dependencies) for more information about using the unbundled version `dist/html2canvas.min.js`.*
45
+
46
+ #### Raw JS
47
+
48
+ You may also download `dist/html2pdf.bundle.min.js` directly to your project folder and include it in your HTML with:
49
+
50
+ ```html
51
+ <script src="html2pdf.bundle.min.js"></script>
52
+ ```
53
+
54
+ #### NPM
55
+
56
+ Install html2pdf.js and its dependencies using NPM with `npm install --save html2pdf.js` (make sure to include `.js` in the package name).
57
+
58
+ *Note: You can use NPM to create your project, but html2pdf.js **will not run in Node.js**, it must be run in a browser.*
59
+
60
+ #### Bower
61
+
62
+ Install html2pdf.js and its dependencies using Bower with `bower install --save html2pdf.js` (make sure to include `.js` in the package name).
63
+
64
+ #### Console
65
+
66
+ If you're on a webpage that you can't modify directly and wish to use html2pdf.js to capture a screenshot, you can follow these steps:
67
+
68
+ 1. Open your browser's console (instructions for different browsers [here](https://webmasters.stackexchange.com/a/77337/94367)).
69
+ 2. Paste in this code:
70
+ ```js
71
+ function addScript(url) {
72
+ var script = document.createElement('script');
73
+ script.type = 'application/javascript';
74
+ script.src = url;
75
+ document.head.appendChild(script);
76
+ }
77
+ addScript('https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js');
78
+ ```
79
+ 3. You may now execute html2pdf.js commands directly from the console. To capture a default PDF of the entire page, use `html2pdf(document.body)`.
80
+
81
+ ## Usage
82
+
83
+ Once installed, html2pdf.js is ready to use. The following command will generate a PDF of `#element-to-print` and prompt the user to save the result:
84
+
85
+ ```js
86
+ var element = document.getElementById('element-to-print');
87
+ html2pdf(element);
88
+ ```
89
+
90
+ ### Advanced usage
91
+
92
+ Every step of html2pdf.js is configurable, using its new Promise-based API. If html2pdf.js is called without arguments, it will return a `Worker` object:
93
+
94
+ ```js
95
+ var worker = html2pdf(); // Or: var worker = new html2pdf.Worker;
96
+ ```
97
+
98
+ This worker has methods that can be chained sequentially, as each Promise resolves, and allows insertion of your own intermediate functions between steps. A prerequisite system allows you to skip over mandatory steps (like canvas creation) without any trouble:
99
+
100
+ ```js
101
+ // This will implicitly create the canvas and PDF objects before saving.
102
+ var worker = html2pdf().from(element).save();
103
+ ```
104
+
105
+ #### Workflow
106
+
107
+ The basic workflow of html2pdf.js tasks (enforced by the prereq system) is:
108
+
109
+ ```
110
+ .from() -> .toContainer() -> .toCanvas() -> .toImg() -> .toPdf() -> .save()
111
+ ```
112
+
113
+ #### Worker API
114
+
115
+ | Method | Arguments | Description |
116
+ |--------------|--------------------|-------------|
117
+ | from | src, type | Sets the source (HTML string or element) for the PDF. Optional `type` specifies other sources: `'string'`, `'element'`, `'canvas'`, or `'img'`. |
118
+ | to | target | Converts the source to the specified target (`'container'`, `'canvas'`, `'img'`, or `'pdf'`). Each target also has its own `toX` method that can be called directly: `toContainer()`, `toCanvas()`, `toImg()`, and `toPdf()`. |
119
+ | output | type, options, src | Routes to the appropriate `outputPdf` or `outputImg` method based on specified `src` (`'pdf'` (default) or `'img'`). |
120
+ | outputPdf | type, options | Sends `type` and `options` to the jsPDF object's `output` method, and returns the result as a Promise (use `.then` to access). See the [jsPDF source code](https://rawgit.com/MrRio/jsPDF/master/docs/jspdf.js.html#line992) for more info. |
121
+ | outputImg | type, options | Returns the specified data type for the image as a Promise (use `.then` to access). Supported types: `'img'`, `'datauristring'`/`'dataurlstring'`, and `'datauri'`/`'dataurl'`. |
122
+ | save | filename | Saves the PDF object with the optional filename (creates user download prompt). |
123
+ | set | opt | Sets the specified properties. See [Options](#options) below for more details. |
124
+ | get | key, cbk | Returns the property specified in `key`, either as a Promise (use `.then` to access), or by calling `cbk` if provided. |
125
+ | then | onFulfilled, onRejected | Standard Promise method, with `this` re-bound to the Worker, and with added progress-tracking (see [Progress](#progress) below). Note that `.then` returns a `Worker`, which is a subclass of Promise. |
126
+ | thenCore | onFulFilled, onRejected | Standard Promise method, with `this` re-bound to the Worker (no progress-tracking). Note that `.thenCore` returns a `Worker`, which is a subclass of Promise. |
127
+ | thenExternal | onFulfilled, onRejected | True Promise method. Using this 'exits' the Worker chain - you will not be able to continue chaining Worker methods after `.thenExternal`. |
128
+ | catch, catchExternal | onRejected | Standard Promise method. `catchExternal` exits the Worker chain - you will not be able to continue chaining Worker methods after `.catchExternal`. |
129
+ | error | msg | Throws an error in the Worker's Promise chain. |
130
+
131
+ A few aliases are also provided for convenience:
132
+
133
+ | Method | Alias |
134
+ |-----------|-----------|
135
+ | save | saveAs |
136
+ | set | using |
137
+ | output | export |
138
+ | then | run |
139
+
140
+ ## Options
141
+
142
+ html2pdf.js can be configured using an optional `opt` parameter:
143
+
144
+ ```js
145
+ var element = document.getElementById('element-to-print');
146
+ var opt = {
147
+ margin: 1,
148
+ filename: 'myfile.pdf',
149
+ image: { type: 'jpeg', quality: 0.98 },
150
+ html2canvas: { scale: 2 },
151
+ jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
152
+ };
153
+
154
+ // New Promise-based usage:
155
+ html2pdf().set(opt).from(element).save();
156
+
157
+ // Old monolithic-style usage:
158
+ html2pdf(element, opt);
159
+ ```
160
+
161
+ The `opt` parameter has the following optional fields:
162
+
163
+ |Name |Type |Default |Description |
164
+ |------------|----------------|--------------------------------|------------------------------------------------------------------------------------------------------------|
165
+ |margin |number or array |`0` |PDF margin (in jsPDF units). Can be a single number, `[vMargin, hMargin]`, or `[top, left, bottom, right]`. |
166
+ |filename |string |`'file.pdf'` |The default filename of the exported PDF. |
167
+ |pagebreak |object |`{mode: ['css', 'legacy']}` |Controls the pagebreak behaviour on the page. See [Page-breaks](#page-breaks) below. |
168
+ |image |object |`{type: 'jpeg', quality: 0.95}` |The image type and quality used to generate the PDF. See [Image type and quality](#image-type-and-quality) below.|
169
+ |enableLinks |boolean |`true` |If enabled, PDF hyperlinks are automatically added ontop of all anchor tags. |
170
+ |html2canvas |object |`{ }` |Configuration options sent directly to `html2canvas` ([see here](https://html2canvas.hertzen.com/configuration) for usage).|
171
+ |jsPDF |object |`{ }` |Configuration options sent directly to `jsPDF` ([see here](http://rawgit.com/MrRio/jsPDF/master/docs/jsPDF.html) for usage).|
172
+
173
+ ### Page-breaks
174
+
175
+ html2pdf.js has the ability to automatically add page-breaks to clean up your document. Page-breaks can be added by CSS styles, set on individual elements using selectors, or avoided from breaking inside all elements (`avoid-all` mode).
176
+
177
+ By default, html2pdf.js will respect most CSS [`break-before`](https://developer.mozilla.org/en-US/docs/Web/CSS/break-before), [`break-after`](https://developer.mozilla.org/en-US/docs/Web/CSS/break-after), and [`break-inside`](https://developer.mozilla.org/en-US/docs/Web/CSS/break-inside) rules, and also add page-breaks after any element with class `html2pdf__page-break` (for legacy purposes).
178
+
179
+ #### Page-break settings
180
+
181
+ |Setting |Type |Default |Description |
182
+ |----------|----------------|--------------------|------------|
183
+ |mode |string or array |`['css', 'legacy']` |The mode(s) on which to automatically add page-breaks. One or more of `'avoid-all'`, `'css'`, and `'legacy'`. |
184
+ |before |string or array |`[]` |CSS selectors for which to add page-breaks before each element. Can be a specific element with an ID (`'#myID'`), all elements of a type (e.g. `'img'`), all of a class (`'.myClass'`), or even `'*'` to match every element. |
185
+ |after |string or array |`[]` |Like 'before', but adds a page-break immediately after the element. |
186
+ |avoid |string or array |`[]` |Like 'before', but avoids page-breaks on these elements. You can enable this feature on every element using the 'avoid-all' mode. |
187
+
188
+ #### Page-break modes
189
+
190
+ | Mode | Description |
191
+ |-----------|-------------|
192
+ | avoid-all | Automatically adds page-breaks to avoid splitting any elements across pages. |
193
+ | css | Adds page-breaks according to the CSS `break-before`, `break-after`, and `break-inside` properties. Only recognizes `always/left/right` for before/after, and `avoid` for inside. |
194
+ | legacy | Adds page-breaks after elements with class `html2pdf__page-break`. This feature may be removed in the future. |
195
+
196
+ #### Example usage
197
+
198
+ ```js
199
+ // Avoid page-breaks on all elements, and add one before #page2el.
200
+ html2pdf().set({
201
+ pagebreak: { mode: 'avoid-all', before: '#page2el' }
202
+ });
203
+
204
+ // Enable all 'modes', with no explicit elements.
205
+ html2pdf().set({
206
+ pagebreak: { mode: ['avoid-all', 'css', 'legacy'] }
207
+ });
208
+
209
+ // No modes, only explicit elements.
210
+ html2pdf().set({
211
+ pagebreak: { before: '.beforeClass', after: ['#after1', '#after2'], avoid: 'img' }
212
+ });
213
+ ```
214
+
215
+ ### Image type and quality
216
+
217
+ You may customize the image type and quality exported from the canvas by setting the `image` option. This must be an object with the following fields:
218
+
219
+ |Name |Type |Default |Description |
220
+ |------------|----------------|------------------------------|---------------------------------------------------------------------------------------------|
221
+ |type |string |'jpeg' |The image type. HTMLCanvasElement only supports 'png', 'jpeg', and 'webp' (on Chrome). |
222
+ |quality |number |0.95 |The image quality, from 0 to 1. This setting is only used for jpeg/webp (not png). |
223
+
224
+ These options are limited to the available settings for [HTMLCanvasElement.toDataURL()](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL), which ignores quality settings for 'png' images. To enable png image compression, try using the [canvas-png-compression shim](https://github.com/ShyykoSerhiy/canvas-png-compression), which should be an in-place solution to enable png compression via the `quality` option.
225
+
226
+ ## Progress tracking
227
+
228
+ The Worker object returned by `html2pdf()` has a built-in progress-tracking mechanism. It will be updated to allow a progress callback that will be called with each update, however it is currently a work-in-progress.
229
+
230
+ ## Dependencies
231
+
232
+ html2pdf.js depends on the external packages [html2canvas](https://github.com/niklasvh/html2canvas) and [jsPDF](https://github.com/MrRio/jsPDF). These dependencies are automatically loaded when using NPM or the bundled package.
233
+
234
+ If using the unbundled `dist/html2pdf.min.js` (or its un-minified version), you must also include each dependency. Order is important, otherwise html2canvas will be overridden by jsPDF's own internal implementation:
235
+
236
+ ```html
237
+ <script src="jspdf.min.js"></script>
238
+ <script src="html2canvas.min.js"></script>
239
+ <script src="html2pdf.min.js"></script>
240
+ ```
241
+
242
+ ## Contributing
243
+
244
+ > [!TIP]
245
+ > Working on html2pdf.js locally? Use `npm start` to host local demos on http://localhost:8000.
246
+
247
+ ### Issues
248
+
249
+ When submitting an issue, please provide reproducible code that highlights the issue, preferably by creating a fork of [this template jsFiddle](https://jsfiddle.net/u6o6ne41/) (which has html2pdf.js already loaded). Remember that html2pdf.js uses [html2canvas](https://github.com/niklasvh/html2canvas) and [jsPDF](https://github.com/MrRio/jsPDF) as dependencies, so it's a good idea to check each of those repositories' issue trackers to see if your problem has already been addressed.
250
+
251
+ #### Known issues
252
+
253
+ 1. **Rendering:** The rendering engine html2canvas isn't perfect (though it's pretty good!). If html2canvas isn't rendering your content correctly, I can't fix it.
254
+ - You can test this with something like [this fiddle](https://jsfiddle.net/eKoopmans/z1rupL4c/), to see if there's a problem in the canvas creation itself.
255
+
256
+ 2. **Node cloning (CSS etc):** The way html2pdf.js clones your content before sending to html2canvas is buggy. A fix is currently being developed - try out:
257
+ - direct file: Go to [html2pdf.js/bugfix/clone-nodes-BUILD](/eKoopmans/html2pdf.js/tree/bugfix/clone-nodes-BUILD) and replace the files in your project with the relevant files (e.g. `dist/html2pdf.bundle.js`)
258
+ - npm: `npm install eKoopmans/html2pdf.js#bugfix/clone-nodes-BUILD`
259
+ - Related project: [Bugfix: Cloned nodes](https://github.com/eKoopmans/html2pdf.js/projects/9)
260
+
261
+ 3. **Resizing:** Currently, html2pdf.js resizes the root element to fit onto a PDF page (causing internal content to "reflow").
262
+ - This is often desired behaviour, but not always.
263
+ - There are plans to add alternate behaviour (e.g. "shrink-to-page"), but nothing that's ready to test yet.
264
+ - Related project: [Feature: Single-page PDFs](https://github.com/eKoopmans/html2pdf.js/projects/1)
265
+
266
+ 4. **Rendered as image:** html2pdf.js renders all content into an image, then places that image into a PDF.
267
+ - This means text is *not selectable or searchable*, and causes large file sizes.
268
+ - This is currently unavoidable, however recent improvements in jsPDF mean that it may soon be possible to render straight into vector graphics.
269
+ - Related project: [Feature: New renderer](https://github.com/eKoopmans/html2pdf.js/projects/4)
270
+
271
+ 5. **Promise clashes:** html2pdf.js relies on specific Promise behaviour, and can fail when used with custom Promise libraries.
272
+ - Related project: [Bugfix: Sandboxed promises](https://github.com/eKoopmans/html2pdf.js/projects/11)
273
+
274
+ 6. **Maximum size:** HTML5 canvases have a [maximum height/width](https://stackoverflow.com/a/11585939/4080966). Anything larger will fail to render.
275
+ - This is a limitation of HTML5 itself, and results in large PDFs rendering completely blank in html2pdf.js.
276
+ - The jsPDF canvas renderer (mentioned in Known Issue #4) may be able to fix this issue!
277
+ - Related project: [Bugfix: Maximum canvas size](https://github.com/eKoopmans/html2pdf.js/projects/5)
278
+
279
+ ### Tests
280
+
281
+ html2pdf.js performs automatic vdiff (visual difference) comparisons on PDFs generated from a collection of sample HTML files. Contributions of additional test cases are more than welcome - see `test/vdiff/html2pdf.vdiff.js` and `test/reference/*.html` for examples. Some changes may require adding more options to the test harness, `test/util/test-harness.js`.
282
+
283
+ ### Pull requests
284
+
285
+ If you want to create a new feature or bugfix, please feel free to fork and submit a pull request! Create a fork, branch off of `main`, and make changes to the `/src/` files (rather than directly to `/dist/`). You can test your changes by rebuilding with `npm run build`.
286
+
287
+ ## Credits
288
+
289
+ [Erik Koopmans](https://github.com/eKoopmans)
290
+
291
+ #### Contributors
292
+
293
+ - [@WilcoBreedt](https://github.com/WilcoBreedt)
294
+ - [@Ranger1230](https://github.com/Ranger1230)
295
+
296
+ #### Special thanks
297
+
298
+ - [Sauce Labs](https://saucelabs.com/) for unit testing.
299
+
300
+ ## License
301
+
302
+ [The MIT License](http://opensource.org/licenses/MIT)
303
+
304
+ Copyright (c) 2017-2019 Erik Koopmans <[http://www.erik-koopmans.com/](http://www.erik-koopmans.com/)>