Import initial du projet Production

This commit is contained in:
KANE LAZENI
2025-12-01 16:12:12 +00:00
commit 2f364ab2fc
14257 changed files with 3395325 additions and 0 deletions

View File

@@ -0,0 +1,3 @@
last 1 version
> 1%
IE >= 9

3
assets/js/html2pdf.js-master/.gitignore vendored Executable file
View File

@@ -0,0 +1,3 @@
node_modules/
.archive/
.devel/

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.

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 `master`, 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/)>

View File

@@ -0,0 +1 @@
theme: jekyll-theme-cayman

View File

@@ -0,0 +1,9 @@
{
"presets": [
[ "@babel/preset-env", {
"useBuiltIns": "usage",
"corejs": { "version": "3.10", "proposals": true }
}]
],
"sourceType": "unambiguous"
}

View File

@@ -0,0 +1,28 @@
{
"name": "html2pdf.js",
"description": "Client-side HTML-to-PDF rendering using pure JS",
"main": "dist/html2pdf.bundle.js",
"moduleType": [
"amd",
"globals",
"node"
],
"authors": [
"Erik Koopmans <erik@erik-koopmans.com>"
],
"license": "MIT",
"keywords": [
"javascript",
"pdf-generation",
"html",
"client-side",
"canvas"
],
"homepage": "https://github.com/eKoopmans/html2pdf",
"ignore": [
"node_modules/",
"bower_components/",
".archive/",
".devel/"
]
}

View File

@@ -0,0 +1,69 @@
#!/usr/bin/env node
const { program } = require('commander');
const { promisify } = require('util');
const exec = promisify(require('child_process').exec);
const { readFileSync } = require('fs');
program
.command('release [newversion] [tagmessage]')
.description('Bump version, build, commit, tag, and promote to local stable branch')
.action(release)
program
.command('publish-gh')
.description('Push master and stable branches to GitHub with tags')
.action(publishGH)
program.parse(process.argv);
/* ----- HELPER ----- */
function getVersion() {
// Uses readFileSync() instead of require() to prevent caching of values.
const pkg = JSON.parse(readFileSync('./package.json'));
return `v${pkg.version}`;
}
/* ----- SUBTASKS ----- */
// Bump version using NPM (only affects package*.json, doesn't commit).
function bumpVersion(newversion) {
console.log('Bumping version number.');
return exec(`npm --no-git-tag-version version ${newversion}`);
}
// Build, commit, and tag in master with the new release version.
async function buildCommitTag(tagmessage) {
console.log('Running build process in master branch.');
await exec(`git checkout master && npm run build`);
const version = getVersion();
const fullTagMessage = tagmessage ? `${version} ${tagmessage}` : version;
console.log('Adding all changes and performing final commit.');
await exec(`git add -A && git commit --allow-empty -m "Build ${version}"`);
console.log('Tagging with provided tag message.');
return exec(`git tag -a ${version} -m "${fullTagMessage}"`);
}
// Pushes master into the local stable branch.
async function promoteToStable() {
console.log('Getting repo root location.');
const res = await exec('git rev-parse --show-toplevel');
const repoRoot = res.stdout.trim('\n');
console.log('Pushing release to local stable branch.');
return exec(`git push --follow-tags ${repoRoot} master:stable`)
}
/* ----- TASKS ----- */
async function release(newversion, tagmessage) {
await bumpVersion(newversion || 'patch');
await buildCommitTag(tagmessage);
await promoteToStable();
}
function publishGH() {
return exec('git push --follow-tags origin master stable');
}

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

5870
assets/js/html2pdf.js-master/dist/html2pdf.js vendored Executable file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

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.1
* Copyright (c) 2021 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

View File

@@ -0,0 +1,116 @@
// Karma configuration
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha', 'chai-spies', 'chai'],
// list of files / patterns to load in the browser
files: [
{ pattern: 'src/index.js', watched: false, served: true },
{ pattern: 'test/**/*.js', watched: true },
{ pattern: 'test/reference/*.*', included: false, served: true },
{ pattern: require.resolve('pdftest/dist/pdftest.client.min.js'), watched: false },
{ pattern: require.resolve('pdftest/dist/chai-pdftest.min.js'), watched: false },
],
// list of files / patterns to exclude
exclude: [
'test/manual/',
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'src/index.js': ['webpack'],
'test/**/*.js': ['webpackTests'],
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['mocha'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity,
// Remove timeouts so the PDF snapshot GUI can wait on user feedback.
browserNoActivityTimeout: 0,
// Suppress console.log messages
client: {
// captureConsole: false
},
webpackPreprocessor: {
output: {
library: 'html2pdf',
libraryExport: 'default',
},
target: 'browserslist',
optimization: { minimize: false },
watch: true,
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
],
},
},
customPreprocessors: {
webpackTests: {
base: 'webpack',
options: {
output: {},
externals: ['html2pdf'],
externalsType: 'global',
},
},
},
});
}

13013
assets/js/html2pdf.js-master/package-lock.json generated Executable file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,75 @@
{
"name": "html2pdf.js",
"version": "0.10.1",
"description": "Client-side HTML-to-PDF rendering using pure JS",
"main": "dist/html2pdf.js",
"files": [
"/src",
"/dist"
],
"repository": {
"type": "git",
"url": "git+https://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": "^2.3.1"
},
"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",
"commander": "^7.2.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",
"release": "node ./build-scripts.js release",
"publish-gh": "node ./build-scripts.js publish-gh"
}
}

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;

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);
}
});
};

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;

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);
}
});
});
};

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);
}

