# Table of Contents
- [Home - Documentation](#home-documentation)
- [ShadingPattern - Documentation](#shadingpattern-documentation)
- [jsPDF - Documentation](#jspdf-documentation)
- [GState - Documentation](#gstate-documentation)
- [AcroFormButton - Documentation](#acroformbutton-documentation)
- [AcroFormCheckBox - Documentation](#acroformcheckbox-documentation)
- [AcroFormChoiceField - Documentation](#acroformchoicefield-documentation)
- [AcroFormComboBox - Documentation](#acroformcombobox-documentation)
- [GState - Documentation](#gstate-documentation)
- [Matrix - Documentation](#matrix-documentation)
- [TilingPattern - Documentation](#tilingpattern-documentation)
- [AcroFormField - Documentation](#acroformfield-documentation)
- [AcroFormPDFObject - Documentation](#acroformpdfobject-documentation)
- [AcroForm - Documentation](#acroform-documentation)
- [canvas - Documentation](#canvas-documentation)
- [AcroFormTextField - Documentation](#acroformtextfield-documentation)
- [AcroFormEditBox - Documentation](#acroformeditbox-documentation)
- [AcroFormListBox - Documentation](#acroformlistbox-documentation)
- [AcroFormPushButton - Documentation](#acroformpushbutton-documentation)
- [AcroFormRadioButton - Documentation](#acroformradiobutton-documentation)
- [Canvas - Documentation](#canvas-documentation)
- [addImage - Documentation](#addimage-documentation)
- [autoprint - Documentation](#autoprint-documentation)
- [annotations - Documentation](#annotations-documentation)
- [arabic - Documentation](#arabic-documentation)
- [bmp_support - Documentation](#bmp-support-documentation)
- [cell - Documentation](#cell-documentation)
- [fileloading - Documentation](#fileloading-documentation)
- [context2d - Documentation](#context2d-documentation)
- [AcroFormPasswordField - Documentation](#acroformpasswordfield-documentation)
- [gif_support - Documentation](#gif-support-documentation)
- [html - Documentation](#html-documentation)
- [javascript - Documentation](#javascript-documentation)
- [outline - Documentation](#outline-documentation)
- [jpeg_support - Documentation](#jpeg-support-documentation)
- [png_support - Documentation](#png-support-documentation)
- [setLanguage - Documentation](#setlanguage-documentation)
- [split_text_to_size - Documentation](#split-text-to-size-documentation)
- [rgba_support - Documentation](#rgba-support-documentation)
- [svg - Documentation](#svg-documentation)
- [ttfsupport - Documentation](#ttfsupport-documentation)
- [webp_support - Documentation](#webp-support-documentation)
- [vFS - Documentation](#vfs-documentation)
- [total_pages - Documentation](#total-pages-documentation)
- [standard_fonts_metrics - Documentation](#standard-fonts-metrics-documentation)
- [utf8 - Documentation](#utf8-documentation)
- [viewerpreferences - Documentation](#viewerpreferences-documentation)
- [xmp_metadata - Documentation](#xmp-metadata-documentation)
- [modules/canvas.js - Documentation](#modules-canvas-js-documentation)
- [modules/bmp_support.js - Documentation](#modules-bmp-support-js-documentation)
- [modules/cell.js - Documentation](#modules-cell-js-documentation)
- [libs/bidiEngine.js - Documentation](#libs-bidiengine-js-documentation)
- [modules/autoprint.js - Documentation](#modules-autoprint-js-documentation)
- [modules/addimage.js - Documentation](#modules-addimage-js-documentation)
- [modules/arabic.js - Documentation](#modules-arabic-js-documentation)
- [modules/fileloading.js - Documentation](#modules-fileloading-js-documentation)
- [modules/annotations.js - Documentation](#modules-annotations-js-documentation)
- [modules/gif_support.js - Documentation](#modules-gif-support-js-documentation)
- [modules/javascript.js - Documentation](#modules-javascript-js-documentation)
- [modules/jpeg_support.js - Documentation](#modules-jpeg-support-js-documentation)
- [modules/acroform.js - Documentation](#modules-acroform-js-documentation)
- [modules/html.js - Documentation](#modules-html-js-documentation)
- [modules/outline.js - Documentation](#modules-outline-js-documentation)
- [modules/rgba_support.js - Documentation](#modules-rgba-support-js-documentation)
- [modules/setlanguage.js - Documentation](#modules-setlanguage-js-documentation)
- [modules/png_support.js - Documentation](#modules-png-support-js-documentation)
- [jspdf.js - Documentation](#jspdf-js-documentation)
- [modules/svg.js - Documentation](#modules-svg-js-documentation)
- [modules/webp_support.js - Documentation](#modules-webp-support-js-documentation)
- [modules/vfs.js - Documentation](#modules-vfs-js-documentation)
- [modules/total_pages.js - Documentation](#modules-total-pages-js-documentation)
- [modules/split_text_to_size.js - Documentation](#modules-split-text-to-size-js-documentation)
- [modules/xmp_metadata.js - Documentation](#modules-xmp-metadata-js-documentation)
- [modules/standard_fonts_metrics.js - Documentation](#modules-standard-fonts-metrics-js-documentation)
- [modules/viewerpreferences.js - Documentation](#modules-viewerpreferences-js-documentation)
- [modules/context2d.js - Documentation](#modules-context2d-js-documentation)
- [Unknown](#unknown)
- [Unknown](#unknown)
- [Unknown](#unknown)
- [Unknown](#unknown)
---
# Home - Documentation

================================================================
[](https://github.com/MrRio/jsPDF/actions/workflows/continuous-integration.yml?query=branch%3Amaster)
[](https://codeclimate.com/repos/57f943855cdc43705e00592f/feed)
[](https://codeclimate.com/repos/57f943855cdc43705e00592f/coverage)
[](https://github.com/MrRio/jsPDF/blob/master/LICENSE)
[](https://lgtm.com/projects/g/MrRio/jsPDF/alerts/)
[](https://lgtm.com/projects/g/MrRio/jsPDF/context:javascript)
[](https://gitpod.io/from-referrer/)
**A library to generate PDFs in JavaScript.**
You can [catch me on twitter](https://twitter.com/MrRio)
: [@MrRio](https://twitter.com/MrRio)
or head over to [my company's website](http://parall.ax/)
for consultancy.
jsPDF is now co-maintained by [yWorks - the diagramming experts](https://www.yworks.com/)
.
[Live Demo](https://raw.githack.com/MrRio/jsPDF/master/)
| [Documentation](https://raw.githack.com/MrRio/jsPDF/master/docs/)
------------------------------------------------------------------------------------------------------------------------------
Install
-------
Recommended: get jsPDF from npm:
npm install jspdf --save
# or
yarn add jspdf
Alternatively, load it from a CDN:
Or always get latest version via [unpkg](https://unpkg.com/browse/jspdf/)
The `dist` folder of this package contains different kinds of files:
* **jspdf.es.\*.js**: Modern ES2015 module format.
* **jspdf.node.\*.js**: For running in Node. Uses file operations for loading/saving files instead of browser APIs.
* **jspdf.umd.\*.js**: UMD module format. For AMD or script-tag loading.
* **polyfills\*.js**: Required polyfills for older browsers like Internet Explorer. The es variant simply imports all required polyfills from `core-js`, the umd variant is self-contained.
Usually it is not necessary to specify the exact file in the import statement. Build tools or Node automatically figure out the right file, so importing "jspdf" is enough.
Usage
-----
Then you're ready to start making your document:
import { jsPDF } from "jspdf";
// Default export is a4 paper, portrait, using millimeters for units
const doc = new jsPDF();
doc.text("Hello world!", 10, 10);
doc.save("a4.pdf");
If you want to change the paper size, orientation, or units, you can do:
// Landscape export, 2×4 inches
const doc = new jsPDF({
orientation: "landscape",
unit: "in",
format: [4, 2]
});
doc.text("Hello world!", 1, 1);
doc.save("two-by-four.pdf");
### Running in Node.js
const { jsPDF } = require("jspdf"); // will automatically load the node version
const doc = new jsPDF();
doc.text("Hello world!", 10, 10);
doc.save("a4.pdf"); // will save the file in the current working directory
### Other Module Formats
**AMD**
require(["jspdf"], ({ jsPDF }) => {
const doc = new jsPDF();
doc.text("Hello world!", 10, 10);
doc.save("a4.pdf");
});
**Globals**
const { jsPDF } = window.jspdf;
const doc = new jsPDF();
doc.text("Hello world!", 10, 10);
doc.save("a4.pdf");
### Optional dependencies
Some functions of jsPDF require optional dependencies. E.g. the `html` method, which depends on `html2canvas` and, when supplied with a string HTML document, `dompurify`. JsPDF loads them dynamically when required (using the respective module format, e.g. dynamic imports). Build tools like Webpack will automatically create separate chunks for each of the optional dependencies. If your application does not use any of the optional dependencies, you can prevent Webpack from generating the chunks by defining them as external dependencies:
// webpack.config.js
module.exports = {
// ...
externals: {
// only define the dependencies you are NOT using as externals!
canvg: "canvg",
html2canvas: "html2canvas",
dompurify: "dompurify"
}
};
In **Vue CLI** projects, externals can be defined via the [configureWebpack](https://cli.vuejs.org/config/#configurewebpack)
or [chainWebpack](https://cli.vuejs.org/config/#chainwebpack)
properties of the `vue.config.js` file (needs to be created, first, in fresh projects).
In **Angular** projects, externals can be defined using [custom webpack builders](https://github.com/just-jeb/angular-builders/tree/master/packages/custom-webpack)
.
In **React** (`create-react-app`) projects, externals can be defined by either using [react-app-rewired](https://github.com/timarney/react-app-rewired)
or ejecting.
### TypeScript/Angular/Webpack/React/etc. Configuration:
jsPDF can be imported just like any other 3rd party library. This works with all major toolkits and frameworks. jsPDF also offers a typings file for TypeScript projects.
import { jsPDF } from "jspdf";
You can add jsPDF to your meteor-project as follows:
meteor add jspdf:core
### Polyfills
jsPDF requires modern browser APIs in order to function. To use jsPDF in older browsers like Internet Explorer, polyfills are required. You can load all required polyfills as follows:
import "jspdf/dist/polyfills.es.js";
Alternatively, you can load the prebundled polyfill file. This is not recommended, since you might end up loading polyfills multiple times. Might still be nifty for small applications or quick POCs.
Use of Unicode Characters / UTF-8:
----------------------------------
The 14 standard fonts in PDF are limited to the ASCII-codepage. If you want to use UTF-8 you have to integrate a custom font, which provides the needed glyphs. jsPDF supports .ttf-files. So if you want to have for example Chinese text in your pdf, your font has to have the necessary Chinese glyphs. So, check if your font supports the wanted glyphs or else it will show garbled characters instead of the right text.
To add the font to jsPDF use our fontconverter in [/fontconverter/fontconverter.html](https://rawgit.com/MrRio/jsPDF/master/fontconverter/fontconverter.html)
. The fontconverter will create a js-file with the content of the provided ttf-file as base64 encoded string and additional code for jsPDF. You just have to add this generated js-File to your project. You are then ready to go to use setFont-method in your code and write your UTF-8 encoded text.
Alternatively you can just load the content of the \*.ttf file as a binary string using `fetch` or `XMLHttpRequest` and add the font to the PDF file:
const doc = new jsPDF();
const myFont = ... // load the *.ttf font file as binary string
// add the font to jsPDF
doc.addFileToVFS("MyFont.ttf", myFont);
doc.addFont("MyFont.ttf", "MyFont", "normal");
doc.setFont("MyFont");
Advanced Functionality
----------------------
Since the merge with the [yWorks fork](https://github.com/yWorks/jsPDF)
there are a lot of new features. However, some of them are API breaking, which is why there is an API-switch between two API modes:
* In "compat" API mode, jsPDF has the same API as MrRio's original version, which means full compatibility with plugins. However, some advanced features like transformation matrices and patterns won't work. This is the default mode.
* In "advanced" API mode, jsPDF has the API you're used from the yWorks-fork version. This means the availability of all advanced features like patterns, FormObjects, and transformation matrices.
You can switch between the two modes by calling
doc.advancedAPI(doc => {
// your code
});
// or
doc.compatAPI(doc => {
// your code
});
JsPDF will automatically switch back to the original API mode after the callback has run.
Support
-------
Please check if your question is already handled at Stackoverflow [https://stackoverflow.com/questions/tagged/jspdf](https://raw.githack.com/MrRio/jsPDF/master/docs/%5C/%5C/stackoverflow.com/questions/tagged/jspdf)
. Feel free to ask a question there with the tag `jspdf`.
Feature requests, bug reports, etc. are very welcome as issues. Note that bug reports should follow these guidelines:
* A bug should be reported as an [mcve](https://stackoverflow.com/help/mcve)
* Make sure code is properly indented and [formatted](https://help.github.com/articles/basic-writing-and-formatting-syntax/#quoting-code)
(Use \`\`\` around code blocks)
* Provide a runnable example.
* Try to make sure and show in your issue that the issue is actually related to jspdf and not your framework of choice.
Contributing
------------
jsPDF cannot live without help from the community! If you think a feature is missing or you found a bug, please consider if you can spare one or two hours and prepare a pull request. If you're simply interested in this project and want to help, have a look at the open issues, especially those labeled with "bug".
You can find information about building and testing jsPDF in the [contribution guide](https://github.com/MrRio/jsPDF/blob/master/CONTRIBUTING.md#pull-requests)
Credits
-------
* Big thanks to Daniel Dotsenko from [Willow Systems Corporation](https://github.com/willowsystems)
for making huge contributions to the codebase.
* Thanks to Ajaxian.com for [featuring us back in 2009](http://web.archive.org/web/20111011192314/http://ajaxian.com/archives/dynamically-generic-pdfs-with-javascript)
. (Internet Archive Wayback Machine reference)
* Our special thanks to GH Lee ([sphilee](https://github.com/sphilee)
) for programming the ttf-file-support and providing a large and long sought after feature
* Everyone else that's contributed patches or bug reports. You rock.
License (MIT)
-------------
Copyright (c) 2010-2021 James Hall, https://github.com/MrRio/jsPDF (c) 2015-2021 yWorks GmbH, https://www.yworks.com/
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---
# ShadingPattern - Documentation
ShadingPattern
==============
#### new ShadingPattern(type, coords, colors, gStateopt, matrixopt)
Source:
* [jspdf.js](https://raw.githack.com/MrRio/jsPDF/master/docs/jspdf.js.html)
, [line 1496](https://raw.githack.com/MrRio/jsPDF/master/docs/jspdf.js.html#line1496)
A pattern describing a shading pattern.
Only available in "advanced" API mode.
##### Parameters:
| Name | Type | Attributes | Description |
| --- | --- | --- | --- |
| `type` | String | | One of "axial" or "radial" |
| `coords` | Array. | | Either \[x1, y1, x2, y2\] for "axial" type describing the two interpolation points or \[x1, y1, r, x2, y2, r2\] for "radial" describing inner and the outer circle. |
| `colors` | Array.
`
1033. `* false: Auto paging is disabled.`
1034. `*
`
1035. `*
`
1036. `* true or 'slice': Will cut shapes or text chunks across page breaks. Will possibly`
1037. `* slice text in half, making it difficult to read.`
1038. `*
`
1039. `*
`
1040. `* 'text': Trys not to cut text in half across page breaks. Works best for documents consisting`
1041. `* mostly of a single column of text.`
1042. `*
`
1043. `*
`
1044. `* Default is true.`
1045. `* @param {string} [options.filename] name of the file`
1046. `* @param {HTMLOptionImage} [options.image] image settings when converting HTML to image`
1047. `* @param {Html2CanvasOptions} [options.html2canvas] html2canvas options`
1048. `* @param {FontFace[]} [options.fontFaces] A list of font-faces to match when resolving fonts. Fonts will be added to the PDF based on the specified URL. If omitted, the font match algorithm falls back to old algorithm.`
1049. `* @param {jsPDF} [options.jsPDF] jsPDF instance`
1050. `* @param {number=} [options.x] x position on the PDF document in jsPDF units.`
1051. `* @param {number=} [options.y] y position on the PDF document in jsPDF units.`
1052. `* @param {number=} [options.width] The target width in the PDF document in jsPDF units. The rendered element will be`
1053. `* scaled such that it fits into the specified width. Has no effect if either the html2canvas.scale is`
1054. `* specified or the windowWidth option is NOT specified.`
1055. `* @param {number=} [options.windowWidth] The window width in CSS pixels. In contrast to the`
1056. `* html2canvas.windowWidth option, this option affects the actual container size while rendering and`
1057. `* does NOT affect CSS media queries. This option only has an effect, if the width option is also specified.`
1058. `*`
1059. `* @example`
1060. `* var doc = new jsPDF();`
1061. `*`
1062. `* doc.html(document.body, {`
1063. `* callback: function (doc) {`
1064. `* doc.save();`
1065. `* },`
1066. `* x: 10,`
1067. `* y: 10`
1068. `* });`
1069. `*/`
1070. `jsPDFAPI.html = function(src, options) {`
1071. `"use strict";`
1073. `options = options || {};`
1074. `options.callback = options.callback || function() {};`
1075. `options.html2canvas = options.html2canvas || {};`
1076. `options.html2canvas.canvas = options.html2canvas.canvas || this.canvas;`
1077. `options.jsPDF = options.jsPDF || this;`
1078. `options.fontFaces = options.fontFaces`
1079. `? options.fontFaces.map(normalizeFontFace)`
1080. `: null;`
1082. `// Create a new worker with the given options.`
1083. `var worker = new Worker(options);`
1085. `if (!options.worker) {`
1086. `// If worker is not set to true, perform the traditional 'simple' operation.`
1087. `return worker.from(src).doCallback();`
1088. `} else {`
1089. `// Otherwise, return the worker for new Promise-based operation.`
1090. `return worker;`
1091. `}`
1092. `};`
1093. `})(jsPDF.API);`
---
# modules/outline.js - Documentation
modules/outline.js
==================
1. `/**`
2. `* @license`
3. `* Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv`
4. `*`
5. `* Licensed under the MIT License.`
6. `* http://opensource.org/licenses/mit-license`
7. `*/`
9. `import { jsPDF } from "../jspdf.js";`
11. `/**`
12. `* jsPDF Outline PlugIn`
13. `*`
14. `* Generates a PDF Outline`
15. `* @name outline`
16. `* @module`
17. `*/`
18. `(function(jsPDFAPI) {`
19. `"use strict";`
21. `var namesOid;`
22. `//var destsGoto = [];`
24. `jsPDFAPI.events.push([`\
25. `"postPutResources",`\
26. `function() {`\
27. `var pdf = this;`\
28. `var rx = /^(\d+) 0 obj$/;`\
\
30. `// Write action goto objects for each page`\
31. `// this.outline.destsGoto = [];`\
32. `// for (var i = 0; i < totalPages; i++) {`\
33. `// var id = pdf.internal.newObject();`\
34. `// this.outline.destsGoto.push(id);`\
35. `// pdf.internal.write("<> endobj");`\
37. `// }`\
38. `//`\
39. `// for (var i = 0; i < dests.length; i++) {`\
40. `// pdf.internal.write("(page_" + (i + 1) + ")" + dests[i] + " 0`\
41. `// R");`\
42. `// }`\
43. `//`\
44. `if (this.outline.root.children.length > 0) {`\
45. `var lines = pdf.outline.render().split(/\r\n/);`\
46. `for (var i = 0; i < lines.length; i++) {`\
47. `var line = lines[i];`\
48. `var m = rx.exec(line);`\
49. `if (m != null) {`\
50. `var oid = m[1];`\
51. `pdf.internal.newObjectDeferredBegin(oid, false);`\
52. `}`\
53. `pdf.internal.write(line);`\
54. `}`\
55. `}`\
\
57. `// This code will write named destination for each page reference`\
58. `// (page_1, etc)`\
59. `if (this.outline.createNamedDestinations) {`\
60. `var totalPages = this.internal.pages.length;`\
61. `// WARNING: this assumes jsPDF starts on page 3 and pageIDs`\
62. `// follow 5, 7, 9, etc`\
63. `// Write destination objects for each page`\
64. `var dests = [];`\
65. `for (var i = 0; i < totalPages; i++) {`\
66. `var id = pdf.internal.newObject();`\
67. `dests.push(id);`\
68. `var info = pdf.internal.getPageInfo(i + 1);`\
69. `pdf.internal.write(`\
70. `"<< /D[" + info.objId + " 0 R /XYZ null null null]>> endobj"`\
71. `);`\
72. `}`\
\
74. `// assign a name for each destination`\
75. `var names2Oid = pdf.internal.newObject();`\
76. `pdf.internal.write("<< /Names [ ");`\
77. `for (var i = 0; i < dests.length; i++) {`\
78. `pdf.internal.write("(page_" + (i + 1) + ")" + dests[i] + " 0 R");`\
79. `}`\
80. `pdf.internal.write(" ] >>", "endobj");`\
\
82. `// var kids = pdf.internal.newObject();`\
83. `// pdf.internal.write('<< /Kids [ ' + names2Oid + ' 0 R');`\
84. `// pdf.internal.write(' ] >>', 'endobj');`\
\
86. `namesOid = pdf.internal.newObject();`\
87. `pdf.internal.write("<< /Dests " + names2Oid + " 0 R");`\
88. `pdf.internal.write(">>", "endobj");`\
89. `}`\
90. `}`\
91. `]);`
93. `jsPDFAPI.events.push([`\
94. `"putCatalog",`\
95. `function() {`\
96. `var pdf = this;`\
97. `if (pdf.outline.root.children.length > 0) {`\
98. `pdf.internal.write(`\
99. `"/Outlines",`\
100. `this.outline.makeRef(this.outline.root)`\
101. `);`\
102. `if (this.outline.createNamedDestinations) {`\
103. `pdf.internal.write("/Names " + namesOid + " 0 R");`\
104. `}`\
105. `// Open with Bookmarks showing`\
106. `// pdf.internal.write("/PageMode /UseOutlines");`\
107. `}`\
108. `}`\
109. `]);`
111. `jsPDFAPI.events.push([`\
112. `"initialized",`\
113. `function() {`\
114. `var pdf = this;`\
\
116. `pdf.outline = {`\
117. `createNamedDestinations: false,`\
118. `root: {`\
119. `children: []`\
120. `}`\
121. `};`\
\
123. `/**`\
124. `* Options: pageNumber`\
125. `*/`\
126. `pdf.outline.add = function(parent, title, options) {`\
127. `var item = {`\
128. `title: title,`\
129. `options: options,`\
130. `children: []`\
131. `};`\
132. `if (parent == null) {`\
133. `parent = this.root;`\
134. `}`\
135. `parent.children.push(item);`\
136. `return item;`\
137. `};`\
\
139. `pdf.outline.render = function() {`\
140. `this.ctx = {};`\
141. `this.ctx.val = "";`\
142. `this.ctx.pdf = pdf;`\
\
144. `this.genIds_r(this.root);`\
145. `this.renderRoot(this.root);`\
146. `this.renderItems(this.root);`\
\
148. `return this.ctx.val;`\
149. `};`\
\
151. `pdf.outline.genIds_r = function(node) {`\
152. `node.id = pdf.internal.newObjectDeferred();`\
153. `for (var i = 0; i < node.children.length; i++) {`\
154. `this.genIds_r(node.children[i]);`\
155. `}`\
156. `};`\
\
158. `pdf.outline.renderRoot = function(node) {`\
159. `this.objStart(node);`\
160. `this.line("/Type /Outlines");`\
161. `if (node.children.length > 0) {`\
162. `this.line("/First " + this.makeRef(node.children[0]));`\
163. `this.line(`\
164. `"/Last " + this.makeRef(node.children[node.children.length - 1])`\
165. `);`\
166. `}`\
167. `this.line(`\
168. `"/Count " +`\
169. `this.count_r(`\
170. `{`\
171. `count: 0`\
172. `},`\
173. `node`\
174. `)`\
175. `);`\
176. `this.objEnd();`\
177. `};`\
\
179. `pdf.outline.renderItems = function(node) {`\
180. `var getVerticalCoordinateString = this.ctx.pdf.internal`\
181. `.getVerticalCoordinateString;`\
182. `for (var i = 0; i < node.children.length; i++) {`\
183. `var item = node.children[i];`\
184. `this.objStart(item);`\
\
186. `this.line("/Title " + this.makeString(item.title));`\
\
188. `this.line("/Parent " + this.makeRef(node));`\
189. `if (i > 0) {`\
190. `this.line("/Prev " + this.makeRef(node.children[i - 1]));`\
191. `}`\
192. `if (i < node.children.length - 1) {`\
193. `this.line("/Next " + this.makeRef(node.children[i + 1]));`\
194. `}`\
195. `if (item.children.length > 0) {`\
196. `this.line("/First " + this.makeRef(item.children[0]));`\
197. `this.line(`\
198. `"/Last " + this.makeRef(item.children[item.children.length - 1])`\
199. `);`\
200. `}`\
\
202. `var count = (this.count = this.count_r(`\
203. `{`\
204. `count: 0`\
205. `},`\
206. `item`\
207. `));`\
208. `if (count > 0) {`\
209. `this.line("/Count " + count);`\
210. `}`\
\
212. `if (item.options) {`\
213. `if (item.options.pageNumber) {`\
214. `// Explicit Destination`\
215. `//WARNING this assumes page ids are 3,5,7, etc.`\
216. `var info = pdf.internal.getPageInfo(item.options.pageNumber);`\
217. `this.line(`\
218. `"/Dest " +`\
219. `"[" +`\
220. `info.objId +`\
221. `" 0 R /XYZ 0 " +`\
222. `getVerticalCoordinateString(0) +`\
223. `" 0]"`\
224. `);`\
225. `// this line does not work on all clients (pageNumber instead of page ref)`\
226. `//this.line('/Dest ' + '[' + (item.options.pageNumber - 1) + ' /XYZ 0 ' + this.ctx.pdf.internal.pageSize.getHeight() + ' 0]');`\
\
228. `// Named Destination`\
229. `// this.line('/Dest (page_' + (item.options.pageNumber) + ')');`\
\
231. `// Action Destination`\
232. `// var id = pdf.internal.newObject();`\
233. `// pdf.internal.write('<> endobj');`\
234. `// this.line('/A ' + id + ' 0 R' );`\
235. `}`\
236. `}`\
237. `this.objEnd();`\
238. `}`\
239. `for (var z = 0; z < node.children.length; z++) {`\
240. `this.renderItems(node.children[z]);`\
241. `}`\
242. `};`\
\
244. `pdf.outline.line = function(text) {`\
245. `this.ctx.val += text + "\r\n";`\
246. `};`\
\
248. `pdf.outline.makeRef = function(node) {`\
249. `return node.id + " 0 R";`\
250. `};`\
\
252. `pdf.outline.makeString = function(val) {`\
253. `return "(" + pdf.internal.pdfEscape(val) + ")";`\
254. `};`\
\
256. `pdf.outline.objStart = function(node) {`\
257. `this.ctx.val += "\r\n" + node.id + " 0 obj" + "\r\n<<\r\n";`\
258. `};`\
\
260. `pdf.outline.objEnd = function() {`\
261. `this.ctx.val += ">> \r\n" + "endobj" + "\r\n";`\
262. `};`\
\
264. `pdf.outline.count_r = function(ctx, node) {`\
265. `for (var i = 0; i < node.children.length; i++) {`\
266. `ctx.count++;`\
267. `this.count_r(ctx, node.children[i]);`\
268. `}`\
269. `return ctx.count;`\
270. `};`\
271. `}`\
272. `]);`
274. `return this;`
275. `})(jsPDF.API);`
---
# modules/rgba_support.js - Documentation
modules/rgba\_support.js
========================
1. `/**`
2. `* @license`
3. `*`
4. `* Copyright (c) 2021 Antti Palola, https://github.com/Pantura`
5. `*`
6. `* Permission is hereby granted, free of charge, to any person obtaining`
7. `* a copy of this software and associated documentation files (the`
8. `* "Software"), to deal in the Software without restriction, including`
9. `* without limitation the rights to use, copy, modify, merge, publish,`
10. `* distribute, sublicense, and/or sell copies of the Software, and to`
11. `* permit persons to whom the Software is furnished to do so, subject to`
12. `* the following conditions:`
13. `*`
14. `* The above copyright notice and this permission notice shall be`
15. `* included in all copies or substantial portions of the Software.`
16. `*`
17. `* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,`
18. `* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF`
19. `* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND`
20. `* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE`
21. `* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION`
22. `* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION`
23. `* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.`
24. `* ====================================================================`
25. `*/`
27. `import { jsPDF } from "../jspdf.js";`
29. `/**`
30. `* jsPDF RGBA array PlugIn`
31. `* @name rgba_support`
32. `* @module`
33. `*/`
34. `(function(jsPDFAPI) {`
35. `"use strict";`
37. `/**`
38. `* @name processRGBA`
39. `* @function`
40. `*`
41. `* Process RGBA Array. This is a one-dimension array with pixel data [red, green, blue, alpha, red, green, ...].`
42. `* RGBA array data can be obtained from DOM canvas getImageData.`
43. `* @ignore`
44. `*/`
45. `jsPDFAPI.processRGBA = function(imageData, index, alias) {`
46. `"use strict";`
48. `var imagePixels = imageData.data;`
49. `var length = imagePixels.length;`
50. `// jsPDF takes alpha data separately so extract that.`
51. `var rgbOut = new Uint8Array((length / 4) * 3);`
52. `var alphaOut = new Uint8Array(length / 4);`
53. `var outIndex = 0;`
54. `var alphaIndex = 0;`
56. `for (var i = 0; i < length; i += 4) {`
57. `var r = imagePixels[i];`
58. `var g = imagePixels[i + 1];`
59. `var b = imagePixels[i + 2];`
60. `var alpha = imagePixels[i + 3];`
61. `rgbOut[outIndex++] = r;`
62. `rgbOut[outIndex++] = g;`
63. `rgbOut[outIndex++] = b;`
64. `alphaOut[alphaIndex++] = alpha;`
65. `}`
67. `var rgbData = this.__addimage__.arrayBufferToBinaryString(rgbOut);`
68. `var alphaData = this.__addimage__.arrayBufferToBinaryString(alphaOut);`
70. `return {`
71. `alpha: alphaData,`
72. `data: rgbData,`
73. `index: index,`
74. `alias: alias,`
75. `colorSpace: "DeviceRGB",`
76. `bitsPerComponent: 8,`
77. `width: imageData.width,`
78. `height: imageData.height`
79. `};`
80. `};`
81. `})(jsPDF.API);`
---
# modules/setlanguage.js - Documentation
modules/setlanguage.js
======================
1. `/**`
2. `* @license`
3. `* Licensed under the MIT License.`
4. `* http://opensource.org/licenses/mit-license`
5. `*/`
7. `import { jsPDF } from "../jspdf.js";`
9. `/**`
10. `* jsPDF setLanguage Plugin`
11. `*`
12. `* @name setLanguage`
13. `* @module`
14. `*/`
15. `(function(jsPDFAPI) {`
16. `"use strict";`
18. `/**`
19. `* Add Language Tag to the generated PDF`
20. `*`
21. `* @name setLanguage`
22. `* @function`
23. `* @param {string} langCode The Language code as ISO-639-1 (e.g. 'en') or as country language code (e.g. 'en-GB').`
24. `* @returns {jsPDF}`
25. `* @example`
26. `* var doc = new jsPDF()`
27. `* doc.text(10, 10, 'This is a test')`
28. `* doc.setLanguage("en-US")`
29. `* doc.save('english.pdf')`
30. `*/`
31. `jsPDFAPI.setLanguage = function(langCode) {`
32. `"use strict";`
34. `var langCodes = {`
35. `af: "Afrikaans",`
36. `sq: "Albanian",`
37. `ar: "Arabic (Standard)",`
38. `"ar-DZ": "Arabic (Algeria)",`
39. `"ar-BH": "Arabic (Bahrain)",`
40. `"ar-EG": "Arabic (Egypt)",`
41. `"ar-IQ": "Arabic (Iraq)",`
42. `"ar-JO": "Arabic (Jordan)",`
43. `"ar-KW": "Arabic (Kuwait)",`
44. `"ar-LB": "Arabic (Lebanon)",`
45. `"ar-LY": "Arabic (Libya)",`
46. `"ar-MA": "Arabic (Morocco)",`
47. `"ar-OM": "Arabic (Oman)",`
48. `"ar-QA": "Arabic (Qatar)",`
49. `"ar-SA": "Arabic (Saudi Arabia)",`
50. `"ar-SY": "Arabic (Syria)",`
51. `"ar-TN": "Arabic (Tunisia)",`
52. `"ar-AE": "Arabic (U.A.E.)",`
53. `"ar-YE": "Arabic (Yemen)",`
54. `an: "Aragonese",`
55. `hy: "Armenian",`
56. `as: "Assamese",`
57. `ast: "Asturian",`
58. `az: "Azerbaijani",`
59. `eu: "Basque",`
60. `be: "Belarusian",`
61. `bn: "Bengali",`
62. `bs: "Bosnian",`
63. `br: "Breton",`
64. `bg: "Bulgarian",`
65. `my: "Burmese",`
66. `ca: "Catalan",`
67. `ch: "Chamorro",`
68. `ce: "Chechen",`
69. `zh: "Chinese",`
70. `"zh-HK": "Chinese (Hong Kong)",`
71. `"zh-CN": "Chinese (PRC)",`
72. `"zh-SG": "Chinese (Singapore)",`
73. `"zh-TW": "Chinese (Taiwan)",`
74. `cv: "Chuvash",`
75. `co: "Corsican",`
76. `cr: "Cree",`
77. `hr: "Croatian",`
78. `cs: "Czech",`
79. `da: "Danish",`
80. `nl: "Dutch (Standard)",`
81. `"nl-BE": "Dutch (Belgian)",`
82. `en: "English",`
83. `"en-AU": "English (Australia)",`
84. `"en-BZ": "English (Belize)",`
85. `"en-CA": "English (Canada)",`
86. `"en-IE": "English (Ireland)",`
87. `"en-JM": "English (Jamaica)",`
88. `"en-NZ": "English (New Zealand)",`
89. `"en-PH": "English (Philippines)",`
90. `"en-ZA": "English (South Africa)",`
91. `"en-TT": "English (Trinidad & Tobago)",`
92. `"en-GB": "English (United Kingdom)",`
93. `"en-US": "English (United States)",`
94. `"en-ZW": "English (Zimbabwe)",`
95. `eo: "Esperanto",`
96. `et: "Estonian",`
97. `fo: "Faeroese",`
98. `fj: "Fijian",`
99. `fi: "Finnish",`
100. `fr: "French (Standard)",`
101. `"fr-BE": "French (Belgium)",`
102. `"fr-CA": "French (Canada)",`
103. `"fr-FR": "French (France)",`
104. `"fr-LU": "French (Luxembourg)",`
105. `"fr-MC": "French (Monaco)",`
106. `"fr-CH": "French (Switzerland)",`
107. `fy: "Frisian",`
108. `fur: "Friulian",`
109. `gd: "Gaelic (Scots)",`
110. `"gd-IE": "Gaelic (Irish)",`
111. `gl: "Galacian",`
112. `ka: "Georgian",`
113. `de: "German (Standard)",`
114. `"de-AT": "German (Austria)",`
115. `"de-DE": "German (Germany)",`
116. `"de-LI": "German (Liechtenstein)",`
117. `"de-LU": "German (Luxembourg)",`
118. `"de-CH": "German (Switzerland)",`
119. `el: "Greek",`
120. `gu: "Gujurati",`
121. `ht: "Haitian",`
122. `he: "Hebrew",`
123. `hi: "Hindi",`
124. `hu: "Hungarian",`
125. `is: "Icelandic",`
126. `id: "Indonesian",`
127. `iu: "Inuktitut",`
128. `ga: "Irish",`
129. `it: "Italian (Standard)",`
130. `"it-CH": "Italian (Switzerland)",`
131. `ja: "Japanese",`
132. `kn: "Kannada",`
133. `ks: "Kashmiri",`
134. `kk: "Kazakh",`
135. `km: "Khmer",`
136. `ky: "Kirghiz",`
137. `tlh: "Klingon",`
138. `ko: "Korean",`
139. `"ko-KP": "Korean (North Korea)",`
140. `"ko-KR": "Korean (South Korea)",`
141. `la: "Latin",`
142. `lv: "Latvian",`
143. `lt: "Lithuanian",`
144. `lb: "Luxembourgish",`
145. `mk: "North Macedonia",`
146. `ms: "Malay",`
147. `ml: "Malayalam",`
148. `mt: "Maltese",`
149. `mi: "Maori",`
150. `mr: "Marathi",`
151. `mo: "Moldavian",`
152. `nv: "Navajo",`
153. `ng: "Ndonga",`
154. `ne: "Nepali",`
155. `no: "Norwegian",`
156. `nb: "Norwegian (Bokmal)",`
157. `nn: "Norwegian (Nynorsk)",`
158. `oc: "Occitan",`
159. `or: "Oriya",`
160. `om: "Oromo",`
161. `fa: "Persian",`
162. `"fa-IR": "Persian/Iran",`
163. `pl: "Polish",`
164. `pt: "Portuguese",`
165. `"pt-BR": "Portuguese (Brazil)",`
166. `pa: "Punjabi",`
167. `"pa-IN": "Punjabi (India)",`
168. `"pa-PK": "Punjabi (Pakistan)",`
169. `qu: "Quechua",`
170. `rm: "Rhaeto-Romanic",`
171. `ro: "Romanian",`
172. `"ro-MO": "Romanian (Moldavia)",`
173. `ru: "Russian",`
174. `"ru-MO": "Russian (Moldavia)",`
175. `sz: "Sami (Lappish)",`
176. `sg: "Sango",`
177. `sa: "Sanskrit",`
178. `sc: "Sardinian",`
179. `sd: "Sindhi",`
180. `si: "Singhalese",`
181. `sr: "Serbian",`
182. `sk: "Slovak",`
183. `sl: "Slovenian",`
184. `so: "Somani",`
185. `sb: "Sorbian",`
186. `es: "Spanish",`
187. `"es-AR": "Spanish (Argentina)",`
188. `"es-BO": "Spanish (Bolivia)",`
189. `"es-CL": "Spanish (Chile)",`
190. `"es-CO": "Spanish (Colombia)",`
191. `"es-CR": "Spanish (Costa Rica)",`
192. `"es-DO": "Spanish (Dominican Republic)",`
193. `"es-EC": "Spanish (Ecuador)",`
194. `"es-SV": "Spanish (El Salvador)",`
195. `"es-GT": "Spanish (Guatemala)",`
196. `"es-HN": "Spanish (Honduras)",`
197. `"es-MX": "Spanish (Mexico)",`
198. `"es-NI": "Spanish (Nicaragua)",`
199. `"es-PA": "Spanish (Panama)",`
200. `"es-PY": "Spanish (Paraguay)",`
201. `"es-PE": "Spanish (Peru)",`
202. `"es-PR": "Spanish (Puerto Rico)",`
203. `"es-ES": "Spanish (Spain)",`
204. `"es-UY": "Spanish (Uruguay)",`
205. `"es-VE": "Spanish (Venezuela)",`
206. `sx: "Sutu",`
207. `sw: "Swahili",`
208. `sv: "Swedish",`
209. `"sv-FI": "Swedish (Finland)",`
210. `"sv-SV": "Swedish (Sweden)",`
211. `ta: "Tamil",`
212. `tt: "Tatar",`
213. `te: "Teluga",`
214. `th: "Thai",`
215. `tig: "Tigre",`
216. `ts: "Tsonga",`
217. `tn: "Tswana",`
218. `tr: "Turkish",`
219. `tk: "Turkmen",`
220. `uk: "Ukrainian",`
221. `hsb: "Upper Sorbian",`
222. `ur: "Urdu",`
223. `ve: "Venda",`
224. `vi: "Vietnamese",`
225. `vo: "Volapuk",`
226. `wa: "Walloon",`
227. `cy: "Welsh",`
228. `xh: "Xhosa",`
229. `ji: "Yiddish",`
230. `zu: "Zulu"`
231. `};`
233. `if (this.internal.languageSettings === undefined) {`
234. `this.internal.languageSettings = {};`
235. `this.internal.languageSettings.isSubscribed = false;`
236. `}`
238. `if (langCodes[langCode] !== undefined) {`
239. `this.internal.languageSettings.languageCode = langCode;`
240. `if (this.internal.languageSettings.isSubscribed === false) {`
241. `this.internal.events.subscribe("putCatalog", function() {`
242. `this.internal.write(`
243. `"/Lang (" + this.internal.languageSettings.languageCode + ")"`
244. `);`
245. `});`
246. `this.internal.languageSettings.isSubscribed = true;`
247. `}`
248. `}`
249. `return this;`
250. `};`
251. `})(jsPDF.API);`
---
# modules/png_support.js - Documentation
modules/png\_support.js
=======================
1. `/**`
2. `* @license`
3. `*`
4. `* Copyright (c) 2014 James Robb, https://github.com/jamesbrobb`
5. `*`
6. `* Permission is hereby granted, free of charge, to any person obtaining`
7. `* a copy of this software and associated documentation files (the`
8. `* "Software"), to deal in the Software without restriction, including`
9. `* without limitation the rights to use, copy, modify, merge, publish,`
10. `* distribute, sublicense, and/or sell copies of the Software, and to`
11. `* permit persons to whom the Software is furnished to do so, subject to`
12. `* the following conditions:`
13. `*`
14. `* The above copyright notice and this permission notice shall be`
15. `* included in all copies or substantial portions of the Software.`
16. `*`
17. `* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,`
18. `* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF`
19. `* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND`
20. `* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE`
21. `* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION`
22. `* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION`
23. `* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.`
24. `* ====================================================================`
25. `*/`
27. `import { jsPDF } from "../jspdf.js";`
28. `import { zlibSync } from "../libs/fflate.js";`
29. `import { PNG } from "../libs/png.js";`
31. `/**`
32. `* jsPDF PNG PlugIn`
33. `* @name png_support`
34. `* @module`
35. `*/`
36. `(function(jsPDFAPI) {`
37. `"use strict";`
39. `/*`
40. `* @see http://www.w3.org/TR/PNG-Chunks.html`
41. `*`
42. `Color Allowed Interpretation`
43. `Type Bit Depths`
45. `0 1,2,4,8,16 Each pixel is a grayscale sample.`
47. `2 8,16 Each pixel is an R,G,B triple.`
49. `3 1,2,4,8 Each pixel is a palette index;`
50. `a PLTE chunk must appear.`
52. `4 8,16 Each pixel is a grayscale sample,`
53. `followed by an alpha sample.`
55. `6 8,16 Each pixel is an R,G,B triple,`
56. `followed by an alpha sample.`
57. `*/`
59. `/*`
60. `* PNG filter method types`
61. `*`
62. `* @see http://www.w3.org/TR/PNG-Filters.html`
63. `* @see http://www.libpng.org/pub/png/book/chapter09.html`
64. `*`
65. `* This is what the value 'Predictor' in decode params relates to`
66. `*`
67. `* 15 is "optimal prediction", which means the prediction algorithm can change from line to line.`
68. `* In that case, you actually have to read the first byte off each line for the prediction algorthim (which should be 0-4, corresponding to PDF 10-14) and select the appropriate unprediction algorithm based on that byte.`
69. `*`
70. `0 None`
71. `1 Sub`
72. `2 Up`
73. `3 Average`
74. `4 Paeth`
75. `*/`
77. `var canCompress = function(value) {`
78. `return value !== jsPDFAPI.image_compression.NONE && hasCompressionJS();`
79. `};`
81. `var hasCompressionJS = function() {`
82. `return typeof zlibSync === "function";`
83. `};`
84. `var compressBytes = function(bytes, lineLength, colorsPerPixel, compression) {`
85. `var level = 4;`
86. `var filter_method = filterUp;`
88. `switch (compression) {`
89. `case jsPDFAPI.image_compression.FAST:`
90. `level = 1;`
91. `filter_method = filterSub;`
92. `break;`
94. `case jsPDFAPI.image_compression.MEDIUM:`
95. `level = 6;`
96. `filter_method = filterAverage;`
97. `break;`
99. `case jsPDFAPI.image_compression.SLOW:`
100. `level = 9;`
101. `filter_method = filterPaeth;`
102. `break;`
103. `}`
105. `bytes = applyPngFilterMethod(`
106. `bytes,`
107. `lineLength,`
108. `colorsPerPixel,`
109. `filter_method`
110. `);`
111. `var dat = zlibSync(bytes, { level: level });`
112. `return jsPDFAPI.__addimage__.arrayBufferToBinaryString(dat);`
113. `};`
115. `var applyPngFilterMethod = function(`
116. `bytes,`
117. `lineLength,`
118. `colorsPerPixel,`
119. `filter_method`
120. `) {`
121. `var lines = bytes.length / lineLength,`
122. `result = new Uint8Array(bytes.length + lines),`
123. `filter_methods = getFilterMethods(),`
124. `line,`
125. `prevLine,`
126. `offset;`
128. `for (var i = 0; i < lines; i += 1) {`
129. `offset = i * lineLength;`
130. `line = bytes.subarray(offset, offset + lineLength);`
132. `if (filter_method) {`
133. `result.set(filter_method(line, colorsPerPixel, prevLine), offset + i);`
134. `} else {`
135. `var len = filter_methods.length,`
136. `results = [];`
138. `for (var j; j < len; j += 1) {`
139. `results[j] = filter_methods[j](line, colorsPerPixel, prevLine);`
140. `}`
142. `var ind = getIndexOfSmallestSum(results.concat());`
144. `result.set(results[ind], offset + i);`
145. `}`
147. `prevLine = line;`
148. `}`
150. `return result;`
151. `};`
153. `var filterNone = function(line) {`
154. `/*var result = new Uint8Array(line.length + 1);`
155. `result[0] = 0;`
156. `result.set(line, 1);*/`
158. `var result = Array.apply([], line);`
159. `result.unshift(0);`
161. `return result;`
162. `};`
164. `var filterSub = function(line, colorsPerPixel) {`
165. `var result = [],`
166. `len = line.length,`
167. `left;`
169. `result[0] = 1;`
171. `for (var i = 0; i < len; i += 1) {`
172. `left = line[i - colorsPerPixel] || 0;`
173. `result[i + 1] = (line[i] - left + 0x0100) & 0xff;`
174. `}`
176. `return result;`
177. `};`
179. `var filterUp = function(line, colorsPerPixel, prevLine) {`
180. `var result = [],`
181. `len = line.length,`
182. `up;`
184. `result[0] = 2;`
186. `for (var i = 0; i < len; i += 1) {`
187. `up = (prevLine && prevLine[i]) || 0;`
188. `result[i + 1] = (line[i] - up + 0x0100) & 0xff;`
189. `}`
191. `return result;`
192. `};`
194. `var filterAverage = function(line, colorsPerPixel, prevLine) {`
195. `var result = [],`
196. `len = line.length,`
197. `left,`
198. `up;`
200. `result[0] = 3;`
202. `for (var i = 0; i < len; i += 1) {`
203. `left = line[i - colorsPerPixel] || 0;`
204. `up = (prevLine && prevLine[i]) || 0;`
205. `result[i + 1] = (line[i] + 0x0100 - ((left + up) >>> 1)) & 0xff;`
206. `}`
208. `return result;`
209. `};`
211. `var filterPaeth = function(line, colorsPerPixel, prevLine) {`
212. `var result = [],`
213. `len = line.length,`
214. `left,`
215. `up,`
216. `upLeft,`
217. `paeth;`
219. `result[0] = 4;`
221. `for (var i = 0; i < len; i += 1) {`
222. `left = line[i - colorsPerPixel] || 0;`
223. `up = (prevLine && prevLine[i]) || 0;`
224. `upLeft = (prevLine && prevLine[i - colorsPerPixel]) || 0;`
225. `paeth = paethPredictor(left, up, upLeft);`
226. `result[i + 1] = (line[i] - paeth + 0x0100) & 0xff;`
227. `}`
229. `return result;`
230. `};`
232. `var paethPredictor = function(left, up, upLeft) {`
233. `if (left === up && up === upLeft) {`
234. `return left;`
235. `}`
236. `var pLeft = Math.abs(up - upLeft),`
237. `pUp = Math.abs(left - upLeft),`
238. `pUpLeft = Math.abs(left + up - upLeft - upLeft);`
239. `return pLeft <= pUp && pLeft <= pUpLeft`
240. `? left`
241. `: pUp <= pUpLeft`
242. `? up`
243. `: upLeft;`
244. `};`
246. `var getFilterMethods = function() {`
247. `return [filterNone, filterSub, filterUp, filterAverage, filterPaeth];`
248. `};`
250. `var getIndexOfSmallestSum = function(arrays) {`
251. `var sum = arrays.map(function(value) {`
252. `return value.reduce(function(pv, cv) {`
253. `return pv + Math.abs(cv);`
254. `}, 0);`
255. `});`
256. `return sum.indexOf(Math.min.apply(null, sum));`
257. `};`
259. `var getPredictorFromCompression = function(compression) {`
260. `var predictor;`
261. `switch (compression) {`
262. `case jsPDFAPI.image_compression.FAST:`
263. `predictor = 11;`
264. `break;`
266. `case jsPDFAPI.image_compression.MEDIUM:`
267. `predictor = 13;`
268. `break;`
270. `case jsPDFAPI.image_compression.SLOW:`
271. `predictor = 14;`
272. `break;`
274. `default:`
275. `predictor = 12;`
276. `break;`
277. `}`
278. `return predictor;`
279. `};`
281. `/**`
282. `* @name processPNG`
283. `* @function`
284. `* @ignore`
285. `*/`
286. `jsPDFAPI.processPNG = function(imageData, index, alias, compression) {`
287. `"use strict";`
289. `var colorSpace,`
290. `filter = this.decode.FLATE_DECODE,`
291. `bitsPerComponent,`
292. `image,`
293. `decodeParameters = "",`
294. `trns,`
295. `colors,`
296. `pal,`
297. `smask,`
298. `pixels,`
299. `len,`
300. `alphaData,`
301. `imgData,`
302. `hasColors,`
303. `pixel,`
304. `i,`
305. `n;`
307. `if (this.__addimage__.isArrayBuffer(imageData))`
308. `imageData = new Uint8Array(imageData);`
310. `if (this.__addimage__.isArrayBufferView(imageData)) {`
311. `image = new PNG(imageData);`
312. `imageData = image.imgData;`
313. `bitsPerComponent = image.bits;`
314. `colorSpace = image.colorSpace;`
315. `colors = image.colors;`
317. `/*`
318. `* colorType 6 - Each pixel is an R,G,B triple, followed by an alpha sample.`
319. `*`
320. `* colorType 4 - Each pixel is a grayscale sample, followed by an alpha sample.`
321. `*`
322. `* Extract alpha to create two separate images, using the alpha as a sMask`
323. `*/`
324. `if ([4, 6].indexOf(image.colorType) !== -1) {`
325. `/*`
326. `* processes 8 bit RGBA and grayscale + alpha images`
327. `*/`
328. `if (image.bits === 8) {`
329. `pixels =`
330. `image.pixelBitlength == 32`
331. `? new Uint32Array(image.decodePixels().buffer)`
332. `: image.pixelBitlength == 16`
333. `? new Uint16Array(image.decodePixels().buffer)`
334. `: new Uint8Array(image.decodePixels().buffer);`
335. `len = pixels.length;`
336. `imgData = new Uint8Array(len * image.colors);`
337. `alphaData = new Uint8Array(len);`
338. `var pDiff = image.pixelBitlength - image.bits;`
339. `i = 0;`
340. `n = 0;`
341. `var pbl;`
343. `for (; i < len; i++) {`
344. `pixel = pixels[i];`
345. `pbl = 0;`
347. `while (pbl < pDiff) {`
348. `imgData[n++] = (pixel >>> pbl) & 0xff;`
349. `pbl = pbl + image.bits;`
350. `}`
352. `alphaData[i] = (pixel >>> pbl) & 0xff;`
353. `}`
354. `}`
356. `/*`
357. `* processes 16 bit RGBA and grayscale + alpha images`
358. `*/`
359. `if (image.bits === 16) {`
360. `pixels = new Uint32Array(image.decodePixels().buffer);`
361. `len = pixels.length;`
362. `imgData = new Uint8Array(`
363. `len * (32 / image.pixelBitlength) * image.colors`
364. `);`
365. `alphaData = new Uint8Array(len * (32 / image.pixelBitlength));`
366. `hasColors = image.colors > 1;`
367. `i = 0;`
368. `n = 0;`
369. `var a = 0;`
371. `while (i < len) {`
372. `pixel = pixels[i++];`
374. `imgData[n++] = (pixel >>> 0) & 0xff;`
376. `if (hasColors) {`
377. `imgData[n++] = (pixel >>> 16) & 0xff;`
379. `pixel = pixels[i++];`
380. `imgData[n++] = (pixel >>> 0) & 0xff;`
381. `}`
383. `alphaData[a++] = (pixel >>> 16) & 0xff;`
384. `}`
385. `bitsPerComponent = 8;`
386. `}`
388. `if (canCompress(compression)) {`
389. `imageData = compressBytes(`
390. `imgData,`
391. `image.width * image.colors,`
392. `image.colors,`
393. `compression`
394. `);`
395. `smask = compressBytes(alphaData, image.width, 1, compression);`
396. `} else {`
397. `imageData = imgData;`
398. `smask = alphaData;`
399. `filter = undefined;`
400. `}`
401. `}`
403. `/*`
404. `* Indexed png. Each pixel is a palette index.`
405. `*/`
406. `if (image.colorType === 3) {`
407. `colorSpace = this.color_spaces.INDEXED;`
408. `pal = image.palette;`
410. `if (image.transparency.indexed) {`
411. `var trans = image.transparency.indexed;`
412. `var total = 0;`
413. `i = 0;`
414. `len = trans.length;`
416. `for (; i < len; ++i) {`
417. `total += trans[i];`
418. `}`
420. `total = total / 255;`
422. `/*`
423. `* a single color is specified as 100% transparent (0),`
424. `* so we set trns to use a /Mask with that index`
425. `*/`
426. `if (total === len - 1 && trans.indexOf(0) !== -1) {`
427. `trns = [trans.indexOf(0)];`
429. `/*`
430. `* there's more than one colour within the palette that specifies`
431. `* a transparency value less than 255, so we unroll the pixels to create an image sMask`
432. `*/`
433. `} else if (total !== len) {`
434. `pixels = image.decodePixels();`
435. `alphaData = new Uint8Array(pixels.length);`
436. `i = 0;`
437. `len = pixels.length;`
439. `for (; i < len; i++) {`
440. `alphaData[i] = trans[pixels[i]];`
441. `}`
443. `smask = compressBytes(alphaData, image.width, 1);`
444. `}`
445. `}`
446. `}`
448. `var predictor = getPredictorFromCompression(compression);`
450. `if (filter === this.decode.FLATE_DECODE) {`
451. `decodeParameters = "/Predictor " + predictor + " ";`
452. `}`
453. `decodeParameters +=`
454. `"/Colors " +`
455. `colors +`
456. `" /BitsPerComponent " +`
457. `bitsPerComponent +`
458. `" /Columns " +`
459. `image.width;`
461. `if (`
462. `this.__addimage__.isArrayBuffer(imageData) ||`
463. `this.__addimage__.isArrayBufferView(imageData)`
464. `) {`
465. `imageData = this.__addimage__.arrayBufferToBinaryString(imageData);`
466. `}`
468. `if (`
469. `(smask && this.__addimage__.isArrayBuffer(smask)) ||`
470. `this.__addimage__.isArrayBufferView(smask)`
471. `) {`
472. `smask = this.__addimage__.arrayBufferToBinaryString(smask);`
473. `}`
475. `return {`
476. `alias: alias,`
477. `data: imageData,`
478. `index: index,`
479. `filter: filter,`
480. `decodeParameters: decodeParameters,`
481. `transparency: trns,`
482. `palette: pal,`
483. `sMask: smask,`
484. `predictor: predictor,`
485. `width: image.width,`
486. `height: image.height,`
487. `bitsPerComponent: bitsPerComponent,`
488. `colorSpace: colorSpace`
489. `};`
490. `}`
491. `};`
492. `})(jsPDF.API);`
---
# jspdf.js - Documentation
jspdf.js
========
1. `/* eslint-disable no-console */`
3. `// @if MODULE_FORMAT!='cjs'`
4. `import { saveAs } from "./libs/FileSaver.js";`
5. `// @endif`
6. `import { globalObject } from "./libs/globalObject.js";`
7. `import { RGBColor } from "./libs/rgbcolor.js";`
8. `import { btoa } from "./libs/AtobBtoa.js";`
9. `import { console } from "./libs/console.js";`
10. `import { PDFSecurity } from "./libs/pdfsecurity.js";`
11. `import { toPDFName } from "./libs/pdfname.js";`
12. `/**`
13. `* jsPDF's Internal PubSub Implementation.`
14. `* Backward compatible rewritten on 2014 by`
15. `* Diego Casorran, https://github.com/diegocr`
16. `*`
17. `* @class`
18. `* @name PubSub`
19. `* @ignore`
20. `*/`
21. `function PubSub(context) {`
22. `if (typeof context !== "object") {`
23. `throw new Error(`
24. `"Invalid Context passed to initialize PubSub (jsPDF-module)"`
25. `);`
26. `}`
27. `var topics = {};`
29. `this.subscribe = function(topic, callback, once) {`
30. `once = once || false;`
31. `if (`
32. `typeof topic !== "string" ||`
33. `typeof callback !== "function" ||`
34. `typeof once !== "boolean"`
35. `) {`
36. `throw new Error(`
37. `"Invalid arguments passed to PubSub.subscribe (jsPDF-module)"`
38. `);`
39. `}`
41. `if (!topics.hasOwnProperty(topic)) {`
42. `topics[topic] = {};`
43. `}`
45. `var token = Math.random().toString(35);`
46. `topics[topic][token] = [callback, !!once];`
48. `return token;`
49. `};`
51. `this.unsubscribe = function(token) {`
52. `for (var topic in topics) {`
53. `if (topics[topic][token]) {`
54. `delete topics[topic][token];`
55. `if (Object.keys(topics[topic]).length === 0) {`
56. `delete topics[topic];`
57. `}`
58. `return true;`
59. `}`
60. `}`
61. `return false;`
62. `};`
64. `this.publish = function(topic) {`
65. `if (topics.hasOwnProperty(topic)) {`
66. `var args = Array.prototype.slice.call(arguments, 1),`
67. `tokens = [];`
69. `for (var token in topics[topic]) {`
70. `var sub = topics[topic][token];`
71. `try {`
72. `sub[0].apply(context, args);`
73. `} catch (ex) {`
74. `if (globalObject.console) {`
75. `console.error("jsPDF PubSub Error", ex.message, ex);`
76. `}`
77. `}`
78. `if (sub[1]) tokens.push(token);`
79. `}`
80. `if (tokens.length) tokens.forEach(this.unsubscribe);`
81. `}`
82. `};`
84. `this.getTopics = function() {`
85. `return topics;`
86. `};`
87. `}`
89. `function GState(parameters) {`
90. `if (!(this instanceof GState)) {`
91. `return new GState(parameters);`
92. `}`
94. `/**`
95. `* @name GState#opacity`
96. `* @type {any}`
97. `*/`
98. `/**`
99. `* @name GState#stroke-opacity`
100. `* @type {any}`
101. `*/`
102. `var supported = "opacity,stroke-opacity".split(",");`
103. `for (var p in parameters) {`
104. `if (parameters.hasOwnProperty(p) && supported.indexOf(p) >= 0) {`
105. `this[p] = parameters[p];`
106. `}`
107. `}`
108. `/**`
109. `* @name GState#id`
110. `* @type {string}`
111. `*/`
112. `this.id = ""; // set by addGState()`
113. `/**`
114. `* @name GState#objectNumber`
115. `* @type {number}`
116. `*/`
117. `this.objectNumber = -1; // will be set by putGState()`
118. `}`
120. `GState.prototype.equals = function equals(other) {`
121. `var ignore = "id,objectNumber,equals";`
122. `var p;`
123. `if (!other || typeof other !== typeof this) return false;`
124. `var count = 0;`
125. `for (p in this) {`
126. `if (ignore.indexOf(p) >= 0) continue;`
127. `if (this.hasOwnProperty(p) && !other.hasOwnProperty(p)) return false;`
128. `if (this[p] !== other[p]) return false;`
129. `count++;`
130. `}`
131. `for (p in other) {`
132. `if (other.hasOwnProperty(p) && ignore.indexOf(p) < 0) count--;`
133. `}`
134. `return count === 0;`
135. `};`
137. `function Pattern(gState, matrix) {`
138. `this.gState = gState;`
139. `this.matrix = matrix;`
141. `this.id = ""; // set by addPattern()`
142. `this.objectNumber = -1; // will be set by putPattern()`
143. `}`
145. `function ShadingPattern(type, coords, colors, gState, matrix) {`
146. `if (!(this instanceof ShadingPattern)) {`
147. `return new ShadingPattern(type, coords, colors, gState, matrix);`
148. `}`
150. `// see putPattern() for information how they are realized`
151. `this.type = type === "axial" ? 2 : 3;`
152. `this.coords = coords;`
153. `this.colors = colors;`
155. `Pattern.call(this, gState, matrix);`
156. `}`
158. `function TilingPattern(boundingBox, xStep, yStep, gState, matrix) {`
159. `if (!(this instanceof TilingPattern)) {`
160. `return new TilingPattern(boundingBox, xStep, yStep, gState, matrix);`
161. `}`
163. `this.boundingBox = boundingBox;`
164. `this.xStep = xStep;`
165. `this.yStep = yStep;`
167. `this.stream = ""; // set by endTilingPattern();`
169. `this.cloneIndex = 0;`
171. `Pattern.call(this, gState, matrix);`
172. `}`
174. `/**`
175. `* Creates new jsPDF document object instance.`
176. `* @name jsPDF`
177. `* @class`
178. `* @param {Object} [options] - Collection of settings initializing the jsPDF-instance`
179. `* @param {string} [options.orientation=portrait] - Orientation of the first page. Possible values are "portrait" or "landscape" (or shortcuts "p" or "l"). `
180. `* @param {string} [options.unit=mm] Measurement unit (base unit) to be used when coordinates are specified. `
181. `* Possible values are "pt" (points), "mm", "cm", "in", "px", "pc", "em" or "ex". Note that in order to get the correct scaling for "px"`
182. `* units, you need to enable the hotfix "px_scaling" by setting options.hotfixes = ["px_scaling"].`
183. `* @param {string/Array} [options.format=a4] The format of the first page. Can be:
a0 - a10
b0 - b10
c0 - c10
dl
letter
government-letter
legal
junior-legal
ledger
tabloid
credit-card
`
184. `* Default is "a4". If you want to use your own format just pass instead of one of the above predefined formats the size as an number-array, e.g. [595.28, 841.89]`
185. `* @param {boolean} [options.putOnlyUsedFonts=false] Only put fonts into the PDF, which were used.`
186. `* @param {boolean} [options.compress=false] Compress the generated PDF.`
187. `* @param {number} [options.precision=16] Precision of the element-positions.`
188. `* @param {number} [options.userUnit=1.0] Not to be confused with the base unit. Please inform yourself before you use it.`
189. `* @param {string[]} [options.hotfixes] An array of strings to enable hotfixes such as correct pixel scaling.`
190. `* @param {Object} [options.encryption]`
191. `* @param {string} [options.encryption.userPassword] Password for the user bound by the given permissions list.`
192. `* @param {string} [options.encryption.ownerPassword] Both userPassword and ownerPassword should be set for proper authentication.`
193. `* @param {string[]} [options.encryption.userPermissions] Array of permissions "print", "modify", "copy", "annot-forms", accessible by the user.`
194. `* @param {number|"smart"} [options.floatPrecision=16]`
195. `* @returns {jsPDF} jsPDF-instance`
196. `* @description`
197. ` * ``` `
198. `* {`
199. `* orientation: 'p',`
200. `* unit: 'mm',`
201. `* format: 'a4',`
202. `* putOnlyUsedFonts:true,`
203. `* floatPrecision: 16 // or "smart", default is 16`
204. `* }`
205. ` * ``` `
206. `*`
207. `* @constructor`
208. `*/`
209. `function jsPDF(options) {`
210. `var orientation = typeof arguments[0] === "string" ? arguments[0] : "p";`
211. `var unit = arguments[1];`
212. `var format = arguments[2];`
213. `var compressPdf = arguments[3];`
214. `var filters = [];`
215. `var userUnit = 1.0;`
216. `var precision;`
217. `var floatPrecision = 16;`
218. `var defaultPathOperation = "S";`
219. `var encryptionOptions = null;`
221. `options = options || {};`
223. `if (typeof options === "object") {`
224. `orientation = options.orientation;`
225. `unit = options.unit || unit;`
226. `format = options.format || format;`
227. `compressPdf = options.compress || options.compressPdf || compressPdf;`
228. `encryptionOptions = options.encryption || null;`
229. `if (encryptionOptions !== null) {`
230. `encryptionOptions.userPassword = encryptionOptions.userPassword || "";`
231. `encryptionOptions.ownerPassword = encryptionOptions.ownerPassword || "";`
232. `encryptionOptions.userPermissions =`
233. `encryptionOptions.userPermissions || [];`
234. `}`
235. `userUnit =`
236. `typeof options.userUnit === "number" ? Math.abs(options.userUnit) : 1.0;`
237. `if (typeof options.precision !== "undefined") {`
238. `precision = options.precision;`
239. `}`
240. `if (typeof options.floatPrecision !== "undefined") {`
241. `floatPrecision = options.floatPrecision;`
242. `}`
243. `defaultPathOperation = options.defaultPathOperation || "S";`
244. `}`
246. `filters =`
247. `options.filters || (compressPdf === true ? ["FlateEncode"] : filters);`
249. `unit = unit || "mm";`
250. `orientation = ("" + (orientation || "P")).toLowerCase();`
251. `var putOnlyUsedFonts = options.putOnlyUsedFonts || false;`
252. `var usedFonts = {};`
254. `var API = {`
255. `internal: {},`
256. `__private__: {}`
257. `};`
259. `API.__private__.PubSub = PubSub;`
261. `var pdfVersion = "1.3";`
262. `var getPdfVersion = (API.__private__.getPdfVersion = function() {`
263. `return pdfVersion;`
264. `});`
266. `API.__private__.setPdfVersion = function(value) {`
267. `pdfVersion = value;`
268. `};`
270. `// Size in pt of various paper formats`
271. `var pageFormats = {`
272. `a0: [2383.94, 3370.39],`
273. `a1: [1683.78, 2383.94],`
274. `a2: [1190.55, 1683.78],`
275. `a3: [841.89, 1190.55],`
276. `a4: [595.28, 841.89],`
277. `a5: [419.53, 595.28],`
278. `a6: [297.64, 419.53],`
279. `a7: [209.76, 297.64],`
280. `a8: [147.4, 209.76],`
281. `a9: [104.88, 147.4],`
282. `a10: [73.7, 104.88],`
283. `b0: [2834.65, 4008.19],`
284. `b1: [2004.09, 2834.65],`
285. `b2: [1417.32, 2004.09],`
286. `b3: [1000.63, 1417.32],`
287. `b4: [708.66, 1000.63],`
288. `b5: [498.9, 708.66],`
289. `b6: [354.33, 498.9],`
290. `b7: [249.45, 354.33],`
291. `b8: [175.75, 249.45],`
292. `b9: [124.72, 175.75],`
293. `b10: [87.87, 124.72],`
294. `c0: [2599.37, 3676.54],`
295. `c1: [1836.85, 2599.37],`
296. `c2: [1298.27, 1836.85],`
297. `c3: [918.43, 1298.27],`
298. `c4: [649.13, 918.43],`
299. `c5: [459.21, 649.13],`
300. `c6: [323.15, 459.21],`
301. `c7: [229.61, 323.15],`
302. `c8: [161.57, 229.61],`
303. `c9: [113.39, 161.57],`
304. `c10: [79.37, 113.39],`
305. `dl: [311.81, 623.62],`
306. `letter: [612, 792],`
307. `"government-letter": [576, 756],`
308. `legal: [612, 1008],`
309. `"junior-legal": [576, 360],`
310. `ledger: [1224, 792],`
311. `tabloid: [792, 1224],`
312. `"credit-card": [153, 243]`
313. `};`
315. `API.__private__.getPageFormats = function() {`
316. `return pageFormats;`
317. `};`
319. `var getPageFormat = (API.__private__.getPageFormat = function(value) {`
320. `return pageFormats[value];`
321. `});`
323. `format = format || "a4";`
325. `var ApiMode = {`
326. `COMPAT: "compat",`
327. `ADVANCED: "advanced"`
328. `};`
329. `var apiMode = ApiMode.COMPAT;`
331. `function advancedAPI() {`
332. `// prepend global change of basis matrix`
333. `// (Now, instead of converting every coordinate to the pdf coordinate system, we apply a matrix`
334. `// that does this job for us (however, texts, images and similar objects must be drawn bottom up))`
335. `this.saveGraphicsState();`
336. `out(`
337. `new Matrix(`
338. `scaleFactor,`
339. `0,`
340. `0,`
341. `-scaleFactor,`
342. `0,`
343. `getPageHeight() * scaleFactor`
344. `).toString() + " cm"`
345. `);`
346. `this.setFontSize(this.getFontSize() / scaleFactor);`
348. `// The default in MrRio's implementation is "S" (stroke), whereas the default in the yWorks implementation`
349. `// was "n" (none). Although this has nothing to do with transforms, we should use the API switch here.`
350. `defaultPathOperation = "n";`
352. `apiMode = ApiMode.ADVANCED;`
353. `}`
355. `function compatAPI() {`
356. `this.restoreGraphicsState();`
357. `defaultPathOperation = "S";`
358. `apiMode = ApiMode.COMPAT;`
359. `}`
361. `/**`
362. `* @function combineFontStyleAndFontWeight`
363. `* @param {string} fontStyle Fontstyle or variant. Example: "italic".`
364. `* @param {number | string} fontWeight Weight of the Font. Example: "normal" | 400`
365. `* @returns {string}`
366. `* @private`
367. `*/`
368. `var combineFontStyleAndFontWeight = (API.__private__.combineFontStyleAndFontWeight = function(`
369. `fontStyle,`
370. `fontWeight`
371. `) {`
372. `if (`
373. `(fontStyle == "bold" && fontWeight == "normal") ||`
374. `(fontStyle == "bold" && fontWeight == 400) ||`
375. `(fontStyle == "normal" && fontWeight == "italic") ||`
376. `(fontStyle == "bold" && fontWeight == "italic")`
377. `) {`
378. `throw new Error("Invalid Combination of fontweight and fontstyle");`
379. `}`
380. `if (fontWeight) {`
381. `fontStyle =`
382. `fontWeight == 400 || fontWeight === "normal"`
383. `? fontStyle === "italic"`
384. `? "italic"`
385. `: "normal"`
386. `: (fontWeight == 700 || fontWeight === "bold") &&`
387. `fontStyle === "normal"`
388. `? "bold"`
389. `: (fontWeight == 700 ? "bold" : fontWeight) + "" + fontStyle;`
390. `}`
391. `return fontStyle;`
392. `});`
394. `/**`
395. `* @callback ApiSwitchBody`
396. `* @param {jsPDF} pdf`
397. `*/`
399. `/**`
400. `* For compatibility reasons jsPDF offers two API modes which differ in the way they convert between the the usual`
401. `* screen coordinates and the PDF coordinate system.`
402. `* - "compat": Offers full compatibility across all plugins but does not allow arbitrary transforms`
403. `* - "advanced": Allows arbitrary transforms and more advanced features like pattern fills. Some plugins might`
404. `* not support this mode, though.`
405. `* Initial mode is "compat".`
406. `*`
407. `* You can either provide a callback to the body argument, which means that jsPDF will automatically switch back to`
408. `* the original API mode afterwards; or you can omit the callback and switch back manually using {@link compatAPI}.`
409. `*`
410. `* Note, that the calls to {@link saveGraphicsState} and {@link restoreGraphicsState} need to be balanced within the`
411. `* callback or between calls of this method and its counterpart {@link compatAPI}. Calls to {@link beginFormObject}`
412. `* or {@link beginTilingPattern} need to be closed by their counterparts before switching back to "compat" API mode.`
413. `*`
414. `* @param {ApiSwitchBody=} body When provided, this callback will be called after the API mode has been switched.`
415. `* The API mode will be switched back automatically afterwards.`
416. `* @returns {jsPDF}`
417. `* @memberof jsPDF#`
418. `* @name advancedAPI`
419. `*/`
420. `API.advancedAPI = function(body) {`
421. `var doSwitch = apiMode === ApiMode.COMPAT;`
423. `if (doSwitch) {`
424. `advancedAPI.call(this);`
425. `}`
427. `if (typeof body !== "function") {`
428. `return this;`
429. `}`
431. `body(this);`
433. `if (doSwitch) {`
434. `compatAPI.call(this);`
435. `}`
437. `return this;`
438. `};`
440. `/**`
441. `* Switches to "compat" API mode. See {@link advancedAPI} for more details.`
442. `*`
443. `* @param {ApiSwitchBody=} body When provided, this callback will be called after the API mode has been switched.`
444. `* The API mode will be switched back automatically afterwards.`
445. `* @return {jsPDF}`
446. `* @memberof jsPDF#`
447. `* @name compatApi`
448. `*/`
449. `API.compatAPI = function(body) {`
450. `var doSwitch = apiMode === ApiMode.ADVANCED;`
452. `if (doSwitch) {`
453. `compatAPI.call(this);`
454. `}`
456. `if (typeof body !== "function") {`
457. `return this;`
458. `}`
460. `body(this);`
462. `if (doSwitch) {`
463. `advancedAPI.call(this);`
464. `}`
466. `return this;`
467. `};`
469. `/**`
470. `* @return {boolean} True iff the current API mode is "advanced". See {@link advancedAPI}.`
471. `* @memberof jsPDF#`
472. `* @name isAdvancedAPI`
473. `*/`
474. `API.isAdvancedAPI = function() {`
475. `return apiMode === ApiMode.ADVANCED;`
476. `};`
478. `var advancedApiModeTrap = function(methodName) {`
479. `if (apiMode !== ApiMode.ADVANCED) {`
480. `throw new Error(`
481. `methodName +`
482. `" is only available in 'advanced' API mode. " +`
483. `"You need to call advancedAPI() first."`
484. `);`
485. `}`
486. `};`
488. `var roundToPrecision = (API.roundToPrecision = API.__private__.roundToPrecision = function(`
489. `number,`
490. `parmPrecision`
491. `) {`
492. `var tmpPrecision = precision || parmPrecision;`
493. `if (isNaN(number) || isNaN(tmpPrecision)) {`
494. `throw new Error("Invalid argument passed to jsPDF.roundToPrecision");`
495. `}`
496. `return number.toFixed(tmpPrecision).replace(/0+$/, "");`
497. `});`
499. `// high precision float`
500. `var hpf;`
501. `if (typeof floatPrecision === "number") {`
502. `hpf = API.hpf = API.__private__.hpf = function(number) {`
503. `if (isNaN(number)) {`
504. `throw new Error("Invalid argument passed to jsPDF.hpf");`
505. `}`
506. `return roundToPrecision(number, floatPrecision);`
507. `};`
508. `} else if (floatPrecision === "smart") {`
509. `hpf = API.hpf = API.__private__.hpf = function(number) {`
510. `if (isNaN(number)) {`
511. `throw new Error("Invalid argument passed to jsPDF.hpf");`
512. `}`
513. `if (number > -1 && number < 1) {`
514. `return roundToPrecision(number, 16);`
515. `} else {`
516. `return roundToPrecision(number, 5);`
517. `}`
518. `};`
519. `} else {`
520. `hpf = API.hpf = API.__private__.hpf = function(number) {`
521. `if (isNaN(number)) {`
522. `throw new Error("Invalid argument passed to jsPDF.hpf");`
523. `}`
524. `return roundToPrecision(number, 16);`
525. `};`
526. `}`
527. `var f2 = (API.f2 = API.__private__.f2 = function(number) {`
528. `if (isNaN(number)) {`
529. `throw new Error("Invalid argument passed to jsPDF.f2");`
530. `}`
531. `return roundToPrecision(number, 2);`
532. `});`
534. `var f3 = (API.__private__.f3 = function(number) {`
535. `if (isNaN(number)) {`
536. `throw new Error("Invalid argument passed to jsPDF.f3");`
537. `}`
538. `return roundToPrecision(number, 3);`
539. `});`
541. `var scale = (API.scale = API.__private__.scale = function(number) {`
542. `if (isNaN(number)) {`
543. `throw new Error("Invalid argument passed to jsPDF.scale");`
544. `}`
545. `if (apiMode === ApiMode.COMPAT) {`
546. `return number * scaleFactor;`
547. `} else if (apiMode === ApiMode.ADVANCED) {`
548. `return number;`
549. `}`
550. `});`
552. `var transformY = function(y) {`
553. `if (apiMode === ApiMode.COMPAT) {`
554. `return getPageHeight() - y;`
555. `} else if (apiMode === ApiMode.ADVANCED) {`
556. `return y;`
557. `}`
558. `};`
560. `var transformScaleY = function(y) {`
561. `return scale(transformY(y));`
562. `};`
564. `/**`
565. `* @name setPrecision`
566. `* @memberof jsPDF#`
567. `* @function`
568. `* @instance`
569. `* @param {string} precision`
570. `* @returns {jsPDF}`
571. `*/`
572. `API.__private__.setPrecision = API.setPrecision = function(value) {`
573. `if (typeof parseInt(value, 10) === "number") {`
574. `precision = parseInt(value, 10);`
575. `}`
576. `};`
578. `var fileId = "00000000000000000000000000000000";`
580. `var getFileId = (API.__private__.getFileId = function() {`
581. `return fileId;`
582. `});`
584. `var setFileId = (API.__private__.setFileId = function(value) {`
585. `if (typeof value !== "undefined" && /^[a-fA-F0-9]{32}$/.test(value)) {`
586. `fileId = value.toUpperCase();`
587. `} else {`
588. `fileId = fileId`
589. `.split("")`
590. `.map(function() {`
591. `return "ABCDEF0123456789".charAt(Math.floor(Math.random() * 16));`
592. `})`
593. `.join("");`
594. `}`
596. `if (encryptionOptions !== null) {`
597. `encryption = new PDFSecurity(`
598. `encryptionOptions.userPermissions,`
599. `encryptionOptions.userPassword,`
600. `encryptionOptions.ownerPassword,`
601. `fileId`
602. `);`
603. `}`
604. `return fileId;`
605. `});`
607. `/**`
608. `* @name setFileId`
609. `* @memberof jsPDF#`
610. `* @function`
611. `* @instance`
612. `* @param {string} value GUID.`
613. `* @returns {jsPDF}`
614. `*/`
615. `API.setFileId = function(value) {`
616. `setFileId(value);`
617. `return this;`
618. `};`
620. `/**`
621. `* @name getFileId`
622. `* @memberof jsPDF#`
623. `* @function`
624. `* @instance`
625. `*`
626. `* @returns {string} GUID.`
627. `*/`
628. `API.getFileId = function() {`
629. `return getFileId();`
630. `};`
632. `var creationDate;`
634. `var convertDateToPDFDate = (API.__private__.convertDateToPDFDate = function(`
635. `parmDate`
636. `) {`
637. `var result = "";`
638. `var tzoffset = parmDate.getTimezoneOffset(),`
639. `tzsign = tzoffset < 0 ? "+" : "-",`
640. `tzhour = Math.floor(Math.abs(tzoffset / 60)),`
641. `tzmin = Math.abs(tzoffset % 60),`
642. `timeZoneString = [tzsign, padd2(tzhour), "'", padd2(tzmin), "'"].join("");`
644. `result = [`\
645. `"D:",`\
646. `parmDate.getFullYear(),`\
647. `padd2(parmDate.getMonth() + 1),`\
648. `padd2(parmDate.getDate()),`\
649. `padd2(parmDate.getHours()),`\
650. `padd2(parmDate.getMinutes()),`\
651. `padd2(parmDate.getSeconds()),`\
652. `timeZoneString`\
653. `].join("");`
654. `return result;`
655. `});`
657. `var convertPDFDateToDate = (API.__private__.convertPDFDateToDate = function(`
658. `parmPDFDate`
659. `) {`
660. `var year = parseInt(parmPDFDate.substr(2, 4), 10);`
661. `var month = parseInt(parmPDFDate.substr(6, 2), 10) - 1;`
662. `var date = parseInt(parmPDFDate.substr(8, 2), 10);`
663. `var hour = parseInt(parmPDFDate.substr(10, 2), 10);`
664. `var minutes = parseInt(parmPDFDate.substr(12, 2), 10);`
665. `var seconds = parseInt(parmPDFDate.substr(14, 2), 10);`
666. `// var timeZoneHour = parseInt(parmPDFDate.substr(16, 2), 10);`
667. `// var timeZoneMinutes = parseInt(parmPDFDate.substr(20, 2), 10);`
669. `var resultingDate = new Date(year, month, date, hour, minutes, seconds, 0);`
670. `return resultingDate;`
671. `});`
673. `var setCreationDate = (API.__private__.setCreationDate = function(date) {`
674. `var tmpCreationDateString;`
675. `var regexPDFCreationDate = /^D:(20[0-2][0-9]|203[0-7]|19[7-9][0-9])(0[0-9]|1[0-2])([0-2][0-9]|3[0-1])(0[0-9]|1[0-9]|2[0-3])(0[0-9]|[1-5][0-9])(0[0-9]|[1-5][0-9])(\+0[0-9]|\+1[0-4]|-0[0-9]|-1[0-1])'(0[0-9]|[1-5][0-9])'?$/;`
676. `if (typeof date === "undefined") {`
677. `date = new Date();`
678. `}`
680. `if (date instanceof Date) {`
681. `tmpCreationDateString = convertDateToPDFDate(date);`
682. `} else if (regexPDFCreationDate.test(date)) {`
683. `tmpCreationDateString = date;`
684. `} else {`
685. `throw new Error("Invalid argument passed to jsPDF.setCreationDate");`
686. `}`
687. `creationDate = tmpCreationDateString;`
688. `return creationDate;`
689. `});`
691. `var getCreationDate = (API.__private__.getCreationDate = function(type) {`
692. `var result = creationDate;`
693. `if (type === "jsDate") {`
694. `result = convertPDFDateToDate(creationDate);`
695. `}`
696. `return result;`
697. `});`
699. `/**`
700. `* @name setCreationDate`
701. `* @memberof jsPDF#`
702. `* @function`
703. `* @instance`
704. `* @param {Object} date`
705. `* @returns {jsPDF}`
706. `*/`
707. `API.setCreationDate = function(date) {`
708. `setCreationDate(date);`
709. `return this;`
710. `};`
712. `/**`
713. `* @name getCreationDate`
714. `* @memberof jsPDF#`
715. `* @function`
716. `* @instance`
717. `* @param {Object} type`
718. `* @returns {Object}`
719. `*/`
720. `API.getCreationDate = function(type) {`
721. `return getCreationDate(type);`
722. `};`
724. `var padd2 = (API.__private__.padd2 = function(number) {`
725. `return ("0" + parseInt(number)).slice(-2);`
726. `});`
728. `var padd2Hex = (API.__private__.padd2Hex = function(hexString) {`
729. `hexString = hexString.toString();`
730. `return ("00" + hexString).substr(hexString.length);`
731. `});`
733. `var objectNumber = 0; // 'n' Current object number`
734. `var offsets = []; // List of offsets. Activated and reset by buildDocument(). Pupulated by various calls buildDocument makes.`
735. `var content = [];`
736. `var contentLength = 0;`
737. `var additionalObjects = [];`
739. `var pages = [];`
740. `var currentPage;`
741. `var hasCustomDestination = false;`
742. `var outputDestination = content;`
744. `var resetDocument = function() {`
745. `//reset fields relevant for objectNumber generation and xref.`
746. `objectNumber = 0;`
747. `contentLength = 0;`
748. `content = [];`
749. `offsets = [];`
750. `additionalObjects = [];`
752. `rootDictionaryObjId = newObjectDeferred();`
753. `resourceDictionaryObjId = newObjectDeferred();`
754. `};`
756. `API.__private__.setCustomOutputDestination = function(destination) {`
757. `hasCustomDestination = true;`
758. `outputDestination = destination;`
759. `};`
760. `var setOutputDestination = function(destination) {`
761. `if (!hasCustomDestination) {`
762. `outputDestination = destination;`
763. `}`
764. `};`
766. `API.__private__.resetCustomOutputDestination = function() {`
767. `hasCustomDestination = false;`
768. `outputDestination = content;`
769. `};`
771. `var out = (API.__private__.out = function(string) {`
772. `string = string.toString();`
773. `contentLength += string.length + 1;`
774. `outputDestination.push(string);`
776. `return outputDestination;`
777. `});`
779. `var write = (API.__private__.write = function(value) {`
780. `return out(`
781. `arguments.length === 1`
782. `? value.toString()`
783. `: Array.prototype.join.call(arguments, " ")`
784. `);`
785. `});`
787. `var getArrayBuffer = (API.__private__.getArrayBuffer = function(data) {`
788. `var len = data.length,`
789. `ab = new ArrayBuffer(len),`
790. `u8 = new Uint8Array(ab);`
792. `while (len--) u8[len] = data.charCodeAt(len);`
793. `return ab;`
794. `});`
796. `var standardFonts = [`\
797. `["Helvetica", "helvetica", "normal", "WinAnsiEncoding"],`\
798. `["Helvetica-Bold", "helvetica", "bold", "WinAnsiEncoding"],`\
799. `["Helvetica-Oblique", "helvetica", "italic", "WinAnsiEncoding"],`\
800. `["Helvetica-BoldOblique", "helvetica", "bolditalic", "WinAnsiEncoding"],`\
801. `["Courier", "courier", "normal", "WinAnsiEncoding"],`\
802. `["Courier-Bold", "courier", "bold", "WinAnsiEncoding"],`\
803. `["Courier-Oblique", "courier", "italic", "WinAnsiEncoding"],`\
804. `["Courier-BoldOblique", "courier", "bolditalic", "WinAnsiEncoding"],`\
805. `["Times-Roman", "times", "normal", "WinAnsiEncoding"],`\
806. `["Times-Bold", "times", "bold", "WinAnsiEncoding"],`\
807. `["Times-Italic", "times", "italic", "WinAnsiEncoding"],`\
808. `["Times-BoldItalic", "times", "bolditalic", "WinAnsiEncoding"],`\
809. `["ZapfDingbats", "zapfdingbats", "normal", null],`\
810. `["Symbol", "symbol", "normal", null]`\
811. `];`
813. `API.__private__.getStandardFonts = function() {`
814. `return standardFonts;`
815. `};`
817. `var activeFontSize = options.fontSize || 16;`
819. `/**`
820. `* Sets font size for upcoming text elements.`
821. `*`
822. `* @param {number} size Font size in points.`
823. `* @function`
824. `* @instance`
825. `* @returns {jsPDF}`
826. `* @memberof jsPDF#`
827. `* @name setFontSize`
828. `*/`
829. `API.__private__.setFontSize = API.setFontSize = function(size) {`
830. `if (apiMode === ApiMode.ADVANCED) {`
831. `activeFontSize = size / scaleFactor;`
832. `} else {`
833. `activeFontSize = size;`
834. `}`
835. `return this;`
836. `};`
838. `/**`
839. `* Gets the fontsize for upcoming text elements.`
840. `*`
841. `* @function`
842. `* @instance`
843. `* @returns {number}`
844. `* @memberof jsPDF#`
845. `* @name getFontSize`
846. `*/`
847. `var getFontSize = (API.__private__.getFontSize = API.getFontSize = function() {`
848. `if (apiMode === ApiMode.COMPAT) {`
849. `return activeFontSize;`
850. `} else {`
851. `return activeFontSize * scaleFactor;`
852. `}`
853. `});`
855. `var R2L = options.R2L || false;`
857. `/**`
858. `* Set value of R2L functionality.`
859. `*`
860. `* @param {boolean} value`
861. `* @function`
862. `* @instance`
863. `* @returns {jsPDF} jsPDF-instance`
864. `* @memberof jsPDF#`
865. `* @name setR2L`
866. `*/`
867. `API.__private__.setR2L = API.setR2L = function(value) {`
868. `R2L = value;`
869. `return this;`
870. `};`
872. `/**`
873. `* Get value of R2L functionality.`
874. `*`
875. `* @function`
876. `* @instance`
877. `* @returns {boolean} jsPDF-instance`
878. `* @memberof jsPDF#`
879. `* @name getR2L`
880. `*/`
881. `API.__private__.getR2L = API.getR2L = function() {`
882. `return R2L;`
883. `};`
885. `var zoomMode; // default: 1;`
887. `var setZoomMode = (API.__private__.setZoomMode = function(zoom) {`
888. `var validZoomModes = [`\
889. `undefined,`\
890. `null,`\
891. `"fullwidth",`\
892. `"fullheight",`\
893. `"fullpage",`\
894. `"original"`\
895. `];`
897. `if (/^(?:\d+\.\d*|\d*\.\d+|\d+)%$/.test(zoom)) {`
898. `zoomMode = zoom;`
899. `} else if (!isNaN(zoom)) {`
900. `zoomMode = parseInt(zoom, 10);`
901. `} else if (validZoomModes.indexOf(zoom) !== -1) {`
902. `zoomMode = zoom;`
903. `} else {`
904. `throw new Error(`
905. `'zoom must be Integer (e.g. 2), a percentage Value (e.g. 300%) or fullwidth, fullheight, fullpage, original. "' +`
906. `zoom +`
907. `'" is not recognized.'`
908. `);`
909. `}`
910. `});`
912. `API.__private__.getZoomMode = function() {`
913. `return zoomMode;`
914. `};`
916. `var pageMode; // default: 'UseOutlines';`
917. `var setPageMode = (API.__private__.setPageMode = function(pmode) {`
918. `var validPageModes = [`\
919. `undefined,`\
920. `null,`\
921. `"UseNone",`\
922. `"UseOutlines",`\
923. `"UseThumbs",`\
924. `"FullScreen"`\
925. `];`
927. `if (validPageModes.indexOf(pmode) == -1) {`
928. `throw new Error(`
929. `'Page mode must be one of UseNone, UseOutlines, UseThumbs, or FullScreen. "' +`
930. `pmode +`
931. `'" is not recognized.'`
932. `);`
933. `}`
934. `pageMode = pmode;`
935. `});`
937. `API.__private__.getPageMode = function() {`
938. `return pageMode;`
939. `};`
941. `var layoutMode; // default: 'continuous';`
942. `var setLayoutMode = (API.__private__.setLayoutMode = function(layout) {`
943. `var validLayoutModes = [`\
944. `undefined,`\
945. `null,`\
946. `"continuous",`\
947. `"single",`\
948. `"twoleft",`\
949. `"tworight",`\
950. `"two"`\
951. `];`
953. `if (validLayoutModes.indexOf(layout) == -1) {`
954. `throw new Error(`
955. `'Layout mode must be one of continuous, single, twoleft, tworight. "' +`
956. `layout +`
957. `'" is not recognized.'`
958. `);`
959. `}`
960. `layoutMode = layout;`
961. `});`
963. `API.__private__.getLayoutMode = function() {`
964. `return layoutMode;`
965. `};`
967. `/**`
968. `* Set the display mode options of the page like zoom and layout.`
969. `*`
970. `* @name setDisplayMode`
971. `* @memberof jsPDF#`
972. `* @function`
973. `* @instance`
974. `* @param {integer|String} zoom You can pass an integer or percentage as`
975. `* a string. 2 will scale the document up 2x, '200%' will scale up by the`
976. `* same amount. You can also set it to 'fullwidth', 'fullheight',`
977. `* 'fullpage', or 'original'.`
978. `*`
979. `* Only certain PDF readers support this, such as Adobe Acrobat.`
980. `*`
981. `* @param {string} layout Layout mode can be: 'continuous' - this is the`
982. `* default continuous scroll. 'single' - the single page mode only shows one`
983. `* page at a time. 'twoleft' - two column left mode, first page starts on`
984. `* the left, and 'tworight' - pages are laid out in two columns, with the`
985. `* first page on the right. This would be used for books.`
986. `* @param {string} pmode 'UseOutlines' - it shows the`
987. `* outline of the document on the left. 'UseThumbs' - shows thumbnails along`
988. `* the left. 'FullScreen' - prompts the user to enter fullscreen mode.`
989. `*`
990. `* @returns {jsPDF}`
991. `*/`
992. `API.__private__.setDisplayMode = API.setDisplayMode = function(`
993. `zoom,`
994. `layout,`
995. `pmode`
996. `) {`
997. `setZoomMode(zoom);`
998. `setLayoutMode(layout);`
999. `setPageMode(pmode);`
1000. `return this;`
1001. `};`
1003. `var documentProperties = {`
1004. `title: "",`
1005. `subject: "",`
1006. `author: "",`
1007. `keywords: "",`
1008. `creator: ""`
1009. `};`
1011. `API.__private__.getDocumentProperty = function(key) {`
1012. `if (Object.keys(documentProperties).indexOf(key) === -1) {`
1013. `throw new Error("Invalid argument passed to jsPDF.getDocumentProperty");`
1014. `}`
1015. `return documentProperties[key];`
1016. `};`
1018. `API.__private__.getDocumentProperties = function() {`
1019. `return documentProperties;`
1020. `};`
1022. `/**`
1023. `* Adds a properties to the PDF document.`
1024. `*`
1025. `* @param {Object} A property_name-to-property_value object structure.`
1026. `* @function`
1027. `* @instance`
1028. `* @returns {jsPDF}`
1029. `* @memberof jsPDF#`
1030. `* @name setDocumentProperties`
1031. `*/`
1032. `API.__private__.setDocumentProperties = API.setProperties = API.setDocumentProperties = function(`
1033. `properties`
1034. `) {`
1035. `// copying only those properties we can render.`
1036. `for (var property in documentProperties) {`
1037. `if (documentProperties.hasOwnProperty(property) && properties[property]) {`
1038. `documentProperties[property] = properties[property];`
1039. `}`
1040. `}`
1041. `return this;`
1042. `};`
1044. `API.__private__.setDocumentProperty = function(key, value) {`
1045. `if (Object.keys(documentProperties).indexOf(key) === -1) {`
1046. `throw new Error("Invalid arguments passed to jsPDF.setDocumentProperty");`
1047. `}`
1048. `return (documentProperties[key] = value);`
1049. `};`
1051. `var fonts = {}; // collection of font objects, where key is fontKey - a dynamically created label for a given font.`
1052. `var fontmap = {}; // mapping structure fontName > fontStyle > font key - performance layer. See addFont()`
1053. `var activeFontKey; // will be string representing the KEY of the font as combination of fontName + fontStyle`
1054. `var fontStateStack = []; //`
1055. `var patterns = {}; // collection of pattern objects`
1056. `var patternMap = {}; // see fonts`
1057. `var gStates = {}; // collection of graphic state objects`
1058. `var gStatesMap = {}; // see fonts`
1059. `var activeGState = null;`
1060. `var scaleFactor; // Scale factor`
1061. `var page = 0;`
1062. `var pagesContext = [];`
1063. `var events = new PubSub(API);`
1064. `var hotfixes = options.hotfixes || [];`
1066. `var renderTargets = {};`
1067. `var renderTargetMap = {};`
1068. `var renderTargetStack = [];`
1069. `var pageX;`
1070. `var pageY;`
1071. `var pageMatrix; // only used for FormObjects`
1073. `/**`
1074. `* A matrix object for 2D homogenous transformations: `
1075. `* | a b 0 | `
1076. `* | c d 0 | `
1077. `* | e f 1 | `
1078. `* pdf multiplies matrices righthand: v' = v x m1 x m2 x ...`
1079. `*`
1080. `* @class`
1081. `* @name Matrix`
1082. `* @param {number} sx`
1083. `* @param {number} shy`
1084. `* @param {number} shx`
1085. `* @param {number} sy`
1086. `* @param {number} tx`
1087. `* @param {number} ty`
1088. `* @constructor`
1089. `*/`
1090. `var Matrix = function(sx, shy, shx, sy, tx, ty) {`
1091. `if (!(this instanceof Matrix)) {`
1092. `return new Matrix(sx, shy, shx, sy, tx, ty);`
1093. `}`
1095. `if (isNaN(sx)) sx = 1;`
1096. `if (isNaN(shy)) shy = 0;`
1097. `if (isNaN(shx)) shx = 0;`
1098. `if (isNaN(sy)) sy = 1;`
1099. `if (isNaN(tx)) tx = 0;`
1100. `if (isNaN(ty)) ty = 0;`
1102. `this._matrix = [sx, shy, shx, sy, tx, ty];`
1103. `};`
1105. `/**`
1106. `* @name sx`
1107. `* @memberof Matrix#`
1108. `*/`
1109. `Object.defineProperty(Matrix.prototype, "sx", {`
1110. `get: function() {`
1111. `return this._matrix[0];`
1112. `},`
1113. `set: function(value) {`
1114. `this._matrix[0] = value;`
1115. `}`
1116. `});`
1118. `/**`
1119. `* @name shy`
1120. `* @memberof Matrix#`
1121. `*/`
1122. `Object.defineProperty(Matrix.prototype, "shy", {`
1123. `get: function() {`
1124. `return this._matrix[1];`
1125. `},`
1126. `set: function(value) {`
1127. `this._matrix[1] = value;`
1128. `}`
1129. `});`
1131. `/**`
1132. `* @name shx`
1133. `* @memberof Matrix#`
1134. `*/`
1135. `Object.defineProperty(Matrix.prototype, "shx", {`
1136. `get: function() {`
1137. `return this._matrix[2];`
1138. `},`
1139. `set: function(value) {`
1140. `this._matrix[2] = value;`
1141. `}`
1142. `});`
1144. `/**`
1145. `* @name sy`
1146. `* @memberof Matrix#`
1147. `*/`
1148. `Object.defineProperty(Matrix.prototype, "sy", {`
1149. `get: function() {`
1150. `return this._matrix[3];`
1151. `},`
1152. `set: function(value) {`
1153. `this._matrix[3] = value;`
1154. `}`
1155. `});`
1157. `/**`
1158. `* @name tx`
1159. `* @memberof Matrix#`
1160. `*/`
1161. `Object.defineProperty(Matrix.prototype, "tx", {`
1162. `get: function() {`
1163. `return this._matrix[4];`
1164. `},`
1165. `set: function(value) {`
1166. `this._matrix[4] = value;`
1167. `}`
1168. `});`
1170. `/**`
1171. `* @name ty`
1172. `* @memberof Matrix#`
1173. `*/`
1174. `Object.defineProperty(Matrix.prototype, "ty", {`
1175. `get: function() {`
1176. `return this._matrix[5];`
1177. `},`
1178. `set: function(value) {`
1179. `this._matrix[5] = value;`
1180. `}`
1181. `});`
1183. `Object.defineProperty(Matrix.prototype, "a", {`
1184. `get: function() {`
1185. `return this._matrix[0];`
1186. `},`
1187. `set: function(value) {`
1188. `this._matrix[0] = value;`
1189. `}`
1190. `});`
1192. `Object.defineProperty(Matrix.prototype, "b", {`
1193. `get: function() {`
1194. `return this._matrix[1];`
1195. `},`
1196. `set: function(value) {`
1197. `this._matrix[1] = value;`
1198. `}`
1199. `});`
1201. `Object.defineProperty(Matrix.prototype, "c", {`
1202. `get: function() {`
1203. `return this._matrix[2];`
1204. `},`
1205. `set: function(value) {`
1206. `this._matrix[2] = value;`
1207. `}`
1208. `});`
1210. `Object.defineProperty(Matrix.prototype, "d", {`
1211. `get: function() {`
1212. `return this._matrix[3];`
1213. `},`
1214. `set: function(value) {`
1215. `this._matrix[3] = value;`
1216. `}`
1217. `});`
1219. `Object.defineProperty(Matrix.prototype, "e", {`
1220. `get: function() {`
1221. `return this._matrix[4];`
1222. `},`
1223. `set: function(value) {`
1224. `this._matrix[4] = value;`
1225. `}`
1226. `});`
1228. `Object.defineProperty(Matrix.prototype, "f", {`
1229. `get: function() {`
1230. `return this._matrix[5];`
1231. `},`
1232. `set: function(value) {`
1233. `this._matrix[5] = value;`
1234. `}`
1235. `});`
1237. `/**`
1238. `* @name rotation`
1239. `* @memberof Matrix#`
1240. `*/`
1241. `Object.defineProperty(Matrix.prototype, "rotation", {`
1242. `get: function() {`
1243. `return Math.atan2(this.shx, this.sx);`
1244. `}`
1245. `});`
1247. `/**`
1248. `* @name scaleX`
1249. `* @memberof Matrix#`
1250. `*/`
1251. `Object.defineProperty(Matrix.prototype, "scaleX", {`
1252. `get: function() {`
1253. `return this.decompose().scale.sx;`
1254. `}`
1255. `});`
1257. `/**`
1258. `* @name scaleY`
1259. `* @memberof Matrix#`
1260. `*/`
1261. `Object.defineProperty(Matrix.prototype, "scaleY", {`
1262. `get: function() {`
1263. `return this.decompose().scale.sy;`
1264. `}`
1265. `});`
1267. `/**`
1268. `* @name isIdentity`
1269. `* @memberof Matrix#`
1270. `*/`
1271. `Object.defineProperty(Matrix.prototype, "isIdentity", {`
1272. `get: function() {`
1273. `if (this.sx !== 1) {`
1274. `return false;`
1275. `}`
1276. `if (this.shy !== 0) {`
1277. `return false;`
1278. `}`
1279. `if (this.shx !== 0) {`
1280. `return false;`
1281. `}`
1282. `if (this.sy !== 1) {`
1283. `return false;`
1284. `}`
1285. `if (this.tx !== 0) {`
1286. `return false;`
1287. `}`
1288. `if (this.ty !== 0) {`
1289. `return false;`
1290. `}`
1291. `return true;`
1292. `}`
1293. `});`
1295. `/**`
1296. `* Join the Matrix Values to a String`
1297. `*`
1298. `* @function join`
1299. `* @param {string} separator Specifies a string to separate each pair of adjacent elements of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma (","). If separator is an empty string, all elements are joined without any characters in between them.`
1300. `* @returns {string} A string with all array elements joined.`
1301. `* @memberof Matrix#`
1302. `*/`
1303. `Matrix.prototype.join = function(separator) {`
1304. `return [this.sx, this.shy, this.shx, this.sy, this.tx, this.ty]`
1305. `.map(hpf)`
1306. `.join(separator);`
1307. `};`
1309. `/**`
1310. `* Multiply the matrix with given Matrix`
1311. `*`
1312. `* @function multiply`
1313. `* @param matrix`
1314. `* @returns {Matrix}`
1315. `* @memberof Matrix#`
1316. `*/`
1317. `Matrix.prototype.multiply = function(matrix) {`
1318. `var sx = matrix.sx * this.sx + matrix.shy * this.shx;`
1319. `var shy = matrix.sx * this.shy + matrix.shy * this.sy;`
1320. `var shx = matrix.shx * this.sx + matrix.sy * this.shx;`
1321. `var sy = matrix.shx * this.shy + matrix.sy * this.sy;`
1322. `var tx = matrix.tx * this.sx + matrix.ty * this.shx + this.tx;`
1323. `var ty = matrix.tx * this.shy + matrix.ty * this.sy + this.ty;`
1325. `return new Matrix(sx, shy, shx, sy, tx, ty);`
1326. `};`
1328. `/**`
1329. `* @function decompose`
1330. `* @memberof Matrix#`
1331. `*/`
1332. `Matrix.prototype.decompose = function() {`
1333. `var a = this.sx;`
1334. `var b = this.shy;`
1335. `var c = this.shx;`
1336. `var d = this.sy;`
1337. `var e = this.tx;`
1338. `var f = this.ty;`
1340. `var scaleX = Math.sqrt(a * a + b * b);`
1341. `a /= scaleX;`
1342. `b /= scaleX;`
1344. `var shear = a * c + b * d;`
1345. `c -= a * shear;`
1346. `d -= b * shear;`
1348. `var scaleY = Math.sqrt(c * c + d * d);`
1349. `c /= scaleY;`
1350. `d /= scaleY;`
1351. `shear /= scaleY;`
1353. `if (a * d < b * c) {`
1354. `a = -a;`
1355. `b = -b;`
1356. `shear = -shear;`
1357. `scaleX = -scaleX;`
1358. `}`
1360. `return {`
1361. `scale: new Matrix(scaleX, 0, 0, scaleY, 0, 0),`
1362. `translate: new Matrix(1, 0, 0, 1, e, f),`
1363. `rotate: new Matrix(a, b, -b, a, 0, 0),`
1364. `skew: new Matrix(1, 0, shear, 1, 0, 0)`
1365. `};`
1366. `};`
1368. `/**`
1369. `* @function toString`
1370. `* @memberof Matrix#`
1371. `*/`
1372. `Matrix.prototype.toString = function(parmPrecision) {`
1373. `return this.join(" ");`
1374. `};`
1376. `/**`
1377. `* @function inversed`
1378. `* @memberof Matrix#`
1379. `*/`
1380. `Matrix.prototype.inversed = function() {`
1381. `var a = this.sx,`
1382. `b = this.shy,`
1383. `c = this.shx,`
1384. `d = this.sy,`
1385. `e = this.tx,`
1386. `f = this.ty;`
1388. `var quot = 1 / (a * d - b * c);`
1390. `var aInv = d * quot;`
1391. `var bInv = -b * quot;`
1392. `var cInv = -c * quot;`
1393. `var dInv = a * quot;`
1394. `var eInv = -aInv * e - cInv * f;`
1395. `var fInv = -bInv * e - dInv * f;`
1397. `return new Matrix(aInv, bInv, cInv, dInv, eInv, fInv);`
1398. `};`
1400. `/**`
1401. `* @function applyToPoint`
1402. `* @memberof Matrix#`
1403. `*/`
1404. `Matrix.prototype.applyToPoint = function(pt) {`
1405. `var x = pt.x * this.sx + pt.y * this.shx + this.tx;`
1406. `var y = pt.x * this.shy + pt.y * this.sy + this.ty;`
1407. `return new Point(x, y);`
1408. `};`
1410. `/**`
1411. `* @function applyToRectangle`
1412. `* @memberof Matrix#`
1413. `*/`
1414. `Matrix.prototype.applyToRectangle = function(rect) {`
1415. `var pt1 = this.applyToPoint(rect);`
1416. `var pt2 = this.applyToPoint(new Point(rect.x + rect.w, rect.y + rect.h));`
1417. `return new Rectangle(pt1.x, pt1.y, pt2.x - pt1.x, pt2.y - pt1.y);`
1418. `};`
1420. `/**`
1421. `* Clone the Matrix`
1422. `*`
1423. `* @function clone`
1424. `* @memberof Matrix#`
1425. `* @name clone`
1426. `* @instance`
1427. `*/`
1428. `Matrix.prototype.clone = function() {`
1429. `var sx = this.sx;`
1430. `var shy = this.shy;`
1431. `var shx = this.shx;`
1432. `var sy = this.sy;`
1433. `var tx = this.tx;`
1434. `var ty = this.ty;`
1436. `return new Matrix(sx, shy, shx, sy, tx, ty);`
1437. `};`
1439. `API.Matrix = Matrix;`
1441. `/**`
1442. `* Multiplies two matrices. (see {@link Matrix})`
1443. `* @param {Matrix} m1`
1444. `* @param {Matrix} m2`
1445. `* @memberof jsPDF#`
1446. `* @name matrixMult`
1447. `*/`
1448. `var matrixMult = (API.matrixMult = function(m1, m2) {`
1449. `return m2.multiply(m1);`
1450. `});`
1452. `/**`
1453. `* The identity matrix (equivalent to new Matrix(1, 0, 0, 1, 0, 0)).`
1454. `* @type {Matrix}`
1455. `* @memberof! jsPDF#`
1456. `* @name identityMatrix`
1457. `*/`
1458. `var identityMatrix = new Matrix(1, 0, 0, 1, 0, 0);`
1459. `API.unitMatrix = API.identityMatrix = identityMatrix;`
1461. `/**`
1462. `* Adds a new pattern for later use.`
1463. `* @param {String} key The key by it can be referenced later. The keys must be unique!`
1464. `* @param {API.Pattern} pattern The pattern`
1465. `*/`
1466. `var addPattern = function(key, pattern) {`
1467. `// only add it if it is not already present (the keys provided by the user must be unique!)`
1468. `if (patternMap[key]) return;`
1470. `var prefix = pattern instanceof ShadingPattern ? "Sh" : "P";`
1471. `var patternKey = prefix + (Object.keys(patterns).length + 1).toString(10);`
1472. `pattern.id = patternKey;`
1474. `patternMap[key] = patternKey;`
1475. `patterns[patternKey] = pattern;`
1477. `events.publish("addPattern", pattern);`
1478. `};`
1480. `/**`
1481. `* A pattern describing a shading pattern.`
1482. `*`
1483. `* Only available in "advanced" API mode.`
1484. `*`
1485. `* @param {String} type One of "axial" or "radial"`
1486. `* @param {Array} coords Either [x1, y1, x2, y2] for "axial" type describing the two interpolation points`
1487. `* or [x1, y1, r, x2, y2, r2] for "radial" describing inner and the outer circle.`
1488. `* @param {Array} colors An array of objects with the fields "offset" and "color". "offset" describes`
1489. `* the offset in parameter space [0, 1]. "color" is an array of length 3 describing RGB values in [0, 255].`
1490. `* @param {GState=} gState An additional graphics state that gets applied to the pattern (optional).`
1491. `* @param {Matrix=} matrix A matrix that describes the transformation between the pattern coordinate system`
1492. `* and the use coordinate system (optional).`
1493. `* @constructor`
1494. `* @extends API.Pattern`
1495. `*/`
1496. `API.ShadingPattern = ShadingPattern;`
1498. `/**`
1499. `* A PDF Tiling pattern.`
1500. `*`
1501. `* Only available in "advanced" API mode.`
1502. `*`
1503. `* @param {Array.} boundingBox The bounding box at which one pattern cell gets clipped.`
1504. `* @param {Number} xStep Horizontal spacing between pattern cells.`
1505. `* @param {Number} yStep Vertical spacing between pattern cells.`
1506. `* @param {API.GState=} gState An additional graphics state that gets applied to the pattern (optional).`
1507. `* @param {Matrix=} matrix A matrix that describes the transformation between the pattern coordinate system`
1508. `* and the use coordinate system (optional).`
1509. `* @constructor`
1510. `* @extends API.Pattern`
1511. `*/`
1512. `API.TilingPattern = TilingPattern;`
1514. `/**`
1515. `* Adds a new {@link API.ShadingPattern} for later use. Only available in "advanced" API mode.`
1516. `* @param {String} key`
1517. `* @param {Pattern} pattern`
1518. `* @function`
1519. `* @returns {jsPDF}`
1520. `* @memberof jsPDF#`
1521. `* @name addPattern`
1522. `*/`
1523. `API.addShadingPattern = function(key, pattern) {`
1524. `advancedApiModeTrap("addShadingPattern()");`
1526. `addPattern(key, pattern);`
1527. `return this;`
1528. `};`
1530. `/**`
1531. `* Begins a new tiling pattern. All subsequent render calls are drawn to this pattern until {@link API.endTilingPattern}`
1532. `* gets called. Only available in "advanced" API mode.`
1533. `* @param {API.Pattern} pattern`
1534. `* @memberof jsPDF#`
1535. `* @name beginTilingPattern`
1536. `*/`
1537. `API.beginTilingPattern = function(pattern) {`
1538. `advancedApiModeTrap("beginTilingPattern()");`
1540. `beginNewRenderTarget(`
1541. `pattern.boundingBox[0],`
1542. `pattern.boundingBox[1],`
1543. `pattern.boundingBox[2] - pattern.boundingBox[0],`
1544. `pattern.boundingBox[3] - pattern.boundingBox[1],`
1545. `pattern.matrix`
1546. `);`
1547. `};`
1549. `/**`
1550. `* Ends a tiling pattern and sets the render target to the one active before {@link API.beginTilingPattern} has been called.`
1551. `*`
1552. `* Only available in "advanced" API mode.`
1553. `*`
1554. `* @param {string} key A unique key that is used to reference this pattern at later use.`
1555. `* @param {API.Pattern} pattern The pattern to end.`
1556. `* @memberof jsPDF#`
1557. `* @name endTilingPattern`
1558. `*/`
1559. `API.endTilingPattern = function(key, pattern) {`
1560. `advancedApiModeTrap("endTilingPattern()");`
1562. `// retrieve the stream`
1563. `pattern.stream = pages[currentPage].join("\n");`
1565. `addPattern(key, pattern);`
1567. `events.publish("endTilingPattern", pattern);`
1569. `// restore state from stack`
1570. `renderTargetStack.pop().restore();`
1571. `};`
1573. `var newObject = (API.__private__.newObject = function() {`
1574. `var oid = newObjectDeferred();`
1575. `newObjectDeferredBegin(oid, true);`
1576. `return oid;`
1577. `});`
1579. `// Does not output the object. The caller must call newObjectDeferredBegin(oid) before outputing any data`
1580. `var newObjectDeferred = (API.__private__.newObjectDeferred = function() {`
1581. `objectNumber++;`
1582. `offsets[objectNumber] = function() {`
1583. `return contentLength;`
1584. `};`
1585. `return objectNumber;`
1586. `});`
1588. `var newObjectDeferredBegin = function(oid, doOutput) {`
1589. `doOutput = typeof doOutput === "boolean" ? doOutput : false;`
1590. `offsets[oid] = contentLength;`
1591. `if (doOutput) {`
1592. `out(oid + " 0 obj");`
1593. `}`
1594. `return oid;`
1595. `};`
1596. `// Does not output the object until after the pages have been output.`
1597. `// Returns an object containing the objectId and content.`
1598. `// All pages have been added so the object ID can be estimated to start right after.`
1599. `// This does not modify the current objectNumber; It must be updated after the newObjects are output.`
1600. `var newAdditionalObject = (API.__private__.newAdditionalObject = function() {`
1601. `var objId = newObjectDeferred();`
1602. `var obj = {`
1603. `objId: objId,`
1604. `content: ""`
1605. `};`
1606. `additionalObjects.push(obj);`
1607. `return obj;`
1608. `});`
1610. `var rootDictionaryObjId = newObjectDeferred();`
1611. `var resourceDictionaryObjId = newObjectDeferred();`
1613. `/////////////////////`
1614. `// Private functions`
1615. `/////////////////////`
1617. `var decodeColorString = (API.__private__.decodeColorString = function(color) {`
1618. `var colorEncoded = color.split(" ");`
1619. `if (`
1620. `colorEncoded.length === 2 &&`
1621. `(colorEncoded[1] === "g" || colorEncoded[1] === "G")`
1622. `) {`
1623. `// convert grayscale value to rgb so that it can be converted to hex for consistency`
1624. `var floatVal = parseFloat(colorEncoded[0]);`
1625. `colorEncoded = [floatVal, floatVal, floatVal, "r"];`
1626. `} else if (`
1627. `colorEncoded.length === 5 &&`
1628. `(colorEncoded[4] === "k" || colorEncoded[4] === "K")`
1629. `) {`
1630. `// convert CMYK values to rbg so that it can be converted to hex for consistency`
1631. `var red = (1.0 - colorEncoded[0]) * (1.0 - colorEncoded[3]);`
1632. `var green = (1.0 - colorEncoded[1]) * (1.0 - colorEncoded[3]);`
1633. `var blue = (1.0 - colorEncoded[2]) * (1.0 - colorEncoded[3]);`
1635. `colorEncoded = [red, green, blue, "r"];`
1636. `}`
1637. `var colorAsRGB = "#";`
1638. `for (var i = 0; i < 3; i++) {`
1639. `colorAsRGB += (`
1640. `"0" + Math.floor(parseFloat(colorEncoded[i]) * 255).toString(16)`
1641. `).slice(-2);`
1642. `}`
1643. `return colorAsRGB;`
1644. `});`
1646. `var encodeColorString = (API.__private__.encodeColorString = function(`
1647. `options`
1648. `) {`
1649. `var color;`
1651. `if (typeof options === "string") {`
1652. `options = {`
1653. `ch1: options`
1654. `};`
1655. `}`
1656. `var ch1 = options.ch1;`
1657. `var ch2 = options.ch2;`
1658. `var ch3 = options.ch3;`
1659. `var ch4 = options.ch4;`
1660. `var letterArray =`
1661. `options.pdfColorType === "draw" ? ["G", "RG", "K"] : ["g", "rg", "k"];`
1663. `if (typeof ch1 === "string" && ch1.charAt(0) !== "#") {`
1664. `var rgbColor = new RGBColor(ch1);`
1665. `if (rgbColor.ok) {`
1666. `ch1 = rgbColor.toHex();`
1667. `} else if (!/^\d*\.?\d*$/.test(ch1)) {`
1668. `throw new Error(`
1669. `'Invalid color "' + ch1 + '" passed to jsPDF.encodeColorString.'`
1670. `);`
1671. `}`
1672. `}`
1673. `//convert short rgb to long form`
1674. `if (typeof ch1 === "string" && /^#[0-9A-Fa-f]{3}$/.test(ch1)) {`
1675. `ch1 = "#" + ch1[1] + ch1[1] + ch1[2] + ch1[2] + ch1[3] + ch1[3];`
1676. `}`
1678. `if (typeof ch1 === "string" && /^#[0-9A-Fa-f]{6}$/.test(ch1)) {`
1679. `var hex = parseInt(ch1.substr(1), 16);`
1680. `ch1 = (hex >> 16) & 255;`
1681. `ch2 = (hex >> 8) & 255;`
1682. `ch3 = hex & 255;`
1683. `}`
1685. `if (`
1686. `typeof ch2 === "undefined" ||`
1687. `(typeof ch4 === "undefined" && ch1 === ch2 && ch2 === ch3)`
1688. `) {`
1689. `// Gray color space.`
1690. `if (typeof ch1 === "string") {`
1691. `color = ch1 + " " + letterArray[0];`
1692. `} else {`
1693. `switch (options.precision) {`
1694. `case 2:`
1695. `color = f2(ch1 / 255) + " " + letterArray[0];`
1696. `break;`
1697. `case 3:`
1698. `default:`
1699. `color = f3(ch1 / 255) + " " + letterArray[0];`
1700. `}`
1701. `}`
1702. `} else if (typeof ch4 === "undefined" || typeof ch4 === "object") {`
1703. `// assume RGBA`
1704. `if (ch4 && !isNaN(ch4.a)) {`
1705. `//TODO Implement transparency.`
1706. `//WORKAROUND use white for now, if transparent, otherwise handle as rgb`
1707. `if (ch4.a === 0) {`
1708. `color = ["1.", "1.", "1.", letterArray[1]].join(" ");`
1709. `return color;`
1710. `}`
1711. `}`
1712. `// assume RGB`
1713. `if (typeof ch1 === "string") {`
1714. `color = [ch1, ch2, ch3, letterArray[1]].join(" ");`
1715. `} else {`
1716. `switch (options.precision) {`
1717. `case 2:`
1718. `color = [`\
1719. `f2(ch1 / 255),`\
1720. `f2(ch2 / 255),`\
1721. `f2(ch3 / 255),`\
1722. `letterArray[1]`\
1723. `].join(" ");`
1724. `break;`
1725. `default:`
1726. `case 3:`
1727. `color = [`\
1728. `f3(ch1 / 255),`\
1729. `f3(ch2 / 255),`\
1730. `f3(ch3 / 255),`\
1731. `letterArray[1]`\
1732. `].join(" ");`
1733. `}`
1734. `}`
1735. `} else {`
1736. `// assume CMYK`
1737. `if (typeof ch1 === "string") {`
1738. `color = [ch1, ch2, ch3, ch4, letterArray[2]].join(" ");`
1739. `} else {`
1740. `switch (options.precision) {`
1741. `case 2:`
1742. `color = [f2(ch1), f2(ch2), f2(ch3), f2(ch4), letterArray[2]].join(`
1743. `" "`
1744. `);`
1745. `break;`
1746. `case 3:`
1747. `default:`
1748. `color = [f3(ch1), f3(ch2), f3(ch3), f3(ch4), letterArray[2]].join(`
1749. `" "`
1750. `);`
1751. `}`
1752. `}`
1753. `}`
1754. `return color;`
1755. `});`
1757. `var getFilters = (API.__private__.getFilters = function() {`
1758. `return filters;`
1759. `});`
1761. `var putStream = (API.__private__.putStream = function(options) {`
1762. `options = options || {};`
1763. `var data = options.data || "";`
1764. `var filters = options.filters || getFilters();`
1765. `var alreadyAppliedFilters = options.alreadyAppliedFilters || [];`
1766. `var addLength1 = options.addLength1 || false;`
1767. `var valueOfLength1 = data.length;`
1768. `var objectId = options.objectId;`
1769. `var encryptor = function(data) {`
1770. `return data;`
1771. `};`
1772. `if (encryptionOptions !== null && typeof objectId == "undefined") {`
1773. `throw new Error(`
1774. `"ObjectId must be passed to putStream for file encryption"`
1775. `);`
1776. `}`
1777. `if (encryptionOptions !== null) {`
1778. `encryptor = encryption.encryptor(objectId, 0);`
1779. `}`
1781. `var processedData = {};`
1782. `if (filters === true) {`
1783. `filters = ["FlateEncode"];`
1784. `}`
1785. `var keyValues = options.additionalKeyValues || [];`
1786. `if (typeof jsPDF.API.processDataByFilters !== "undefined") {`
1787. `processedData = jsPDF.API.processDataByFilters(data, filters);`
1788. `} else {`
1789. `processedData = { data: data, reverseChain: [] };`
1790. `}`
1791. `var filterAsString =`
1792. `processedData.reverseChain +`
1793. `(Array.isArray(alreadyAppliedFilters)`
1794. `? alreadyAppliedFilters.join(" ")`
1795. `: alreadyAppliedFilters.toString());`
1797. `if (processedData.data.length !== 0) {`
1798. `keyValues.push({`
1799. `key: "Length",`
1800. `value: processedData.data.length`
1801. `});`
1802. `if (addLength1 === true) {`
1803. `keyValues.push({`
1804. `key: "Length1",`
1805. `value: valueOfLength1`
1806. `});`
1807. `}`
1808. `}`
1810. `if (filterAsString.length != 0) {`
1811. `if (filterAsString.split("/").length - 1 === 1) {`
1812. `keyValues.push({`
1813. `key: "Filter",`
1814. `value: filterAsString`
1815. `});`
1816. `} else {`
1817. `keyValues.push({`
1818. `key: "Filter",`
1819. `value: "[" + filterAsString + "]"`
1820. `});`
1822. `for (var j = 0; j < keyValues.length; j += 1) {`
1823. `if (keyValues[j].key === "DecodeParms") {`
1824. `var decodeParmsArray = [];`
1826. `for (`
1827. `var i = 0;`
1828. `i < processedData.reverseChain.split("/").length - 1;`
1829. `i += 1`
1830. `) {`
1831. `decodeParmsArray.push("null");`
1832. `}`
1834. `decodeParmsArray.push(keyValues[j].value);`
1835. `keyValues[j].value = "[" + decodeParmsArray.join(" ") + "]";`
1836. `}`
1837. `}`
1838. `}`
1839. `}`
1841. `out("<<");`
1842. `for (var k = 0; k < keyValues.length; k++) {`
1843. `out("/" + keyValues[k].key + " " + keyValues[k].value);`
1844. `}`
1845. `out(">>");`
1846. `if (processedData.data.length !== 0) {`
1847. `out("stream");`
1848. `out(encryptor(processedData.data));`
1849. `out("endstream");`
1850. `}`
1851. `});`
1853. `var putPage = (API.__private__.putPage = function(page) {`
1854. `var pageNumber = page.number;`
1855. `var data = page.data;`
1856. `var pageObjectNumber = page.objId;`
1857. `var pageContentsObjId = page.contentsObjId;`
1859. `newObjectDeferredBegin(pageObjectNumber, true);`
1860. `out("<>");`
1942. `out("endobj");`
1943. `// Page content`
1944. `var pageContent = data.join("\n");`
1946. `if (apiMode === ApiMode.ADVANCED) {`
1947. `// if the user forgot to switch back to COMPAT mode, we must balance the graphics stack again`
1948. `pageContent += "\nQ";`
1949. `}`
1951. `newObjectDeferredBegin(pageContentsObjId, true);`
1952. `putStream({`
1953. `data: pageContent,`
1954. `filters: getFilters(),`
1955. `objectId: pageContentsObjId`
1956. `});`
1957. `out("endobj");`
1958. `return pageObjectNumber;`
1959. `});`
1961. `var putPages = (API.__private__.putPages = function() {`
1962. `var n,`
1963. `i,`
1964. `pageObjectNumbers = [];`
1966. `for (n = 1; n <= page; n++) {`
1967. `pagesContext[n].objId = newObjectDeferred();`
1968. `pagesContext[n].contentsObjId = newObjectDeferred();`
1969. `}`
1971. `for (n = 1; n <= page; n++) {`
1972. `pageObjectNumbers.push(`
1973. `putPage({`
1974. `number: n,`
1975. `data: pages[n],`
1976. `objId: pagesContext[n].objId,`
1977. `contentsObjId: pagesContext[n].contentsObjId,`
1978. `mediaBox: pagesContext[n].mediaBox,`
1979. `cropBox: pagesContext[n].cropBox,`
1980. `bleedBox: pagesContext[n].bleedBox,`
1981. `trimBox: pagesContext[n].trimBox,`
1982. `artBox: pagesContext[n].artBox,`
1983. `userUnit: pagesContext[n].userUnit,`
1984. `rootDictionaryObjId: rootDictionaryObjId,`
1985. `resourceDictionaryObjId: resourceDictionaryObjId`
1986. `})`
1987. `);`
1988. `}`
1989. `newObjectDeferredBegin(rootDictionaryObjId, true);`
1990. `out("<>");`
1998. `out("endobj");`
1999. `events.publish("postPutPages");`
2000. `});`
2002. `var putFont = function(font) {`
2003. `events.publish("putFont", {`
2004. `font: font,`
2005. `out: out,`
2006. `newObject: newObject,`
2007. `putStream: putStream`
2008. `});`
2010. `if (font.isAlreadyPutted !== true) {`
2011. `font.objectNumber = newObject();`
2012. `out("<<");`
2013. `out("/Type /Font");`
2014. `out("/BaseFont /" + toPDFName(font.postScriptName));`
2015. `out("/Subtype /Type1");`
2016. `if (typeof font.encoding === "string") {`
2017. `out("/Encoding /" + font.encoding);`
2018. `}`
2019. `out("/FirstChar 32");`
2020. `out("/LastChar 255");`
2021. `out(">>");`
2022. `out("endobj");`
2023. `}`
2024. `};`
2026. `var putFonts = function() {`
2027. `for (var fontKey in fonts) {`
2028. `if (fonts.hasOwnProperty(fontKey)) {`
2029. `if (`
2030. `putOnlyUsedFonts === false ||`
2031. `(putOnlyUsedFonts === true && usedFonts.hasOwnProperty(fontKey))`
2032. `) {`
2033. `putFont(fonts[fontKey]);`
2034. `}`
2035. `}`
2036. `}`
2037. `};`
2039. `var putXObject = function(xObject) {`
2040. `xObject.objectNumber = newObject();`
2042. `var options = [];`
2043. `options.push({ key: "Type", value: "/XObject" });`
2044. `options.push({ key: "Subtype", value: "/Form" });`
2045. `options.push({`
2046. `key: "BBox",`
2047. `value:`
2048. `"[" +`\
2049. `[`\
2050. `hpf(xObject.x),`\
2051. `hpf(xObject.y),`\
2052. `hpf(xObject.x + xObject.width),`\
2053. `hpf(xObject.y + xObject.height)`\
2054. `].join(" ") +`\
2055. `"]"`
2056. `});`
2057. `options.push({`
2058. `key: "Matrix",`
2059. `value: "[" + xObject.matrix.toString() + "]"`
2060. `});`
2061. `// TODO: /Resources`
2063. `var stream = xObject.pages[1].join("\n");`
2064. `putStream({`
2065. `data: stream,`
2066. `additionalKeyValues: options,`
2067. `objectId: xObject.objectNumber`
2068. `});`
2069. `out("endobj");`
2070. `};`
2072. `var putXObjects = function() {`
2073. `for (var xObjectKey in renderTargets) {`
2074. `if (renderTargets.hasOwnProperty(xObjectKey)) {`
2075. `putXObject(renderTargets[xObjectKey]);`
2076. `}`
2077. `}`
2078. `};`
2080. `var interpolateAndEncodeRGBStream = function(colors, numberSamples) {`
2081. `var tValues = [];`
2082. `var t;`
2083. `var dT = 1.0 / (numberSamples - 1);`
2084. `for (t = 0.0; t < 1.0; t += dT) {`
2085. `tValues.push(t);`
2086. `}`
2087. `tValues.push(1.0);`
2088. `// add first and last control point if not present`
2089. `if (colors[0].offset != 0.0) {`
2090. `var c0 = {`
2091. `offset: 0.0,`
2092. `color: colors[0].color`
2093. `};`
2094. `colors.unshift(c0);`
2095. `}`
2096. `if (colors[colors.length - 1].offset != 1.0) {`
2097. `var c1 = {`
2098. `offset: 1.0,`
2099. `color: colors[colors.length - 1].color`
2100. `};`
2101. `colors.push(c1);`
2102. `}`
2103. `var out = "";`
2104. `var index = 0;`
2106. `for (var i = 0; i < tValues.length; i++) {`
2107. `t = tValues[i];`
2108. `while (t > colors[index + 1].offset) index++;`
2109. `var a = colors[index].offset;`
2110. `var b = colors[index + 1].offset;`
2111. `var d = (t - a) / (b - a);`
2113. `var aColor = colors[index].color;`
2114. `var bColor = colors[index + 1].color;`
2116. `out +=`
2117. `padd2Hex(Math.round((1 - d) * aColor[0] + d * bColor[0]).toString(16)) +`
2118. `padd2Hex(Math.round((1 - d) * aColor[1] + d * bColor[1]).toString(16)) +`
2119. `padd2Hex(Math.round((1 - d) * aColor[2] + d * bColor[2]).toString(16));`
2120. `}`
2121. `return out.trim();`
2122. `};`
2124. `var putShadingPattern = function(pattern, numberSamples) {`
2125. `/*`
2126. `Axial patterns shade between the two points specified in coords, radial patterns between the inner`
2127. `and outer circle.`
2128. `The user can specify an array (colors) that maps t-Values in [0, 1] to RGB colors. These are now`
2129. `interpolated to equidistant samples and written to pdf as a sample (type 0) function.`
2130. `*/`
2131. `// The number of color samples that should be used to describe the shading.`
2132. `// The higher, the more accurate the gradient will be.`
2133. `numberSamples || (numberSamples = 21);`
2134. `var funcObjectNumber = newObject();`
2135. `var stream = interpolateAndEncodeRGBStream(pattern.colors, numberSamples);`
2137. `var options = [];`
2138. `options.push({ key: "FunctionType", value: "0" });`
2139. `options.push({ key: "Domain", value: "[0.0 1.0]" });`
2140. `options.push({ key: "Size", value: "[" + numberSamples + "]" });`
2141. `options.push({ key: "BitsPerSample", value: "8" });`
2142. `options.push({ key: "Range", value: "[0.0 1.0 0.0 1.0 0.0 1.0]" });`
2143. `options.push({ key: "Decode", value: "[0.0 1.0 0.0 1.0 0.0 1.0]" });`
2145. `putStream({`
2146. `data: stream,`
2147. `additionalKeyValues: options,`
2148. `alreadyAppliedFilters: ["/ASCIIHexDecode"],`
2149. `objectId: funcObjectNumber`
2150. `});`
2151. `out("endobj");`
2153. `pattern.objectNumber = newObject();`
2154. `out("<< /ShadingType " + pattern.type);`
2155. `out("/ColorSpace /DeviceRGB");`
2156. `var coords =`
2157. `"/Coords [" +`\
2158. `hpf(parseFloat(pattern.coords[0])) +`\
2159. `" " + // x1`\
2160. `hpf(parseFloat(pattern.coords[1])) +`\
2161. `" "; // y1`\
2162. `if (pattern.type === 2) {`\
2163. `// axial`\
2164. `coords +=`\
2165. `hpf(parseFloat(pattern.coords[2])) +`\
2166. `" " + // x2`\
2167. `hpf(parseFloat(pattern.coords[3])); // y2`\
2168. `} else {`\
2169. `// radial`\
2170. `coords +=`\
2171. `hpf(parseFloat(pattern.coords[2])) +`\
2172. `" " + // r1`\
2173. `hpf(parseFloat(pattern.coords[3])) +`\
2174. `" " + // x2`\
2175. `hpf(parseFloat(pattern.coords[4])) +`\
2176. `" " + // y2`\
2177. `hpf(parseFloat(pattern.coords[5])); // r2`\
2178. `}`\
2179. `coords += "]";`
2180. `out(coords);`
2182. `if (pattern.matrix) {`
2183. `out("/Matrix [" + pattern.matrix.toString() + "]");`
2184. `}`
2185. `out("/Function " + funcObjectNumber + " 0 R");`
2186. `out("/Extend [true true]");`
2187. `out(">>");`
2188. `out("endobj");`
2189. `};`
2191. `var putTilingPattern = function(pattern, deferredResourceDictionaryIds) {`
2192. `var resourcesObjectId = newObjectDeferred();`
2193. `var patternObjectId = newObject();`
2195. `deferredResourceDictionaryIds.push({`
2196. `resourcesOid: resourcesObjectId,`
2197. `objectOid: patternObjectId`
2198. `});`
2200. `pattern.objectNumber = patternObjectId;`
2201. `var options = [];`
2202. `options.push({ key: "Type", value: "/Pattern" });`
2203. `options.push({ key: "PatternType", value: "1" }); // tiling pattern`
2204. `options.push({ key: "PaintType", value: "1" }); // colored tiling pattern`
2205. `options.push({ key: "TilingType", value: "1" }); // constant spacing`
2206. `options.push({`
2207. `key: "BBox",`
2208. `value: "[" + pattern.boundingBox.map(hpf).join(" ") + "]"`
2209. `});`
2210. `options.push({ key: "XStep", value: hpf(pattern.xStep) });`
2211. `options.push({ key: "YStep", value: hpf(pattern.yStep) });`
2212. `options.push({ key: "Resources", value: resourcesObjectId + " 0 R" });`
2213. `if (pattern.matrix) {`
2214. `options.push({`
2215. `key: "Matrix",`
2216. `value: "[" + pattern.matrix.toString() + "]"`
2217. `});`
2218. `}`
2220. `putStream({`
2221. `data: pattern.stream,`
2222. `additionalKeyValues: options,`
2223. `objectId: pattern.objectNumber`
2224. `});`
2225. `out("endobj");`
2226. `};`
2228. `var putPatterns = function(deferredResourceDictionaryIds) {`
2229. `var patternKey;`
2230. `for (patternKey in patterns) {`
2231. `if (patterns.hasOwnProperty(patternKey)) {`
2232. `if (patterns[patternKey] instanceof ShadingPattern) {`
2233. `putShadingPattern(patterns[patternKey]);`
2234. `} else if (patterns[patternKey] instanceof TilingPattern) {`
2235. `putTilingPattern(patterns[patternKey], deferredResourceDictionaryIds);`
2236. `}`
2237. `}`
2238. `}`
2239. `};`
2241. `var putGState = function(gState) {`
2242. `gState.objectNumber = newObject();`
2243. `out("<<");`
2244. `for (var p in gState) {`
2245. `switch (p) {`
2246. `case "opacity":`
2247. `out("/ca " + f2(gState[p]));`
2248. `break;`
2249. `case "stroke-opacity":`
2250. `out("/CA " + f2(gState[p]));`
2251. `break;`
2252. `}`
2253. `}`
2254. `out(">>");`
2255. `out("endobj");`
2256. `};`
2258. `var putGStates = function() {`
2259. `var gStateKey;`
2260. `for (gStateKey in gStates) {`
2261. `if (gStates.hasOwnProperty(gStateKey)) {`
2262. `putGState(gStates[gStateKey]);`
2263. `}`
2264. `}`
2265. `};`
2267. `var putXobjectDict = function() {`
2268. `out("/XObject <<");`
2269. `for (var xObjectKey in renderTargets) {`
2270. `if (`
2271. `renderTargets.hasOwnProperty(xObjectKey) &&`
2272. `renderTargets[xObjectKey].objectNumber >= 0`
2273. `) {`
2274. `out(`
2275. `"/" +`
2276. `xObjectKey +`
2277. `" " +`
2278. `renderTargets[xObjectKey].objectNumber +`
2279. `" 0 R"`
2280. `);`
2281. `}`
2282. `}`
2284. `// Loop through images, or other data objects`
2285. `events.publish("putXobjectDict");`
2286. `out(">>");`
2287. `};`
2289. `var putEncryptionDict = function() {`
2290. `encryption.oid = newObject();`
2291. `out("<<");`
2292. `out("/Filter /Standard");`
2293. `out("/V " + encryption.v);`
2294. `out("/R " + encryption.r);`
2295. `out("/U <" + encryption.toHexString(encryption.U) + ">");`
2296. `out("/O <" + encryption.toHexString(encryption.O) + ">");`
2297. `out("/P " + encryption.P);`
2298. `out(">>");`
2299. `out("endobj");`
2300. `};`
2302. `var putFontDict = function() {`
2303. `out("/Font <<");`
2305. `for (var fontKey in fonts) {`
2306. `if (fonts.hasOwnProperty(fontKey)) {`
2307. `if (`
2308. `putOnlyUsedFonts === false ||`
2309. `(putOnlyUsedFonts === true && usedFonts.hasOwnProperty(fontKey))`
2310. `) {`
2311. `out("/" + fontKey + " " + fonts[fontKey].objectNumber + " 0 R");`
2312. `}`
2313. `}`
2314. `}`
2315. `out(">>");`
2316. `};`
2318. `var putShadingPatternDict = function() {`
2319. `if (Object.keys(patterns).length > 0) {`
2320. `out("/Shading <<");`
2321. `for (var patternKey in patterns) {`
2322. `if (`
2323. `patterns.hasOwnProperty(patternKey) &&`
2324. `patterns[patternKey] instanceof ShadingPattern &&`
2325. `patterns[patternKey].objectNumber >= 0`
2326. `) {`
2327. `out(`
2328. `"/" + patternKey + " " + patterns[patternKey].objectNumber + " 0 R"`
2329. `);`
2330. `}`
2331. `}`
2333. `events.publish("putShadingPatternDict");`
2334. `out(">>");`
2335. `}`
2336. `};`
2338. `var putTilingPatternDict = function(objectOid) {`
2339. `if (Object.keys(patterns).length > 0) {`
2340. `out("/Pattern <<");`
2341. `for (var patternKey in patterns) {`
2342. `if (`
2343. `patterns.hasOwnProperty(patternKey) &&`
2344. `patterns[patternKey] instanceof API.TilingPattern &&`
2345. `patterns[patternKey].objectNumber >= 0 &&`
2346. `patterns[patternKey].objectNumber < objectOid // prevent cyclic dependencies`
2347. `) {`
2348. `out(`
2349. `"/" + patternKey + " " + patterns[patternKey].objectNumber + " 0 R"`
2350. `);`
2351. `}`
2352. `}`
2353. `events.publish("putTilingPatternDict");`
2354. `out(">>");`
2355. `}`
2356. `};`
2358. `var putGStatesDict = function() {`
2359. `if (Object.keys(gStates).length > 0) {`
2360. `var gStateKey;`
2361. `out("/ExtGState <<");`
2362. `for (gStateKey in gStates) {`
2363. `if (`
2364. `gStates.hasOwnProperty(gStateKey) &&`
2365. `gStates[gStateKey].objectNumber >= 0`
2366. `) {`
2367. `out("/" + gStateKey + " " + gStates[gStateKey].objectNumber + " 0 R");`
2368. `}`
2369. `}`
2371. `events.publish("putGStateDict");`
2372. `out(">>");`
2373. `}`
2374. `};`
2376. `var putResourceDictionary = function(objectIds) {`
2377. `newObjectDeferredBegin(objectIds.resourcesOid, true);`
2378. `out("<<");`
2379. `out("/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]");`
2380. `putFontDict();`
2381. `putShadingPatternDict();`
2382. `putTilingPatternDict(objectIds.objectOid);`
2383. `putGStatesDict();`
2384. `putXobjectDict();`
2385. `out(">>");`
2386. `out("endobj");`
2387. `};`
2389. `var putResources = function() {`
2390. `// FormObjects, Patterns etc. might use other FormObjects/Patterns/Images`
2391. `// which means their resource dictionaries must contain the already resolved`
2392. `// object ids. For this reason we defer the serialization of the resource`
2393. `// dicts until all objects have been serialized and have object ids.`
2394. `//`
2395. `// In order to prevent cyclic dependencies (which Adobe Reader doesn't like),`
2396. `// we only put all oids that are smaller than the oid of the object the`
2397. `// resource dict belongs to. This is correct behavior, since the streams`
2398. `// may only use other objects that have already been defined and thus appear`
2399. `// earlier in their respective collection.`
2400. `// Currently, this only affects tiling patterns, but a (more) correct`
2401. `// implementation of FormObjects would also define their own resource dicts.`
2402. `var deferredResourceDictionaryIds = [];`
2404. `putFonts();`
2405. `putGStates();`
2406. `putXObjects();`
2407. `putPatterns(deferredResourceDictionaryIds);`
2409. `events.publish("putResources");`
2410. `deferredResourceDictionaryIds.forEach(putResourceDictionary);`
2411. `putResourceDictionary({`
2412. `resourcesOid: resourceDictionaryObjId,`
2413. `objectOid: Number.MAX_SAFE_INTEGER // output all objects`
2414. `});`
2415. `events.publish("postPutResources");`
2416. `};`
2418. `var putAdditionalObjects = function() {`
2419. `events.publish("putAdditionalObjects");`
2420. `for (var i = 0; i < additionalObjects.length; i++) {`
2421. `var obj = additionalObjects[i];`
2422. `newObjectDeferredBegin(obj.objId, true);`
2423. `out(obj.content);`
2424. `out("endobj");`
2425. `}`
2426. `events.publish("postPutAdditionalObjects");`
2427. `};`
2429. `var addFontToFontDictionary = function(font) {`
2430. `fontmap[font.fontName] = fontmap[font.fontName] || {};`
2431. `fontmap[font.fontName][font.fontStyle] = font.id;`
2432. `};`
2434. `var addFont = function(`
2435. `postScriptName,`
2436. `fontName,`
2437. `fontStyle,`
2438. `encoding,`
2439. `isStandardFont`
2440. `) {`
2441. `var font = {`
2442. `id: "F" + (Object.keys(fonts).length + 1).toString(10),`
2443. `postScriptName: postScriptName,`
2444. `fontName: fontName,`
2445. `fontStyle: fontStyle,`
2446. `encoding: encoding,`
2447. `isStandardFont: isStandardFont || false,`
2448. `metadata: {}`
2449. `};`
2451. `events.publish("addFont", {`
2452. `font: font,`
2453. `instance: this`
2454. `});`
2456. `fonts[font.id] = font;`
2457. `addFontToFontDictionary(font);`
2458. `return font.id;`
2459. `};`
2461. `var addFonts = function(arrayOfFonts) {`
2462. `for (var i = 0, l = standardFonts.length; i < l; i++) {`
2463. `var fontKey = addFont.call(`
2464. `this,`
2465. `arrayOfFonts[i][0],`
2466. `arrayOfFonts[i][1],`
2467. `arrayOfFonts[i][2],`
2468. `standardFonts[i][3],`
2469. `true`
2470. `);`
2472. `if (putOnlyUsedFonts === false) {`
2473. `usedFonts[fontKey] = true;`
2474. `}`
2475. `// adding aliases for standard fonts, this time matching the capitalization`
2476. `var parts = arrayOfFonts[i][0].split("-");`
2477. `addFontToFontDictionary({`
2478. `id: fontKey,`
2479. `fontName: parts[0],`
2480. `fontStyle: parts[1] || ""`
2481. `});`
2482. `}`
2483. `events.publish("addFonts", {`
2484. `fonts: fonts,`
2485. `dictionary: fontmap`
2486. `});`
2487. `};`
2489. `var SAFE = function __safeCall(fn) {`
2490. `fn.foo = function __safeCallWrapper() {`
2491. `try {`
2492. `return fn.apply(this, arguments);`
2493. `} catch (e) {`
2494. `var stack = e.stack || "";`
2495. `if (~stack.indexOf(" at ")) stack = stack.split(" at ")[1];`
2496. `var m =`
2497. `"Error in function " +`
2498. `stack.split("\n")[0].split("<")[0] +`
2499. `": " +`
2500. `e.message;`
2501. `if (globalObject.console) {`
2502. `globalObject.console.error(m, e);`
2503. `if (globalObject.alert) alert(m);`
2504. `} else {`
2505. `throw new Error(m);`
2506. `}`
2507. `}`
2508. `};`
2509. `fn.foo.bar = fn;`
2510. `return fn.foo;`
2511. `};`
2513. `var to8bitStream = function(text, flags) {`
2514. `/**`
2515. `* PDF 1.3 spec:`
2516. `* "For text strings encoded in Unicode, the first two bytes must be 254 followed by`
2517. `* 255, representing the Unicode byte order marker, U+FEFF. (This sequence conflicts`
2518. `* with the PDFDocEncoding character sequence thorn ydieresis, which is unlikely`
2519. `* to be a meaningful beginning of a word or phrase.) The remainder of the`
2520. `* string consists of Unicode character codes, according to the UTF-16 encoding`
2521. `* specified in the Unicode standard, version 2.0. Commonly used Unicode values`
2522. `* are represented as 2 bytes per character, with the high-order byte appearing first`
2523. `* in the string."`
2524. `*`
2525. `* In other words, if there are chars in a string with char code above 255, we`
2526. `* recode the string to UCS2 BE - string doubles in length and BOM is prepended.`
2527. `*`
2528. `* HOWEVER!`
2529. `* Actual *content* (body) text (as opposed to strings used in document properties etc)`
2530. `* does NOT expect BOM. There, it is treated as a literal GID (Glyph ID)`
2531. `*`
2532. `* Because of Adobe's focus on "you subset your fonts!" you are not supposed to have`
2533. `* a font that maps directly Unicode (UCS2 / UTF16BE) code to font GID, but you could`
2534. `* fudge it with "Identity-H" encoding and custom CIDtoGID map that mimics Unicode`
2535. `* code page. There, however, all characters in the stream are treated as GIDs,`
2536. `* including BOM, which is the reason we need to skip BOM in content text (i.e. that`
2537. `* that is tied to a font).`
2538. `*`
2539. `* To signal this "special" PDFEscape / to8bitStream handling mode,`
2540. `* API.text() function sets (unless you overwrite it with manual values`
2541. `* given to API.text(.., flags) )`
2542. `* flags.autoencode = true`
2543. `* flags.noBOM = true`
2544. `*`
2545. `* ===================================================================================`
2546. ``* `flags` properties relied upon:``
2547. `* .sourceEncoding = string with encoding label.`
2548. `* "Unicode" by default. = encoding of the incoming text.`
2549. `* pass some non-existing encoding name`
2550. `* (ex: 'Do not touch my strings! I know what I am doing.')`
2551. `* to make encoding code skip the encoding step.`
2552. `* .outputEncoding = Either valid PDF encoding name`
2553. `* (must be supported by jsPDF font metrics, otherwise no encoding)`
2554. `* or a JS object, where key = sourceCharCode, value = outputCharCode`
2555. `* missing keys will be treated as: sourceCharCode === outputCharCode`
2556. `* .noBOM`
2557. `* See comment higher above for explanation for why this is important`
2558. `* .autoencode`
2559. `* See comment higher above for explanation for why this is important`
2560. `*/`
2562. `var i,`
2563. `l,`
2564. `sourceEncoding,`
2565. `encodingBlock,`
2566. `outputEncoding,`
2567. `newtext,`
2568. `isUnicode,`
2569. `ch,`
2570. `bch;`
2572. `flags = flags || {};`
2573. `sourceEncoding = flags.sourceEncoding || "Unicode";`
2574. `outputEncoding = flags.outputEncoding;`
2576. `// This 'encoding' section relies on font metrics format`
2577. `// attached to font objects by, among others,`
2578. `// "Willow Systems' standard_font_metrics plugin"`
2579. `// see jspdf.plugin.standard_font_metrics.js for format`
2580. `// of the font.metadata.encoding Object.`
2581. `// It should be something like`
2582. `// .encoding = {'codePages':['WinANSI....'], 'WinANSI...':{code:code, ...}}`
2583. `// .widths = {0:width, code:width, ..., 'fof':divisor}`
2584. `// .kerning = {code:{previous_char_code:shift, ..., 'fof':-divisor},...}`
2585. `if (`
2586. `(flags.autoencode || outputEncoding) &&`
2587. `fonts[activeFontKey].metadata &&`
2588. `fonts[activeFontKey].metadata[sourceEncoding] &&`
2589. `fonts[activeFontKey].metadata[sourceEncoding].encoding`
2590. `) {`
2591. `encodingBlock = fonts[activeFontKey].metadata[sourceEncoding].encoding;`
2593. `// each font has default encoding. Some have it clearly defined.`
2594. `if (!outputEncoding && fonts[activeFontKey].encoding) {`
2595. `outputEncoding = fonts[activeFontKey].encoding;`
2596. `}`
2598. `// Hmmm, the above did not work? Let's try again, in different place.`
2599. `if (!outputEncoding && encodingBlock.codePages) {`
2600. `outputEncoding = encodingBlock.codePages[0]; // let's say, first one is the default`
2601. `}`
2603. `if (typeof outputEncoding === "string") {`
2604. `outputEncoding = encodingBlock[outputEncoding];`
2605. `}`
2606. `// we want output encoding to be a JS Object, where`
2607. `// key = sourceEncoding's character code and`
2608. `// value = outputEncoding's character code.`
2609. `if (outputEncoding) {`
2610. `isUnicode = false;`
2611. `newtext = [];`
2612. `for (i = 0, l = text.length; i < l; i++) {`
2613. `ch = outputEncoding[text.charCodeAt(i)];`
2614. `if (ch) {`
2615. `newtext.push(String.fromCharCode(ch));`
2616. `} else {`
2617. `newtext.push(text[i]);`
2618. `}`
2620. `// since we are looping over chars anyway, might as well`
2621. `// check for residual unicodeness`
2622. `if (newtext[i].charCodeAt(0) >> 8) {`
2623. `/* more than 255 */`
2624. `isUnicode = true;`
2625. `}`
2626. `}`
2627. `text = newtext.join("");`
2628. `}`
2629. `}`
2631. `i = text.length;`
2632. `// isUnicode may be set to false above. Hence the triple-equal to undefined`
2633. `while (isUnicode === undefined && i !== 0) {`
2634. `if (text.charCodeAt(i - 1) >> 8) {`
2635. `/* more than 255 */`
2636. `isUnicode = true;`
2637. `}`
2638. `i--;`
2639. `}`
2640. `if (!isUnicode) {`
2641. `return text;`
2642. `}`
2644. `newtext = flags.noBOM ? [] : [254, 255];`
2645. `for (i = 0, l = text.length; i < l; i++) {`
2646. `ch = text.charCodeAt(i);`
2647. `bch = ch >> 8; // divide by 256`
2648. `if (bch >> 8) {`
2649. `/* something left after dividing by 256 second time */`
2650. `throw new Error(`
2651. `"Character at position " +`
2652. `i +`
2653. `" of string '" +`
2654. `text +`
2655. `"' exceeds 16bits. Cannot be encoded into UCS-2 BE"`
2656. `);`
2657. `}`
2658. `newtext.push(bch);`
2659. `newtext.push(ch - (bch << 8));`
2660. `}`
2661. `return String.fromCharCode.apply(undefined, newtext);`
2662. `};`
2664. `var pdfEscape = (API.__private__.pdfEscape = API.pdfEscape = function(`
2665. `text,`
2666. `flags`
2667. `) {`
2668. `/**`
2669. `* Replace '/', '(', and ')' with pdf-safe versions`
2670. `*`
2671. `* Doing to8bitStream does NOT make this PDF display unicode text. For that`
2672. `* we also need to reference a unicode font and embed it - royal pain in the rear.`
2673. `*`
2674. `* There is still a benefit to to8bitStream - PDF simply cannot handle 16bit chars,`
2675. `* which JavaScript Strings are happy to provide. So, while we still cannot display`
2676. `* 2-byte characters property, at least CONDITIONALLY converting (entire string containing)`
2677. `* 16bit chars to (USC-2-BE) 2-bytes per char + BOM streams we ensure that entire PDF`
2678. `* is still parseable.`
2679. `* This will allow immediate support for unicode in document properties strings.`
2680. `*/`
2681. `return to8bitStream(text, flags)`
2682. `.replace(/\\/g, "\\\\")`
2683. `.replace(/\(/g, "\\(")`
2684. `.replace(/\)/g, "\\)");`
2685. `});`
2687. `var beginPage = (API.__private__.beginPage = function(format) {`
2688. `pages[++page] = [];`
2689. `pagesContext[page] = {`
2690. `objId: 0,`
2691. `contentsObjId: 0,`
2692. `userUnit: Number(userUnit),`
2693. `artBox: null,`
2694. `bleedBox: null,`
2695. `cropBox: null,`
2696. `trimBox: null,`
2697. `mediaBox: {`
2698. `bottomLeftX: 0,`
2699. `bottomLeftY: 0,`
2700. `topRightX: Number(format[0]),`
2701. `topRightY: Number(format[1])`
2702. `}`
2703. `};`
2704. `_setPage(page);`
2705. `setOutputDestination(pages[currentPage]);`
2706. `});`
2708. `var _addPage = function(parmFormat, parmOrientation) {`
2709. `var dimensions, width, height;`
2711. `orientation = parmOrientation || orientation;`
2713. `if (typeof parmFormat === "string") {`
2714. `dimensions = getPageFormat(parmFormat.toLowerCase());`
2715. `if (Array.isArray(dimensions)) {`
2716. `width = dimensions[0];`
2717. `height = dimensions[1];`
2718. `}`
2719. `}`
2721. `if (Array.isArray(parmFormat)) {`
2722. `width = parmFormat[0] * scaleFactor;`
2723. `height = parmFormat[1] * scaleFactor;`
2724. `}`
2726. `if (isNaN(width)) {`
2727. `width = format[0];`
2728. `height = format[1];`
2729. `}`
2731. `if (width > 14400 || height > 14400) {`
2732. `console.warn(`
2733. `"A page in a PDF can not be wider or taller than 14400 userUnit. jsPDF limits the width/height to 14400"`
2734. `);`
2735. `width = Math.min(14400, width);`
2736. `height = Math.min(14400, height);`
2737. `}`
2739. `format = [width, height];`
2741. `switch (orientation.substr(0, 1)) {`
2742. `case "l":`
2743. `if (height > width) {`
2744. `format = [height, width];`
2745. `}`
2746. `break;`
2747. `case "p":`
2748. `if (width > height) {`
2749. `format = [height, width];`
2750. `}`
2751. `break;`
2752. `}`
2754. `beginPage(format);`
2756. `// Set line width`
2757. `setLineWidth(lineWidth);`
2758. `// Set draw color`
2759. `out(strokeColor);`
2760. `// resurrecting non-default line caps, joins`
2761. `if (lineCapID !== 0) {`
2762. `out(lineCapID + " J");`
2763. `}`
2764. `if (lineJoinID !== 0) {`
2765. `out(lineJoinID + " j");`
2766. `}`
2767. `events.publish("addPage", {`
2768. `pageNumber: page`
2769. `});`
2770. `};`
2772. `var _deletePage = function(n) {`
2773. `if (n > 0 && n <= page) {`
2774. `pages.splice(n, 1);`
2775. `pagesContext.splice(n, 1);`
2776. `page--;`
2777. `if (currentPage > page) {`
2778. `currentPage = page;`
2779. `}`
2780. `this.setPage(currentPage);`
2781. `}`
2782. `};`
2784. `var _setPage = function(n) {`
2785. `if (n > 0 && n <= page) {`
2786. `currentPage = n;`
2787. `}`
2788. `};`
2790. `var getNumberOfPages = (API.__private__.getNumberOfPages = API.getNumberOfPages = function() {`
2791. `return pages.length - 1;`
2792. `});`
2794. `/**`
2795. `* Returns a document-specific font key - a label assigned to a`
2796. `* font name + font type combination at the time the font was added`
2797. `* to the font inventory.`
2798. `*`
2799. `* Font key is used as label for the desired font for a block of text`
2800. `* to be added to the PDF document stream.`
2801. `* @private`
2802. `* @function`
2803. `* @param fontName {string} can be undefined on "falthy" to indicate "use current"`
2804. `* @param fontStyle {string} can be undefined on "falthy" to indicate "use current"`
2805. `* @returns {string} Font key.`
2806. `* @ignore`
2807. `*/`
2808. `var getFont = function(fontName, fontStyle, options) {`
2809. `var key = undefined,`
2810. `fontNameLowerCase;`
2811. `options = options || {};`
2813. `fontName =`
2814. `fontName !== undefined ? fontName : fonts[activeFontKey].fontName;`
2815. `fontStyle =`
2816. `fontStyle !== undefined ? fontStyle : fonts[activeFontKey].fontStyle;`
2817. `fontNameLowerCase = fontName.toLowerCase();`
2819. `if (`
2820. `fontmap[fontNameLowerCase] !== undefined &&`
2821. `fontmap[fontNameLowerCase][fontStyle] !== undefined`
2822. `) {`
2823. `key = fontmap[fontNameLowerCase][fontStyle];`
2824. `} else if (`
2825. `fontmap[fontName] !== undefined &&`
2826. `fontmap[fontName][fontStyle] !== undefined`
2827. `) {`
2828. `key = fontmap[fontName][fontStyle];`
2829. `} else {`
2830. `if (options.disableWarning === false) {`
2831. `console.warn(`
2832. `"Unable to look up font label for font '" +`
2833. `fontName +`
2834. `"', '" +`
2835. `fontStyle +`
2836. `"'. Refer to getFontList() for available fonts."`
2837. `);`
2838. `}`
2839. `}`
2841. `if (!key && !options.noFallback) {`
2842. `key = fontmap["times"][fontStyle];`
2843. `if (key == null) {`
2844. `key = fontmap["times"]["normal"];`
2845. `}`
2846. `}`
2847. `return key;`
2848. `};`
2850. `var putInfo = (API.__private__.putInfo = function() {`
2851. `var objectId = newObject();`
2852. `var encryptor = function(data) {`
2853. `return data;`
2854. `};`
2855. `if (encryptionOptions !== null) {`
2856. `encryptor = encryption.encryptor(objectId, 0);`
2857. `}`
2858. `out("<<");`
2859. `out("/Producer (" + pdfEscape(encryptor("jsPDF " + jsPDF.version)) + ")");`
2860. `for (var key in documentProperties) {`
2861. `if (documentProperties.hasOwnProperty(key) && documentProperties[key]) {`
2862. `out(`
2863. `"/" +`
2864. `key.substr(0, 1).toUpperCase() +`
2865. `key.substr(1) +`
2866. `" (" +`
2867. `pdfEscape(encryptor(documentProperties[key])) +`
2868. `")"`
2869. `);`
2870. `}`
2871. `}`
2872. `out("/CreationDate (" + pdfEscape(encryptor(creationDate)) + ")");`
2873. `out(">>");`
2874. `out("endobj");`
2875. `});`
2877. `var putCatalog = (API.__private__.putCatalog = function(options) {`
2878. `options = options || {};`
2879. `var tmpRootDictionaryObjId =`
2880. `options.rootDictionaryObjId || rootDictionaryObjId;`
2881. `newObject();`
2882. `out("<<");`
2883. `out("/Type /Catalog");`
2884. `out("/Pages " + tmpRootDictionaryObjId + " 0 R");`
2885. `// PDF13ref Section 7.2.1`
2886. `if (!zoomMode) zoomMode = "fullwidth";`
2887. `switch (zoomMode) {`
2888. `case "fullwidth":`
2889. `out("/OpenAction [3 0 R /FitH null]");`
2890. `break;`
2891. `case "fullheight":`
2892. `out("/OpenAction [3 0 R /FitV null]");`
2893. `break;`
2894. `case "fullpage":`
2895. `out("/OpenAction [3 0 R /Fit]");`
2896. `break;`
2897. `case "original":`
2898. `out("/OpenAction [3 0 R /XYZ null null 1]");`
2899. `break;`
2900. `default:`
2901. `var pcn = "" + zoomMode;`
2902. `if (pcn.substr(pcn.length - 1) === "%")`
2903. `zoomMode = parseInt(zoomMode) / 100;`
2904. `if (typeof zoomMode === "number") {`
2905. `out("/OpenAction [3 0 R /XYZ null null " + f2(zoomMode) + "]");`
2906. `}`
2907. `}`
2908. `if (!layoutMode) layoutMode = "continuous";`
2909. `switch (layoutMode) {`
2910. `case "continuous":`
2911. `out("/PageLayout /OneColumn");`
2912. `break;`
2913. `case "single":`
2914. `out("/PageLayout /SinglePage");`
2915. `break;`
2916. `case "two":`
2917. `case "twoleft":`
2918. `out("/PageLayout /TwoColumnLeft");`
2919. `break;`
2920. `case "tworight":`
2921. `out("/PageLayout /TwoColumnRight");`
2922. `break;`
2923. `}`
2924. `if (pageMode) {`
2925. `/**`
2926. `* A name object specifying how the document should be displayed when opened:`
2927. `* UseNone : Neither document outline nor thumbnail images visible -- DEFAULT`
2928. `* UseOutlines : Document outline visible`
2929. `* UseThumbs : Thumbnail images visible`
2930. `* FullScreen : Full-screen mode, with no menu bar, window controls, or any other window visible`
2931. `*/`
2932. `out("/PageMode /" + pageMode);`
2933. `}`
2934. `events.publish("putCatalog");`
2935. `out(">>");`
2936. `out("endobj");`
2937. `});`
2939. `var putTrailer = (API.__private__.putTrailer = function() {`
2940. `out("trailer");`
2941. `out("<<");`
2942. `out("/Size " + (objectNumber + 1));`
2943. `// Root and Info must be the last and second last objects written respectively`
2944. `out("/Root " + objectNumber + " 0 R");`
2945. `out("/Info " + (objectNumber - 1) + " 0 R");`
2946. `if (encryptionOptions !== null) {`
2947. `out("/Encrypt " + encryption.oid + " 0 R");`
2948. `}`
2949. `out("/ID [ <" + fileId + "> <" + fileId + "> ]");`
2950. `out(">>");`
2951. `});`
2953. `var putHeader = (API.__private__.putHeader = function() {`
2954. `out("%PDF-" + pdfVersion);`
2955. `out("%\xBA\xDF\xAC\xE0");`
2956. `});`
2958. `var putXRef = (API.__private__.putXRef = function() {`
2959. `var p = "0000000000";`
2961. `out("xref");`
2962. `out("0 " + (objectNumber + 1));`
2963. `out("0000000000 65535 f ");`
2964. `for (var i = 1; i <= objectNumber; i++) {`
2965. `var offset = offsets[i];`
2966. `if (typeof offset === "function") {`
2967. `out((p + offsets[i]()).slice(-10) + " 00000 n ");`
2968. `} else {`
2969. `if (typeof offsets[i] !== "undefined") {`
2970. `out((p + offsets[i]).slice(-10) + " 00000 n ");`
2971. `} else {`
2972. `out("0000000000 00000 n ");`
2973. `}`
2974. `}`
2975. `}`
2976. `});`
2978. `var buildDocument = (API.__private__.buildDocument = function() {`
2979. `resetDocument();`
2980. `setOutputDestination(content);`
2982. `events.publish("buildDocument");`
2984. `putHeader();`
2985. `putPages();`
2986. `putAdditionalObjects();`
2987. `putResources();`
2988. `if (encryptionOptions !== null) putEncryptionDict();`
2989. `putInfo();`
2990. `putCatalog();`
2992. `var offsetOfXRef = contentLength;`
2993. `putXRef();`
2994. `putTrailer();`
2995. `out("startxref");`
2996. `out("" + offsetOfXRef);`
2997. `out("%%EOF");`
2999. `setOutputDestination(pages[currentPage]);`
3001. `return content.join("\n");`
3002. `});`
3004. `var getBlob = (API.__private__.getBlob = function(data) {`
3005. `return new Blob([getArrayBuffer(data)], {`
3006. `type: "application/pdf"`
3007. `});`
3008. `});`
3010. `/**`
3011. `* Generates the PDF document.`
3012. `*`
3013. ``* If `type` argument is undefined, output is raw body of resulting PDF returned as a string.``
3014. `*`
3015. `* @param {string} type A string identifying one of the possible output types. `
3016. `* Possible values are: `
3017. `* 'arraybuffer' -> (ArrayBuffer) `
3018. `* 'blob' -> (Blob) `
3019. `* 'bloburi'/'bloburl' -> (string) `
3020. `* 'datauristring'/'dataurlstring' -> (string) `
3021. `* 'datauri'/'dataurl' -> (undefined) -> change location to generated datauristring/dataurlstring `
3022. `* 'dataurlnewwindow' -> (window | null | undefined) throws error if global isn't a window object(node) `
3023. `* 'pdfobjectnewwindow' -> (window | null) throws error if global isn't a window object(node) `
3024. `* 'pdfjsnewwindow' -> (wind | null)`
3025. `* @param {Object|string} options An object providing some additional signalling to PDF generator. `
3026. `* Possible options are 'filename'. `
3027. `* A string can be passed instead of {filename:string} and defaults to 'generated.pdf'`
3028. `* @function`
3029. `* @instance`
3030. `* @returns {string|window|ArrayBuffer|Blob|jsPDF|null|undefined}`
3031. `* @memberof jsPDF#`
3032. `* @name output`
3033. `*/`
3034. `var output = (API.output = API.__private__.output = SAFE(function output(`
3035. `type,`
3036. `options`
3037. `) {`
3038. `options = options || {};`
3040. `if (typeof options === "string") {`
3041. `options = {`
3042. `filename: options`
3043. `};`
3044. `} else {`
3045. `options.filename = options.filename || "generated.pdf";`
3046. `}`
3048. `switch (type) {`
3049. `case undefined:`
3050. `return buildDocument();`
3051. `case "save":`
3052. `API.save(options.filename);`
3053. `break;`
3054. `case "arraybuffer":`
3055. `return getArrayBuffer(buildDocument());`
3056. `case "blob":`
3057. `return getBlob(buildDocument());`
3058. `case "bloburi":`
3059. `case "bloburl":`
3060. `// Developer is responsible of calling revokeObjectURL`
3061. `if (`
3062. `typeof globalObject.URL !== "undefined" &&`
3063. `typeof globalObject.URL.createObjectURL === "function"`
3064. `) {`
3065. `return (`
3066. `(globalObject.URL &&`
3067. `globalObject.URL.createObjectURL(getBlob(buildDocument()))) ||`
3068. `void 0`
3069. `);`
3070. `} else {`
3071. `console.warn(`
3072. `"bloburl is not supported by your system, because URL.createObjectURL is not supported by your browser."`
3073. `);`
3074. `}`
3075. `break;`
3076. `case "datauristring":`
3077. `case "dataurlstring":`
3078. `var dataURI = "";`
3079. `var pdfDocument = buildDocument();`
3080. `try {`
3081. `dataURI = btoa(pdfDocument);`
3082. `} catch (e) {`
3083. `dataURI = btoa(unescape(encodeURIComponent(pdfDocument)));`
3084. `}`
3085. `return (`
3086. `"data:application/pdf;filename=" +`
3087. `options.filename +`
3088. `";base64," +`
3089. `dataURI`
3090. `);`
3091. `case "pdfobjectnewwindow":`
3092. `if (`
3093. `Object.prototype.toString.call(globalObject) === "[object Window]"`
3094. `) {`
3095. `var pdfObjectUrl =`
3096. `"https://cdnjs.cloudflare.com/ajax/libs/pdfobject/2.1.1/pdfobject.min.js";`
3097. `var integrity =`
3098. `' integrity="sha512-4ze/a9/4jqu+tX9dfOqJYSvyYd5M6qum/3HpCLr+/Jqf0whc37VUbkpNGHR7/8pSnCFw47T1fmIpwBV7UySh3g==" crossorigin="anonymous"';`
3100. `if (options.pdfObjectUrl) {`
3101. `pdfObjectUrl = options.pdfObjectUrl;`
3102. `integrity = "";`
3103. `}`
3105. `var htmlForNewWindow =`
3106. `"" +`
3107. `'";`
3116. `var nW = globalObject.open();`
3118. `if (nW !== null) {`
3119. `nW.document.write(htmlForNewWindow);`
3120. `}`
3121. `return nW;`
3122. `} else {`
3123. `throw new Error(`
3124. `"The option pdfobjectnewwindow just works in a browser-environment."`
3125. `);`
3126. `}`
3127. `case "pdfjsnewwindow":`
3128. `if (`
3129. `Object.prototype.toString.call(globalObject) === "[object Window]"`
3130. `) {`
3131. `var pdfJsUrl = options.pdfJsUrl || "examples/PDF.js/web/viewer.html";`
3132. `var htmlForPDFjsNewWindow =`
3133. `"" +`
3134. `"" +`
3135. `'' +`
3140. `"";`
3141. `var PDFjsNewWindow = globalObject.open();`
3143. `if (PDFjsNewWindow !== null) {`
3144. `PDFjsNewWindow.document.write(htmlForPDFjsNewWindow);`
3145. `var scope = this;`
3146. `PDFjsNewWindow.document.documentElement.querySelector(`
3147. `"#pdfViewer"`
3148. `).onload = function() {`
3149. `PDFjsNewWindow.document.title = options.filename;`
3150. `PDFjsNewWindow.document.documentElement`
3151. `.querySelector("#pdfViewer")`
3152. `.contentWindow.PDFViewerApplication.open(`
3153. `scope.output("bloburl")`
3154. `);`
3155. `};`
3156. `}`
3157. `return PDFjsNewWindow;`
3158. `} else {`
3159. `throw new Error(`
3160. `"The option pdfjsnewwindow just works in a browser-environment."`
3161. `);`
3162. `}`
3163. `case "dataurlnewwindow":`
3164. `if (`
3165. `Object.prototype.toString.call(globalObject) === "[object Window]"`
3166. `) {`
3167. `var htmlForDataURLNewWindow =`
3168. `"" +`
3169. `"" +`
3170. `"" +`
3171. `'' +`
3174. `"";`
3175. `var dataURLNewWindow = globalObject.open();`
3176. `if (dataURLNewWindow !== null) {`
3177. `dataURLNewWindow.document.write(htmlForDataURLNewWindow);`
3178. `dataURLNewWindow.document.title = options.filename;`
3179. `}`
3180. `if (dataURLNewWindow || typeof safari === "undefined")`
3181. `return dataURLNewWindow;`
3182. `} else {`
3183. `throw new Error(`
3184. `"The option dataurlnewwindow just works in a browser-environment."`
3185. `);`
3186. `}`
3187. `break;`
3188. `case "datauri":`
3189. `case "dataurl":`
3190. `return (globalObject.document.location.href = this.output(`
3191. `"datauristring",`
3192. `options`
3193. `));`
3194. `default:`
3195. `return null;`
3196. `}`
3197. `}));`
3199. `/**`
3200. `* Used to see if a supplied hotfix was requested when the pdf instance was created.`
3201. `* @param {string} hotfixName - The name of the hotfix to check.`
3202. `* @returns {boolean}`
3203. `*/`
3204. `var hasHotfix = function(hotfixName) {`
3205. `return (`
3206. `Array.isArray(hotfixes) === true && hotfixes.indexOf(hotfixName) > -1`
3207. `);`
3208. `};`
3210. `switch (unit) {`
3211. `case "pt":`
3212. `scaleFactor = 1;`
3213. `break;`
3214. `case "mm":`
3215. `scaleFactor = 72 / 25.4;`
3216. `break;`
3217. `case "cm":`
3218. `scaleFactor = 72 / 2.54;`
3219. `break;`
3220. `case "in":`
3221. `scaleFactor = 72;`
3222. `break;`
3223. `case "px":`
3224. `if (hasHotfix("px_scaling") == true) {`
3225. `scaleFactor = 72 / 96;`
3226. `} else {`
3227. `scaleFactor = 96 / 72;`
3228. `}`
3229. `break;`
3230. `case "pc":`
3231. `scaleFactor = 12;`
3232. `break;`
3233. `case "em":`
3234. `scaleFactor = 12;`
3235. `break;`
3236. `case "ex":`
3237. `scaleFactor = 6;`
3238. `break;`
3239. `default:`
3240. `if (typeof unit === "number") {`
3241. `scaleFactor = unit;`
3242. `} else {`
3243. `throw new Error("Invalid unit: " + unit);`
3244. `}`
3245. `}`
3247. `var encryption = null;`
3248. `setCreationDate();`
3249. `setFileId();`
3251. `var getEncryptor = function(objectId) {`
3252. `if (encryptionOptions !== null) {`
3253. `return encryption.encryptor(objectId, 0);`
3254. `}`
3255. `return function(data) {`
3256. `return data;`
3257. `};`
3258. `};`
3260. `//---------------------------------------`
3261. `// Public API`
3263. `var getPageInfo = (API.__private__.getPageInfo = API.getPageInfo = function(`
3264. `pageNumberOneBased`
3265. `) {`
3266. `if (isNaN(pageNumberOneBased) || pageNumberOneBased % 1 !== 0) {`
3267. `throw new Error("Invalid argument passed to jsPDF.getPageInfo");`
3268. `}`
3269. `var objId = pagesContext[pageNumberOneBased].objId;`
3270. `return {`
3271. `objId: objId,`
3272. `pageNumber: pageNumberOneBased,`
3273. `pageContext: pagesContext[pageNumberOneBased]`
3274. `};`
3275. `});`
3277. `var getPageInfoByObjId = (API.__private__.getPageInfoByObjId = function(`
3278. `objId`
3279. `) {`
3280. `if (isNaN(objId) || objId % 1 !== 0) {`
3281. `throw new Error("Invalid argument passed to jsPDF.getPageInfoByObjId");`
3282. `}`
3283. `for (var pageNumber in pagesContext) {`
3284. `if (pagesContext[pageNumber].objId === objId) {`
3285. `break;`
3286. `}`
3287. `}`
3288. `return getPageInfo(pageNumber);`
3289. `});`
3291. `var getCurrentPageInfo = (API.__private__.getCurrentPageInfo = API.getCurrentPageInfo = function() {`
3292. `return {`
3293. `objId: pagesContext[currentPage].objId,`
3294. `pageNumber: currentPage,`
3295. `pageContext: pagesContext[currentPage]`
3296. `};`
3297. `});`
3299. `/**`
3300. `* Adds (and transfers the focus to) new page to the PDF document.`
3301. `* @param format {String/Array} The format of the new page. Can be:
a0 - a10
b0 - b10
c0 - c10
dl
letter
government-letter
legal
junior-legal
ledger
tabloid
credit-card
`
3302. `* Default is "a4". If you want to use your own format just pass instead of one of the above predefined formats the size as an number-array, e.g. [595.28, 841.89]`
3303. `* @param orientation {string} Orientation of the new page. Possible values are "portrait" or "landscape" (or shortcuts "p" (Default), "l").`
3304. `* @function`
3305. `* @instance`
3306. `* @returns {jsPDF}`
3307. `*`
3308. `* @memberof jsPDF#`
3309. `* @name addPage`
3310. `*/`
3311. `API.addPage = function() {`
3312. `_addPage.apply(this, arguments);`
3313. `return this;`
3314. `};`
3315. `/**`
3316. `* Adds (and transfers the focus to) new page to the PDF document.`
3317. `* @function`
3318. `* @instance`
3319. `* @returns {jsPDF}`
3320. `*`
3321. `* @memberof jsPDF#`
3322. `* @name setPage`
3323. `* @param {number} page Switch the active page to the page number specified (indexed starting at 1).`
3324. `* @example`
3325. `* doc = jsPDF()`
3326. `* doc.addPage()`
3327. `* doc.addPage()`
3328. `* doc.text('I am on page 3', 10, 10)`
3329. `* doc.setPage(1)`
3330. `* doc.text('I am on page 1', 10, 10)`
3331. `*/`
3332. `API.setPage = function() {`
3333. `_setPage.apply(this, arguments);`
3334. `setOutputDestination.call(this, pages[currentPage]);`
3335. `return this;`
3336. `};`
3338. `/**`
3339. `* @name insertPage`
3340. `* @memberof jsPDF#`
3341. `*`
3342. `* @function`
3343. `* @instance`
3344. `* @param {Object} beforePage`
3345. `* @returns {jsPDF}`
3346. `*/`
3347. `API.insertPage = function(beforePage) {`
3348. `this.addPage();`
3349. `this.movePage(currentPage, beforePage);`
3350. `return this;`
3351. `};`
3353. `/**`
3354. `* @name movePage`
3355. `* @memberof jsPDF#`
3356. `* @function`
3357. `* @instance`
3358. `* @param {number} targetPage`
3359. `* @param {number} beforePage`
3360. `* @returns {jsPDF}`
3361. `*/`
3362. `API.movePage = function(targetPage, beforePage) {`
3363. `var tmpPages, tmpPagesContext;`
3364. `if (targetPage > beforePage) {`
3365. `tmpPages = pages[targetPage];`
3366. `tmpPagesContext = pagesContext[targetPage];`
3367. `for (var i = targetPage; i > beforePage; i--) {`
3368. `pages[i] = pages[i - 1];`
3369. `pagesContext[i] = pagesContext[i - 1];`
3370. `}`
3371. `pages[beforePage] = tmpPages;`
3372. `pagesContext[beforePage] = tmpPagesContext;`
3373. `this.setPage(beforePage);`
3374. `} else if (targetPage < beforePage) {`
3375. `tmpPages = pages[targetPage];`
3376. `tmpPagesContext = pagesContext[targetPage];`
3377. `for (var j = targetPage; j < beforePage; j++) {`
3378. `pages[j] = pages[j + 1];`
3379. `pagesContext[j] = pagesContext[j + 1];`
3380. `}`
3381. `pages[beforePage] = tmpPages;`
3382. `pagesContext[beforePage] = tmpPagesContext;`
3383. `this.setPage(beforePage);`
3384. `}`
3385. `return this;`
3386. `};`
3388. `/**`
3389. `* Deletes a page from the PDF.`
3390. `* @name deletePage`
3391. `* @memberof jsPDF#`
3392. `* @function`
3393. `* @param {number} targetPage`
3394. `* @instance`
3395. `* @returns {jsPDF}`
3396. `*/`
3397. `API.deletePage = function() {`
3398. `_deletePage.apply(this, arguments);`
3399. `return this;`
3400. `};`
3402. `/**`
3403. `* Adds text to page. Supports adding multiline text when 'text' argument is an Array of Strings.`
3404. `*`
3405. `* @function`
3406. `* @instance`
3407. `* @param {String|Array} text String or array of strings to be added to the page. Each line is shifted one line down per font, spacing settings declared before this call.`
3408. `* @param {number} x Coordinate (in units declared at inception of PDF document) against left edge of the page.`
3409. `* @param {number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page.`
3410. `* @param {Object} [options] - Collection of settings signaling how the text must be encoded.`
3411. `* @param {string} [options.align=left] - The alignment of the text, possible values: left, center, right, justify.`
3412. `* @param {string} [options.baseline=alphabetic] - Sets text baseline used when drawing the text, possible values: alphabetic, ideographic, bottom, top, middle, hanging`
3413. `* @param {number|Matrix} [options.angle=0] - Rotate the text clockwise or counterclockwise. Expects the angle in degree.`
3414. `* @param {number} [options.rotationDirection=1] - Direction of the rotation. 0 = clockwise, 1 = counterclockwise.`
3415. `* @param {number} [options.charSpace=0] - The space between each letter.`
3416. `* @param {number} [options.horizontalScale=1] - Horizontal scale of the text as a factor of the regular size.`
3417. `* @param {number} [options.lineHeightFactor=1.15] - The lineheight of each line.`
3418. `* @param {Object} [options.flags] - Flags for to8bitStream.`
3419. `* @param {boolean} [options.flags.noBOM=true] - Don't add BOM to Unicode-text.`
3420. `* @param {boolean} [options.flags.autoencode=true] - Autoencode the Text.`
3421. `* @param {number} [options.maxWidth=0] - Split the text by given width, 0 = no split.`
3422. `* @param {string} [options.renderingMode=fill] - Set how the text should be rendered, possible values: fill, stroke, fillThenStroke, invisible, fillAndAddForClipping, strokeAndAddPathForClipping, fillThenStrokeAndAddToPathForClipping, addToPathForClipping.`
3423. `* @param {boolean} [options.isInputVisual] - Option for the BidiEngine`
3424. `* @param {boolean} [options.isOutputVisual] - Option for the BidiEngine`
3425. `* @param {boolean} [options.isInputRtl] - Option for the BidiEngine`
3426. `* @param {boolean} [options.isOutputRtl] - Option for the BidiEngine`
3427. `* @param {boolean} [options.isSymmetricSwapping] - Option for the BidiEngine`
3428. `* @param {number|Matrix} transform If transform is a number the text will be rotated by this value around the anchor set by x and y.`
3429. `*`
3430. `* If it is a Matrix, this matrix gets directly applied to the text, which allows shearing`
3431. `* effects etc.; the x and y offsets are then applied AFTER the coordinate system has been established by this`
3432. `* matrix. This means passing a rotation matrix that is equivalent to some rotation angle will in general yield a`
3433. `* DIFFERENT result. A matrix is only allowed in "advanced" API mode.`
3434. `* @returns {jsPDF}`
3435. `* @memberof jsPDF#`
3436. `* @name text`
3437. `*/`
3438. `API.__private__.text = API.text = function(text, x, y, options, transform) {`
3439. `/*`
3440. `* Inserts something like this into PDF`
3441. `* BT`
3442. `* /F1 16 Tf % Font name + size`
3443. `* 16 TL % How many units down for next line in multiline text`
3444. `* 0 g % color`
3445. `* 28.35 813.54 Td % position`
3446. `* (line one) Tj`
3447. `* T* (line two) Tj`
3448. `* T* (line three) Tj`
3449. `* ET`
3450. `*/`
3451. `options = options || {};`
3452. `var scope = options.scope || this;`
3453. `var payload, da, angle, align, charSpace, maxWidth, flags, horizontalScale;`
3455. `// Pre-August-2012 the order of arguments was function(x, y, text, flags)`
3456. `// in effort to make all calls have similar signature like`
3457. `// function(data, coordinates... , miscellaneous)`
3458. `// this method had its args flipped.`
3459. `// code below allows backward compatibility with old arg order.`
3460. `if (`
3461. `typeof text === "number" &&`
3462. `typeof x === "number" &&`
3463. `(typeof y === "string" || Array.isArray(y))`
3464. `) {`
3465. `var tmp = y;`
3466. `y = x;`
3467. `x = text;`
3468. `text = tmp;`
3469. `}`
3471. `var transformationMatrix;`
3473. `if (arguments[3] instanceof Matrix === false) {`
3474. `flags = arguments[3];`
3475. `angle = arguments[4];`
3476. `align = arguments[5];`
3478. `if (typeof flags !== "object" || flags === null) {`
3479. `if (typeof angle === "string") {`
3480. `align = angle;`
3481. `angle = null;`
3482. `}`
3483. `if (typeof flags === "string") {`
3484. `align = flags;`
3485. `flags = null;`
3486. `}`
3487. `if (typeof flags === "number") {`
3488. `angle = flags;`
3489. `flags = null;`
3490. `}`
3491. `options = {`
3492. `flags: flags,`
3493. `angle: angle,`
3494. `align: align`
3495. `};`
3496. `}`
3497. `} else {`
3498. `advancedApiModeTrap(`
3499. `"The transform parameter of text() with a Matrix value"`
3500. `);`
3501. `transformationMatrix = transform;`
3502. `}`
3504. `if (isNaN(x) || isNaN(y) || typeof text === "undefined" || text === null) {`
3505. `throw new Error("Invalid arguments passed to jsPDF.text");`
3506. `}`
3508. `if (text.length === 0) {`
3509. `return scope;`
3510. `}`
3512. `var xtra = "";`
3513. `var isHex = false;`
3514. `var lineHeight =`
3515. `typeof options.lineHeightFactor === "number"`
3516. `? options.lineHeightFactor`
3517. `: lineHeightFactor;`
3518. `var scaleFactor = scope.internal.scaleFactor;`
3520. `function ESC(s) {`
3521. `s = s.split("\t").join(Array(options.TabLen || 9).join(" "));`
3522. `return pdfEscape(s, flags);`
3523. `}`
3525. `function transformTextToSpecialArray(text) {`
3526. `//we don't want to destroy original text array, so cloning it`
3527. `var sa = text.concat();`
3528. `var da = [];`
3529. `var len = sa.length;`
3530. `var curDa;`
3531. `//we do array.join('text that must not be PDFescaped")`
3532. `//thus, pdfEscape each component separately`
3533. `while (len--) {`
3534. `curDa = sa.shift();`
3535. `if (typeof curDa === "string") {`
3536. `da.push(curDa);`
3537. `} else {`
3538. `if (`
3539. `Array.isArray(text) &&`
3540. `(curDa.length === 1 ||`
3541. `(curDa[1] === undefined && curDa[2] === undefined))`
3542. `) {`
3543. `da.push(curDa[0]);`
3544. `} else {`
3545. `da.push([curDa[0], curDa[1], curDa[2]]);`
3546. `}`
3547. `}`
3548. `}`
3549. `return da;`
3550. `}`
3552. `function processTextByFunction(text, processingFunction) {`
3553. `var result;`
3554. `if (typeof text === "string") {`
3555. `result = processingFunction(text)[0];`
3556. `} else if (Array.isArray(text)) {`
3557. `//we don't want to destroy original text array, so cloning it`
3558. `var sa = text.concat();`
3559. `var da = [];`
3560. `var len = sa.length;`
3561. `var curDa;`
3562. `var tmpResult;`
3563. `//we do array.join('text that must not be PDFescaped")`
3564. `//thus, pdfEscape each component separately`
3565. `while (len--) {`
3566. `curDa = sa.shift();`
3567. `if (typeof curDa === "string") {`
3568. `da.push(processingFunction(curDa)[0]);`
3569. `} else if (Array.isArray(curDa) && typeof curDa[0] === "string") {`
3570. `tmpResult = processingFunction(curDa[0], curDa[1], curDa[2]);`
3571. `da.push([tmpResult[0], tmpResult[1], tmpResult[2]]);`
3572. `}`
3573. `}`
3574. `result = da;`
3575. `}`
3576. `return result;`
3577. `}`
3579. `//Check if text is of type String`
3580. `var textIsOfTypeString = false;`
3581. `var tmpTextIsOfTypeString = true;`
3583. `if (typeof text === "string") {`
3584. `textIsOfTypeString = true;`
3585. `} else if (Array.isArray(text)) {`
3586. `//we don't want to destroy original text array, so cloning it`
3587. `var sa = text.concat();`
3588. `da = [];`
3589. `var len = sa.length;`
3590. `var curDa;`
3591. `//we do array.join('text that must not be PDFescaped")`
3592. `//thus, pdfEscape each component separately`
3593. `while (len--) {`
3594. `curDa = sa.shift();`
3595. `if (`
3596. `typeof curDa !== "string" ||`
3597. `(Array.isArray(curDa) && typeof curDa[0] !== "string")`
3598. `) {`
3599. `tmpTextIsOfTypeString = false;`
3600. `}`
3601. `}`
3602. `textIsOfTypeString = tmpTextIsOfTypeString;`
3603. `}`
3604. `if (textIsOfTypeString === false) {`
3605. `throw new Error(`
3606. `'Type of text must be string or Array. "' +`
3607. `text +`
3608. `'" is not recognized.'`
3609. `);`
3610. `}`
3612. `//If there are any newlines in text, we assume`
3613. `//the user wanted to print multiple lines, so break the`
3614. `//text up into an array. If the text is already an array,`
3615. `//we assume the user knows what they are doing.`
3616. `//Convert text into an array anyway to simplify`
3617. `//later code.`
3619. `if (typeof text === "string") {`
3620. `if (text.match(/[\r?\n]/)) {`
3621. `text = text.split(/\r\n|\r|\n/g);`
3622. `} else {`
3623. `text = [text];`
3624. `}`
3625. `}`
3627. `//baseline`
3628. `var height = activeFontSize / scope.internal.scaleFactor;`
3629. `var descent = height * (lineHeight - 1);`
3631. `switch (options.baseline) {`
3632. `case "bottom":`
3633. `y -= descent;`
3634. `break;`
3635. `case "top":`
3636. `y += height - descent;`
3637. `break;`
3638. `case "hanging":`
3639. `y += height - 2 * descent;`
3640. `break;`
3641. `case "middle":`
3642. `y += height / 2 - descent;`
3643. `break;`
3644. `case "ideographic":`
3645. `case "alphabetic":`
3646. `default:`
3647. `// do nothing, everything is fine`
3648. `break;`
3649. `}`
3651. `//multiline`
3652. `maxWidth = options.maxWidth || 0;`
3654. `if (maxWidth > 0) {`
3655. `if (typeof text === "string") {`
3656. `text = scope.splitTextToSize(text, maxWidth);`
3657. `} else if (Object.prototype.toString.call(text) === "[object Array]") {`
3658. `text = text.reduce(function(acc, textLine) {`
3659. `return acc.concat(scope.splitTextToSize(textLine, maxWidth));`
3660. `}, []);`
3661. `}`
3662. `}`
3664. `//creating Payload-Object to make text byRef`
3665. `payload = {`
3666. `text: text,`
3667. `x: x,`
3668. `y: y,`
3669. `options: options,`
3670. `mutex: {`
3671. `pdfEscape: pdfEscape,`
3672. `activeFontKey: activeFontKey,`
3673. `fonts: fonts,`
3674. `activeFontSize: activeFontSize`
3675. `}`
3676. `};`
3677. `events.publish("preProcessText", payload);`
3679. `text = payload.text;`
3680. `options = payload.options;`
3682. `//angle`
3683. `angle = options.angle;`
3685. `if (`
3686. `transformationMatrix instanceof Matrix === false &&`
3687. `angle &&`
3688. `typeof angle === "number"`
3689. `) {`
3690. `angle *= Math.PI / 180;`
3692. `if (options.rotationDirection === 0) {`
3693. `angle = -angle;`
3694. `}`
3696. `if (apiMode === ApiMode.ADVANCED) {`
3697. `angle = -angle;`
3698. `}`
3700. `var c = Math.cos(angle);`
3701. `var s = Math.sin(angle);`
3702. `transformationMatrix = new Matrix(c, s, -s, c, 0, 0);`
3703. `} else if (angle && angle instanceof Matrix) {`
3704. `transformationMatrix = angle;`
3705. `}`
3707. `if (apiMode === ApiMode.ADVANCED && !transformationMatrix) {`
3708. `transformationMatrix = identityMatrix;`
3709. `}`
3711. `//charSpace`
3713. `charSpace = options.charSpace || activeCharSpace;`
3715. `if (typeof charSpace !== "undefined") {`
3716. `xtra += hpf(scale(charSpace)) + " Tc\n";`
3717. `this.setCharSpace(this.getCharSpace() || 0);`
3718. `}`
3720. `horizontalScale = options.horizontalScale;`
3721. `if (typeof horizontalScale !== "undefined") {`
3722. `xtra += hpf(horizontalScale * 100) + " Tz\n";`
3723. `}`
3725. `//lang`
3727. `var lang = options.lang;`
3729. `if (lang) {`
3730. `// xtra += "/Lang (" + lang +")\n";`
3731. `}`
3733. `//renderingMode`
3734. `var renderingMode = -1;`
3735. `var parmRenderingMode =`
3736. `typeof options.renderingMode !== "undefined"`
3737. `? options.renderingMode`
3738. `: options.stroke;`
3739. `var pageContext = scope.internal.getCurrentPageInfo().pageContext;`
3741. `switch (parmRenderingMode) {`
3742. `case 0:`
3743. `case false:`
3744. `case "fill":`
3745. `renderingMode = 0;`
3746. `break;`
3747. `case 1:`
3748. `case true:`
3749. `case "stroke":`
3750. `renderingMode = 1;`
3751. `break;`
3752. `case 2:`
3753. `case "fillThenStroke":`
3754. `renderingMode = 2;`
3755. `break;`
3756. `case 3:`
3757. `case "invisible":`
3758. `renderingMode = 3;`
3759. `break;`
3760. `case 4:`
3761. `case "fillAndAddForClipping":`
3762. `renderingMode = 4;`
3763. `break;`
3764. `case 5:`
3765. `case "strokeAndAddPathForClipping":`
3766. `renderingMode = 5;`
3767. `break;`
3768. `case 6:`
3769. `case "fillThenStrokeAndAddToPathForClipping":`
3770. `renderingMode = 6;`
3771. `break;`
3772. `case 7:`
3773. `case "addToPathForClipping":`
3774. `renderingMode = 7;`
3775. `break;`
3776. `}`
3778. `var usedRenderingMode =`
3779. `typeof pageContext.usedRenderingMode !== "undefined"`
3780. `? pageContext.usedRenderingMode`
3781. `: -1;`
3783. `//if the coder wrote it explicitly to use a specific`
3784. `//renderingMode, then use it`
3785. `if (renderingMode !== -1) {`
3786. `xtra += renderingMode + " Tr\n";`
3787. `//otherwise check if we used the rendering Mode already`
3788. `//if so then set the rendering Mode...`
3789. `} else if (usedRenderingMode !== -1) {`
3790. `xtra += "0 Tr\n";`
3791. `}`
3793. `if (renderingMode !== -1) {`
3794. `pageContext.usedRenderingMode = renderingMode;`
3795. `}`
3797. `//align`
3798. `align = options.align || "left";`
3799. `var leading = activeFontSize * lineHeight;`
3800. `var pageWidth = scope.internal.pageSize.getWidth();`
3801. `var activeFont = fonts[activeFontKey];`
3802. `charSpace = options.charSpace || activeCharSpace;`
3803. `maxWidth = options.maxWidth || 0;`
3805. `var lineWidths;`
3806. `flags = Object.assign({ autoencode: true, noBOM: true }, options.flags);`
3808. `var wordSpacingPerLine = [];`
3809. `var findWidth = function(v) {`
3810. `return (`
3811. `(scope.getStringUnitWidth(v, {`
3812. `font: activeFont,`
3813. `charSpace: charSpace,`
3814. `fontSize: activeFontSize,`
3815. `doKerning: false`
3816. `}) *`
3817. `activeFontSize) /`
3818. `scaleFactor`
3819. `);`
3820. `};`
3821. `if (Object.prototype.toString.call(text) === "[object Array]") {`
3822. `da = transformTextToSpecialArray(text);`
3823. `var newY;`
3824. `if (align !== "left") {`
3825. `lineWidths = da.map(findWidth);`
3826. `}`
3827. `//The first line uses the "main" Td setting,`
3828. `//and the subsequent lines are offset by the`
3829. `//previous line's x coordinate.`
3830. `var prevWidth = 0;`
3831. `var newX;`
3832. `if (align === "right") {`
3833. `//The passed in x coordinate defines the`
3834. `//rightmost point of the text.`
3835. `x -= lineWidths[0];`
3836. `text = [];`
3837. `len = da.length;`
3838. `for (var i = 0; i < len; i++) {`
3839. `if (i === 0) {`
3840. `newX = getHorizontalCoordinate(x);`
3841. `newY = getVerticalCoordinate(y);`
3842. `} else {`
3843. `newX = scale(prevWidth - lineWidths[i]);`
3844. `newY = -leading;`
3845. `}`
3846. `text.push([da[i], newX, newY]);`
3847. `prevWidth = lineWidths[i];`
3848. `}`
3849. `} else if (align === "center") {`
3850. `//The passed in x coordinate defines`
3851. `//the center point.`
3852. `x -= lineWidths[0] / 2;`
3853. `text = [];`
3854. `len = da.length;`
3855. `for (var j = 0; j < len; j++) {`
3856. `if (j === 0) {`
3857. `newX = getHorizontalCoordinate(x);`
3858. `newY = getVerticalCoordinate(y);`
3859. `} else {`
3860. `newX = scale((prevWidth - lineWidths[j]) / 2);`
3861. `newY = -leading;`
3862. `}`
3863. `text.push([da[j], newX, newY]);`
3864. `prevWidth = lineWidths[j];`
3865. `}`
3866. `} else if (align === "left") {`
3867. `text = [];`
3868. `len = da.length;`
3869. `for (var h = 0; h < len; h++) {`
3870. `text.push(da[h]);`
3871. `}`
3872. `} else if (align === "justify" && activeFont.encoding === "Identity-H") {`
3873. `// when using unicode fonts, wordSpacePerLine does not apply`
3874. `text = [];`
3875. `len = da.length;`
3876. `maxWidth = maxWidth !== 0 ? maxWidth : pageWidth;`
3877. `let backToStartX = 0;`
3878. `for (var l = 0; l < len; l++) {`
3879. `newY = l === 0 ? getVerticalCoordinate(y) : -leading;`
3880. `newX = l === 0 ? getHorizontalCoordinate(x) : backToStartX;`
3881. `if (l < len - 1) {`
3882. `let spacing = scale(`
3883. `(maxWidth - lineWidths[l]) / (da[l].split(" ").length - 1)`
3884. `);`
3885. `let words = da[l].split(" ");`
3886. `text.push([words[0] + " ", newX, newY]);`
3887. `backToStartX = 0; // distance to reset back to the left`
3888. `for (let i = 1; i < words.length; i++) {`
3889. `let shiftAmount =`
3890. `(findWidth(words[i - 1] + " " + words[i]) -`
3891. `findWidth(words[i])) *`
3892. `scaleFactor +`
3893. `spacing;`
3894. `if (i == words.length - 1) text.push([words[i], shiftAmount, 0]);`
3895. `else text.push([words[i] + " ", shiftAmount, 0]);`
3896. `backToStartX -= shiftAmount;`
3897. `}`
3898. `} else {`
3899. `text.push([da[l], newX, newY]);`
3900. `}`
3901. `}`
3902. `text.push(["", backToStartX, 0]);`
3903. `} else if (align === "justify") {`
3904. `text = [];`
3905. `len = da.length;`
3906. `maxWidth = maxWidth !== 0 ? maxWidth : pageWidth;`
3907. `for (var l = 0; l < len; l++) {`
3908. `newY = l === 0 ? getVerticalCoordinate(y) : -leading;`
3909. `newX = l === 0 ? getHorizontalCoordinate(x) : 0;`
3910. `if (l < len - 1) {`
3911. `wordSpacingPerLine.push(`
3912. `hpf(`
3913. `scale(`
3914. `(maxWidth - lineWidths[l]) / (da[l].split(" ").length - 1)`
3915. `)`
3916. `)`
3917. `);`
3918. `} else {`
3919. `wordSpacingPerLine.push(0);`
3920. `}`
3921. `text.push([da[l], newX, newY]);`
3922. `}`
3923. `} else {`
3924. `throw new Error(`
3925. `'Unrecognized alignment option, use "left", "center", "right" or "justify".'`
3926. `);`
3927. `}`
3928. `}`
3930. `//R2L`
3931. `var doReversing = typeof options.R2L === "boolean" ? options.R2L : R2L;`
3932. `if (doReversing === true) {`
3933. `text = processTextByFunction(text, function(text, posX, posY) {`
3934. `return [`\
3935. `text`\
3936. `.split("")`\
3937. `.reverse()`\
3938. `.join(""),`\
3939. `posX,`\
3940. `posY`\
3941. `];`
3942. `});`
3943. `}`
3945. `//creating Payload-Object to make text byRef`
3946. `payload = {`
3947. `text: text,`
3948. `x: x,`
3949. `y: y,`
3950. `options: options,`
3951. `mutex: {`
3952. `pdfEscape: pdfEscape,`
3953. `activeFontKey: activeFontKey,`
3954. `fonts: fonts,`
3955. `activeFontSize: activeFontSize`
3956. `}`
3957. `};`
3958. `events.publish("postProcessText", payload);`
3960. `text = payload.text;`
3961. `isHex = payload.mutex.isHex || false;`
3963. `//Escaping`
3964. `var activeFontEncoding = fonts[activeFontKey].encoding;`
3966. `if (`
3967. `activeFontEncoding === "WinAnsiEncoding" ||`
3968. `activeFontEncoding === "StandardEncoding"`
3969. `) {`
3970. `text = processTextByFunction(text, function(text, posX, posY) {`
3971. `return [ESC(text), posX, posY];`
3972. `});`
3973. `}`
3975. `da = transformTextToSpecialArray(text);`
3977. `text = [];`
3978. `var STRING = 0;`
3979. `var ARRAY = 1;`
3980. `var variant = Array.isArray(da[0]) ? ARRAY : STRING;`
3981. `var posX;`
3982. `var posY;`
3983. `var content;`
3984. `var wordSpacing = "";`
3986. `var generatePosition = function(`
3987. `parmPosX,`
3988. `parmPosY,`
3989. `parmTransformationMatrix`
3990. `) {`
3991. `var position = "";`
3992. `if (parmTransformationMatrix instanceof Matrix) {`
3993. `// It is kind of more intuitive to apply a plain rotation around the text anchor set by x and y`
3994. `// but when the user supplies an arbitrary transformation matrix, the x and y offsets should be applied`
3995. `// in the coordinate system established by this matrix`
3996. `if (typeof options.angle === "number") {`
3997. `parmTransformationMatrix = matrixMult(`
3998. `parmTransformationMatrix,`
3999. `new Matrix(1, 0, 0, 1, parmPosX, parmPosY)`
4000. `);`
4001. `} else {`
4002. `parmTransformationMatrix = matrixMult(`
4003. `new Matrix(1, 0, 0, 1, parmPosX, parmPosY),`
4004. `parmTransformationMatrix`
4005. `);`
4006. `}`
4008. `if (apiMode === ApiMode.ADVANCED) {`
4009. `parmTransformationMatrix = matrixMult(`
4010. `new Matrix(1, 0, 0, -1, 0, 0),`
4011. `parmTransformationMatrix`
4012. `);`
4013. `}`
4015. `position = parmTransformationMatrix.join(" ") + " Tm\n";`
4016. `} else {`
4017. `position = hpf(parmPosX) + " " + hpf(parmPosY) + " Td\n";`
4018. `}`
4019. `return position;`
4020. `};`
4022. `for (var lineIndex = 0; lineIndex < da.length; lineIndex++) {`
4023. `wordSpacing = "";`
4025. `switch (variant) {`
4026. `case ARRAY:`
4027. `content =`
4028. `(isHex ? "<" : "(") + da[lineIndex][0] + (isHex ? ">" : ")");`
4029. `posX = parseFloat(da[lineIndex][1]);`
4030. `posY = parseFloat(da[lineIndex][2]);`
4031. `break;`
4032. `case STRING:`
4033. `content = (isHex ? "<" : "(") + da[lineIndex] + (isHex ? ">" : ")");`
4034. `posX = getHorizontalCoordinate(x);`
4035. `posY = getVerticalCoordinate(y);`
4036. `break;`
4037. `}`
4039. `if (`
4040. `typeof wordSpacingPerLine !== "undefined" &&`
4041. `typeof wordSpacingPerLine[lineIndex] !== "undefined"`
4042. `) {`
4043. `wordSpacing = wordSpacingPerLine[lineIndex] + " Tw\n";`
4044. `}`
4046. `if (lineIndex === 0) {`
4047. `text.push(`
4048. `wordSpacing +`
4049. `generatePosition(posX, posY, transformationMatrix) +`
4050. `content`
4051. `);`
4052. `} else if (variant === STRING) {`
4053. `text.push(wordSpacing + content);`
4054. `} else if (variant === ARRAY) {`
4055. `text.push(`
4056. `wordSpacing +`
4057. `generatePosition(posX, posY, transformationMatrix) +`
4058. `content`
4059. `);`
4060. `}`
4061. `}`
4063. `text = variant === STRING ? text.join(" Tj\nT* ") : text.join(" Tj\n");`
4064. `text += " Tj\n";`
4066. `var result = "BT\n/";`
4067. `result += activeFontKey + " " + activeFontSize + " Tf\n"; // font face, style, size`
4068. `result += hpf(activeFontSize * lineHeight) + " TL\n"; // line spacing`
4069. `result += textColor + "\n";`
4070. `result += xtra;`
4071. `result += text;`
4072. `result += "ET";`
4074. `out(result);`
4075. `usedFonts[activeFontKey] = true;`
4076. `return scope;`
4077. `};`
4079. `// PDF supports these path painting and clip path operators:`
4080. `//`
4081. `// S - stroke`
4082. `// s - close/stroke`
4083. `// f (F) - fill non-zero`
4084. `// f* - fill evenodd`
4085. `// B - fill stroke nonzero`
4086. `// B* - fill stroke evenodd`
4087. `// b - close fill stroke nonzero`
4088. `// b* - close fill stroke evenodd`
4089. `// n - nothing (consume path)`
4090. `// W - clip nonzero`
4091. `// W* - clip evenodd`
4092. `//`
4093. `// In order to keep the API small, we omit the close-and-fill/stroke operators and provide a separate close()`
4094. `// method.`
4095. `/**`
4096. `*`
4097. `* @name clip`
4098. `* @function`
4099. `* @instance`
4100. `* @param {string} rule Only possible value is 'evenodd'`
4101. `* @returns {jsPDF}`
4102. `* @memberof jsPDF#`
4103. `* @description All .clip() after calling drawing ops with a style argument of null.`
4104. `*/`
4105. `var clip = (API.__private__.clip = API.clip = function(rule) {`
4106. `// Call .clip() after calling drawing ops with a style argument of null`
4107. `// W is the PDF clipping op`
4108. `if ("evenodd" === rule) {`
4109. `out("W*");`
4110. `} else {`
4111. `out("W");`
4112. `}`
4113. `return this;`
4114. `});`
4116. `/**`
4117. `* @name clipEvenOdd`
4118. `* @function`
4119. `* @instance`
4120. `* @returns {jsPDF}`
4121. `* @memberof jsPDF#`
4122. `* @description Modify the current clip path by intersecting it with the current path using the even-odd rule. Note`
4123. `* that this will NOT consume the current path. In order to only use this path for clipping call`
4124. `* {@link API.discardPath} afterwards.`
4125. `*/`
4126. `API.clipEvenOdd = function() {`
4127. `return clip("evenodd");`
4128. `};`
4130. `/**`
4131. `* Consumes the current path without any effect. Mainly used in combination with {@link clip} or`
4132. `* {@link clipEvenOdd}. The PDF "n" operator.`
4133. `* @name discardPath`
4134. `* @function`
4135. `* @instance`
4136. `* @returns {jsPDF}`
4137. `* @memberof jsPDF#`
4138. `*/`
4139. `API.__private__.discardPath = API.discardPath = function() {`
4140. `out("n");`
4141. `return this;`
4142. `};`
4144. `var isValidStyle = (API.__private__.isValidStyle = function(style) {`
4145. `var validStyleVariants = [`\
4146. `undefined,`\
4147. `null,`\
4148. `"S",`\
4149. `"D",`\
4150. `"F",`\
4151. `"DF",`\
4152. `"FD",`\
4153. `"f",`\
4154. `"f*",`\
4155. `"B",`\
4156. `"B*",`\
4157. `"n"`\
4158. `];`
4159. `var result = false;`
4160. `if (validStyleVariants.indexOf(style) !== -1) {`
4161. `result = true;`
4162. `}`
4163. `return result;`
4164. `});`
4166. `API.__private__.setDefaultPathOperation = API.setDefaultPathOperation = function(`
4167. `operator`
4168. `) {`
4169. `if (isValidStyle(operator)) {`
4170. `defaultPathOperation = operator;`
4171. `}`
4172. `return this;`
4173. `};`
4175. `var getStyle = (API.__private__.getStyle = API.getStyle = function(style) {`
4176. `// see path-painting operators in PDF spec`
4177. `var op = defaultPathOperation; // stroke`
4179. `switch (style) {`
4180. `case "D":`
4181. `case "S":`
4182. `op = "S"; // stroke`
4183. `break;`
4184. `case "F":`
4185. `op = "f"; // fill`
4186. `break;`
4187. `case "FD":`
4188. `case "DF":`
4189. `op = "B";`
4190. `break;`
4191. `case "f":`
4192. `case "f*":`
4193. `case "B":`
4194. `case "B*":`
4195. `/*`
4196. `Allow direct use of these PDF path-painting operators:`
4197. `- f fill using nonzero winding number rule`
4198. `- f* fill using even-odd rule`
4199. `- B fill then stroke with fill using non-zero winding number rule`
4200. `- B* fill then stroke with fill using even-odd rule`
4201. `*/`
4202. `op = style;`
4203. `break;`
4204. `}`
4205. `return op;`
4206. `});`
4208. `/**`
4209. `* Close the current path. The PDF "h" operator.`
4210. `* @name close`
4211. `* @function`
4212. `* @instance`
4213. `* @returns {jsPDF}`
4214. `* @memberof jsPDF#`
4215. `*/`
4216. `var close = (API.close = function() {`
4217. `out("h");`
4218. `return this;`
4219. `});`
4221. `/**`
4222. `* Stroke the path. The PDF "S" operator.`
4223. `* @name stroke`
4224. `* @function`
4225. `* @instance`
4226. `* @returns {jsPDF}`
4227. `* @memberof jsPDF#`
4228. `*/`
4229. `API.stroke = function() {`
4230. `out("S");`
4231. `return this;`
4232. `};`
4234. `/**`
4235. `* Fill the current path using the nonzero winding number rule. If a pattern is provided, the path will be filled`
4236. `* with this pattern, otherwise with the current fill color. Equivalent to the PDF "f" operator.`
4237. `* @name fill`
4238. `* @function`
4239. `* @instance`
4240. `* @param {PatternData=} pattern If provided the path will be filled with this pattern`
4241. `* @returns {jsPDF}`
4242. `* @memberof jsPDF#`
4243. `*/`
4244. `API.fill = function(pattern) {`
4245. `fillWithOptionalPattern("f", pattern);`
4246. `return this;`
4247. `};`
4249. `/**`
4250. `* Fill the current path using the even-odd rule. The PDF f* operator.`
4251. `* @see API.fill`
4252. `* @name fillEvenOdd`
4253. `* @function`
4254. `* @instance`
4255. `* @param {PatternData=} pattern If provided the path will be filled with this pattern`
4256. `* @returns {jsPDF}`
4257. `* @memberof jsPDF#`
4258. `*/`
4259. `API.fillEvenOdd = function(pattern) {`
4260. `fillWithOptionalPattern("f*", pattern);`
4261. `return this;`
4262. `};`
4264. `/**`
4265. `* Fill using the nonzero winding number rule and then stroke the current Path. The PDF "B" operator.`
4266. `* @see API.fill`
4267. `* @name fillStroke`
4268. `* @function`
4269. `* @instance`
4270. `* @param {PatternData=} pattern If provided the path will be stroked with this pattern`
4271. `* @returns {jsPDF}`
4272. `* @memberof jsPDF#`
4273. `*/`
4274. `API.fillStroke = function(pattern) {`
4275. `fillWithOptionalPattern("B", pattern);`
4276. `return this;`
4277. `};`
4279. `/**`
4280. `* Fill using the even-odd rule and then stroke the current Path. The PDF "B" operator.`
4281. `* @see API.fill`
4282. `* @name fillStrokeEvenOdd`
4283. `* @function`
4284. `* @instance`
4285. `* @param {PatternData=} pattern If provided the path will be fill-stroked with this pattern`
4286. `* @returns {jsPDF}`
4287. `* @memberof jsPDF#`
4288. `*/`
4289. `API.fillStrokeEvenOdd = function(pattern) {`
4290. `fillWithOptionalPattern("B*", pattern);`
4291. `return this;`
4292. `};`
4294. `var fillWithOptionalPattern = function(style, pattern) {`
4295. `if (typeof pattern === "object") {`
4296. `fillWithPattern(pattern, style);`
4297. `} else {`
4298. `out(style);`
4299. `}`
4300. `};`
4302. `var putStyle = function(style) {`
4303. `if (`
4304. `style === null ||`
4305. `(apiMode === ApiMode.ADVANCED && style === undefined)`
4306. `) {`
4307. `return;`
4308. `}`
4310. `style = getStyle(style);`
4312. `// stroking / filling / both the path`
4313. `out(style);`
4314. `};`
4316. `function cloneTilingPattern(patternKey, boundingBox, xStep, yStep, matrix) {`
4317. `var clone = new TilingPattern(`
4318. `boundingBox || this.boundingBox,`
4319. `xStep || this.xStep,`
4320. `yStep || this.yStep,`
4321. `this.gState,`
4322. `matrix || this.matrix`
4323. `);`
4324. `clone.stream = this.stream;`
4325. `var key = patternKey + "$$" + this.cloneIndex++ + "$$";`
4326. `addPattern(key, clone);`
4327. `return clone;`
4328. `}`
4330. `var fillWithPattern = function(patternData, style) {`
4331. `var patternId = patternMap[patternData.key];`
4332. `var pattern = patterns[patternId];`
4334. `if (pattern instanceof ShadingPattern) {`
4335. `out("q");`
4337. `out(clipRuleFromStyle(style));`
4339. `if (pattern.gState) {`
4340. `API.setGState(pattern.gState);`
4341. `}`
4342. `out(patternData.matrix.toString() + " cm");`
4343. `out("/" + patternId + " sh");`
4344. `out("Q");`
4345. `} else if (pattern instanceof TilingPattern) {`
4346. `// pdf draws patterns starting at the bottom left corner and they are not affected by the global transformation,`
4347. `// so we must flip them`
4348. `var matrix = new Matrix(1, 0, 0, -1, 0, getPageHeight());`
4350. `if (patternData.matrix) {`
4351. `matrix = matrix.multiply(patternData.matrix || identityMatrix);`
4352. `// we cannot apply a matrix to the pattern on use so we must abuse the pattern matrix and create new instances`
4353. `// for each use`
4354. `patternId = cloneTilingPattern.call(`
4355. `pattern,`
4356. `patternData.key,`
4357. `patternData.boundingBox,`
4358. `patternData.xStep,`
4359. `patternData.yStep,`
4360. `matrix`
4361. `).id;`
4362. `}`
4364. `out("q");`
4365. `out("/Pattern cs");`
4366. `out("/" + patternId + " scn");`
4368. `if (pattern.gState) {`
4369. `API.setGState(pattern.gState);`
4370. `}`
4372. `out(style);`
4373. `out("Q");`
4374. `}`
4375. `};`
4377. `var clipRuleFromStyle = function(style) {`
4378. `switch (style) {`
4379. `case "f":`
4380. `case "F":`
4381. `return "W n";`
4382. `case "f*":`
4383. `return "W* n";`
4384. `case "B":`
4385. `return "W S";`
4386. `case "B*":`
4387. `return "W* S";`
4389. `// these two are for compatibility reasons (in the past, calling any primitive method with a shading pattern`
4390. `// and "n"/"S" as style would still fill/fill and stroke the path)`
4391. `case "S":`
4392. `return "W S";`
4393. `case "n":`
4394. `return "W n";`
4395. `}`
4396. `};`
4398. `/**`
4399. `* Begin a new subpath by moving the current point to coordinates (x, y). The PDF "m" operator.`
4400. `* @param {number} x`
4401. `* @param {number} y`
4402. `* @name moveTo`
4403. `* @function`
4404. `* @instance`
4405. `* @memberof jsPDF#`
4406. `* @returns {jsPDF}`
4407. `*/`
4408. `var moveTo = (API.moveTo = function(x, y) {`
4409. `out(hpf(scale(x)) + " " + hpf(transformScaleY(y)) + " m");`
4410. `return this;`
4411. `});`
4413. `/**`
4414. `* Append a straight line segment from the current point to the point (x, y). The PDF "l" operator.`
4415. `* @param {number} x`
4416. `* @param {number} y`
4417. `* @memberof jsPDF#`
4418. `* @name lineTo`
4419. `* @function`
4420. `* @instance`
4421. `* @memberof jsPDF#`
4422. `* @returns {jsPDF}`
4423. `*/`
4424. `var lineTo = (API.lineTo = function(x, y) {`
4425. `out(hpf(scale(x)) + " " + hpf(transformScaleY(y)) + " l");`
4426. `return this;`
4427. `});`
4429. `/**`
4430. `* Append a cubic Bézier curve to the current path. The curve shall extend from the current point to the point`
4431. `* (x3, y3), using (x1, y1) and (x2, y2) as Bézier control points. The new current point shall be (x3, x3).`
4432. `* @param {number} x1`
4433. `* @param {number} y1`
4434. `* @param {number} x2`
4435. `* @param {number} y2`
4436. `* @param {number} x3`
4437. `* @param {number} y3`
4438. `* @memberof jsPDF#`
4439. `* @name curveTo`
4440. `* @function`
4441. `* @instance`
4442. `* @memberof jsPDF#`
4443. `* @returns {jsPDF}`
4444. `*/`
4445. `var curveTo = (API.curveTo = function(x1, y1, x2, y2, x3, y3) {`
4446. `out(`
4447. `[`\
4448. `hpf(scale(x1)),`\
4449. `hpf(transformScaleY(y1)),`\
4450. `hpf(scale(x2)),`\
4451. `hpf(transformScaleY(y2)),`\
4452. `hpf(scale(x3)),`\
4453. `hpf(transformScaleY(y3)),`\
4454. `"c"`\
4455. `].join(" ")`
4456. `);`
4457. `return this;`
4458. `});`
4460. `/**`
4461. `* Draw a line on the current page.`
4462. `*`
4463. `* @name line`
4464. `* @function`
4465. `* @instance`
4466. `* @param {number} x1`
4467. `* @param {number} y1`
4468. `* @param {number} x2`
4469. `* @param {number} y2`
4470. `* @param {string} style A string specifying the painting style or null. Valid styles include: 'S' [default] - stroke, 'F' - fill, and 'DF' (or 'FD') - fill then stroke. A null value postpones setting the style so that a shape may be composed using multiple method calls. The last drawing method call used to define the shape should not have a null style argument. default: 'S'`
4471. `* @returns {jsPDF}`
4472. `* @memberof jsPDF#`
4473. `*/`
4474. `API.__private__.line = API.line = function(x1, y1, x2, y2, style) {`
4475. `if (`
4476. `isNaN(x1) ||`
4477. `isNaN(y1) ||`
4478. `isNaN(x2) ||`
4479. `isNaN(y2) ||`
4480. `!isValidStyle(style)`
4481. `) {`
4482. `throw new Error("Invalid arguments passed to jsPDF.line");`
4483. `}`
4484. `if (apiMode === ApiMode.COMPAT) {`
4485. `return this.lines([[x2 - x1, y2 - y1]], x1, y1, [1, 1], style || "S");`
4486. `} else {`
4487. `return this.lines([[x2 - x1, y2 - y1]], x1, y1, [1, 1]).stroke();`
4488. `}`
4489. `};`
4491. `/**`
4492. `* @typedef {Object} PatternData`
4493. `* {Matrix|undefined} matrix`
4494. `* {Number|undefined} xStep`
4495. `* {Number|undefined} yStep`
4496. `* {Array.|undefined} boundingBox`
4497. `*/`
4499. `/**`
4500. ``* Adds series of curves (straight lines or cubic bezier curves) to canvas, starting at `x`, `y` coordinates.``
4501. ``* All data points in `lines` are relative to last line origin.``
4502. ``* `x`, `y` become x1,y1 for first line / curve in the set.``
4503. `* For lines you only need to specify [x2, y2] - (ending point) vector against x1, y1 starting point.`
4504. `* For bezier curves you need to specify [x2,y2,x3,y3,x4,y4] - vectors to control points 1, 2, ending point. All vectors are against the start of the curve - x1,y1.`
4505. `*`
4506. `* @example .lines([[2,2],[-2,2],[1,1,2,2,3,3],[2,1]], 212,110, [1,1], 'F', false) // line, line, bezier curve, line`
4507. `* @param {Array} lines Array of *vector* shifts as pairs (lines) or sextets (cubic bezier curves).`
4508. `* @param {number} x Coordinate (in units declared at inception of PDF document) against left edge of the page`
4509. `* @param {number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page`
4510. `* @param {number} scale (Defaults to [1.0,1.0]) x,y Scaling factor for all vectors. Elements can be any floating number Sub-one makes drawing smaller. Over-one grows the drawing. Negative flips the direction.`
4511. `* @param {string=} style A string specifying the painting style or null. Valid styles include:`
4512. `* 'S' [default] - stroke,`
4513. `* 'F' - fill,`
4514. `* and 'DF' (or 'FD') - fill then stroke.`
4515. `* In "compat" API mode, a null value postpones setting the style so that a shape may be composed using multiple`
4516. `* method calls. The last drawing method call used to define the shape should not have a null style argument.`
4517. `*`
4518. `* In "advanced" API mode this parameter is deprecated.`
4519. `* @param {Boolean=} closed If true, the path is closed with a straight line from the end of the last curve to the starting point.`
4520. `* @function`
4521. `* @instance`
4522. `* @returns {jsPDF}`
4523. `* @memberof jsPDF#`
4524. `* @name lines`
4525. `*/`
4526. `API.__private__.lines = API.lines = function(`
4527. `lines,`
4528. `x,`
4529. `y,`
4530. `scale,`
4531. `style,`
4532. `closed`
4533. `) {`
4534. `var scalex, scaley, i, l, leg, x2, y2, x3, y3, x4, y4, tmp;`
4536. `// Pre-August-2012 the order of arguments was function(x, y, lines, scale, style)`
4537. `// in effort to make all calls have similar signature like`
4538. `// function(content, coordinateX, coordinateY , miscellaneous)`
4539. `// this method had its args flipped.`
4540. `// code below allows backward compatibility with old arg order.`
4541. `if (typeof lines === "number") {`
4542. `tmp = y;`
4543. `y = x;`
4544. `x = lines;`
4545. `lines = tmp;`
4546. `}`
4548. `scale = scale || [1, 1];`
4549. `closed = closed || false;`
4551. `if (`
4552. `isNaN(x) ||`
4553. `isNaN(y) ||`
4554. `!Array.isArray(lines) ||`
4555. `!Array.isArray(scale) ||`
4556. `!isValidStyle(style) ||`
4557. `typeof closed !== "boolean"`
4558. `) {`
4559. `throw new Error("Invalid arguments passed to jsPDF.lines");`
4560. `}`
4562. `// starting point`
4563. `moveTo(x, y);`
4565. `scalex = scale[0];`
4566. `scaley = scale[1];`
4567. `l = lines.length;`
4568. `//, x2, y2 // bezier only. In page default measurement "units", *after* scaling`
4569. `//, x3, y3 // bezier only. In page default measurement "units", *after* scaling`
4570. `// ending point for all, lines and bezier. . In page default measurement "units", *after* scaling`
4571. `x4 = x; // last / ending point = starting point for first item.`
4572. `y4 = y; // last / ending point = starting point for first item.`
4574. `for (i = 0; i < l; i++) {`
4575. `leg = lines[i];`
4576. `if (leg.length === 2) {`
4577. `// simple line`
4578. `x4 = leg[0] * scalex + x4; // here last x4 was prior ending point`
4579. `y4 = leg[1] * scaley + y4; // here last y4 was prior ending point`
4580. `lineTo(x4, y4);`
4581. `} else {`
4582. `// bezier curve`
4583. `x2 = leg[0] * scalex + x4; // here last x4 is prior ending point`
4584. `y2 = leg[1] * scaley + y4; // here last y4 is prior ending point`
4585. `x3 = leg[2] * scalex + x4; // here last x4 is prior ending point`
4586. `y3 = leg[3] * scaley + y4; // here last y4 is prior ending point`
4587. `x4 = leg[4] * scalex + x4; // here last x4 was prior ending point`
4588. `y4 = leg[5] * scaley + y4; // here last y4 was prior ending point`
4589. `curveTo(x2, y2, x3, y3, x4, y4);`
4590. `}`
4591. `}`
4593. `if (closed) {`
4594. `close();`
4595. `}`
4597. `putStyle(style);`
4598. `return this;`
4599. `};`
4601. `/**`
4602. `* Similar to {@link API.lines} but all coordinates are interpreted as absolute coordinates instead of relative.`
4603. `* @param {Array} lines An array of {op: operator, c: coordinates} object, where op is one of "m" (move to), "l" (line to)`
4604. `* "c" (cubic bezier curve) and "h" (close (sub)path)). c is an array of coordinates. "m" and "l" expect two, "c"`
4605. `* six and "h" an empty array (or undefined).`
4606. `* @function`
4607. `* @returns {jsPDF}`
4608. `* @memberof jsPDF#`
4609. `* @name path`
4610. `*/`
4611. `API.path = function(lines) {`
4612. `for (var i = 0; i < lines.length; i++) {`
4613. `var leg = lines[i];`
4614. `var coords = leg.c;`
4615. `switch (leg.op) {`
4616. `case "m":`
4617. `moveTo(coords[0], coords[1]);`
4618. `break;`
4619. `case "l":`
4620. `lineTo(coords[0], coords[1]);`
4621. `break;`
4622. `case "c":`
4623. `curveTo.apply(this, coords);`
4624. `break;`
4625. `case "h":`
4626. `close();`
4627. `break;`
4628. `}`
4629. `}`
4631. `return this;`
4632. `};`
4634. `/**`
4635. `* Adds a rectangle to PDF.`
4636. `*`
4637. `* @param {number} x Coordinate (in units declared at inception of PDF document) against left edge of the page`
4638. `* @param {number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page`
4639. `* @param {number} w Width (in units declared at inception of PDF document)`
4640. `* @param {number} h Height (in units declared at inception of PDF document)`
4641. `* @param {string=} style A string specifying the painting style or null. Valid styles include:`
4642. `* 'S' [default] - stroke,`
4643. `* 'F' - fill,`
4644. `* and 'DF' (or 'FD') - fill then stroke.`
4645. `* In "compat" API mode, a null value postpones setting the style so that a shape may be composed using multiple`
4646. `* method calls. The last drawing method call used to define the shape should not have a null style argument.`
4647. `*`
4648. `* In "advanced" API mode this parameter is deprecated.`
4649. `* @function`
4650. `* @instance`
4651. `* @returns {jsPDF}`
4652. `* @memberof jsPDF#`
4653. `* @name rect`
4654. `*/`
4655. `API.__private__.rect = API.rect = function(x, y, w, h, style) {`
4656. `if (isNaN(x) || isNaN(y) || isNaN(w) || isNaN(h) || !isValidStyle(style)) {`
4657. `throw new Error("Invalid arguments passed to jsPDF.rect");`
4658. `}`
4659. `if (apiMode === ApiMode.COMPAT) {`
4660. `h = -h;`
4661. `}`
4663. `out(`
4664. `[`\
4665. `hpf(scale(x)),`\
4666. `hpf(transformScaleY(y)),`\
4667. `hpf(scale(w)),`\
4668. `hpf(scale(h)),`\
4669. `"re"`\
4670. `].join(" ")`
4671. `);`
4673. `putStyle(style);`
4674. `return this;`
4675. `};`
4677. `/**`
4678. `* Adds a triangle to PDF.`
4679. `*`
4680. `* @param {number} x1 Coordinate (in units declared at inception of PDF document) against left edge of the page`
4681. `* @param {number} y1 Coordinate (in units declared at inception of PDF document) against upper edge of the page`
4682. `* @param {number} x2 Coordinate (in units declared at inception of PDF document) against left edge of the page`
4683. `* @param {number} y2 Coordinate (in units declared at inception of PDF document) against upper edge of the page`
4684. `* @param {number} x3 Coordinate (in units declared at inception of PDF document) against left edge of the page`
4685. `* @param {number} y3 Coordinate (in units declared at inception of PDF document) against upper edge of the page`
4686. `* @param {string=} style A string specifying the painting style or null. Valid styles include:`
4687. `* 'S' [default] - stroke,`
4688. `* 'F' - fill,`
4689. `* and 'DF' (or 'FD') - fill then stroke.`
4690. `* In "compat" API mode, a null value postpones setting the style so that a shape may be composed using multiple`
4691. `* method calls. The last drawing method call used to define the shape should not have a null style argument.`
4692. `*`
4693. `* In "advanced" API mode this parameter is deprecated.`
4694. `* @function`
4695. `* @instance`
4696. `* @returns {jsPDF}`
4697. `* @memberof jsPDF#`
4698. `* @name triangle`
4699. `*/`
4700. `API.__private__.triangle = API.triangle = function(`
4701. `x1,`
4702. `y1,`
4703. `x2,`
4704. `y2,`
4705. `x3,`
4706. `y3,`
4707. `style`
4708. `) {`
4709. `if (`
4710. `isNaN(x1) ||`
4711. `isNaN(y1) ||`
4712. `isNaN(x2) ||`
4713. `isNaN(y2) ||`
4714. `isNaN(x3) ||`
4715. `isNaN(y3) ||`
4716. `!isValidStyle(style)`
4717. `) {`
4718. `throw new Error("Invalid arguments passed to jsPDF.triangle");`
4719. `}`
4720. `this.lines(`
4721. `[`\
4722. `[x2 - x1, y2 - y1], // vector to point 2`\
4723. `[x3 - x2, y3 - y2], // vector to point 3`\
4724. `[x1 - x3, y1 - y3] // closing vector back to point 1`\
4725. `],`
4726. `x1,`
4727. `y1, // start of path`
4728. `[1, 1],`
4729. `style,`
4730. `true`
4731. `);`
4732. `return this;`
4733. `};`
4735. `/**`
4736. `* Adds a rectangle with rounded corners to PDF.`
4737. `*`
4738. `* @param {number} x Coordinate (in units declared at inception of PDF document) against left edge of the page`
4739. `* @param {number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page`
4740. `* @param {number} w Width (in units declared at inception of PDF document)`
4741. `* @param {number} h Height (in units declared at inception of PDF document)`
4742. `* @param {number} rx Radius along x axis (in units declared at inception of PDF document)`
4743. `* @param {number} ry Radius along y axis (in units declared at inception of PDF document)`
4744. `* @param {string=} style A string specifying the painting style or null. Valid styles include:`
4745. `* 'S' [default] - stroke,`
4746. `* 'F' - fill,`
4747. `* and 'DF' (or 'FD') - fill then stroke.`
4748. `* In "compat" API mode, a null value postpones setting the style so that a shape may be composed using multiple`
4749. `* method calls. The last drawing method call used to define the shape should not have a null style argument.`
4750. `*`
4751. `* In "advanced" API mode this parameter is deprecated.`
4752. `* @function`
4753. `* @instance`
4754. `* @returns {jsPDF}`
4755. `* @memberof jsPDF#`
4756. `* @name roundedRect`
4757. `*/`
4758. `API.__private__.roundedRect = API.roundedRect = function(`
4759. `x,`
4760. `y,`
4761. `w,`
4762. `h,`
4763. `rx,`
4764. `ry,`
4765. `style`
4766. `) {`
4767. `if (`
4768. `isNaN(x) ||`
4769. `isNaN(y) ||`
4770. `isNaN(w) ||`
4771. `isNaN(h) ||`
4772. `isNaN(rx) ||`
4773. `isNaN(ry) ||`
4774. `!isValidStyle(style)`
4775. `) {`
4776. `throw new Error("Invalid arguments passed to jsPDF.roundedRect");`
4777. `}`
4778. `var MyArc = (4 / 3) * (Math.SQRT2 - 1);`
4780. `rx = Math.min(rx, w * 0.5);`
4781. `ry = Math.min(ry, h * 0.5);`
4783. `this.lines(`
4784. `[`\
4785. `[w - 2 * rx, 0],`\
4786. `[rx * MyArc, 0, rx, ry - ry * MyArc, rx, ry],`\
4787. `[0, h - 2 * ry],`\
4788. `[0, ry * MyArc, -(rx * MyArc), ry, -rx, ry],`\
4789. `[-w + 2 * rx, 0],`\
4790. `[-(rx * MyArc), 0, -rx, -(ry * MyArc), -rx, -ry],`\
4791. `[0, -h + 2 * ry],`\
4792. `[0, -(ry * MyArc), rx * MyArc, -ry, rx, -ry]`\
4793. `],`
4794. `x + rx,`
4795. `y, // start of path`
4796. `[1, 1],`
4797. `style,`
4798. `true`
4799. `);`
4800. `return this;`
4801. `};`
4803. `/**`
4804. `* Adds an ellipse to PDF.`
4805. `*`
4806. `* @param {number} x Coordinate (in units declared at inception of PDF document) against left edge of the page`
4807. `* @param {number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page`
4808. `* @param {number} rx Radius along x axis (in units declared at inception of PDF document)`
4809. `* @param {number} ry Radius along y axis (in units declared at inception of PDF document)`
4810. `* @param {string=} style A string specifying the painting style or null. Valid styles include:`
4811. `* 'S' [default] - stroke,`
4812. `* 'F' - fill,`
4813. `* and 'DF' (or 'FD') - fill then stroke.`
4814. `* In "compat" API mode, a null value postpones setting the style so that a shape may be composed using multiple`
4815. `* method calls. The last drawing method call used to define the shape should not have a null style argument.`
4816. `*`
4817. `* In "advanced" API mode this parameter is deprecated.`
4818. `* @function`
4819. `* @instance`
4820. `* @returns {jsPDF}`
4821. `* @memberof jsPDF#`
4822. `* @name ellipse`
4823. `*/`
4824. `API.__private__.ellipse = API.ellipse = function(x, y, rx, ry, style) {`
4825. `if (`
4826. `isNaN(x) ||`
4827. `isNaN(y) ||`
4828. `isNaN(rx) ||`
4829. `isNaN(ry) ||`
4830. `!isValidStyle(style)`
4831. `) {`
4832. `throw new Error("Invalid arguments passed to jsPDF.ellipse");`
4833. `}`
4834. `var lx = (4 / 3) * (Math.SQRT2 - 1) * rx,`
4835. `ly = (4 / 3) * (Math.SQRT2 - 1) * ry;`
4837. `moveTo(x + rx, y);`
4838. `curveTo(x + rx, y - ly, x + lx, y - ry, x, y - ry);`
4839. `curveTo(x - lx, y - ry, x - rx, y - ly, x - rx, y);`
4840. `curveTo(x - rx, y + ly, x - lx, y + ry, x, y + ry);`
4841. `curveTo(x + lx, y + ry, x + rx, y + ly, x + rx, y);`
4843. `putStyle(style);`
4844. `return this;`
4845. `};`
4847. `/**`
4848. `* Adds an circle to PDF.`
4849. `*`
4850. `* @param {number} x Coordinate (in units declared at inception of PDF document) against left edge of the page`
4851. `* @param {number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page`
4852. `* @param {number} r Radius (in units declared at inception of PDF document)`
4853. `* @param {string=} style A string specifying the painting style or null. Valid styles include:`
4854. `* 'S' [default] - stroke,`
4855. `* 'F' - fill,`
4856. `* and 'DF' (or 'FD') - fill then stroke.`
4857. `* In "compat" API mode, a null value postpones setting the style so that a shape may be composed using multiple`
4858. `* method calls. The last drawing method call used to define the shape should not have a null style argument.`
4859. `*`
4860. `* In "advanced" API mode this parameter is deprecated.`
4861. `* @function`
4862. `* @instance`
4863. `* @returns {jsPDF}`
4864. `* @memberof jsPDF#`
4865. `* @name circle`
4866. `*/`
4867. `API.__private__.circle = API.circle = function(x, y, r, style) {`
4868. `if (isNaN(x) || isNaN(y) || isNaN(r) || !isValidStyle(style)) {`
4869. `throw new Error("Invalid arguments passed to jsPDF.circle");`
4870. `}`
4871. `return this.ellipse(x, y, r, r, style);`
4872. `};`
4874. `/**`
4875. `* Sets text font face, variant for upcoming text elements.`
4876. `* See output of jsPDF.getFontList() for possible font names, styles.`
4877. `*`
4878. `* @param {string} fontName Font name or family. Example: "times".`
4879. `* @param {string} fontStyle Font style or variant. Example: "italic".`
4880. `* @param {number | string} fontWeight Weight of the Font. Example: "normal" | 400`
4881. `* @function`
4882. `* @instance`
4883. `* @returns {jsPDF}`
4884. `* @memberof jsPDF#`
4885. `* @name setFont`
4886. `*/`
4887. `API.setFont = function(fontName, fontStyle, fontWeight) {`
4888. `if (fontWeight) {`
4889. `fontStyle = combineFontStyleAndFontWeight(fontStyle, fontWeight);`
4890. `}`
4891. `activeFontKey = getFont(fontName, fontStyle, {`
4892. `disableWarning: false`
4893. `});`
4894. `return this;`
4895. `};`
4897. `/**`
4898. `* Gets text font face, variant for upcoming text elements.`
4899. `*`
4900. `* @function`
4901. `* @instance`
4902. `* @returns {Object}`
4903. `* @memberof jsPDF#`
4904. `* @name getFont`
4905. `*/`
4906. `var getFontEntry = (API.__private__.getFont = API.getFont = function() {`
4907. `return fonts[getFont.apply(API, arguments)];`
4908. `});`
4910. `/**`
4911. `* Returns an object - a tree of fontName to fontStyle relationships available to`
4912. `* active PDF document.`
4913. `*`
4914. `* @public`
4915. `* @function`
4916. `* @instance`
4917. `* @returns {Object} Like {'times':['normal', 'italic', ... ], 'arial':['normal', 'bold', ... ], ... }`
4918. `* @memberof jsPDF#`
4919. `* @name getFontList`
4920. `*/`
4921. `API.__private__.getFontList = API.getFontList = function() {`
4922. `var list = {},`
4923. `fontName,`
4924. `fontStyle;`
4926. `for (fontName in fontmap) {`
4927. `if (fontmap.hasOwnProperty(fontName)) {`
4928. `list[fontName] = [];`
4929. `for (fontStyle in fontmap[fontName]) {`
4930. `if (fontmap[fontName].hasOwnProperty(fontStyle)) {`
4931. `list[fontName].push(fontStyle);`
4932. `}`
4933. `}`
4934. `}`
4935. `}`
4936. `return list;`
4937. `};`
4939. `/**`
4940. `* Add a custom font to the current instance.`
4941. `*`
4942. `* @param {string} postScriptName PDF specification full name for the font.`
4943. `* @param {string} id PDF-document-instance-specific label assinged to the font.`
4944. `* @param {string} fontStyle Style of the Font.`
4945. `* @param {number | string} fontWeight Weight of the Font.`
4946. `* @param {Object} encoding Encoding_name-to-Font_metrics_object mapping.`
4947. `* @function`
4948. `* @instance`
4949. `* @memberof jsPDF#`
4950. `* @name addFont`
4951. `* @returns {string} fontId`
4952. `*/`
4953. `API.addFont = function(`
4954. `postScriptName,`
4955. `fontName,`
4956. `fontStyle,`
4957. `fontWeight,`
4958. `encoding`
4959. `) {`
4960. `var encodingOptions = [`\
4961. `"StandardEncoding",`\
4962. `"MacRomanEncoding",`\
4963. `"Identity-H",`\
4964. `"WinAnsiEncoding"`\
4965. `];`
4966. `if (arguments[3] && encodingOptions.indexOf(arguments[3]) !== -1) {`
4967. `//IE 11 fix`
4968. `encoding = arguments[3];`
4969. `} else if (arguments[3] && encodingOptions.indexOf(arguments[3]) == -1) {`
4970. `fontStyle = combineFontStyleAndFontWeight(fontStyle, fontWeight);`
4971. `}`
4972. `encoding = encoding || "Identity-H";`
4973. `return addFont.call(this, postScriptName, fontName, fontStyle, encoding);`
4974. `};`
4976. `var lineWidth = options.lineWidth || 0.200025; // 2mm`
4977. `/**`
4978. `* Gets the line width, default: 0.200025.`
4979. `*`
4980. `* @function`
4981. `* @instance`
4982. `* @returns {number} lineWidth`
4983. `* @memberof jsPDF#`
4984. `* @name getLineWidth`
4985. `*/`
4986. `var getLineWidth = (API.__private__.getLineWidth = API.getLineWidth = function() {`
4987. `return lineWidth;`
4988. `});`
4990. `/**`
4991. `* Sets line width for upcoming lines.`
4992. `*`
4993. `* @param {number} width Line width (in units declared at inception of PDF document).`
4994. `* @function`
4995. `* @instance`
4996. `* @returns {jsPDF}`
4997. `* @memberof jsPDF#`
4998. `* @name setLineWidth`
4999. `*/`
5000. `var setLineWidth = (API.__private__.setLineWidth = API.setLineWidth = function(`
5001. `width`
5002. `) {`
5003. `lineWidth = width;`
5004. `out(hpf(scale(width)) + " w");`
5005. `return this;`
5006. `});`
5008. `/**`
5009. `* Sets the dash pattern for upcoming lines.`
5010. `*`
5011. `* To reset the settings simply call the method without any parameters.`
5012. `* @param {Array} dashArray An array containing 0-2 numbers. The first number sets the length of the`
5013. `* dashes, the second number the length of the gaps. If the second number is missing, the gaps are considered`
5014. `* to be as long as the dashes. An empty array means solid, unbroken lines.`
5015. `* @param {number} dashPhase The phase lines start with.`
5016. `* @function`
5017. `* @instance`
5018. `* @returns {jsPDF}`
5019. `* @memberof jsPDF#`
5020. `* @name setLineDashPattern`
5021. `*/`
5022. `API.__private__.setLineDash = jsPDF.API.setLineDash = jsPDF.API.setLineDashPattern = function(`
5023. `dashArray,`
5024. `dashPhase`
5025. `) {`
5026. `dashArray = dashArray || [];`
5027. `dashPhase = dashPhase || 0;`
5029. `if (isNaN(dashPhase) || !Array.isArray(dashArray)) {`
5030. `throw new Error("Invalid arguments passed to jsPDF.setLineDash");`
5031. `}`
5033. `dashArray = dashArray`
5034. `.map(function(x) {`
5035. `return hpf(scale(x));`
5036. `})`
5037. `.join(" ");`
5038. `dashPhase = hpf(scale(dashPhase));`
5040. `out("[" + dashArray + "] " + dashPhase + " d");`
5041. `return this;`
5042. `};`
5044. `var lineHeightFactor;`
5046. `var getLineHeight = (API.__private__.getLineHeight = API.getLineHeight = function() {`
5047. `return activeFontSize * lineHeightFactor;`
5048. `});`
5050. `API.__private__.getLineHeight = API.getLineHeight = function() {`
5051. `return activeFontSize * lineHeightFactor;`
5052. `};`
5054. `/**`
5055. `* Sets the LineHeightFactor of proportion.`
5056. `*`
5057. `* @param {number} value LineHeightFactor value. Default: 1.15.`
5058. `* @function`
5059. `* @instance`
5060. `* @returns {jsPDF}`
5061. `* @memberof jsPDF#`
5062. `* @name setLineHeightFactor`
5063. `*/`
5064. `var setLineHeightFactor = (API.__private__.setLineHeightFactor = API.setLineHeightFactor = function(`
5065. `value`
5066. `) {`
5067. `value = value || 1.15;`
5068. `if (typeof value === "number") {`
5069. `lineHeightFactor = value;`
5070. `}`
5071. `return this;`
5072. `});`
5074. `/**`
5075. `* Gets the LineHeightFactor, default: 1.15.`
5076. `*`
5077. `* @function`
5078. `* @instance`
5079. `* @returns {number} lineHeightFactor`
5080. `* @memberof jsPDF#`
5081. `* @name getLineHeightFactor`
5082. `*/`
5083. `var getLineHeightFactor = (API.__private__.getLineHeightFactor = API.getLineHeightFactor = function() {`
5084. `return lineHeightFactor;`
5085. `});`
5087. `setLineHeightFactor(options.lineHeight);`
5089. `var getHorizontalCoordinate = (API.__private__.getHorizontalCoordinate = function(`
5090. `value`
5091. `) {`
5092. `return scale(value);`
5093. `});`
5095. `var getVerticalCoordinate = (API.__private__.getVerticalCoordinate = function(`
5096. `value`
5097. `) {`
5098. `if (apiMode === ApiMode.ADVANCED) {`
5099. `return value;`
5100. `} else {`
5101. `var pageHeight =`
5102. `pagesContext[currentPage].mediaBox.topRightY -`
5103. `pagesContext[currentPage].mediaBox.bottomLeftY;`
5104. `return pageHeight - scale(value);`
5105. `}`
5106. `});`
5108. `var getHorizontalCoordinateString = (API.__private__.getHorizontalCoordinateString = API.getHorizontalCoordinateString = function(`
5109. `value`
5110. `) {`
5111. `return hpf(getHorizontalCoordinate(value));`
5112. `});`
5114. `var getVerticalCoordinateString = (API.__private__.getVerticalCoordinateString = API.getVerticalCoordinateString = function(`
5115. `value`
5116. `) {`
5117. `return hpf(getVerticalCoordinate(value));`
5118. `});`
5120. `var strokeColor = options.strokeColor || "0 G";`
5122. `/**`
5123. `* Gets the stroke color for upcoming elements.`
5124. `*`
5125. `* @function`
5126. `* @instance`
5127. `* @returns {string} colorAsHex`
5128. `* @memberof jsPDF#`
5129. `* @name getDrawColor`
5130. `*/`
5131. `API.__private__.getStrokeColor = API.getDrawColor = function() {`
5132. `return decodeColorString(strokeColor);`
5133. `};`
5135. `/**`
5136. `* Sets the stroke color for upcoming elements.`
5137. `*`
5138. `* Depending on the number of arguments given, Gray, RGB, or CMYK`
5139. `* color space is implied.`
5140. `*`
5141. `* When only ch1 is given, "Gray" color space is implied and it`
5142. `* must be a value in the range from 0.00 (solid black) to to 1.00 (white)`
5143. `* if values are communicated as String types, or in range from 0 (black)`
5144. `* to 255 (white) if communicated as Number type.`
5145. `* The RGB-like 0-255 range is provided for backward compatibility.`
5146. `*`
5147. `* When only ch1,ch2,ch3 are given, "RGB" color space is implied and each`
5148. `* value must be in the range from 0.00 (minimum intensity) to to 1.00`
5149. `* (max intensity) if values are communicated as String types, or`
5150. `* from 0 (min intensity) to to 255 (max intensity) if values are communicated`
5151. `* as Number types.`
5152. `* The RGB-like 0-255 range is provided for backward compatibility.`
5153. `*`
5154. `* When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each`
5155. `* value must be a in the range from 0.00 (0% concentration) to to`
5156. `* 1.00 (100% concentration)`
5157. `*`
5158. `* Because JavaScript treats fixed point numbers badly (rounds to`
5159. `* floating point nearest to binary representation) it is highly advised to`
5160. `* communicate the fractional numbers as String types, not JavaScript Number type.`
5161. `*`
5162. `* @param {Number|String} ch1 Color channel value or {string} ch1 color value in hexadecimal, example: '#FFFFFF'.`
5163. `* @param {Number} ch2 Color channel value.`
5164. `* @param {Number} ch3 Color channel value.`
5165. `* @param {Number} ch4 Color channel value.`
5166. `*`
5167. `* @function`
5168. `* @instance`
5169. `* @returns {jsPDF}`
5170. `* @memberof jsPDF#`
5171. `* @name setDrawColor`
5172. `*/`
5173. `API.__private__.setStrokeColor = API.setDrawColor = function(`
5174. `ch1,`
5175. `ch2,`
5176. `ch3,`
5177. `ch4`
5178. `) {`
5179. `var options = {`
5180. `ch1: ch1,`
5181. `ch2: ch2,`
5182. `ch3: ch3,`
5183. `ch4: ch4,`
5184. `pdfColorType: "draw",`
5185. `precision: 2`
5186. `};`
5188. `strokeColor = encodeColorString(options);`
5189. `out(strokeColor);`
5190. `return this;`
5191. `};`
5193. `var fillColor = options.fillColor || "0 g";`
5195. `/**`
5196. `* Gets the fill color for upcoming elements.`
5197. `*`
5198. `* @function`
5199. `* @instance`
5200. `* @returns {string} colorAsHex`
5201. `* @memberof jsPDF#`
5202. `* @name getFillColor`
5203. `*/`
5204. `API.__private__.getFillColor = API.getFillColor = function() {`
5205. `return decodeColorString(fillColor);`
5206. `};`
5208. `/**`
5209. `* Sets the fill color for upcoming elements.`
5210. `*`
5211. `* Depending on the number of arguments given, Gray, RGB, or CMYK`
5212. `* color space is implied.`
5213. `*`
5214. `* When only ch1 is given, "Gray" color space is implied and it`
5215. `* must be a value in the range from 0.00 (solid black) to to 1.00 (white)`
5216. `* if values are communicated as String types, or in range from 0 (black)`
5217. `* to 255 (white) if communicated as Number type.`
5218. `* The RGB-like 0-255 range is provided for backward compatibility.`
5219. `*`
5220. `* When only ch1,ch2,ch3 are given, "RGB" color space is implied and each`
5221. `* value must be in the range from 0.00 (minimum intensity) to to 1.00`
5222. `* (max intensity) if values are communicated as String types, or`
5223. `* from 0 (min intensity) to to 255 (max intensity) if values are communicated`
5224. `* as Number types.`
5225. `* The RGB-like 0-255 range is provided for backward compatibility.`
5226. `*`
5227. `* When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each`
5228. `* value must be a in the range from 0.00 (0% concentration) to to`
5229. `* 1.00 (100% concentration)`
5230. `*`
5231. `* Because JavaScript treats fixed point numbers badly (rounds to`
5232. `* floating point nearest to binary representation) it is highly advised to`
5233. `* communicate the fractional numbers as String types, not JavaScript Number type.`
5234. `*`
5235. `* @param {Number|String} ch1 Color channel value or {string} ch1 color value in hexadecimal, example: '#FFFFFF'.`
5236. `* @param {Number} ch2 Color channel value.`
5237. `* @param {Number} ch3 Color channel value.`
5238. `* @param {Number} ch4 Color channel value.`
5239. `*`
5240. `* @function`
5241. `* @instance`
5242. `* @returns {jsPDF}`
5243. `* @memberof jsPDF#`
5244. `* @name setFillColor`
5245. `*/`
5246. `API.__private__.setFillColor = API.setFillColor = function(`
5247. `ch1,`
5248. `ch2,`
5249. `ch3,`
5250. `ch4`
5251. `) {`
5252. `var options = {`
5253. `ch1: ch1,`
5254. `ch2: ch2,`
5255. `ch3: ch3,`
5256. `ch4: ch4,`
5257. `pdfColorType: "fill",`
5258. `precision: 2`
5259. `};`
5261. `fillColor = encodeColorString(options);`
5262. `out(fillColor);`
5263. `return this;`
5264. `};`
5266. `var textColor = options.textColor || "0 g";`
5267. `/**`
5268. `* Gets the text color for upcoming elements.`
5269. `*`
5270. `* @function`
5271. `* @instance`
5272. `* @returns {string} colorAsHex`
5273. `* @memberof jsPDF#`
5274. `* @name getTextColor`
5275. `*/`
5276. `var getTextColor = (API.__private__.getTextColor = API.getTextColor = function() {`
5277. `return decodeColorString(textColor);`
5278. `});`
5279. `/**`
5280. `* Sets the text color for upcoming elements.`
5281. `*`
5282. `* Depending on the number of arguments given, Gray, RGB, or CMYK`
5283. `* color space is implied.`
5284. `*`
5285. `* When only ch1 is given, "Gray" color space is implied and it`
5286. `* must be a value in the range from 0.00 (solid black) to to 1.00 (white)`
5287. `* if values are communicated as String types, or in range from 0 (black)`
5288. `* to 255 (white) if communicated as Number type.`
5289. `* The RGB-like 0-255 range is provided for backward compatibility.`
5290. `*`
5291. `* When only ch1,ch2,ch3 are given, "RGB" color space is implied and each`
5292. `* value must be in the range from 0.00 (minimum intensity) to to 1.00`
5293. `* (max intensity) if values are communicated as String types, or`
5294. `* from 0 (min intensity) to to 255 (max intensity) if values are communicated`
5295. `* as Number types.`
5296. `* The RGB-like 0-255 range is provided for backward compatibility.`
5297. `*`
5298. `* When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each`
5299. `* value must be a in the range from 0.00 (0% concentration) to to`
5300. `* 1.00 (100% concentration)`
5301. `*`
5302. `* Because JavaScript treats fixed point numbers badly (rounds to`
5303. `* floating point nearest to binary representation) it is highly advised to`
5304. `* communicate the fractional numbers as String types, not JavaScript Number type.`
5305. `*`
5306. `* @param {Number|String} ch1 Color channel value or {string} ch1 color value in hexadecimal, example: '#FFFFFF'.`
5307. `* @param {Number} ch2 Color channel value.`
5308. `* @param {Number} ch3 Color channel value.`
5309. `* @param {Number} ch4 Color channel value.`
5310. `*`
5311. `* @function`
5312. `* @instance`
5313. `* @returns {jsPDF}`
5314. `* @memberof jsPDF#`
5315. `* @name setTextColor`
5316. `*/`
5317. `API.__private__.setTextColor = API.setTextColor = function(`
5318. `ch1,`
5319. `ch2,`
5320. `ch3,`
5321. `ch4`
5322. `) {`
5323. `var options = {`
5324. `ch1: ch1,`
5325. `ch2: ch2,`
5326. `ch3: ch3,`
5327. `ch4: ch4,`
5328. `pdfColorType: "text",`
5329. `precision: 3`
5330. `};`
5331. `textColor = encodeColorString(options);`
5333. `return this;`
5334. `};`
5336. `var activeCharSpace = options.charSpace;`
5338. `/**`
5339. `* Get global value of CharSpace.`
5340. `*`
5341. `* @function`
5342. `* @instance`
5343. `* @returns {number} charSpace`
5344. `* @memberof jsPDF#`
5345. `* @name getCharSpace`
5346. `*/`
5347. `var getCharSpace = (API.__private__.getCharSpace = API.getCharSpace = function() {`
5348. `return parseFloat(activeCharSpace || 0);`
5349. `});`
5351. `/**`
5352. `* Set global value of CharSpace.`
5353. `*`
5354. `* @param {number} charSpace`
5355. `* @function`
5356. `* @instance`
5357. `* @returns {jsPDF} jsPDF-instance`
5358. `* @memberof jsPDF#`
5359. `* @name setCharSpace`
5360. `*/`
5361. `API.__private__.setCharSpace = API.setCharSpace = function(charSpace) {`
5362. `if (isNaN(charSpace)) {`
5363. `throw new Error("Invalid argument passed to jsPDF.setCharSpace");`
5364. `}`
5365. `activeCharSpace = charSpace;`
5366. `return this;`
5367. `};`
5369. `var lineCapID = 0;`
5370. `/**`
5371. `* Is an Object providing a mapping from human-readable to`
5372. `* integer flag values designating the varieties of line cap`
5373. `* and join styles.`
5374. `*`
5375. `* @memberof jsPDF#`
5376. `* @name CapJoinStyles`
5377. `*/`
5378. `API.CapJoinStyles = {`
5379. `0: 0,`
5380. `butt: 0,`
5381. `but: 0,`
5382. `miter: 0,`
5383. `1: 1,`
5384. `round: 1,`
5385. `rounded: 1,`
5386. `circle: 1,`
5387. `2: 2,`
5388. `projecting: 2,`
5389. `project: 2,`
5390. `square: 2,`
5391. `bevel: 2`
5392. `};`
5394. `/**`
5395. `* Sets the line cap styles.`
5396. `* See {jsPDF.CapJoinStyles} for variants.`
5397. `*`
5398. `* @param {String|Number} style A string or number identifying the type of line cap.`
5399. `* @function`
5400. `* @instance`
5401. `* @returns {jsPDF}`
5402. `* @memberof jsPDF#`
5403. `* @name setLineCap`
5404. `*/`
5405. `API.__private__.setLineCap = API.setLineCap = function(style) {`
5406. `var id = API.CapJoinStyles[style];`
5407. `if (id === undefined) {`
5408. `throw new Error(`
5409. `"Line cap style of '" +`
5410. `style +`
5411. `"' is not recognized. See or extend .CapJoinStyles property for valid styles"`
5412. `);`
5413. `}`
5414. `lineCapID = id;`
5415. `out(id + " J");`
5417. `return this;`
5418. `};`
5420. `var lineJoinID = 0;`
5421. `/**`
5422. `* Sets the line join styles.`
5423. `* See {jsPDF.CapJoinStyles} for variants.`
5424. `*`
5425. `* @param {String|Number} style A string or number identifying the type of line join.`
5426. `* @function`
5427. `* @instance`
5428. `* @returns {jsPDF}`
5429. `* @memberof jsPDF#`
5430. `* @name setLineJoin`
5431. `*/`
5432. `API.__private__.setLineJoin = API.setLineJoin = function(style) {`
5433. `var id = API.CapJoinStyles[style];`
5434. `if (id === undefined) {`
5435. `throw new Error(`
5436. `"Line join style of '" +`
5437. `style +`
5438. `"' is not recognized. See or extend .CapJoinStyles property for valid styles"`
5439. `);`
5440. `}`
5441. `lineJoinID = id;`
5442. `out(id + " j");`
5444. `return this;`
5445. `};`
5447. `var miterLimit;`
5448. `/**`
5449. `* Sets the miterLimit property, which effects the maximum miter length.`
5450. `*`
5451. `* @param {number} length The length of the miter`
5452. `* @function`
5453. `* @instance`
5454. `* @returns {jsPDF}`
5455. `* @memberof jsPDF#`
5456. `* @name setLineMiterLimit`
5457. `*/`
5458. `API.__private__.setLineMiterLimit = API.__private__.setMiterLimit = API.setLineMiterLimit = API.setMiterLimit = function(`
5459. `length`
5460. `) {`
5461. `length = length || 0;`
5462. `if (isNaN(length)) {`
5463. `throw new Error("Invalid argument passed to jsPDF.setLineMiterLimit");`
5464. `}`
5465. `out(hpf(scale(length)) + " M");`
5467. `return this;`
5468. `};`
5470. `/**`
5471. `* An object representing a pdf graphics state.`
5472. `* @class GState`
5473. `*/`
5475. `/**`
5476. `*`
5477. `* @param parameters A parameter object that contains all properties this graphics state wants to set.`
5478. `* Supported are: opacity, stroke-opacity`
5479. `* @constructor`
5480. `*/`
5481. `API.GState = GState;`
5483. `/**`
5484. `* Sets a either previously added {@link GState} (via {@link addGState}) or a new {@link GState}.`
5485. `* @param {String|GState} gState If type is string, a previously added GState is used, if type is GState`
5486. `* it will be added before use.`
5487. `* @function`
5488. `* @returns {jsPDF}`
5489. `* @memberof jsPDF#`
5490. `* @name setGState`
5491. `*/`
5492. `API.setGState = function(gState) {`
5493. `if (typeof gState === "string") {`
5494. `gState = gStates[gStatesMap[gState]];`
5495. `} else {`
5496. `gState = addGState(null, gState);`
5497. `}`
5499. `if (!gState.equals(activeGState)) {`
5500. `out("/" + gState.id + " gs");`
5501. `activeGState = gState;`
5502. `}`
5503. `};`
5505. `/**`
5506. `* Adds a new Graphics State. Duplicates are automatically eliminated.`
5507. `* @param {String} key Might also be null, if no later reference to this gState is needed`
5508. `* @param {Object} gState The gState object`
5509. `*/`
5510. `var addGState = function(key, gState) {`
5511. `// only add it if it is not already present (the keys provided by the user must be unique!)`
5512. `if (key && gStatesMap[key]) return;`
5513. `var duplicate = false;`
5514. `for (var s in gStates) {`
5515. `if (gStates.hasOwnProperty(s)) {`
5516. `if (gStates[s].equals(gState)) {`
5517. `duplicate = true;`
5518. `break;`
5519. `}`
5520. `}`
5521. `}`
5523. `if (duplicate) {`
5524. `gState = gStates[s];`
5525. `} else {`
5526. `var gStateKey = "GS" + (Object.keys(gStates).length + 1).toString(10);`
5527. `gStates[gStateKey] = gState;`
5528. `gState.id = gStateKey;`
5529. `}`
5531. `// several user keys may point to the same GState object`
5532. `key && (gStatesMap[key] = gState.id);`
5534. `events.publish("addGState", gState);`
5536. `return gState;`
5537. `};`
5539. `/**`
5540. `* Adds a new {@link GState} for later use. See {@link setGState}.`
5541. `* @param {String} key`
5542. `* @param {GState} gState`
5543. `* @function`
5544. `* @instance`
5545. `* @returns {jsPDF}`
5546. `*`
5547. `* @memberof jsPDF#`
5548. `* @name addGState`
5549. `*/`
5550. `API.addGState = function(key, gState) {`
5551. `addGState(key, gState);`
5552. `return this;`
5553. `};`
5555. `/**`
5556. `* Saves the current graphics state ("pushes it on the stack"). It can be restored by {@link restoreGraphicsState}`
5557. `* later. Here, the general pdf graphics state is meant, also including the current transformation matrix,`
5558. `* fill and stroke colors etc.`
5559. `* @function`
5560. `* @returns {jsPDF}`
5561. `* @memberof jsPDF#`
5562. `* @name saveGraphicsState`
5563. `*/`
5564. `API.saveGraphicsState = function() {`
5565. `out("q");`
5566. `// as we cannot set font key and size independently we must keep track of both`
5567. `fontStateStack.push({`
5568. `key: activeFontKey,`
5569. `size: activeFontSize,`
5570. `color: textColor`
5571. `});`
5572. `return this;`
5573. `};`
5575. `/**`
5576. `* Restores a previously saved graphics state saved by {@link saveGraphicsState} ("pops the stack").`
5577. `* @function`
5578. `* @returns {jsPDF}`
5579. `* @memberof jsPDF#`
5580. `* @name restoreGraphicsState`
5581. `*/`
5582. `API.restoreGraphicsState = function() {`
5583. `out("Q");`
5585. `// restore previous font state`
5586. `var fontState = fontStateStack.pop();`
5587. `activeFontKey = fontState.key;`
5588. `activeFontSize = fontState.size;`
5589. `textColor = fontState.color;`
5591. `activeGState = null;`
5593. `return this;`
5594. `};`
5596. `/**`
5597. `* Appends this matrix to the left of all previously applied matrices.`
5598. `*`
5599. `* @param {Matrix} matrix`
5600. `* @function`
5601. `* @returns {jsPDF}`
5602. `* @memberof jsPDF#`
5603. `* @name setCurrentTransformationMatrix`
5604. `*/`
5605. `API.setCurrentTransformationMatrix = function(matrix) {`
5606. `out(matrix.toString() + " cm");`
5607. `return this;`
5608. `};`
5610. `/**`
5611. `* Inserts a debug comment into the generated pdf.`
5612. `* @function`
5613. `* @instance`
5614. `* @param {String} text`
5615. `* @returns {jsPDF}`
5616. `* @memberof jsPDF#`
5617. `* @name comment`
5618. `*/`
5619. `API.comment = function(text) {`
5620. `out("#" + text);`
5621. `return this;`
5622. `};`
5624. `/**`
5625. `* Point`
5626. `*/`
5627. `var Point = function(x, y) {`
5628. `var _x = x || 0;`
5629. `Object.defineProperty(this, "x", {`
5630. `enumerable: true,`
5631. `get: function() {`
5632. `return _x;`
5633. `},`
5634. `set: function(value) {`
5635. `if (!isNaN(value)) {`
5636. `_x = parseFloat(value);`
5637. `}`
5638. `}`
5639. `});`
5641. `var _y = y || 0;`
5642. `Object.defineProperty(this, "y", {`
5643. `enumerable: true,`
5644. `get: function() {`
5645. `return _y;`
5646. `},`
5647. `set: function(value) {`
5648. `if (!isNaN(value)) {`
5649. `_y = parseFloat(value);`
5650. `}`
5651. `}`
5652. `});`
5654. `var _type = "pt";`
5655. `Object.defineProperty(this, "type", {`
5656. `enumerable: true,`
5657. `get: function() {`
5658. `return _type;`
5659. `},`
5660. `set: function(value) {`
5661. `_type = value.toString();`
5662. `}`
5663. `});`
5664. `return this;`
5665. `};`
5667. `/**`
5668. `* Rectangle`
5669. `*/`
5670. `var Rectangle = function(x, y, w, h) {`
5671. `Point.call(this, x, y);`
5672. `this.type = "rect";`
5674. `var _w = w || 0;`
5675. `Object.defineProperty(this, "w", {`
5676. `enumerable: true,`
5677. `get: function() {`
5678. `return _w;`
5679. `},`
5680. `set: function(value) {`
5681. `if (!isNaN(value)) {`
5682. `_w = parseFloat(value);`
5683. `}`
5684. `}`
5685. `});`
5687. `var _h = h || 0;`
5688. `Object.defineProperty(this, "h", {`
5689. `enumerable: true,`
5690. `get: function() {`
5691. `return _h;`
5692. `},`
5693. `set: function(value) {`
5694. `if (!isNaN(value)) {`
5695. `_h = parseFloat(value);`
5696. `}`
5697. `}`
5698. `});`
5700. `return this;`
5701. `};`
5703. `/**`
5704. `* FormObject/RenderTarget`
5705. `*/`
5707. `var RenderTarget = function() {`
5708. `this.page = page;`
5709. `this.currentPage = currentPage;`
5710. `this.pages = pages.slice(0);`
5711. `this.pagesContext = pagesContext.slice(0);`
5712. `this.x = pageX;`
5713. `this.y = pageY;`
5714. `this.matrix = pageMatrix;`
5715. `this.width = getPageWidth(currentPage);`
5716. `this.height = getPageHeight(currentPage);`
5717. `this.outputDestination = outputDestination;`
5719. `this.id = ""; // set by endFormObject()`
5720. `this.objectNumber = -1; // will be set by putXObject()`
5721. `};`
5723. `RenderTarget.prototype.restore = function() {`
5724. `page = this.page;`
5725. `currentPage = this.currentPage;`
5726. `pagesContext = this.pagesContext;`
5727. `pages = this.pages;`
5728. `pageX = this.x;`
5729. `pageY = this.y;`
5730. `pageMatrix = this.matrix;`
5731. `setPageWidth(currentPage, this.width);`
5732. `setPageHeight(currentPage, this.height);`
5733. `outputDestination = this.outputDestination;`
5734. `};`
5736. `var beginNewRenderTarget = function(x, y, width, height, matrix) {`
5737. `// save current state`
5738. `renderTargetStack.push(new RenderTarget());`
5740. `// clear pages`
5741. `page = currentPage = 0;`
5742. `pages = [];`
5743. `pageX = x;`
5744. `pageY = y;`
5746. `pageMatrix = matrix;`
5748. `beginPage([width, height]);`
5749. `};`
5751. `var endFormObject = function(key) {`
5752. `// only add it if it is not already present (the keys provided by the user must be unique!)`
5753. `if (renderTargetMap[key]) {`
5754. `renderTargetStack.pop().restore();`
5755. `return;`
5756. `}`
5758. `// save the created xObject`
5759. `var newXObject = new RenderTarget();`
5761. `var xObjectId = "Xo" + (Object.keys(renderTargets).length + 1).toString(10);`
5762. `newXObject.id = xObjectId;`
5764. `renderTargetMap[key] = xObjectId;`
5765. `renderTargets[xObjectId] = newXObject;`
5767. `events.publish("addFormObject", newXObject);`
5769. `// restore state from stack`
5770. `renderTargetStack.pop().restore();`
5771. `};`
5773. `/**`
5774. `* Starts a new pdf form object, which means that all consequent draw calls target a new independent object`
5775. `* until {@link endFormObject} is called. The created object can be referenced and drawn later using`
5776. `* {@link doFormObject}. Nested form objects are possible.`
5777. `* x, y, width, height set the bounding box that is used to clip the content.`
5778. `*`
5779. `* @param {number} x`
5780. `* @param {number} y`
5781. `* @param {number} width`
5782. `* @param {number} height`
5783. `* @param {Matrix} matrix The matrix that will be applied to convert the form objects coordinate system to`
5784. `* the parent's.`
5785. `* @function`
5786. `* @returns {jsPDF}`
5787. `* @memberof jsPDF#`
5788. `* @name beginFormObject`
5789. `*/`
5790. `API.beginFormObject = function(x, y, width, height, matrix) {`
5791. `// The user can set the output target to a new form object. Nested form objects are possible.`
5792. `// Currently, they use the resource dictionary of the surrounding stream. This should be changed, as`
5793. `// the PDF-Spec states:`
5794. `// "In PDF 1.2 and later versions, form XObjects may be independent of the content streams in which`
5795. `// they appear, and this is strongly recommended although not requiredIn PDF 1.2 and later versions,`
5796. `// form XObjects may be independent of the content streams in which they appear, and this is strongly`
5797. `// recommended although not required"`
5798. `beginNewRenderTarget(x, y, width, height, matrix);`
5799. `return this;`
5800. `};`
5802. `/**`
5803. `* Completes and saves the form object.`
5804. `* @param {String} key The key by which this form object can be referenced.`
5805. `* @function`
5806. `* @returns {jsPDF}`
5807. `* @memberof jsPDF#`
5808. `* @name endFormObject`
5809. `*/`
5810. `API.endFormObject = function(key) {`
5811. `endFormObject(key);`
5812. `return this;`
5813. `};`
5815. `/**`
5816. `* Draws the specified form object by referencing to the respective pdf XObject created with`
5817. `* {@link API.beginFormObject} and {@link endFormObject}.`
5818. `* The location is determined by matrix.`
5819. `*`
5820. `* @param {String} key The key to the form object.`
5821. `* @param {Matrix} matrix The matrix applied before drawing the form object.`
5822. `* @function`
5823. `* @returns {jsPDF}`
5824. `* @memberof jsPDF#`
5825. `* @name doFormObject`
5826. `*/`
5827. `API.doFormObject = function(key, matrix) {`
5828. `var xObject = renderTargets[renderTargetMap[key]];`
5829. `out("q");`
5830. `out(matrix.toString() + " cm");`
5831. `out("/" + xObject.id + " Do");`
5832. `out("Q");`
5833. `return this;`
5834. `};`
5836. `/**`
5837. `* Returns the form object specified by key.`
5838. `* @param key {String}`
5839. `* @returns {{x: number, y: number, width: number, height: number, matrix: Matrix}}`
5840. `* @function`
5841. `* @returns {jsPDF}`
5842. `* @memberof jsPDF#`
5843. `* @name getFormObject`
5844. `*/`
5845. `API.getFormObject = function(key) {`
5846. `var xObject = renderTargets[renderTargetMap[key]];`
5847. `return {`
5848. `x: xObject.x,`
5849. `y: xObject.y,`
5850. `width: xObject.width,`
5851. `height: xObject.height,`
5852. `matrix: xObject.matrix`
5853. `};`
5854. `};`
5856. `/**`
5857. `* Saves as PDF document. An alias of jsPDF.output('save', 'filename.pdf').`
5858. `* Uses FileSaver.js-method saveAs.`
5859. `*`
5860. `* @memberof jsPDF#`
5861. `* @name save`
5862. `* @function`
5863. `* @instance`
5864. `* @param {string} filename The filename including extension.`
5865. `* @param {Object} options An Object with additional options, possible options: 'returnPromise'.`
5866. `* @returns {jsPDF|Promise} jsPDF-instance */`
5867. `API.save = function(filename, options) {`
5868. `filename = filename || "generated.pdf";`
5870. `options = options || {};`
5871. `options.returnPromise = options.returnPromise || false;`
5873. `// @if MODULE_FORMAT!='cjs'`
5874. `if (options.returnPromise === false) {`
5875. `saveAs(getBlob(buildDocument()), filename);`
5876. `if (typeof saveAs.unload === "function") {`
5877. `if (globalObject.setTimeout) {`
5878. `setTimeout(saveAs.unload, 911);`
5879. `}`
5880. `}`
5881. `return this;`
5882. `} else {`
5883. `return new Promise(function(resolve, reject) {`
5884. `try {`
5885. `var result = saveAs(getBlob(buildDocument()), filename);`
5886. `if (typeof saveAs.unload === "function") {`
5887. `if (globalObject.setTimeout) {`
5888. `setTimeout(saveAs.unload, 911);`
5889. `}`
5890. `}`
5891. `resolve(result);`
5892. `} catch (e) {`
5893. `reject(e.message);`
5894. `}`
5895. `});`
5896. `}`
5897. `// @endif`
5899. `// @if MODULE_FORMAT='cjs'`
5900. `// eslint-disable-next-line no-unreachable`
5901. `var fs = require("fs");`
5902. `var buffer = Buffer.from(getArrayBuffer(buildDocument()));`
5903. `if (options.returnPromise === false) {`
5904. `fs.writeFileSync(filename, buffer);`
5905. `} else {`
5906. `return new Promise(function(resolve, reject) {`
5907. `fs.writeFile(filename, buffer, function(err) {`
5908. `if (err) {`
5909. `reject(err);`
5910. `} else {`
5911. `resolve();`
5912. `}`
5913. `});`
5914. `});`
5915. `}`
5916. `// @endif`
5917. `};`
5919. `// applying plugins (more methods) ON TOP of built-in API.`
5920. `// this is intentional as we allow plugins to override`
5921. `// built-ins`
5922. `for (var plugin in jsPDF.API) {`
5923. `if (jsPDF.API.hasOwnProperty(plugin)) {`
5924. `if (plugin === "events" && jsPDF.API.events.length) {`
5925. `(function(events, newEvents) {`
5926. `// jsPDF.API.events is a JS Array of Arrays`
5927. `// where each Array is a pair of event name, handler`
5928. `// Events were added by plugins to the jsPDF instantiator.`
5929. `// These are always added to the new instance and some ran`
5930. `// during instantiation.`
5931. `var eventname, handler_and_args, i;`
5933. `for (i = newEvents.length - 1; i !== -1; i--) {`
5934. `// subscribe takes 3 args: 'topic', function, runonce_flag`
5935. `// if undefined, runonce is false.`
5936. `// users can attach callback directly,`
5937. `// or they can attach an array with [callback, runonce_flag]`
5938. `// that's what the "apply" magic is for below.`
5939. `eventname = newEvents[i][0];`
5940. `handler_and_args = newEvents[i][1];`
5941. `events.subscribe.apply(`
5942. `events,`
5943. `[eventname].concat(`
5944. `typeof handler_and_args === "function"`
5945. `? [handler_and_args]`
5946. `: handler_and_args`
5947. `)`
5948. `);`
5949. `}`
5950. `})(events, jsPDF.API.events);`
5951. `} else {`
5952. `API[plugin] = jsPDF.API[plugin];`
5953. `}`
5954. `}`
5955. `}`
5957. `var getPageWidth = (API.getPageWidth = function(pageNumber) {`
5958. `pageNumber = pageNumber || currentPage;`
5959. `return (`
5960. `(pagesContext[pageNumber].mediaBox.topRightX -`
5961. `pagesContext[pageNumber].mediaBox.bottomLeftX) /`
5962. `scaleFactor`
5963. `);`
5964. `});`
5966. `var setPageWidth = (API.setPageWidth = function(pageNumber, value) {`
5967. `pagesContext[pageNumber].mediaBox.topRightX =`
5968. `value * scaleFactor + pagesContext[pageNumber].mediaBox.bottomLeftX;`
5969. `});`
5971. `var getPageHeight = (API.getPageHeight = function(pageNumber) {`
5972. `pageNumber = pageNumber || currentPage;`
5973. `return (`
5974. `(pagesContext[pageNumber].mediaBox.topRightY -`
5975. `pagesContext[pageNumber].mediaBox.bottomLeftY) /`
5976. `scaleFactor`
5977. `);`
5978. `});`
5980. `var setPageHeight = (API.setPageHeight = function(pageNumber, value) {`
5981. `pagesContext[pageNumber].mediaBox.topRightY =`
5982. `value * scaleFactor + pagesContext[pageNumber].mediaBox.bottomLeftY;`
5983. `});`
5985. `/**`
5986. `* Object exposing internal API to plugins`
5987. `* @public`
5988. `* @ignore`
5989. `*/`
5990. `API.internal = {`
5991. `pdfEscape: pdfEscape,`
5992. `getStyle: getStyle,`
5993. `getFont: getFontEntry,`
5994. `getFontSize: getFontSize,`
5995. `getCharSpace: getCharSpace,`
5996. `getTextColor: getTextColor,`
5997. `getLineHeight: getLineHeight,`
5998. `getLineHeightFactor: getLineHeightFactor,`
5999. `getLineWidth: getLineWidth,`
6000. `write: write,`
6001. `getHorizontalCoordinate: getHorizontalCoordinate,`
6002. `getVerticalCoordinate: getVerticalCoordinate,`
6003. `getCoordinateString: getHorizontalCoordinateString,`
6004. `getVerticalCoordinateString: getVerticalCoordinateString,`
6005. `collections: {},`
6006. `newObject: newObject,`
6007. `newAdditionalObject: newAdditionalObject,`
6008. `newObjectDeferred: newObjectDeferred,`
6009. `newObjectDeferredBegin: newObjectDeferredBegin,`
6010. `getFilters: getFilters,`
6011. `putStream: putStream,`
6012. `events: events,`
6013. `scaleFactor: scaleFactor,`
6014. `pageSize: {`
6015. `getWidth: function() {`
6016. `return getPageWidth(currentPage);`
6017. `},`
6018. `setWidth: function(value) {`
6019. `setPageWidth(currentPage, value);`
6020. `},`
6021. `getHeight: function() {`
6022. `return getPageHeight(currentPage);`
6023. `},`
6024. `setHeight: function(value) {`
6025. `setPageHeight(currentPage, value);`
6026. `}`
6027. `},`
6028. `encryptionOptions: encryptionOptions,`
6029. `encryption: encryption,`
6030. `getEncryptor: getEncryptor,`
6031. `output: output,`
6032. `getNumberOfPages: getNumberOfPages,`
6033. `pages: pages,`
6034. `out: out,`
6035. `f2: f2,`
6036. `f3: f3,`
6037. `getPageInfo: getPageInfo,`
6038. `getPageInfoByObjId: getPageInfoByObjId,`
6039. `getCurrentPageInfo: getCurrentPageInfo,`
6040. `getPDFVersion: getPdfVersion,`
6041. `Point: Point,`
6042. `Rectangle: Rectangle,`
6043. `Matrix: Matrix,`
6044. `hasHotfix: hasHotfix //Expose the hasHotfix check so plugins can also check them.`
6045. `};`
6047. `Object.defineProperty(API.internal.pageSize, "width", {`
6048. `get: function() {`
6049. `return getPageWidth(currentPage);`
6050. `},`
6051. `set: function(value) {`
6052. `setPageWidth(currentPage, value);`
6053. `},`
6054. `enumerable: true,`
6055. `configurable: true`
6056. `});`
6057. `Object.defineProperty(API.internal.pageSize, "height", {`
6058. `get: function() {`
6059. `return getPageHeight(currentPage);`
6060. `},`
6061. `set: function(value) {`
6062. `setPageHeight(currentPage, value);`
6063. `},`
6064. `enumerable: true,`
6065. `configurable: true`
6066. `});`
6068. `//////////////////////////////////////////////////////`
6069. `// continuing initialization of jsPDF Document object`
6070. `//////////////////////////////////////////////////////`
6071. `// Add the first page automatically`
6072. `addFonts.call(API, standardFonts);`
6073. `activeFontKey = "F1";`
6074. `_addPage(format, orientation);`
6076. `events.publish("initialized");`
6077. `return API;`
6078. `}`
6080. `/**`
6081. `* jsPDF.API is a STATIC property of jsPDF class.`
6082. `* jsPDF.API is an object you can add methods and properties to.`
6083. `* The methods / properties you add will show up in new jsPDF objects.`
6084. `*`
6085. `* One property is prepopulated. It is the 'events' Object. Plugin authors can add topics,`
6086. `* callbacks to this object. These will be reassigned to all new instances of jsPDF.`
6087. `*`
6088. `* @static`
6089. `* @public`
6090. `* @memberof jsPDF#`
6091. `* @name API`
6092. `*`
6093. `* @example`
6094. `* jsPDF.API.mymethod = function(){`
6095. `* // 'this' will be ref to internal API object. see jsPDF source`
6096. `* // , so you can refer to built-in methods like so:`
6097. `* // this.line(....)`
6098. `* // this.text(....)`
6099. `* }`
6100. `* var pdfdoc = new jsPDF()`
6101. `* pdfdoc.mymethod() // <- !!!!!!`
6102. `*/`
6103. `jsPDF.API = {`
6104. `events: []`
6105. `};`
6106. `/**`
6107. `* The version of jsPDF.`
6108. `* @name version`
6109. `* @type {string}`
6110. `* @memberof jsPDF#`
6111. `*/`
6112. `jsPDF.version = "0.0.0";`
6114. `export { jsPDF, ShadingPattern, TilingPattern, GState };`
6115. `export default jsPDF;`
---
# modules/svg.js - Documentation
modules/svg.js
==============
1. `/** @license`
2. `* Copyright (c) 2012 Willow Systems Corporation, https://github.com/willowsystems`
3. `*`
4. `* Permission is hereby granted, free of charge, to any person obtaining`
5. `* a copy of this software and associated documentation files (the`
6. `* "Software"), to deal in the Software without restriction, including`
7. `* without limitation the rights to use, copy, modify, merge, publish,`
8. `* distribute, sublicense, and/or sell copies of the Software, and to`
9. `* permit persons to whom the Software is furnished to do so, subject to`
10. `* the following conditions:`
11. `*`
12. `* The above copyright notice and this permission notice shall be`
13. `* included in all copies or substantial portions of the Software.`
14. `*`
15. `* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,`
16. `* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF`
17. `* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND`
18. `* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE`
19. `* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION`
20. `* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION`
21. `* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.`
22. `* ====================================================================`
23. `*/`
25. `import { jsPDF } from "../jspdf.js";`
26. `import { console } from "../libs/console.js";`
27. `import { globalObject } from "../libs/globalObject.js";`
29. `/**`
30. `* jsPDF SVG plugin`
31. `*`
32. `* @name svg`
33. `* @module`
34. `*/`
35. `(function(jsPDFAPI) {`
36. `"use strict";`
38. `function loadCanvg() {`
39. `return (function() {`
40. `if (globalObject["canvg"]) {`
41. `return Promise.resolve(globalObject["canvg"]);`
42. `}`
44. `// @if MODULE_FORMAT='es'`
45. `return import("canvg");`
46. `// @endif`
48. `// @if MODULE_FORMAT!='es'`
49. `if (typeof exports === "object" && typeof module !== "undefined") {`
50. `return new Promise(function(resolve, reject) {`
51. `try {`
52. `resolve(require("canvg"));`
53. `} catch (e) {`
54. `reject(e);`
55. `}`
56. `});`
57. `}`
58. `if (typeof define === "function" && define.amd) {`
59. `return new Promise(function(resolve, reject) {`
60. `try {`
61. `require(["canvg"], resolve);`
62. `} catch (e) {`
63. `reject(e);`
64. `}`
65. `});`
66. `}`
67. `return Promise.reject(new Error("Could not load canvg"));`
68. `// @endif`
69. `})()`
70. `.catch(function(e) {`
71. `return Promise.reject(new Error("Could not load canvg: " + e));`
72. `})`
73. `.then(function(canvg) {`
74. `return canvg.default ? canvg.default : canvg;`
75. `});`
76. `}`
78. `/**`
79. `* Parses SVG XML and saves it as image into the PDF.`
80. `*`
81. `* Depends on canvas-element and canvg`
82. `*`
83. `* @name addSvgAsImage`
84. `* @public`
85. `* @function`
86. `* @param {string} SVG-Data as Text`
87. `* @param {number} x Coordinate (in units declared at inception of PDF document) against left edge of the page`
88. `* @param {number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page`
89. `* @param {number} width of SVG-Image (in units declared at inception of PDF document)`
90. `* @param {number} height of SVG-Image (in units declared at inception of PDF document)`
91. `* @param {string} alias of SVG-Image (if used multiple times)`
92. `* @param {string} compression of the generated JPEG, can have the values 'NONE', 'FAST', 'MEDIUM' and 'SLOW'`
93. `* @param {number} rotation of the image in degrees (0-359)`
94. `*`
95. `* @returns jsPDF jsPDF-instance`
96. `*/`
97. `jsPDFAPI.addSvgAsImage = function(`
98. `svg,`
99. `x,`
100. `y,`
101. `w,`
102. `h,`
103. `alias,`
104. `compression,`
105. `rotation`
106. `) {`
107. `if (isNaN(x) || isNaN(y)) {`
108. `console.error("jsPDF.addSvgAsImage: Invalid coordinates", arguments);`
109. `throw new Error("Invalid coordinates passed to jsPDF.addSvgAsImage");`
110. `}`
112. `if (isNaN(w) || isNaN(h)) {`
113. `console.error("jsPDF.addSvgAsImage: Invalid measurements", arguments);`
114. `throw new Error(`
115. `"Invalid measurements (width and/or height) passed to jsPDF.addSvgAsImage"`
116. `);`
117. `}`
119. `var canvas = document.createElement("canvas");`
120. `canvas.width = w;`
121. `canvas.height = h;`
122. `var ctx = canvas.getContext("2d");`
123. `ctx.fillStyle = "#fff"; /// set white fill style`
124. `ctx.fillRect(0, 0, canvas.width, canvas.height);`
126. `var options = {`
127. `ignoreMouse: true,`
128. `ignoreAnimation: true,`
129. `ignoreDimensions: true`
130. `};`
131. `var doc = this;`
132. `return loadCanvg()`
133. `.then(`
134. `function(canvg) {`
135. `return canvg.fromString(ctx, svg, options);`
136. `},`
137. `function() {`
138. `return Promise.reject(new Error("Could not load canvg."));`
139. `}`
140. `)`
141. `.then(function(instance) {`
142. `return instance.render(options);`
143. `})`
144. `.then(function() {`
145. `doc.addImage(`
146. `canvas.toDataURL("image/jpeg", 1.0),`
147. `x,`
148. `y,`
149. `w,`
150. `h,`
151. `compression,`
152. `rotation`
153. `);`
154. `});`
155. `};`
156. `})(jsPDF.API);`
---
# modules/webp_support.js - Documentation
modules/webp\_support.js
========================
1. `/**`
2. `* @license`
3. `* Copyright (c) 2019 Aras Abbasi`
4. `*`
5. `* Licensed under the MIT License.`
6. `* http://opensource.org/licenses/mit-license`
7. `*/`
9. `import { jsPDF } from "../jspdf.js";`
10. `import { JPEGEncoder } from "../libs/JPEGEncoder.js";`
11. `import { WebPDecoder } from "../libs/WebPDecoder.js";`
13. `/**`
14. `* jsPDF webp Support PlugIn`
15. `*`
16. `* @name webp_support`
17. `* @module`
18. `*/`
19. `(function(jsPDFAPI) {`
20. `"use strict";`
22. `jsPDFAPI.processWEBP = function(imageData, index, alias, compression) {`
23. `var reader = new WebPDecoder(imageData, false);`
24. `var width = reader.width,`
25. `height = reader.height;`
26. `var qu = 100;`
27. `var pixels = reader.getData();`
29. `var rawImageData = {`
30. `data: pixels,`
31. `width: width,`
32. `height: height`
33. `};`
35. `var encoder = new JPEGEncoder(qu);`
36. `var data = encoder.encode(rawImageData, qu);`
37. `return jsPDFAPI.processJPEG.call(this, data, index, alias, compression);`
38. `};`
39. `})(jsPDF.API);`
---
# modules/vfs.js - Documentation
modules/vfs.js
==============
1. `/**`
2. `* @license`
3. `* jsPDF virtual FileSystem functionality`
4. `*`
5. `* Licensed under the MIT License.`
6. `* http://opensource.org/licenses/mit-license`
7. `*/`
9. `import { jsPDF } from "../jspdf.js";`
11. `/**`
12. `* Use the vFS to handle files`
13. `*`
14. `* @name vFS`
15. `* @module`
16. `*/`
17. `(function(jsPDFAPI) {`
18. `"use strict";`
20. `var _initializeVFS = function() {`
21. `if (typeof this.internal.vFS === "undefined") {`
22. `this.internal.vFS = {};`
23. `}`
24. `return true;`
25. `};`
27. `/**`
28. `* Check if the file exists in the vFS`
29. `*`
30. `* @name existsFileInVFS`
31. `* @function`
32. `* @param {string} Possible filename in the vFS.`
33. `* @returns {boolean}`
34. `* @example`
35. `* doc.existsFileInVFS("someFile.txt");`
36. `*/`
37. `jsPDFAPI.existsFileInVFS = function(filename) {`
38. `_initializeVFS.call(this);`
39. `return typeof this.internal.vFS[filename] !== "undefined";`
40. `};`
42. `/**`
43. `* Add a file to the vFS`
44. `*`
45. `* @name addFileToVFS`
46. `* @function`
47. `* @param {string} filename The name of the file which should be added.`
48. `* @param {string} filecontent The content of the file.`
49. `* @returns {jsPDF}`
50. `* @example`
51. `* doc.addFileToVFS("someFile.txt", "BADFACE1");`
52. `*/`
53. `jsPDFAPI.addFileToVFS = function(filename, filecontent) {`
54. `_initializeVFS.call(this);`
55. `this.internal.vFS[filename] = filecontent;`
56. `return this;`
57. `};`
59. `/**`
60. `* Get the file from the vFS`
61. `*`
62. `* @name getFileFromVFS`
63. `* @function`
64. `* @param {string} The name of the file which gets requested.`
65. `* @returns {string}`
66. `* @example`
67. `* doc.getFileFromVFS("someFile.txt");`
68. `*/`
69. `jsPDFAPI.getFileFromVFS = function(filename) {`
70. `_initializeVFS.call(this);`
72. `if (typeof this.internal.vFS[filename] !== "undefined") {`
73. `return this.internal.vFS[filename];`
74. `}`
75. `return null;`
76. `};`
77. `})(jsPDF.API);`
---
# modules/total_pages.js - Documentation
modules/total\_pages.js
=======================
1. `/**`
2. `* @license`
3. `* ====================================================================`
4. `* Copyright (c) 2013 Eduardo Menezes de Morais, eduardo.morais@usp.br`
5. `*`
6. `* Permission is hereby granted, free of charge, to any person obtaining`
7. `* a copy of this software and associated documentation files (the`
8. `* "Software"), to deal in the Software without restriction, including`
9. `* without limitation the rights to use, copy, modify, merge, publish,`
10. `* distribute, sublicense, and/or sell copies of the Software, and to`
11. `* permit persons to whom the Software is furnished to do so, subject to`
12. `* the following conditions:`
13. `*`
14. `* The above copyright notice and this permission notice shall be`
15. `* included in all copies or substantial portions of the Software.`
16. `*`
17. `* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,`
18. `* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF`
19. `* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND`
20. `* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE`
21. `* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION`
22. `* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION`
23. `* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.`
24. `* ====================================================================`
25. `*/`
27. `import { jsPDF } from "../jspdf.js";`
29. `/**`
30. `* jsPDF total_pages plugin`
31. `* @name total_pages`
32. `* @module`
33. `*/`
34. `(function(jsPDFAPI) {`
35. `"use strict";`
36. `/**`
37. `* @name putTotalPages`
38. `* @function`
39. `* @param {string} pageExpression Regular Expression`
40. `* @returns {jsPDF} jsPDF-instance`
41. `*/`
43. `jsPDFAPI.putTotalPages = function(pageExpression) {`
44. `"use strict";`
46. `var replaceExpression;`
47. `var totalNumberOfPages = 0;`
48. `if (parseInt(this.internal.getFont().id.substr(1), 10) < 15) {`
49. `replaceExpression = new RegExp(pageExpression, "g");`
50. `totalNumberOfPages = this.internal.getNumberOfPages();`
51. `} else {`
52. `replaceExpression = new RegExp(`
53. `this.pdfEscape16(pageExpression, this.internal.getFont()),`
54. `"g"`
55. `);`
56. `totalNumberOfPages = this.pdfEscape16(`
57. `this.internal.getNumberOfPages() + "",`
58. `this.internal.getFont()`
59. `);`
60. `}`
62. `for (var n = 1; n <= this.internal.getNumberOfPages(); n++) {`
63. `for (var i = 0; i < this.internal.pages[n].length; i++) {`
64. `this.internal.pages[n][i] = this.internal.pages[n][i].replace(`
65. `replaceExpression,`
66. `totalNumberOfPages`
67. `);`
68. `}`
69. `}`
71. `return this;`
72. `};`
73. `})(jsPDF.API);`
---
# modules/split_text_to_size.js - Documentation
modules/split\_text\_to\_size.js
================================
1. `/** @license`
2. `* MIT license.`
3. `* Copyright (c) 2012 Willow Systems Corporation, https://github.com/willowsystems`
4. `* 2014 Diego Casorran, https://github.com/diegocr`
5. `*`
6. `* Permission is hereby granted, free of charge, to any person obtaining`
7. `* a copy of this software and associated documentation files (the`
8. `* "Software"), to deal in the Software without restriction, including`
9. `* without limitation the rights to use, copy, modify, merge, publish,`
10. `* distribute, sublicense, and/or sell copies of the Software, and to`
11. `* permit persons to whom the Software is furnished to do so, subject to`
12. `* the following conditions:`
13. `*`
14. `* The above copyright notice and this permission notice shall be`
15. `* included in all copies or substantial portions of the Software.`
16. `*`
17. `* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,`
18. `* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF`
19. `* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND`
20. `* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE`
21. `* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION`
22. `* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION`
23. `* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.`
24. `* ====================================================================`
25. `*/`
27. `import { jsPDF } from "../jspdf.js";`
29. `/**`
30. `* jsPDF split_text_to_size plugin`
31. `*`
32. `* @name split_text_to_size`
33. `* @module`
34. `*/`
35. `(function(API) {`
36. `"use strict";`
37. `/**`
38. `* Returns an array of length matching length of the 'word' string, with each`
39. `* cell occupied by the width of the char in that position.`
40. `*`
41. `* @name getCharWidthsArray`
42. `* @function`
43. `* @param {string} text`
44. `* @param {Object} options`
45. `* @returns {Array}`
46. `*/`
47. `var getCharWidthsArray = (API.getCharWidthsArray = function(text, options) {`
48. `options = options || {};`
50. `var activeFont = options.font || this.internal.getFont();`
51. `var fontSize = options.fontSize || this.internal.getFontSize();`
52. `var charSpace = options.charSpace || this.internal.getCharSpace();`
54. `var widths = options.widths`
55. `? options.widths`
56. `: activeFont.metadata.Unicode.widths;`
57. `var widthsFractionOf = widths.fof ? widths.fof : 1;`
58. `var kerning = options.kerning`
59. `? options.kerning`
60. `: activeFont.metadata.Unicode.kerning;`
61. `var kerningFractionOf = kerning.fof ? kerning.fof : 1;`
62. `var doKerning = options.doKerning === false ? false : true;`
63. `var kerningValue = 0;`
65. `var i;`
66. `var length = text.length;`
67. `var char_code;`
68. `var prior_char_code = 0; //for kerning`
69. `var default_char_width = widths[0] || widthsFractionOf;`
70. `var output = [];`
72. `for (i = 0; i < length; i++) {`
73. `char_code = text.charCodeAt(i);`
75. `if (typeof activeFont.metadata.widthOfString === "function") {`
76. `output.push(`
77. `(activeFont.metadata.widthOfGlyph(`
78. `activeFont.metadata.characterToGlyph(char_code)`
79. `) +`
80. `charSpace * (1000 / fontSize) || 0) / 1000`
81. `);`
82. `} else {`
83. `if (`
84. `doKerning &&`
85. `typeof kerning[char_code] === "object" &&`
86. `!isNaN(parseInt(kerning[char_code][prior_char_code], 10))`
87. `) {`
88. `kerningValue =`
89. `kerning[char_code][prior_char_code] / kerningFractionOf;`
90. `} else {`
91. `kerningValue = 0;`
92. `}`
93. `output.push(`
94. `(widths[char_code] || default_char_width) / widthsFractionOf +`
95. `kerningValue`
96. `);`
97. `}`
98. `prior_char_code = char_code;`
99. `}`
101. `return output;`
102. `});`
104. `/**`
105. `* Returns a widths of string in a given font, if the font size is set as 1 point.`
106. `*`
107. `* In other words, this is "proportional" value. For 1 unit of font size, the length`
108. `* of the string will be that much.`
109. `*`
110. `* Multiply by font size to get actual width in *points*`
111. `* Then divide by 72 to get inches or divide by (72/25.6) to get 'mm' etc.`
112. `*`
113. `* @name getStringUnitWidth`
114. `* @public`
115. `* @function`
116. `* @param {string} text`
117. `* @param {string} options`
118. `* @returns {number} result`
119. `*/`
120. `var getStringUnitWidth = (API.getStringUnitWidth = function(text, options) {`
121. `options = options || {};`
123. `var fontSize = options.fontSize || this.internal.getFontSize();`
124. `var font = options.font || this.internal.getFont();`
125. `var charSpace = options.charSpace || this.internal.getCharSpace();`
126. `var result = 0;`
128. `if (API.processArabic) {`
129. `text = API.processArabic(text);`
130. `}`
132. `if (typeof font.metadata.widthOfString === "function") {`
133. `result =`
134. `font.metadata.widthOfString(text, fontSize, charSpace) / fontSize;`
135. `} else {`
136. `result = getCharWidthsArray`
137. `.apply(this, arguments)`
138. `.reduce(function(pv, cv) {`
139. `return pv + cv;`
140. `}, 0);`
141. `}`
142. `return result;`
143. `});`
145. `/**`
146. `returns array of lines`
147. `*/`
148. `var splitLongWord = function(word, widths_array, firstLineMaxLen, maxLen) {`
149. `var answer = [];`
151. `// 1st, chop off the piece that can fit on the hanging line.`
152. `var i = 0,`
153. `l = word.length,`
154. `workingLen = 0;`
155. `while (i !== l && workingLen + widths_array[i] < firstLineMaxLen) {`
156. `workingLen += widths_array[i];`
157. `i++;`
158. `}`
159. `// this is first line.`
160. `answer.push(word.slice(0, i));`
162. `// 2nd. Split the rest into maxLen pieces.`
163. `var startOfLine = i;`
164. `workingLen = 0;`
165. `while (i !== l) {`
166. `if (workingLen + widths_array[i] > maxLen) {`
167. `answer.push(word.slice(startOfLine, i));`
168. `workingLen = 0;`
169. `startOfLine = i;`
170. `}`
171. `workingLen += widths_array[i];`
172. `i++;`
173. `}`
174. `if (startOfLine !== i) {`
175. `answer.push(word.slice(startOfLine, i));`
176. `}`
178. `return answer;`
179. `};`
181. `// Note, all sizing inputs for this function must be in "font measurement units"`
182. `// By default, for PDF, it's "point".`
183. `var splitParagraphIntoLines = function(text, maxlen, options) {`
184. `// at this time works only on Western scripts, ones with space char`
185. `// separating the words. Feel free to expand.`
187. `if (!options) {`
188. `options = {};`
189. `}`
191. `var line = [],`
192. `lines = [line],`
193. `line_length = options.textIndent || 0,`
194. `separator_length = 0,`
195. `current_word_length = 0,`
196. `word,`
197. `widths_array,`
198. `words = text.split(" "),`
199. `spaceCharWidth = getCharWidthsArray.apply(this, [" ", options])[0],`
200. `i,`
201. `l,`
202. `tmp,`
203. `lineIndent;`
205. `if (options.lineIndent === -1) {`
206. `lineIndent = words[0].length + 2;`
207. `} else {`
208. `lineIndent = options.lineIndent || 0;`
209. `}`
210. `if (lineIndent) {`
211. `var pad = Array(lineIndent).join(" "),`
212. `wrds = [];`
213. `words.map(function(wrd) {`
214. `wrd = wrd.split(/\s*\n/);`
215. `if (wrd.length > 1) {`
216. `wrds = wrds.concat(`
217. `wrd.map(function(wrd, idx) {`
218. `return (idx && wrd.length ? "\n" : "") + wrd;`
219. `})`
220. `);`
221. `} else {`
222. `wrds.push(wrd[0]);`
223. `}`
224. `});`
225. `words = wrds;`
226. `lineIndent = getStringUnitWidth.apply(this, [pad, options]);`
227. `}`
229. `for (i = 0, l = words.length; i < l; i++) {`
230. `var force = 0;`
232. `word = words[i];`
233. `if (lineIndent && word[0] == "\n") {`
234. `word = word.substr(1);`
235. `force = 1;`
236. `}`
237. `widths_array = getCharWidthsArray.apply(this, [word, options]);`
238. `current_word_length = widths_array.reduce(function(pv, cv) {`
239. `return pv + cv;`
240. `}, 0);`
242. `if (`
243. `line_length + separator_length + current_word_length > maxlen ||`
244. `force`
245. `) {`
246. `if (current_word_length > maxlen) {`
247. `// this happens when you have space-less long URLs for example.`
248. `// we just chop these to size. We do NOT insert hiphens`
249. `tmp = splitLongWord.apply(this, [`\
250. `word,`\
251. `widths_array,`\
252. `maxlen - (line_length + separator_length),`\
253. `maxlen`\
254. `]);`
255. `// first line we add to existing line object`
256. `line.push(tmp.shift()); // it's ok to have extra space indicator there`
257. `// last line we make into new line object`
258. `line = [tmp.pop()];`
259. `// lines in the middle we apped to lines object as whole lines`
260. `while (tmp.length) {`
261. `lines.push([tmp.shift()]); // single fragment occupies whole line`
262. `}`
263. `current_word_length = widths_array`
264. `.slice(word.length - (line[0] ? line[0].length : 0))`
265. `.reduce(function(pv, cv) {`
266. `return pv + cv;`
267. `}, 0);`
268. `} else {`
269. `// just put it on a new line`
270. `line = [word];`
271. `}`
273. `// now we attach new line to lines`
274. `lines.push(line);`
275. `line_length = current_word_length + lineIndent;`
276. `separator_length = spaceCharWidth;`
277. `} else {`
278. `line.push(word);`
280. `line_length += separator_length + current_word_length;`
281. `separator_length = spaceCharWidth;`
282. `}`
283. `}`
285. `var postProcess;`
286. `if (lineIndent) {`
287. `postProcess = function(ln, idx) {`
288. `return (idx ? pad : "") + ln.join(" ");`
289. `};`
290. `} else {`
291. `postProcess = function(ln) {`
292. `return ln.join(" ");`
293. `};`
294. `}`
296. `return lines.map(postProcess);`
297. `};`
299. `/**`
300. `* Splits a given string into an array of strings. Uses 'size' value`
301. `* (in measurement units declared as default for the jsPDF instance)`
302. `* and the font's "widths" and "Kerning" tables, where available, to`
303. `* determine display length of a given string for a given font.`
304. `*`
305. `* We use character's 100% of unit size (height) as width when Width`
306. `* table or other default width is not available.`
307. `*`
308. `* @name splitTextToSize`
309. `* @public`
310. `* @function`
311. `* @param {string} text Unencoded, regular JavaScript (Unicode, UTF-16 / UCS-2) string.`
312. `* @param {number} size Nominal number, measured in units default to this instance of jsPDF.`
313. `* @param {Object} options Optional flags needed for chopper to do the right thing.`
314. `* @returns {Array} array Array with strings chopped to size.`
315. `*/`
316. `API.splitTextToSize = function(text, maxlen, options) {`
317. `"use strict";`
319. `options = options || {};`
321. `var fsize = options.fontSize || this.internal.getFontSize(),`
322. `newOptions = function(options) {`
323. `var widths = {`
324. `0: 1`
325. `},`
326. `kerning = {};`
328. `if (!options.widths || !options.kerning) {`
329. `var f = this.internal.getFont(options.fontName, options.fontStyle),`
330. `encoding = "Unicode";`
331. `// NOT UTF8, NOT UTF16BE/LE, NOT UCS2BE/LE`
332. `// Actual JavaScript-native String's 16bit char codes used.`
333. `// no multi-byte logic here`
335. `if (f.metadata[encoding]) {`
336. `return {`
337. `widths: f.metadata[encoding].widths || widths,`
338. `kerning: f.metadata[encoding].kerning || kerning`
339. `};`
340. `} else {`
341. `return {`
342. `font: f.metadata,`
343. `fontSize: this.internal.getFontSize(),`
344. `charSpace: this.internal.getCharSpace()`
345. `};`
346. `}`
347. `} else {`
348. `return {`
349. `widths: options.widths,`
350. `kerning: options.kerning`
351. `};`
352. `}`
353. `}.call(this, options);`
355. `// first we split on end-of-line chars`
356. `var paragraphs;`
357. `if (Array.isArray(text)) {`
358. `paragraphs = text;`
359. `} else {`
360. `paragraphs = String(text).split(/\r?\n/);`
361. `}`
363. `// now we convert size (max length of line) into "font size units"`
364. `// at present time, the "font size unit" is always 'point'`
365. `// 'proportional' means, "in proportion to font size"`
366. `var fontUnit_maxLen = (1.0 * this.internal.scaleFactor * maxlen) / fsize;`
367. `// at this time, fsize is always in "points" regardless of the default measurement unit of the doc.`
368. `// this may change in the future?`
369. `// until then, proportional_maxlen is likely to be in 'points'`
371. `// If first line is to be indented (shorter or longer) than maxLen`
372. `// we indicate that by using CSS-style "text-indent" option.`
373. `// here it's in font units too (which is likely 'points')`
374. `// it can be negative (which makes the first line longer than maxLen)`
375. `newOptions.textIndent = options.textIndent`
376. `? (options.textIndent * 1.0 * this.internal.scaleFactor) / fsize`
377. `: 0;`
378. `newOptions.lineIndent = options.lineIndent;`
380. `var i,`
381. `l,`
382. `output = [];`
383. `for (i = 0, l = paragraphs.length; i < l; i++) {`
384. `output = output.concat(`
385. `splitParagraphIntoLines.apply(this, [`\
386. `paragraphs[i],`\
387. `fontUnit_maxLen,`\
388. `newOptions`\
389. `])`
390. `);`
391. `}`
393. `return output;`
394. `};`
395. `})(jsPDF.API);`
---
# modules/xmp_metadata.js - Documentation
modules/xmp\_metadata.js
========================
1. `/** ====================================================================`
2. `* @license`
3. `* jsPDF XMP metadata plugin`
4. `* Copyright (c) 2016 Jussi Utunen, u-jussi@suomi24.fi`
5. `*`
6. `* Permission is hereby granted, free of charge, to any person obtaining`
7. `* a copy of this software and associated documentation files (the`
8. `* "Software"), to deal in the Software without restriction, including`
9. `* without limitation the rights to use, copy, modify, merge, publish,`
10. `* distribute, sublicense, and/or sell copies of the Software, and to`
11. `* permit persons to whom the Software is furnished to do so, subject to`
12. `* the following conditions:`
13. `*`
14. `* The above copyright notice and this permission notice shall be`
15. `* included in all copies or substantial portions of the Software.`
16. `*`
17. `* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,`
18. `* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF`
19. `* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND`
20. `* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE`
21. `* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION`
22. `* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION`
23. `* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.`
24. `* ====================================================================`
25. `*/`
27. `import { jsPDF } from "../jspdf.js";`
29. `/**`
30. `* @name xmp_metadata`
31. `* @module`
32. `*/`
33. `(function(jsPDFAPI) {`
34. `"use strict";`
36. `var postPutResources = function() {`
37. `var xmpmeta_beginning = '';`
38. `var rdf_beginning =`
39. `'';`
42. `var rdf_ending = "";`
43. `var xmpmeta_ending = "";`
44. `var utf8_xmpmeta_beginning = unescape(`
45. `encodeURIComponent(xmpmeta_beginning)`
46. `);`
47. `var utf8_rdf_beginning = unescape(encodeURIComponent(rdf_beginning));`
48. `var utf8_metadata = unescape(`
49. `encodeURIComponent(this.internal.__metadata__.metadata)`
50. `);`
51. `var utf8_rdf_ending = unescape(encodeURIComponent(rdf_ending));`
52. `var utf8_xmpmeta_ending = unescape(encodeURIComponent(xmpmeta_ending));`
54. `var total_len =`
55. `utf8_rdf_beginning.length +`
56. `utf8_metadata.length +`
57. `utf8_rdf_ending.length +`
58. `utf8_xmpmeta_beginning.length +`
59. `utf8_xmpmeta_ending.length;`
61. `this.internal.__metadata__.metadata_object_number = this.internal.newObject();`
62. `this.internal.write(`
63. `"<< /Type /Metadata /Subtype /XML /Length " + total_len + " >>"`
64. `);`
65. `this.internal.write("stream");`
66. `this.internal.write(`
67. `utf8_xmpmeta_beginning +`
68. `utf8_rdf_beginning +`
69. `utf8_metadata +`
70. `utf8_rdf_ending +`
71. `utf8_xmpmeta_ending`
72. `);`
73. `this.internal.write("endstream");`
74. `this.internal.write("endobj");`
75. `};`
77. `var putCatalog = function() {`
78. `if (this.internal.__metadata__.metadata_object_number) {`
79. `this.internal.write(`
80. `"/Metadata " +`
81. `this.internal.__metadata__.metadata_object_number +`
82. `" 0 R"`
83. `);`
84. `}`
85. `};`
87. `/**`
88. `* Adds XMP formatted metadata to PDF`
89. `*`
90. `* @name addMetadata`
91. `* @function`
92. `* @param {String} metadata The actual metadata to be added. The metadata shall be stored as XMP simple value. Note that if the metadata string contains XML markup characters "<", ">" or "&", those characters should be written using XML entities.`
93. `* @param {String} namespaceuri Sets the namespace URI for the metadata. Last character should be slash or hash.`
94. `* @returns {jsPDF} jsPDF-instance`
95. `*/`
96. `jsPDFAPI.addMetadata = function(metadata, namespaceuri) {`
97. `if (typeof this.internal.__metadata__ === "undefined") {`
98. `this.internal.__metadata__ = {`
99. `metadata: metadata,`
100. `namespaceuri: namespaceuri || "http://jspdf.default.namespaceuri/"`
101. `};`
102. `this.internal.events.subscribe("putCatalog", putCatalog);`
104. `this.internal.events.subscribe("postPutResources", postPutResources);`
105. `}`
106. `return this;`
107. `};`
108. `})(jsPDF.API);`
---
# modules/standard_fonts_metrics.js - Documentation
modules/standard\_fonts\_metrics.js
===================================
1. `/** @license`
2. `jsPDF standard_fonts_metrics plugin`
3. `* Copyright (c) 2012 Willow Systems Corporation, https://github.com/willowsystems`
4. `* MIT license.`
5. `* Permission is hereby granted, free of charge, to any person obtaining`
6. `* a copy of this software and associated documentation files (the`
7. `* "Software"), to deal in the Software without restriction, including`
8. `* without limitation the rights to use, copy, modify, merge, publish,`
9. `* distribute, sublicense, and/or sell copies of the Software, and to`
10. `* permit persons to whom the Software is furnished to do so, subject to`
11. `* the following conditions:`
12. `*`
13. `* The above copyright notice and this permission notice shall be`
14. `* included in all copies or substantial portions of the Software.`
15. `*`
16. `* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,`
17. `* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF`
18. `* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND`
19. `* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE`
20. `* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION`
21. `* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION`
22. `* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.`
23. `* ====================================================================`
24. `*/`
26. `import { jsPDF } from "../jspdf.js";`
28. `/**`
29. `* This file adds the standard font metrics to jsPDF.`
30. `*`
31. `* Font metrics data is reprocessed derivative of contents of`
32. `* "Font Metrics for PDF Core 14 Fonts" package, which exhibits the following copyright and license:`
33. `*`
34. `* Copyright (c) 1989, 1990, 1991, 1992, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.`
35. `*`
36. `* This file and the 14 PostScript(R) AFM files it accompanies may be used,`
37. `* copied, and distributed for any purpose and without charge, with or without`
38. `* modification, provided that all copyright notices are retained; that the AFM`
39. `* files are not distributed without this file; that all modifications to this`
40. `* file or any of the AFM files are prominently noted in the modified file(s);`
41. `* and that this paragraph is not modified. Adobe Systems has no responsibility`
42. `* or obligation to support the use of the AFM files.`
43. `*`
44. `* @name standard_fonts_metrics`
45. `* @module`
46. `*/`
48. `(function(API) {`
49. `"use strict";`
50. `API.__fontmetrics__ = API.__fontmetrics__ || {};`
52. `var decoded = "0123456789abcdef",`
53. `encoded = "klmnopqrstuvwxyz",`
54. `mappingUncompress = {},`
55. `mappingCompress = {};`
57. `for (var i = 0; i < encoded.length; i++) {`
58. `mappingUncompress[encoded[i]] = decoded[i];`
59. `mappingCompress[decoded[i]] = encoded[i];`
60. `}`
62. `var hex = function(value) {`
63. `return "0x" + parseInt(value, 10).toString(16);`
64. `};`
66. `var compress = (API.__fontmetrics__.compress = function(data) {`
67. `var vals = ["{"];`
68. `var value, keystring, valuestring, numberprefix;`
70. `for (var key in data) {`
71. `value = data[key];`
73. `if (!isNaN(parseInt(key, 10))) {`
74. `key = parseInt(key, 10);`
75. `keystring = hex(key).slice(2);`
76. `keystring =`
77. `keystring.slice(0, -1) + mappingCompress[keystring.slice(-1)];`
78. `} else {`
79. `keystring = "'" + key + "'";`
80. `}`
82. `if (typeof value == "number") {`
83. `if (value < 0) {`
84. `valuestring = hex(value).slice(3);`
85. `numberprefix = "-";`
86. `} else {`
87. `valuestring = hex(value).slice(2);`
88. `numberprefix = "";`
89. `}`
90. `valuestring =`
91. `numberprefix +`
92. `valuestring.slice(0, -1) +`
93. `mappingCompress[valuestring.slice(-1)];`
94. `} else {`
95. `if (typeof value === "object") {`
96. `valuestring = compress(value);`
97. `} else {`
98. `throw new Error(`
99. `"Don't know what to do with value type " + typeof value + "."`
100. `);`
101. `}`
102. `}`
103. `vals.push(keystring + valuestring);`
104. `}`
105. `vals.push("}");`
106. `return vals.join("");`
107. `});`
109. `/**`
110. `* Uncompresses data compressed into custom, base16-like format.`
111. `*`
112. `* @public`
113. `* @function`
114. `* @param`
115. `* @returns {Type}`
116. `*/`
117. `var uncompress = (API.__fontmetrics__.uncompress = function(data) {`
118. `if (typeof data !== "string") {`
119. `throw new Error("Invalid argument passed to uncompress.");`
120. `}`
122. `var output = {},`
123. `sign = 1,`
124. `stringparts, // undef. will be [] in string mode`
125. `activeobject = output,`
126. `parentchain = [],`
127. `parent_key_pair,`
128. `keyparts = "",`
129. `valueparts = "",`
130. `key, // undef. will be Truthy when Key is resolved.`
131. `datalen = data.length - 1, // stripping ending }`
132. `ch;`
134. `for (var i = 1; i < datalen; i += 1) {`
135. `// - { } ' are special.`
137. `ch = data[i];`
139. `if (ch == "'") {`
140. `if (stringparts) {`
141. `// end of string mode`
142. `key = stringparts.join("");`
143. `stringparts = undefined;`
144. `} else {`
145. `// start of string mode`
146. `stringparts = [];`
147. `}`
148. `} else if (stringparts) {`
149. `stringparts.push(ch);`
150. `} else if (ch == "{") {`
151. `// start of object`
152. `parentchain.push([activeobject, key]);`
153. `activeobject = {};`
154. `key = undefined;`
155. `} else if (ch == "}") {`
156. `// end of object`
157. `parent_key_pair = parentchain.pop();`
158. `parent_key_pair[0][parent_key_pair[1]] = activeobject;`
159. `key = undefined;`
160. `activeobject = parent_key_pair[0];`
161. `} else if (ch == "-") {`
162. `sign = -1;`
163. `} else {`
164. `// must be number`
165. `if (key === undefined) {`
166. `if (mappingUncompress.hasOwnProperty(ch)) {`
167. `keyparts += mappingUncompress[ch];`
168. `key = parseInt(keyparts, 16) * sign;`
169. `sign = +1;`
170. `keyparts = "";`
171. `} else {`
172. `keyparts += ch;`
173. `}`
174. `} else {`
175. `if (mappingUncompress.hasOwnProperty(ch)) {`
176. `valueparts += mappingUncompress[ch];`
177. `activeobject[key] = parseInt(valueparts, 16) * sign;`
178. `sign = +1;`
179. `key = undefined;`
180. `valueparts = "";`
181. `} else {`
182. `valueparts += ch;`
183. `}`
184. `}`
185. `}`
186. `}`
187. `return output;`
188. `});`
190. `// encoding = 'Unicode'`
191. `// NOT UTF8, NOT UTF16BE/LE, NOT UCS2BE/LE. NO clever BOM behavior`
192. `// Actual 16bit char codes used.`
193. `// no multi-byte logic here`
195. `// Unicode characters to WinAnsiEncoding:`
196. `// {402: 131, 8211: 150, 8212: 151, 8216: 145, 8217: 146, 8218: 130, 8220: 147, 8221: 148, 8222: 132, 8224: 134, 8225: 135, 8226: 149, 8230: 133, 8364: 128, 8240:137, 8249: 139, 8250: 155, 710: 136, 8482: 153, 338: 140, 339: 156, 732: 152, 352: 138, 353: 154, 376: 159, 381: 142, 382: 158}`
197. `// as you can see, all Unicode chars are outside of 0-255 range. No char code conflicts.`
198. `// this means that you can give Win cp1252 encoded strings to jsPDF for rendering directly`
199. `// as well as give strings with some (supported by these fonts) Unicode characters and`
200. `// these will be mapped to win cp1252`
201. `// for example, you can send char code (cp1252) 0x80 or (unicode) 0x20AC, getting "Euro" glyph displayed in both cases.`
203. `var encodingBlock = {`
204. `codePages: ["WinAnsiEncoding"],`
205. `WinAnsiEncoding: uncompress(`
206. `"{19m8n201n9q201o9r201s9l201t9m201u8m201w9n201x9o201y8o202k8q202l8r202m9p202q8p20aw8k203k8t203t8v203u9v2cq8s212m9t15m8w15n9w2dw9s16k8u16l9u17s9z17x8y17y9y}"`
207. `)`
208. `};`
209. `var encodings = {`
210. `Unicode: {`
211. `Courier: encodingBlock,`
212. `"Courier-Bold": encodingBlock,`
213. `"Courier-BoldOblique": encodingBlock,`
214. `"Courier-Oblique": encodingBlock,`
215. `Helvetica: encodingBlock,`
216. `"Helvetica-Bold": encodingBlock,`
217. `"Helvetica-BoldOblique": encodingBlock,`
218. `"Helvetica-Oblique": encodingBlock,`
219. `"Times-Roman": encodingBlock,`
220. `"Times-Bold": encodingBlock,`
221. `"Times-BoldItalic": encodingBlock,`
222. `"Times-Italic": encodingBlock`
223. `// , 'Symbol'`
224. `// , 'ZapfDingbats'`
225. `}`
226. `};`
228. `var fontMetrics = {`
229. `Unicode: {`
230. `// all sizing numbers are n/fontMetricsFractionOf = one font size unit`
231. `// this means that if fontMetricsFractionOf = 1000, and letter A's width is 476, it's`
232. `// width is 476/1000 or 47.6% of its height (regardless of font size)`
233. `// At this time this value applies to "widths" and "kerning" numbers.`
235. `// char code 0 represents "default" (average) width - use it for chars missing in this table.`
236. `// key 'fof' represents the "fontMetricsFractionOf" value`
238. `"Courier-Oblique": uncompress(`
239. `"{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"`
240. `),`
241. `"Times-BoldItalic": uncompress(`
242. `"{'widths'{k3o2q4ycx2r201n3m201o6o201s2l201t2l201u2l201w3m201x3m201y3m2k1t2l2r202m2n2n3m2o3m2p5n202q6o2r1w2s2l2t2l2u3m2v3t2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v2l3w3t3x3t3y3t3z3m4k5n4l4m4m4m4n4m4o4s4p4m4q4m4r4s4s4y4t2r4u3m4v4m4w3x4x5t4y4s4z4s5k3x5l4s5m4m5n3r5o3x5p4s5q4m5r5t5s4m5t3x5u3x5v2l5w1w5x2l5y3t5z3m6k2l6l3m6m3m6n2w6o3m6p2w6q2l6r3m6s3r6t1w6u1w6v3m6w1w6x4y6y3r6z3m7k3m7l3m7m2r7n2r7o1w7p3r7q2w7r4m7s3m7t2w7u2r7v2n7w1q7x2n7y3t202l3mcl4mal2ram3man3mao3map3mar3mas2lat4uau1uav3maw3way4uaz2lbk2sbl3t'fof'6obo2lbp3tbq3mbr1tbs2lbu1ybv3mbz3mck4m202k3mcm4mcn4mco4mcp4mcq5ycr4mcs4mct4mcu4mcv4mcw2r2m3rcy2rcz2rdl4sdm4sdn4sdo4sdp4sdq4sds4sdt4sdu4sdv4sdw4sdz3mek3mel3mem3men3meo3mep3meq4ser2wes2wet2weu2wev2wew1wex1wey1wez1wfl3rfm3mfn3mfo3mfp3mfq3mfr3tfs3mft3rfu3rfv3rfw3rfz2w203k6o212m6o2dw2l2cq2l3t3m3u2l17s3x19m3m}'kerning'{cl{4qu5kt5qt5rs17ss5ts}201s{201ss}201t{cks4lscmscnscoscpscls2wu2yu201ts}201x{2wu2yu}2k{201ts}2w{4qx5kx5ou5qx5rs17su5tu}2x{17su5tu5ou}2y{4qx5kx5ou5qx5rs17ss5ts}'fof'-6ofn{17sw5tw5ou5qw5rs}7t{cksclscmscnscoscps4ls}3u{17su5tu5os5qs}3v{17su5tu5os5qs}7p{17su5tu}ck{4qu5kt5qt5rs17ss5ts}4l{4qu5kt5qt5rs17ss5ts}cm{4qu5kt5qt5rs17ss5ts}cn{4qu5kt5qt5rs17ss5ts}co{4qu5kt5qt5rs17ss5ts}cp{4qu5kt5qt5rs17ss5ts}6l{4qu5ou5qw5rt17su5tu}5q{ckuclucmucnucoucpu4lu}5r{ckuclucmucnucoucpu4lu}7q{cksclscmscnscoscps4ls}6p{4qu5ou5qw5rt17sw5tw}ek{4qu5ou5qw5rt17su5tu}el{4qu5ou5qw5rt17su5tu}em{4qu5ou5qw5rt17su5tu}en{4qu5ou5qw5rt17su5tu}eo{4qu5ou5qw5rt17su5tu}ep{4qu5ou5qw5rt17su5tu}es{17ss5ts5qs4qu}et{4qu5ou5qw5rt17sw5tw}eu{4qu5ou5qw5rt17ss5ts}ev{17ss5ts5qs4qu}6z{17sw5tw5ou5qw5rs}fm{17sw5tw5ou5qw5rs}7n{201ts}fo{17sw5tw5ou5qw5rs}fp{17sw5tw5ou5qw5rs}fq{17sw5tw5ou5qw5rs}7r{cksclscmscnscoscps4ls}fs{17sw5tw5ou5qw5rs}ft{17su5tu}fu{17su5tu}fv{17su5tu}fw{17su5tu}fz{cksclscmscnscoscps4ls}}}"`
243. `),`
244. `"Helvetica-Bold": uncompress(`
245. `"{'widths'{k3s2q4scx1w201n3r201o6o201s1w201t1w201u1w201w3m201x3m201y3m2k1w2l2l202m2n2n3r2o3r2p5t202q6o2r1s2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v2l3w3u3x3u3y3u3z3x4k6l4l4s4m4s4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3r4v4s4w3x4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v2l5w1w5x2l5y3u5z3r6k2l6l3r6m3x6n3r6o3x6p3r6q2l6r3x6s3x6t1w6u1w6v3r6w1w6x5t6y3x6z3x7k3x7l3x7m2r7n3r7o2l7p3x7q3r7r4y7s3r7t3r7u3m7v2r7w1w7x2r7y3u202l3rcl4sal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3xbq3rbr1wbs2lbu2obv3rbz3xck4s202k3rcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw1w2m2zcy1wcz1wdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3res3ret3reu3rev3rew1wex1wey1wez1wfl3xfm3xfn3xfo3xfp3xfq3xfr3ufs3xft3xfu3xfv3xfw3xfz3r203k6o212m6o2dw2l2cq2l3t3r3u2l17s4m19m3r}'kerning'{cl{4qs5ku5ot5qs17sv5tv}201t{2ww4wy2yw}201w{2ks}201x{2ww4wy2yw}2k{201ts201xs}2w{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}2x{5ow5qs}2y{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}'fof'-6o7p{17su5tu5ot}ck{4qs5ku5ot5qs17sv5tv}4l{4qs5ku5ot5qs17sv5tv}cm{4qs5ku5ot5qs17sv5tv}cn{4qs5ku5ot5qs17sv5tv}co{4qs5ku5ot5qs17sv5tv}cp{4qs5ku5ot5qs17sv5tv}6l{17st5tt5os}17s{2kwclvcmvcnvcovcpv4lv4wwckv}5o{2kucltcmtcntcotcpt4lt4wtckt}5q{2ksclscmscnscoscps4ls4wvcks}5r{2ks4ws}5t{2kwclvcmvcnvcovcpv4lv4wwckv}eo{17st5tt5os}fu{17su5tu5ot}6p{17ss5ts}ek{17st5tt5os}el{17st5tt5os}em{17st5tt5os}en{17st5tt5os}6o{201ts}ep{17st5tt5os}es{17ss5ts}et{17ss5ts}eu{17ss5ts}ev{17ss5ts}6z{17su5tu5os5qt}fm{17su5tu5os5qt}fn{17su5tu5os5qt}fo{17su5tu5os5qt}fp{17su5tu5os5qt}fq{17su5tu5os5qt}fs{17su5tu5os5qt}ft{17su5tu5ot}7m{5os}fv{17su5tu5ot}fw{17su5tu5ot}}}"`
246. `),`
247. `Courier: uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),`
248. `"Courier-BoldOblique": uncompress(`
249. `"{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"`
250. `),`
251. `"Times-Bold": uncompress(`
252. `"{'widths'{k3q2q5ncx2r201n3m201o6o201s2l201t2l201u2l201w3m201x3m201y3m2k1t2l2l202m2n2n3m2o3m2p6o202q6o2r1w2s2l2t2l2u3m2v3t2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v2l3w3t3x3t3y3t3z3m4k5x4l4s4m4m4n4s4o4s4p4m4q3x4r4y4s4y4t2r4u3m4v4y4w4m4x5y4y4s4z4y5k3x5l4y5m4s5n3r5o4m5p4s5q4s5r6o5s4s5t4s5u4m5v2l5w1w5x2l5y3u5z3m6k2l6l3m6m3r6n2w6o3r6p2w6q2l6r3m6s3r6t1w6u2l6v3r6w1w6x5n6y3r6z3m7k3r7l3r7m2w7n2r7o2l7p3r7q3m7r4s7s3m7t3m7u2w7v2r7w1q7x2r7y3o202l3mcl4sal2lam3man3mao3map3mar3mas2lat4uau1yav3maw3tay4uaz2lbk2sbl3t'fof'6obo2lbp3rbr1tbs2lbu2lbv3mbz3mck4s202k3mcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw2r2m3rcy2rcz2rdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3rek3mel3mem3men3meo3mep3meq4ser2wes2wet2weu2wev2wew1wex1wey1wez1wfl3rfm3mfn3mfo3mfp3mfq3mfr3tfs3mft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3m3u2l17s4s19m3m}'kerning'{cl{4qt5ks5ot5qy5rw17sv5tv}201t{cks4lscmscnscoscpscls4wv}2k{201ts}2w{4qu5ku7mu5os5qx5ru17su5tu}2x{17su5tu5ou5qs}2y{4qv5kv7mu5ot5qz5ru17su5tu}'fof'-6o7t{cksclscmscnscoscps4ls}3u{17su5tu5os5qu}3v{17su5tu5os5qu}fu{17su5tu5ou5qu}7p{17su5tu5ou5qu}ck{4qt5ks5ot5qy5rw17sv5tv}4l{4qt5ks5ot5qy5rw17sv5tv}cm{4qt5ks5ot5qy5rw17sv5tv}cn{4qt5ks5ot5qy5rw17sv5tv}co{4qt5ks5ot5qy5rw17sv5tv}cp{4qt5ks5ot5qy5rw17sv5tv}6l{17st5tt5ou5qu}17s{ckuclucmucnucoucpu4lu4wu}5o{ckuclucmucnucoucpu4lu4wu}5q{ckzclzcmzcnzcozcpz4lz4wu}5r{ckxclxcmxcnxcoxcpx4lx4wu}5t{ckuclucmucnucoucpu4lu4wu}7q{ckuclucmucnucoucpu4lu}6p{17sw5tw5ou5qu}ek{17st5tt5qu}el{17st5tt5ou5qu}em{17st5tt5qu}en{17st5tt5qu}eo{17st5tt5qu}ep{17st5tt5ou5qu}es{17ss5ts5qu}et{17sw5tw5ou5qu}eu{17sw5tw5ou5qu}ev{17ss5ts5qu}6z{17sw5tw5ou5qu5rs}fm{17sw5tw5ou5qu5rs}fn{17sw5tw5ou5qu5rs}fo{17sw5tw5ou5qu5rs}fp{17sw5tw5ou5qu5rs}fq{17sw5tw5ou5qu5rs}7r{cktcltcmtcntcotcpt4lt5os}fs{17sw5tw5ou5qu5rs}ft{17su5tu5ou5qu}7m{5os}fv{17su5tu5ou5qu}fw{17su5tu5ou5qu}fz{cksclscmscnscoscps4ls}}}"`
253. `),`
254. `Symbol: uncompress(`
255. `"{'widths'{k3uaw4r19m3m2k1t2l2l202m2y2n3m2p5n202q6o3k3m2s2l2t2l2v3r2w1t3m3m2y1t2z1wbk2sbl3r'fof'6o3n3m3o3m3p3m3q3m3r3m3s3m3t3m3u1w3v1w3w3r3x3r3y3r3z2wbp3t3l3m5v2l5x2l5z3m2q4yfr3r7v3k7w1o7x3k}'kerning'{'fof'-6o}}"`
256. `),`
257. `Helvetica: uncompress(`
258. `"{'widths'{k3p2q4mcx1w201n3r201o6o201s1q201t1q201u1q201w2l201x2l201y2l2k1w2l1w202m2n2n3r2o3r2p5t202q6o2r1n2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v1w3w3u3x3u3y3u3z3r4k6p4l4m4m4m4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3m4v4m4w3r4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v1w5w1w5x1w5y2z5z3r6k2l6l3r6m3r6n3m6o3r6p3r6q1w6r3r6s3r6t1q6u1q6v3m6w1q6x5n6y3r6z3r7k3r7l3r7m2l7n3m7o1w7p3r7q3m7r4s7s3m7t3m7u3m7v2l7w1u7x2l7y3u202l3rcl4mal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3rbr1wbs2lbu2obv3rbz3xck4m202k3rcm4mcn4mco4mcp4mcq6ocr4scs4mct4mcu4mcv4mcw1w2m2ncy1wcz1wdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3mes3ret3reu3rev3rew1wex1wey1wez1wfl3rfm3rfn3rfo3rfp3rfq3rfr3ufs3xft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3r3u1w17s4m19m3r}'kerning'{5q{4wv}cl{4qs5kw5ow5qs17sv5tv}201t{2wu4w1k2yu}201x{2wu4wy2yu}17s{2ktclucmucnu4otcpu4lu4wycoucku}2w{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}2x{17sy5ty5oy5qs}2y{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}'fof'-6o7p{17sv5tv5ow}ck{4qs5kw5ow5qs17sv5tv}4l{4qs5kw5ow5qs17sv5tv}cm{4qs5kw5ow5qs17sv5tv}cn{4qs5kw5ow5qs17sv5tv}co{4qs5kw5ow5qs17sv5tv}cp{4qs5kw5ow5qs17sv5tv}6l{17sy5ty5ow}do{17st5tt}4z{17st5tt}7s{fst}dm{17st5tt}dn{17st5tt}5o{ckwclwcmwcnwcowcpw4lw4wv}dp{17st5tt}dq{17st5tt}7t{5ow}ds{17st5tt}5t{2ktclucmucnu4otcpu4lu4wycoucku}fu{17sv5tv5ow}6p{17sy5ty5ow5qs}ek{17sy5ty5ow}el{17sy5ty5ow}em{17sy5ty5ow}en{5ty}eo{17sy5ty5ow}ep{17sy5ty5ow}es{17sy5ty5qs}et{17sy5ty5ow5qs}eu{17sy5ty5ow5qs}ev{17sy5ty5ow5qs}6z{17sy5ty5ow5qs}fm{17sy5ty5ow5qs}fn{17sy5ty5ow5qs}fo{17sy5ty5ow5qs}fp{17sy5ty5qs}fq{17sy5ty5ow5qs}7r{5ow}fs{17sy5ty5ow5qs}ft{17sv5tv5ow}7m{5ow}fv{17sv5tv5ow}fw{17sv5tv5ow}}}"`
259. `),`
260. `"Helvetica-BoldOblique": uncompress(`
261. `"{'widths'{k3s2q4scx1w201n3r201o6o201s1w201t1w201u1w201w3m201x3m201y3m2k1w2l2l202m2n2n3r2o3r2p5t202q6o2r1s2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v2l3w3u3x3u3y3u3z3x4k6l4l4s4m4s4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3r4v4s4w3x4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v2l5w1w5x2l5y3u5z3r6k2l6l3r6m3x6n3r6o3x6p3r6q2l6r3x6s3x6t1w6u1w6v3r6w1w6x5t6y3x6z3x7k3x7l3x7m2r7n3r7o2l7p3x7q3r7r4y7s3r7t3r7u3m7v2r7w1w7x2r7y3u202l3rcl4sal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3xbq3rbr1wbs2lbu2obv3rbz3xck4s202k3rcm4scn4sco4scp4scq6ocr4scs4mct4mcu4mcv4mcw1w2m2zcy1wcz1wdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3res3ret3reu3rev3rew1wex1wey1wez1wfl3xfm3xfn3xfo3xfp3xfq3xfr3ufs3xft3xfu3xfv3xfw3xfz3r203k6o212m6o2dw2l2cq2l3t3r3u2l17s4m19m3r}'kerning'{cl{4qs5ku5ot5qs17sv5tv}201t{2ww4wy2yw}201w{2ks}201x{2ww4wy2yw}2k{201ts201xs}2w{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}2x{5ow5qs}2y{7qs4qu5kw5os5qw5rs17su5tu7tsfzs}'fof'-6o7p{17su5tu5ot}ck{4qs5ku5ot5qs17sv5tv}4l{4qs5ku5ot5qs17sv5tv}cm{4qs5ku5ot5qs17sv5tv}cn{4qs5ku5ot5qs17sv5tv}co{4qs5ku5ot5qs17sv5tv}cp{4qs5ku5ot5qs17sv5tv}6l{17st5tt5os}17s{2kwclvcmvcnvcovcpv4lv4wwckv}5o{2kucltcmtcntcotcpt4lt4wtckt}5q{2ksclscmscnscoscps4ls4wvcks}5r{2ks4ws}5t{2kwclvcmvcnvcovcpv4lv4wwckv}eo{17st5tt5os}fu{17su5tu5ot}6p{17ss5ts}ek{17st5tt5os}el{17st5tt5os}em{17st5tt5os}en{17st5tt5os}6o{201ts}ep{17st5tt5os}es{17ss5ts}et{17ss5ts}eu{17ss5ts}ev{17ss5ts}6z{17su5tu5os5qt}fm{17su5tu5os5qt}fn{17su5tu5os5qt}fo{17su5tu5os5qt}fp{17su5tu5os5qt}fq{17su5tu5os5qt}fs{17su5tu5os5qt}ft{17su5tu5ot}7m{5os}fv{17su5tu5ot}fw{17su5tu5ot}}}"`
262. `),`
263. `ZapfDingbats: uncompress("{'widths'{k4u2k1w'fof'6o}'kerning'{'fof'-6o}}"),`
264. `"Courier-Bold": uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}"),`
265. `"Times-Italic": uncompress(`
266. `"{'widths'{k3n2q4ycx2l201n3m201o5t201s2l201t2l201u2l201w3r201x3r201y3r2k1t2l2l202m2n2n3m2o3m2p5n202q5t2r1p2s2l2t2l2u3m2v4n2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v2l3w4n3x4n3y4n3z3m4k5w4l3x4m3x4n4m4o4s4p3x4q3x4r4s4s4s4t2l4u2w4v4m4w3r4x5n4y4m4z4s5k3x5l4s5m3x5n3m5o3r5p4s5q3x5r5n5s3x5t3r5u3r5v2r5w1w5x2r5y2u5z3m6k2l6l3m6m3m6n2w6o3m6p2w6q1w6r3m6s3m6t1w6u1w6v2w6w1w6x4s6y3m6z3m7k3m7l3m7m2r7n2r7o1w7p3m7q2w7r4m7s2w7t2w7u2r7v2s7w1v7x2s7y3q202l3mcl3xal2ram3man3mao3map3mar3mas2lat4wau1vav3maw4nay4waz2lbk2sbl4n'fof'6obo2lbp3mbq3obr1tbs2lbu1zbv3mbz3mck3x202k3mcm3xcn3xco3xcp3xcq5tcr4mcs3xct3xcu3xcv3xcw2l2m2ucy2lcz2ldl4mdm4sdn4sdo4sdp4sdq4sds4sdt4sdu4sdv4sdw4sdz3mek3mel3mem3men3meo3mep3meq4mer2wes2wet2weu2wev2wew1wex1wey1wez1wfl3mfm3mfn3mfo3mfp3mfq3mfr4nfs3mft3mfu3mfv3mfw3mfz2w203k6o212m6m2dw2l2cq2l3t3m3u2l17s3r19m3m}'kerning'{cl{5kt4qw}201s{201sw}201t{201tw2wy2yy6q-t}201x{2wy2yy}2k{201tw}2w{7qs4qy7rs5ky7mw5os5qx5ru17su5tu}2x{17ss5ts5os}2y{7qs4qy7rs5ky7mw5os5qx5ru17su5tu}'fof'-6o6t{17ss5ts5qs}7t{5os}3v{5qs}7p{17su5tu5qs}ck{5kt4qw}4l{5kt4qw}cm{5kt4qw}cn{5kt4qw}co{5kt4qw}cp{5kt4qw}6l{4qs5ks5ou5qw5ru17su5tu}17s{2ks}5q{ckvclvcmvcnvcovcpv4lv}5r{ckuclucmucnucoucpu4lu}5t{2ks}6p{4qs5ks5ou5qw5ru17su5tu}ek{4qs5ks5ou5qw5ru17su5tu}el{4qs5ks5ou5qw5ru17su5tu}em{4qs5ks5ou5qw5ru17su5tu}en{4qs5ks5ou5qw5ru17su5tu}eo{4qs5ks5ou5qw5ru17su5tu}ep{4qs5ks5ou5qw5ru17su5tu}es{5ks5qs4qs}et{4qs5ks5ou5qw5ru17su5tu}eu{4qs5ks5qw5ru17su5tu}ev{5ks5qs4qs}ex{17ss5ts5qs}6z{4qv5ks5ou5qw5ru17su5tu}fm{4qv5ks5ou5qw5ru17su5tu}fn{4qv5ks5ou5qw5ru17su5tu}fo{4qv5ks5ou5qw5ru17su5tu}fp{4qv5ks5ou5qw5ru17su5tu}fq{4qv5ks5ou5qw5ru17su5tu}7r{5os}fs{4qv5ks5ou5qw5ru17su5tu}ft{17su5tu5qs}fu{17su5tu5qs}fv{17su5tu5qs}fw{17su5tu5qs}}}"`
267. `),`
268. `"Times-Roman": uncompress(`
269. `"{'widths'{k3n2q4ycx2l201n3m201o6o201s2l201t2l201u2l201w2w201x2w201y2w2k1t2l2l202m2n2n3m2o3m2p5n202q6o2r1m2s2l2t2l2u3m2v3s2w1t2x2l2y1t2z1w3k3m3l3m3m3m3n3m3o3m3p3m3q3m3r3m3s3m203t2l203u2l3v1w3w3s3x3s3y3s3z2w4k5w4l4s4m4m4n4m4o4s4p3x4q3r4r4s4s4s4t2l4u2r4v4s4w3x4x5t4y4s4z4s5k3r5l4s5m4m5n3r5o3x5p4s5q4s5r5y5s4s5t4s5u3x5v2l5w1w5x2l5y2z5z3m6k2l6l2w6m3m6n2w6o3m6p2w6q2l6r3m6s3m6t1w6u1w6v3m6w1w6x4y6y3m6z3m7k3m7l3m7m2l7n2r7o1w7p3m7q3m7r4s7s3m7t3m7u2w7v3k7w1o7x3k7y3q202l3mcl4sal2lam3man3mao3map3mar3mas2lat4wau1vav3maw3say4waz2lbk2sbl3s'fof'6obo2lbp3mbq2xbr1tbs2lbu1zbv3mbz2wck4s202k3mcm4scn4sco4scp4scq5tcr4mcs3xct3xcu3xcv3xcw2l2m2tcy2lcz2ldl4sdm4sdn4sdo4sdp4sdq4sds4sdt4sdu4sdv4sdw4sdz3mek2wel2wem2wen2weo2wep2weq4mer2wes2wet2weu2wev2wew1wex1wey1wez1wfl3mfm3mfn3mfo3mfp3mfq3mfr3sfs3mft3mfu3mfv3mfw3mfz3m203k6o212m6m2dw2l2cq2l3t3m3u1w17s4s19m3m}'kerning'{cl{4qs5ku17sw5ou5qy5rw201ss5tw201ws}201s{201ss}201t{ckw4lwcmwcnwcowcpwclw4wu201ts}2k{201ts}2w{4qs5kw5os5qx5ru17sx5tx}2x{17sw5tw5ou5qu}2y{4qs5kw5os5qx5ru17sx5tx}'fof'-6o7t{ckuclucmucnucoucpu4lu5os5rs}3u{17su5tu5qs}3v{17su5tu5qs}7p{17sw5tw5qs}ck{4qs5ku17sw5ou5qy5rw201ss5tw201ws}4l{4qs5ku17sw5ou5qy5rw201ss5tw201ws}cm{4qs5ku17sw5ou5qy5rw201ss5tw201ws}cn{4qs5ku17sw5ou5qy5rw201ss5tw201ws}co{4qs5ku17sw5ou5qy5rw201ss5tw201ws}cp{4qs5ku17sw5ou5qy5rw201ss5tw201ws}6l{17su5tu5os5qw5rs}17s{2ktclvcmvcnvcovcpv4lv4wuckv}5o{ckwclwcmwcnwcowcpw4lw4wu}5q{ckyclycmycnycoycpy4ly4wu5ms}5r{cktcltcmtcntcotcpt4lt4ws}5t{2ktclvcmvcnvcovcpv4lv4wuckv}7q{cksclscmscnscoscps4ls}6p{17su5tu5qw5rs}ek{5qs5rs}el{17su5tu5os5qw5rs}em{17su5tu5os5qs5rs}en{17su5qs5rs}eo{5qs5rs}ep{17su5tu5os5qw5rs}es{5qs}et{17su5tu5qw5rs}eu{17su5tu5qs5rs}ev{5qs}6z{17sv5tv5os5qx5rs}fm{5os5qt5rs}fn{17sv5tv5os5qx5rs}fo{17sv5tv5os5qx5rs}fp{5os5qt5rs}fq{5os5qt5rs}7r{ckuclucmucnucoucpu4lu5os}fs{17sv5tv5os5qx5rs}ft{17ss5ts5qs}fu{17sw5tw5qs}fv{17sw5tw5qs}fw{17ss5ts5qs}fz{ckuclucmucnucoucpu4lu5os5rs}}}"`
270. `),`
271. `"Helvetica-Oblique": uncompress(`
272. `"{'widths'{k3p2q4mcx1w201n3r201o6o201s1q201t1q201u1q201w2l201x2l201y2l2k1w2l1w202m2n2n3r2o3r2p5t202q6o2r1n2s2l2t2l2u2r2v3u2w1w2x2l2y1w2z1w3k3r3l3r3m3r3n3r3o3r3p3r3q3r3r3r3s3r203t2l203u2l3v1w3w3u3x3u3y3u3z3r4k6p4l4m4m4m4n4s4o4s4p4m4q3x4r4y4s4s4t1w4u3m4v4m4w3r4x5n4y4s4z4y5k4m5l4y5m4s5n4m5o3x5p4s5q4m5r5y5s4m5t4m5u3x5v1w5w1w5x1w5y2z5z3r6k2l6l3r6m3r6n3m6o3r6p3r6q1w6r3r6s3r6t1q6u1q6v3m6w1q6x5n6y3r6z3r7k3r7l3r7m2l7n3m7o1w7p3r7q3m7r4s7s3m7t3m7u3m7v2l7w1u7x2l7y3u202l3rcl4mal2lam3ran3rao3rap3rar3ras2lat4tau2pav3raw3uay4taz2lbk2sbl3u'fof'6obo2lbp3rbr1wbs2lbu2obv3rbz3xck4m202k3rcm4mcn4mco4mcp4mcq6ocr4scs4mct4mcu4mcv4mcw1w2m2ncy1wcz1wdl4sdm4ydn4ydo4ydp4ydq4yds4ydt4sdu4sdv4sdw4sdz3xek3rel3rem3ren3reo3rep3req5ter3mes3ret3reu3rev3rew1wex1wey1wez1wfl3rfm3rfn3rfo3rfp3rfq3rfr3ufs3xft3rfu3rfv3rfw3rfz3m203k6o212m6o2dw2l2cq2l3t3r3u1w17s4m19m3r}'kerning'{5q{4wv}cl{4qs5kw5ow5qs17sv5tv}201t{2wu4w1k2yu}201x{2wu4wy2yu}17s{2ktclucmucnu4otcpu4lu4wycoucku}2w{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}2x{17sy5ty5oy5qs}2y{7qs4qz5k1m17sy5ow5qx5rsfsu5ty7tufzu}'fof'-6o7p{17sv5tv5ow}ck{4qs5kw5ow5qs17sv5tv}4l{4qs5kw5ow5qs17sv5tv}cm{4qs5kw5ow5qs17sv5tv}cn{4qs5kw5ow5qs17sv5tv}co{4qs5kw5ow5qs17sv5tv}cp{4qs5kw5ow5qs17sv5tv}6l{17sy5ty5ow}do{17st5tt}4z{17st5tt}7s{fst}dm{17st5tt}dn{17st5tt}5o{ckwclwcmwcnwcowcpw4lw4wv}dp{17st5tt}dq{17st5tt}7t{5ow}ds{17st5tt}5t{2ktclucmucnu4otcpu4lu4wycoucku}fu{17sv5tv5ow}6p{17sy5ty5ow5qs}ek{17sy5ty5ow}el{17sy5ty5ow}em{17sy5ty5ow}en{5ty}eo{17sy5ty5ow}ep{17sy5ty5ow}es{17sy5ty5qs}et{17sy5ty5ow5qs}eu{17sy5ty5ow5qs}ev{17sy5ty5ow5qs}6z{17sy5ty5ow5qs}fm{17sy5ty5ow5qs}fn{17sy5ty5ow5qs}fo{17sy5ty5ow5qs}fp{17sy5ty5qs}fq{17sy5ty5ow5qs}7r{5ow}fs{17sy5ty5ow5qs}ft{17sv5tv5ow}7m{5ow}fv{17sv5tv5ow}fw{17sv5tv5ow}}}"`
273. `)`
274. `}`
275. `};`
277. `/*`
278. `This event handler is fired when a new jsPDF object is initialized`
279. `This event handler appends metrics data to standard fonts within`
280. `that jsPDF instance. The metrics are mapped over Unicode character`
281. `codes, NOT CIDs or other codes matching the StandardEncoding table of the`
282. `standard PDF fonts.`
283. `Future:`
284. `Also included is the encoding maping table, converting Unicode (UCS-2, UTF-16)`
285. `char codes to StandardEncoding character codes. The encoding table is to be used`
286. `somewhere around "pdfEscape" call.`
287. `*/`
288. `API.events.push([`\
289. `"addFont",`\
290. `function(data) {`\
291. `var font = data.font;`\
\
293. `var metrics = fontMetrics["Unicode"][font.postScriptName];`\
294. `if (metrics) {`\
295. `font.metadata["Unicode"] = {};`\
296. `font.metadata["Unicode"].widths = metrics.widths;`\
297. `font.metadata["Unicode"].kerning = metrics.kerning;`\
298. `}`\
\
300. `var encodingBlock = encodings["Unicode"][font.postScriptName];`\
301. `if (encodingBlock) {`\
302. `font.metadata["Unicode"].encoding = encodingBlock;`\
303. `font.encoding = encodingBlock.codePages[0];`\
304. `}`\
305. `}`\
306. `]); // end of adding event handler`
307. `})(jsPDF.API);`
---
# modules/viewerpreferences.js - Documentation
modules/viewerpreferences.js
============================
1. `/**`
2. `* @license`
3. `* jsPDF viewerPreferences Plugin`
4. `* @author Aras Abbasi (github.com/arasabbasi)`
5. `* Licensed under the MIT License.`
6. `* http://opensource.org/licenses/mit-license`
7. `*/`
9. `import { jsPDF } from "../jspdf.js";`
11. `/**`
12. `* Adds the ability to set ViewerPreferences and by thus`
13. `* controlling the way the document is to be presented on the`
14. `* screen or in print.`
15. `* @name viewerpreferences`
16. `* @module`
17. `*/`
18. `(function(jsPDFAPI) {`
19. `"use strict";`
20. `/**`
21. `* Set the ViewerPreferences of the generated PDF`
22. `*`
23. `* @name viewerPreferences`
24. `* @function`
25. `* @public`
26. `* @param {Object} options Array with the ViewerPreferences `
27. `* Example: doc.viewerPreferences({"FitWindow":true}); `
28. `* `
29. `* You can set following preferences: `
30. `* `
31. `* HideToolbar(boolean) `
32. `* Default value: false `
33. `* `
34. `* HideMenubar(boolean) `
35. `* Default value: false. `
36. `* `
37. `* HideWindowUI(boolean) `
38. `* Default value: false. `
39. `* `
40. `* FitWindow(boolean) `
41. `* Default value: false. `
42. `* `
43. `* CenterWindow(boolean) `
44. `* Default value: false `
45. `* `
46. `* DisplayDocTitle(boolean) `
47. `* Default value: false. `
48. `* `
49. `* NonFullScreenPageMode(string) `
50. `* Possible values: UseNone, UseOutlines, UseThumbs, UseOC `
51. `* Default value: UseNone `
52. `* `
53. `* Direction(string) `
54. `* Possible values: L2R, R2L `
55. `* Default value: L2R. `
56. `* `
57. `* ViewArea(string) `
58. `* Possible values: MediaBox, CropBox, TrimBox, BleedBox, ArtBox `
59. `* Default value: CropBox. `
60. `* `
61. `* ViewClip(string) `
62. `* Possible values: MediaBox, CropBox, TrimBox, BleedBox, ArtBox `
63. `* Default value: CropBox `
64. `* `
65. `* PrintArea(string) `
66. `* Possible values: MediaBox, CropBox, TrimBox, BleedBox, ArtBox `
67. `* Default value: CropBox `
68. `* `
69. `* PrintClip(string) `
70. `* Possible values: MediaBox, CropBox, TrimBox, BleedBox, ArtBox `
71. `* Default value: CropBox. `
72. `* `
73. `* PrintScaling(string) `
74. `* Possible values: AppDefault, None `
75. `* Default value: AppDefault. `
76. `* `
77. `* Duplex(string) `
78. `* Possible values: Simplex, DuplexFlipLongEdge, DuplexFlipShortEdge`
79. `* Default value: none `
80. `* `
81. `* PickTrayByPDFSize(boolean) `
82. `* Default value: false `
83. `* `
84. `* PrintPageRange(Array) `
85. `* Example: [[1,5], [7,9]] `
86. `* Default value: as defined by PDF viewer application `
87. `* `
88. `* NumCopies(Number) `
89. `* Possible values: 1, 2, 3, 4, 5 `
90. `* Default value: 1 `
91. `* `
92. `* For more information see the PDF Reference, sixth edition on Page 577`
93. `* @param {boolean} doReset True to reset the settings`
94. `* @function`
95. `* @returns jsPDF jsPDF-instance`
96. `* @example`
97. `* var doc = new jsPDF()`
98. `* doc.text('This is a test', 10, 10)`
99. `* doc.viewerPreferences({'FitWindow': true}, true)`
100. `* doc.save("viewerPreferences.pdf")`
101. `*`
102. `* // Example printing 10 copies, using cropbox, and hiding UI.`
103. `* doc.viewerPreferences({`
104. `* 'HideWindowUI': true,`
105. `* 'PrintArea': 'CropBox',`
106. `* 'NumCopies': 10`
107. `* })`
108. `*/`
109. `jsPDFAPI.viewerPreferences = function(options, doReset) {`
110. `options = options || {};`
111. `doReset = doReset || false;`
113. `var configuration;`
114. `var configurationTemplate = {`
115. `HideToolbar: {`
116. `defaultValue: false,`
117. `value: false,`
118. `type: "boolean",`
119. `explicitSet: false,`
120. `valueSet: [true, false],`
121. `pdfVersion: 1.3`
122. `},`
123. `HideMenubar: {`
124. `defaultValue: false,`
125. `value: false,`
126. `type: "boolean",`
127. `explicitSet: false,`
128. `valueSet: [true, false],`
129. `pdfVersion: 1.3`
130. `},`
131. `HideWindowUI: {`
132. `defaultValue: false,`
133. `value: false,`
134. `type: "boolean",`
135. `explicitSet: false,`
136. `valueSet: [true, false],`
137. `pdfVersion: 1.3`
138. `},`
139. `FitWindow: {`
140. `defaultValue: false,`
141. `value: false,`
142. `type: "boolean",`
143. `explicitSet: false,`
144. `valueSet: [true, false],`
145. `pdfVersion: 1.3`
146. `},`
147. `CenterWindow: {`
148. `defaultValue: false,`
149. `value: false,`
150. `type: "boolean",`
151. `explicitSet: false,`
152. `valueSet: [true, false],`
153. `pdfVersion: 1.3`
154. `},`
155. `DisplayDocTitle: {`
156. `defaultValue: false,`
157. `value: false,`
158. `type: "boolean",`
159. `explicitSet: false,`
160. `valueSet: [true, false],`
161. `pdfVersion: 1.4`
162. `},`
163. `NonFullScreenPageMode: {`
164. `defaultValue: "UseNone",`
165. `value: "UseNone",`
166. `type: "name",`
167. `explicitSet: false,`
168. `valueSet: ["UseNone", "UseOutlines", "UseThumbs", "UseOC"],`
169. `pdfVersion: 1.3`
170. `},`
171. `Direction: {`
172. `defaultValue: "L2R",`
173. `value: "L2R",`
174. `type: "name",`
175. `explicitSet: false,`
176. `valueSet: ["L2R", "R2L"],`
177. `pdfVersion: 1.3`
178. `},`
179. `ViewArea: {`
180. `defaultValue: "CropBox",`
181. `value: "CropBox",`
182. `type: "name",`
183. `explicitSet: false,`
184. `valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"],`
185. `pdfVersion: 1.4`
186. `},`
187. `ViewClip: {`
188. `defaultValue: "CropBox",`
189. `value: "CropBox",`
190. `type: "name",`
191. `explicitSet: false,`
192. `valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"],`
193. `pdfVersion: 1.4`
194. `},`
195. `PrintArea: {`
196. `defaultValue: "CropBox",`
197. `value: "CropBox",`
198. `type: "name",`
199. `explicitSet: false,`
200. `valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"],`
201. `pdfVersion: 1.4`
202. `},`
203. `PrintClip: {`
204. `defaultValue: "CropBox",`
205. `value: "CropBox",`
206. `type: "name",`
207. `explicitSet: false,`
208. `valueSet: ["MediaBox", "CropBox", "TrimBox", "BleedBox", "ArtBox"],`
209. `pdfVersion: 1.4`
210. `},`
211. `PrintScaling: {`
212. `defaultValue: "AppDefault",`
213. `value: "AppDefault",`
214. `type: "name",`
215. `explicitSet: false,`
216. `valueSet: ["AppDefault", "None"],`
217. `pdfVersion: 1.6`
218. `},`
219. `Duplex: {`
220. `defaultValue: "",`
221. `value: "none",`
222. `type: "name",`
223. `explicitSet: false,`
224. `valueSet: [`\
225. `"Simplex",`\
226. `"DuplexFlipShortEdge",`\
227. `"DuplexFlipLongEdge",`\
228. `"none"`\
229. `],`
230. `pdfVersion: 1.7`
231. `},`
232. `PickTrayByPDFSize: {`
233. `defaultValue: false,`
234. `value: false,`
235. `type: "boolean",`
236. `explicitSet: false,`
237. `valueSet: [true, false],`
238. `pdfVersion: 1.7`
239. `},`
240. `PrintPageRange: {`
241. `defaultValue: "",`
242. `value: "",`
243. `type: "array",`
244. `explicitSet: false,`
245. `valueSet: null,`
246. `pdfVersion: 1.7`
247. `},`
248. `NumCopies: {`
249. `defaultValue: 1,`
250. `value: 1,`
251. `type: "integer",`
252. `explicitSet: false,`
253. `valueSet: null,`
254. `pdfVersion: 1.7`
255. `}`
256. `};`
258. `var configurationKeys = Object.keys(configurationTemplate);`
260. `var rangeArray = [];`
261. `var i = 0;`
262. `var j = 0;`
263. `var k = 0;`
264. `var isValid;`
266. `var method;`
267. `var value;`
269. `function arrayContainsElement(array, element) {`
270. `var iterator;`
271. `var result = false;`
273. `for (iterator = 0; iterator < array.length; iterator += 1) {`
274. `if (array[iterator] === element) {`
275. `result = true;`
276. `}`
277. `}`
278. `return result;`
279. `}`
281. `if (this.internal.viewerpreferences === undefined) {`
282. `this.internal.viewerpreferences = {};`
283. `this.internal.viewerpreferences.configuration = JSON.parse(`
284. `JSON.stringify(configurationTemplate)`
285. `);`
286. `this.internal.viewerpreferences.isSubscribed = false;`
287. `}`
288. `configuration = this.internal.viewerpreferences.configuration;`
290. `if (options === "reset" || doReset === true) {`
291. `var len = configurationKeys.length;`
293. `for (k = 0; k < len; k += 1) {`
294. `configuration[configurationKeys[k]].value =`
295. `configuration[configurationKeys[k]].defaultValue;`
296. `configuration[configurationKeys[k]].explicitSet = false;`
297. `}`
298. `}`
300. `if (typeof options === "object") {`
301. `for (method in options) {`
302. `value = options[method];`
303. `if (`
304. `arrayContainsElement(configurationKeys, method) &&`
305. `value !== undefined`
306. `) {`
307. `if (`
308. `configuration[method].type === "boolean" &&`
309. `typeof value === "boolean"`
310. `) {`
311. `configuration[method].value = value;`
312. `} else if (`
313. `configuration[method].type === "name" &&`
314. `arrayContainsElement(configuration[method].valueSet, value)`
315. `) {`
316. `configuration[method].value = value;`
317. `} else if (`
318. `configuration[method].type === "integer" &&`
319. `Number.isInteger(value)`
320. `) {`
321. `configuration[method].value = value;`
322. `} else if (configuration[method].type === "array") {`
323. `for (i = 0; i < value.length; i += 1) {`
324. `isValid = true;`
325. `if (value[i].length === 1 && typeof value[i][0] === "number") {`
326. `rangeArray.push(String(value[i] - 1));`
327. `} else if (value[i].length > 1) {`
328. `for (j = 0; j < value[i].length; j += 1) {`
329. `if (typeof value[i][j] !== "number") {`
330. `isValid = false;`
331. `}`
332. `}`
333. `if (isValid === true) {`
334. `rangeArray.push([value[i][0] - 1, value[i][1] - 1].join(" "));`
335. `}`
336. `}`
337. `}`
338. `configuration[method].value = "[" + rangeArray.join(" ") + "]";`
339. `} else {`
340. `configuration[method].value = configuration[method].defaultValue;`
341. `}`
343. `configuration[method].explicitSet = true;`
344. `}`
345. `}`
346. `}`
348. `if (this.internal.viewerpreferences.isSubscribed === false) {`
349. `this.internal.events.subscribe("putCatalog", function() {`
350. `var pdfDict = [];`
351. `var vPref;`
352. `for (vPref in configuration) {`
353. `if (configuration[vPref].explicitSet === true) {`
354. `if (configuration[vPref].type === "name") {`
355. `pdfDict.push("/" + vPref + " /" + configuration[vPref].value);`
356. `} else {`
357. `pdfDict.push("/" + vPref + " " + configuration[vPref].value);`
358. `}`
359. `}`
360. `}`
361. `if (pdfDict.length !== 0) {`
362. `this.internal.write(`
363. `"/ViewerPreferences\n<<\n" + pdfDict.join("\n") + "\n>>"`
364. `);`
365. `}`
366. `});`
367. `this.internal.viewerpreferences.isSubscribed = true;`
368. `}`
370. `this.internal.viewerpreferences.configuration = configuration;`
371. `return this;`
372. `};`
373. `})(jsPDF.API);`
---
# modules/context2d.js - Documentation
modules/context2d.js
====================
1. `/* eslint-disable no-fallthrough */`
2. `/* eslint-disable no-console */`
3. `/**`
4. `* @license`
5. `* jsPDF Context2D PlugIn Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv`
6. `*`
7. `* Licensed under the MIT License. http://opensource.org/licenses/mit-license`
8. `*/`
10. `import { jsPDF } from "../jspdf.js";`
11. `import { RGBColor } from "../libs/rgbcolor.js";`
12. `import { console } from "../libs/console.js";`
13. `import {`
14. `buildFontFaceMap,`
15. `parseFontFamily,`
16. `resolveFontFace`
17. `} from "../libs/fontFace.js";`
19. `/**`
20. `* This plugin mimics the HTML5 CanvasRenderingContext2D.`
21. `*`
22. `* The goal is to provide a way for current canvas implementations to print directly to a PDF.`
23. `*`
24. `* @name context2d`
25. `* @module`
26. `*/`
27. `(function(jsPDFAPI) {`
28. `"use strict";`
29. `var ContextLayer = function(ctx) {`
30. `ctx = ctx || {};`
31. `this.isStrokeTransparent = ctx.isStrokeTransparent || false;`
32. `this.strokeOpacity = ctx.strokeOpacity || 1;`
33. `this.strokeStyle = ctx.strokeStyle || "#000000";`
34. `this.fillStyle = ctx.fillStyle || "#000000";`
35. `this.isFillTransparent = ctx.isFillTransparent || false;`
36. `this.fillOpacity = ctx.fillOpacity || 1;`
37. `this.font = ctx.font || "10px sans-serif";`
38. `this.textBaseline = ctx.textBaseline || "alphabetic";`
39. `this.textAlign = ctx.textAlign || "left";`
40. `this.lineWidth = ctx.lineWidth || 1;`
41. `this.lineJoin = ctx.lineJoin || "miter";`
42. `this.lineCap = ctx.lineCap || "butt";`
43. `this.path = ctx.path || [];`
44. `this.transform =`
45. `typeof ctx.transform !== "undefined"`
46. `? ctx.transform.clone()`
47. `: new Matrix();`
48. `this.globalCompositeOperation = ctx.globalCompositeOperation || "normal";`
49. `this.globalAlpha = ctx.globalAlpha || 1.0;`
50. `this.clip_path = ctx.clip_path || [];`
51. `this.currentPoint = ctx.currentPoint || new Point();`
52. `this.miterLimit = ctx.miterLimit || 10.0;`
53. `this.lastPoint = ctx.lastPoint || new Point();`
54. `this.lineDashOffset = ctx.lineDashOffset || 0.0;`
55. `this.lineDash = ctx.lineDash || [];`
56. `this.margin = ctx.margin || [0, 0, 0, 0];`
57. `this.prevPageLastElemOffset = ctx.prevPageLastElemOffset || 0;`
59. `this.ignoreClearRect =`
60. `typeof ctx.ignoreClearRect === "boolean" ? ctx.ignoreClearRect : true;`
61. `return this;`
62. `};`
64. `//stub`
65. `var f2,`
66. `getHorizontalCoordinateString,`
67. `getVerticalCoordinateString,`
68. `getHorizontalCoordinate,`
69. `getVerticalCoordinate,`
70. `Point,`
71. `Rectangle,`
72. `Matrix,`
73. `_ctx;`
74. `jsPDFAPI.events.push([`\
75. `"initialized",`\
76. `function() {`\
77. `this.context2d = new Context2D(this);`\
\
79. `f2 = this.internal.f2;`\
80. `getHorizontalCoordinateString = this.internal.getCoordinateString;`\
81. `getVerticalCoordinateString = this.internal.getVerticalCoordinateString;`\
82. `getHorizontalCoordinate = this.internal.getHorizontalCoordinate;`\
83. `getVerticalCoordinate = this.internal.getVerticalCoordinate;`\
84. `Point = this.internal.Point;`\
85. `Rectangle = this.internal.Rectangle;`\
86. `Matrix = this.internal.Matrix;`\
87. `_ctx = new ContextLayer();`\
88. `}`\
89. `]);`
91. `var Context2D = function(pdf) {`
92. `Object.defineProperty(this, "canvas", {`
93. `get: function() {`
94. `return { parentNode: false, style: false };`
95. `}`
96. `});`
98. `var _pdf = pdf;`
99. `Object.defineProperty(this, "pdf", {`
100. `get: function() {`
101. `return _pdf;`
102. `}`
103. `});`
105. `var _pageWrapXEnabled = false;`
106. `/**`
107. `* @name pageWrapXEnabled`
108. `* @type {boolean}`
109. `* @default false`
110. `*/`
111. `Object.defineProperty(this, "pageWrapXEnabled", {`
112. `get: function() {`
113. `return _pageWrapXEnabled;`
114. `},`
115. `set: function(value) {`
116. `_pageWrapXEnabled = Boolean(value);`
117. `}`
118. `});`
120. `var _pageWrapYEnabled = false;`
121. `/**`
122. `* @name pageWrapYEnabled`
123. `* @type {boolean}`
124. `* @default true`
125. `*/`
126. `Object.defineProperty(this, "pageWrapYEnabled", {`
127. `get: function() {`
128. `return _pageWrapYEnabled;`
129. `},`
130. `set: function(value) {`
131. `_pageWrapYEnabled = Boolean(value);`
132. `}`
133. `});`
135. `var _posX = 0;`
136. `/**`
137. `* @name posX`
138. `* @type {number}`
139. `* @default 0`
140. `*/`
141. `Object.defineProperty(this, "posX", {`
142. `get: function() {`
143. `return _posX;`
144. `},`
145. `set: function(value) {`
146. `if (!isNaN(value)) {`
147. `_posX = value;`
148. `}`
149. `}`
150. `});`
152. `var _posY = 0;`
153. `/**`
154. `* @name posY`
155. `* @type {number}`
156. `* @default 0`
157. `*/`
158. `Object.defineProperty(this, "posY", {`
159. `get: function() {`
160. `return _posY;`
161. `},`
162. `set: function(value) {`
163. `if (!isNaN(value)) {`
164. `_posY = value;`
165. `}`
166. `}`
167. `});`
169. `/**`
170. `* Gets or sets the page margin when using auto paging. Has no effect when {@link autoPaging} is off.`
171. `* @name margin`
172. `* @type {number|number[]}`
173. `* @default [0, 0, 0, 0]`
174. `*/`
175. `Object.defineProperty(this, "margin", {`
176. `get: function() {`
177. `return _ctx.margin;`
178. `},`
179. `set: function(value) {`
180. `var margin;`
181. `if (typeof value === "number") {`
182. `margin = [value, value, value, value];`
183. `} else {`
184. `margin = new Array(4);`
185. `margin[0] = value[0];`
186. `margin[1] = value.length >= 2 ? value[1] : margin[0];`
187. `margin[2] = value.length >= 3 ? value[2] : margin[0];`
188. `margin[3] = value.length >= 4 ? value[3] : margin[1];`
189. `}`
190. `_ctx.margin = margin;`
191. `}`
192. `});`
194. `var _autoPaging = false;`
195. `/**`
196. `* Gets or sets the auto paging mode. When auto paging is enabled, the context2d will automatically draw on the`
197. `* next page if a shape or text chunk doesn't fit entirely on the current page. The context2d will create new`
198. `* pages if required.`
199. `*`
200. `* Context2d supports different modes:`
201. `*
`
202. `*
`
203. `* false: Auto paging is disabled.`
204. `*
`
205. `*
`
206. `* true or 'slice': Will cut shapes or text chunks across page breaks. Will possibly`
207. `* slice text in half, making it difficult to read.`
208. `*
`
209. `*
`
210. `* 'text': Trys not to cut text in half across page breaks. Works best for documents consisting`
211. `* mostly of a single column of text.`
212. `*
`
213. `*
`
214. `* @name Context2D#autoPaging`
215. `* @type {boolean|"slice"|"text"}`
216. `* @default false`
217. `*/`
218. `Object.defineProperty(this, "autoPaging", {`
219. `get: function() {`
220. `return _autoPaging;`
221. `},`
222. `set: function(value) {`
223. `_autoPaging = value;`
224. `}`
225. `});`
227. `var lastBreak = 0;`
228. `/**`
229. `* @name lastBreak`
230. `* @type {number}`
231. `* @default 0`
232. `*/`
233. `Object.defineProperty(this, "lastBreak", {`
234. `get: function() {`
235. `return lastBreak;`
236. `},`
237. `set: function(value) {`
238. `lastBreak = value;`
239. `}`
240. `});`
242. `var pageBreaks = [];`
243. `/**`
244. `* Y Position of page breaks.`
245. `* @name pageBreaks`
246. `* @type {number}`
247. `* @default 0`
248. `*/`
249. `Object.defineProperty(this, "pageBreaks", {`
250. `get: function() {`
251. `return pageBreaks;`
252. `},`
253. `set: function(value) {`
254. `pageBreaks = value;`
255. `}`
256. `});`
258. `/**`
259. `* @name ctx`
260. `* @type {object}`
261. `* @default {}`
262. `*/`
263. `Object.defineProperty(this, "ctx", {`
264. `get: function() {`
265. `return _ctx;`
266. `},`
267. `set: function(value) {`
268. `if (value instanceof ContextLayer) {`
269. `_ctx = value;`
270. `}`
271. `}`
272. `});`
274. `/**`
275. `* @name path`
276. `* @type {array}`
277. `* @default []`
278. `*/`
279. `Object.defineProperty(this, "path", {`
280. `get: function() {`
281. `return _ctx.path;`
282. `},`
283. `set: function(value) {`
284. `_ctx.path = value;`
285. `}`
286. `});`
288. `/**`
289. `* @name ctxStack`
290. `* @type {array}`
291. `* @default []`
292. `*/`
293. `var _ctxStack = [];`
294. `Object.defineProperty(this, "ctxStack", {`
295. `get: function() {`
296. `return _ctxStack;`
297. `},`
298. `set: function(value) {`
299. `_ctxStack = value;`
300. `}`
301. `});`
303. `/**`
304. `* Sets or returns the color, gradient, or pattern used to fill the drawing`
305. `*`
306. `* @name fillStyle`
307. `* @default #000000`
308. `* @property {(color|gradient|pattern)} value The color of the drawing. Default value is #000000 `
309. `* A gradient object (linear or radial) used to fill the drawing (not supported by context2d) `
310. `* A pattern object to use to fill the drawing (not supported by context2d)`
311. `*/`
312. `Object.defineProperty(this, "fillStyle", {`
313. `get: function() {`
314. `return this.ctx.fillStyle;`
315. `},`
316. `set: function(value) {`
317. `var rgba;`
318. `rgba = getRGBA(value);`
320. `this.ctx.fillStyle = rgba.style;`
321. `this.ctx.isFillTransparent = rgba.a === 0;`
322. `this.ctx.fillOpacity = rgba.a;`
324. `this.pdf.setFillColor(rgba.r, rgba.g, rgba.b, { a: rgba.a });`
325. `this.pdf.setTextColor(rgba.r, rgba.g, rgba.b, { a: rgba.a });`
326. `}`
327. `});`
329. `/**`
330. `* Sets or returns the color, gradient, or pattern used for strokes`
331. `*`
332. `* @name strokeStyle`
333. `* @default #000000`
334. `* @property {color} color A CSS color value that indicates the stroke color of the drawing. Default value is #000000 (not supported by context2d)`
335. `* @property {gradient} gradient A gradient object (linear or radial) used to create a gradient stroke (not supported by context2d)`
336. `* @property {pattern} pattern A pattern object used to create a pattern stroke (not supported by context2d)`
337. `*/`
338. `Object.defineProperty(this, "strokeStyle", {`
339. `get: function() {`
340. `return this.ctx.strokeStyle;`
341. `},`
342. `set: function(value) {`
343. `var rgba = getRGBA(value);`
345. `this.ctx.strokeStyle = rgba.style;`
346. `this.ctx.isStrokeTransparent = rgba.a === 0;`
347. `this.ctx.strokeOpacity = rgba.a;`
349. `if (rgba.a === 0) {`
350. `this.pdf.setDrawColor(255, 255, 255);`
351. `} else if (rgba.a === 1) {`
352. `this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b);`
353. `} else {`
354. `this.pdf.setDrawColor(rgba.r, rgba.g, rgba.b);`
355. `}`
356. `}`
357. `});`
359. `/**`
360. `* Sets or returns the style of the end caps for a line`
361. `*`
362. `* @name lineCap`
363. `* @default butt`
364. `* @property {(butt|round|square)} lineCap butt A flat edge is added to each end of the line `
365. `* round A rounded end cap is added to each end of the line `
366. `* square A square end cap is added to each end of the line `
367. `*/`
368. `Object.defineProperty(this, "lineCap", {`
369. `get: function() {`
370. `return this.ctx.lineCap;`
371. `},`
372. `set: function(value) {`
373. `if (["butt", "round", "square"].indexOf(value) !== -1) {`
374. `this.ctx.lineCap = value;`
375. `this.pdf.setLineCap(value);`
376. `}`
377. `}`
378. `});`
380. `/**`
381. `* Sets or returns the current line width`
382. `*`
383. `* @name lineWidth`
384. `* @default 1`
385. `* @property {number} lineWidth The current line width, in pixels`
386. `*/`
387. `Object.defineProperty(this, "lineWidth", {`
388. `get: function() {`
389. `return this.ctx.lineWidth;`
390. `},`
391. `set: function(value) {`
392. `if (!isNaN(value)) {`
393. `this.ctx.lineWidth = value;`
394. `this.pdf.setLineWidth(value);`
395. `}`
396. `}`
397. `});`
399. `/**`
400. `* Sets or returns the type of corner created, when two lines meet`
401. `*/`
402. `Object.defineProperty(this, "lineJoin", {`
403. `get: function() {`
404. `return this.ctx.lineJoin;`
405. `},`
406. `set: function(value) {`
407. `if (["bevel", "round", "miter"].indexOf(value) !== -1) {`
408. `this.ctx.lineJoin = value;`
409. `this.pdf.setLineJoin(value);`
410. `}`
411. `}`
412. `});`
414. `/**`
415. `* A number specifying the miter limit ratio in coordinate space units. Zero, negative, Infinity, and NaN values are ignored. The default value is 10.0.`
416. `*`
417. `* @name miterLimit`
418. `* @default 10`
419. `*/`
420. `Object.defineProperty(this, "miterLimit", {`
421. `get: function() {`
422. `return this.ctx.miterLimit;`
423. `},`
424. `set: function(value) {`
425. `if (!isNaN(value)) {`
426. `this.ctx.miterLimit = value;`
427. `this.pdf.setMiterLimit(value);`
428. `}`
429. `}`
430. `});`
432. `Object.defineProperty(this, "textBaseline", {`
433. `get: function() {`
434. `return this.ctx.textBaseline;`
435. `},`
436. `set: function(value) {`
437. `this.ctx.textBaseline = value;`
438. `}`
439. `});`
441. `Object.defineProperty(this, "textAlign", {`
442. `get: function() {`
443. `return this.ctx.textAlign;`
444. `},`
445. `set: function(value) {`
446. `if (["right", "end", "center", "left", "start"].indexOf(value) !== -1) {`
447. `this.ctx.textAlign = value;`
448. `}`
449. `}`
450. `});`
452. `var _fontFaceMap = null;`
454. `function getFontFaceMap(pdf, fontFaces) {`
455. `if (_fontFaceMap === null) {`
456. `var fontMap = pdf.getFontList();`
458. `var convertedFontFaces = convertToFontFaces(fontMap);`
460. `_fontFaceMap = buildFontFaceMap(convertedFontFaces.concat(fontFaces));`
461. `}`
463. `return _fontFaceMap;`
464. `}`
466. `function convertToFontFaces(fontMap) {`
467. `var fontFaces = [];`
469. `Object.keys(fontMap).forEach(function(family) {`
470. `var styles = fontMap[family];`
472. `styles.forEach(function(style) {`
473. `var fontFace = null;`
475. `switch (style) {`
476. `case "bold":`
477. `fontFace = {`
478. `family: family,`
479. `weight: "bold"`
480. `};`
481. `break;`
483. `case "italic":`
484. `fontFace = {`
485. `family: family,`
486. `style: "italic"`
487. `};`
488. `break;`
490. `case "bolditalic":`
491. `fontFace = {`
492. `family: family,`
493. `weight: "bold",`
494. `style: "italic"`
495. `};`
496. `break;`
498. `case "":`
499. `case "normal":`
500. `fontFace = {`
501. `family: family`
502. `};`
503. `break;`
504. `}`
506. `// If font-face is still null here, it is a font with some styling we don't recognize and`
507. `// cannot map or it is a font added via the fontFaces option of .html().`
508. `if (fontFace !== null) {`
509. `fontFace.ref = {`
510. `name: family,`
511. `style: style`
512. `};`
514. `fontFaces.push(fontFace);`
515. `}`
516. `});`
517. `});`
519. `return fontFaces;`
520. `}`
522. `var _fontFaces = null;`
523. `/**`
524. `* A map of available font-faces, as passed in the options of`
525. `* .html(). If set a limited implementation of the font style matching`
526. `* algorithm defined by https://www.w3.org/TR/css-fonts-3/#font-matching-algorithm`
527. `* will be used. If not set it will fallback to previous behavior.`
528. `*/`
530. `Object.defineProperty(this, "fontFaces", {`
531. `get: function() {`
532. `return _fontFaces;`
533. `},`
534. `set: function(value) {`
535. `_fontFaceMap = null;`
536. `_fontFaces = value;`
537. `}`
538. `});`
540. `Object.defineProperty(this, "font", {`
541. `get: function() {`
542. `return this.ctx.font;`
543. `},`
544. `set: function(value) {`
545. `this.ctx.font = value;`
546. `var rx, matches;`
548. `//source: https://stackoverflow.com/a/10136041`
549. `// eslint-disable-next-line no-useless-escape`
550. `rx = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-_,\"\'\sa-z]+?)\s*$/i;`
551. `matches = rx.exec(value);`
552. `if (matches !== null) {`
553. `var fontStyle = matches[1];`
554. `var fontVariant = matches[2];`
555. `var fontWeight = matches[3];`
556. `var fontSize = matches[4];`
557. `var lineHeight = matches[5];`
558. `var fontFamily = matches[6];`
559. `} else {`
560. `return;`
561. `}`
562. `var rxFontSize = /^([.\d]+)((?:%|in|[cem]m|ex|p[ctx]))$/i;`
563. `var fontSizeUnit = rxFontSize.exec(fontSize)[2];`
565. `if ("px" === fontSizeUnit) {`
566. `fontSize = Math.floor(`
567. `parseFloat(fontSize) * this.pdf.internal.scaleFactor`
568. `);`
569. `} else if ("em" === fontSizeUnit) {`
570. `fontSize = Math.floor(parseFloat(fontSize) * this.pdf.getFontSize());`
571. `} else {`
572. `fontSize = Math.floor(`
573. `parseFloat(fontSize) * this.pdf.internal.scaleFactor`
574. `);`
575. `}`
577. `this.pdf.setFontSize(fontSize);`
578. `var parts = parseFontFamily(fontFamily);`
580. `if (this.fontFaces) {`
581. `var fontFaceMap = getFontFaceMap(this.pdf, this.fontFaces);`
583. `var rules = parts.map(function(ff) {`
584. `return {`
585. `family: ff,`
586. `stretch: "normal", // TODO: Extract font-stretch from font rule (perhaps write proper parser for it?)`
587. `weight: fontWeight,`
588. `style: fontStyle`
589. `};`
590. `});`
592. `var font = resolveFontFace(fontFaceMap, rules);`
593. `this.pdf.setFont(font.ref.name, font.ref.style);`
594. `return;`
595. `}`
597. `var style = "";`
598. `if (`
599. `fontWeight === "bold" ||`
600. `parseInt(fontWeight, 10) >= 700 ||`
601. `fontStyle === "bold"`
602. `) {`
603. `style = "bold";`
604. `}`
606. `if (fontStyle === "italic") {`
607. `style += "italic";`
608. `}`
610. `if (style.length === 0) {`
611. `style = "normal";`
612. `}`
613. `var jsPdfFontName = "";`
615. `var fallbackFonts = {`
616. `arial: "Helvetica",`
617. `Arial: "Helvetica",`
618. `verdana: "Helvetica",`
619. `Verdana: "Helvetica",`
620. `helvetica: "Helvetica",`
621. `Helvetica: "Helvetica",`
622. `"sans-serif": "Helvetica",`
623. `fixed: "Courier",`
624. `monospace: "Courier",`
625. `terminal: "Courier",`
626. `cursive: "Times",`
627. `fantasy: "Times",`
628. `serif: "Times"`
629. `};`
631. `for (var i = 0; i < parts.length; i++) {`
632. `if (`
633. `this.pdf.internal.getFont(parts[i], style, {`
634. `noFallback: true,`
635. `disableWarning: true`
636. `}) !== undefined`
637. `) {`
638. `jsPdfFontName = parts[i];`
639. `break;`
640. `} else if (`
641. `style === "bolditalic" &&`
642. `this.pdf.internal.getFont(parts[i], "bold", {`
643. `noFallback: true,`
644. `disableWarning: true`
645. `}) !== undefined`
646. `) {`
647. `jsPdfFontName = parts[i];`
648. `style = "bold";`
649. `} else if (`
650. `this.pdf.internal.getFont(parts[i], "normal", {`
651. `noFallback: true,`
652. `disableWarning: true`
653. `}) !== undefined`
654. `) {`
655. `jsPdfFontName = parts[i];`
656. `style = "normal";`
657. `break;`
658. `}`
659. `}`
660. `if (jsPdfFontName === "") {`
661. `for (var j = 0; j < parts.length; j++) {`
662. `if (fallbackFonts[parts[j]]) {`
663. `jsPdfFontName = fallbackFonts[parts[j]];`
664. `break;`
665. `}`
666. `}`
667. `}`
668. `jsPdfFontName = jsPdfFontName === "" ? "Times" : jsPdfFontName;`
669. `this.pdf.setFont(jsPdfFontName, style);`
670. `}`
671. `});`
673. `Object.defineProperty(this, "globalCompositeOperation", {`
674. `get: function() {`
675. `return this.ctx.globalCompositeOperation;`
676. `},`
677. `set: function(value) {`
678. `this.ctx.globalCompositeOperation = value;`
679. `}`
680. `});`
682. `Object.defineProperty(this, "globalAlpha", {`
683. `get: function() {`
684. `return this.ctx.globalAlpha;`
685. `},`
686. `set: function(value) {`
687. `this.ctx.globalAlpha = value;`
688. `}`
689. `});`
691. `/**`
692. `* A float specifying the amount of the line dash offset. The default value is 0.0.`
693. `*`
694. `* @name lineDashOffset`
695. `* @default 0.0`
696. `*/`
697. `Object.defineProperty(this, "lineDashOffset", {`
698. `get: function() {`
699. `return this.ctx.lineDashOffset;`
700. `},`
701. `set: function(value) {`
702. `this.ctx.lineDashOffset = value;`
703. `setLineDash.call(this);`
704. `}`
705. `});`
707. `// Not HTML API`
708. `Object.defineProperty(this, "lineDash", {`
709. `get: function() {`
710. `return this.ctx.lineDash;`
711. `},`
712. `set: function(value) {`
713. `this.ctx.lineDash = value;`
714. `setLineDash.call(this);`
715. `}`
716. `});`
718. `// Not HTML API`
719. `Object.defineProperty(this, "ignoreClearRect", {`
720. `get: function() {`
721. `return this.ctx.ignoreClearRect;`
722. `},`
723. `set: function(value) {`
724. `this.ctx.ignoreClearRect = Boolean(value);`
725. `}`
726. `});`
727. `};`
729. `/**`
730. `* Sets the line dash pattern used when stroking lines.`
731. `* @name setLineDash`
732. `* @function`
733. `* @description It uses an array of values that specify alternating lengths of lines and gaps which describe the pattern.`
734. `*/`
735. `Context2D.prototype.setLineDash = function(dashArray) {`
736. `this.lineDash = dashArray;`
737. `};`
739. `/**`
740. `* gets the current line dash pattern.`
741. `* @name getLineDash`
742. `* @function`
743. `* @returns {Array} An Array of numbers that specify distances to alternately draw a line and a gap (in coordinate space units). If the number, when setting the elements, is odd, the elements of the array get copied and concatenated. For example, setting the line dash to [5, 15, 25] will result in getting back [5, 15, 25, 5, 15, 25].`
744. `*/`
745. `Context2D.prototype.getLineDash = function() {`
746. `if (this.lineDash.length % 2) {`
747. `// https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/getLineDash#return_value`
748. `return this.lineDash.concat(this.lineDash);`
749. `} else {`
750. `// The copied value is returned to prevent contamination from outside.`
751. `return this.lineDash.slice();`
752. `}`
753. `};`
755. `Context2D.prototype.fill = function() {`
756. `pathPreProcess.call(this, "fill", false);`
757. `};`
759. `/**`
760. `* Actually draws the path you have defined`
761. `*`
762. `* @name stroke`
763. `* @function`
764. `* @description The stroke() method actually draws the path you have defined with all those moveTo() and lineTo() methods. The default color is black.`
765. `*/`
766. `Context2D.prototype.stroke = function() {`
767. `pathPreProcess.call(this, "stroke", false);`
768. `};`
770. `/**`
771. `* Begins a path, or resets the current`
772. `*`
773. `* @name beginPath`
774. `* @function`
775. `* @description The beginPath() method begins a path, or resets the current path.`
776. `*/`
777. `Context2D.prototype.beginPath = function() {`
778. `this.path = [`\
779. `{`\
780. `type: "begin"`\
781. `}`\
782. `];`
783. `};`
785. `/**`
786. `* Moves the path to the specified point in the canvas, without creating a line`
787. `*`
788. `* @name moveTo`
789. `* @function`
790. `* @param x {Number} The x-coordinate of where to move the path to`
791. `* @param y {Number} The y-coordinate of where to move the path to`
792. `*/`
793. `Context2D.prototype.moveTo = function(x, y) {`
794. `if (isNaN(x) || isNaN(y)) {`
795. `console.error("jsPDF.context2d.moveTo: Invalid arguments", arguments);`
796. `throw new Error("Invalid arguments passed to jsPDF.context2d.moveTo");`
797. `}`
799. `var pt = this.ctx.transform.applyToPoint(new Point(x, y));`
801. `this.path.push({`
802. `type: "mt",`
803. `x: pt.x,`
804. `y: pt.y`
805. `});`
806. `this.ctx.lastPoint = new Point(x, y);`
807. `};`
809. `/**`
810. `* Creates a path from the current point back to the starting point`
811. `*`
812. `* @name closePath`
813. `* @function`
814. `* @description The closePath() method creates a path from the current point back to the starting point.`
815. `*/`
816. `Context2D.prototype.closePath = function() {`
817. `var pathBegin = new Point(0, 0);`
818. `var i = 0;`
819. `for (i = this.path.length - 1; i !== -1; i--) {`
820. `if (this.path[i].type === "begin") {`
821. `if (`
822. `typeof this.path[i + 1] === "object" &&`
823. `typeof this.path[i + 1].x === "number"`
824. `) {`
825. `pathBegin = new Point(this.path[i + 1].x, this.path[i + 1].y);`
826. `break;`
827. `}`
828. `}`
829. `}`
830. `this.path.push({`
831. `type: "close"`
832. `});`
833. `this.ctx.lastPoint = new Point(pathBegin.x, pathBegin.y);`
834. `};`
836. `/**`
837. `* Adds a new point and creates a line to that point from the last specified point in the canvas`
838. `*`
839. `* @name lineTo`
840. `* @function`
841. `* @param x The x-coordinate of where to create the line to`
842. `* @param y The y-coordinate of where to create the line to`
843. `* @description The lineTo() method adds a new point and creates a line TO that point FROM the last specified point in the canvas (this method does not draw the line).`
844. `*/`
845. `Context2D.prototype.lineTo = function(x, y) {`
846. `if (isNaN(x) || isNaN(y)) {`
847. `console.error("jsPDF.context2d.lineTo: Invalid arguments", arguments);`
848. `throw new Error("Invalid arguments passed to jsPDF.context2d.lineTo");`
849. `}`
851. `var pt = this.ctx.transform.applyToPoint(new Point(x, y));`
853. `this.path.push({`
854. `type: "lt",`
855. `x: pt.x,`
856. `y: pt.y`
857. `});`
858. `this.ctx.lastPoint = new Point(pt.x, pt.y);`
859. `};`
861. `/**`
862. `* Clips a region of any shape and size from the original canvas`
863. `*`
864. `* @name clip`
865. `* @function`
866. `* @description The clip() method clips a region of any shape and size from the original canvas.`
867. `*/`
868. `Context2D.prototype.clip = function() {`
869. `this.ctx.clip_path = JSON.parse(JSON.stringify(this.path));`
870. `pathPreProcess.call(this, null, true);`
871. `};`
873. `/**`
874. `* Creates a cubic Bézier curve`
875. `*`
876. `* @name quadraticCurveTo`
877. `* @function`
878. `* @param cpx {Number} The x-coordinate of the Bézier control point`
879. `* @param cpy {Number} The y-coordinate of the Bézier control point`
880. `* @param x {Number} The x-coordinate of the ending point`
881. `* @param y {Number} The y-coordinate of the ending point`
882. `* @description The quadraticCurveTo() method adds a point to the current path by using the specified control points that represent a quadratic Bézier curve.
A quadratic Bézier curve requires two points. The first point is a control point that is used in the quadratic Bézier calculation and the second point is the ending point for the curve. The starting point for the curve is the last point in the current path. If a path does not exist, use the beginPath() and moveTo() methods to define a starting point.`
883. `*/`
884. `Context2D.prototype.quadraticCurveTo = function(cpx, cpy, x, y) {`
885. `if (isNaN(x) || isNaN(y) || isNaN(cpx) || isNaN(cpy)) {`
886. `console.error(`
887. `"jsPDF.context2d.quadraticCurveTo: Invalid arguments",`
888. `arguments`
889. `);`
890. `throw new Error(`
891. `"Invalid arguments passed to jsPDF.context2d.quadraticCurveTo"`
892. `);`
893. `}`
895. `var pt0 = this.ctx.transform.applyToPoint(new Point(x, y));`
896. `var pt1 = this.ctx.transform.applyToPoint(new Point(cpx, cpy));`
898. `this.path.push({`
899. `type: "qct",`
900. `x1: pt1.x,`
901. `y1: pt1.y,`
902. `x: pt0.x,`
903. `y: pt0.y`
904. `});`
905. `this.ctx.lastPoint = new Point(pt0.x, pt0.y);`
906. `};`
908. `/**`
909. `* Creates a cubic Bézier curve`
910. `*`
911. `* @name bezierCurveTo`
912. `* @function`
913. `* @param cp1x {Number} The x-coordinate of the first Bézier control point`
914. `* @param cp1y {Number} The y-coordinate of the first Bézier control point`
915. `* @param cp2x {Number} The x-coordinate of the second Bézier control point`
916. `* @param cp2y {Number} The y-coordinate of the second Bézier control point`
917. `* @param x {Number} The x-coordinate of the ending point`
918. `* @param y {Number} The y-coordinate of the ending point`
919. `* @description The bezierCurveTo() method adds a point to the current path by using the specified control points that represent a cubic Bézier curve.
A cubic bezier curve requires three points. The first two points are control points that are used in the cubic Bézier calculation and the last point is the ending point for the curve. The starting point for the curve is the last point in the current path. If a path does not exist, use the beginPath() and moveTo() methods to define a starting point.`
920. `*/`
921. `Context2D.prototype.bezierCurveTo = function(cp1x, cp1y, cp2x, cp2y, x, y) {`
922. `if (`
923. `isNaN(x) ||`
924. `isNaN(y) ||`
925. `isNaN(cp1x) ||`
926. `isNaN(cp1y) ||`
927. `isNaN(cp2x) ||`
928. `isNaN(cp2y)`
929. `) {`
930. `console.error(`
931. `"jsPDF.context2d.bezierCurveTo: Invalid arguments",`
932. `arguments`
933. `);`
934. `throw new Error(`
935. `"Invalid arguments passed to jsPDF.context2d.bezierCurveTo"`
936. `);`
937. `}`
938. `var pt0 = this.ctx.transform.applyToPoint(new Point(x, y));`
939. `var pt1 = this.ctx.transform.applyToPoint(new Point(cp1x, cp1y));`
940. `var pt2 = this.ctx.transform.applyToPoint(new Point(cp2x, cp2y));`
942. `this.path.push({`
943. `type: "bct",`
944. `x1: pt1.x,`
945. `y1: pt1.y,`
946. `x2: pt2.x,`
947. `y2: pt2.y,`
948. `x: pt0.x,`
949. `y: pt0.y`
950. `});`
951. `this.ctx.lastPoint = new Point(pt0.x, pt0.y);`
952. `};`
954. `/**`
955. `* Creates an arc/curve (used to create circles, or parts of circles)`
956. `*`
957. `* @name arc`
958. `* @function`
959. `* @param x {Number} The x-coordinate of the center of the circle`
960. `* @param y {Number} The y-coordinate of the center of the circle`
961. `* @param radius {Number} The radius of the circle`
962. `* @param startAngle {Number} The starting angle, in radians (0 is at the 3 o'clock position of the arc's circle)`
963. `* @param endAngle {Number} The ending angle, in radians`
964. `* @param counterclockwise {Boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise.`
965. `* @description The arc() method creates an arc/curve (used to create circles, or parts of circles).`
966. `*/`
967. `Context2D.prototype.arc = function(`
968. `x,`
969. `y,`
970. `radius,`
971. `startAngle,`
972. `endAngle,`
973. `counterclockwise`
974. `) {`
975. `if (`
976. `isNaN(x) ||`
977. `isNaN(y) ||`
978. `isNaN(radius) ||`
979. `isNaN(startAngle) ||`
980. `isNaN(endAngle)`
981. `) {`
982. `console.error("jsPDF.context2d.arc: Invalid arguments", arguments);`
983. `throw new Error("Invalid arguments passed to jsPDF.context2d.arc");`
984. `}`
985. `counterclockwise = Boolean(counterclockwise);`
987. `if (!this.ctx.transform.isIdentity) {`
988. `var xpt = this.ctx.transform.applyToPoint(new Point(x, y));`
989. `x = xpt.x;`
990. `y = xpt.y;`
992. `var x_radPt = this.ctx.transform.applyToPoint(new Point(0, radius));`
993. `var x_radPt0 = this.ctx.transform.applyToPoint(new Point(0, 0));`
994. `radius = Math.sqrt(`
995. `Math.pow(x_radPt.x - x_radPt0.x, 2) +`
996. `Math.pow(x_radPt.y - x_radPt0.y, 2)`
997. `);`
998. `}`
999. `if (Math.abs(endAngle - startAngle) >= 2 * Math.PI) {`
1000. `startAngle = 0;`
1001. `endAngle = 2 * Math.PI;`
1002. `}`
1004. `this.path.push({`
1005. `type: "arc",`
1006. `x: x,`
1007. `y: y,`
1008. `radius: radius,`
1009. `startAngle: startAngle,`
1010. `endAngle: endAngle,`
1011. `counterclockwise: counterclockwise`
1012. `});`
1013. `// this.ctx.lastPoint(new Point(pt.x,pt.y));`
1014. `};`
1016. `/**`
1017. `* Creates an arc/curve between two tangents`
1018. `*`
1019. `* @name arcTo`
1020. `* @function`
1021. `* @param x1 {Number} The x-coordinate of the first tangent`
1022. `* @param y1 {Number} The y-coordinate of the first tangent`
1023. `* @param x2 {Number} The x-coordinate of the second tangent`
1024. `* @param y2 {Number} The y-coordinate of the second tangent`
1025. `* @param radius The radius of the arc`
1026. `* @description The arcTo() method creates an arc/curve between two tangents on the canvas.`
1027. `*/`
1028. `// eslint-disable-next-line no-unused-vars`
1029. `Context2D.prototype.arcTo = function(x1, y1, x2, y2, radius) {`
1030. `throw new Error("arcTo not implemented.");`
1031. `};`
1033. `/**`
1034. `* Creates a rectangle`
1035. `*`
1036. `* @name rect`
1037. `* @function`
1038. `* @param x {Number} The x-coordinate of the upper-left corner of the rectangle`
1039. `* @param y {Number} The y-coordinate of the upper-left corner of the rectangle`
1040. `* @param w {Number} The width of the rectangle, in pixels`
1041. `* @param h {Number} The height of the rectangle, in pixels`
1042. `* @description The rect() method creates a rectangle.`
1043. `*/`
1044. `Context2D.prototype.rect = function(x, y, w, h) {`
1045. `if (isNaN(x) || isNaN(y) || isNaN(w) || isNaN(h)) {`
1046. `console.error("jsPDF.context2d.rect: Invalid arguments", arguments);`
1047. `throw new Error("Invalid arguments passed to jsPDF.context2d.rect");`
1048. `}`
1049. `this.moveTo(x, y);`
1050. `this.lineTo(x + w, y);`
1051. `this.lineTo(x + w, y + h);`
1052. `this.lineTo(x, y + h);`
1053. `this.lineTo(x, y);`
1054. `this.lineTo(x + w, y);`
1055. `this.lineTo(x, y);`
1056. `};`
1058. `/**`
1059. `* Draws a "filled" rectangle`
1060. `*`
1061. `* @name fillRect`
1062. `* @function`
1063. `* @param x {Number} The x-coordinate of the upper-left corner of the rectangle`
1064. `* @param y {Number} The y-coordinate of the upper-left corner of the rectangle`
1065. `* @param w {Number} The width of the rectangle, in pixels`
1066. `* @param h {Number} The height of the rectangle, in pixels`
1067. `* @description The fillRect() method draws a "filled" rectangle. The default color of the fill is black.`
1068. `*/`
1069. `Context2D.prototype.fillRect = function(x, y, w, h) {`
1070. `if (isNaN(x) || isNaN(y) || isNaN(w) || isNaN(h)) {`
1071. `console.error("jsPDF.context2d.fillRect: Invalid arguments", arguments);`
1072. `throw new Error("Invalid arguments passed to jsPDF.context2d.fillRect");`
1073. `}`
1074. `if (isFillTransparent.call(this)) {`
1075. `return;`
1076. `}`
1077. `var tmp = {};`
1078. `if (this.lineCap !== "butt") {`
1079. `tmp.lineCap = this.lineCap;`
1080. `this.lineCap = "butt";`
1081. `}`
1082. `if (this.lineJoin !== "miter") {`
1083. `tmp.lineJoin = this.lineJoin;`
1084. `this.lineJoin = "miter";`
1085. `}`
1087. `this.beginPath();`
1088. `this.rect(x, y, w, h);`
1089. `this.fill();`
1091. `if (tmp.hasOwnProperty("lineCap")) {`
1092. `this.lineCap = tmp.lineCap;`
1093. `}`
1094. `if (tmp.hasOwnProperty("lineJoin")) {`
1095. `this.lineJoin = tmp.lineJoin;`
1096. `}`
1097. `};`
1099. `/**`
1100. `* Draws a rectangle (no fill)`
1101. `*`
1102. `* @name strokeRect`
1103. `* @function`
1104. `* @param x {Number} The x-coordinate of the upper-left corner of the rectangle`
1105. `* @param y {Number} The y-coordinate of the upper-left corner of the rectangle`
1106. `* @param w {Number} The width of the rectangle, in pixels`
1107. `* @param h {Number} The height of the rectangle, in pixels`
1108. `* @description The strokeRect() method draws a rectangle (no fill). The default color of the stroke is black.`
1109. `*/`
1110. `Context2D.prototype.strokeRect = function strokeRect(x, y, w, h) {`
1111. `if (isNaN(x) || isNaN(y) || isNaN(w) || isNaN(h)) {`
1112. `console.error("jsPDF.context2d.strokeRect: Invalid arguments", arguments);`
1113. `throw new Error("Invalid arguments passed to jsPDF.context2d.strokeRect");`
1114. `}`
1115. `if (isStrokeTransparent.call(this)) {`
1116. `return;`
1117. `}`
1118. `this.beginPath();`
1119. `this.rect(x, y, w, h);`
1120. `this.stroke();`
1121. `};`
1123. `/**`
1124. `* Clears the specified pixels within a given rectangle`
1125. `*`
1126. `* @name clearRect`
1127. `* @function`
1128. `* @param x {Number} The x-coordinate of the upper-left corner of the rectangle`
1129. `* @param y {Number} The y-coordinate of the upper-left corner of the rectangle`
1130. `* @param w {Number} The width of the rectangle to clear, in pixels`
1131. `* @param h {Number} The height of the rectangle to clear, in pixels`
1132. `* @description We cannot clear PDF commands that were already written to PDF, so we use white instead. `
1133. `* As a special case, read a special flag (ignoreClearRect) and do nothing if it is set.`
1134. `* This results in all calls to clearRect() to do nothing, and keep the canvas transparent.`
1135. `* This flag is stored in the save/restore context and is managed the same way as other drawing states.`
1136. `*`
1137. `*/`
1138. `Context2D.prototype.clearRect = function(x, y, w, h) {`
1139. `if (isNaN(x) || isNaN(y) || isNaN(w) || isNaN(h)) {`
1140. `console.error("jsPDF.context2d.clearRect: Invalid arguments", arguments);`
1141. `throw new Error("Invalid arguments passed to jsPDF.context2d.clearRect");`
1142. `}`
1143. `if (this.ignoreClearRect) {`
1144. `return;`
1145. `}`
1147. `this.fillStyle = "#ffffff";`
1148. `this.fillRect(x, y, w, h);`
1149. `};`
1151. `/**`
1152. `* Saves the state of the current context`
1153. `*`
1154. `* @name save`
1155. `* @function`
1156. `*/`
1157. `Context2D.prototype.save = function(doStackPush) {`
1158. `doStackPush = typeof doStackPush === "boolean" ? doStackPush : true;`
1159. `var tmpPageNumber = this.pdf.internal.getCurrentPageInfo().pageNumber;`
1160. `for (var i = 0; i < this.pdf.internal.getNumberOfPages(); i++) {`
1161. `this.pdf.setPage(i + 1);`
1162. `this.pdf.internal.out("q");`
1163. `}`
1164. `this.pdf.setPage(tmpPageNumber);`
1166. `if (doStackPush) {`
1167. `this.ctx.fontSize = this.pdf.internal.getFontSize();`
1168. `var ctx = new ContextLayer(this.ctx);`
1169. `this.ctxStack.push(this.ctx);`
1170. `this.ctx = ctx;`
1171. `}`
1172. `};`
1174. `/**`
1175. `* Returns previously saved path state and attributes`
1176. `*`
1177. `* @name restore`
1178. `* @function`
1179. `*/`
1180. `Context2D.prototype.restore = function(doStackPop) {`
1181. `doStackPop = typeof doStackPop === "boolean" ? doStackPop : true;`
1182. `var tmpPageNumber = this.pdf.internal.getCurrentPageInfo().pageNumber;`
1183. `for (var i = 0; i < this.pdf.internal.getNumberOfPages(); i++) {`
1184. `this.pdf.setPage(i + 1);`
1185. `this.pdf.internal.out("Q");`
1186. `}`
1187. `this.pdf.setPage(tmpPageNumber);`
1189. `if (doStackPop && this.ctxStack.length !== 0) {`
1190. `this.ctx = this.ctxStack.pop();`
1191. `this.fillStyle = this.ctx.fillStyle;`
1192. `this.strokeStyle = this.ctx.strokeStyle;`
1193. `this.font = this.ctx.font;`
1194. `this.lineCap = this.ctx.lineCap;`
1195. `this.lineWidth = this.ctx.lineWidth;`
1196. `this.lineJoin = this.ctx.lineJoin;`
1197. `this.lineDash = this.ctx.lineDash;`
1198. `this.lineDashOffset = this.ctx.lineDashOffset;`
1199. `}`
1200. `};`
1202. `/**`
1203. `* @name toDataURL`
1204. `* @function`
1205. `*/`
1206. `Context2D.prototype.toDataURL = function() {`
1207. `throw new Error("toDataUrl not implemented.");`
1208. `};`
1210. `//helper functions`
1212. `/**`
1213. `* Get the decimal values of r, g, b and a`
1214. `*`
1215. `* @name getRGBA`
1216. `* @function`
1217. `* @private`
1218. `* @ignore`
1219. `*/`
1220. `var getRGBA = function(style) {`
1221. `var rxRgb = /rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/;`
1222. `var rxRgba = /rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d.]+)\s*\)/;`
1223. `var rxTransparent = /transparent|rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*0+\s*\)/;`
1225. `var r, g, b, a;`
1227. `if (style.isCanvasGradient === true) {`
1228. `style = style.getColor();`
1229. `}`
1231. `if (!style) {`
1232. `return { r: 0, g: 0, b: 0, a: 0, style: style };`
1233. `}`
1235. `if (rxTransparent.test(style)) {`
1236. `r = 0;`
1237. `g = 0;`
1238. `b = 0;`
1239. `a = 0;`
1240. `} else {`
1241. `var matches = rxRgb.exec(style);`
1242. `if (matches !== null) {`
1243. `r = parseInt(matches[1]);`
1244. `g = parseInt(matches[2]);`
1245. `b = parseInt(matches[3]);`
1246. `a = 1;`
1247. `} else {`
1248. `matches = rxRgba.exec(style);`
1249. `if (matches !== null) {`
1250. `r = parseInt(matches[1]);`
1251. `g = parseInt(matches[2]);`
1252. `b = parseInt(matches[3]);`
1253. `a = parseFloat(matches[4]);`
1254. `} else {`
1255. `a = 1;`
1257. `if (typeof style === "string" && style.charAt(0) !== "#") {`
1258. `var rgbColor = new RGBColor(style);`
1259. `if (rgbColor.ok) {`
1260. `style = rgbColor.toHex();`
1261. `} else {`
1262. `style = "#000000";`
1263. `}`
1264. `}`
1266. `if (style.length === 4) {`
1267. `r = style.substring(1, 2);`
1268. `r += r;`
1269. `g = style.substring(2, 3);`
1270. `g += g;`
1271. `b = style.substring(3, 4);`
1272. `b += b;`
1273. `} else {`
1274. `r = style.substring(1, 3);`
1275. `g = style.substring(3, 5);`
1276. `b = style.substring(5, 7);`
1277. `}`
1278. `r = parseInt(r, 16);`
1279. `g = parseInt(g, 16);`
1280. `b = parseInt(b, 16);`
1281. `}`
1282. `}`
1283. `}`
1284. `return { r: r, g: g, b: b, a: a, style: style };`
1285. `};`
1287. `/**`
1288. `* @name isFillTransparent`
1289. `* @function`
1290. `* @private`
1291. `* @ignore`
1292. `* @returns {Boolean}`
1293. `*/`
1294. `var isFillTransparent = function() {`
1295. `return this.ctx.isFillTransparent || this.globalAlpha == 0;`
1296. `};`
1298. `/**`
1299. `* @name isStrokeTransparent`
1300. `* @function`
1301. `* @private`
1302. `* @ignore`
1303. `* @returns {Boolean}`
1304. `*/`
1305. `var isStrokeTransparent = function() {`
1306. `return Boolean(this.ctx.isStrokeTransparent || this.globalAlpha == 0);`
1307. `};`
1309. `/**`
1310. `* Draws "filled" text on the canvas`
1311. `*`
1312. `* @name fillText`
1313. `* @function`
1314. `* @param text {String} Specifies the text that will be written on the canvas`
1315. `* @param x {Number} The x coordinate where to start painting the text (relative to the canvas)`
1316. `* @param y {Number} The y coordinate where to start painting the text (relative to the canvas)`
1317. `* @param maxWidth {Number} Optional. The maximum allowed width of the text, in pixels`
1318. `* @description The fillText() method draws filled text on the canvas. The default color of the text is black.`
1319. `*/`
1320. `Context2D.prototype.fillText = function(text, x, y, maxWidth) {`
1321. `if (isNaN(x) || isNaN(y) || typeof text !== "string") {`
1322. `console.error("jsPDF.context2d.fillText: Invalid arguments", arguments);`
1323. `throw new Error("Invalid arguments passed to jsPDF.context2d.fillText");`
1324. `}`
1325. `maxWidth = isNaN(maxWidth) ? undefined : maxWidth;`
1326. `if (isFillTransparent.call(this)) {`
1327. `return;`
1328. `}`
1330. `var degs = rad2deg(this.ctx.transform.rotation);`
1332. `// We only use X axis as scale hint`
1333. `var scale = this.ctx.transform.scaleX;`
1335. `putText.call(this, {`
1336. `text: text,`
1337. `x: x,`
1338. `y: y,`
1339. `scale: scale,`
1340. `angle: degs,`
1341. `align: this.textAlign,`
1342. `maxWidth: maxWidth`
1343. `});`
1344. `};`
1346. `/**`
1347. `* Draws text on the canvas (no fill)`
1348. `*`
1349. `* @name strokeText`
1350. `* @function`
1351. `* @param text {String} Specifies the text that will be written on the canvas`
1352. `* @param x {Number} The x coordinate where to start painting the text (relative to the canvas)`
1353. `* @param y {Number} The y coordinate where to start painting the text (relative to the canvas)`
1354. `* @param maxWidth {Number} Optional. The maximum allowed width of the text, in pixels`
1355. `* @description The strokeText() method draws text (with no fill) on the canvas. The default color of the text is black.`
1356. `*/`
1357. `Context2D.prototype.strokeText = function(text, x, y, maxWidth) {`
1358. `if (isNaN(x) || isNaN(y) || typeof text !== "string") {`
1359. `console.error("jsPDF.context2d.strokeText: Invalid arguments", arguments);`
1360. `throw new Error("Invalid arguments passed to jsPDF.context2d.strokeText");`
1361. `}`
1362. `if (isStrokeTransparent.call(this)) {`
1363. `return;`
1364. `}`
1366. `maxWidth = isNaN(maxWidth) ? undefined : maxWidth;`
1368. `var degs = rad2deg(this.ctx.transform.rotation);`
1369. `var scale = this.ctx.transform.scaleX;`
1371. `putText.call(this, {`
1372. `text: text,`
1373. `x: x,`
1374. `y: y,`
1375. `scale: scale,`
1376. `renderingMode: "stroke",`
1377. `angle: degs,`
1378. `align: this.textAlign,`
1379. `maxWidth: maxWidth`
1380. `});`
1381. `};`
1383. `/**`
1384. `* Returns an object that contains the width of the specified text`
1385. `*`
1386. `* @name measureText`
1387. `* @function`
1388. `* @param text {String} The text to be measured`
1389. `* @description The measureText() method returns an object that contains the width of the specified text, in pixels.`
1390. `* @returns {Number}`
1391. `*/`
1392. `Context2D.prototype.measureText = function(text) {`
1393. `if (typeof text !== "string") {`
1394. `console.error(`
1395. `"jsPDF.context2d.measureText: Invalid arguments",`
1396. `arguments`
1397. `);`
1398. `throw new Error(`
1399. `"Invalid arguments passed to jsPDF.context2d.measureText"`
1400. `);`
1401. `}`
1402. `var pdf = this.pdf;`
1403. `var k = this.pdf.internal.scaleFactor;`
1405. `var fontSize = pdf.internal.getFontSize();`
1406. `var txtWidth =`
1407. `(pdf.getStringUnitWidth(text) * fontSize) / pdf.internal.scaleFactor;`
1408. `txtWidth *= Math.round(((k * 96) / 72) * 10000) / 10000;`
1410. `var TextMetrics = function(options) {`
1411. `options = options || {};`
1412. `var _width = options.width || 0;`
1413. `Object.defineProperty(this, "width", {`
1414. `get: function() {`
1415. `return _width;`
1416. `}`
1417. `});`
1418. `return this;`
1419. `};`
1420. `return new TextMetrics({ width: txtWidth });`
1421. `};`
1423. `//Transformations`
1425. `/**`
1426. `* Scales the current drawing bigger or smaller`
1427. `*`
1428. `* @name scale`
1429. `* @function`
1430. `* @param scalewidth {Number} Scales the width of the current drawing (1=100%, 0.5=50%, 2=200%, etc.)`
1431. `* @param scaleheight {Number} Scales the height of the current drawing (1=100%, 0.5=50%, 2=200%, etc.)`
1432. `* @description The scale() method scales the current drawing, bigger or smaller.`
1433. `*/`
1434. `Context2D.prototype.scale = function(scalewidth, scaleheight) {`
1435. `if (isNaN(scalewidth) || isNaN(scaleheight)) {`
1436. `console.error("jsPDF.context2d.scale: Invalid arguments", arguments);`
1437. `throw new Error("Invalid arguments passed to jsPDF.context2d.scale");`
1438. `}`
1439. `var matrix = new Matrix(scalewidth, 0.0, 0.0, scaleheight, 0.0, 0.0);`
1440. `this.ctx.transform = this.ctx.transform.multiply(matrix);`
1441. `};`
1443. `/**`
1444. `* Rotates the current drawing`
1445. `*`
1446. `* @name rotate`
1447. `* @function`
1448. `* @param angle {Number} The rotation angle, in radians.`
1449. `* @description To calculate from degrees to radians: degrees*Math.PI/180. `
1450. `* Example: to rotate 5 degrees, specify the following: 5*Math.PI/180`
1451. `*/`
1452. `Context2D.prototype.rotate = function(angle) {`
1453. `if (isNaN(angle)) {`
1454. `console.error("jsPDF.context2d.rotate: Invalid arguments", arguments);`
1455. `throw new Error("Invalid arguments passed to jsPDF.context2d.rotate");`
1456. `}`
1457. `var matrix = new Matrix(`
1458. `Math.cos(angle),`
1459. `Math.sin(angle),`
1460. `-Math.sin(angle),`
1461. `Math.cos(angle),`
1462. `0.0,`
1463. `0.0`
1464. `);`
1465. `this.ctx.transform = this.ctx.transform.multiply(matrix);`
1466. `};`
1468. `/**`
1469. `* Remaps the (0,0) position on the canvas`
1470. `*`
1471. `* @name translate`
1472. `* @function`
1473. `* @param x {Number} The value to add to horizontal (x) coordinates`
1474. `* @param y {Number} The value to add to vertical (y) coordinates`
1475. `* @description The translate() method remaps the (0,0) position on the canvas.`
1476. `*/`
1477. `Context2D.prototype.translate = function(x, y) {`
1478. `if (isNaN(x) || isNaN(y)) {`
1479. `console.error("jsPDF.context2d.translate: Invalid arguments", arguments);`
1480. `throw new Error("Invalid arguments passed to jsPDF.context2d.translate");`
1481. `}`
1482. `var matrix = new Matrix(1.0, 0.0, 0.0, 1.0, x, y);`
1483. `this.ctx.transform = this.ctx.transform.multiply(matrix);`
1484. `};`
1486. `/**`
1487. `* Replaces the current transformation matrix for the drawing`
1488. `*`
1489. `* @name transform`
1490. `* @function`
1491. `* @param a {Number} Horizontal scaling`
1492. `* @param b {Number} Horizontal skewing`
1493. `* @param c {Number} Vertical skewing`
1494. `* @param d {Number} Vertical scaling`
1495. `* @param e {Number} Horizontal moving`
1496. `* @param f {Number} Vertical moving`
1497. `* @description Each object on the canvas has a current transformation matrix.
The transform() method replaces the current transformation matrix. It multiplies the current transformation matrix with the matrix described by:
a c e
b d f
0 0 1
In other words, the transform() method lets you scale, rotate, move, and skew the current context.`
1498. `*/`
1499. `Context2D.prototype.transform = function(a, b, c, d, e, f) {`
1500. `if (isNaN(a) || isNaN(b) || isNaN(c) || isNaN(d) || isNaN(e) || isNaN(f)) {`
1501. `console.error("jsPDF.context2d.transform: Invalid arguments", arguments);`
1502. `throw new Error("Invalid arguments passed to jsPDF.context2d.transform");`
1503. `}`
1504. `var matrix = new Matrix(a, b, c, d, e, f);`
1505. `this.ctx.transform = this.ctx.transform.multiply(matrix);`
1506. `};`
1508. `/**`
1509. `* Resets the current transform to the identity matrix. Then runs transform()`
1510. `*`
1511. `* @name setTransform`
1512. `* @function`
1513. `* @param a {Number} Horizontal scaling`
1514. `* @param b {Number} Horizontal skewing`
1515. `* @param c {Number} Vertical skewing`
1516. `* @param d {Number} Vertical scaling`
1517. `* @param e {Number} Horizontal moving`
1518. `* @param f {Number} Vertical moving`
1519. `* @description Each object on the canvas has a current transformation matrix.
The setTransform() method resets the current transform to the identity matrix, and then runs transform() with the same arguments.