first commit

This commit is contained in:
2026-07-19 03:44:35 +09:00
commit 7f950339ae
23281 changed files with 3217138 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
The MIT License
Copyright (c) 2017 Erik Koopmans
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+305
View File
@@ -0,0 +1,305 @@
# html2pdf.js
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).
> :warning: There have been several issues reported in v0.10. They are being investigated but in the meantime you may wish to remain on v0.9.3 ("^0.9.3" in npm, or [use cdnjs for HTML script tags](https://cdnjs.com/libraries/html2pdf.js/0.9.3)).
## Table of contents
- [Getting started](#getting-started)
- [CDN](#cdn)
- [Raw JS](#raw-js)
- [NPM](#npm)
- [Bower](#bower)
- [Console](#console)
- [Usage](#usage)
- [Advanced usage](#advanced-usage)
- [Workflow](#workflow)
- [Worker API](#worker-api)
- [Options](#options)
- [Page-breaks](#page-breaks)
- [Page-break settings](#page-break-settings)
- [Page-break modes](#page-break-modes)
- [Example usage](#example-usage)
- [Image type and quality](#image-type-and-quality)
- [Progress tracking](#progress-tracking)
- [Dependencies](#dependencies)
- [Contributing](#contributing)
- [Issues](#issues)
- [Tests](#tests)
- [Pull requests](#pull-requests)
- [Credits](#credits)
- [License](#license)
## Getting started
#### CDN
The simplest way to use html2pdf.js is to include it as a script in your HTML by using cdnjs:
```html
<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>
```
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).
*Note: [Read about dependences](#dependencies) for more information about using the unbundled version `dist/html2canvas.min.js`.*
#### Raw JS
You may also download `dist/html2pdf.bundle.min.js` directly to your project folder and include it in your HTML with:
```html
<script src="html2pdf.bundle.min.js"></script>
```
#### NPM
Install html2pdf.js and its dependencies using NPM with `npm install --save html2pdf.js` (make sure to include `.js` in the package name).
*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.*
#### Bower
Install html2pdf.js and its dependencies using Bower with `bower install --save html2pdf.js` (make sure to include `.js` in the package name).
#### Console
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:
1. Open your browser's console (instructions for different browsers [here](https://webmasters.stackexchange.com/a/77337/94367)).
2. Paste in this code:
```js
function addScript(url) {
var script = document.createElement('script');
script.type = 'application/javascript';
script.src = url;
document.head.appendChild(script);
}
addScript('https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js');
```
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)`.
## Usage
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:
```js
var element = document.getElementById('element-to-print');
html2pdf(element);
```
### Advanced usage
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:
```js
var worker = html2pdf(); // Or: var worker = new html2pdf.Worker;
```
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:
```js
// This will implicitly create the canvas and PDF objects before saving.
var worker = html2pdf().from(element).save();
```
#### Workflow
The basic workflow of html2pdf.js tasks (enforced by the prereq system) is:
```
.from() -> .toContainer() -> .toCanvas() -> .toImg() -> .toPdf() -> .save()
```
#### Worker API
| Method | Arguments | Description |
|--------------|--------------------|-------------|
| from | src, type | Sets the source (HTML string or element) for the PDF. Optional `type` specifies other sources: `'string'`, `'element'`, `'canvas'`, or `'img'`. |
| 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()`. |
| output | type, options, src | Routes to the appropriate `outputPdf` or `outputImg` method based on specified `src` (`'pdf'` (default) or `'img'`). |
| 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. |
| 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'`. |
| save | filename | Saves the PDF object with the optional filename (creates user download prompt). |
| set | opt | Sets the specified properties. See [Options](#options) below for more details. |
| get | key, cbk | Returns the property specified in `key`, either as a Promise (use `.then` to access), or by calling `cbk` if provided. |
| 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. |
| 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. |
| thenExternal | onFulfilled, onRejected | True Promise method. Using this 'exits' the Worker chain - you will not be able to continue chaining Worker methods after `.thenExternal`. |
| catch, catchExternal | onRejected | Standard Promise method. `catchExternal` exits the Worker chain - you will not be able to continue chaining Worker methods after `.catchExternal`. |
| error | msg | Throws an error in the Worker's Promise chain. |
A few aliases are also provided for convenience:
| Method | Alias |
|-----------|-----------|
| save | saveAs |
| set | using |
| output | export |
| then | run |
## Options
html2pdf.js can be configured using an optional `opt` parameter:
```js
var element = document.getElementById('element-to-print');
var opt = {
margin: 1,
filename: 'myfile.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
};
// New Promise-based usage:
html2pdf().set(opt).from(element).save();
// Old monolithic-style usage:
html2pdf(element, opt);
```
The `opt` parameter has the following optional fields:
|Name |Type |Default |Description |
|------------|----------------|--------------------------------|------------------------------------------------------------------------------------------------------------|
|margin |number or array |`0` |PDF margin (in jsPDF units). Can be a single number, `[vMargin, hMargin]`, or `[top, left, bottom, right]`. |
|filename |string |`'file.pdf'` |The default filename of the exported PDF. |
|pagebreak |object |`{mode: ['css', 'legacy']}` |Controls the pagebreak behaviour on the page. See [Page-breaks](#page-breaks) below. |
|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.|
|enableLinks |boolean |`true` |If enabled, PDF hyperlinks are automatically added ontop of all anchor tags. |
|html2canvas |object |`{ }` |Configuration options sent directly to `html2canvas` ([see here](https://html2canvas.hertzen.com/configuration) for usage).|
|jsPDF |object |`{ }` |Configuration options sent directly to `jsPDF` ([see here](http://rawgit.com/MrRio/jsPDF/master/docs/jsPDF.html) for usage).|
### Page-breaks
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).
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).
#### Page-break settings
|Setting |Type |Default |Description |
|----------|----------------|--------------------|------------|
|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'`. |
|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. |
|after |string or array |`[]` |Like 'before', but adds a page-break immediately after the element. |
|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. |
#### Page-break modes
| Mode | Description |
|-----------|-------------|
| avoid-all | Automatically adds page-breaks to avoid splitting any elements across pages. |
| 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. |
| legacy | Adds page-breaks after elements with class `html2pdf__page-break`. This feature may be removed in the future. |
#### Example usage
```js
// Avoid page-breaks on all elements, and add one before #page2el.
html2pdf().set({
pagebreak: { mode: 'avoid-all', before: '#page2el' }
});
// Enable all 'modes', with no explicit elements.
html2pdf().set({
pagebreak: { mode: ['avoid-all', 'css', 'legacy'] }
});
// No modes, only explicit elements.
html2pdf().set({
pagebreak: { before: '.beforeClass', after: ['#after1', '#after2'], avoid: 'img' }
});
```
### Image type and quality
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:
|Name |Type |Default |Description |
|------------|----------------|------------------------------|---------------------------------------------------------------------------------------------|
|type |string |'jpeg' |The image type. HTMLCanvasElement only supports 'png', 'jpeg', and 'webp' (on Chrome). |
|quality |number |0.95 |The image quality, from 0 to 1. This setting is only used for jpeg/webp (not png). |
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.
## Progress tracking
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.
## Dependencies
html2pdf.js depends on the external packages [html2canvas](https://github.com/niklasvh/html2canvas), [jsPDF](https://github.com/MrRio/jsPDF), and [es6-promise](https://github.com/stefanpenner/es6-promise). These dependencies are automatically loaded when using NPM or the bundled package.
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:
```html
<script src="es6-promise.auto.min.js"></script>
<script src="jspdf.min.js"></script>
<script src="html2canvas.min.js"></script>
<script src="html2pdf.min.js"></script>
```
## Contributing
### Issues
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.
#### Known issues
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.
- 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.
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:
- 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`)
- npm: `npm install eKoopmans/html2pdf.js#bugfix/clone-nodes-BUILD`
- Related project: [Bugfix: Cloned nodes](https://github.com/eKoopmans/html2pdf.js/projects/9)
3. **Resizing:** Currently, html2pdf.js resizes the root element to fit onto a PDF page (causing internal content to "reflow").
- This is often desired behaviour, but not always.
- There are plans to add alternate behaviour (e.g. "shrink-to-page"), but nothing that's ready to test yet.
- Related project: [Feature: Single-page PDFs](https://github.com/eKoopmans/html2pdf.js/projects/1)
4. **Rendered as image:** html2pdf.js renders all content into an image, then places that image into a PDF.
- This means text is *not selectable or searchable*, and causes large file sizes.
- This is currently unavoidable, however recent improvements in jsPDF mean that it may soon be possible to render straight into vector graphics.
- Related project: [Feature: New renderer](https://github.com/eKoopmans/html2pdf.js/projects/4)
5. **Promise clashes:** html2pdf.js relies on specific Promise behaviour, and can fail when used with custom Promise libraries.
- In the next release, Promises will be sandboxed in html2pdf.js to remove this issue.
- Related project: [Bugfix: Sandboxed promises](https://github.com/eKoopmans/html2pdf.js/projects/11)
6. **Maximum size:** HTML5 canvases have a [maximum height/width](https://stackoverflow.com/a/11585939/4080966). Anything larger will fail to render.
- This is a limitation of HTML5 itself, and results in large PDFs rendering completely blank in html2pdf.js.
- The jsPDF canvas renderer (mentioned in Known Issue #4) may be able to fix this issue!
- Related project: [Bugfix: Maximum canvas size](https://github.com/eKoopmans/html2pdf.js/projects/5)
### Tests
html2pdf.js is currently sorely lacking in unit tests. Any contributions or suggestions of automated (or manual) tests are welcome. This is high on the to-do list for this project.
### Pull requests
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`.
## Credits
[Erik Koopmans](https://github.com/eKoopmans)
#### Contributors
- [@WilcoBreedt](https://github.com/WilcoBreedt)
- [@Ranger1230](https://github.com/Ranger1230)
#### Special thanks
- [Sauce Labs](https://saucelabs.com/) for unit testing.
## License
[The MIT License](http://opensource.org/licenses/MIT)
Copyright (c) 2017-2019 Erik Koopmans <[http://www.erik-koopmans.com/](http://www.erik-koopmans.com/)>
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+731
View File
@@ -0,0 +1,731 @@
/*!
* @overview es6-promise - a tiny implementation of Promises/A+.
* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
* @license Licensed under MIT license
* See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
* @version v4.2.8+1e68dce6
*/
/*!
* html2pdf.js v0.10.3
* Copyright (c) 2025 Erik Koopmans
* Released under the MIT License.
*/
/*! ../internals/a-function */
/*! ../internals/a-possible-prototype */
/*! ../internals/add-to-unscopables */
/*! ../internals/an-object */
/*! ../internals/array-for-each */
/*! ../internals/array-includes */
/*! ../internals/array-iteration */
/*! ../internals/array-method-has-species-support */
/*! ../internals/array-method-is-strict */
/*! ../internals/array-species-constructor */
/*! ../internals/array-species-create */
/*! ../internals/classof */
/*! ../internals/classof-raw */
/*! ../internals/copy-constructor-properties */
/*! ../internals/correct-prototype-getter */
/*! ../internals/create-html */
/*! ../internals/create-iterator-constructor */
/*! ../internals/create-non-enumerable-property */
/*! ../internals/create-property */
/*! ../internals/create-property-descriptor */
/*! ../internals/define-iterator */
/*! ../internals/define-well-known-symbol */
/*! ../internals/descriptors */
/*! ../internals/document-create-element */
/*! ../internals/dom-iterables */
/*! ../internals/engine-user-agent */
/*! ../internals/engine-v8-version */
/*! ../internals/enum-bug-keys */
/*! ../internals/export */
/*! ../internals/fails */
/*! ../internals/function-bind-context */
/*! ../internals/get-built-in */
/*! ../internals/global */
/*! ../internals/has */
/*! ../internals/hidden-keys */
/*! ../internals/html */
/*! ../internals/ie8-dom-define */
/*! ../internals/indexed-object */
/*! ../internals/inherit-if-required */
/*! ../internals/inspect-source */
/*! ../internals/internal-state */
/*! ../internals/is-array */
/*! ../internals/is-forced */
/*! ../internals/is-object */
/*! ../internals/is-pure */
/*! ../internals/is-symbol */
/*! ../internals/iterators */
/*! ../internals/iterators-core */
/*! ../internals/native-symbol */
/*! ../internals/native-weak-map */
/*! ../internals/object-assign */
/*! ../internals/object-create */
/*! ../internals/object-define-properties */
/*! ../internals/object-define-property */
/*! ../internals/object-get-own-property-descriptor */
/*! ../internals/object-get-own-property-names */
/*! ../internals/object-get-own-property-names-external */
/*! ../internals/object-get-own-property-symbols */
/*! ../internals/object-get-prototype-of */
/*! ../internals/object-keys */
/*! ../internals/object-keys-internal */
/*! ../internals/object-property-is-enumerable */
/*! ../internals/object-set-prototype-of */
/*! ../internals/object-to-string */
/*! ../internals/ordinary-to-primitive */
/*! ../internals/own-keys */
/*! ../internals/path */
/*! ../internals/redefine */
/*! ../internals/regexp-flags */
/*! ../internals/require-object-coercible */
/*! ../internals/set-global */
/*! ../internals/set-to-string-tag */
/*! ../internals/shared */
/*! ../internals/shared-key */
/*! ../internals/shared-store */
/*! ../internals/string-html-forced */
/*! ../internals/string-multibyte */
/*! ../internals/string-trim */
/*! ../internals/to-absolute-index */
/*! ../internals/to-indexed-object */
/*! ../internals/to-integer */
/*! ../internals/to-length */
/*! ../internals/to-object */
/*! ../internals/to-primitive */
/*! ../internals/to-property-key */
/*! ../internals/to-string */
/*! ../internals/to-string-tag-support */
/*! ../internals/uid */
/*! ../internals/use-symbol-as-uid */
/*! ../internals/well-known-symbol */
/*! ../internals/well-known-symbol-wrapped */
/*! ../internals/whitespaces */
/*! ../modules/es.array.iterator */
/*! ../utils.js */
/*! ../worker.js */
/*! ./plugin/hyperlinks.js */
/*! ./plugin/jspdf-plugin.js */
/*! ./plugin/pagebreaks.js */
/*! ./utils.js */
/*! ./worker.js */
/*! core-js/modules/es.array.concat.js */
/*! core-js/modules/es.array.iterator.js */
/*! core-js/modules/es.array.join.js */
/*! core-js/modules/es.array.map.js */
/*! core-js/modules/es.array.slice.js */
/*! core-js/modules/es.function.name.js */
/*! core-js/modules/es.number.constructor.js */
/*! core-js/modules/es.object.assign.js */
/*! core-js/modules/es.object.keys.js */
/*! core-js/modules/es.object.to-string.js */
/*! core-js/modules/es.regexp.to-string.js */
/*! core-js/modules/es.string.iterator.js */
/*! core-js/modules/es.string.link.js */
/*! core-js/modules/es.symbol.description.js */
/*! core-js/modules/es.symbol.iterator.js */
/*! core-js/modules/es.symbol.js */
/*! core-js/modules/web.dom-collections.for-each.js */
/*! core-js/modules/web.dom-collections.iterator.js */
/*! es6-promise */
/*! html2canvas */
/*! jspdf */
/*!**********************!*\
!*** ./src/index.js ***!
\**********************/
/*!**********************!*\
!*** ./src/utils.js ***!
\**********************/
/*!***********************!*\
!*** ./src/worker.js ***!
\***********************/
/*!************************!*\
!*** external "jspdf" ***!
\************************/
/*!******************************!*\
!*** external "html2canvas" ***!
\******************************/
/*!**********************************!*\
!*** ./src/plugin/hyperlinks.js ***!
\**********************************/
/*!**********************************!*\
!*** ./src/plugin/pagebreaks.js ***!
\**********************************/
/*!************************************!*\
!*** ./src/plugin/jspdf-plugin.js ***!
\************************************/
/*!***********************************************!*\
!*** ./node_modules/core-js/internals/has.js ***!
\***********************************************/
/*!***********************************************!*\
!*** ./node_modules/core-js/internals/uid.js ***!
\***********************************************/
/*!************************************************!*\
!*** ./node_modules/core-js/internals/html.js ***!
\************************************************/
/*!************************************************!*\
!*** ./node_modules/core-js/internals/path.js ***!
\************************************************/
/*!*************************************************!*\
!*** ./node_modules/core-js/internals/fails.js ***!
\*************************************************/
/*!**************************************************!*\
!*** ./node_modules/core-js/internals/export.js ***!
\**************************************************/
/*!**************************************************!*\
!*** ./node_modules/core-js/internals/global.js ***!
\**************************************************/
/*!**************************************************!*\
!*** ./node_modules/core-js/internals/shared.js ***!
\**************************************************/
/*!***************************************************!*\
!*** ./node_modules/core-js/internals/classof.js ***!
\***************************************************/
/*!***************************************************!*\
!*** ./node_modules/core-js/internals/is-pure.js ***!
\***************************************************/
/*!***************************************************!*\
!*** ./node_modules/core-js/modules/es.symbol.js ***!
\***************************************************/
/*!****************************************************!*\
!*** ./node_modules/core-js/internals/is-array.js ***!
\****************************************************/
/*!****************************************************!*\
!*** ./node_modules/core-js/internals/own-keys.js ***!
\****************************************************/
/*!****************************************************!*\
!*** ./node_modules/core-js/internals/redefine.js ***!
\****************************************************/
/*!*****************************************************!*\
!*** ./node_modules/core-js/internals/an-object.js ***!
\*****************************************************/
/*!*****************************************************!*\
!*** ./node_modules/core-js/internals/is-forced.js ***!
\*****************************************************/
/*!*****************************************************!*\
!*** ./node_modules/core-js/internals/is-object.js ***!
\*****************************************************/
/*!*****************************************************!*\
!*** ./node_modules/core-js/internals/is-symbol.js ***!
\*****************************************************/
/*!*****************************************************!*\
!*** ./node_modules/core-js/internals/iterators.js ***!
\*****************************************************/
/*!*****************************************************!*\
!*** ./node_modules/core-js/internals/to-length.js ***!
\*****************************************************/
/*!*****************************************************!*\
!*** ./node_modules/core-js/internals/to-object.js ***!
\*****************************************************/
/*!*****************************************************!*\
!*** ./node_modules/core-js/internals/to-string.js ***!
\*****************************************************/
/*!******************************************************!*\
!*** ./node_modules/core-js/internals/a-function.js ***!
\******************************************************/
/*!******************************************************!*\
!*** ./node_modules/core-js/internals/set-global.js ***!
\******************************************************/
/*!******************************************************!*\
!*** ./node_modules/core-js/internals/shared-key.js ***!
\******************************************************/
/*!******************************************************!*\
!*** ./node_modules/core-js/internals/to-integer.js ***!
\******************************************************/
/*!******************************************************!*\
!*** ./node_modules/core-js/modules/es.array.map.js ***!
\******************************************************/
/*!******************************************************!*\
!*** ./node_modules/es6-promise/dist/es6-promise.js ***!
\******************************************************/
/*!*******************************************************!*\
!*** ./node_modules/core-js/internals/classof-raw.js ***!
\*******************************************************/
/*!*******************************************************!*\
!*** ./node_modules/core-js/internals/create-html.js ***!
\*******************************************************/
/*!*******************************************************!*\
!*** ./node_modules/core-js/internals/descriptors.js ***!
\*******************************************************/
/*!*******************************************************!*\
!*** ./node_modules/core-js/internals/hidden-keys.js ***!
\*******************************************************/
/*!*******************************************************!*\
!*** ./node_modules/core-js/internals/object-keys.js ***!
\*******************************************************/
/*!*******************************************************!*\
!*** ./node_modules/core-js/internals/string-trim.js ***!
\*******************************************************/
/*!*******************************************************!*\
!*** ./node_modules/core-js/internals/whitespaces.js ***!
\*******************************************************/
/*!*******************************************************!*\
!*** ./node_modules/core-js/modules/es.array.join.js ***!
\*******************************************************/
/*!********************************************************!*\
!*** ./node_modules/core-js/internals/get-built-in.js ***!
\********************************************************/
/*!********************************************************!*\
!*** ./node_modules/core-js/internals/regexp-flags.js ***!
\********************************************************/
/*!********************************************************!*\
!*** ./node_modules/core-js/internals/shared-store.js ***!
\********************************************************/
/*!********************************************************!*\
!*** ./node_modules/core-js/internals/to-primitive.js ***!
\********************************************************/
/*!********************************************************!*\
!*** ./node_modules/core-js/modules/es.array.slice.js ***!
\********************************************************/
/*!********************************************************!*\
!*** ./node_modules/core-js/modules/es.object.keys.js ***!
\********************************************************/
/*!********************************************************!*\
!*** ./node_modules/core-js/modules/es.string.link.js ***!
\********************************************************/
/*!*********************************************************!*\
!*** ./node_modules/core-js/internals/dom-iterables.js ***!
\*********************************************************/
/*!*********************************************************!*\
!*** ./node_modules/core-js/internals/enum-bug-keys.js ***!
\*********************************************************/
/*!*********************************************************!*\
!*** ./node_modules/core-js/internals/native-symbol.js ***!
\*********************************************************/
/*!*********************************************************!*\
!*** ./node_modules/core-js/internals/object-assign.js ***!
\*********************************************************/
/*!*********************************************************!*\
!*** ./node_modules/core-js/internals/object-create.js ***!
\*********************************************************/
/*!*********************************************************!*\
!*** ./node_modules/core-js/modules/es.array.concat.js ***!
\*********************************************************/
/*!**********************************************************!*\
!*** ./node_modules/core-js/internals/array-for-each.js ***!
\**********************************************************/
/*!**********************************************************!*\
!*** ./node_modules/core-js/internals/array-includes.js ***!
\**********************************************************/
/*!**********************************************************!*\
!*** ./node_modules/core-js/internals/ie8-dom-define.js ***!
\**********************************************************/
/*!**********************************************************!*\
!*** ./node_modules/core-js/internals/indexed-object.js ***!
\**********************************************************/
/*!**********************************************************!*\
!*** ./node_modules/core-js/internals/inspect-source.js ***!
\**********************************************************/
/*!**********************************************************!*\
!*** ./node_modules/core-js/internals/internal-state.js ***!
\**********************************************************/
/*!**********************************************************!*\
!*** ./node_modules/core-js/internals/iterators-core.js ***!
\**********************************************************/
/*!**********************************************************!*\
!*** ./node_modules/core-js/modules/es.function.name.js ***!
\**********************************************************/
/*!**********************************************************!*\
!*** ./node_modules/core-js/modules/es.object.assign.js ***!
\**********************************************************/
/*!***********************************************************!*\
!*** ./node_modules/core-js/internals/array-iteration.js ***!
\***********************************************************/
/*!***********************************************************!*\
!*** ./node_modules/core-js/internals/create-property.js ***!
\***********************************************************/
/*!***********************************************************!*\
!*** ./node_modules/core-js/internals/define-iterator.js ***!
\***********************************************************/
/*!***********************************************************!*\
!*** ./node_modules/core-js/internals/native-weak-map.js ***!
\***********************************************************/
/*!***********************************************************!*\
!*** ./node_modules/core-js/internals/to-property-key.js ***!
\***********************************************************/
/*!***********************************************************!*\
!*** ./node_modules/core-js/modules/es.array.iterator.js ***!
\***********************************************************/
/*!************************************************************!*\
!*** ./node_modules/core-js/internals/object-to-string.js ***!
\************************************************************/
/*!************************************************************!*\
!*** ./node_modules/core-js/internals/string-multibyte.js ***!
\************************************************************/
/*!************************************************************!*\
!*** ./node_modules/core-js/modules/es.string.iterator.js ***!
\************************************************************/
/*!************************************************************!*\
!*** ./node_modules/core-js/modules/es.symbol.iterator.js ***!
\************************************************************/
/*!*************************************************************!*\
!*** ./node_modules/core-js/internals/engine-user-agent.js ***!
\*************************************************************/
/*!*************************************************************!*\
!*** ./node_modules/core-js/internals/engine-v8-version.js ***!
\*************************************************************/
/*!*************************************************************!*\
!*** ./node_modules/core-js/internals/set-to-string-tag.js ***!
\*************************************************************/
/*!*************************************************************!*\
!*** ./node_modules/core-js/internals/to-absolute-index.js ***!
\*************************************************************/
/*!*************************************************************!*\
!*** ./node_modules/core-js/internals/to-indexed-object.js ***!
\*************************************************************/
/*!*************************************************************!*\
!*** ./node_modules/core-js/internals/use-symbol-as-uid.js ***!
\*************************************************************/
/*!*************************************************************!*\
!*** ./node_modules/core-js/internals/well-known-symbol.js ***!
\*************************************************************/
/*!*************************************************************!*\
!*** ./node_modules/core-js/modules/es.object.to-string.js ***!
\*************************************************************/
/*!*************************************************************!*\
!*** ./node_modules/core-js/modules/es.regexp.to-string.js ***!
\*************************************************************/
/*!**************************************************************!*\
!*** ./node_modules/core-js/internals/add-to-unscopables.js ***!
\**************************************************************/
/*!**************************************************************!*\
!*** ./node_modules/core-js/internals/string-html-forced.js ***!
\**************************************************************/
/*!***************************************************************!*\
!*** ./node_modules/core-js/internals/inherit-if-required.js ***!
\***************************************************************/
/*!***************************************************************!*\
!*** ./node_modules/core-js/modules/es.number.constructor.js ***!
\***************************************************************/
/*!***************************************************************!*\
!*** ./node_modules/core-js/modules/es.symbol.description.js ***!
\***************************************************************/
/*!****************************************************************!*\
!*** ./node_modules/core-js/internals/a-possible-prototype.js ***!
\****************************************************************/
/*!****************************************************************!*\
!*** ./node_modules/core-js/internals/array-species-create.js ***!
\****************************************************************/
/*!****************************************************************!*\
!*** ./node_modules/core-js/internals/object-keys-internal.js ***!
\****************************************************************/
/*!*****************************************************************!*\
!*** ./node_modules/core-js/internals/function-bind-context.js ***!
\*****************************************************************/
/*!*****************************************************************!*\
!*** ./node_modules/core-js/internals/ordinary-to-primitive.js ***!
\*****************************************************************/
/*!*****************************************************************!*\
!*** ./node_modules/core-js/internals/to-string-tag-support.js ***!
\*****************************************************************/
/*!******************************************************************!*\
!*** ./node_modules/core-js/internals/array-method-is-strict.js ***!
\******************************************************************/
/*!******************************************************************!*\
!*** ./node_modules/core-js/internals/object-define-property.js ***!
\******************************************************************/
/*!*******************************************************************!*\
!*** ./node_modules/core-js/internals/document-create-element.js ***!
\*******************************************************************/
/*!*******************************************************************!*\
!*** ./node_modules/core-js/internals/object-get-prototype-of.js ***!
\*******************************************************************/
/*!*******************************************************************!*\
!*** ./node_modules/core-js/internals/object-set-prototype-of.js ***!
\*******************************************************************/
/*!********************************************************************!*\
!*** ./node_modules/core-js/internals/correct-prototype-getter.js ***!
\********************************************************************/
/*!********************************************************************!*\
!*** ./node_modules/core-js/internals/define-well-known-symbol.js ***!
\********************************************************************/
/*!********************************************************************!*\
!*** ./node_modules/core-js/internals/object-define-properties.js ***!
\********************************************************************/
/*!********************************************************************!*\
!*** ./node_modules/core-js/internals/require-object-coercible.js ***!
\********************************************************************/
/*!*********************************************************************!*\
!*** ./node_modules/core-js/internals/array-species-constructor.js ***!
\*********************************************************************/
/*!*********************************************************************!*\
!*** ./node_modules/core-js/internals/well-known-symbol-wrapped.js ***!
\*********************************************************************/
/*!**********************************************************************!*\
!*** ./node_modules/core-js/internals/create-property-descriptor.js ***!
\**********************************************************************/
/*!**********************************************************************!*\
!*** ./node_modules/core-js/modules/web.dom-collections.for-each.js ***!
\**********************************************************************/
/*!**********************************************************************!*\
!*** ./node_modules/core-js/modules/web.dom-collections.iterator.js ***!
\**********************************************************************/
/*!***********************************************************************!*\
!*** ./node_modules/core-js/internals/copy-constructor-properties.js ***!
\***********************************************************************/
/*!***********************************************************************!*\
!*** ./node_modules/core-js/internals/create-iterator-constructor.js ***!
\***********************************************************************/
/*!*************************************************************************!*\
!*** ./node_modules/core-js/internals/object-get-own-property-names.js ***!
\*************************************************************************/
/*!*************************************************************************!*\
!*** ./node_modules/core-js/internals/object-property-is-enumerable.js ***!
\*************************************************************************/
/*!**************************************************************************!*\
!*** ./node_modules/core-js/internals/create-non-enumerable-property.js ***!
\**************************************************************************/
/*!***************************************************************************!*\
!*** ./node_modules/core-js/internals/object-get-own-property-symbols.js ***!
\***************************************************************************/
/*!****************************************************************************!*\
!*** ./node_modules/core-js/internals/array-method-has-species-support.js ***!
\****************************************************************************/
/*!******************************************************************************!*\
!*** ./node_modules/core-js/internals/object-get-own-property-descriptor.js ***!
\******************************************************************************/
/*!**********************************************************************************!*\
!*** ./node_modules/core-js/internals/object-get-own-property-names-external.js ***!
\**********************************************************************************/
File diff suppressed because one or more lines are too long
+22
View File
@@ -0,0 +1,22 @@
Copyright
(c) 2010-2025 James Hall, https://github.com/MrRio/jsPDF
(c) 2015-2025 yWorks GmbH, https://www.yworks.com/
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+286
View File
@@ -0,0 +1,286 @@
# ![jsPDF](https://parall.ax/parallax-2016/img/svg/jspdf-logo.svg)
[![Continous Integration](https://github.com/MrRio/jsPDF/actions/workflows/continuous-integration.yml/badge.svg)](https://github.com/MrRio/jsPDF/actions/workflows/continuous-integration.yml?query=branch%3Amaster)
[![Code Climate](https://codeclimate.com/repos/57f943855cdc43705e00592f/badges/2665cddeba042dc5191f/gpa.svg)](https://codeclimate.com/repos/57f943855cdc43705e00592f/feed)
[![Test Coverage](https://codeclimate.com/repos/57f943855cdc43705e00592f/badges/2665cddeba042dc5191f/coverage.svg)](https://codeclimate.com/repos/57f943855cdc43705e00592f/coverage)
[![GitHub license](https://img.shields.io/github/license/MrRio/jsPDF.svg)](https://github.com/MrRio/jsPDF/blob/master/LICENSE)
[![Total alerts](https://img.shields.io/lgtm/alerts/g/MrRio/jsPDF.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/MrRio/jsPDF/alerts/)
[![Language grade: JavaScript](https://img.shields.io/lgtm/grade/javascript/g/MrRio/jsPDF.svg?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/MrRio/jsPDF/context:javascript)
[![Gitpod ready-to-code](https://img.shields.io/badge/Gitpod-ready--to--code-blue?logo=gitpod)](https://gitpod.io/from-referrer/)
**A library to generate PDFs in JavaScript.**
You can [catch me on twitter](http://twitter.com/MrRio): [@MrRio](http://twitter.com/MrRio) or head over to [my company's website](http://parall.ax) for consultancy.
jsPDF is now co-maintained by [yWorks - the diagramming experts](https://www.yworks.com/).
## [Live Demo](http://raw.githack.com/MrRio/jsPDF/master/) | [Documentation](http://raw.githack.com/MrRio/jsPDF/master/docs/)
## Install
Recommended: get jsPDF from npm:
```sh
npm install jspdf --save
# or
yarn add jspdf
```
Alternatively, load it from a CDN:
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/3.0.4/jspdf.umd.min.js"></script>
```
Or always get latest version via [unpkg](https://unpkg.com/browse/jspdf/)
```html
<script src="https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js"></script>
```
The `dist` folder of this package contains different kinds of files:
- **jspdf.es.\*.js**: Modern ES2015 module format.
- **jspdf.node.\*.js**: For running in Node. Uses file operations for loading/saving files instead of browser APIs.
- **jspdf.umd.\*.js**: UMD module format. For AMD or script-tag loading.
- **polyfills\*.js**: Required polyfills for older browsers like Internet Explorer. The es variant simply imports all
required polyfills from `core-js`, the umd variant is self-contained.
Usually it is not necessary to specify the exact file in the import statement. Build tools or Node automatically figure
out the right file, so importing "jspdf" is enough.
## Usage
Then you're ready to start making your document:
```javascript
import { jsPDF } from "jspdf";
// Default export is a4 paper, portrait, using millimeters for units
const doc = new jsPDF();
doc.text("Hello world!", 10, 10);
doc.save("a4.pdf");
```
If you want to change the paper size, orientation, or units, you can do:
```javascript
// Landscape export, 2×4 inches
const doc = new jsPDF({
orientation: "landscape",
unit: "in",
format: [4, 2]
});
doc.text("Hello world!", 1, 1);
doc.save("two-by-four.pdf");
```
### Running in Node.js
```javascript
const { jsPDF } = require("jspdf"); // will automatically load the node version
const doc = new jsPDF();
doc.text("Hello world!", 10, 10);
doc.save("a4.pdf"); // will save the file in the current working directory
```
### Other Module Formats
<details>
<summary>
<b>AMD</b>
</summary>
```js
require(["jspdf"], ({ jsPDF }) => {
const doc = new jsPDF();
doc.text("Hello world!", 10, 10);
doc.save("a4.pdf");
});
```
</details>
<details>
<summary>
<b>Globals</b>
</summary>
```js
const { jsPDF } = window.jspdf;
const doc = new jsPDF();
doc.text("Hello world!", 10, 10);
doc.save("a4.pdf");
```
</details>
### Optional dependencies
Some functions of jsPDF require optional dependencies. E.g. the `html` method, which depends on `html2canvas` and,
when supplied with a string HTML document, `dompurify`. JsPDF loads them dynamically when required
(using the respective module format, e.g. dynamic imports). Build tools like Webpack will automatically create separate
chunks for each of the optional dependencies. If your application does not use any of the optional dependencies, you
can prevent Webpack from generating the chunks by defining them as external dependencies:
```js
// webpack.config.js
module.exports = {
// ...
externals: {
// only define the dependencies you are NOT using as externals!
canvg: "canvg",
html2canvas: "html2canvas",
dompurify: "dompurify"
}
};
```
In **Vue CLI** projects, externals can be defined via the [configureWebpack](https://cli.vuejs.org/config/#configurewebpack)
or [chainWebpack](https://cli.vuejs.org/config/#chainwebpack) properties of the `vue.config.js` file
(needs to be created, first, in fresh projects).
In **Angular** projects, externals can be defined using
[custom webpack builders](https://github.com/just-jeb/angular-builders/tree/master/packages/custom-webpack).
In **React** (`create-react-app`) projects, externals can be defined by either using
[react-app-rewired](https://github.com/timarney/react-app-rewired) or ejecting.
### TypeScript/Angular/Webpack/React/etc. Configuration:
jsPDF can be imported just like any other 3rd party library. This works with all major toolkits and frameworks. jsPDF
also offers a typings file for TypeScript projects.
```js
import { jsPDF } from "jspdf";
```
You can add jsPDF to your meteor-project as follows:
```
meteor add jspdf:core
```
### Polyfills
jsPDF requires modern browser APIs in order to function. To use jsPDF in older browsers like Internet Explorer,
polyfills are required. You can load all required polyfills as follows:
```js
import "jspdf/dist/polyfills.es.js";
```
Alternatively, you can load the prebundled polyfill file. This is not recommended, since you might end up
loading polyfills multiple times. Might still be nifty for small applications or quick POCs.
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/3.0.4/polyfills.umd.js"></script>
```
## Use of Unicode Characters / UTF-8:
The 14 standard fonts in PDF are limited to the ASCII-codepage. If you want to use UTF-8 you have to integrate a
custom font, which provides the needed glyphs. jsPDF supports .ttf-files. So if you want to have for example
Chinese text in your pdf, your font has to have the necessary Chinese glyphs. So, check if your font supports
the wanted glyphs or else it will show garbled characters instead of the right text.
To add the font to jsPDF use our fontconverter in
[/fontconverter/fontconverter.html](https://rawgit.com/MrRio/jsPDF/master/fontconverter/fontconverter.html).
The fontconverter will create a js-file with the content of the provided ttf-file as base64 encoded string
and additional code for jsPDF. You just have to add this generated js-File to your project.
You are then ready to go to use setFont-method in your code and write your UTF-8 encoded text.
Alternatively you can just load the content of the \*.ttf file as a binary string using `fetch` or `XMLHttpRequest` and
add the font to the PDF file:
```js
const doc = new jsPDF();
const myFont = ... // load the *.ttf font file as binary string
// add the font to jsPDF
doc.addFileToVFS("MyFont.ttf", myFont);
doc.addFont("MyFont.ttf", "MyFont", "normal");
doc.setFont("MyFont");
```
## Advanced Functionality
Since the merge with the [yWorks fork](https://github.com/yWorks/jsPDF) there are a lot of new features. However, some
of them are API breaking, which is why there is an API-switch between two API modes:
- In "compat" API mode, jsPDF has the same API as MrRio's original version, which means full compatibility with plugins.
However, some advanced features like transformation matrices and patterns won't work. This is the default mode.
- In "advanced" API mode, jsPDF has the API you're used from the yWorks-fork version. This means the availability of
all advanced features like patterns, FormObjects, and transformation matrices.
You can switch between the two modes by calling
```javascript
doc.advancedAPI(doc => {
// your code
});
// or
doc.compatAPI(doc => {
// your code
});
```
JsPDF will automatically switch back to the original API mode after the callback has run.
## Support
Please check if your question is already handled at Stackoverflow <https://stackoverflow.com/questions/tagged/jspdf>.
Feel free to ask a question there with the tag `jspdf`.
Feature requests, bug reports, etc. are very welcome as issues. Note that bug reports should follow these guidelines:
- A bug should be reported as an [mcve](https://stackoverflow.com/help/mcve)
- Make sure code is properly indented and [formatted](https://help.github.com/articles/basic-writing-and-formatting-syntax/#quoting-code) (Use ``` around code blocks)
- Provide a runnable example.
- Try to make sure and show in your issue that the issue is actually related to jspdf and not your framework of choice.
## Contributing
jsPDF cannot live without help from the community! If you think a feature is missing or you found a bug, please consider
if you can spare one or two hours and prepare a pull request. If you're simply interested in this project and want to
help, have a look at the open issues, especially those labeled with "bug".
You can find information about building and testing jsPDF in the
[contribution guide](https://github.com/MrRio/jsPDF/blob/master/CONTRIBUTING.md#pull-requests)
## Credits
- Big thanks to Daniel Dotsenko from [Willow Systems Corporation](https://github.com/willowsystems) for making huge contributions to the codebase.
- Thanks to Ajaxian.com for [featuring us back in 2009](http://web.archive.org/web/20111011192314/http://ajaxian.com/archives/dynamically-generic-pdfs-with-javascript). (Internet Archive Wayback Machine reference)
- Our special thanks to GH Lee ([sphilee](https://github.com/sphilee)) for programming the ttf-file-support and providing a large and long sought after feature
- Everyone else that's contributed patches or bug reports. You rock.
## License (MIT)
Copyright
(c) 2010-2025 James Hall, https://github.com/MrRio/jsPDF
(c) 2015-2025 yWorks GmbH, https://www.yworks.com/
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+122
View File
@@ -0,0 +1,122 @@
{
"name": "jspdf",
"version": "3.0.4",
"homepage": "https://github.com/parallax/jsPDF",
"description": "PDF Document creation from JavaScript",
"main": "dist/jspdf.node.min.js",
"module": "dist/jspdf.es.min.js",
"browser": "dist/jspdf.es.min.js",
"exports": {
".": {
"node": "./dist/jspdf.node.min.js",
"browser": "./dist/jspdf.es.min.js",
"types": "./types/index.d.ts"
},
"./dist/*": "./dist/*",
"./package.json": "./package.json"
},
"files": [
"dist",
"types/index.d.ts",
"README.md",
"LICENSE"
],
"typings": "types/index.d.ts",
"types": "types/index.d.ts",
"keywords": [
"pdf"
],
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/parallax/jsPDF.git"
},
"dependencies": {
"@babel/runtime": "^7.28.4",
"fflate": "^0.8.1",
"fast-png": "^6.2.0"
},
"optionalDependencies": {
"canvg": "^3.0.11",
"core-js": "^3.6.0",
"dompurify": "^3.2.4",
"html2canvas": "^1.0.0-rc.5"
},
"devDependencies": {
"@babel/core": "^7.10.4",
"@babel/plugin-transform-runtime": "^7.14.5",
"@babel/preset-env": "^7.10.4",
"@rollup/plugin-babel": "^5.3.0",
"@rollup/plugin-replace": "^2.3.3",
"@rollup/plugin-terser": "^0.4.4",
"@rollup/plugin-typescript": "^8.0.0",
"@types/jasmine": "^3.5.11",
"@types/node": "^20.16.5",
"@typescript-eslint/eslint-plugin": "^3.6.0",
"@typescript-eslint/parser": "^3.6.0",
"chalk": "^4.1.0",
"codeclimate-test-reporter": "^0.5.1",
"core-js": "^3.33.0",
"diff": "^4.0.2",
"docdash": "^1.2.0",
"eslint": "^7.4.0",
"eslint-plugin-jasmine": "^4.1.1",
"folder-delete": "^1.0.4",
"inquirer": "^6.5.2",
"jasmine": "3.5.0",
"jasmine-core": "3.5.0",
"jasmine-expect": "4.0.3",
"jsdoc": "^3.6.3",
"karma": "5.1.0",
"karma-babel-preprocessor": "8.0.1",
"karma-chrome-launcher": "3.1.0",
"karma-coverage": "2.0.2",
"karma-firefox-launcher": "1.3.0",
"karma-ie-launcher": "1.0.0",
"karma-jasmine": "3.3.1",
"karma-jasmine-matchers": "4.0.2",
"karma-mocha-reporter": "2.2.5",
"karma-rollup-preprocessor": "^7.0.7",
"karma-typescript": "^5.5.4",
"karma-verbose-reporter": "0.0.6",
"local-web-server": "^4.2.1",
"log-utils": "^1.0.0",
"markdown": "0.5.0",
"preprocess": "^3.2.0",
"prettier": "^1.19.1",
"regenerator-runtime": "^0.13.5",
"requirejs": "^2.3.6",
"rollup": "^2.18.2",
"rollup-plugin-commonjs": "^10.1.0",
"rollup-plugin-license": "^2.1.0",
"rollup-plugin-node-resolve": "5.2.0",
"rollup-plugin-preprocess": "0.0.4",
"typescript": "^5.6.2",
"yarpm": "^0.2.1"
},
"scripts": {
"start": "ws",
"build": "rollup --config rollup.config.js",
"version": "yarpm run build && yarpm run generate-docs && git add -A dist docs",
"pretest": "yarpm run build",
"test": "yarpm run test-node && yarpm run test-ci",
"test-ci": "karma start test/unit/karma.conf.js --browsers=ChromeHeadless --single-run --verbose && for a in coverage/*; do codeclimate-test-reporter < \\\"$a/lcov.info\\\"; break; done",
"test-local": "yarpm run test-unit && yarpm run test-node && yarpm run test-amd && yarpm run test-esm && yarpm run test-globals && yarpm run test-typescript && yarpm run test-webworker",
"test-unit": "karma start test/unit/karma.conf.js --single-run",
"test-amd": "karma start test/deployment/amd/karma.conf.js --single-run",
"test-esm": "karma start test/deployment/esm/karma.conf.js --single-run",
"test-globals": "karma start test/deployment/globals/karma.conf.js --single-run",
"test-typescript": "karma start test/deployment/typescript/karma.conf.js --single-run",
"test-webworker": "karma start test/deployment/webworker/karma.conf.js --single-run",
"test-node": "jasmine --config=test/deployment/node/jasmine.json",
"test-training": "node test/utils/reference-server.js",
"test-typings": "tsc -p types/tsconfig.json && tsc -p types/tsconfig-node.json",
"prettier": "prettier --write \"*.{js,ts,md,css,json}\" \"{spec,examples,src,types}/**/*.{js,ts,md,css,json}\"",
"lint": "prettier --check \"*.{js,ts,md,css,json}\" \"{spec,examples,src,types}/**/*.{js,ts,md,css,json}\"",
"pregenerate-docs": "node deletedocs.js",
"generate-docs": "jsdoc -c jsdoc.json --readme README.md"
},
"browserslist": [
"last 2 versions"
]
}
File diff suppressed because it is too large Load Diff
+69
View File
@@ -0,0 +1,69 @@
{
"name": "html2pdf.js",
"version": "0.10.3",
"description": "Client-side HTML-to-PDF rendering using pure JS",
"main": "dist/html2pdf.js",
"files": [
"/src",
"/dist"
],
"repository": "git@github.com:eKoopmans/html2pdf.js.git",
"keywords": [
"javascript",
"pdf-generation",
"html",
"client-side",
"canvas"
],
"author": {
"name": "Erik Koopmans",
"email": "erik@erik-koopmans.com",
"url": "https://www.erik-koopmans.com"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/eKoopmans/html2pdf.js/issues"
},
"homepage": "https://ekoopmans.github.io/html2pdf.js/",
"dependencies": {
"es6-promise": "^4.2.5",
"html2canvas": "^1.0.0",
"jspdf": "^3.0.0"
},
"devDependencies": {
"@babel/core": "^7.14.8",
"@babel/preset-env": "^7.14.8",
"babel-loader": "^8.2.2",
"chai": "^4.2.0",
"chai-spies": "^1.0.0",
"core-js": "^3.16.0",
"karma": "^6.3.4",
"karma-chai": "^0.1.0",
"karma-chai-spies": "^0.1.4",
"karma-chrome-launcher": "^2.2.0",
"karma-edge-launcher": "^0.4.2",
"karma-firefox-launcher": "^1.1.0",
"karma-ie-launcher": "^1.0.0",
"karma-mocha": "^2.0.1",
"karma-mocha-reporter": "^2.2.5",
"karma-sauce-launcher": "^2.0.2",
"karma-webpack-preprocessor": "ekoopmans/karma-webpack-preprocessor#update-2021",
"mocha": "^6.1.4",
"pdftest": "^0.3.0",
"rimraf": "^2.6.2",
"start-server-and-test": "^1.12.0",
"webpack": "^5.45.1",
"webpack-bundle-analyzer": "^4.4.2",
"webpack-cli": "^4.7.2"
},
"scripts": {
"build": "npm run clean && webpack --env=prod",
"build:analyze": "npm run clean && webpack --env=prod --env=analyzer",
"clean": "rimraf dist/*",
"dev": "webpack --env=dev",
"dev:analyze": "webpack --env=dev --env=analyzer",
"test": "start-server-and-test test:serve http://localhost:3000 test:run",
"test:serve": "pdftest serve 3000 ./test/reference/snapshot",
"test:run": "npx karma start karma.conf.js"
}
}
+29
View File
@@ -0,0 +1,29 @@
import Worker from './worker.js';
import './plugin/jspdf-plugin.js';
import './plugin/pagebreaks.js';
import './plugin/hyperlinks.js';
/**
* Generate a PDF from an HTML element or string using html2canvas and jsPDF.
*
* @param {Element|string} source The source element or HTML string.
* @param {Object=} opt An object of optional settings: 'margin', 'filename',
* 'image' ('type' and 'quality'), and 'html2canvas' / 'jspdf', which are
* sent as settings to their corresponding functions.
*/
var html2pdf = function html2pdf(src, opt) {
// Create a new worker with the given options.
var worker = new html2pdf.Worker(opt);
if (src) {
// If src is specified, perform the traditional 'simple' operation.
return worker.from(src).save();
} else {
// Otherwise, return the worker for new Promise-based operation.
return worker;
}
}
html2pdf.Worker = Worker;
// Expose the html2pdf function.
export default html2pdf;
+59
View File
@@ -0,0 +1,59 @@
import Worker from '../worker.js';
import { unitConvert } from '../utils.js';
// Add hyperlink functionality to the PDF creation.
// Main link array, and refs to original functions.
var linkInfo = [];
var orig = {
toContainer: Worker.prototype.toContainer,
toPdf: Worker.prototype.toPdf,
};
Worker.prototype.toContainer = function toContainer() {
return orig.toContainer.call(this).then(function toContainer_hyperlink() {
// Retrieve hyperlink info if the option is enabled.
if (this.opt.enableLinks) {
// Find all anchor tags and get the container's bounds for reference.
var container = this.prop.container;
var links = container.querySelectorAll('a');
var containerRect = unitConvert(container.getBoundingClientRect(), this.prop.pageSize.k);
linkInfo = [];
// Loop through each anchor tag.
Array.prototype.forEach.call(links, function(link) {
// Treat each client rect as a separate link (for text-wrapping).
var clientRects = link.getClientRects();
for (var i=0; i<clientRects.length; i++) {
var clientRect = unitConvert(clientRects[i], this.prop.pageSize.k);
clientRect.left -= containerRect.left;
clientRect.top -= containerRect.top;
var page = Math.floor(clientRect.top / this.prop.pageSize.inner.height) + 1;
var top = this.opt.margin[0] + clientRect.top % this.prop.pageSize.inner.height;
var left = this.opt.margin[1] + clientRect.left;
linkInfo.push({ page, top, left, clientRect, link });
}
}, this);
}
});
};
Worker.prototype.toPdf = function toPdf() {
return orig.toPdf.call(this).then(function toPdf_hyperlink() {
// Add hyperlinks if the option is enabled.
if (this.opt.enableLinks) {
// Attach each anchor tag based on info from toContainer().
linkInfo.forEach(function(l) {
this.prop.pdf.setPage(l.page);
this.prop.pdf.link(l.left, l.top, l.clientRect.width, l.clientRect.height,
{ url: l.link.href });
}, this);
// Reset the active page of the PDF to the final page.
var nPages = this.prop.pdf.internal.getNumberOfPages();
this.prop.pdf.setPage(nPages);
}
});
};
+99
View File
@@ -0,0 +1,99 @@
// Import dependencies.
import { jsPDF } from 'jspdf';
// Get dimensions of a PDF page, as determined by jsPDF.
jsPDF.getPageSize = function(orientation, unit, format) {
// Decode options object
if (typeof orientation === 'object') {
var options = orientation;
orientation = options.orientation;
unit = options.unit || unit;
format = options.format || format;
}
// Default options
unit = unit || 'mm';
format = format || 'a4';
orientation = ('' + (orientation || 'P')).toLowerCase();
var format_as_string = ('' + format).toLowerCase();
// Size in pt of various paper formats
var pageFormats = {
'a0' : [2383.94, 3370.39], 'a1' : [1683.78, 2383.94],
'a2' : [1190.55, 1683.78], 'a3' : [ 841.89, 1190.55],
'a4' : [ 595.28, 841.89], 'a5' : [ 419.53, 595.28],
'a6' : [ 297.64, 419.53], 'a7' : [ 209.76, 297.64],
'a8' : [ 147.40, 209.76], 'a9' : [ 104.88, 147.40],
'a10' : [ 73.70, 104.88], 'b0' : [2834.65, 4008.19],
'b1' : [2004.09, 2834.65], 'b2' : [1417.32, 2004.09],
'b3' : [1000.63, 1417.32], 'b4' : [ 708.66, 1000.63],
'b5' : [ 498.90, 708.66], 'b6' : [ 354.33, 498.90],
'b7' : [ 249.45, 354.33], 'b8' : [ 175.75, 249.45],
'b9' : [ 124.72, 175.75], 'b10' : [ 87.87, 124.72],
'c0' : [2599.37, 3676.54], 'c1' : [1836.85, 2599.37],
'c2' : [1298.27, 1836.85], 'c3' : [ 918.43, 1298.27],
'c4' : [ 649.13, 918.43], 'c5' : [ 459.21, 649.13],
'c6' : [ 323.15, 459.21], 'c7' : [ 229.61, 323.15],
'c8' : [ 161.57, 229.61], 'c9' : [ 113.39, 161.57],
'c10' : [ 79.37, 113.39], 'dl' : [ 311.81, 623.62],
'letter' : [612, 792],
'government-letter' : [576, 756],
'legal' : [612, 1008],
'junior-legal' : [576, 360],
'ledger' : [1224, 792],
'tabloid' : [792, 1224],
'credit-card' : [153, 243]
};
// Unit conversion
switch (unit) {
case 'pt': var k = 1; break;
case 'mm': var k = 72 / 25.4; break;
case 'cm': var k = 72 / 2.54; break;
case 'in': var k = 72; break;
case 'px': var k = 72 / 96; break;
case 'pc': var k = 12; break;
case 'em': var k = 12; break;
case 'ex': var k = 6; break;
default:
throw ('Invalid unit: ' + unit);
}
// Dimensions are stored as user units and converted to points on output
if (pageFormats.hasOwnProperty(format_as_string)) {
var pageHeight = pageFormats[format_as_string][1] / k;
var pageWidth = pageFormats[format_as_string][0] / k;
} else {
try {
var pageHeight = format[1];
var pageWidth = format[0];
} catch (err) {
throw new Error('Invalid format: ' + format);
}
}
// Handle page orientation
if (orientation === 'p' || orientation === 'portrait') {
orientation = 'p';
if (pageWidth > pageHeight) {
var tmp = pageWidth;
pageWidth = pageHeight;
pageHeight = tmp;
}
} else if (orientation === 'l' || orientation === 'landscape') {
orientation = 'l';
if (pageHeight > pageWidth) {
var tmp = pageWidth;
pageWidth = pageHeight;
pageHeight = tmp;
}
} else {
throw('Invalid orientation: ' + orientation);
}
// Return information (k is the unit conversion ratio from pts)
var info = { 'width': pageWidth, 'height': pageHeight, 'unit': unit, 'k': k };
return info;
};
export default jsPDF;
+134
View File
@@ -0,0 +1,134 @@
import Worker from '../worker.js';
import { objType, createElement } from '../utils.js';
/* Pagebreak plugin:
Adds page-break functionality to the html2pdf library. Page-breaks can be
enabled by CSS styles, set on individual elements using selectors, or
avoided from breaking inside all elements.
Options on the `opt.pagebreak` object:
mode: String or array of strings: 'avoid-all', 'css', and/or 'legacy'
Default: ['css', 'legacy']
before: String or array of 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.
after: Like 'before', but adds a page-break immediately after the element.
avoid: Like 'before', but avoids page-breaks on these elements. You can
enable this feature on every element using the 'avoid-all' mode.
*/
// Refs to original functions.
var orig = {
toContainer: Worker.prototype.toContainer
};
// Add pagebreak default options to the Worker template.
Worker.template.opt.pagebreak = {
mode: ['css', 'legacy'],
before: [],
after: [],
avoid: []
};
Worker.prototype.toContainer = function toContainer() {
return orig.toContainer.call(this).then(function toContainer_pagebreak() {
// Setup root element and inner page height.
var root = this.prop.container;
var pxPageHeight = this.prop.pageSize.inner.px.height;
// Check all requested modes.
var modeSrc = [].concat(this.opt.pagebreak.mode);
var mode = {
avoidAll: modeSrc.indexOf('avoid-all') !== -1,
css: modeSrc.indexOf('css') !== -1,
legacy: modeSrc.indexOf('legacy') !== -1
};
// Get arrays of all explicitly requested elements.
var select = {};
var self = this;
['before', 'after', 'avoid'].forEach(function(key) {
var all = mode.avoidAll && key === 'avoid';
select[key] = all ? [] : [].concat(self.opt.pagebreak[key] || []);
if (select[key].length > 0) {
select[key] = Array.prototype.slice.call(
root.querySelectorAll(select[key].join(', ')));
}
});
// Get all legacy page-break elements.
var legacyEls = root.querySelectorAll('.html2pdf__page-break');
legacyEls = Array.prototype.slice.call(legacyEls);
// Loop through all elements.
var els = root.querySelectorAll('*');
Array.prototype.forEach.call(els, function pagebreak_loop(el) {
// Setup pagebreak rules based on legacy and avoidAll modes.
var rules = {
before: false,
after: mode.legacy && legacyEls.indexOf(el) !== -1,
avoid: mode.avoidAll
};
// Add rules for css mode.
if (mode.css) {
// TODO: Check if this is valid with iFrames.
var style = window.getComputedStyle(el);
// TODO: Handle 'left' and 'right' correctly.
// TODO: Add support for 'avoid' on breakBefore/After.
var breakOpt = ['always', 'page', 'left', 'right'];
var avoidOpt = ['avoid', 'avoid-page'];
rules = {
before: rules.before || breakOpt.indexOf(style.breakBefore || style.pageBreakBefore) !== -1,
after: rules.after || breakOpt.indexOf(style.breakAfter || style.pageBreakAfter) !== -1,
avoid: rules.avoid || avoidOpt.indexOf(style.breakInside || style.pageBreakInside) !== -1
};
}
// Add rules for explicit requests.
Object.keys(rules).forEach(function(key) {
rules[key] = rules[key] || select[key].indexOf(el) !== -1;
});
// Get element position on the screen.
// TODO: Subtract the top of the container from clientRect.top/bottom?
var clientRect = el.getBoundingClientRect();
// Avoid: Check if a break happens mid-element.
if (rules.avoid && !rules.before) {
var startPage = Math.floor(clientRect.top / pxPageHeight);
var endPage = Math.floor(clientRect.bottom / pxPageHeight);
var nPages = Math.abs(clientRect.bottom - clientRect.top) / pxPageHeight;
// Turn on rules.before if the el is broken and is at most one page long.
if (endPage !== startPage && nPages <= 1) {
rules.before = true;
}
}
// Before: Create a padding div to push the element to the next page.
if (rules.before) {
var pad = createElement('div', {style: {
display: 'block',
height: pxPageHeight - (clientRect.top % pxPageHeight) + 'px'
}});
el.parentNode.insertBefore(pad, el);
}
// After: Create a padding div to fill the remaining page.
if (rules.after) {
var pad = createElement('div', {style: {
display: 'block',
height: pxPageHeight - (clientRect.bottom % pxPageHeight) + 'px'
}});
el.parentNode.insertBefore(pad, el.nextSibling);
}
});
});
};
+78
View File
@@ -0,0 +1,78 @@
// Determine the type of a variable/object.
export const objType = function objType(obj) {
var type = typeof obj;
if (type === 'undefined') return 'undefined';
else if (type === 'string' || obj instanceof String) return 'string';
else if (type === 'number' || obj instanceof Number) return 'number';
else if (type === 'function' || obj instanceof Function) return 'function';
else if (!!obj && obj.constructor === Array) return 'array';
else if (obj && obj.nodeType === 1) return 'element';
else if (type === 'object') return 'object';
else return 'unknown';
};
// Create an HTML element with optional className, innerHTML, and style.
export const createElement = function createElement(tagName, opt) {
var el = document.createElement(tagName);
if (opt.className) el.className = opt.className;
if (opt.innerHTML) {
el.innerHTML = opt.innerHTML;
var scripts = el.getElementsByTagName('script');
for (var i = scripts.length; i-- > 0; null) {
scripts[i].parentNode.removeChild(scripts[i]);
}
}
for (var key in opt.style) {
el.style[key] = opt.style[key];
}
return el;
};
// Deep-clone a node and preserve contents/properties.
export const cloneNode = function cloneNode(node, javascriptEnabled) {
// Recursively clone the node.
var clone = node.nodeType === 3 ? document.createTextNode(node.nodeValue) : node.cloneNode(false);
for (var child = node.firstChild; child; child = child.nextSibling) {
if (javascriptEnabled === true || child.nodeType !== 1 || child.nodeName !== 'SCRIPT') {
clone.appendChild(cloneNode(child, javascriptEnabled));
}
}
if (node.nodeType === 1) {
// Preserve contents/properties of special nodes.
if (node.nodeName === 'CANVAS') {
clone.width = node.width;
clone.height = node.height;
clone.getContext('2d').drawImage(node, 0, 0);
} else if (node.nodeName === 'TEXTAREA' || node.nodeName === 'SELECT') {
clone.value = node.value;
}
// Preserve the node's scroll position when it loads.
clone.addEventListener('load', function() {
clone.scrollTop = node.scrollTop;
clone.scrollLeft = node.scrollLeft;
}, true);
}
// Return the cloned node.
return clone;
}
// Convert units from px using the conversion value 'k' from jsPDF.
export const unitConvert = function unitConvert(obj, k) {
if (objType(obj) === 'number') {
return obj * 72 / 96 / k;
} else {
var newObj = {};
for (var key in obj) {
newObj[key] = obj[key] * 72 / 96 / k;
}
return newObj;
}
};
// Convert units to px using the conversion value 'k' from jsPDF.
export const toPx = function toPx(val, k) {
return Math.floor(val * k / 72 * 96);
}
+482
View File
@@ -0,0 +1,482 @@
import { jsPDF } from 'jspdf';
import * as html2canvas from 'html2canvas';
import { objType, createElement, cloneNode, toPx } from './utils.js';
import es6promise from 'es6-promise';
var Promise = es6promise.Promise;
/* ----- CONSTRUCTOR ----- */
var Worker = function Worker(opt) {
// Create the root parent for the proto chain, and the starting Worker.
var root = Object.assign(Worker.convert(Promise.resolve()),
JSON.parse(JSON.stringify(Worker.template)));
var self = Worker.convert(Promise.resolve(), root);
// Set progress, optional settings, and return.
self = self.setProgress(1, Worker, 1, [Worker]);
self = self.set(opt);
return self;
};
// Boilerplate for subclassing Promise.
Worker.prototype = Object.create(Promise.prototype);
Worker.prototype.constructor = Worker;
// Converts/casts promises into Workers.
Worker.convert = function convert(promise, inherit) {
// Uses prototypal inheritance to receive changes made to ancestors' properties.
promise.__proto__ = inherit || Worker.prototype;
return promise;
};
Worker.template = {
prop: {
src: null,
container: null,
overlay: null,
canvas: null,
img: null,
pdf: null,
pageSize: null
},
progress: {
val: 0,
state: null,
n: 0,
stack: []
},
opt: {
filename: 'file.pdf',
margin: [0,0,0,0],
image: { type: 'jpeg', quality: 0.95 },
enableLinks: true,
html2canvas: {},
jsPDF: {}
}
};
/* ----- FROM / TO ----- */
Worker.prototype.from = function from(src, type) {
function getType(src) {
switch (objType(src)) {
case 'string': return 'string';
case 'element': return src.nodeName.toLowerCase && src.nodeName.toLowerCase() === 'canvas' ? 'canvas' : 'element';
default: return 'unknown';
}
}
return this.then(function from_main() {
type = type || getType(src);
switch (type) {
case 'string': return this.set({ src: createElement('div', {innerHTML: src}) });
case 'element': return this.set({ src: src });
case 'canvas': return this.set({ canvas: src });
case 'img': return this.set({ img: src });
default: return this.error('Unknown source type.');
}
});
};
Worker.prototype.to = function to(target) {
// Route the 'to' request to the appropriate method.
switch (target) {
case 'container':
return this.toContainer();
case 'canvas':
return this.toCanvas();
case 'img':
return this.toImg();
case 'pdf':
return this.toPdf();
default:
return this.error('Invalid target.');
}
};
Worker.prototype.toContainer = function toContainer() {
// Set up function prerequisites.
var prereqs = [
function checkSrc() { return this.prop.src || this.error('Cannot duplicate - no source HTML.'); },
function checkPageSize() { return this.prop.pageSize || this.setPageSize(); }
];
return this.thenList(prereqs).then(function toContainer_main() {
// Define the CSS styles for the container and its overlay parent.
var overlayCSS = {
position: 'fixed', overflow: 'hidden', zIndex: 1000,
left: 0, right: 0, bottom: 0, top: 0,
backgroundColor: 'rgba(0,0,0,0.8)'
};
var containerCSS = {
position: 'absolute', width: this.prop.pageSize.inner.width + this.prop.pageSize.unit,
left: 0, right: 0, top: 0, height: 'auto', margin: 'auto',
backgroundColor: 'white'
};
// Set the overlay to hidden (could be changed in the future to provide a print preview).
overlayCSS.opacity = 0;
// Create and attach the elements.
var source = cloneNode(this.prop.src, this.opt.html2canvas.javascriptEnabled);
this.prop.overlay = createElement('div', { className: 'html2pdf__overlay', style: overlayCSS });
this.prop.container = createElement('div', { className: 'html2pdf__container', style: containerCSS });
this.prop.container.appendChild(source);
this.prop.overlay.appendChild(this.prop.container);
document.body.appendChild(this.prop.overlay);
});
};
Worker.prototype.toCanvas = function toCanvas() {
// Set up function prerequisites.
var prereqs = [
function checkContainer() { return document.body.contains(this.prop.container)
|| this.toContainer(); }
];
// Fulfill prereqs then create the canvas.
return this.thenList(prereqs).then(function toCanvas_main() {
// Handle old-fashioned 'onrendered' argument.
var options = Object.assign({}, this.opt.html2canvas);
delete options.onrendered;
return html2canvas(this.prop.container, options);
}).then(function toCanvas_post(canvas) {
// Handle old-fashioned 'onrendered' argument.
var onRendered = this.opt.html2canvas.onrendered || function () {};
onRendered(canvas);
this.prop.canvas = canvas;
document.body.removeChild(this.prop.overlay);
});
};
Worker.prototype.toImg = function toImg() {
// Set up function prerequisites.
var prereqs = [
function checkCanvas() { return this.prop.canvas || this.toCanvas(); }
];
// Fulfill prereqs then create the image.
return this.thenList(prereqs).then(function toImg_main() {
var imgData = this.prop.canvas.toDataURL('image/' + this.opt.image.type, this.opt.image.quality);
this.prop.img = document.createElement('img');
this.prop.img.src = imgData;
});
};
Worker.prototype.toPdf = function toPdf() {
// Set up function prerequisites.
var prereqs = [
function checkCanvas() { return this.prop.canvas || this.toCanvas(); },
function checkPageSize() { return this.prop.pageSize || this.setPageSize(); }
];
// Fulfill prereqs then create the image.
return this.thenList(prereqs).then(function toPdf_main() {
// Create local copies of frequently used properties.
var canvas = this.prop.canvas;
var opt = this.opt;
// Calculate the number of pages.
var pxFullHeight = canvas.height;
var pxPageHeight = Math.floor(canvas.width * this.prop.pageSize.inner.ratio);
var nPages = Math.ceil(pxFullHeight / pxPageHeight);
// Define pageHeight separately so it can be trimmed on the final page.
var pageHeight = this.prop.pageSize.inner.height;
// Create a one-page canvas to split up the full image.
var pageCanvas = document.createElement('canvas');
var pageCtx = pageCanvas.getContext('2d');
pageCanvas.width = canvas.width;
pageCanvas.height = pxPageHeight;
// Initialize the PDF.
this.prop.pdf = this.prop.pdf || new jsPDF(opt.jsPDF);
for (var page=0; page<nPages; page++) {
// Trim the final page to reduce file size.
if (page === nPages-1 && pxFullHeight % pxPageHeight !== 0) {
pageCanvas.height = pxFullHeight % pxPageHeight;
pageHeight = pageCanvas.height * this.prop.pageSize.inner.width / pageCanvas.width;
}
// Display the page.
var w = pageCanvas.width;
var h = pageCanvas.height;
pageCtx.fillStyle = 'white';
pageCtx.fillRect(0, 0, w, h);
pageCtx.drawImage(canvas, 0, page*pxPageHeight, w, h, 0, 0, w, h);
// Add the page to the PDF.
if (page) this.prop.pdf.addPage();
var imgData = pageCanvas.toDataURL('image/' + opt.image.type, opt.image.quality);
this.prop.pdf.addImage(imgData, opt.image.type, opt.margin[1], opt.margin[0],
this.prop.pageSize.inner.width, pageHeight);
}
});
};
/* ----- OUTPUT / SAVE ----- */
Worker.prototype.output = function output(type, options, src) {
// Redirect requests to the correct function (outputPdf / outputImg).
src = src || 'pdf';
if (src.toLowerCase() === 'img' || src.toLowerCase() === 'image') {
return this.outputImg(type, options);
} else {
return this.outputPdf(type, options);
}
};
Worker.prototype.outputPdf = function outputPdf(type, options) {
// Set up function prerequisites.
var prereqs = [
function checkPdf() { return this.prop.pdf || this.toPdf(); }
];
// Fulfill prereqs then perform the appropriate output.
return this.thenList(prereqs).then(function outputPdf_main() {
/* Currently implemented output types:
* https://rawgit.com/MrRio/jsPDF/master/docs/jspdf.js.html#line992
* save(options), arraybuffer, blob, bloburi/bloburl,
* datauristring/dataurlstring, dataurlnewwindow, datauri/dataurl
*/
return this.prop.pdf.output(type, options);
});
};
Worker.prototype.outputImg = function outputImg(type, options) {
// Set up function prerequisites.
var prereqs = [
function checkImg() { return this.prop.img || this.toImg(); }
];
// Fulfill prereqs then perform the appropriate output.
return this.thenList(prereqs).then(function outputImg_main() {
switch (type) {
case undefined:
case 'img':
return this.prop.img;
case 'datauristring':
case 'dataurlstring':
return this.prop.img.src;
case 'datauri':
case 'dataurl':
return document.location.href = this.prop.img.src;
default:
throw 'Image output type "' + type + '" is not supported.';
}
});
};
Worker.prototype.save = function save(filename) {
// Set up function prerequisites.
var prereqs = [
function checkPdf() { return this.prop.pdf || this.toPdf(); }
];
// Fulfill prereqs, update the filename (if provided), and save the PDF.
return this.thenList(prereqs).set(
filename ? { filename: filename } : null
).then(function save_main() {
this.prop.pdf.save(this.opt.filename);
});
};
/* ----- SET / GET ----- */
Worker.prototype.set = function set(opt) {
// TODO: Implement ordered pairs?
// Silently ignore invalid or empty input.
if (objType(opt) !== 'object') {
return this;
}
// Build an array of setter functions to queue.
var fns = Object.keys(opt || {}).map(function (key) {
switch (key) {
case 'margin':
return this.setMargin.bind(this, opt.margin);
case 'jsPDF':
return function set_jsPDF() { this.opt.jsPDF = opt.jsPDF; return this.setPageSize(); }
case 'pageSize':
return this.setPageSize.bind(this, opt.pageSize);
default:
if (key in Worker.template.prop) {
// Set pre-defined properties in prop.
return function set_prop() { this.prop[key] = opt[key]; }
} else {
// Set any other properties in opt.
return function set_opt() { this.opt[key] = opt[key] };
}
}
}, this);
// Set properties within the promise chain.
return this.then(function set_main() {
return this.thenList(fns);
});
};
Worker.prototype.get = function get(key, cbk) {
return this.then(function get_main() {
// Fetch the requested property, either as a predefined prop or in opt.
var val = (key in Worker.template.prop) ? this.prop[key] : this.opt[key];
return cbk ? cbk(val) : val;
});
};
Worker.prototype.setMargin = function setMargin(margin) {
return this.then(function setMargin_main() {
// Parse the margin property: [top, left, bottom, right].
switch (objType(margin)) {
case 'number':
margin = [margin, margin, margin, margin];
case 'array':
if (margin.length === 2) {
margin = [margin[0], margin[1], margin[0], margin[1]];
}
if (margin.length === 4) {
break;
}
default:
return this.error('Invalid margin array.');
}
// Set the margin property, then update pageSize.
this.opt.margin = margin;
}).then(this.setPageSize);
}
Worker.prototype.setPageSize = function setPageSize(pageSize) {
return this.then(function setPageSize_main() {
// Retrieve page-size based on jsPDF settings, if not explicitly provided.
pageSize = pageSize || jsPDF.getPageSize(this.opt.jsPDF);
// Add 'inner' field if not present.
if (!pageSize.hasOwnProperty('inner')) {
pageSize.inner = {
width: pageSize.width - this.opt.margin[1] - this.opt.margin[3],
height: pageSize.height - this.opt.margin[0] - this.opt.margin[2]
};
pageSize.inner.px = {
width: toPx(pageSize.inner.width, pageSize.k),
height: toPx(pageSize.inner.height, pageSize.k)
};
pageSize.inner.ratio = pageSize.inner.height / pageSize.inner.width;
}
// Attach pageSize to this.
this.prop.pageSize = pageSize;
});
}
Worker.prototype.setProgress = function setProgress(val, state, n, stack) {
// Immediately update all progress values.
if (val != null) this.progress.val = val;
if (state != null) this.progress.state = state;
if (n != null) this.progress.n = n;
if (stack != null) this.progress.stack = stack;
this.progress.ratio = this.progress.val / this.progress.state;
// Return this for command chaining.
return this;
};
Worker.prototype.updateProgress = function updateProgress(val, state, n, stack) {
// Immediately update all progress values, using setProgress.
return this.setProgress(
val ? this.progress.val + val : null,
state ? state : null,
n ? this.progress.n + n : null,
stack ? this.progress.stack.concat(stack) : null
);
};
/* ----- PROMISE MAPPING ----- */
Worker.prototype.then = function then(onFulfilled, onRejected) {
// Wrap `this` for encapsulation.
var self = this;
return this.thenCore(onFulfilled, onRejected, function then_main(onFulfilled, onRejected) {
// Update progress while queuing, calling, and resolving `then`.
self.updateProgress(null, null, 1, [onFulfilled]);
return Promise.prototype.then.call(this, function then_pre(val) {
self.updateProgress(null, onFulfilled);
return val;
}).then(onFulfilled, onRejected).then(function then_post(val) {
self.updateProgress(1);
return val;
});
});
};
Worker.prototype.thenCore = function thenCore(onFulfilled, onRejected, thenBase) {
// Handle optional thenBase parameter.
thenBase = thenBase || Promise.prototype.then;
// Wrap `this` for encapsulation and bind it to the promise handlers.
var self = this;
if (onFulfilled) { onFulfilled = onFulfilled.bind(self); }
if (onRejected) { onRejected = onRejected.bind(self); }
// Cast self into a Promise to avoid polyfills recursively defining `then`.
var isNative = Promise.toString().indexOf('[native code]') !== -1 && Promise.name === 'Promise';
var selfPromise = isNative ? self : Worker.convert(Object.assign({}, self), Promise.prototype);
// Return the promise, after casting it into a Worker and preserving props.
var returnVal = thenBase.call(selfPromise, onFulfilled, onRejected);
return Worker.convert(returnVal, self.__proto__);
};
Worker.prototype.thenExternal = function thenExternal(onFulfilled, onRejected) {
// Call `then` and return a standard promise (exits the Worker chain).
return Promise.prototype.then.call(this, onFulfilled, onRejected);
};
Worker.prototype.thenList = function thenList(fns) {
// Queue a series of promise 'factories' into the promise chain.
var self = this;
fns.forEach(function thenList_forEach(fn) {
self = self.thenCore(fn);
});
return self;
};
Worker.prototype['catch'] = function (onRejected) {
// Bind `this` to the promise handler, call `catch`, and return a Worker.
if (onRejected) { onRejected = onRejected.bind(this); }
var returnVal = Promise.prototype['catch'].call(this, onRejected);
return Worker.convert(returnVal, this);
};
Worker.prototype.catchExternal = function catchExternal(onRejected) {
// Call `catch` and return a standard promise (exits the Worker chain).
return Promise.prototype['catch'].call(this, onRejected);
};
Worker.prototype.error = function error(msg) {
// Throw the error in the Promise chain.
return this.then(function error_main() {
throw new Error(msg);
});
};
/* ----- ALIASES ----- */
Worker.prototype.using = Worker.prototype.set;
Worker.prototype.saveAs = Worker.prototype.save;
Worker.prototype.export = Worker.prototype.output;
Worker.prototype.run = Worker.prototype.then;
/* ----- FINISHING ----- */
// Expose the Worker class.
export default Worker;