View File

@@ -0,0 +1,481 @@
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 === '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(); }
];
// 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;

View File

@@ -0,0 +1,11 @@
describe('creation', function () {
it('html2pdf should exist', function () {
expect(window.html2pdf).to.exist;
});
it('html2pdf() should produce a thenable object', function () {
expect(html2pdf().then).to.be.a('function');
});
it('new html2pdf.Worker should produce a thenable object', function () {
expect((new html2pdf.Worker).then).to.be.a('function');
});
});

View File

@@ -0,0 +1,82 @@
<!DOCTYPE html>
<html>
<head>
<style>
html, body {
height: 100%;
}
#iframe {
position: relative;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<p>This is for testing on localhost (run npx serve at project root). Does not work on file:// protocol.</p>
<p>
Target test file: <input id="target" value="../reference/lorem-ipsum.html">
<button onclick="loadIframe()">Load in iframe</button>
<button onclick="loadPopup()">Load in popup</button>
<span id="ready"></span>
</p>
<p>
Document querySelector: <input id="selector" value="body">
<button onclick="savePdf()">Make PDF and save</button>
<button onclick="makeContainer()">Make PDF container and set visible</button>
</p>
<iframe id="iframe"></iframe>
<script>
var html2pdf;
var _window;
var popup;
var target = document.getElementById('target');
var iframe = document.getElementById('iframe');
var ready = document.getElementById('ready');
var selector = document.getElementById('selector');
function loadIframe () {
ready.innerHTML = '';
iframe.onload = function () { _window = iframe.contentWindow; testLoaded(); };
iframe.src = target.value;
}
function loadPopup () {
ready.innerHTML = '';
_window = window.open(target.value, 'html2pdf testing', 'location=0');
_window.addEventListener('load', testLoaded);
_window.focus();
}
function testLoaded () {
var _document = _window.document;
var script = _document.createElement('script');
script.addEventListener('load', scriptLoaded);
script.src = '../../dist/html2pdf.bundle.js';
_document.body.appendChild(script);
}
function scriptLoaded () {
html2pdf = _window.html2pdf;
ready.innerHTML = 'Ready';
}
function savePdf () {
_window.focus();
var element = _window.document.querySelector(selector.value);
html2pdf().from(element).save();
}
function makeContainer () {
_window.focus();
var element = _window.document.querySelector(selector.value);
html2pdf().from(element).toContainer().then(function () {
_window.document.querySelector('.html2pdf__overlay').style.opacity = 1;
});
}
</script>
</body>
</html>

View File

@@ -0,0 +1,123 @@
<!DOCTYPE HTML>
<html>
<head>
<title>html2pdf Test - Pagebreaks</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style type="text/css">
/* Avoid unexpected sizing on all elements. */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
/* CSS styling for before/after/avoid. */
.before {
page-break-before: always;
}
.after {
page-break-after: always;
}
.avoid {
page-break-inside: avoid;
}
/* Big and bigger elements. */
.big {
height: 10.9in;
background-color: yellow;
border: 1px solid black;
}
.fullpage {
height: 11in;
background-color: fuchsia;
border: 1px solid black;
}
.bigger {
height: 11.1in;
background-color: aqua;
border: 1px solid black;
}
/* Table styling */
table {
border-collapse: collapse;
}
td {
border: 1px solid black;
}
</style>
</head>
<body>
<!-- Different options. -->
<select id="mode">
<option value="avoid-all">Avoid-all</option>
<option value="css">CSS</option>
<option value="legacy">Legacy</option>
<option value="specify">Specified elements (using before/after/avoid)</option>
</select>
<!-- Button to generate PDF. -->
<button onclick="test()">Generate PDF</button>
<!-- Div to capture. -->
<div id="root">
<p>First line</p>
<p class="before">Break before</p>
<p class="after">Break after</p>
<p>No effect (should be top of 3rd page, using css or specify).</p>
<p class="html2pdf__page-break">Legacy (should create a break after).</p>
<p>No effect (should be top of 2nd page, using legacy).</p>
<p class="avoid big">Big element (should start on new page, using avoid-all/css/specify).</p>
<p>No effect (should start on next page *only* using avoid-all).</p>
<p>No effect (for spacing).</p>
<p class="avoid fullpage">Full-page element (should start on new page using avoid-all/css/specify).</p>
<p>No effect (for spacing).</p>
<p class="avoid bigger">Even bigger element (should continue normally, because it's more than a page).</p>
<!-- Advanced avoid-all tests. -->
<div>
<p>No effect inside parent div (testing avoid-all - no break yet because parent is more than a page).</p>
<p class="big">Big element inside parent div (testing avoid-all - should have break before this).</p>
</div>
<table>
<tr>
<td>Cell 1-1 - start of new page (avoid-all only)</td>
<td>Cell 1-2 - start of new page (avoid-all only)</td>
</tr>
<tr class="big">
<td>Cell 2-1 - start of another new page (avoid-all only)</td>
<td>Cell 2-2 - start of another new page (avoid-all only)</td>
</tr>
</table>
</div>
<!-- Include html2pdf bundle. -->
<script src="../../dist/html2pdf.bundle.js"></script>
<script>
// Pagebreak fields: mode, before, after, avoid
// Pagebreak modes: 'avoid-all', 'css', 'legacy'
function test() {
// Get the element.
var element = document.getElementById('root');
// Choose pagebreak options based on mode.
var mode = document.getElementById('mode').value;
var pagebreak = (mode === 'specify') ?
{ mode: '', before: '.before', after: '.after', avoid: '.avoid' } :
{ mode: mode };
// Generate the PDF.
html2pdf().from(element).set({
filename: mode + '.pdf',
pagebreak: pagebreak,
jsPDF: {orientation: 'portrait', unit: 'in', format: 'letter', compressPDF: true}
}).save();
}
</script>
</body>
</html>

View File

@@ -0,0 +1,44 @@
<!DOCTYPE HTML>
<html>
<head>
<title>html2pdf Test - Template</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style type="text/css">
/* Basic styling for root. */
#root {
width: 500px;
height: 700px;
background-color: yellow;
}
</style>
</head>
<body>
<!-- Button to generate PDF. -->
<button onclick="test()">Generate PDF</button>
<!-- Div to capture. -->
<div id="root">
This is a test
</div>
<!-- Include html2pdf bundle. -->
<script src="../../dist/html2pdf.bundle.js"></script>
<script>
function test() {
// Get the element.
var element = document.getElementById('root');
// Generate the PDF.
html2pdf().from(element).set({
margin: 1,
filename: 'test.pdf',
html2canvas: { scale: 2 },
jsPDF: {orientation: 'portrait', unit: 'in', format: 'letter', compressPDF: true}
}).save();
}
</script>
</body>
</html>

