beta works

This commit is contained in:
Christian Genco 2015-04-06 05:19:50 -05:00
commit d44588797f
41 changed files with 8393 additions and 0 deletions

BIN
.DS_Store vendored Normal file

Binary file not shown.

158
index.html Normal file
View File

@ -0,0 +1,158 @@
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
font-family: 'times new roman';
font-size: 12pt;
}
p{
line-height: 3em;
}
.body p{
text-indent: 0.5in;
}
@page{
size: 8.5in 11in;
margin: 1in;
counter-increment: page;
counter-reset: page 1;
@top-right {
/*content: counter(page);*/
content: "hi";
}
}
</style>
</head>
<body>
<script type="text/javascript" src="./js/jquery.js"></script>
<script type="text/javascript" src="./js/jspdf.js"></script>
<script type="text/javascript" src="./js/Deflate/adler32cs.js"></script>
<script type="text/javascript" src="./js/FileSaver.js/FileSaver.js"></script>
<script type="text/javascript" src="./js/Blob.js/BlobBuilder.js"></script>
<script type="text/javascript" src="./js/jspdf.plugin.addimage.js"></script>
<script type="text/javascript" src="./js/jspdf.plugin.standard_fonts_metrics.js"></script>
<script type="text/javascript" src="./js/jspdf.plugin.split_text_to_size.js"></script>
<script type="text/javascript" src="./js/jspdf.plugin.from_html.js"></script>
<script type="text/javascript">
(function(API){
API.textWidth = function(txt) {
var fontSize = this.internal.getFontSize();
var pageWidth = this.internal.pageSize.width;
/* You multiply the unit width of your string by your font size and divide
* by the internal scale factor. The division is necessary
* for the case where you use units other than 'pt' in the constructor
* of jsPDF.
*/
return this.getStringUnitWidth(txt)*fontSize/this.internal.scaleFactor;
}
API.space = function(length){
var charWidth = this.textWidth(" ");
var res = "";
for(var i=0; i<length / charWidth; i++)
res += " ";
return res;
}
API.textHeight = function(){
// doc.internal.getLineHeight() / doc.internal.scaleFactor
return 0.115;
}
API.txt = function(text, x, y, flags, angle, align){
y += this.textHeight();
this.text(text, x, y, flags, angle, align);
}
API.line = function(text, align){
this.y || (this.y = this.marginTop);
// doc.rect(this.marginLeft, this.y, this.textWidth(text), this.textHeight());
if(this.y > this.internal.pageSize.height - this.marginBottom){
this.y = this.marginTop;
this.addPage();
this.header();
}
this.y += this.textHeight();
var x = this.marginLeft;
if(align && align == 'center'){
x = doc.internal.pageSize.width/2;
}
this.text(text, x, this.y, align);
this.y += this.textHeight() * this.spacing;
}
API.p = function(text){
text = this.space(0.5) + text;
for(var line of this.splitTextToSize(text, doc.internal.pageSize.width - doc.marginLeft - doc.marginRight)){
this.line(line);
}
}
})(jsPDF.API);
var doc = new jsPDF('p', 'in', 'letter');
doc.setLineWidth(0.01)
doc.setFont("Times", "Roman");
doc.setFontSize(12);
doc.spacing = 2.6;
doc.marginTop = 1;
doc.marginLeft = 1;
doc.marginRight = 1;
doc.marginBottom = 1;
// function pagenum(){
// doc.rightText(1, 0.5, "Angeli " + doc.page);
// doc.page++;
// };
// pagenum();
// doc.text(1, 1, ["Elizabeth L. Angeli", "Professor Patricia Sullivan", "English 624", "12 February 2012"], {lineHeight: 28});
// doc.centerText(0, 1, "Centered text")
doc.page = 1;
doc.header = function(){
doc.txt("Angeli " + doc.page, 8.5-1, 0.5, "right");
doc.page++;
}
doc.header()
doc.line("Elizabeth L. Angeli");
doc.line("Professor Patricia Sullivan");
doc.line("English 624");
doc.line("12 February 2012");
doc.line("Toward a Recovery of Nineteenth Century Farming Handbooks", "center");
doc.p("While researching texts written about nineteenth century farming, I found a few authors who published books about the literature of nineteenth century farming, particularly agricultural journals, newspapers, pamphlets, and brochures. These authors often placed the farming literature they were studying into an historical context by discussing the important events in agriculture of the year in which the literature was published (see Demaree, for example). However, while these authors discuss journals, newspapers, pamphlets, and brochures, I could not find much discussion about another important source of farming knowledge: farming handbooks. My goal in this paper is to bring this source into the agricultural literature discussion by connecting three agricultural handbooks from the nineteenth century with nineteenth century agricultural history.");
doc.p("To achieve this goal, I have organized my paper into four main sections, two of which have sub-sections. In the first section, I provide an account of three important events in nineteenth century agricultural history: population and technological changes, the distribution of scientific new knowledge, and farming's influence on education. In the second section, I discuss three nineteenth century farming handbooks in connection with the important events described in the first section. I end my paper with a third section that offers research questions that could be answered in future versions of this paper and conclude with a fourth section that discusses the importance of expanding this particular project. I also include an appendix after the Works Cited that contains images of the three handbooks I examined. Before I can begin the examination of the three handbooks, however, I need to provide an historical context in which the books were written, and it is to this that I now turn.");
$("<iframe />").attr('src', doc.output('datauristring')).attr('width', '100%').attr('height', '500px').prependTo('body')
// doc.save()
</script>
</body>
</html>

BIN
js/.DS_Store vendored Normal file

Binary file not shown.

177
js/Blob.js/Blob.js Normal file
View File

@ -0,0 +1,177 @@
/* Blob.js
* A Blob implementation.
* 2013-01-23
*
* By Eli Grey, http://eligrey.com
* By Devin Samarin, https://github.com/eboyjr
* License: X11/MIT
* See LICENSE.md
*/
/*global self, unescape */
/*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true,
plusplus: true */
/*! @source http://purl.eligrey.com/github/Blob.js/blob/master/Blob.js */
if (typeof Blob !== "function")
var Blob = (function (view) {
"use strict";
var BlobBuilder = view.BlobBuilder || view.WebKitBlobBuilder || view.MozBlobBuilder || view.MSBlobBuilder || (function(view) {
var
get_class = function(object) {
return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
}
, FakeBlobBuilder = function BlobBuilder() {
this.data = [];
}
, FakeBlob = function Blob(data, type, encoding) {
this.data = data;
this.size = data.length;
this.type = type;
this.encoding = encoding;
}
, FBB_proto = FakeBlobBuilder.prototype
, FB_proto = FakeBlob.prototype
, FileReaderSync = view.FileReaderSync
, FileException = function(type) {
this.code = this[this.name = type];
}
, file_ex_codes = (
"NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR "
+ "NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR"
).split(" ")
, file_ex_code = file_ex_codes.length
, real_URL = view.URL || view.webkitURL || view
, real_create_object_URL = real_URL.createObjectURL
, real_revoke_object_URL = real_URL.revokeObjectURL
, URL = real_URL
, btoa = view.btoa
, atob = view.atob
, can_apply_typed_arrays = false
, can_apply_typed_arrays_test = function(pass) {
can_apply_typed_arrays = !pass;
}
, ArrayBuffer = view.ArrayBuffer
, Uint8Array = view.Uint8Array
;
FakeBlob.fake = FB_proto.fake = true;
while (file_ex_code--) {
FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1;
}
try {
if (Uint8Array) {
can_apply_typed_arrays_test.apply(0, new Uint8Array(1));
}
} catch (ex) {}
if (!real_URL.createObjectURL) {
URL = view.URL = {};
}
URL.createObjectURL = function(blob) {
var
type = blob.type
, data_URI_header
;
if (type === null) {
type = "application/octet-stream";
}
if (blob instanceof FakeBlob) {
data_URI_header = "data:" + type;
if (blob.encoding === "base64") {
return data_URI_header + ";base64," + blob.data;
} else if (blob.encoding === "URI") {
return data_URI_header + "," + decodeURIComponent(blob.data);
} if (btoa) {
return data_URI_header + ";base64," + btoa(blob.data);
} else {
return data_URI_header + "," + encodeURIComponent(blob.data);
}
} else if (real_create_object_URL) {
return real_create_object_URL.call(real_URL, blob);
}
};
URL.revokeObjectURL = function(object_URL) {
if (object_URL.substring(0, 5) !== "data:" && real_revoke_object_URL) {
real_revoke_object_URL.call(real_URL, object_URL);
}
};
FBB_proto.append = function(data/*, endings*/) {
var bb = this.data;
// decode data to a binary string
if (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) {
if (can_apply_typed_arrays) {
bb.push(String.fromCharCode.apply(String, new Uint8Array(data)));
} else {
var
str = ""
, buf = new Uint8Array(data)
, i = 0
, buf_len = buf.length
;
for (; i < buf_len; i++) {
str += String.fromCharCode(buf[i]);
}
}
} else if (get_class(data) === "Blob" || get_class(data) === "File") {
if (FileReaderSync) {
var fr = new FileReaderSync;
bb.push(fr.readAsBinaryString(data));
} else {
// async FileReader won't work as BlobBuilder is sync
throw new FileException("NOT_READABLE_ERR");
}
} else if (data instanceof FakeBlob) {
if (data.encoding === "base64" && atob) {
bb.push(atob(data.data));
} else if (data.encoding === "URI") {
bb.push(decodeURIComponent(data.data));
} else if (data.encoding === "raw") {
bb.push(data.data);
}
} else {
if (typeof data !== "string") {
data += ""; // convert unsupported types to strings
}
// decode UTF-16 to binary string
bb.push(unescape(encodeURIComponent(data)));
}
};
FBB_proto.getBlob = function(type) {
if (!arguments.length) {
type = null;
}
return new FakeBlob(this.data.join(""), type, "raw");
};
FBB_proto.toString = function() {
return "[object BlobBuilder]";
};
FB_proto.slice = function(start, end, type) {
var args = arguments.length;
if (args < 3) {
type = null;
}
return new FakeBlob(
this.data.slice(start, args > 1 ? end : this.data.length)
, type
, this.encoding
);
};
FB_proto.toString = function() {
return "[object Blob]";
};
return FakeBlobBuilder;
}(view));
return function Blob(blobParts, options) {
var type = options ? (options.type || "") : "";
var builder = new BlobBuilder();
if (blobParts) {
for (var i = 0, len = blobParts.length; i < len; i++) {
builder.append(blobParts[i]);
}
}
return builder.getBlob(type);
};
}(self));

161
js/Blob.js/BlobBuilder.js Normal file
View File

@ -0,0 +1,161 @@
/* BlobBuilder.js
* A BlobBuilder implementation.
* 2012-04-21
*
* By Eli Grey, http://eligrey.com
* License: X11/MIT
* See LICENSE.md
*/
/*global self, unescape */
/*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true,
plusplus: true */
/*! @source http://purl.eligrey.com/github/BlobBuilder.js/blob/master/BlobBuilder.js */
var BlobBuilder = BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder || (function(view) {
"use strict";
var
get_class = function(object) {
return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
}
, FakeBlobBuilder = function(){
this.data = [];
}
, FakeBlob = function(data, type, encoding) {
this.data = data;
this.size = data.length;
this.type = type;
this.encoding = encoding;
}
, FBB_proto = FakeBlobBuilder.prototype
, FB_proto = FakeBlob.prototype
, FileReaderSync = view.FileReaderSync
, FileException = function(type) {
this.code = this[this.name = type];
}
, file_ex_codes = (
"NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR "
+ "NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR"
).split(" ")
, file_ex_code = file_ex_codes.length
, real_URL = view.URL || view.webkitURL || view
, real_create_object_URL = real_URL.createObjectURL
, real_revoke_object_URL = real_URL.revokeObjectURL
, URL = real_URL
, btoa = view.btoa
, atob = view.atob
, can_apply_typed_arrays = false
, can_apply_typed_arrays_test = function(pass) {
can_apply_typed_arrays = !pass;
}
, ArrayBuffer = view.ArrayBuffer
, Uint8Array = view.Uint8Array
;
FakeBlobBuilder.fake = FB_proto.fake = true;
while (file_ex_code--) {
FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1;
}
try {
if (Uint8Array) {
can_apply_typed_arrays_test.apply(0, new Uint8Array(1));
}
} catch (ex) {}
if (!real_URL.createObjectURL) {
URL = view.URL = {};
}
URL.createObjectURL = function(blob) {
var
type = blob.type
, data_URI_header
;
if (type === null) {
type = "application/octet-stream";
}
if (blob instanceof FakeBlob) {
data_URI_header = "data:" + type;
if (blob.encoding === "base64") {
return data_URI_header + ";base64," + blob.data;
} else if (blob.encoding === "URI") {
return data_URI_header + "," + decodeURIComponent(blob.data);
} if (btoa) {
return data_URI_header + ";base64," + btoa(blob.data);
} else {
return data_URI_header + "," + encodeURIComponent(blob.data);
}
} else if (real_create_object_URL) {
return real_create_object_URL.call(real_URL, blob);
}
};
URL.revokeObjectURL = function(object_URL) {
if (object_URL.substring(0, 5) !== "data:" && real_revoke_object_URL) {
real_revoke_object_URL.call(real_URL, object_URL);
}
};
FBB_proto.append = function(data/*, endings*/) {
var bb = this.data;
// decode data to a binary string
if (Uint8Array && data instanceof ArrayBuffer) {
if (can_apply_typed_arrays) {
bb.push(String.fromCharCode.apply(String, new Uint8Array(data)));
} else {
var
str = ""
, buf = new Uint8Array(data)
, i = 0
, buf_len = buf.length
;
for (; i < buf_len; i++) {
str += String.fromCharCode(buf[i]);
}
}
} else if (get_class(data) === "Blob" || get_class(data) === "File") {
if (FileReaderSync) {
var fr = new FileReaderSync;
bb.push(fr.readAsBinaryString(data));
} else {
// async FileReader won't work as BlobBuilder is sync
throw new FileException("NOT_READABLE_ERR");
}
} else if (data instanceof FakeBlob) {
if (data.encoding === "base64" && atob) {
bb.push(atob(data.data));
} else if (data.encoding === "URI") {
bb.push(decodeURIComponent(data.data));
} else if (data.encoding === "raw") {
bb.push(data.data);
}
} else {
if (typeof data !== "string") {
data += ""; // convert unsupported types to strings
}
// decode UTF-16 to binary string
bb.push(unescape(encodeURIComponent(data)));
}
};
FBB_proto.getBlob = function(type) {
if (!arguments.length) {
type = null;
}
return new FakeBlob(this.data.join(""), type, "raw");
};
FBB_proto.toString = function() {
return "[object BlobBuilder]";
};
FB_proto.slice = function(start, end, type) {
var args = arguments.length;
if (args < 3) {
type = null;
}
return new FakeBlob(
this.data.slice(start, args > 1 ? end : this.data.length)
, type
, this.encoding
);
};
FB_proto.toString = function() {
return "[object Blob]";
};
return FakeBlobBuilder;
}(self));

2
js/Blob.js/BlobBuilder.min.js vendored Normal file
View File

@ -0,0 +1,2 @@
/*! @source http://purl.eligrey.com/github/BlobBuilder.js/blob/master/BlobBuilder.js */
var BlobBuilder=BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||(function(j){"use strict";var c=function(v){return Object.prototype.toString.call(v).match(/^\[object\s(.*)\]$/)[1]},u=function(){this.data=[]},t=function(x,v,w){this.data=x;this.size=x.length;this.type=v;this.encoding=w},k=u.prototype,s=t.prototype,n=j.FileReaderSync,a=function(v){this.code=this[this.name=v]},l=("NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR").split(" "),r=l.length,o=j.URL||j.webkitURL||j,p=o.createObjectURL,b=o.revokeObjectURL,e=o,i=j.btoa,f=j.atob,m=false,h=function(v){m=!v},d=j.ArrayBuffer,g=j.Uint8Array;u.fake=s.fake=true;while(r--){a.prototype[l[r]]=r+1}try{if(g){h.apply(0,new g(1))}}catch(q){}if(!o.createObjectURL){e=j.URL={}}e.createObjectURL=function(w){var x=w.type,v;if(x===null){x="application/octet-stream"}if(w instanceof t){v="data:"+x;if(w.encoding==="base64"){return v+";base64,"+w.data}else{if(w.encoding==="URI"){return v+","+decodeURIComponent(w.data)}}if(i){return v+";base64,"+i(w.data)}else{return v+","+encodeURIComponent(w.data)}}else{if(real_create_object_url){return real_create_object_url.call(o,w)}}};e.revokeObjectURL=function(v){if(v.substring(0,5)!=="data:"&&real_revoke_object_url){real_revoke_object_url.call(o,v)}};k.append=function(z){var B=this.data;if(g&&z instanceof d){if(m){B.push(String.fromCharCode.apply(String,new g(z)))}else{var A="",w=new g(z),x=0,y=w.length;for(;x<y;x++){A+=String.fromCharCode(w[x])}}}else{if(c(z)==="Blob"||c(z)==="File"){if(n){var v=new n;B.push(v.readAsBinaryString(z))}else{throw new a("NOT_READABLE_ERR")}}else{if(z instanceof t){if(z.encoding==="base64"&&f){B.push(f(z.data))}else{if(z.encoding==="URI"){B.push(decodeURIComponent(z.data))}else{if(z.encoding==="raw"){B.push(z.data)}}}}else{if(typeof z!=="string"){z+=""}B.push(unescape(encodeURIComponent(z)))}}}};k.getBlob=function(v){if(!arguments.length){v=null}return new t(this.data.join(""),v,"raw")};k.toString=function(){return"[object BlobBuilder]"};s.slice=function(y,v,x){var w=arguments.length;if(w<3){x=null}return new t(this.data.slice(y,w>1?v:this.data.length),x,this.encoding)};s.toString=function(){return"[object Blob]"};return u}(self));