View File

@@ -0,0 +1,13 @@
describe('promise', function () {
it('promises should exist', function () {
expect(window.Promise).to.exist;
});
it('promises should resolve', function () {
return Promise.resolve();
});
it('promises should preserve their value', function () {
return Promise.resolve(5).then(function (result) {
expect(result).to.equal(5);
});
});
});

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

View File

@@ -0,0 +1,284 @@
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="baseline.css">
<style type="text/css">
table {
border-collapse: collapse;
}
table td, table th {
border: 1px solid black;
}
.header {
background-color: #593186;
color: white;
padding: 10px;
}
.table-left {
background-color:#888;
}
.table-main {
background-color:#BBB;
}
</style>
</head>
<body>
<!-- Text tags -->
<h1 class="header" id="text-tags">Text Tags</h1>
<h1>Header 1</h1>
<h2>Header 2</h2>
<h3>Header 3</h3>
<h4>Header 4</h4>
<h5>Header 5</h5>
<h6>Header 6</h6>
<p>Paragraph</p>
<address>Address</address>
<blockquote>Block quote</blockquote>
<pre>Preformatted text (preserves spaces and
line breaks)</pre>
Horizontal rule: <hr>
<!-- Lists -->
<h1 class="header" id="lists">Lists</h1>
<ol>
<li>Ordered</li>
<li>list</li>
</ol>
<ul>
<li>Unordered</li>
<li>list</li>
</ul>
<dl>
<dt>Description list</dt>
<dd>terms paired with their description</dd>
<dt>Another term</dt>
<dd>description</dd>
</dl>
<details open>
<summary>Details element - Summary</summary>
<p>Details (hidden when collapsed)</p>
</details>
<select>
<option>Drop-down</option>
<option>list</option>
<optgroup label="With groups">
<option>Group item 1</option>
<option>Group item 2</option>
</optgroup>
</select>
<!-- Text styling (in a paragraph) -->
<h1 class="header" id="text-styling">Text Styling</h1>
<p>
line break,<br>
<b>bold,</b>
<i>italics,</i>
<u>underlined,</u>
<s>inaccurate,</s>
<mark>marked,</mark>
<small>small,</small>
<sub>subscript,</sub>
<sup>superscript,</sup>
<!-- <q>short quotation,</q> -->
<abbr title="Abbreviation">abbrev.</abbr>,
<code>code,</code>
<br>
<strong>important,</strong>
<em>emphasized,</em>
<ins>inserted,</ins>
<del>deleted,</del>
<samp>computer output,</samp>
<kbd>keyboard input,</kbd>
<var>variable,</var>
<cite>title of a work,</cite>
<dfn>definition,</dfn>
<br>
<span>span (a way of sectioning off text),</span>
<br>
word break oppor<wbr />tunity (for long words),
<br>
<time datetime="08:00">time (for machine readability),</time>
<data value="12345">data (for machine readability),</data>
<br>
<bdi>bi-directional isolation (text direction),</bdi>
<bdo dir="rtl">bi-directional override</bdo>,
<ruby>ruby annotation<rp>(</rp><rt>explanation/pronunciation</rt><rp>)</rp></ruby>
</p>
<!-- Sections -->
<h1 class="header" id="sections">Sections</h1>
<div>Div: Basic division/section</div>
<article>Article: Independent, self-contained content</article>
<aside>Aside: Indirectly related to the surrounding content</aside>
<dialog open>Dialog: Dialog box or subwindow</dialog>
<header>Header: Introductory content</header>
<main>Main: Main content</main>
<footer>Footer: Copyright, contact info, etc.</footer>
<nav>Nav: Set of <a href="#sections">navigation</a> <a href="#tables">links</a></nav>
<section>Section: Thematic grouping of content</section>
<!-- Tables -->
<h1 class="header" id="tables">Tables</h1>
<p><em><strong>Note:</strong> Tables do not have borders (lines between cells) by default. These must be added using CSS.</em></p>
<!-- Simple table -->
<h3>Simple table</h3>
<table>
<tr>
<td>Row 1 cell 1</td>
<td>Row 1 cell 2</td>
</tr>
<tr>
<td>Row 2 cell 1</td>
<td>Row 2 cell 2</td>
</tr>
</table>
<!-- Advanced table -->
<h3>Advanced table</h3>
<table>
<caption>Table caption</caption>
<colgroup>
<col class="table-left">
<col class="table-main" span="2">
</colgroup>
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1 cell 1</td>
<td>Row 1 cell 2</td>
<td>Row 1 cell 3</td>
</tr>
<tr>
<td>Row 2 cell 1</td>
<td>Row 2 cell 2</td>
<td>Row 2 cell 3</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Footer 1</td>
<td colspan="2">Footer 2 (Spanning 2 columns)</td>
</tr>
</tfoot>
</table>
<!-- Forms -->
<h1 class="header" id="forms">Forms</h1>
<form action="">
Text input: <input type="text" name="textInput1" value="Value"><br>
Button input: <input type="button" value="Button"><br>
Checkbox input: <input type="checkbox"><br>
Color input: <input type="color"><br>
Date input: <input type="date"><br>
Datetime input: <input type="datetime-local"><br>
Email input: <input type="email"><br>
File input: <input type="file"><br>
Hidden input: <input type="hidden"><br>
Image input: <input type="image"><br>
Month input: <input type="month"><br>
Number input: <input type="number"><br>
Password input: <input type="password"><br>
Radio input: <input type="radio"><br>
Range input: <input type="range"><br>
Reset input: <input type="reset"><br>
Search input: <input type="search"><br>
Submit input: <input type="submit"><br>
Tel input: <input type="tel"><br>
Time input: <input type="time"><br>
URL input: <input type="url"><br>
Week input: <input type="week"><br>
<label for="textInput2">Label (for text input):</label>
<input type="text" id="textInput2" name="textInput2" placeholder="Placeholder"><br>
Input with datalist: <input list="datalist1"><br>
<datalist id="datalist1">
<option>Option 1</option>
<option>Option 2</option>
</datalist>
<output>Output</output><br>
<textarea>Textarea</textarea><br>
<fieldset>
<legend>Fieldset with legend</legend>
Input in a fieldset: <input>
</fieldset>
</form>
<!-- Inline elements -->
<h1 class="header" id="inline-elements">Inline elements</h1>
<a href="https://www.google.com/">Anchor tag (hyperlink)</a>
<button>Button</button>
<meter value="0.6">60%</meter>
<progress value="0.6">60%</progress>
<!-- <iframe src="lorem-ipsum.html"></iframe> -->
<embed type="text/html" src="lorem-ipsum.html" />
<object data="lorem-ipsum.html">
<param name="autoplay" value="true">
</object>
<!-- Media elements -->
<h1 class="header" id="media-elements">Media elements</h1>
<img src="Wikipedia-logo-v2.png" alt="Wikipedia logo">
<picture>
<source media="(min-width:650px)" srcset="Wikipedia-logo-v2.png" />
<img src="Wikipedia-logo-v2.png" alt="Wikipedia logo">
</picture>
<img src="Wikipedia-logo-v2.png" alt="Wikipedia logo" usemap="#imgmap">
<map name="imgmap">
<area shape="rect" coords="0,0,100,92" alt="Area 1" href="#text-tags">
<area shape="rect" coords="100,92,200,183" alt="Area 2" href="#media-elements">
</map>
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
Sorry, your browser does not support inline SVG.
</svg>
<canvas id="canvas">Your browser does not support the canvas tag.</canvas>
<audio controls>
<source src="https://www.w3schools.com/TAGS/horse.mp3" />
<track src="" kind="subtitles" />
</audio>
<video controls poster="Wikipedia-logo-v2.png">
<source src="https://www.w3schools.com/TAGS/movie.mp4" />
</video>
<figure>
<img src="Wikipedia-logo-v2.png" alt="Wikipedia logo">
<figcaption>Figure with caption</figcaption>
</figure>
<!-- Non-rendered elements -->
<noscript>Only rendered when JS is disabled</noscript>
<template>Used for duplication with JS</template>
<script>
var ctx = document.getElementById("canvas").getContext('2d');
ctx.fillStyle = "#FF0000";
ctx.fillRect(0, 0, 300, 150);
</script>
</body>
</html>

View File

@@ -0,0 +1,4 @@
html, body {
margin: 0;
padding: 0;
}

View File

@@ -0,0 +1,9 @@
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="baseline.css">
</head>
<body>
</body>
</html>

View File

@@ -0,0 +1,63 @@
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="baseline.css">
<style>
p {
background-color: red;
margin: 0;
min-height: 18px;
}
.test-class-selector {
background-color: orange;
}
#test-id-selector {
background-color: yellow;
}
[data-attribute="test-attribute-selector"] {
background-color: green;
}
.test-after-empty-selectors::after {
content: "Test after and empty selectors";
background-color: blue;
}
p:empty {
background-color: indigo;
}
#main .test-ancestor-selector {
background-color: violet;
}
#main > .test-parent-selector {
background-color: #eee;
}
.test-parent-selector + .test-direct-sibling-selector {
background-color: #ddd;
}
.test-parent-selector ~ .test-sibling-selector {
background-color: #ccc;
}
#unincluded-ancestor .test-unincluded-ancestor {
background-color: #bbb;
}
</style>
</head>
<body>
<div id="unincluded-ancestor">
<div id="main">
<!-- The parent divs here are for the "test-untargeted-ancestor" condition. -->
<p>Test element selector</p>
<p class="test-class-selector">Test class selector</p>
<p id="test-id-selector">Test ID selector</p>
<p data-attribute="test-attribute-selector">Test attribute selector</p>
<p class="test-after-empty-selectors"></p>
<p class="test-empty-selector"></p>
<p class="test-ancestor-selector">Test ancestor selector</p>
<p class="test-parent-selector">Test parent selector</p>
<p class="test-direct-sibling-selector">Test direct sibling selector</p>
<p class="test-sibling-selector">Test general sibling selector</p>
<p class="test-unincluded-ancestor">Test unincluded ancestor (KNOWN FAILURE - WILL APPEAR RED)</p>
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,21 @@
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="baseline.css">
</head>
<body>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis tempor nisl sit amet consectetur pharetra. In iaculis venenatis mauris eu mollis. Nulla facilisi. Donec id eros vel metus sodales blandit placerat eget enim. Mauris orci ipsum, cursus vel nisl et, euismod varius elit. Mauris eleifend ipsum eu dui venenatis malesuada sed at nisl. Mauris eu varius massa.</p>
<p>Morbi est turpis, lacinia nec turpis ut, pretium venenatis magna. Donec ultricies dolor sit amet ante rutrum, a maximus orci commodo. Morbi nisi lectus, faucibus a feugiat ac, viverra quis mi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut sit amet auctor felis. Donec id enim nec lacus ullamcorper iaculis. Nunc quis nisi orci. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Praesent aliquet vel tellus at fermentum. Pellentesque faucibus ipsum et turpis condimentum viverra. Donec sed ante ac purus porttitor condimentum ac id metus. Fusce vel risus pellentesque, molestie nisi et, iaculis nunc. Quisque ut neque vitae dui suscipit mollis in sed magna.</p>
<p>Quisque volutpat feugiat augue. Fusce lacinia tempus elit, vel gravida est congue rutrum. Nullam nec nisi id mi consequat luctus et non sem. Sed suscipit, velit nec lobortis bibendum, ex mauris vestibulum quam, id consectetur magna augue quis felis. In eget augue non ex consectetur molestie. Maecenas suscipit eget magna mattis ullamcorper. Nam at ornare massa. Suspendisse non ex tincidunt, commodo tortor ac, rutrum ex.</p>
<p>Donec blandit sem erat, in facilisis velit malesuada sed. In hac habitasse platea dictumst. Vivamus blandit faucibus tempus. Maecenas porttitor mi id neque pulvinar imperdiet. Mauris accumsan lorem in urna pulvinar imperdiet. Pellentesque magna mi, tempor sed euismod a, blandit at arcu. Mauris sit amet lacinia sem. Nulla volutpat ac tortor a venenatis. Nunc non odio dictum, sodales metus vel, faucibus libero. Maecenas nisl mi, blandit quis leo in, molestie vulputate libero.</p>
<p>Aliquam erat volutpat. Fusce ac odio nulla. Nam mattis sem velit, eu aliquam quam dictum in. Proin fermentum vestibulum tellus sit amet varius. Maecenas in porttitor metus. Fusce vestibulum augue risus, ut rutrum odio aliquet id. Curabitur sed vulputate est. Sed euismod cursus sem, id aliquam leo sodales quis. Pellentesque bibendum odio a mi varius placerat. In eleifend sem eu scelerisque blandit. Praesent vehicula metus sed libero egestas, a varius nulla consectetur. Quisque hendrerit rutrum nisl, quis pretium elit ullamcorper non. Duis nec suscipit odio.</p>
<p>Mauris in ipsum fermentum, accumsan metus in, interdum neque. Sed ullamcorper eget sem sed ultricies. Suspendisse consectetur sem id lectus tincidunt vehicula. Aenean nec lorem purus. Quisque dapibus sollicitudin eros quis laoreet. Maecenas lacus odio, laoreet eu turpis vitae, tristique tincidunt turpis. In malesuada egestas lectus nec consequat. Maecenas posuere, nibh at porttitor mollis, purus sem fermentum nisi, eu laoreet sem velit nec risus. Fusce sodales ex massa, sed egestas odio egestas nec. Curabitur in leo tellus. Etiam tellus ipsum, finibus ut tellus non, fermentum suscipit magna. Donec tincidunt placerat urna eu tristique. Suspendisse sit amet facilisis ipsum. Donec varius convallis nibh nec euismod. Nullam scelerisque ultricies mollis. Cras tincidunt consequat neque eu efficitur.</p>
<p>Duis non elit imperdiet, interdum ante ut, ornare lorem. Aenean vel ante volutpat, maximus ex ut, egestas enim. Vivamus sodales est id augue mattis, vitae dapibus orci tempor. Mauris neque odio, varius et justo sed, venenatis lacinia elit. Suspendisse non dapibus orci. Mauris pellentesque leo eu ipsum gravida, eu tempor elit pretium. Phasellus eu sapien iaculis, consectetur felis sit amet, auctor odio. Duis ac feugiat eros, id elementum urna. Suspendisse at sagittis lectus. Etiam eget sodales augue, ac volutpat mauris. Donec blandit luctus purus ac ultrices.</p>
<p>Aliquam sed tellus ligula. Sed vitae dapibus elit, sed vulputate ipsum. Nullam a mauris nec neque commodo iaculis. Proin mattis luctus libero eu mollis. Mauris justo justo, placerat ut diam sagittis, semper semper turpis. In lobortis quis erat ac lobortis. Vivamus nunc risus, interdum a turpis nec, consequat bibendum libero. Sed ac sollicitudin libero. Aenean dapibus lorem a mauris lacinia luctus. Nullam consectetur, turpis at lobortis vehicula, ipsum arcu hendrerit diam, at dictum dui ligula quis tellus. Ut nec tempor purus, nec rutrum purus. Aenean eget lorem orci. Maecenas aliquet condimentum lectus, non tristique orci semper sed. Pellentesque lacinia enim et enim sagittis dapibus. Phasellus vitae risus sit amet velit egestas vulputate aliquam et nisi.</p>
<p>Praesent non ante gravida, auctor mauris in, scelerisque odio. Mauris semper magna eget ligula euismod tincidunt. Praesent non pharetra lacus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Morbi quis massa libero. Aenean ac cursus turpis. Mauris sed enim purus. Donec gravida ex sit amet sollicitudin bibendum. Vivamus sed felis nulla. Cras vulputate metus vitae velit congue gravida. Donec quis eros porta, venenatis purus quis, malesuada quam.</p>
<p>Aenean non consequat nunc. Nulla lectus nibh, imperdiet vel lorem vel, volutpat interdum est. Cras fringilla enim sed tortor convallis, ac eleifend dolor pellentesque. Maecenas ut arcu non nunc luctus consectetur. Donec tincidunt at odio vel porta. Pellentesque tincidunt mauris nec nisi cursus ornare. Nulla in ipsum dui. Sed consequat eget nibh non malesuada. Nulla pulvinar nibh non scelerisque dapibus. Nam viverra turpis eget fringilla pulvinar. Quisque et augue fermentum, bibendum risus in, placerat lacus. Sed tempus quam massa, ac dignissim est volutpat quis. Aliquam ligula elit, tempor vel mollis quis, convallis nec leo. In sed mattis eros.</p>
<p>Mauris lobortis aliquet rutrum. Ut eros augue, interdum ut porttitor ac, eleifend vitae lectus. Nunc scelerisque orci sed eros vulputate, sed dapibus purus iaculis. Cras sagittis odio in augue euismod, at consequat leo tempus. Nullam sed porta arcu, at pulvinar lorem. Fusce ex enim, sollicitudin a congue ut, pellentesque eu enim. Nullam dolor augue, bibendum eget blandit id, vulputate interdum augue. Cras porttitor mattis nulla eget tincidunt. Suspendisse ultrices nibh quis accumsan rhoncus. Quisque massa mi, sollicitudin ut leo et, convallis maximus eros. Duis et ipsum sed quam porta ultrices eget dapibus orci. Etiam dapibus lectus dui, non facilisis lectus placerat id. Etiam sit amet tellus ac nunc sagittis tempus efficitur eu sem.</p>
<p>In erat risus, sagittis et elit vitae, egestas iaculis tellus. Nulla sed mi volutpat urna mollis egestas nec vitae enim. Vestibulum ac pretium odio. Sed at leo bibendum justo lobortis consequat non vitae elit. Cras maximus neque id erat sollicitudin fermentum. Aenean tincidunt non nibh in pellentesque. Ut eu augue gravida, dictum ipsum ut, scelerisque sapien. Etiam malesuada mi lacus, vel ornare augue accumsan suscipit.</p>
</body>
</html>