30
js/Blob.js/LICENSE.md Normal file
View File

@ -0,0 +1,30 @@
This software is licensed under the MIT/X11 license.
MIT/X11 license
---------------
Copyright &copy; 2011 [Eli Grey][1].
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.
[1]: http://eligrey.com

9
js/Blob.js/README.md Normal file
View File

@ -0,0 +1,9 @@
Blob.js
==============
Blob.js implements the W3C [`Blob`][1] interface in browsers that do
not natively support it.
![Tracking image](https://in.getclicky.com/212712ns.gif)
[1]: http://www.w3.org/TR/FileAPI/#blob

182
js/Deflate/adler32cs.js Normal file
View File

@ -0,0 +1,182 @@
/*
* Copyright (c) 2012 chick307 <chick307@gmail.com>
*
* Licensed under the MIT License.
* http://opensource.org/licenses/mit-license
*/
void function(global, callback) {
if (typeof module === 'object') {
module.exports = callback();
} else if (typeof define === 'function') {
define(callback);
} else {
global.adler32cs = callback();
}
}(this, function() {
var _hasArrayBuffer = typeof ArrayBuffer === 'function' &&
typeof Uint8Array === 'function';
var _Buffer = null, _isBuffer = (function() {
if (!_hasArrayBuffer)
return function _isBuffer() { return false };
try {
var buffer = require('buffer');
if (typeof buffer.Buffer === 'function')
_Buffer = buffer.Buffer;
} catch (error) {}
return function _isBuffer(value) {
return value instanceof ArrayBuffer ||
_Buffer !== null && value instanceof _Buffer;
};
}());
var _utf8ToBinary = (function() {
if (_Buffer !== null) {
return function _utf8ToBinary(utf8String) {
return new _Buffer(utf8String, 'utf8').toString('binary');
};
} else {
return function _utf8ToBinary(utf8String) {
return unescape(encodeURIComponent(utf8String));
};
}
}());
var MOD = 65521;
var _update = function _update(checksum, binaryString) {
var a = checksum & 0xFFFF, b = checksum >>> 16;
for (var i = 0, length = binaryString.length; i < length; i++) {
a = (a + (binaryString.charCodeAt(i) & 0xFF)) % MOD;
b = (b + a) % MOD;
}
return (b << 16 | a) >>> 0;
};
var _updateUint8Array = function _updateUint8Array(checksum, uint8Array) {
var a = checksum & 0xFFFF, b = checksum >>> 16;
for (var i = 0, length = uint8Array.length, x; i < length; i++) {
a = (a + uint8Array[i]) % MOD;
b = (b + a) % MOD;
}
return (b << 16 | a) >>> 0
};
var exports = {};
var Adler32 = exports.Adler32 = (function() {
var ctor = function Adler32(checksum) {
if (!(this instanceof ctor)) {
throw new TypeError(
'Constructor cannot called be as a function.');
}
if (!isFinite(checksum = checksum == null ? 1 : +checksum)) {
throw new Error(
'First arguments needs to be a finite number.');
}
this.checksum = checksum >>> 0;
};
var proto = ctor.prototype = {};
proto.constructor = ctor;
ctor.from = function(from) {
from.prototype = proto;
return from;
}(function from(binaryString) {
if (!(this instanceof ctor)) {
throw new TypeError(
'Constructor cannot called be as a function.');
}
if (binaryString == null)
throw new Error('First argument needs to be a string.');
this.checksum = _update(1, binaryString.toString());
});
ctor.fromUtf8 = function(fromUtf8) {
fromUtf8.prototype = proto;
return fromUtf8;
}(function fromUtf8(utf8String) {
if (!(this instanceof ctor)) {
throw new TypeError(
'Constructor cannot called be as a function.');
}
if (utf8String == null)
throw new Error('First argument needs to be a string.');
var binaryString = _utf8ToBinary(utf8String.toString());
this.checksum = _update(1, binaryString);
});
if (_hasArrayBuffer) {
ctor.fromBuffer = function(fromBuffer) {
fromBuffer.prototype = proto;
return fromBuffer;
}(function fromBuffer(buffer) {
if (!(this instanceof ctor)) {
throw new TypeError(
'Constructor cannot called be as a function.');
}
if (!_isBuffer(buffer))
throw new Error('First argument needs to be ArrayBuffer.');
var array = new Uint8Array(buffer);
return this.checksum = _updateUint8Array(1, array);
});
}
proto.update = function update(binaryString) {
if (binaryString == null)
throw new Error('First argument needs to be a string.');
binaryString = binaryString.toString();
return this.checksum = _update(this.checksum, binaryString);
};
proto.updateUtf8 = function updateUtf8(utf8String) {
if (utf8String == null)
throw new Error('First argument needs to be a string.');
var binaryString = _utf8ToBinary(utf8String.toString());
return this.checksum = _update(this.checksum, binaryString);
};
if (_hasArrayBuffer) {
proto.updateBuffer = function updateBuffer(buffer) {
if (!_isBuffer(buffer))
throw new Error('First argument needs to be ArrayBuffer.');
var array = new Uint8Array(buffer);
return this.checksum = _updateUint8Array(this.checksum, array);
};
}
proto.clone = function clone() {
return new Adler32(this.checksum);
};
return ctor;
}());
exports.from = function from(binaryString) {
if (binaryString == null)
throw new Error('First argument needs to be a string.');
return _update(1, binaryString.toString());
};
exports.fromUtf8 = function fromUtf8(utf8String) {
if (utf8String == null)
throw new Error('First argument needs to be a string.');
var binaryString = _utf8ToBinary(utf8String.toString());
return _update(1, binaryString);
};
if (_hasArrayBuffer) {
exports.fromBuffer = function fromBuffer(buffer) {
if (!_isBuffer(buffer))
throw new Error('First argument need to be ArrayBuffer.');
var array = new Uint8Array(buffer);
return _updateUint8Array(1, array);
};
}
return exports;
});

2053
js/Deflate/deflate.js Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,22 @@
Downloadify: Client Side File Creation
JavaScript + Flash Library
Copyright (c) 2009 Douglas C. Neiner
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,113 @@
h2. Downloadify: Client Side File Creation
*_Important! The swf has been compiled for online use only. Testing from the file path (i.e. file:// ) will not work as it will violate the security sandbox._*
h3. Overview
This library is a tiny JavaScript + Flash library that allows you to generate files on the fly, in the browser, without server interaction. Web applications that allow you to generate vCards, color palettes, custom code, etc would benefit from using this library. In addition to increasing speed (no round trip to the server) this solution can reduce the database and server load of existing web applications. _This is not a library to 'force download' a file from a server. It does not interact with a server at all._
h3. Demo
A "very simple demo is available":http://pixelgraphics.us/downloadify/test.html that lets you supply your own content and filename and test out saving, canceling, and the error functionality when the file is blank.
For a real world usage, see "Starter for jQuery":http://starter.pixelgraphics.us . To quickly demo the usage, just click "Load Example Data" then click Download. After the initial page load, no further contact is made with the server. Everything happens on the client side.
h3. Download
Please download from the "Downloads":http://github.com/dcneiner/Downloadify/downloads section of this project.
h3. Support
For support, please use the "Issues":http://github.com/dcneiner/Downloadify/issues section of this project. You can also try to hit me up on "Twitter at @dougneiner":http://twitter.com/dougneiner but I might just ask you to file an issue. :)
h3. Dependencies
_The end user must have Flash 10 or higher installed for this plugin to work. As of September 2009, it was at a 93% saturation, so most users should already have it installed._
Downloadify is only dependent on "SWFObject 2.0":http://code.google.com/p/swfobject/ which is included with the download. It is compatible with any JavaScript framework but has a helper for both jQuery and MooTools. Neither helper will be activatd if Downloadify is inserted prior to including the framework library.
h3. Usage
*Any JavaScript framework*:
<pre>Downloadify.create( id_or_DOM_element, options );</pre>
*jQuery*:
<pre>$("#element").downloadify( options );</pre>
*MooTools:*
<pre>$("elementid").downloadify( options );</pre>
h3. Options
Unless you are using the jQuery plugin included with Downloadify, you must supply all required options with your call to the <tt>Downloadify.create</tt> function.
*Defaults and Required Options*
* <tt>swf</tt>: <tt>'media/downloadify.swf'</tt> <span style="color:red">*Required*</span> <br />_Path to the SWF File. Can be relative from the page, or an absolute path._
* <tt>downloadImage</tt>: <tt>'images/download.png'</tt> <span style="color:red">*Required*</span> <br />_Path to the Button Image. Can be relative from the page or an absolute path._
* <tt>width</tt>: 175 <span style="color:red">*Required*</span> <br />_Width of the button (and the flash movie)_
* <tt>height</tt>: 55 <span style="color:red">*Required*</span> <br />_Height of the button. This will be 1/4 the height of the image._
* <tt>filename</tt>: <span style="color:red">*Required*</span><br /> _Can be a String or a function callback. If a function, the return value of the function will be used as the filename._
* <tt>data</tt>: <span style="color:red">*Required*</span><br /> _Can be a normal String, base64 encoded String, or a function callback. If a function, the return value of the function will be used as the file data._
* <tt>dataType</tt>: <tt>'string'</tt><br /> _Must be a String with the value <tt>string</tt> or <tt>base64</tt>. Data paired with the <tt>dataType</tt> of <tt>base64</tt> will be decoded into a <tt>ByteArray</tt> prior to saving._
* <tt>transparent</tt>: false <br />_Set this to true to use wmode=transparent on the flash movie._
* <tt>append</tt>: false <br />_By default the contents of the targeted DOM element are removed. Set this to true to keep the contents and append the button._
*Event Callbacks*
No data is passed into these functions, they are simply called.
* <tt>onError</tt>: _Called when the Download button is clicked but your <tt>data</tt> callback returns <tt>""</tt>._
* <tt>onCancel</tt>: _Called when the Download button is clicked but the user then cancels without saving._
* <tt>onComplete</tt>: _Called when the Download button is clicked and the file is saved to the user's computer._
h3. Setting Up the Image
Downloadify supports (i.e. requires) three button states with limited support for a fourth. The states are:
* *Normal*
* *Over* ( When the mouse hovers over the button )
* *Down* ( When the button is pressed )
* *Disabled* ( Limited support, when .disable() is called on the Downloadify.Container object )
In trying to keep this plugin as simple as possible, all four states are always assumed to be present. You should prepare your button image as a single image the width you want your button, and four times the height of the button. All four states should then live in that one image in the same order as the previous list from top to bottom.
h3. Potential Issues
When working with different button images, you may find Flash has cached your image. This is the desired behavior on a live site, but not during development. To get around this, simply supply a ?rev=1 or ?rev=2 etc on the end of your downloadImage url.
h3. Compiling Notes
I develop locally using Xcode and the Flex 4 SDK Beta 2. Please do not submit request on how to setup a local testing environment. If you are interested in my Xcode project files, send me a message.
h3. Developers
*Core Developer:* "Doug Neiner":http://dougneiner.com
*Contributors:*
* "David Walsh":http://davidwalsh.name -- Contributed the MooTools helper
h3. Change Log
* *Version 0.2*:
** Added support for <tt>base64</tt> via the "as3base64 Library":http://github.com/spjwebster/as3base64
** Added <tt>dataType</tt> option
** Added MooTools helper (Thanks David!)
** Upgraded SWFObject to v2.2
* *Original Release:* Version 0.1
h3. License Information: MIT
as3base64: "Copyright (c) 2006 Steve Webster":http://github.com/spjwebster/as3base64
All Downloadify Code: Copyright (c) 2009 Douglas C. Neiner
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.

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

3
js/Downloadify/js/downloadify.min.js vendored Normal file
View File

@ -0,0 +1,3 @@
/* Downloadify 0.2 (c) 2009 by Douglas Neiner. Licensed under the MIT license */
/* See http://github.com/dcneiner/Downloadify for license and more info */
(function(){Downloadify=window.Downloadify={queue:{},uid:new Date().getTime(),getTextForSave:function(a){var b=Downloadify.queue[a];if(b)return b.getData();return""},getFileNameForSave:function(a){var b=Downloadify.queue[a];if(b)return b.getFilename();return""},getDataTypeForSave:function(a){var b=Downloadify.queue[a];if(b)return b.getDataType();return""},saveComplete:function(a){var b=Downloadify.queue[a];if(b)b.complete();return true},saveCancel:function(a){var b=Downloadify.queue[a];if(b)b.cancel();return true},saveError:function(a){var b=Downloadify.queue[a];if(b)b.error();return true},addToQueue:function(a){Downloadify.queue[a.queue_name]=a},getUID:function(a){if(a.id=="")a.id='downloadify_'+Downloadify.uid++;return a.id}};Downloadify.create=function(a,b){var c=(typeof(a)=="string"?document.getElementById(a):a);return new Downloadify.Container(c,b)};Downloadify.Container=function(d,e){var f=this;f.el=d;f.enabled=true;f.dataCallback=null;f.filenameCallback=null;f.data=null;f.filename=null;var g=function(){f.options=e;if(!f.options.append)f.el.innerHTML="";f.flashContainer=document.createElement('span');f.el.appendChild(f.flashContainer);f.queue_name=Downloadify.getUID(f.flashContainer);if(typeof(f.options.filename)==="function")f.filenameCallback=f.options.filename;else if(f.options.filename)f.filename=f.options.filename;if(typeof(f.options.data)==="function")f.dataCallback=f.options.data;else if(f.options.data)f.data=f.options.data;var a={queue_name:f.queue_name,width:f.options.width,height:f.options.height};var b={allowScriptAccess:'always'};var c={id:f.flashContainer.id,name:f.flashContainer.id};if(f.options.enabled===false)f.enabled=false;if(f.options.transparent===true)b.wmode="transparent";if(f.options.downloadImage)a.downloadImage=f.options.downloadImage;swfobject.embedSWF(f.options.swf,f.flashContainer.id,f.options.width,f.options.height,"10",null,a,b,c);Downloadify.addToQueue(f)};f.enable=function(){var a=document.getElementById(f.flashContainer.id);a.setEnabled(true);f.enabled=true};f.disable=function(){var a=document.getElementById(f.flashContainer.id);a.setEnabled(false);f.enabled=false};f.getData=function(){if(!f.enabled)return"";if(f.dataCallback)return f.dataCallback();else if(f.data)return f.data;else return""};f.getFilename=function(){if(f.filenameCallback)return f.filenameCallback();else if(f.filename)return f.filename;else return""};f.getDataType=function(){if(f.options.dataType)return f.options.dataType;return"string"};f.complete=function(){if(typeof(f.options.onComplete)==="function")f.options.onComplete()};f.cancel=function(){if(typeof(f.options.onCancel)==="function")f.options.onCancel()};f.error=function(){if(typeof(f.options.onError)==="function")f.options.onError()};g()};Downloadify.defaultOptions={swf:'media/downloadify.swf',downloadImage:'images/download.png',width:100,height:30,transparent:true,append:false,dataType:"string"}})();if(typeof(jQuery)!="undefined"){(function($){$.fn.downloadify=function(b){return this.each(function(){b=$.extend({},Downloadify.defaultOptions,b);var a=Downloadify.create(this,b);$(this).data('Downloadify',a)})}})(jQuery)};if(typeof(MooTools)!='undefined'){Element.implement({downloadify:function(a){a=$merge(Downloadify.defaultOptions,a);return this.store('Downloadify',Downloadify.create(this,a))}})};

File diff suppressed because one or more lines are too long

Binary file not shown.

View File

@ -0,0 +1,173 @@
/*
Downloadify: Client Side File Creation
JavaScript + Flash Library
Version: 0.2
Copyright (c) 2009 Douglas C. Neiner
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.
*/
package {
import flash.system.Security;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.net.FileReference;
import flash.net.FileFilter;
import flash.net.URLRequest;
import flash.display.*;
import flash.utils.ByteArray;
import flash.external.ExternalInterface;
import com.dynamicflash.util.Base64;
[SWF(backgroundColor="#CCCCCC")]
[SWF(backgroundAlpha=0)]
public class Downloadify extends Sprite {
private var options:Object,
file:FileReference = new FileReference(),
queue_name:String = "",
_width:Number = 0,
_height:Number = 0,
enabled:Boolean = true,
over:Boolean = false,
down:Boolean = false,
buttonImage:String = "images/download.png",
button:Loader;
public function Downloadify() {
Security.allowDomain('*');
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
options = this.root.loaderInfo.parameters;
queue_name = options.queue_name.toString();
_width = options.width;
_height = options.height;
if(options.downloadImage){
buttonImage = options.downloadImage;
}
setupDefaultButton();
addChild(button);
this.buttonMode = true;
this.addEventListener(MouseEvent.CLICK, onMouseClickEvent);
this.addEventListener(MouseEvent.ROLL_OVER , onMouseEnter);
this.addEventListener(MouseEvent.ROLL_OUT , onMouseLeave);
this.addEventListener(MouseEvent.MOUSE_DOWN , onMouseDown);
this.addEventListener(MouseEvent.MOUSE_UP , onMouseUp);
ExternalInterface.addCallback('setEnabled', setEnabled);
file.addEventListener(Event.COMPLETE, onSaveComplete);
file.addEventListener(Event.CANCEL, onSaveCancel);
}
private function setEnabled(isEnabled:Boolean):Boolean {
enabled = isEnabled;
if(enabled === true){
button.y = 0;
this.buttonMode = true;
} else {
button.y = (-3 * _height);
this.buttonMode = false;
}
return enabled;
}
private function setupDefaultButton():void {
button = new Loader();
var urlReq:URLRequest = new URLRequest(buttonImage);
button.load(urlReq);
button.x = 0;
button.y = 0;
}
protected function onMouseEnter(event:Event):void {
if(enabled === true){
if(down === false) button.y = (-1 * _height);
over = true;
}
}
protected function onMouseLeave(event:Event):void {
if(enabled === true){
if(down === false) button.y = 0;
over = false;
}
}
protected function onMouseDown(event:Event):void {
if(enabled === true){
button.y = button.y = (-2 * _height);
down = true;
}
}
protected function onMouseUp(event:Event):void {
if(enabled === true){
if(over === false){
button.y = 0;
} else {
button.y = (-1 * _height);
}
down = false;
}
}
protected function onMouseClickEvent(event:Event):void{
var theData:String = ExternalInterface.call('Downloadify.getTextForSave',queue_name),
filename:String = ExternalInterface.call('Downloadify.getFileNameForSave',queue_name),
dataType:String = ExternalInterface.call('Downloadify.getDataTypeForSave',queue_name);
if (dataType == "string" && theData != "") {
file.save(theData, filename);
} else if (dataType == "base64" && theData){
file.save(Base64.decodeToByteArray(theData), filename);
} else {
onSaveError();
}
}
protected function onSaveComplete(event:Event):void{
trace('Save Complete');
ExternalInterface.call('Downloadify.saveComplete',queue_name);
}
protected function onSaveCancel(event:Event):void{
trace('Save Cancel');
ExternalInterface.call('Downloadify.saveCancel',queue_name);
}
protected function onSaveError():void{
trace('Save Error');
ExternalInterface.call('Downloadify.saveError',queue_name);
}
}
}

View File

@ -0,0 +1,135 @@
/*
Base64 - 1.1.0
Copyright (c) 2006 Steve Webster
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.
*/
package com.dynamicflash.util {
import flash.utils.ByteArray;
public class Base64 {
private static const BASE64_CHARS:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
public static const version:String = "1.1.0";
public static function encode(data:String):String {
// Convert string to ByteArray
var bytes:ByteArray = new ByteArray();
bytes.writeUTFBytes(data);
// Return encoded ByteArray
return encodeByteArray(bytes);
}
public static function encodeByteArray(data:ByteArray):String {
// Initialise output
var output:String = "";
// Create data and output buffers
var dataBuffer:Array;
var outputBuffer:Array = new Array(4);
// Rewind ByteArray
data.position = 0;
// while there are still bytes to be processed
while (data.bytesAvailable > 0) {
// Create new data buffer and populate next 3 bytes from data
dataBuffer = new Array();
for (var i:uint = 0; i < 3 && data.bytesAvailable > 0; i++) {
dataBuffer[i] = data.readUnsignedByte();
}
// Convert to data buffer Base64 character positions and
// store in output buffer
outputBuffer[0] = (dataBuffer[0] & 0xfc) >> 2;
outputBuffer[1] = ((dataBuffer[0] & 0x03) << 4) | ((dataBuffer[1]) >> 4);
outputBuffer[2] = ((dataBuffer[1] & 0x0f) << 2) | ((dataBuffer[2]) >> 6);
outputBuffer[3] = dataBuffer[2] & 0x3f;
// If data buffer was short (i.e not 3 characters) then set
// end character indexes in data buffer to index of '=' symbol.
// This is necessary because Base64 data is always a multiple of
// 4 bytes and is basses with '=' symbols.
for (var j:uint = dataBuffer.length; j < 3; j++) {
outputBuffer[j + 1] = 64;
}
// Loop through output buffer and add Base64 characters to
// encoded data string for each character.
for (var k:uint = 0; k < outputBuffer.length; k++) {
output += BASE64_CHARS.charAt(outputBuffer[k]);
}
}
// Return encoded data
return output;
}
public static function decode(data:String):String {
// Decode data to ByteArray
var bytes:ByteArray = decodeToByteArray(data);
// Convert to string and return
return bytes.readUTFBytes(bytes.length);
}
public static function decodeToByteArray(data:String):ByteArray {
// Initialise output ByteArray for decoded data
var output:ByteArray = new ByteArray();
// Create data and output buffers
var dataBuffer:Array = new Array(4);
var outputBuffer:Array = new Array(3);
// While there are data bytes left to be processed
for (var i:uint = 0; i < data.length; i += 4) {
// Populate data buffer with position of Base64 characters for
// next 4 bytes from encoded data
for (var j:uint = 0; j < 4 && i + j < data.length; j++) {
dataBuffer[j] = BASE64_CHARS.indexOf(data.charAt(i + j));
}
// Decode data buffer back into bytes
outputBuffer[0] = (dataBuffer[0] << 2) + ((dataBuffer[1] & 0x30) >> 4);
outputBuffer[1] = ((dataBuffer[1] & 0x0f) << 4) + ((dataBuffer[2] & 0x3c) >> 2);
outputBuffer[2] = ((dataBuffer[2] & 0x03) << 6) + dataBuffer[3];
// Add all non-padded bytes in output buffer to decoded data
for (var k:uint = 0; k < outputBuffer.length; k++) {
if (dataBuffer[k+1] == 64) break;
output.writeByte(outputBuffer[k]);
}
}
// Rewind decoded data ByteArray
output.position = 0;
// Return decoded data
return output;
}
public function Base64() {
throw new Error("Base64 class is static container only");
}
}
}

View File

@ -0,0 +1,60 @@
/*
Copyright (c) 2006 Steve Webster
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.
*/
package com.dynamicflash.util.tests {
import flexunit.framework.TestCase;
import flexunit.framework.TestSuite;
import flash.utils.ByteArray;
import com.dynamicflash.util.Base64;
public class Base64Test extends TestCase {
public function Base64Test(methodName:String = null) {
super(methodName);
}
public function testEncode():void {
assertEquals("VGhpcyBpcyBhIHRlc3Q=",Base64.encode("This is a test"));
}
public function testEncodeDecodeBytes():void {
var obj:Object = {name:"Dynamic Flash", url:"http://dynamicflash.com"};
var source:ByteArray = new ByteArray();
source.writeObject(obj);
var encoded:String = Base64.encodeByteArray(source);
var decoded:ByteArray = Base64.decodeToByteArray(encoded);
var obj2:Object = decoded.readObject();
assertEquals(obj.name, obj2.name);
assertEquals(obj.url, obj2.url);
}
public function testDecode():void {
assertEquals("This is a test",Base64.decode("VGhpcyBpcyBhIHRlc3Q="));
}
public function testEncodeDecode():void {
var string:String = "The quick brown fox jumped over the lazy dogs";
assertEquals(string, Base64.decode(Base64.encode(string)));
}
}
}

View File

@ -0,0 +1,213 @@
/*
Downloadify: Client Side File Creation
JavaScript + Flash Library
Version: 0.2
Copyright (c) 2009 Douglas C. Neiner
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.
*/
(function(){
Downloadify = window.Downloadify = {
queue: {},
uid: new Date().getTime(),
getTextForSave: function(queue){
var obj = Downloadify.queue[queue];
if(obj) return obj.getData();
return "";
},
getFileNameForSave: function(queue){
var obj = Downloadify.queue[queue];
if(obj) return obj.getFilename();
return "";
},
getDataTypeForSave: function(queue){
var obj = Downloadify.queue[queue];
if(obj) return obj.getDataType();
return "";
},
saveComplete: function(queue){
var obj = Downloadify.queue[queue];
if(obj) obj.complete();
return true;
},
saveCancel: function(queue){
var obj = Downloadify.queue[queue];
if(obj) obj.cancel();
return true;
},
saveError: function(queue){
var obj = Downloadify.queue[queue];
if(obj) obj.error();
return true;
},
addToQueue: function(container){
Downloadify.queue[container.queue_name] = container;
},
// Concept adapted from: http://tinyurl.com/yzsyfto
// SWF object runs off of ID's, so this is the good way to get a unique ID
getUID: function(el){
if(el.id == "") el.id = 'downloadify_' + Downloadify.uid++;
return el.id;
}
};
Downloadify.create = function( idOrDOM, options ){
var el = (typeof(idOrDOM) == "string" ? document.getElementById(idOrDOM) : idOrDOM );
return new Downloadify.Container(el, options);
};
Downloadify.Container = function(el, options){
var base = this;
base.el = el;
base.enabled = true;
base.dataCallback = null;
base.filenameCallback = null;
base.data = null;
base.filename = null;
var init = function(){
base.options = options;
if( !base.options.append ) base.el.innerHTML = "";
base.flashContainer = document.createElement('span');
base.el.appendChild(base.flashContainer);
base.queue_name = Downloadify.getUID( base.flashContainer );
if( typeof(base.options.filename) === "function" )
base.filenameCallback = base.options.filename;
else if (base.options.filename)
base.filename = base.options.filename;
if( typeof(base.options.data) === "function" )
base.dataCallback = base.options.data;
else if (base.options.data)
base.data = base.options.data;
var flashVars = {
queue_name: base.queue_name,
width: base.options.width,
height: base.options.height
};
var params = {
allowScriptAccess: 'always'
};
var attributes = {
id: base.flashContainer.id,
name: base.flashContainer.id
};
if(base.options.enabled === false) base.enabled = false;
if(base.options.transparent === true) params.wmode = "transparent";
if(base.options.downloadImage) flashVars.downloadImage = base.options.downloadImage;
swfobject.embedSWF(base.options.swf, base.flashContainer.id, base.options.width, base.options.height, "10", null, flashVars, params, attributes );
Downloadify.addToQueue( base );
};
base.enable = function(){
var swf = document.getElementById(base.flashContainer.id);
swf.setEnabled(true);
base.enabled = true;
};
base.disable = function(){
var swf = document.getElementById(base.flashContainer.id);
swf.setEnabled(false);
base.enabled = false;
};
base.getData = function(){
if( !base.enabled ) return "";
if( base.dataCallback ) return base.dataCallback();
else if (base.data) return base.data;
else return "";
};
base.getFilename = function(){
if( base.filenameCallback ) return base.filenameCallback();
else if (base.filename) return base.filename;
else return "";
};
base.getDataType = function(){
if (base.options.dataType) return base.options.dataType;
return "string";
};
base.complete = function(){
if( typeof(base.options.onComplete) === "function" ) base.options.onComplete();
};
base.cancel = function(){
if( typeof(base.options.onCancel) === "function" ) base.options.onCancel();
};
base.error = function(){
if( typeof(base.options.onError) === "function" ) base.options.onError();
};
init();
};
Downloadify.defaultOptions = {
swf: 'media/downloadify.swf',
downloadImage: 'images/download.png',
width: 100,
height: 30,
transparent: true,
append: false,
dataType: "string"
};
})();
// Support for jQuery
if(typeof(jQuery) != "undefined"){
(function($){
$.fn.downloadify = function(options){
return this.each(function(){
options = $.extend({}, Downloadify.defaultOptions, options);
var dl = Downloadify.create( this, options);
$(this).data('Downloadify', dl);
});
};
})(jQuery);
};
/* mootools helper */
if(typeof(MooTools) != 'undefined'){
Element.implement({
downloadify: function(options) {
options = $merge(Downloadify.defaultOptions,options);
return this.store('Downloadify',Downloadify.create(this,options));
}
});
};

84
js/Downloadify/test.html Normal file
View File

@ -0,0 +1,84 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>Downloadify</title>
<style type="text/css" media="screen">
body {background: #fff; width: 500px; margin: 20px auto;}
label, input, textarea, h1, h2, p { font-family: Arial, sans-serif; font-size: 12pt;}
input, textarea { border: solid 1px #aaa; padding: 4px; width: 98%;}
label { font-weight: bold;}
h1 { font-size: 30pt; font-weight: bold; letter-spacing: -1px;}
h2 { font-size: 14pt;}
pre { overflow: auto; padding: 10px; background: #222; color: #ccc;}
</style>
<script type="text/javascript" src="js/swfobject.js"></script>
<script type="text/javascript" src="js/downloadify.min.js"></script>
</head>
<body onload="load();">
<h1>Downloadify Example</h1>
<p>More info available at the <a href="http://github.com/dcneiner/Downloadify">Github Project Page</a></p>
<form>
<p>
<label for="filename">Filename</label><br />
<input type="text" name="filename" value="testfile.txt" id="filename" />
</p>
<p>
<label for="data">File Contents</label><br />
<textarea cols="60" rows="10" name="data" id="data">
Whatever you put in this text box will be downloaded and saved in the file. If you leave it blank, no file will be downloaded</textarea>
</p>
<p id="downloadify">
You must have Flash 10 installed to download this file.
</p>
</form>
<script type="text/javascript">
function load(){
Downloadify.create('downloadify',{
filename: function(){
return document.getElementById('filename').value;
},
data: function(){
return document.getElementById('data').value;
},
onComplete: function(){ alert('Your File Has Been Saved!'); },
onCancel: function(){ alert('You have cancelled the saving of this file.'); },
onError: function(){ alert('You must put something in the File Contents or there will be nothing to save!'); },
swf: 'media/downloadify.swf',
downloadImage: 'images/download.png',
width: 100,
height: 30,
transparent: true,
append: false
});
}
</script>
<h2>Downloadify Invoke Script For This Page</h2>
<pre>
Downloadify.create(&#x27;downloadify&#x27;,{
filename: function(){
return document.getElementById(&#x27;filename&#x27;).value;
},
data: function(){
return document.getElementById(&#x27;data&#x27;).value;
},
onComplete: function(){
alert(&#x27;Your File Has Been Saved!&#x27;);
},
onCancel: function(){
alert(&#x27;You have cancelled the saving of this file.&#x27;);
},
onError: function(){
alert(&#x27;You must put something in the File Contents or there will be nothing to save!&#x27;);
},
swf: &#x27;media/downloadify.swf&#x27;,
downloadImage: &#x27;images/download.png&#x27;,
width: 100,
height: 30,
transparent: true,
append: false
});
</pre>
</body>
</html>

View File

@ -0,0 +1,217 @@
/* FileSaver.js
* A saveAs() FileSaver implementation.
* 2013-01-23
*
* By Eli Grey, http://eligrey.com
* License: X11/MIT
* See LICENSE.md
*/
/*global self */
/*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true,
plusplus: true */
/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
var saveAs = saveAs
|| (navigator.msSaveBlob && navigator.msSaveBlob.bind(navigator))
|| (function(view) {
"use strict";
var
doc = view.document
// only get URL when necessary in case BlobBuilder.js hasn't overridden it yet
, get_URL = function() {
return view.URL || view.webkitURL || view;
}
, URL = view.URL || view.webkitURL || view
, save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
, can_use_save_link = "download" in save_link
, click = function(node) {
var event = doc.createEvent("MouseEvents");
event.initMouseEvent(
"click", true, false, view, 0, 0, 0, 0, 0
, false, false, false, false, 0, null
);
return node.dispatchEvent(event); // false if event was cancelled
}
, webkit_req_fs = view.webkitRequestFileSystem
, req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem
, throw_outside = function (ex) {
(view.setImmediate || view.setTimeout)(function() {
throw ex;
}, 0);
}
, force_saveable_type = "application/octet-stream"
, fs_min_size = 0
, deletion_queue = []
, process_deletion_queue = function() {
var i = deletion_queue.length;
while (i--) {
var file = deletion_queue[i];
if (typeof file === "string") { // file is an object URL
URL.revokeObjectURL(file);
} else { // file is a File
file.remove();
}
}
deletion_queue.length = 0; // clear queue
}
, dispatch = function(filesaver, event_types, event) {
event_types = [].concat(event_types);
var i = event_types.length;
while (i--) {
var listener = filesaver["on" + event_types[i]];
if (typeof listener === "function") {
try {
listener.call(filesaver, event || filesaver);
} catch (ex) {
throw_outside(ex);
}
}
}
}
, FileSaver = function(blob, name) {
// First try a.download, then web filesystem, then object URLs
var
filesaver = this
, type = blob.type
, blob_changed = false
, object_url
, target_view
, get_object_url = function() {
var object_url = get_URL().createObjectURL(blob);
deletion_queue.push(object_url);
return object_url;
}
, dispatch_all = function() {
dispatch(filesaver, "writestart progress write writeend".split(" "));
}
// on any filesys errors revert to saving with object URLs
, fs_error = function() {
// don't create more object URLs than needed
if (blob_changed || !object_url) {
object_url = get_object_url(blob);
}
if (target_view) {
target_view.location.href = object_url;
}
filesaver.readyState = filesaver.DONE;
dispatch_all();
}
, abortable = function(func) {
return function() {
if (filesaver.readyState !== filesaver.DONE) {
return func.apply(this, arguments);
}
};
}
, create_if_not_found = {create: true, exclusive: false}
, slice
;
filesaver.readyState = filesaver.INIT;
if (!name) {
name = "download";
}
if (can_use_save_link) {
object_url = get_object_url(blob);
save_link.href = object_url;
save_link.download = name;
if (click(save_link)) {
filesaver.readyState = filesaver.DONE;
dispatch_all();
return;
}
}
// Object and web filesystem URLs have a problem saving in Google Chrome when
// viewed in a tab, so I force save with application/octet-stream
// http://code.google.com/p/chromium/issues/detail?id=91158
if (view.chrome && type && type !== force_saveable_type) {
slice = blob.slice || blob.webkitSlice;
blob = slice.call(blob, 0, blob.size, force_saveable_type);
blob_changed = true;
}
// Since I can't be sure that the guessed media type will trigger a download
// in WebKit, I append .download to the filename.
// https://bugs.webkit.org/show_bug.cgi?id=65440
if (webkit_req_fs && name !== "download") {
name += ".download";
}
if (type === force_saveable_type || webkit_req_fs) {
target_view = view;
} else {
target_view = view.open();
}
if (!req_fs) {
fs_error();
return;
}
fs_min_size += blob.size;
req_fs(view.TEMPORARY, fs_min_size, abortable(function(fs) {
fs.root.getDirectory("saved", create_if_not_found, abortable(function(dir) {
var save = function() {
dir.getFile(name, create_if_not_found, abortable(function(file) {
file.createWriter(abortable(function(writer) {
writer.onwriteend = function(event) {
target_view.location.href = file.toURL();
deletion_queue.push(file);
filesaver.readyState = filesaver.DONE;
dispatch(filesaver, "writeend", event);
};
writer.onerror = function() {
var error = writer.error;
if (error.code !== error.ABORT_ERR) {
fs_error();
}
};
"writestart progress write abort".split(" ").forEach(function(event) {
writer["on" + event] = filesaver["on" + event];
});
writer.write(blob);
filesaver.abort = function() {
writer.abort();
filesaver.readyState = filesaver.DONE;
};
filesaver.readyState = filesaver.WRITING;
}), fs_error);
}), fs_error);
};
dir.getFile(name, {create: false}, abortable(function(file) {
// delete file if it already exists
file.remove();
save();
}), abortable(function(ex) {
if (ex.code === ex.NOT_FOUND_ERR) {
save();
} else {
fs_error();
}
}));
}), fs_error);
}), fs_error);
}
, FS_proto = FileSaver.prototype
, saveAs = function(blob, name) {
return new FileSaver(blob, name);
}
;
FS_proto.abort = function() {
var filesaver = this;
filesaver.readyState = filesaver.DONE;
dispatch(filesaver, "abort");
};
FS_proto.readyState = FS_proto.INIT = 0;
FS_proto.WRITING = 1;
FS_proto.DONE = 2;
FS_proto.error =
FS_proto.onwritestart =
FS_proto.onprogress =
FS_proto.onwrite =
FS_proto.onabort =
FS_proto.onerror =
FS_proto.onwriteend =
null;
view.addEventListener("unload", process_deletion_queue, false);
return saveAs;
}(self));

2
js/FileSaver.js/FileSaver.min.js vendored Normal file
View File

@ -0,0 +1,2 @@
/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
var saveAs=saveAs||navigator.msSaveBlob&&navigator.msSaveBlob.bind(navigator)||function(a){"use strict";var b=a.document,c=function(){return a.URL||a.webkitURL||a},d=a.URL||a.webkitURL||a,e=b.createElementNS("http://www.w3.org/1999/xhtml","a"),f="download"in e,g=function(c){var d=b.createEvent("MouseEvents");return d.initMouseEvent("click",!0,!1,a,0,0,0,0,0,!1,!1,!1,!1,0,null),c.dispatchEvent(d)},h=a.webkitRequestFileSystem,i=a.requestFileSystem||h||a.mozRequestFileSystem,j=function(b){(a.setImmediate||a.setTimeout)(function(){throw b},0)},k="application/octet-stream",l=0,m=[],n=function(){for(var a=m.length;a--;){var b=m[a];"string"==typeof b?d.revokeObjectURL(b):b.remove()}m.length=0},o=function(a,b,c){b=[].concat(b);for(var d=b.length;d--;){var e=a["on"+b[d]];if("function"==typeof e)try{e.call(a,c||a)}catch(f){j(f)}}},p=function(b,d){var q,r,x,j=this,n=b.type,p=!1,s=function(){var a=c().createObjectURL(b);return m.push(a),a},t=function(){o(j,"writestart progress write writeend".split(" "))},u=function(){(p||!q)&&(q=s(b)),r&&(r.location.href=q),j.readyState=j.DONE,t()},v=function(a){return function(){return j.readyState!==j.DONE?a.apply(this,arguments):void 0}},w={create:!0,exclusive:!1};return j.readyState=j.INIT,d||(d="download"),f&&(q=s(b),e.href=q,e.download=d,g(e))?(j.readyState=j.DONE,t(),void 0):(a.chrome&&n&&n!==k&&(x=b.slice||b.webkitSlice,b=x.call(b,0,b.size,k),p=!0),h&&"download"!==d&&(d+=".download"),r=n===k||h?a:a.open(),i?(l+=b.size,i(a.TEMPORARY,l,v(function(a){a.root.getDirectory("saved",w,v(function(a){var c=function(){a.getFile(d,w,v(function(a){a.createWriter(v(function(c){c.onwriteend=function(b){r.location.href=a.toURL(),m.push(a),j.readyState=j.DONE,o(j,"writeend",b)},c.onerror=function(){var a=c.error;a.code!==a.ABORT_ERR&&u()},"writestart progress write abort".split(" ").forEach(function(a){c["on"+a]=j["on"+a]}),c.write(b),j.abort=function(){c.abort(),j.readyState=j.DONE},j.readyState=j.WRITING}),u)}),u)};a.getFile(d,{create:!1},v(function(a){a.remove(),c()}),v(function(a){a.code===a.NOT_FOUND_ERR?c():u()}))}),u)}),u),void 0):(u(),void 0))},q=p.prototype,r=function(a,b){return new p(a,b)};return q.abort=function(){var a=this;a.readyState=a.DONE,o(a,"abort")},q.readyState=q.INIT=0,q.WRITING=1,q.DONE=2,q.error=q.onwritestart=q.onprogress=q.onwrite=q.onabort=q.onerror=q.onwriteend=null,a.addEventListener("unload",n,!1),r}(self);

View File

@ -0,0 +1,30 @@
This software is licensed under the MIT/X11 license.
MIT/X11 license
---------------
Copyright &copy; 2011 [Eli Grey][1].
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.
[1]: http://eligrey.com

69
js/FileSaver.js/README.md Normal file
View File

@ -0,0 +1,69 @@
FileSaver.js
============
FileSaver.js implements the W3C `saveAs()` [FileSaver][1] interface in browsers that do
not natively support it. There is a [FileSaver.js demo][2] that demonstrates saving
various media types.
FileSaver.js is the solution to saving files on the client side, and is perfect for
webapps that need to generate files or for saving sensitive information that shouldn't be
sent to an external server.
Supported Browsers
------------------
* Internet Explorer 10+
* Firefox 4+
* Google Chrome
* Opera 11+
* Safari 5+
Unlisted versions of browsers (e.g. Firefox 3.6) will probably work too; I just haven't
tested them.
Syntax
------
FileSaver saveAs(in Blob data, in DOMString filename)
Examples
--------
### Saving text
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");
The standard W3C File API [`Blob`][3] interface is not available in all browsers.
[Blob.js][4] is a cross-browser `BlobBuilder` implementation that solves this.
### Saving a canvas
var canvas = document.getElementById("my-canvas"), ctx = canvas.getContext("2d");
// draw to canvas...
canvas.toBlob(function(blob) {
saveAs(blob, "pretty image.png");
});
Note: The standard HTML5 `canvas.toBlob()` method is not available in all browsers.
[canvas-toBlob.js][5] is a cross-browser `canvas.toBlob()` implementation that solves
this.
### Aborting a save
var filesaver = saveAs(blob, "whatever");
cancel_button.addEventListener("click", function() {
if (filesaver.abort) {
filesaver.abort();
}
}, false);
This isn't that useful unless you're saving very large files (e.g. generated video).
![Tracking image](https://in.getclicky.com/212712ns.gif)
[1]: http://www.w3.org/TR/file-writer-api/#the-filesaver-interface
[2]: http://oftn.org/projects/FileSaver.js/demo/
[3]: https://developer.mozilla.org/en-US/docs/DOM/Blob
[4]: https://github.com/eligrey/Blob.js
[5]: https://github.com/eligrey/canvas-toBlob.js

View File

@ -0,0 +1,55 @@
html {
background-color: #DDD;
}
body {
width: 900px;
margin: 0 auto;
font-family: Verdana, Helvetica, Arial, sans-serif;
box-shadow: 0 0 5px #000;
box-shadow: 0 0 10px 2px rgba(0, 0, 0, .5);
padding: 7px 25px;
background-color: #FFF;
}
h1, h2, h3, h4, h5, h6 {
font-family: Georgia, "Times New Roman", serif;
}
h2, form {
text-align: center;
}
form {
margin-top: 5px;
}
.input {
width: 500px;
height: 300px;
margin: 0 auto;
display: block;
}
section {
margin-top: 40px;
}
dt {
font-weight: bold;
font-size: larger;
}
#canvas {
cursor: crosshair;
}
#canvas, #html {
border: 1px solid black;
}
.filename {
text-align: right;
}
#html {
box-sizing: border-box;
ms-box-sizing: border-box;
webkit-box-sizing: border-box;
moz-box-sizing: border-box;
overflow: auto;
padding: 1em;
}
dt:target {
background-color: Highlight;
color: HighlightText;
}

View File

@ -0,0 +1,212 @@
/* FileSaver.js demo script
* 2012-01-23
*
* By Eli Grey, http://eligrey.com
* License: X11/MIT
* See LICENSE.md
*/
/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/demo/demo.js */
(function(view) {
"use strict";
// The canvas drawing portion of the demo is based off the demo at
// http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app/
var
document = view.document
, $ = function(id) {
return document.getElementById(id);
}
, session = view.sessionStorage
// only get URL when necessary in case Blob.js hasn't defined it yet
, get_blob = function() {
return view.Blob;
}
, canvas = $("canvas")
, canvas_options_form = $("canvas-options")
, canvas_filename = $("canvas-filename")
, canvas_clear_button = $("canvas-clear")
, text = $("text")
, text_options_form = $("text-options")
, text_filename = $("text-filename")
, html = $("html")
, html_options_form = $("html-options")
, html_filename = $("html-filename")
, ctx = canvas.getContext("2d")
, drawing = false
, x_points = session.x_points || []
, y_points = session.y_points || []
, drag_points = session.drag_points || []
, add_point = function(x, y, dragging) {
x_points.push(x);
y_points.push(y);
drag_points.push(dragging);
}
, draw = function(){
canvas.width = canvas.width;
ctx.lineWidth = 6;
ctx.lineJoin = "round";
ctx.strokeStyle = "#000000";
var
i = 0
, len = x_points.length
;
for(; i < len; i++) {
ctx.beginPath();
if (i && drag_points[i]) {
ctx.moveTo(x_points[i-1], y_points[i-1]);
} else {
ctx.moveTo(x_points[i]-1, y_points[i]);
}
ctx.lineTo(x_points[i], y_points[i]);
ctx.closePath();
ctx.stroke();
}
}
, stop_drawing = function() {
drawing = false;
}
// Title guesser and document creator available at https://gist.github.com/1059648
, guess_title = function(doc) {
var
h = "h6 h5 h4 h3 h2 h1".split(" ")
, i = h.length
, headers
, header_text
;
while (i--) {
headers = doc.getElementsByTagName(h[i]);
for (var j = 0, len = headers.length; j < len; j++) {
header_text = headers[j].textContent.trim();
if (header_text) {
return header_text;
}
}
}
}
, doc_impl = document.implementation
, create_html_doc = function(html) {
var
dt = doc_impl.createDocumentType('html', null, null)
, doc = doc_impl.createDocument("http://www.w3.org/1999/xhtml", "html", dt)
, doc_el = doc.documentElement
, head = doc_el.appendChild(doc.createElement("head"))
, charset_meta = head.appendChild(doc.createElement("meta"))
, title = head.appendChild(doc.createElement("title"))
, body = doc_el.appendChild(doc.createElement("body"))
, i = 0
, len = html.childNodes.length
;
charset_meta.setAttribute("charset", html.ownerDocument.characterSet);
for (; i < len; i++) {
body.appendChild(doc.importNode(html.childNodes.item(i), true));
}
var title_text = guess_title(doc);
if (title_text) {
title.appendChild(doc.createTextNode(title_text));
}
return doc;
}
;
canvas.width = 500;
canvas.height = 300;
if (typeof x_points === "string") {
x_points = JSON.parse(x_points);
} if (typeof y_points === "string") {
y_points = JSON.parse(y_points);
} if (typeof drag_points === "string") {
drag_points = JSON.parse(drag_points);
} if (session.canvas_filename) {
canvas_filename.value = session.canvas_filename;
} if (session.text) {
text.value = session.text;
} if (session.text_filename) {
text_filename.value = session.text_filename;
} if (session.html) {
html.innerHTML = session.html;
} if (session.html_filename) {
html_filename.value = session.html_filename;
}
drawing = true;
draw();
drawing = false;
canvas_clear_button.addEventListener("click", function() {
canvas.width = canvas.width;
x_points.length =
y_points.length =
drag_points.length =
0;
}, false);
canvas.addEventListener("mousedown", function(event) {
drawing = true;
add_point(event.pageX - canvas.offsetLeft, event.pageY - canvas.offsetTop, false);
draw();
}, false);
canvas.addEventListener("mousemove", function(event) {
if (drawing) {
add_point(event.pageX - canvas.offsetLeft, event.pageY - canvas.offsetTop, true);
draw();
}
}, false);
canvas.addEventListener("mouseup", stop_drawing, false);
canvas.addEventListener("mouseout", stop_drawing, false);
canvas_options_form.addEventListener("submit", function(event) {
event.preventDefault();
canvas.toBlob(function(blob) {
saveAs(
blob
, (canvas_filename.value || canvas_filename.placeholder) + ".png"
);
}, "image/png");
}, false);
text_options_form.addEventListener("submit", function(event) {
event.preventDefault();
var BB = get_blob();
saveAs(
new BB(
[text.value || text.placeholder]
, {type: "text/plain;charset=" + document.characterSet}
)
, (text_filename.value || text_filename.placeholder) + ".txt"
);
}, false);
html_options_form.addEventListener("submit", function(event) {
event.preventDefault();
var
BB = get_blob()
, xml_serializer = new XMLSerializer
, doc = create_html_doc(html)
;
saveAs(
new BB(
[xml_serializer.serializeToString(doc)]
, {type: "application/xhtml+xml;charset=" + document.characterSet}
)
, (html_filename.value || html_filename.placeholder) + ".xhtml"
);
}, false);
view.addEventListener("unload", function() {
session.x_points = JSON.stringify(x_points);
session.y_points = JSON.stringify(y_points);
session.drag_points = JSON.stringify(drag_points);
session.canvas_filename = canvas_filename.value;
session.text = text.value;
session.text_filename = text_filename.value;
session.html = html.innerHTML;
session.html_filename = html_filename.value;
}, false);
}(self));

2
js/FileSaver.js/demo/demo.min.js vendored Normal file
View File

@ -0,0 +1,2 @@
/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/demo/demo.js */
(function(n){"use strict";var s=n.document,g=function(A){return s.getElementById(A)},b=n.sessionStorage,w=function(){return n.BlobBuilder||n.WebKitBlobBuilder||n.MozBlobBuilder},f=g("canvas"),r=g("canvas-options"),y=g("canvas-filename"),p=g("canvas-clear"),q=g("text"),t=g("text-options"),h=g("text-filename"),m=g("html"),e=g("html-options"),i=g("html-filename"),u=f.getContext("2d"),z=false,a=b.x_points||[],o=b.y_points||[],d=b.drag_points||[],j=function(A,C,B){a.push(A);o.push(C);d.push(B)},l=function(){f.width=f.width;u.lineWidth=6;u.lineJoin="round";u.strokeStyle="#000000";var B=0,A=a.length;for(;B<A;B++){u.beginPath();if(B&&d[B]){u.moveTo(a[B-1],o[B-1])}else{u.moveTo(a[B]-1,o[B])}u.lineTo(a[B],o[B]);u.closePath();u.stroke()}},c=function(){z=false},x=function(E){var D="h6 h5 h4 h3 h2 h1".split(" "),C=D.length,F,G;while(C--){F=E.getElementsByTagName(D[C]);for(var B=0,A=F.length;B<A;B++){G=F[B].textContent.trim();if(G){return G}}}},v=s.implementation,k=function(D){var B=v.createDocumentType("html",null,null),J=v.createDocument("http://www.w3.org/1999/xhtml","html",B),A=J.documentElement,H=A.appendChild(J.createElement("head")),K=H.appendChild(J.createElement("meta")),I=H.appendChild(J.createElement("title")),E=A.appendChild(J.createElement("body")),C=0,G=D.childNodes.length;K.setAttribute("charset",D.ownerDocument.characterSet);for(;C<G;C++){E.appendChild(J.importNode(D.childNodes.item(C),true))}var F=x(J);if(F){I.appendChild(J.createTextNode(F))}return J};f.width=500;f.height=300;if(typeof a==="string"){a=JSON.parse(a)}if(typeof o==="string"){o=JSON.parse(o)}if(typeof d==="string"){d=JSON.parse(d)}if(b.canvas_filename){y.value=b.canvas_filename}if(b.text){q.value=b.text}if(b.text_filename){h.value=b.text_filename}if(b.html){m.innerHTML=b.html}if(b.html_filename){i.value=b.html_filename}z=true;l();z=false;p.addEventListener("click",function(){f.width=f.width;a.length=o.length=d.length=0},false);f.addEventListener("mousedown",function(A){z=true;j(A.pageX-f.offsetLeft,A.pageY-f.offsetTop,false);l()},false);f.addEventListener("mousemove",function(A){if(z){j(A.pageX-f.offsetLeft,A.pageY-f.offsetTop,true);l()}},false);f.addEventListener("mouseup",c,false);f.addEventListener("mouseout",c,false);r.addEventListener("submit",function(A){A.preventDefault();f.toBlob(function(B){saveAs(B,(y.value||y.placeholder)+".png")},"image/png")},false);t.addEventListener("submit",function(A){A.preventDefault();var C=w();var B=new C;B.append(q.value||q.placeholder);saveAs(B.getBlob("text/plain;charset="+s.characterSet),(h.value||h.placeholder)+".txt")},false);e.addEventListener("submit",function(B){B.preventDefault();var E=w(),D=new E,A=new XMLSerializer,C=k(m);D.append(A.serializeToString(C));saveAs(D.getBlob("application/xhtml+xml;charset="+s.characterSet),(i.value||i.placeholder)+".xhtml")},false);n.addEventListener("unload",function(){b.x_points=JSON.stringify(a);b.y_points=JSON.stringify(o);b.drag_points=JSON.stringify(d);b.canvas_filename=y.value;b.text=q.value;b.text_filename=h.value;b.html=m.innerHTML;b.html_filename=i.value},false)}(self));

View File

@ -0,0 +1,68 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US-x-Hixie">
<head>
<meta charset="utf-8"/>
<title>FileSaver.js demo</title>
<link rel="stylesheet" type="text/css" href="demo.css"/>
</head>
<body>
<h1><a href="https://github.com/eligrey/FileSaver.js">FileSaver.js</a> demo</h1>
<p>
The following examples demonstrate how it is possible to generate and save any type of data right in the browser using the W3C <code>saveAs()</code> <a href="http://www.w3.org/TR/file-writer-api/#the-filesaver-interface">FileSaver</a> interface, without contacting any servers.
</p>
<section id="image-demo">
<h2>Saving an image</h2>
<canvas class="input" id="canvas" width="500" height="300"/>
<form id="canvas-options">
<label>Filename: <input type="text" class="filename" id="canvas-filename" placeholder="doodle"/>.png</label>
<input type="submit" value="Save"/>
<input type="button" id="canvas-clear" value="Clear"/>
</form>
</section>
<section id="text-demo">
<h2>Saving text</h2>
<textarea class="input" id="text" placeholder="Once upon a time..."/>
<form id="text-options">
<label>Filename: <input type="text" class="filename" id="text-filename" placeholder="a plain document"/>.txt</label>
<input type="submit" value="Save"/>
</form>
</section>
<section id="html-demo">
<h2>Saving rich text</h2>
<div class="input" id="html" contenteditable="">
<h3>Some example rich text</h3>
<ul>
<li><del>Plain</del> <ins>Boring</ins> text.</li>
<li><em>Emphasized text!</em></li>
<li><strong>Strong text!</strong></li>
<li>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="70" height="70">
<circle cx="35" cy="35" r="35" fill="red"/>
<text x="10" y="40">image</text>
</svg>
</li>
<li><a href="https://github.com/eligrey/FileSaver.js">A link.</a></li>
</ul>
</div>
<form id="html-options">
<label>Filename: <input type="text" class="filename" id="html-filename" placeholder="a rich document"/>.xhtml</label>
<input type="submit" value="Save"/>
</form>
</section>
<section id="faq">
<h1>FAQ</h1>
<dl>
<dt>Why isn't my filename saved?</dt>
<dd>
<p>
Saving with filenames is only available in browsers that natively support <a href="http://www.w3.org/TR/file-writer-api/#the-filesaver-interface"><code>FileSaver</code></a> or browsers like <a href="http://www.chromium.org/getting-involved/dev-channel">Google Chrome 14 dev</a> and <a href="http://tools.google.com/dlpage/chromesxs">Google Chrome Canary</a>, that support <a href="http://developers.whatwg.org/links.html#downloading-resources"><code><![CDATA[<a>.@download]]></code></a> or <a href="http://www.w3.org/TR/file-system-api/#using-localfilesystem"><code>LocalFileSystem</code></a>.
</p>
</dd>
</dl>
</section>
<script type="application/ecmascript" async="" src="https://raw.github.com/eligrey/Blob.js/master/Blob.min.js"/>
<script type="application/ecmascript" async="" src="https://raw.github.com/eligrey/canvas-toBlob.js/master/canvas-toBlob.js"/>
<script type="application/ecmascript" async="" src="https://raw.github.com/eligrey/FileSaver.js/master/FileSaver.js"/>
<script type="application/ecmascript" async="" src="https://raw.github.com/eligrey/FileSaver.js/master/demo/demo.js"/>
</body>
</html>

4
js/jquery.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,45 @@
/** ====================================================================
* jsPDF [NAME] plugin
* Copyright (c) 2013 [YOUR NAME HERE] [WAY TO CONTACT YOU HERE]
*
* 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.
* ====================================================================
*/
(function(jsPDFAPI) {
'use strict'
jsPDFAPI.myFunction = function(args) {
'use strict'
// `this` is _jsPDF object returned when jsPDF is inited (new jsPDF())
// `this.internal` is a collection of useful, specific-to-raw-PDF-stream functions.
// for example, `this.internal.write` function allowing you to write directly to PDF stream.
// `this.line`, `this.text` etc are available directly.
// so if your plugin just wraps complex series of this.line or this.text or other public API calls,
// you don't need to look into `this.internal`
// See _jsPDF object in jspdf.js for complete list of what's available to you.
// it is good practice to return ref to jsPDF instance to make
// the calls chainable.
return this
}
})(jsPDF.API)

1930
js/jspdf.js Normal file

File diff suppressed because it is too large Load Diff

223
js/jspdf.plugin.addimage.js Normal file
View File

@ -0,0 +1,223 @@
/** @preserve
jsPDF addImage plugin (JPEG only at this time)
Copyright (c) 2012 https://github.com/siefkenj/
*/
/**
* 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.
* ====================================================================
*/
;(function(jsPDFAPI) {
'use strict'
var namespace = 'addImage_'
// takes a string imgData containing the raw bytes of
// a jpeg image and returns [width, height]
// Algorithm from: http://www.64lines.com/jpeg-width-height
var getJpegSize = function(imgData) {
'use strict'
var width, height;
// Verify we have a valid jpeg header 0xff,0xd8,0xff,0xe0,?,?,'J','F','I','F',0x00
if (!imgData.charCodeAt(0) === 0xff ||
!imgData.charCodeAt(1) === 0xd8 ||
!imgData.charCodeAt(2) === 0xff ||
!imgData.charCodeAt(3) === 0xe0 ||
!imgData.charCodeAt(6) === 'J'.charCodeAt(0) ||
!imgData.charCodeAt(7) === 'F'.charCodeAt(0) ||
!imgData.charCodeAt(8) === 'I'.charCodeAt(0) ||
!imgData.charCodeAt(9) === 'F'.charCodeAt(0) ||
!imgData.charCodeAt(10) === 0x00) {
throw new Error('getJpegSize requires a binary jpeg file')
}
var blockLength = imgData.charCodeAt(4)*256 + imgData.charCodeAt(5);
var i = 4, len = imgData.length;
while ( i < len ) {
i += blockLength;
if (imgData.charCodeAt(i) !== 0xff) {
throw new Error('getJpegSize could not find the size of the image');
}
if (imgData.charCodeAt(i+1) === 0xc0) {
height = imgData.charCodeAt(i+5)*256 + imgData.charCodeAt(i+6);
width = imgData.charCodeAt(i+7)*256 + imgData.charCodeAt(i+8);
return [width, height];
} else {
i += 2;
blockLength = imgData.charCodeAt(i)*256 + imgData.charCodeAt(i+1)
}
}
}
// Image functionality ported from pdf.js
, putImage = function(img) {
var objectNumber = this.internal.newObject()
, out = this.internal.write
, putStream = this.internal.putStream
img['n'] = objectNumber
out('<</Type /XObject')
out('/Subtype /Image')
out('/Width ' + img['w'])
out('/Height ' + img['h'])
if (img['cs'] === 'Indexed') {
out('/ColorSpace [/Indexed /DeviceRGB '
+ (img['pal'].length / 3 - 1) + ' ' + (objectNumber + 1)
+ ' 0 R]');
} else {
out('/ColorSpace /' + img['cs']);
if (img['cs'] === 'DeviceCMYK') {
out('/Decode [1 0 1 0 1 0 1 0]');
}
}
out('/BitsPerComponent ' + img['bpc']);
if ('f' in img) {
out('/Filter /' + img['f']);
}
if ('dp' in img) {
out('/DecodeParms <<' + img['dp'] + '>>');
}
if ('trns' in img && img['trns'].constructor == Array) {
var trns = '';
for ( var i = 0; i < img['trns'].length; i++) {
trns += (img[trns][i] + ' ' + img['trns'][i] + ' ');
out('/Mask [' + trns + ']');
}
}
if ('smask' in img) {
out('/SMask ' + (objectNumber + 1) + ' 0 R');
}
out('/Length ' + img['data'].length + '>>');
putStream(img['data']);
out('endobj');
}
, putResourcesCallback = function() {
var images = this.internal.collections[namespace + 'images']
for ( var i in images ) {
putImage.call(this, images[i])
}
}
, putXObjectsDictCallback = function(){
var images = this.internal.collections[namespace + 'images']
, out = this.internal.write
, image
for (var i in images) {
image = images[i]
out(
'/I' + image['i']
, image['n']
, '0'
, 'R'
)
}
}
jsPDFAPI.addImage = function(imageData, format, x, y, w, h) {
'use strict'
if (typeof imageData === 'object' && imageData.nodeType === 1) {
var canvas = document.createElement('canvas');
canvas.width = imageData.clientWidth;
canvas.height = imageData.clientHeight;
var ctx = canvas.getContext('2d');
if (!ctx) {
throw ('addImage requires canvas to be supported by browser.');
}
ctx.drawImage(imageData, 0, 0, canvas.width, canvas.height);
imageData = canvas.toDataURL('image/jpeg');
format = "JPEG";
}
if (format.toUpperCase() !== 'JPEG') {
throw new Error('addImage currently only supports format \'JPEG\', not \''+format+'\'');
}
var imageIndex
, images = this.internal.collections[namespace + 'images']
, coord = this.internal.getCoordinateString
, vcoord = this.internal.getVerticalCoordinateString;
// Detect if the imageData is raw binary or Data URL
if (imageData.substring(0, 23) === 'data:image/jpeg;base64,') {
imageData = atob(imageData.replace('data:image/jpeg;base64,', ''));
}
if (images){
// this is NOT the first time this method is ran on this instance of jsPDF object.
imageIndex = Object.keys ?
Object.keys(images).length :
(function(o){
var i = 0
for (var e in o){if(o.hasOwnProperty(e)){ i++ }}
return i
})(images)
} else {
// this is the first time this method is ran on this instance of jsPDF object.
imageIndex = 0
this.internal.collections[namespace + 'images'] = images = {}
this.internal.events.subscribe('putResources', putResourcesCallback)
this.internal.events.subscribe('putXobjectDict', putXObjectsDictCallback)
}
var dims = getJpegSize(imageData);
var info = {
w : dims[0],
h : dims[1],
cs : 'DeviceRGB',
bpc : 8,
f : 'DCTDecode',
i : imageIndex,
data : imageData
// n: objectNumber will be added by putImage code
};
images[imageIndex] = info
if (!w && !h) {
w = -96;
h = -96;
}
if (w < 0) {
w = (-1) * info['w'] * 72 / w / this.internal.scaleFactor;
}
if (h < 0) {
h = (-1) * info['h'] * 72 / h / this.internal.scaleFactor;
}
if (w === 0) {
w = h * info['w'] / info['h'];
}
if (h === 0) {
h = w * info['h'] / info['w'];
}
this.internal.write(
'q'
, coord(w)
, '0 0'
, coord(h) // TODO: check if this should be shifted by vcoord
, coord(x)
, vcoord(y + h)
, 'cm /I'+info['i']
, 'Do Q'
)
return this
}
})(jsPDF.API)

372
js/jspdf.plugin.cell.js Normal file
View File

@ -0,0 +1,372 @@
/** ====================================================================
* jsPDF Cell plugin
* Copyright (c) 2013 Youssef Beddad, youssef.beddad@gmail.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.
* ====================================================================
*/
(function (jsPDFAPI) {
'use strict';
/*jslint browser:true */
/*global document: false, jsPDF */
var maxLn = 0,
lnP = 0,
fontName,
fontSize,
fontStyle,
lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined },
pages = 1,
newPage = false,
setLastCellPosition = function (x, y, w, h, ln) {
lastCellPos = { x: x, y: y, w: w, h: h, ln: ln };
},
getLastCellPosition = function () {
return lastCellPos;
},
setMaxLn = function (x) {
maxLn = x;
},
getMaxLn = function () {
return maxLn;
},
setLnP = function (x) {
lnP = x;
},
getLnP = function (x) {
return lnP;
};
jsPDFAPI.getTextDimensions = function (txt) {
fontName = this.internal.getFont().fontName;
fontSize = this.internal.getFontSize();
fontStyle = this.internal.getFont().fontStyle;
// 1 pixel = 0.264583 mm and 1 mm = 72/25.4 point
var px2pt = 0.264583 * 72 / 25.4,
dimensions,
text;
text = document.createElement('font');
text.id = "jsPDFCell";
text.style.fontStyle = fontStyle;
text.style.fontName = fontName;
text.style.fontSize = fontSize + 'pt';
text.innerText = txt;
document.body.appendChild(text);
dimensions = { w: (text.offsetWidth + 1) * px2pt, h: (text.offsetHeight + 1) * px2pt};
document.body.removeChild(text);
return dimensions;
};
jsPDFAPI.cellAddPage = function () {
this.addPage();
setLastCellPosition(undefined, undefined, undefined, undefined, undefined);
newPage = true;
pages += 1;
setLnP(1);
};
jsPDFAPI.cellInitialize = function () {
maxLn = 0;
lastCellPos = { x: undefined, y: undefined, w: undefined, h: undefined, ln: undefined };
pages = 1;
newPage = false;
setLnP(0);
};
jsPDFAPI.cell = function (x, y, w, h, txt, ln) {
this.lnMod = this.lnMod === undefined ? 0 : this.lnMod;
if (this.printingHeaderRow !== true && this.lnMod !== 0) {
ln = ln + this.lnMod;
}
if ((((ln * h) + y + (h * 2)) / pages) >= this.internal.pageSize.height && pages === 1 && !newPage) {
this.cellAddPage();
if (this.printHeaders && this.tableHeaderRow) {
this.printHeaderRow(ln);
this.lnMod += 1;
ln += 1;
}
if (getMaxLn() === 0) {
setMaxLn(Math.round((this.internal.pageSize.height - (h * 2)) / h));
}
} else if (newPage && getLastCellPosition().ln !== ln && getLnP() === getMaxLn()) {
this.cellAddPage();
if (this.printHeaders && this.tableHeaderRow) {
this.printHeaderRow(ln);
this.lnMod += 1;
ln += 1;
}
}
var curCell = getLastCellPosition(),
dim = this.getTextDimensions(txt),
isNewLn = 1;
if (curCell.x !== undefined && curCell.ln === ln) {
x = curCell.x + curCell.w;
}
if (curCell.y !== undefined && curCell.y === y) {
y = curCell.y;
}
if (curCell.h !== undefined && curCell.h === h) {
h = curCell.h;
}
if (curCell.ln !== undefined && curCell.ln === ln) {
ln = curCell.ln;
isNewLn = 0;
}
if (newPage) {
y = h * (getLnP() + isNewLn);
} else {
y = (y + (h * Math.abs(getMaxLn() * pages - ln - getMaxLn())));
}
this.rect(x, y, w, h);
this.text(txt, x + 3, y + h - 3);
setLnP(getLnP() + isNewLn);
setLastCellPosition(x, y, w, h, ln);
return this;
};
/**
* Return an array containing all of the owned keys of an Object
* @type {Function}
* @return {String[]} of Object keys
*/
jsPDFAPI.getKeys = (typeof Object.keys === 'function')
? function (object) {
if (!object) {
return [];
}
return Object.keys(object);
}
: function (object) {
var keys = [],
property;
for (property in object) {
if (object.hasOwnProperty(property)) {
keys.push(property);
}
}
return keys;
};
/**
* Return the maximum value from an array
* @param array
* @param comparisonFn
* @returns {*}
*/
jsPDFAPI.arrayMax = function (array, comparisonFn) {
var max = array[0],
i,
ln,
item;
for (i = 0, ln = array.length; i < ln; i += 1) {
item = array[i];
if (comparisonFn) {
if (comparisonFn(max, item) === -1) {
max = item;
}
} else {
if (item > max) {
max = item;
}
}
}
return max;
};
/**
* Create a table from a set of data.
* @param {Object[]} data As array of objects containing key-value pairs
* @param {String[]} [headers] Omit or null to auto-generate headers at a performance cost
* @param {Object} [config.printHeaders] True to print column headers at the top of every page
* @param {Object} [config.autoSize] True to dynamically set the column widths to match the widest cell value
* @param {Object} [config.autoStretch] True to force the table to fit the width of the page
*/
jsPDFAPI.table = function (data, headers, config) {
var headerNames = [],
headerPrompts = [],
header,
autoSize,
printHeaders,
autoStretch,
i,
ln,
columnMatrix = {},
columnWidths = {},
columnData,
column,
columnMinWidths = [],
j,
tableHeaderConfigs = [],
model,
jln,
func;
/**
* @property {Number} lnMod
* Keep track of the current line number modifier used when creating cells
*/
this.lnMod = 0;
if (config) {
autoSize = config.autoSize || false;
printHeaders = this.printHeaders = config.printHeaders || true;
autoStretch = config.autoStretch || true;
}
if (!data) {
throw 'No data for PDF table';
}
// Set headers
if (headers === undefined || (headers === null)) {
// No headers defined so we derive from data
headerNames = this.getKeys(data[0]);
} else if (headers[0] && (typeof headers[0] !== 'string')) {
// Split header configs into names and prompts
for (i = 0, ln = headers.length; i < ln; i += 1) {
header = headers[i];
headerNames.push(header.name);
headerPrompts.push(header.prompt);
}
} else {
headerNames = headers;
}
if (config.autoSize) {
// Create Columns Matrix
func = function (rec) {
return rec[header];
};
for (i = 0, ln = headerNames.length; i < ln; i += 1) {
header = headerNames[i];
columnMatrix[header] = data.map(
func
);
// get header width
columnMinWidths.push(this.getTextDimensions(headerPrompts[i] || header).w);
column = columnMatrix[header];
// get cell widths
for (j = 0, ln = column.length; j < ln; j += 1) {
columnData = column[j];
columnMinWidths.push(this.getTextDimensions(columnData).w);
}
// get final column width
columnWidths[header] = jsPDFAPI.arrayMax(columnMinWidths);
}
}
// -- Construct the table
if (config.printHeaders) {
// Construct the header row
for (i = 0, ln = headerNames.length; i < ln; i += 1) {
header = headerNames[i];
tableHeaderConfigs.push([10, 10, columnWidths[header], 25, String(headerPrompts.length ? headerPrompts[i] : header)]);
}
// Store the table header config
this.setTableHeaderRow(tableHeaderConfigs);
// Print the header for the start of the table
this.printHeaderRow(1);
}
// Construct the data rows
for (i = 0, ln = data.length; i < ln; i += 1) {
model = data[i];
for (j = 0, jln = headerNames.length; j < jln; j += 1) {
header = headerNames[j];
this.cell(10, 10, columnWidths[header], 25, String(model[header]), i + 2);
}
}
return this;
};
/**
* Store the config for outputting a table header
* @param {Object[]} config
* An array of cell configs that would define a header row: Each config matches the config used by jsPDFAPI.cell
* except the ln parameter is excluded
*/
jsPDFAPI.setTableHeaderRow = function (config) {
this.tableHeaderRow = config;
};
/**
* Output the store header row
* @param lineNumber The line number to output the header at
*/
jsPDFAPI.printHeaderRow = function (lineNumber) {
if (!this.tableHeaderRow) {
throw 'Property tableHeaderRow does not exist.';
}
var tableHeaderCell,
tmpArray,
i,
ln;
this.printingHeaderRow = true;
for (i = 0, ln = this.tableHeaderRow.length; i < ln; i += 1) {
tableHeaderCell = this.tableHeaderRow[i];
tmpArray = [].concat(tableHeaderCell);
this.cell.apply(this, tmpArray.concat(lineNumber));
}
this.printingHeaderRow = false;
};
}(jsPDF.API));

View File

@ -0,0 +1,594 @@
/** @preserve
jsPDF fromHTML plugin. BETA stage. API subject to change. Needs browser, jQuery
Copyright (c) 2012 2012 Willow Systems Corporation, willow-systems.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.
* ====================================================================
*/
;(function(jsPDFAPI) {
'use strict'
if(!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g,'');
};
}
if(!String.prototype.trimLeft) {
String.prototype.trimLeft = function () {
return this.replace(/^\s+/g,'');
};
}
if(!String.prototype.trimRight) {
String.prototype.trimRight = function () {
return this.replace(/\s+$/g,'');
};
}
function PurgeWhiteSpace(array){
var i = 0, l = array.length, fragment
, lTrimmed = false
, rTrimmed = false
while (!lTrimmed && i !== l) {
fragment = array[i] = array[i].trimLeft()
if (fragment) {
// there is something left there.
lTrimmed = true
}
;i++;
}
i = l - 1
while (l && !rTrimmed && i !== -1) {
fragment = array[i] = array[i].trimRight()
if (fragment) {
// there is something left there.
rTrimmed = true
}
;i--;
}
var r = /\s+$/g
, trailingSpace = true // it's safe to assume we always trim start of display:block element's text.
for (i = 0; i !== l; i++) {
fragment = array[i].replace(/\s+/g, ' ')
// if (l > 1) {
// console.log(i, trailingSpace, fragment)
// }
if (trailingSpace) {
fragment = fragment.trimLeft()
}
if (fragment) {
// meaning, it was not reduced to ""
// if it was, we don't want to clear trailingSpace flag.
trailingSpace = r.test(fragment)
}
array[i] = fragment
}
return array
}
function Renderer(pdf, x, y, settings) {
this.pdf = pdf
this.x = x
this.y = y
this.settings = settings
this.init()
return this
}
Renderer.prototype.init = function(){
this.paragraph = {
'text': []
, 'style': []
}
this.pdf.internal.write(
'q'
)
}
Renderer.prototype.dispose = function(){
this.pdf.internal.write(
'Q' // closes the 'q' in init()
)
return {
'x':this.x, 'y':this.y // bottom left of last line. = upper left of what comes after us.
// TODO: we cannot traverse pages yet, but need to figure out how to communicate that when we do.
// TODO: add more stats: number of lines, paragraphs etc.
}
}
Renderer.prototype.splitFragmentsIntoLines = function(fragments, styles){
var defaultFontSize = 12 // points
, k = this.pdf.internal.scaleFactor // when multiplied by this, converts jsPDF instance units into 'points'
// var widths = options.widths ? options.widths : this.internal.getFont().metadata.Unicode.widths
// , kerning = options.kerning ? options.kerning : this.internal.getFont().metadata.Unicode.kerning
, fontMetricsCache = {}
, ff, fs
, fontMetrics
, fragment // string, element of `fragments`
, style // object with properties with names similar to CSS. Holds pertinent style info for given fragment
, fragmentSpecificMetrics // fontMetrics + some indent and sizing properties populated. We reuse it, hence the bother.
, fragmentLength // fragment's length in jsPDF units
, fragmentChopped // will be array - fragment split into "lines"
, line = [] // array of pairs of arrays [t,s], where t is text string, and s is style object for that t.
, lines = [line] // array of arrays of pairs of arrays
, currentLineLength = 0 // in jsPDF instance units (inches, cm etc)
, maxLineLength = this.settings.width // need to decide if this is the best way to know width of content.
// this loop sorts text fragments (and associated style)
// into lines. Some fragments will be chopped into smaller
// fragments to be spread over multiple lines.
while (fragments.length) {
fragment = fragments.shift()
style = styles.shift()
// if not empty string
if (fragment) {
ff = style['font-family']
fs = style['font-style']
fontMetrics = fontMetricsCache[ff+fs]
if (!fontMetrics) {
fontMetrics = this.pdf.internal.getFont(ff, fs).metadata.Unicode
fontMetricsCache[ff+fs] = fontMetrics
}
fragmentSpecificMetrics = {
'widths': fontMetrics.widths
, 'kerning': fontMetrics.kerning
// fontSize comes to us from CSS scraper as "proportion of normal" value
// , hence the multiplication
, 'fontSize': style['font-size'] * defaultFontSize
// // these should not matter as we provide the metrics manually
// // if we would not, we would need these:
// , 'fontName': style.fontName
// , 'fontStyle': style.fontStyle
// this is setting for "indent first line of paragraph", but we abuse it
// for continuing inline spans of text. Indent value = space in jsPDF instance units
// (whatever user passed to 'new jsPDF(orientation, units, size)
// already consumed on this line. May be zero, of course, for "start of line"
// it's used only on chopper, ignored in all "sizing" code
, 'textIndent': currentLineLength
}
// in user units (inch, cm etc.)
fragmentLength = this.pdf.getStringUnitWidth(
fragment
, fragmentSpecificMetrics
) * fragmentSpecificMetrics.fontSize / k
if (currentLineLength + fragmentLength > maxLineLength) {
// whatever is already on the line + this new fragment
// will be longer than max len for a line.
// Hence, chopping fragment into lines:
fragmentChopped = this.pdf.splitTextToSize(
fragment
, maxLineLength
, fragmentSpecificMetrics
)
line.push([fragmentChopped.shift(), style])
while (fragmentChopped.length){
line = [[fragmentChopped.shift(), style]]
lines.push(line)
}
currentLineLength = this.pdf.getStringUnitWidth(
// new line's first (and only) fragment's length is our new line length
line[0][0]
, fragmentSpecificMetrics
) * fragmentSpecificMetrics.fontSize / k
} else {
// nice, we can fit this fragment on current line. Less work for us...
line.push([fragment, style])
currentLineLength += fragmentLength
}
}
}
return lines
}
Renderer.prototype.RenderTextFragment = function(text, style) {
var defaultFontSize = 12
// , header = "/F1 16 Tf\n16 TL\n0 g"
, font = this.pdf.internal.getFont(style['font-family'], style['font-style'])
this.pdf.internal.write(
'/' + font.id // font key
, (defaultFontSize * style['font-size']).toFixed(2) // font size comes as float = proportion to normal.
, 'Tf' // font def marker
, '('+this.pdf.internal.pdfEscape(text)+') Tj'
)
}
Renderer.prototype.renderParagraph = function(){
var fragments = PurgeWhiteSpace( this.paragraph.text )
, styles = this.paragraph.style
, blockstyle = this.paragraph.blockstyle
, priorblockstype = this.paragraph.blockstyle || {}
this.paragraph = {'text':[], 'style':[], 'blockstyle':{}, 'priorblockstyle':blockstyle}
if (!fragments.join('').trim()) {
/* if it's empty string */
return
} // else there is something to draw
var lines = this.splitFragmentsIntoLines(fragments, styles)
, line // will be array of array pairs [[t,s],[t,s],[t,s]...] where t = text, s = style object
, maxLineHeight
, defaultFontSize = 12
, fontToUnitRatio = defaultFontSize / this.pdf.internal.scaleFactor
// these will be in pdf instance units
, paragraphspacing_before = (
// we only use margin-top potion that is larger than margin-bottom of previous elem
// because CSS margins don't stack, they overlap.
Math.max( ( blockstyle['margin-top'] || 0 ) - ( priorblockstype['margin-bottom'] || 0 ), 0 ) +
( blockstyle['padding-top'] || 0 )
) * fontToUnitRatio
, paragraphspacing_after = (
( blockstyle['margin-bottom'] || 0 ) + ( blockstyle['padding-bottom'] || 0 )
) * fontToUnitRatio
, out = this.pdf.internal.write
, i, l
this.y += paragraphspacing_before
out(
'q' // canning the scope
, 'BT' // Begin Text
// and this moves the text start to desired position.
, this.pdf.internal.getCoordinateString(this.x)
, this.pdf.internal.getVerticalCoordinateString(this.y)
, 'Td'
)
// looping through lines
while (lines.length) {
line = lines.shift()
maxLineHeight = 0
for (i = 0, l = line.length; i !== l; i++) {
if (line[i][0].trim()) {
maxLineHeight = Math.max(maxLineHeight, line[i][1]['line-height'], line[i][1]['font-size'])
}
}
// current coordinates are "top left" corner of text box. Text must start from "lower left"
// so, lowering the current coord one line height.
out(
0
, (-1 * defaultFontSize * maxLineHeight).toFixed(2) // shifting down a line in native `points' means reducing y coordinate
, 'Td'
// , (defaultFontSize * maxLineHeight).toFixed(2) // line height comes as float = proportion to normal.
// , 'TL' // line height marker. Not sure we need it with "Td", but...
)
for (i = 0, l = line.length; i !== l; i++) {
if (line[i][0]) {
this.RenderTextFragment(line[i][0], line[i][1])
}
}
// y is in user units (cm, inch etc)
// maxLineHeight is ratio of defaultFontSize
// defaultFontSize is in points always.
// this.internal.scaleFactor is ratio of user unit to points.
// Dividing by it converts points to user units.
// vertical offset will be in user units.
// this.y is in user units.
this.y += maxLineHeight * fontToUnitRatio
}
out(
'ET' // End Text
, 'Q' // restore scope
)
this.y += paragraphspacing_after
}
Renderer.prototype.setBlockBoundary = function(){
this.renderParagraph()
}
Renderer.prototype.setBlockStyle = function(css){
this.paragraph.blockstyle = css
}
Renderer.prototype.addText = function(text, css){
this.paragraph.text.push(text)
this.paragraph.style.push(css)
}
//=====================
// these are DrillForContent and friends
var FontNameDB = {
'helvetica':'helvetica'
, 'sans-serif':'helvetica'
, 'serif':'times'
, 'times':'times'
, 'times new roman':'times'
, 'monospace':'courier'
, 'courier':'courier'
}
, FontWeightMap = {"100":'normal',"200":'normal',"300":'normal',"400":'normal',"500":'bold',"600":'bold',"700":'bold',"800":'bold',"900":'bold',"normal":'normal',"bold":'bold',"bolder":'bold',"lighter":'normal'}
, FontStyleMap = {'normal':'normal','italic':'italic','oblique':'italic'}
, UnitedNumberMap = {'normal':1}
function ResolveFont(css_font_family_string){
var name
, parts = css_font_family_string.split(',') // yes, we don't care about , inside quotes
, part = parts.shift()
while (!name && part){
name = FontNameDB[ part.trim().toLowerCase() ]
part = parts.shift()
}
return name
}
// return ratio to "normal" font size. in other words, it's fraction of 16 pixels.
function ResolveUnitedNumber(css_line_height_string){
var undef
, normal = 16.00
, value = UnitedNumberMap[css_line_height_string]
if (value) {
return value
}
// not in cache, ok. need to parse it.
// Could it be a named value?
// we will use Windows 94dpi sizing with CSS2 suggested 1.2 step ratio
// where "normal" or "medium" is 16px
// see: http://style.cleverchimp.com/font_size_intervals/altintervals.html
value = ({
'xx-small':9
, 'x-small':11
, 'small':13
, 'medium':16
, 'large':19
, 'x-large':23
, 'xx-large':28
, 'auto':0
})[css_line_height_string]
if (value !== undef) {
// caching, returning
return UnitedNumberMap[css_line_height_string] = value / normal
}
// not in cache, ok. need to parse it.
// is it int?
if (value = parseFloat(css_line_height_string)) {
// caching, returning
return UnitedNumberMap[css_line_height_string] = value / normal
}
// must be a "united" value ('123em', '134px' etc.)
// most browsers convert it to px so, only handling the px
value = css_line_height_string.match( /([\d\.]+)(px)/ )
if (value.length === 3) {
// caching, returning
return UnitedNumberMap[css_line_height_string] = parseFloat( value[1] ) / normal
}
return UnitedNumberMap[css_line_height_string] = 1
}
function GetCSS(element){
var $e = $(element)
, css = {}
, tmp
css['font-family'] = ResolveFont( $e.css('font-family') ) || 'times'
css['font-style'] = FontStyleMap [ $e.css('font-style') ] || 'normal'
tmp = FontWeightMap[ $e.css('font-weight') ] || 'normal'
if (tmp === 'bold') {
if (css['font-style'] === 'normal') {
css['font-style'] = tmp
} else {
css['font-style'] = tmp + css['font-style'] // jsPDF's default fonts have it as "bolditalic"
}
}
css['font-size'] = ResolveUnitedNumber( $e.css('font-size') ) || 1 // ratio to "normal" size
css['line-height'] = ResolveUnitedNumber( $e.css('line-height') ) || 1 // ratio to "normal" size
css['display'] = $e.css('display') === 'inline' ? 'inline' : 'block'
if (css['display'] === 'block'){
css['margin-top'] = ResolveUnitedNumber( $e.css('margin-top') ) || 0
css['margin-bottom'] = ResolveUnitedNumber( $e.css('margin-bottom') ) || 0
css['padding-top'] = ResolveUnitedNumber( $e.css('padding-top') ) || 0
css['padding-bottom'] = ResolveUnitedNumber( $e.css('padding-bottom') ) || 0
}
return css
}
function elementHandledElsewhere(element, renderer, elementHandlers){
var isHandledElsewhere = false
var i, l, t
, handlers = elementHandlers['#'+element.id]
if (handlers) {
if (typeof handlers === 'function') {
isHandledElsewhere = handlers(element, renderer)
} else /* array */ {
i = 0
l = handlers.length
while (!isHandledElsewhere && i !== l){
isHandledElsewhere = handlers[i](element, renderer)
;i++;
}
}
}
handlers = elementHandlers[element.nodeName]
if (!isHandledElsewhere && handlers) {
if (typeof handlers === 'function') {
isHandledElsewhere = handlers(element, renderer)
} else /* array */ {
i = 0
l = handlers.length
while (!isHandledElsewhere && i !== l){
isHandledElsewhere = handlers[i](element, renderer)
;i++;
}
}
}
return isHandledElsewhere
}
function DrillForContent(element, renderer, elementHandlers){
var cns = element.childNodes
, cn
, fragmentCSS = GetCSS(element)
, isBlock = fragmentCSS.display === 'block'
if (isBlock) {
renderer.setBlockBoundary()
renderer.setBlockStyle(fragmentCSS)
}
for (var i = 0, l = cns.length; i < l ; i++){
cn = cns[i]
if (typeof cn === 'object') {
// Don't render the insides of script tags, they contain text nodes which then render
if (cn.nodeType === 1 && cn.nodeName != 'SCRIPT') {
if (!elementHandledElsewhere(cn, renderer, elementHandlers)) {
DrillForContent(cn, renderer, elementHandlers)
}
} else if (cn.nodeType === 3){
renderer.addText( cn.nodeValue, fragmentCSS )
}
} else if (typeof cn === 'string') {
renderer.addText( cn, fragmentCSS )
}
}
if (isBlock) {
renderer.setBlockBoundary()
}
}
function process(pdf, element, x, y, settings) {
// we operate on DOM elems. So HTML-formatted strings need to pushed into one
if (typeof element === 'string') {
element = (function(element) {
var framename = "jsPDFhtmlText" + Date.now().toString() + (Math.random() * 1000).toFixed(0)
, visuallyhidden = 'position: absolute !important;' +
'clip: rect(1px 1px 1px 1px); /* IE6, IE7 */' +
'clip: rect(1px, 1px, 1px, 1px);' +
'padding:0 !important;' +
'border:0 !important;' +
'height: 1px !important;' +
'width: 1px !important; ' +
'top:auto;' +
'left:-100px;' +
'overflow: hidden;'
// TODO: clean up hidden div
, $hiddendiv = $(
'<div style="'+visuallyhidden+'">' +
'<iframe style="height:1px;width:1px" name="'+framename+'" />' +
'</div>'
).appendTo(document.body)
, $frame = window.frames[framename]
return $($frame.document.body).html(element)[0]
})( element )
}
var r = new Renderer( pdf, x, y, settings )
, a = DrillForContent( element, r, settings.elementHandlers )
return r.dispose()
}
/**
Converts HTML-formatted text into formatted PDF text.
Notes:
2012-07-18
Plugin relies on having browser, DOM around. The HTML is pushed into dom and traversed.
Plugin relies on jQuery for CSS extraction.
Targeting HTML output from Markdown templating, which is a very simple
markup - div, span, em, strong, p. No br-based paragraph separation supported explicitly (but still may work.)
Images, tables are NOT supported.
@public
@function
@param HTML {String or DOM Element} HTML-formatted text, or pointer to DOM element that is to be rendered into PDF.
@param x {Number} starting X coordinate in jsPDF instance's declared units.
@param y {Number} starting Y coordinate in jsPDF instance's declared units.
@param settings {Object} Additional / optional variables controlling parsing, rendering.
@returns {Object} jsPDF instance
*/
jsPDFAPI.fromHTML = function(HTML, x, y, settings) {
'use strict'
// `this` is _jsPDF object returned when jsPDF is inited (new jsPDF())
// `this.internal` is a collection of useful, specific-to-raw-PDF-stream functions.
// for example, `this.internal.write` function allowing you to write directly to PDF stream.
// `this.line`, `this.text` etc are available directly.
// so if your plugin just wraps complex series of this.line or this.text or other public API calls,
// you don't need to look into `this.internal`
// See _jsPDF object in jspdf.js for complete list of what's available to you.
// it is good practice to return ref to jsPDF instance to make
// the calls chainable.
// return this
// but in this case it is more usefull to return some stats about what we rendered.
return process(this, HTML, x, y, settings)
}
})(jsPDF.API)

View File

@ -0,0 +1,59 @@
/** ====================================================================
* jsPDF IE Below 9 Shim plugin 0.1.0
* Known to be compatible with jsPDF 0.9.0
*
* Copyright (c) 2013 James Hall, james@snapshotmedia.co.uk
*
* 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.
* ====================================================================
*/
;(function(API) {
'use strict'
var name = 'jsPDF IE Below 9 Shim plugin';
// Shim in IE6-9 support
API.output = function(type, options) {
// If not IE then return early
return this.internal.output(type, options);
var filename = 'Output.pdf';
switch (type) {
case 'datauristring':
case 'dataurlstring':
case 'datauri':
case 'dataurl':
case 'dataurlnewwindow':
console.log(name + ': Data URIs are not supported on IE6-9.');
break;
case 'save':
filename = options;
break;
}
// @TODO: IE shim
};
})(jsPDF.API)

View File

@ -0,0 +1,52 @@
/** ====================================================================
* jsPDF JavaScript plugin
* Copyright (c) 2013 Youssef Beddad, youssef.beddad@gmail.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.
* ====================================================================
*/
/*global jsPDF */
(function (jsPDFAPI) {
'use strict';
var jsNamesObj, jsJsObj, text;
jsPDFAPI.addJS = function (txt) {
text = txt;
this.internal.events.subscribe(
'postPutResources',
function (txt) {
jsNamesObj = this.internal.newObject();
this.internal.write('<< /Names [(EmbeddedJS) ' + (jsNamesObj + 1) + ' 0 R] >>', 'endobj');
jsJsObj = this.internal.newObject();
this.internal.write('<< /S /JavaScript /JS (', text, ') >>', 'endobj');
}
);
this.internal.events.subscribe(
'putCatalog',
function () {
if (jsNamesObj !== undefined && jsJsObj !== undefined) {
this.internal.write('/Names <</JavaScript ' + jsNamesObj + ' 0 R>>');
}
}
);
return this;
};
}(jsPDF.API));

View File

@ -0,0 +1,181 @@
/** @preserve
jsPDF Silly SVG plugin
Copyright (c) 2012 Willow Systems Corporation, willow-systems.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.
* ====================================================================
*/
;(function(jsPDFAPI) {
'use strict'
/**
Parses SVG XML and converts only some of the SVG elements into
PDF elements.
Supports:
paths
@public
@function
@param
@returns {Type}
*/
jsPDFAPI.addSVG = function(svgtext, x, y, w, h) {
// 'this' is _jsPDF object returned when jsPDF is inited (new jsPDF())
var undef
if (x === undef || x === undef) {
throw new Error("addSVG needs values for 'x' and 'y'")
}
function InjectCSS(cssbody, document) {
var styletag = document.createElement('style')
styletag.type = 'text/css'
if (styletag.styleSheet) {
// ie
styletag.styleSheet.cssText = cssbody
} else {
// others
styletag.appendChild(document.createTextNode(cssbody))
}
document.getElementsByTagName("head")[0].appendChild(styletag)
}
function createWorkerNode(document){
var frameID = 'childframe' // Date.now().toString() + '_' + (Math.random() * 100).toString()
, frame = document.createElement('iframe')
InjectCSS(
'.jsPDF_sillysvg_iframe {display:none;position:absolute;}'
, document
)
frame.name = frameID
frame.setAttribute("width", 0)
frame.setAttribute("height", 0)
frame.setAttribute("frameborder", "0")
frame.setAttribute("scrolling", "no")
frame.setAttribute("seamless", "seamless")
frame.setAttribute("class", "jsPDF_sillysvg_iframe")
document.body.appendChild(frame)
return frame
}
function attachSVGToWorkerNode(svgtext, frame){
var framedoc = ( frame.contentWindow || frame.contentDocument ).document
framedoc.write(svgtext)
framedoc.close()
return framedoc.getElementsByTagName('svg')[0]
}
function convertPathToPDFLinesArgs(path){
'use strict'
// we will use 'lines' method call. it needs:
// - starting coordinate pair
// - array of arrays of vector shifts (2-len for line, 6 len for bezier)
// - scale array [horizontal, vertical] ratios
// - style (stroke, fill, both)
var x = parseFloat(path[1])
, y = parseFloat(path[2])
, vectors = []
, position = 3
, len = path.length
while (position < len){
if (path[position] === 'c'){
vectors.push([
parseFloat(path[position + 1])
, parseFloat(path[position + 2])
, parseFloat(path[position + 3])
, parseFloat(path[position + 4])
, parseFloat(path[position + 5])
, parseFloat(path[position + 6])
])
position += 7
} else if (path[position] === 'l') {
vectors.push([
parseFloat(path[position + 1])
, parseFloat(path[position + 2])
])
position += 3
} else {
position += 1
}
}
return [x,y,vectors]
}
var workernode = createWorkerNode(document)
, svgnode = attachSVGToWorkerNode(svgtext, workernode)
, scale = [1,1]
, svgw = parseFloat(svgnode.getAttribute('width'))
, svgh = parseFloat(svgnode.getAttribute('height'))
if (svgw && svgh) {
// setting both w and h makes image stretch to size.
// this may distort the image, but fits your demanded size
if (w && h) {
scale = [w / svgw, h / svgh]
}
// if only one is set, that value is set as max and SVG
// is scaled proportionately.
else if (w) {
scale = [w / svgw, w / svgw]
} else if (h) {
scale = [h / svgh, h / svgh]
}
}
var i, l, tmp
, linesargs
, items = svgnode.childNodes
for (i = 0, l = items.length; i < l; i++) {
tmp = items[i]
if (tmp.tagName && tmp.tagName.toUpperCase() === 'PATH') {
linesargs = convertPathToPDFLinesArgs( tmp.getAttribute("d").split(' ') )
// path start x coordinate
linesargs[0] = linesargs[0] * scale[0] + x // where x is upper left X of image
// path start y coordinate
linesargs[1] = linesargs[1] * scale[1] + y // where y is upper left Y of image
// the rest of lines are vectors. these will adjust with scale value auto.
this.lines.call(
this
, linesargs[2] // lines
, linesargs[0] // starting x
, linesargs[1] // starting y
, scale
)
}
}
// clean up
// workernode.parentNode.removeChild(workernode)
return this
}
})(jsPDF.API)

View File

@ -0,0 +1,298 @@
/** @preserve
jsPDF split_text_to_size plugin
Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
MIT license.
*/
/**
* 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.
* ====================================================================
*/
;(function(API) {
'use strict'
/**
Returns an array of length matching length of the 'word' string, with each
cell ocupied by the width of the char in that position.
@function
@param word {String}
@param widths {Object}
@param kerning {Object}
@returns {Array}
*/
var getCharWidthsArray = API.getCharWidthsArray = function(text, options){
if (!options) {
options = {}
}
var widths = options.widths ? options.widths : this.internal.getFont().metadata.Unicode.widths
, widthsFractionOf = widths.fof ? widths.fof : 1
, kerning = options.kerning ? options.kerning : this.internal.getFont().metadata.Unicode.kerning
, kerningFractionOf = kerning.fof ? kerning.fof : 1
// console.log("widths, kergnings", widths, kerning)
var i, l
, char_code
, char_width
, prior_char_code = 0 // for kerning
, default_char_width = widths[0] || widthsFractionOf
, output = []
for (i = 0, l = text.length; i < l; i++) {
char_code = text.charCodeAt(i)
output.push(
( widths[char_code] || default_char_width ) / widthsFractionOf +
( kerning[char_code] && kerning[char_code][prior_char_code] || 0 ) / kerningFractionOf
)
prior_char_code = char_code
}
return output
}
var getArraySum = function(array){
var i = array.length
, output = 0
while(i){
;i--;
output += array[i]
}
return output
}
/**
Returns a widths of string in a given font, if the font size is set as 1 point.
In other words, this is "proportional" value. For 1 unit of font size, the length
of the string will be that much.
Multiply by font size to get actual width in *points*
Then divide by 72 to get inches or divide by (72/25.6) to get 'mm' etc.
@public
@function
@param
@returns {Type}
*/
var getStringUnitWidth = API.getStringUnitWidth = function(text, options) {
return getArraySum(getCharWidthsArray.call(this, text, options))
}
/**
returns array of lines
*/
var splitLongWord = function(word, widths_array, firstLineMaxLen, maxLen){
var answer = []
// 1st, chop off the piece that can fit on the hanging line.
var i = 0
, l = word.length
, workingLen = 0
while (i !== l && workingLen + widths_array[i] < firstLineMaxLen){
workingLen += widths_array[i]
;i++;
}
// this is first line.
answer.push(word.slice(0, i))
// 2nd. Split the rest into maxLen pieces.
var startOfLine = i
workingLen = 0
while (i !== l){
if (workingLen + widths_array[i] > maxLen) {
answer.push(word.slice(startOfLine, i))
workingLen = 0
startOfLine = i
}
workingLen += widths_array[i]
;i++;
}
if (startOfLine !== i) {
answer.push(word.slice(startOfLine, i))
}
return answer
}
// Note, all sizing inputs for this function must be in "font measurement units"
// By default, for PDF, it's "point".
var splitParagraphIntoLines = function(text, maxlen, options){
// at this time works only on Western scripts, ones with space char
// separating the words. Feel free to expand.
if (!options) {
options = {}
}
var spaceCharWidth = getCharWidthsArray(' ', options)[0]
var words = text.split(' ')
var line = []
, lines = [line]
, line_length = options.textIndent || 0
, separator_length = 0
, current_word_length = 0
, word
, widths_array
var i, l, tmp
for (i = 0, l = words.length; i < l; i++) {
word = words[i]
widths_array = getCharWidthsArray(word, options)
current_word_length = getArraySum(widths_array)
if (line_length + separator_length + current_word_length > maxlen) {
if (current_word_length > maxlen) {
// this happens when you have space-less long URLs for example.
// we just chop these to size. We do NOT insert hiphens
tmp = splitLongWord(word, widths_array, maxlen - (line_length + separator_length), maxlen)
// first line we add to existing line object
line.push(tmp.shift()) // it's ok to have extra space indicator there
// last line we make into new line object
line = [tmp.pop()]
// lines in the middle we apped to lines object as whole lines
while(tmp.length){
lines.push([tmp.shift()]) // single fragment occupies whole line
}
current_word_length = getArraySum( widths_array.slice(word.length - line[0].length) )
} else {
// just put it on a new line
line = [word]
}
// now we attach new line to lines
lines.push(line)
line_length = current_word_length
separator_length = spaceCharWidth
} else {
line.push(word)
line_length += separator_length + current_word_length
separator_length = spaceCharWidth
}
}
var output = []
for (i = 0, l = lines.length; i < l; i++) {
output.push( lines[i].join(' ') )
}
return output
}
/**
Splits a given string into an array of strings. Uses 'size' value
(in measurement units declared as default for the jsPDF instance)
and the font's "widths" and "Kerning" tables, where availabe, to
determine display length of a given string for a given font.
We use character's 100% of unit size (height) as width when Width
table or other default width is not available.
@public
@function
@param text {String} Unencoded, regular JavaScript (Unicode, UTF-16 / UCS-2) string.
@param size {Number} Nominal number, measured in units default to this instance of jsPDF.
@param options {Object} Optional flags needed for chopper to do the right thing.
@returns {Array} with strings chopped to size.
*/
API.splitTextToSize = function(text, maxlen, options) {
'use strict'
if (!options) {
options = {}
}
var fsize = options.fontSize || this.internal.getFontSize()
, newOptions = (function(options){
var widths = {0:1}
, kerning = {}
if (!options.widths || !options.kerning) {
var f = this.internal.getFont(options.fontName, options.fontStyle)
, encoding = 'Unicode'
// NOT UTF8, NOT UTF16BE/LE, NOT UCS2BE/LE
// Actual JavaScript-native String's 16bit char codes used.
// no multi-byte logic here
if (f.metadata[encoding]) {
return {
widths: f.metadata[encoding].widths || widths
, kerning: f.metadata[encoding].kerning || kerning
}
}
} else {
return {
widths: options.widths
, kerning: options.kerning
}
}
// then use default values
return {
widths: widths
, kerning: kerning
}
}).call(this, options)
// first we split on end-of-line chars
var paragraphs
if (text.match(/[\n\r]/)) {
paragraphs = text.split(/\r\n|\r|\n/g)
} else {
paragraphs = [text]
}
// now we convert size (max length of line) into "font size units"
// at present time, the "font size unit" is always 'point'
// 'proportional' means, "in proportion to font size"
var fontUnit_maxLen = 1.0 * this.internal.scaleFactor * maxlen / fsize
// at this time, fsize is always in "points" regardless of the default measurement unit of the doc.
// this may change in the future?
// until then, proportional_maxlen is likely to be in 'points'
// If first line is to be indented (shorter or longer) than maxLen
// we indicate that by using CSS-style "text-indent" option.
// here it's in font units too (which is likely 'points')
// it can be negative (which makes the first line longer than maxLen)
newOptions.textIndent = options.textIndent ?
options.textIndent * 1.0 * this.internal.scaleFactor / fsize :
0
var i, l
, output = []
for (i = 0, l = paragraphs.length; i < l; i++) {
output = output.concat(
splitParagraphIntoLines(
paragraphs[i]
, fontUnit_maxLen
, newOptions
)
)
}
return output
}
})(jsPDF.API);

View File

@ -0,0 +1,395 @@
/** @preserve
jsPDF standard_fonts_metrics plugin
Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
MIT license.
*/
/**
* 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.
* ====================================================================
*/
;(function(API) {
'use strict'
/*
# reference (Python) versions of 'compress' and 'uncompress'
# only 'uncompress' function is featured lower as JavaScript
# if you want to unit test "roundtrip", just transcribe the reference
# 'compress' function from Python into JavaScript
def compress(data):
keys = '0123456789abcdef'
values = 'klmnopqrstuvwxyz'
mapping = dict(zip(keys, values))
vals = []
for key in data.keys():
value = data[key]
try:
keystring = hex(key)[2:]
keystring = keystring[:-1] + mapping[keystring[-1:]]
except:
keystring = key.join(["'","'"])
#print('Keystring is %s' % keystring)
try:
if value < 0:
valuestring = hex(value)[3:]
numberprefix = '-'
else:
valuestring = hex(value)[2:]
numberprefix = ''
valuestring = numberprefix + valuestring[:-1] + mapping[valuestring[-1:]]
except:
if type(value) == dict:
valuestring = compress(value)
else:
raise Exception("Don't know what to do with value type %s" % type(value))
vals.append(keystring+valuestring)
return '{' + ''.join(vals) + '}'
def uncompress(data):
decoded = '0123456789abcdef'
encoded = 'klmnopqrstuvwxyz'
mapping = dict(zip(encoded, decoded))
sign = +1
stringmode = False
stringparts = []
output = {}
activeobject = output
parentchain = []
keyparts = ''
valueparts = ''
key = None
ending = set(encoded)
i = 1
l = len(data) - 1 # stripping starting, ending {}
while i != l: # stripping {}
# -, {, }, ' are special.
ch = data[i]
i += 1
if ch == "'":
if stringmode:
# end of string mode
stringmode = False
key = ''.join(stringparts)
else:
# start of string mode
stringmode = True
stringparts = []
elif stringmode == True:
#print("Adding %s to stringpart" % ch)
stringparts.append(ch)
elif ch == '{':
# start of object
parentchain.append( [activeobject, key] )
activeobject = {}
key = None
#DEBUG = True
elif ch == '}':
# end of object
parent, key = parentchain.pop()
parent[key] = activeobject
key = None
activeobject = parent
#DEBUG = False
elif ch == '-':
sign = -1
else:
# must be number
if key == None:
#debug("In Key. It is '%s', ch is '%s'" % (keyparts, ch))
if ch in ending:
#debug("End of key")
keyparts += mapping[ch]
key = int(keyparts, 16) * sign
sign = +1
keyparts = ''
else:
keyparts += ch
else:
#debug("In value. It is '%s', ch is '%s'" % (valueparts, ch))
if ch in ending:
#debug("End of value")
valueparts += mapping[ch]
activeobject[key] = int(valueparts, 16) * sign
sign = +1
key = None
valueparts = ''
else:
valueparts += ch
#debug(activeobject)
return output
*/
/**
Uncompresses data compressed into custom, base16-like format.
@public
@function
@param
@returns {Type}
*/
var uncompress = function(data){
var decoded = '0123456789abcdef'
, encoded = 'klmnopqrstuvwxyz'
, mapping = {}
for (var i = 0; i < encoded.length; i++){
mapping[encoded[i]] = decoded[i]
}
var undef
, output = {}
, sign = 1
, stringparts // undef. will be [] in string mode
, activeobject = output
, parentchain = []
, parent_key_pair
, keyparts = ''
, valueparts = ''
, key // undef. will be Truthy when Key is resolved.
, datalen = data.length - 1 // stripping ending }
, ch
i = 1 // stripping starting {
while (i != datalen){
// - { } ' are special.
ch = data[i]
i += 1
if (ch == "'"){
if (stringparts){
// end of string mode
key = stringparts.join('')
stringparts = undef
} else {
// start of string mode
stringparts = []
}
} else if (stringparts){
stringparts.push(ch)
} else if (ch == '{'){
// start of object
parentchain.push( [activeobject, key] )
activeobject = {}
key = undef
} else if (ch == '}'){
// end of object
parent_key_pair = parentchain.pop()
parent_key_pair[0][parent_key_pair[1]] = activeobject
key = undef
activeobject = parent_key_pair[0]
} else if (ch == '-'){
sign = -1
} else {
// must be number
if (key === undef) {
if (mapping.hasOwnProperty(ch)){
keyparts += mapping[ch]
key = parseInt(keyparts, 16) * sign
sign = +1
keyparts = ''
} else {
keyparts += ch
}
} else {
if (mapping.hasOwnProperty(ch)){
valueparts += mapping[ch]
activeobject[key] = parseInt(valueparts, 16) * sign
sign = +1
key = undef
valueparts = ''
} else {
valueparts += ch
}
}
}
} // end while
return output
}
// encoding = 'Unicode'
// NOT UTF8, NOT UTF16BE/LE, NOT UCS2BE/LE. NO clever BOM behavior
// Actual 16bit char codes used.
// no multi-byte logic here
// Unicode characters to WinAnsiEncoding:
// {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}
// as you can see, all Unicode chars are outside of 0-255 range. No char code conflicts.
// this means that you can give Win cp1252 encoded strings to jsPDF for rendering directly
// as well as give strings with some (supported by these fonts) Unicode characters and
// these will be mapped to win cp1252
// for example, you can send char code (cp1252) 0x80 or (unicode) 0x20AC, getting "Euro" glyph displayed in both cases.
var encodingBlock = {
'codePages': ['WinAnsiEncoding']
, 'WinAnsiEncoding': uncompress("{19m8n201n9q201o9r201s9l201t9m201u8m201w9n201x9o201y8o202k8q202l8r202m9p202q8p20aw8k203k8t203t8v203u9v2cq8s212m9t15m8w15n9w2dw9s16k8u16l9u17s9z17x8y17y9y}")
}
, encodings = {'Unicode':{
'Courier': encodingBlock
, 'Courier-Bold': encodingBlock
, 'Courier-BoldOblique': encodingBlock
, 'Courier-Oblique': encodingBlock
, 'Helvetica': encodingBlock
, 'Helvetica-Bold': encodingBlock
, 'Helvetica-BoldOblique': encodingBlock
, 'Helvetica-Oblique': encodingBlock
, 'Times-Roman': encodingBlock
, 'Times-Bold': encodingBlock
, 'Times-BoldItalic': encodingBlock
, 'Times-Italic': encodingBlock
// , 'Symbol'
// , 'ZapfDingbats'
}}
/**
Resources:
Font metrics data is reprocessed derivative of contents of
"Font Metrics for PDF Core 14 Fonts" package, which exhibits the following copyright and license:
Copyright (c) 1989, 1990, 1991, 1992, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.
This file and the 14 PostScript(R) AFM files it accompanies may be used,
copied, and distributed for any purpose and without charge, with or without
modification, provided that all copyright notices are retained; that the AFM
files are not distributed without this file; that all modifications to this
file or any of the AFM files are prominently noted in the modified file(s);
and that this paragraph is not modified. Adobe Systems has no responsibility
or obligation to support the use of the AFM files.
*/
, fontMetrics = {'Unicode':{
// all sizing numbers are n/fontMetricsFractionOf = one font size unit
// this means that if fontMetricsFractionOf = 1000, and letter A's width is 476, it's
// width is 476/1000 or 47.6% of its height (regardless of font size)
// At this time this value applies to "widths" and "kerning" numbers.
// char code 0 represents "default" (average) width - use it for chars missing in this table.
// key 'fof' represents the "fontMetricsFractionOf" value
'Courier-Oblique': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}")
, 'Times-BoldItalic': uncompress("{'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}}}")
, 'Helvetica-Bold': uncompress("{'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}}}")
, 'Courier': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}")
, 'Courier-BoldOblique': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}")
, 'Times-Bold': uncompress("{'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}}}")
//, 'Symbol': uncompress("{'widths'{k3uaw4r19m3m2k1t2l2l202m2y2n3m2p5n202q6o3k3m2s2l2t2l2v3r2w1t3m3m2y1t2z1wbk2sbl3r'fof'6o3n3m3o3m3p3m3q3m3r3m3s3m3t3m3u1w3v1w3w3r3x3r3y3r3z2wbp3t3l3m5v2l5x2l5z3m2q4yfr3r7v3k7w1o7x3k}'kerning'{'fof'-6o}}")
, 'Helvetica': uncompress("{'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}}}")
, 'Helvetica-BoldOblique': uncompress("{'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}}}")
//, 'ZapfDingbats': uncompress("{'widths'{k4u2k1w'fof'6o}'kerning'{'fof'-6o}}")
, 'Courier-Bold': uncompress("{'widths'{k3w'fof'6o}'kerning'{'fof'-6o}}")
, 'Times-Italic': uncompress("{'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}}}")
, 'Times-Roman': uncompress("{'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}}}")
, 'Helvetica-Oblique': uncompress("{'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}}}")
}};
/*
This event handler is fired when a new jsPDF object is initialized
This event handler appends metrics data to standard fonts within
that jsPDF instance. The metrics are mapped over Unicode character
codes, NOT CIDs or other codes matching the StandardEncoding table of the
standard PDF fonts.
Future:
Also included is the encoding maping table, converting Unicode (UCS-2, UTF-16)
char codes to StandardEncoding character codes. The encoding table is to be used
somewhere around "pdfEscape" call.
*/
API.events.push([
'addFonts'
,function(fontManagementObjects) {
// fontManagementObjects is {
// 'fonts':font_ID-keyed hash of font objects
// , 'dictionary': lookup object, linking ["FontFamily"]['Style'] to font ID
//}
var font
, fontID
, metrics
, unicode_section
, encoding = 'Unicode'
, encodingBlock
for (fontID in fontManagementObjects.fonts){
if (fontManagementObjects.fonts.hasOwnProperty(fontID)) {
font = fontManagementObjects.fonts[fontID]
// // we only ship 'Unicode' mappings and metrics. No need for loop.
// // still, leaving this for the future.
// for (encoding in fontMetrics){
// if (fontMetrics.hasOwnProperty(encoding)) {
metrics = fontMetrics[encoding][font.PostScriptName]
if (metrics) {
if (font.metadata[encoding]) {
unicode_section = font.metadata[encoding]
} else {
unicode_section = font.metadata[encoding] = {}
}
unicode_section.widths = metrics.widths
unicode_section.kerning = metrics.kerning
}
// }
// }
// for (encoding in encodings){
// if (encodings.hasOwnProperty(encoding)) {
encodingBlock = encodings[encoding][font.PostScriptName]
if (encodingBlock) {
if (font.metadata[encoding]) {
unicode_section = font.metadata[encoding]
} else {
unicode_section = font.metadata[encoding] = {}
}
unicode_section.encoding = encodingBlock
if (encodingBlock.codePages && encodingBlock.codePages.length) {
font.encoding = encodingBlock.codePages[0]
}
}
// }
// }
}
}
}
]) // end of adding event handler
})(jsPDF.API);

6
todo.md Normal file
View File

@ -0,0 +1,6 @@
# Todo
* bold/italic/underline
* blockquotes
* works cited page
* citations