View File

@@ -0,0 +1,83 @@
<!DOCTYPE html>
<html>
<head>
<title>html2pdf Test - Pagebreaks</title>
<link rel="stylesheet" href="baseline.css">
<style type="text/css">
/* Avoid unexpected sizing on all elements. */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
/* CSS styling for before/after/avoid. */
.before {
page-break-before: always;
}
.after {
page-break-after: always;
}
.avoid {
page-break-inside: avoid;
}
/* Big and bigger elements. */
.big {
height: 10.9in;
background-color: yellow;
border: 1px solid black;
}
.fullpage {
height: 11in;
background-color: fuchsia;
border: 1px solid black;
}
.bigger {
height: 11.1in;
background-color: aqua;
border: 1px solid black;
}
/* Table styling */
table {
border-collapse: collapse;
}
td {
border: 1px solid black;
}
</style>
</head>
<body>
<p>First line</p>
<p class="before">Break before</p>
<p class="after">Break after</p>
<p>No effect (should be top of 3rd page, using css or specify).</p>
<p class="html2pdf__page-break">Legacy (should create a break after).</p>
<p>No effect (should be top of 2nd page, using legacy).</p>
<p class="avoid big">Big element (should start on new page, using avoid-all/css/specify).</p>
<p>No effect (should start on next page *only* using avoid-all).</p>
<p>No effect (for spacing).</p>
<p class="avoid fullpage">Full-page element (should start on new page using avoid-all/css/specify).</p>
<p>No effect (for spacing).</p>
<p class="avoid bigger">Even bigger element (should continue normally, because it's more than a page).</p>
<!-- Advanced avoid-all tests. -->
<div>
<p>No effect inside parent div (testing avoid-all - no break yet because parent is more than a page).</p>
<p class="big">Big element inside parent div (testing avoid-all - should have break before this).</p>
</div>
<table>
<tr>
<td>Cell 1-1 - start of new page (avoid-all only)</td>
<td>Cell 1-2 - start of new page (avoid-all only)</td>
</tr>
<tr class="big">
<td>Cell 2-1 - start of another new page (avoid-all only)</td>
<td>Cell 2-2 - start of another new page (avoid-all only)</td>
</tr>
</table>
</body>
</html>

View File

@@ -0,0 +1,130 @@
describe('settings', function () {
describe('default settings', function () {
var worker = html2pdf();
var template = html2pdf.Worker.template;
for (var key in template) {
it(key + ' should begin with its default value', function () {
// Use eql (a deep equal) to compare objects.
expect(worker[key]).to.eql(template[key]);
});
}
});
// Sample settings to test with.
var settings = {
src: document.createElement('div'),
container: document.createElement('div'),
overlay: document.createElement('div'),
canvas: document.createElement('canvas'),
img: document.createElement('img'),
pdf: 'REPLACE WITH NEW JSPDF',
// Omitting pageSize because of unique behaviour.
// pageSize: { 'width': 595.28, 'height': 841.89, 'unit': 'pt', 'k': 1 },
filename: 'test.pdf',
margin: [1,2,3,4],
image: { type: 'png', quality: 1.0 },
enableLinks: false,
html2canvas: {test: 1},
jsPDF: {test: 1},
miscOpt: 1
};
describe('changing settings (batch)', function () {
var worker = html2pdf().set(settings);
for (var key in settings) {
it(key + ' should be set to ' + settings[key], function () {
return worker.get(key).then(function (val) {
expect(val).to.eql(settings[key]);
});
});
}
});
describe('changing settings (individual)', function () {
var worker = html2pdf();
for (var key in settings) {
it(key + ' should be set to ' + settings[key], function () {
var setting = {};
setting[key] = settings[key];
return worker.set(setting).get(key).then(function (val) {
expect(val).to.eql(settings[key]);
});
});
}
});
describe('changing margin', function () {
var worker = html2pdf();
it('setMargin should work with [1,1,1,1]', function () {
return worker.setMargin([1,1,1,1]).get('margin').then(function (val) {
expect(val).to.eql([1,1,1,1]);
});
});
it('should convert [2,3] (w,h) to [2,3,2,3] (top,left,bottom,right)', function () {
return worker.setMargin([2,3]).get('margin').then(function (val) {
expect(val).to.eql([2,3,2,3]);
});
});
it('should convert 4 (margin) to [4,4,4,4] (top,left,bottom,right)', function () {
return worker.setMargin(4).get('margin').then(function (val) {
expect(val).to.eql([4,4,4,4]);
});
});
});
describe('changing pageSize', function () {
// NOTE: Currently setPageSize() should not be used externally, it's interdependent with the jsPDF setting.
function makePageSize(unit, k, format, margin) {
var pageSize = {unit: unit, k: k, width: format[0] / k, height: format[1] / k};
pageSize.inner = {
width: pageSize.width - margin[1] - margin[3],
height: pageSize.height - margin[0] - 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;
return pageSize;
}
function toPx(val, k) {
return Math.floor(val * k / 72 * 96);
}
it('set({ pageSize }) should call setPageSize', function () {
var worker = html2pdf();
chai.spy.on(worker, 'setPageSize', function () { return this.then(function () {}); });
return worker.set({ pageSize: 'test' }).then(function () {
expect(worker.setPageSize).to.have.been.called.with('test');
chai.spy.restore();
});
});
it('setPageSize() with no argument should use jsPDF default settings', function () {
var worker = html2pdf();
return worker.setPageSize().get('pageSize').then(function (val) {
var a4 = [595.28, 841.89];
expect(val).to.eql(makePageSize('mm', 72 / 25.4, a4, [0,0,0,0]));
});
});
it('changing margin should update pageSize.inner', function () {
var worker = html2pdf();
return worker.set({margin: 1}).get('margin').then(function (val) {
expect(val).to.eql([1, 1, 1, 1]);
}).get('pageSize').then(function (val) {
var a4 = [595.28, 841.89];
expect(val).to.eql(makePageSize('mm', 72 / 25.4, a4, [1,1,1,1]));
});
});
it('changing jsPDF should update pageSize', function () {
var worker = html2pdf();
var jsPDF = {orientation: 'p', unit: 'in', format: 'letter'};
return worker.set({jsPDF: jsPDF}).get('jsPDF').then(function (val) {
expect(val).to.eql(jsPDF);
}).get('pageSize').then(function (val) {
var letter = [612, 792];
expect(val).to.eql(makePageSize(jsPDF.unit, 72, letter, [0,0,0,0]));
});
});
});
});

View File

@@ -0,0 +1,82 @@
describe('snapshot', () => {
before(() => {
return pdftest.api.connect('http://localhost:3000');
});
function loadElement({ document, tagName, src }) {
const element = document.createElement(tagName);
const loaded = new Promise(resolve => element.addEventListener('load', () => resolve(element)));
element.src = src;
document.body.appendChild(element);
return loaded;
}
const defaultSettings = { html2canvas: { logging: false } };
const pageBreakSettings = pagebreak => Object.assign({}, defaultSettings, { pagebreak, jsPDF: { orientation: 'portrait', unit: 'in', format: 'letter' } });
const defaultCondition = (window, customSettings, src) => {
const settings = Object.assign({}, defaultSettings, customSettings);
return window.html2pdf().set(settings).from(src || window.document.body).outputPdf('arraybuffer');
};
const conditions = {
default: {
runner: defaultCondition,
name: file => `${file}.pdf`,
},
legacy: {
runner: window => window.html2pdf(window.document.body, defaultSettings).outputPdf('arraybuffer'),
name: file => `${file}.pdf`,
},
margin: {
runner: window => defaultCondition(window, { margin: 1, jsPDF: { unit: 'in' } }),
name: file => `${file}_margin.pdf`,
},
selectMainId: {
runner: window => defaultCondition(window, {}, window.document.getElementById('main')),
name: file => `${file}.pdf`,
},
pagebreakLegacy: {
runner: window => defaultCondition(window, pageBreakSettings({ mode: 'legacy' })),
name: file => `${file}_legacy.pdf`,
},
pagebreakCss: {
runner: window => defaultCondition(window, pageBreakSettings({ mode: 'css' })),
name: file => `${file}_css.pdf`,
},
pagebreakAvoidAll: {
runner: window => defaultCondition(window, pageBreakSettings({ mode: 'avoid-all' })),
name: file => `${file}_avoid-all.pdf`,
},
pagebreakSpecify: {
runner: window => defaultCondition(window, pageBreakSettings({ before: '.before', after: '.after', avoid: '.avoid' })),
name: file => `${file}_specify.pdf`,
},
};
const filesToTest = {
'blank': [ 'default' ],
'lorem-ipsum': [ 'default', 'legacy', 'margin' ],
'all-tags': [ 'default' ],
'css-selectors': [ 'selectMainId' ],
'pagebreaks': [ 'pagebreakLegacy', 'pagebreakCss', 'pagebreakAvoidAll', 'pagebreakSpecify' ],
};
Object.keys(filesToTest).forEach(file => describe(file, () => {
let iframe;
before(async () => {
iframe = await loadElement({ document, tagName: 'iframe', src: `/base/test/reference/${file}.html` });
await loadElement({ document: iframe.contentDocument, tagName: 'script', src: '/base/src/index.js' });
chai.spy.on(iframe.contentWindow.html2pdf.Worker.prototype, 'save', function () { return this.then(function save() {}); });
});
after(() => {
chai.spy.restore();
document.body.removeChild(iframe);
});
filesToTest[file].forEach(condition => it(`should match snapshot for ${condition} settings`, async () => {
const pdf = await conditions[condition].runner(iframe.contentWindow);
await expect(pdf).to.matchPdfSnapshot({ interactive: true, customSnapshotIdentifier: conditions[condition].name(file) });
}));
}));
});

View File

@@ -0,0 +1,82 @@
const path = require('path');
const webpack = require('webpack');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const pkg = require('./package.json');
const externals = [ 'jspdf', 'html2canvas' ];
const banner = `${pkg.name} v${pkg.version}
Copyright (c) ${(new Date).getFullYear()} Erik Koopmans
Released under the ${pkg.license} License.`;
module.exports = env => {
const isDev = env.dev;
const mode = isDev ? 'production' : 'development';
const watch = isDev;
const useAnalyzer = env.analyzer;
const makeUMDConfig = (filename, { bundle, min } = {}) => ({
output: {
filename,
library: {
name: 'html2pdf',
type: 'umd',
export: 'default',
umdNamedDefine: true,
}
},
target: 'browserslist',
externals: bundle ? [] : externals,
externalsType: 'umd',
optimization: { minimize: min },
devtool: min ? 'source-map' : false,
bundleAnalyzer: {
analyzerMode: useAnalyzer ? 'server' : 'disabled',
analyzerPort: 'auto',
defaultSizes: 'stat',
},
});
const builds = {
umd: makeUMDConfig('html2pdf.js'),
umdBundle: makeUMDConfig('html2pdf.bundle.js', { bundle: true }),
...(isDev ? {} : {
umdMin: makeUMDConfig('html2pdf.min.js', { min: true }),
umdBundleMin: makeUMDConfig('html2pdf.bundle.min.js', { bundle: true, min: true }),
}),
};
return Object.values(builds).map(build => ({
entry: './src/index.js',
mode,
target: build.target,
watch,
watchOptions: {
ignored: /node_modules/,
},
output: {
path: path.resolve(__dirname, 'dist'),
chunkFormat: false,
...build.output,
},
node: false,
externals: build.externals,
externalsType: build.externalsType,
optimization: build.optimization,
devtool: build.devtool || false,
plugins: [
new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 1 }),
new webpack.BannerPlugin(banner),
new BundleAnalyzerPlugin(build.bundleAnalyzer || { analyzerMode: 'disabled' }),
],
experiments: build.experiments,
module: {
rules: [
{
test: /\.m?js$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
],
},
}));
};