'use strict';var _typeof2=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj;}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};(function(global,factory){(typeof exports==='undefined'?'undefined':_typeof2(exports))==='object'&&typeof module!=='undefined'?factory(exports):typeof define==='function'&&define.amd?define(['exports'],factory):factory(global.jsPDF={});})(undefined,function(exports){'use strict';/**
* JavaScript Polyfill functions for jsPDF
* Collected from public resources by
* https://github.com/diegocr
*/(function(global){if(_typeof2(global.console)!=="object"){// Console-polyfill. MIT license.
// https://github.com/paulmillr/console-polyfill
// Make it safe to do console.log() always.
global.console={};var con=global.console;var prop,method;var dummy=function dummy(){};var properties=["memory"];var methods=("assert,clear,count,debug,dir,dirxml,error,exception,group,"+"groupCollapsed,groupEnd,info,log,markTimeline,profile,profiles,profileEnd,"+"show,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn").split(",");while(prop=properties.pop()){if(!con[prop])con[prop]={};}while(method=methods.pop()){if(!con[method])con[method]=dummy;}}var b64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";if(typeof global.btoa==="undefined"){global.btoa=function(data){// discuss at: http://phpjs.org/functions/base64_encode/
// original by: Tyler Akins (http://rumkin.com)
// improved by: Bayron Guevara
// improved by: Thunder.m
// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// improved by: Rafal Kukawski (http://kukawski.pl)
// bugfixed by: Pellentesque Malesuada
// example 1: base64_encode('Kevin van Zonneveld');
// returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
var o1,o2,o3,h1,h2,h3,h4,bits,i=0,ac=0,enc="",tmp_arr=[];if(!data){return data;}do{// pack three octets into four hexets
o1=data.charCodeAt(i++);o2=data.charCodeAt(i++);o3=data.charCodeAt(i++);bits=o1<<16|o2<<8|o3;h1=bits>>18&0x3f;h2=bits>>12&0x3f;h3=bits>>6&0x3f;h4=bits&0x3f;// use hexets to index into b64, and append result to encoded string
tmp_arr[ac++]=b64.charAt(h1)+b64.charAt(h2)+b64.charAt(h3)+b64.charAt(h4);}while(i>16&0xff;o2=bits>>8&0xff;o3=bits&0xff;if(h3==64){tmp_arr[ac++]=String.fromCharCode(o1);}else if(h4==64){tmp_arr[ac++]=String.fromCharCode(o1,o2);}else{tmp_arr[ac++]=String.fromCharCode(o1,o2,o3);}}while(i>>0,res=new Array(len);var thisArg=arguments.length>1?arguments[1]:void 0;for(var i=0;i>>0;for(var i=0;i} */this._deferreds=[];doResolve(fn,this);}function handle(self,deferred){while(self._state===3){self=self._value;}if(self._state===0){self._deferreds.push(deferred);return;}self._handled=true;Promise._immediateFn(function(){var cb=self._state===1?deferred.onFulfilled:deferred.onRejected;if(cb===null){(self._state===1?resolve:reject)(deferred.promise,self._value);return;}var ret;try{ret=cb(self._value);}catch(e){reject(deferred.promise,e);return;}resolve(deferred.promise,ret);});}function resolve(self,newValue){try{// Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
if(newValue===self)throw new TypeError('A promise cannot be resolved with itself.');if(newValue&&((typeof newValue==='undefined'?'undefined':_typeof2(newValue))==='object'||typeof newValue==='function')){var then=newValue.then;if(newValue instanceof Promise){self._state=3;self._value=newValue;finale(self);return;}else if(typeof then==='function'){doResolve(bind(then,newValue),self);return;}}self._state=1;self._value=newValue;finale(self);}catch(e){reject(self,e);}}function reject(self,newValue){self._state=2;self._value=newValue;finale(self);}function finale(self){if(self._state===2&&self._deferreds.length===0){Promise._immediateFn(function(){if(!self._handled){Promise._unhandledRejectionFn(self._value);}});}for(var i=0,len=self._deferreds.length;i, https://github.com/HackbrettXXX
* 2010-2016 James Hall , https://github.com/MrRio/jsPDF
* 2010 Aaron Spike, https://github.com/acspike
* 2012 Willow Systems Corporation, willow-systems.com
* 2012 Pablo Hess, https://github.com/pablohess
* 2012 Florian Jenett, https://github.com/fjenett
* 2013 Warren Weckesser, https://github.com/warrenweckesser
* 2013 Youssef Beddad, https://github.com/lifof
* 2013 Lee Driscoll, https://github.com/lsdriscoll
* 2013 Stefan Slonevskiy, https://github.com/stefslon
* 2013 Jeremy Morel, https://github.com/jmorel
* 2013 Christoph Hartmann, https://github.com/chris-rock
* 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria
* 2014 James Makes, https://github.com/dollaruw
* 2014 Diego Casorran, https://github.com/diegocr
* 2014 Steven Spungin, https://github.com/Flamenco
* 2014 Kenneth Glassey, https://github.com/Gavvers
*
* Licensed under the MIT License
*
* Contributor(s):
* siefkenj, ahwolf, rickygu, Midnith, saintclair, eaparango,
* kim3er, mfo, alnorth, Flamenco
*//**
* Creates new jsPDF document object instance.
* @name jsPDF
* @class
* @param orientation {string/Object} Orientation of the first page. Possible values are "portrait" or "landscape" (or shortcuts "p" (Default), "l")
* Can also be an options object.
* @param unit {string} Measurement unit to be used when coordinates are specified.
* Possible values are "pt" (points), "mm" (Default), "cm", "in" or "px".
* @param format {string/Array} The format of the first page. Can be
a0 - a10
b0 - b10
c0 - c10
c0 - c10
dl
letter
government-letter
legal
junior-legal
ledger
tabloid
credit-card
* Default is "a4". If you want to use your own format just pass instead of one of the above predefined formats the size as an number-array , e.g. [595.28, 841.89]
* @returns {jsPDF} jsPDF-instance
* @description
* If the first parameter (orientation) is an object, it will be interpreted as an object of named parameters
* ```
* {
* orientation: 'p',
* unit: 'mm',
* format: 'a4',
* hotfixes: [] // an array of hotfix strings to enable
* }
* ```
*/var jsPDF=function(global){var pdfVersion="1.3",pageFormats={// Size in pt of various paper formats
a0:[2383.94,3370.39],a1:[1683.78,2383.94],a2:[1190.55,1683.78],a3:[841.89,1190.55],a4:[595.28,841.89],a5:[419.53,595.28],a6:[297.64,419.53],a7:[209.76,297.64],a8:[147.4,209.76],a9:[104.88,147.4],a10:[73.7,104.88],b0:[2834.65,4008.19],b1:[2004.09,2834.65],b2:[1417.32,2004.09],b3:[1000.63,1417.32],b4:[708.66,1000.63],b5:[498.9,708.66],b6:[354.33,498.9],b7:[249.45,354.33],b8:[175.75,249.45],b9:[124.72,175.75],b10:[87.87,124.72],c0:[2599.37,3676.54],c1:[1836.85,2599.37],c2:[1298.27,1836.85],c3:[918.43,1298.27],c4:[649.13,918.43],c5:[459.21,649.13],c6:[323.15,459.21],c7:[229.61,323.15],c8:[161.57,229.61],c9:[113.39,161.57],c10:[79.37,113.39],dl:[311.81,623.62],letter:[612,792],"government-letter":[576,756],legal:[612,1008],"junior-legal":[576,360],ledger:[1224,792],tabloid:[792,1224],"credit-card":[153,243]};/**
* jsPDF's Internal PubSub Implementation.
* Backward compatible rewritten on 2014 by
* Diego Casorran, https://github.com/diegocr
*
* @class
* @name PubSub
* @ignore
*/function PubSub(context){var topics={};this.subscribe=function(topic,callback,once){if(typeof callback!=="function"){return false;}if(!topics.hasOwnProperty(topic)){topics[topic]={};}var id=Math.random().toString(35);topics[topic][id]=[callback,!!once];return id;};this.unsubscribe=function(token){for(var topic in topics){if(topics[topic][token]){delete topics[topic][token];return true;}}return false;};this.publish=function(topic){if(topics.hasOwnProperty(topic)){var args=Array.prototype.slice.call(arguments,1),idr=[];for(var id in topics[topic]){var sub=topics[topic][id];try{sub[0].apply(context,args);}catch(ex){if(global.console){console.error("jsPDF PubSub Error",ex.message,ex);}}if(sub[1])idr.push(id);}if(idr.length)idr.forEach(this.unsubscribe);}};}/**
* @constructor
* @private
*/function jsPDF(orientation,unit,format,compressPdf){var options={};if(_typeof(orientation)==="object"){options=orientation;orientation=options.orientation;unit=options.unit||unit;format=options.format||format;compressPdf=options.compress||options.compressPdf||compressPdf;}// Default options
unit=unit||"mm";format=format||"a4";orientation=(""+(orientation||"P")).toLowerCase();var format_as_string=(""+format).toLowerCase(),compress=!!compressPdf&&typeof Uint8Array==="function",textColor=options.textColor||"0 g",drawColor=options.drawColor||"0 G",activeFontSize=options.fontSize||16,activeCharSpace=options.charSpace||0,R2L=options.R2L||false,lineHeightProportion=options.lineHeight||1.15,lineWidth=options.lineWidth||0.200025,// 2mm
fileId="00000000000000000000000000000000",objectNumber=2,// 'n' Current object number
outToPages=!1,// switches where out() prints. outToPages true = push to pages obj. outToPages false = doc builder content
offsets=[],// List of offsets. Activated and reset by buildDocument(). Pupulated by various calls buildDocument makes.
fonts={},// collection of font objects, where key is fontKey - a dynamically created label for a given font.
fontmap={},// mapping structure fontName > fontStyle > font key - performance layer. See addFont()
activeFontKey,// will be string representing the KEY of the font as combination of fontName + fontStyle
fontStateStack=[],//
patterns={},// collection of pattern objects
patternMap={},// see fonts
gStates={},// collection of graphic state objects
gStatesMap={},// see fonts
activeGState=null,k,// Scale factor
tmp,page=0,currentPage,pages=[],pagesContext=[],// same index as pages and pagedim
pagedim=[],content=[],additionalObjects=[],lineCapID=0,lineJoinID=0,content_length=0,renderTargets={},renderTargetMap={},renderTargetStack=[],pageX,pageY,pageMatrix,// only used for FormObjects
pageWidth,pageHeight,pageMode,zoomMode,layoutMode,creationDate,documentProperties={title:"",subject:"",author:"",keywords:"",creator:""},API={},ApiMode={COMPAT:"compat",ADVANCED:"advanced"},apiMode=ApiMode.COMPAT,events=new PubSub(API),hotfixes=options.hotfixes||[],/////////////////////
// Private functions
/////////////////////
generateColorString=function generateColorString(options){var color;var ch1=options.ch1;var ch2=options.ch2;var ch3=options.ch3;var ch4=options.ch4;var precision=options.precision;var letterArray=options.pdfColorType==="draw"?["G","RG","K"]:["g","rg","k"];if(typeof ch1==="string"&&ch1.charAt(0)!=="#"){var rgbColor=new RGBColor(ch1);if(rgbColor.ok){ch1=rgbColor.toHex();}}//convert short rgb to long form
if(typeof ch1==="string"&&/^#[0-9A-Fa-f]{3}$/.test(ch1)){ch1="#"+ch1[1]+ch1[1]+ch1[2]+ch1[2]+ch1[3]+ch1[3];}if(typeof ch1==="string"&&/^#[0-9A-Fa-f]{6}$/.test(ch1)){var hex=parseInt(ch1.substr(1),16);ch1=hex>>16&255;ch2=hex>>8&255;ch3=hex&255;}if(typeof ch2==="undefined"||typeof ch4==="undefined"&&ch1===ch2&&ch2===ch3){// Gray color space.
if(typeof ch1==="string"){color=ch1+" "+letterArray[0];}else{switch(options.precision){case 2:color=f2(ch1/255)+" "+letterArray[0];break;case 3:default:color=f3(ch1/255)+" "+letterArray[0];}}}else if(typeof ch4==="undefined"||_typeof(ch4)==="object"){// assume RGB
if(typeof ch1==="string"){color=[ch1,ch2,ch3,letterArray[1]].join(" ");}else{switch(options.precision){case 2:color=[f2(ch1/255),f2(ch2/255),f2(ch3/255),letterArray[1]].join(" ");break;default:case 3:color=[f3(ch1/255),f3(ch2/255),f3(ch3/255),letterArray[1]].join(" ");}}// assume RGBA
if(ch4&&ch4.a===0){//TODO Implement transparency.
//WORKAROUND use white for now
color=["255","255","255",letterArray[1]].join(" ");}}else{// assume CMYK
if(typeof ch1==="string"){color=[ch1,ch2,ch3,ch4,letterArray[2]].join(" ");}else{switch(options.precision){case 2:color=[f2(ch1),f2(ch2),f2(ch3),f2(ch4),letterArray[2]].join(" ");break;case 3:default:color=[f3(ch1),f3(ch2),f3(ch3),f3(ch4),letterArray[2]].join(" ");}}}return color;},convertDateToPDFDate=function convertDateToPDFDate(parmDate){var padd2=function padd2(number){return("0"+parseInt(number)).slice(-2);};var result="";var tzoffset=parmDate.getTimezoneOffset(),tzsign=tzoffset<0?"+":"-",tzhour=Math.floor(Math.abs(tzoffset/60)),tzmin=Math.abs(tzoffset%60),timeZoneString=[tzsign,padd2(tzhour),"'",padd2(tzmin),"'"].join("");result=["D:",parmDate.getFullYear(),padd2(parmDate.getMonth()+1),padd2(parmDate.getDate()),padd2(parmDate.getHours()),padd2(parmDate.getMinutes()),padd2(parmDate.getSeconds()),timeZoneString].join("");return result;},convertPDFDateToDate=function convertPDFDateToDate(parmPDFDate){var year=parseInt(parmPDFDate.substr(2,4),10);var month=parseInt(parmPDFDate.substr(6,2),10)-1;var date=parseInt(parmPDFDate.substr(8,2),10);var hour=parseInt(parmPDFDate.substr(10,2),10);var minutes=parseInt(parmPDFDate.substr(12,2),10);var seconds=parseInt(parmPDFDate.substr(14,2),10);var timeZoneHour=parseInt(parmPDFDate.substr(16,2),10);var timeZoneMinutes=parseInt(parmPDFDate.substr(20,2),10);var resultingDate=new Date(year,month,date,hour,minutes,seconds,0);return resultingDate;},setCreationDate=function setCreationDate(date){var tmpCreationDateString;var regexPDFCreationDate=/^D:(20[0-2][0-9]|203[0-7]|19[7-9][0-9])(0[0-9]|1[0-2])([0-2][0-9]|3[0-1])(0[0-9]|1[0-9]|2[0-3])(0[0-9]|[1-5][0-9])(0[0-9]|[1-5][0-9])(\+0[0-9]|\+1[0-4]|\-0[0-9]|\-1[0-1])\'(0[0-9]|[1-5][0-9])\'?$/;if(_typeof(date)===undefined){date=new Date();}if(_typeof(date)==="object"&&Object.prototype.toString.call(date)==="[object Date]"){tmpCreationDateString=convertDateToPDFDate(date);}else if(regexPDFCreationDate.test(date)){tmpCreationDateString=date;}else{tmpCreationDateString=convertDateToPDFDate(new Date());}creationDate=tmpCreationDateString;return creationDate;},getCreationDate=function getCreationDate(type){var result=creationDate;if(type==="jsDate"){result=convertPDFDateToDate(creationDate);}return result;},setFileId=function setFileId(value){value=value||"12345678901234567890123456789012".split("").map(function(){return"ABCDEF0123456789".charAt(Math.floor(Math.random()*16));}).join("");fileId=value;return fileId;},getFileId=function getFileId(){return fileId;},f2=function f2(number){return number.toFixed(2);// Ie, %.2f
},f3=function f3(number){return number.toFixed(3);// Ie, %.3f
},// high precision float
hpf=function hpf(number){return number.toFixed(16).replace(/0+$/,"");},scaleByK=function scaleByK(coordinate){if(apiMode===ApiMode.COMPAT){return coordinate*k;}else if(apiMode===ApiMode.ADVANCED){return coordinate;}},transformY=function transformY(y){if(apiMode===ApiMode.COMPAT){return pageHeight-y;}else if(apiMode===ApiMode.ADVANCED){return y;}},transformScaleY=function transformScaleY(y){return scaleByK(transformY(y));},padd2Hex=function padd2Hex(hexString){var s="00"+hexString;return s.substr(s.length-2);},advancedApiModeTrap=function advancedApiModeTrap(methodName){if(apiMode!==ApiMode.ADVANCED){throw new Error(methodName+" is only available in 'advanced' API mode. "+"You need to call advancedAPI() first.");}},out=function out(string){string=typeof string==="string"?string:string.toString();if(outToPages){/* set by beginPage */pages[currentPage].push(string);}else{// +1 for '\n' that will be used to join 'content'
content_length+=string.length+1;content.push(string);}},newObject=function newObject(){// Begin a new object
objectNumber++;offsets[objectNumber]=content_length;out(objectNumber+" 0 obj");return objectNumber;},// Does not output the object until after the pages have been output.
// Returns an object containing the objectId and content.
// All pages have been added so the object ID can be estimated to start right after.
// This does not modify the current objectNumber; It must be updated after the newObjects are output.
newAdditionalObject=function newAdditionalObject(){var objId=pages.length*2+1;objId+=additionalObjects.length;var obj={objId:objId,content:""};additionalObjects.push(obj);return obj;},// Does not output the object. The caller must call newObjectDeferredBegin(oid) before outputing any data
newObjectDeferred=function newObjectDeferred(){objectNumber++;offsets[objectNumber]=function(){return content_length;};return objectNumber;},newObjectDeferredBegin=function newObjectDeferredBegin(oid){offsets[oid]=content_length;},putStream=function putStream(str){out("stream");out(str);out("endstream");},appendBuffer=function appendBuffer(buffer1,buffer2){var tmp=new Uint8Array(buffer1.byteLength+buffer2.byteLength);tmp.set(new Uint8Array(buffer1),0);tmp.set(new Uint8Array(buffer2),buffer1.byteLength);return tmp;},putPages=function putPages(){var n,p,arr,i,deflater,adler32,adler32cs,wPt,hPt,pageObjectNumbers=[];adler32cs=global.adler32cs||jsPDF.API.adler32cs;if(compress&&typeof adler32cs==="undefined"){compress=false;}// outToPages = false as set in endDocument(). out() writes to content.
for(n=1;n<=page;n++){pageObjectNumbers.push(newObject());wPt=(pageWidth=pagedim[n].width)*k;hPt=(pageHeight=pagedim[n].height)*k;out("<>");out("endobj");// Page content
p=pages[n].join("\n");if(apiMode===ApiMode.ADVANCED){// if the user forgot to switch back to COMPAT mode, we must balance the graphics stack again
p+="\nQ";}newObject();if(compress){arr=[];i=p.length;while(i--){arr[i]=p.charCodeAt(i);}adler32=adler32cs.from(p);deflater=new Deflater(6);p=deflater.append(new Uint8Array(arr));p=appendBuffer(p,deflater.flush());arr=new Uint8Array(p.byteLength+6);arr.set(new Uint8Array([120,156]));arr.set(p,2);arr.set(new Uint8Array([adler32&0xff,adler32>>8&0xff,adler32>>16&0xff,adler32>>24&0xff]),p.byteLength+2);var strings=[],chunkSize=0xffff;// There is a maximum stack size. We cannot call String.fromCharCode with as many arguments as we want
for(var j=0;j*chunkSize>");}else{out("<>");}putStream(p);out("endobj");}offsets[1]=content_length;out("1 0 obj");out("<>");out("endobj");events.publish("postPutPages");},putFont=function putFont(font){events.publish("putFont",{font:font,out:out,newObject:newObject,putStream:putStream});if(font.isAlreadyPutted!==true){font.objectNumber=newObject();out("<<");out("/Type /Font");out("/BaseFont /"+font.postScriptName);out("/Subtype /Type1");if(typeof font.encoding==="string"){out("/Encoding /"+font.encoding);}out("/FirstChar 32");out("/LastChar 255");out(">>");out("endobj");}},putFonts=function putFonts(){for(var fontKey in fonts){if(fonts.hasOwnProperty(fontKey)){putFont(fonts[fontKey]);}}},putXObject=function putXObject(xObject){xObject.objectNumber=newObject();out("<<");out("/Type /XObject");out("/Subtype /Form");out("/BBox ["+[hpf(xObject.x),hpf(xObject.y),hpf(xObject.x+xObject.width),hpf(xObject.y+xObject.height)].join(" ")+"]");out("/Matrix ["+xObject.matrix.toString()+"]");// TODO: /Resources
var p=xObject.pages[1].join("\n");out("/Length "+p.length);out(">>");putStream(p);out("endobj");},putXObjects=function putXObjects(){for(var xObjectKey in renderTargets){if(renderTargets.hasOwnProperty(xObjectKey)){putXObject(renderTargets[xObjectKey]);}}},interpolateAndEncodeRGBStream=function interpolateAndEncodeRGBStream(colors,numberSamples){var tValues=[];var t;var dT=1.0/(numberSamples-1);for(t=0.0;t<1.0;t+=dT){tValues.push(t);}tValues.push(1.0);// add first and last control point if not present
if(colors[0].offset!=0.0){var c0={offset:0.0,color:colors[0].color};colors.unshift(c0);}if(colors[colors.length-1].offset!=1.0){var c1={offset:1.0,color:colors[colors.length-1].color};colors.push(c1);}var out="";var index=0;for(var i=0;icolors[index+1].offset){index++;}var a=colors[index].offset;var b=colors[index+1].offset;var d=(t-a)/(b-a);var aColor=colors[index].color;var bColor=colors[index+1].color;out+=padd2Hex(Math.round((1-d)*aColor[0]+d*bColor[0]).toString(16))+padd2Hex(Math.round((1-d)*aColor[1]+d*bColor[1]).toString(16))+padd2Hex(Math.round((1-d)*aColor[2]+d*bColor[2]).toString(16));}return out.trim();},putShadingPattern=function putShadingPattern(pattern,numberSamples){/*
Axial patterns shade between the two points specified in coords, radial patterns between the inner
and outer circle.
The user can specify an array (colors) that maps t-Values in [0, 1] to RGB colors. These are now
interpolated to equidistant samples and written to pdf as a sample (type 0) function.
*/// The number of color samples that should be used to describe the shading.
// The higher, the more accurate the gradient will be.
numberSamples||(numberSamples=21);var funcObjectNumber=newObject();var stream=interpolateAndEncodeRGBStream(pattern.colors,numberSamples);out("<< /FunctionType 0");out("/Domain [0.0 1.0]");out("/Size ["+numberSamples+"]");out("/BitsPerSample 8");out("/Range [0.0 1.0 0.0 1.0 0.0 1.0]");out("/Decode [0.0 1.0 0.0 1.0 0.0 1.0]");out("/Length "+stream.length);// The stream is Hex encoded
out("/Filter /ASCIIHexDecode");out(">>");putStream(stream);out("endobj");pattern.objectNumber=newObject();out("<< /ShadingType "+pattern.type);out("/ColorSpace /DeviceRGB");var coords="/Coords ["+hpf(parseFloat(pattern.coords[0]))+" "+// x1
hpf(parseFloat(pattern.coords[1]))+" ";// y1
if(pattern.type===2){// axial
coords+=hpf(parseFloat(pattern.coords[2]))+" "+// x2
hpf(parseFloat(pattern.coords[3]));// y2
}else{// radial
coords+=hpf(parseFloat(pattern.coords[2]))+" "+// r1
hpf(parseFloat(pattern.coords[3]))+" "+// x2
hpf(parseFloat(pattern.coords[4]))+" "+// y2
hpf(parseFloat(pattern.coords[5]));// r2
}coords+="]";out(coords);if(pattern.matrix){out("/Matrix ["+pattern.matrix.toString()+"]");}out("/Function "+funcObjectNumber+" 0 R");out("/Extend [true true]");out(">>");out("endobj");},putTilingPattern=function putTilingPattern(pattern){var resourcesObjectNumber=newObject();out("<<");putResourceDictionary();out(">>");out("endobj");pattern.objectNumber=newObject();out("<< /Type /Pattern");out("/PatternType 1");// tiling pattern
out("/PaintType 1");// colored tiling pattern
out("/TilingType 1");// constant spacing
out("/BBox ["+pattern.boundingBox.map(hpf).join(" ")+"]");out("/XStep "+hpf(pattern.xStep));out("/YStep "+hpf(pattern.yStep));out("/Length "+pattern.stream.length);out("/Resources "+resourcesObjectNumber+" 0 R");// TODO: resources
pattern.matrix&&out("/Matrix ["+pattern.matrix.toString()+"]");out(">>");putStream(pattern.stream);out("endobj");},putPatterns=function putPatterns(){var patternKey;for(patternKey in patterns){if(patterns.hasOwnProperty(patternKey)){if(patterns[patternKey]instanceof API.ShadingPattern){putShadingPattern(patterns[patternKey]);}else if(patterns[patternKey]instanceof API.TilingPattern){putTilingPattern(patterns[patternKey]);}}}},putGState=function putGState(gState){gState.objectNumber=newObject();out("<<");for(var p in gState){switch(p){case"opacity":out("/ca "+f2(gState[p]));break;case"stroke-opacity":out("/CA "+f2(gState[p]));break;}}out(">>");out("endobj");},putGStates=function putGStates(){var gStateKey;for(gStateKey in gStates){if(gStates.hasOwnProperty(gStateKey)){putGState(gStates[gStateKey]);}}},putXobjectDict=function putXobjectDict(){for(var xObjectKey in renderTargets){if(renderTargets.hasOwnProperty(xObjectKey)&&renderTargets[xObjectKey].objectNumber>=0){out("/"+xObjectKey+" "+renderTargets[xObjectKey].objectNumber+" 0 R");}}events.publish("putXobjectDict");},putShadingPatternDict=function putShadingPatternDict(){for(var patternKey in patterns){if(patterns.hasOwnProperty(patternKey)&&patterns[patternKey]instanceof API.ShadingPattern&&patterns[patternKey].objectNumber>=0){out("/"+patternKey+" "+patterns[patternKey].objectNumber+" 0 R");}}events.publish("putShadingPatternDict");},putTilingPatternDict=function putTilingPatternDict(){for(var patternKey in patterns){if(patterns.hasOwnProperty(patternKey)&&patterns[patternKey]instanceof API.TilingPattern&&patterns[patternKey].objectNumber>=0){out("/"+patternKey+" "+patterns[patternKey].objectNumber+" 0 R");}}events.publish("putTilingPatternDict");},putGStatesDict=function putGStatesDict(){var gStateKey;for(gStateKey in gStates){if(gStates.hasOwnProperty(gStateKey)&&gStates[gStateKey].objectNumber>=0){out("/"+gStateKey+" "+gStates[gStateKey].objectNumber+" 0 R");}}events.publish("putGStateDict");},putResourceDictionary=function putResourceDictionary(){out("/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]");out("/Font <<");// Do this for each font, the '1' bit is the index of the font
for(var fontKey in fonts){if(fonts.hasOwnProperty(fontKey)){out("/"+fontKey+" "+fonts[fontKey].objectNumber+" 0 R");}}out(">>");out("/Shading <<");putShadingPatternDict();out(">>");out("/Pattern <<");putTilingPatternDict();out(">>");out("/ExtGState <<");putGStatesDict();out(">>");out("/XObject <<");putXobjectDict();out(">>");},putResources=function putResources(){putFonts();putGStates();putXObjects();putPatterns();events.publish("putResources");// Resource dictionary
offsets[2]=content_length;out("2 0 obj");out("<<");putResourceDictionary();out(">>");out("endobj");events.publish("postPutResources");},putAdditionalObjects=function putAdditionalObjects(){events.publish("putAdditionalObjects");for(var i=0;i>8){/* more than 255 */isUnicode=true;}}text=newtext.join("");}}i=text.length;// isUnicode may be set to false above. Hence the triple-equal to undefined
while(isUnicode===undefined&&i!==0){if(text.charCodeAt(i-1)>>8){/* more than 255 */isUnicode=true;}i--;}if(!isUnicode){return text;}newtext=flags.noBOM?[]:[254,255];for(i=0,l=text.length;i>8;// divide by 256
if(bch>>8){/* something left after dividing by 256 second time */throw new Error("Character at position "+i+" of string '"+text+"' exceeds 16bits. Cannot be encoded into UCS-2 BE");}newtext.push(bch);newtext.push(ch-(bch<<8));}return String.fromCharCode.apply(undefined,newtext);},pdfEscape=function pdfEscape(text,flags){/**
* Replace '/', '(', and ')' with pdf-safe versions
*
* Doing to8bitStream does NOT make this PDF display unicode text. For that
* we also need to reference a unicode font and embed it - royal pain in the rear.
*
* There is still a benefit to to8bitStream - PDF simply cannot handle 16bit chars,
* which JavaScript Strings are happy to provide. So, while we still cannot display
* 2-byte characters property, at least CONDITIONALLY converting (entire string containing)
* 16bit chars to (USC-2-BE) 2-bytes per char + BOM streams we ensure that entire PDF
* is still parseable.
* This will allow immediate support for unicode in document properties strings.
*/return to8bitStream(text,flags).replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)");},putInfo=function putInfo(){out("/Producer (jsPDF "+jsPDF.version+")");for(var key in documentProperties){if(documentProperties.hasOwnProperty(key)&&documentProperties[key]){out("/"+key.substr(0,1).toUpperCase()+key.substr(1)+" ("+pdfEscape(documentProperties[key])+")");}}out("/CreationDate ("+creationDate+")");},putCatalog=function putCatalog(){out("/Type /Catalog");out("/Pages 1 0 R");// PDF13ref Section 7.2.1
if(!zoomMode)zoomMode="fullwidth";switch(zoomMode){case"fullwidth":out("/OpenAction [3 0 R /FitH null]");break;case"fullheight":out("/OpenAction [3 0 R /FitV null]");break;case"fullpage":out("/OpenAction [3 0 R /Fit]");break;case"original":out("/OpenAction [3 0 R /XYZ null null 1]");break;default:var pcn=""+zoomMode;if(pcn.substr(pcn.length-1)==="%")zoomMode=parseInt(zoomMode)/100;if(typeof zoomMode==="number"){out("/OpenAction [3 0 R /XYZ null null "+f2(zoomMode)+"]");}}if(!layoutMode)layoutMode="continuous";switch(layoutMode){case"continuous":out("/PageLayout /OneColumn");break;case"single":out("/PageLayout /SinglePage");break;case"two":case"twoleft":out("/PageLayout /TwoColumnLeft");break;case"tworight":out("/PageLayout /TwoColumnRight");break;}if(pageMode){/**
* A name object specifying how the document should be displayed when opened:
* UseNone : Neither document outline nor thumbnail images visible -- DEFAULT
* UseOutlines : Document outline visible
* UseThumbs : Thumbnail images visible
* FullScreen : Full-screen mode, with no menu bar, window controls, or any other window visible
*/out("/PageMode /"+pageMode);}events.publish("putCatalog");},putTrailer=function putTrailer(){out("/Size "+(objectNumber+1));out("/Root "+objectNumber+" 0 R");out("/Info "+(objectNumber-1)+" 0 R");out("/ID [ <"+fileId+"> <"+fileId+"> ]");},beginPage=function beginPage(width,height){outToPages=true;pages[++page]=[];pagedim[page]={width:Number(width)||pageWidth,height:Number(height)||pageHeight};pagesContext[page]={};_setPage(page);},_addPage=function _addPage(width,height){// Dimensions are stored as user units and converted to points on output
var orientation=typeof height==="string"&&height.toLowerCase();if(typeof width==="string"){var format=width.toLowerCase();if(pageFormats.hasOwnProperty(format)){width=pageFormats[format][0]/k;height=pageFormats[format][1]/k;}}if(Array.isArray(width)){height=width[1];width=width[0];}if(orientation){switch(orientation.substr(0,1)){case"l":if(height>width)orientation="s";break;case"p":if(width>height)orientation="s";break;}if(orientation==="s"){tmp=width;width=height;height=tmp;}}beginPage(width,height);// Set line width
out(hpf(lineWidth*k)+" w");// Set draw color
out(drawColor);// resurrecting non-default line caps, joins
if(lineCapID!==0){out(lineCapID+" J");}if(lineJoinID!==0){out(lineJoinID+" j");}events.publish("addPage",{pageNumber:page});},_deletePage=function _deletePage(n){if(n>0&&n<=page){pages.splice(n,1);pagedim.splice(n,1);page--;if(currentPage>page){currentPage=page;}this.setPage(currentPage);}},_setPage=function _setPage(n){if(n>0&&n<=page){currentPage=n;pageWidth=pagedim[n].width;pageHeight=pagedim[n].height;}},/**
* Returns a document-specific font key - a label assigned to a
* font name + font type combination at the time the font was added
* to the font inventory.
*
* Font key is used as label for the desired font for a block of text
* to be added to the PDF document stream.
* @private
* @function
* @param {String} fontName can be undefined on "falthy" to indicate "use current"
* @param {String} fontStyle can be undefined on "falthy" to indicate "use current"
* @returns {String} Font key.
*/_getFont=function getFont(fontName,fontStyle,options){var key=undefined,fontNameLowerCase;options=options||{};fontName=fontName!==undefined?fontName:fonts[activeFontKey].fontName;fontStyle=fontStyle!==undefined?fontStyle:fonts[activeFontKey].fontStyle;fontNameLowerCase=fontName.toLowerCase();if(fontmap[fontNameLowerCase]!==undefined&&fontmap[fontNameLowerCase][fontStyle]!==undefined){key=fontmap[fontNameLowerCase][fontStyle];}else if(fontmap[fontName]!==undefined&&fontmap[fontName][fontStyle]!==undefined){key=fontmap[fontName][fontStyle];}else{if(options.disableWarning===false){console.warn("Unable to look up font label for font '"+fontName+"', '"+fontStyle+"'. Refer to getFontList() for available fonts.");}}if(!key&&!options.noFallback){key=fontmap["times"][fontStyle];if(key==null){key=fontmap["times"]["normal"];}}return key;},buildDocument=function buildDocument(){outToPages=false;// switches out() to content
objectNumber=2;content_length=0;content=[];offsets=[];additionalObjects=[];// Added for AcroForm
events.publish("buildDocument");// putHeader()
out("%PDF-"+pdfVersion);out("%\xBA\xDF\xAC\xE0");putPages();// Must happen after putPages
// Modifies current object Id
putAdditionalObjects();putResources();// Info
newObject();out("<<");putInfo();out(">>");out("endobj");// Catalog
newObject();out("<<");putCatalog();out(">>");out("endobj");// Cross-ref
var o=content_length,i,p="0000000000";out("xref");out("0 "+(objectNumber+1));out(p+" 65535 f ");for(i=1;i<=objectNumber;i++){var offset=offsets[i];if(typeof offset==="function"){out((p+offsets[i]()).slice(-10)+" 00000 n ");}else{out((p+offsets[i]).slice(-10)+" 00000 n ");}}// Trailer
out("trailer");out("<<");putTrailer();out(">>");out("startxref");out(""+o);out("%%EOF");outToPages=true;return content.join("\n");},getStyle=function getStyle(style){// see path-painting operators in PDF spec
// The default in MrRio's implementation is "S" (stroke), whereas the default in the yWorks implementation
// was "n" (none). Although this has nothing to do with transforms, we should use the API switch here.
var op=apiMode===ApiMode.COMPAT?"S":"n";if(style==="D"){op="S";// stroke
}else if(style==="F"){op="f";// fill
}else if(style==="FD"||style==="DF"){op="B";// both
}else if(style==="f"||style==="f*"||style==="B"||style==="B*"){/*
Allow direct use of these PDF path-painting operators:
- f fill using nonzero winding number rule
- f* fill using even-odd rule
- B fill then stroke with fill using non-zero winding number rule
- B* fill then stroke with fill using even-odd rule
*/op=style;}return op;},// puts the style for the previously drawn path. If a patternKey is provided, the pattern is used to fill
// the path. Use patternMatrix to transform the pattern to rhe right location.
putStyle=function putStyle(style,patternKey,patternData){if(style===null||apiMode===ApiMode.ADVANCED&&style===undefined){return;}style=getStyle(style);// stroking / filling / both the path
if(!patternKey){out(style);return;}if(!patternData){patternData={matrix:unitMatrix};}if(patternData instanceof Matrix){patternData={matrix:patternData};}patternData.key=patternKey;patternData||(patternData=unitMatrix);fillWithPattern(patternData,style);},fillWithPattern=function fillWithPattern(patternData,style){var patternId=patternMap[patternData.key];var pattern=patterns[patternId];if(pattern instanceof API.ShadingPattern){out("q");out(clipRuleFromStyle(style));if(pattern.gState){API.setGState(pattern.gState);}out(patternData.matrix.toString()+" cm");out("/"+patternId+" sh");out("Q");}else if(pattern instanceof API.TilingPattern){// pdf draws patterns starting at the bottom left corner and they are not affected by the global transformation,
// so we must flip them
var matrix=new Matrix(1,0,0,-1,0,pageHeight);if(patternData.matrix){matrix=matrixMult(patternData.matrix||unitMatrix,matrix);// we cannot apply a matrix to the pattern on use so we must abuse the pattern matrix and create new instances
// for each use
patternId=pattern.createClone(patternData.key,patternData.boundingBox,patternData.xStep,patternData.yStep,matrix).id;}out("q");out("/Pattern cs");out("/"+patternId+" scn");if(pattern.gState){API.setGState(pattern.gState);}out(style);out("Q");}},clipRuleFromStyle=function clipRuleFromStyle(style){switch(style){case"f":case"F":return"W n";case"f*":return"W* n";case"B":return"W S";case"B*":return"W* S";// these two are for compatibility reasons (in the past, calling any primitive method with a shading pattern
// and "n"/"S" as style would still fill/fill and stroke the path)
case"S":return"W S";case"n":return"W n";}},getArrayBuffer=function getArrayBuffer(){var data=buildDocument(),len=data.length,ab=new ArrayBuffer(len),u8=new Uint8Array(ab);while(len--){u8[len]=data.charCodeAt(len);}return ab;},getBlob=function getBlob(){return new Blob([getArrayBuffer()],{type:"application/pdf"});},_output=SAFE(function(type,options){if(typeof options==="string"){options={filename:options};}else{options=options||{};options.filename=options.filename||"generated.pdf";}var datauri=(""+type).substr(0,6)==="dataur"?"data:application/pdf;filename="+options.filename+";base64,"+btoa(buildDocument()):0;switch(type){case undefined:return buildDocument();case"save":if((typeof navigator==="undefined"?"undefined":_typeof(navigator))==="object"&&navigator.getUserMedia){if(global.URL===undefined||global.URL.createObjectURL===undefined){return API.output("dataurlnewwindow");}}saveAs(getBlob(),options.filename);if(typeof saveAs.unload==="function"){if(global.setTimeout){setTimeout(saveAs.unload,911);}}break;case"arraybuffer":return getArrayBuffer();case"blob":return getBlob();case"bloburi":case"bloburl":// User is responsible of calling revokeObjectURL
return global.URL&&global.URL.createObjectURL(getBlob())||void 0;case"datauristring":case"dataurlstring":return datauri;case"dataurlnewwindow":var htmlForNewWindow=""+""+""+''+"";var nW=global.open();if(nW!==null){nW.document.write(htmlForNewWindow);}if(nW||typeof safari==="undefined")return nW;/* pass through */case"datauri":case"dataurl":return global.document.location.href=datauri;default:throw new Error('Output type "'+type+'" is not supported.');}// @TODO: Add different output options
}),/**
* Used to see if a supplied hotfix was requested when the pdf instance was created.
* @param {string} hotfixName - The name of the hotfix to check.
* @returns {boolean}
*/hasHotfix=function hasHotfix(hotfixName){return Array.isArray(hotfixes)===true&&hotfixes.indexOf(hotfixName)>-1;};switch(unit){case"pt":k=1;break;case"mm":k=72/25.4000508;break;case"cm":k=72/2.54000508;break;case"in":k=72;break;case"px":if(hasHotfix("px_scaling")==true){k=72/96;}else{k=96/72;}break;case"pc":k=12;break;case"em":k=12;break;case"ex":k=6;break;default:throw"Invalid unit: "+unit;}setCreationDate();setFileId();//---------------------------------------
// Public API
/**
* Object exposing internal API to plugins
* @public
* @ignore
*/API.internal={pdfEscape:pdfEscape,getStyle:getStyle,/**
* Returns {FontObject} describing a particular font.
* @public
* @function
* @param {String} fontName (Optional) Font's family name
* @param {String} fontStyle (Optional) Font's style variation name (Example:"Italic")
* @returns {FontObject}
*/getFont:function getFont(){return fonts[_getFont.apply(API,arguments)];},getFontSize:function getFontSize(){return activeFontSize;},getCharSpace:function getCharSpace(){return activeCharSpace;},getTextColor:function getTextColor(){var colorEncoded=textColor.split(" ");if(colorEncoded.length===2&&colorEncoded[1]==="g"){// convert grayscale value to rgb so that it can be converted to hex for consistency
var floatVal=parseFloat(colorEncoded[0]);colorEncoded=[floatVal,floatVal,floatVal,"r"];}var colorAsHex="#";for(var i=0;i<3;i++){colorAsHex+=("0"+Math.floor(parseFloat(colorEncoded[i])*255).toString(16)).slice(-2);}return colorAsHex;},getLineHeight:function getLineHeight(){return activeFontSize*lineHeightProportion;},write:function write(string1/*, string2, string3, etc */){out(arguments.length===1?string1:Array.prototype.join.call(arguments," "));},getCoordinateString:function getCoordinateString(value){return hpf(scaleByK(value));},getVerticalCoordinateString:function getVerticalCoordinateString(value){return hpf(transformScaleY(value));},collections:{},newObject:newObject,newAdditionalObject:newAdditionalObject,newObjectDeferred:newObjectDeferred,newObjectDeferredBegin:newObjectDeferredBegin,putStream:putStream,events:events,// ratio that you use in multiplication of a given "size" number to arrive to 'point'
// units of measurement.
// scaleFactor is set at initialization of the document and calculated against the stated
// default measurement units for the document.
// If default is "mm", k is the number that will turn number in 'mm' into 'points' number.
// through multiplication.
scaleFactor:k,pageSize:{getWidth:function getWidth(){return pageWidth;},getHeight:function getHeight(){return pageHeight;}},output:function output(type,options){return _output(type,options);},getNumberOfPages:function getNumberOfPages(){return pages.length-1;},pages:pages,out:out,f2:f2,getPageInfo:function getPageInfo(pageNumberOneBased){var objId=(pageNumberOneBased-1)*2+3;return{objId:objId,pageNumber:pageNumberOneBased,pageContext:pagesContext[pageNumberOneBased]};},getCurrentPageInfo:function getCurrentPageInfo(){var objId=(currentPage-1)*2+3;return{objId:objId,pageNumber:currentPage,pageContext:pagesContext[currentPage]};},getPDFVersion:function getPDFVersion(){return pdfVersion;},hasHotfix:hasHotfix//Expose the hasHotfix check so plugins can also check them.
};function advancedAPI(){// prepend global change of basis matrix
// (Now, instead of converting every coordinate to the pdf coordinate system, we apply a matrix
// that does this job for us (however, texts, images and similar objects must be drawn bottom up))
this.saveGraphicsState();out(new Matrix(k,0,0,-k,0,pageHeight*k).toString()+" cm");this.setFontSize(this.getFontSize()/k);apiMode=ApiMode.ADVANCED;}function compatAPI(){this.restoreGraphicsState();apiMode=ApiMode.COMPAT;}/**
* @callback ApiSwitchBody
* @param {jsPDF} pdf
*//**
* For compatibility reasons jsPDF offers two API modes which differ in the way they convert between the the usual
* screen coordinates and the PDF coordinate system.
* - "compat": Offers full compatibility across all plugins but does not allow arbitrary transforms
* - "advanced": Allows arbitrary transforms and more advanced features like pattern fills. Some plugins might
* not support this mode, though.
* Initial mode is "compat".
*
* You can either provide a callback to the body argument, which means that jsPDF will automatically switch back to
* the original API mode afterwards; or you can omit the callback and switch back manually using {@link compatAPI}.
*
* Note, that the calls to {@link saveGraphicsState} and {@link restoreGraphicsState} need to be balanced within the
* callback or between calls of this method and its counterpart {@link compatAPI}. Calls to {@link beginFormObject}
* or {@link beginTilingPattern} need to be closed by their counterparts before switching back to "compat" API mode.
*
* @param {ApiSwitchBody=} body When provided, this callback will be called after the API mode has been switched.
* The API mode will be switched back automatically afterwards.
* @returns {jsPDF}
* @methodOf jsPDF#
* @name advancedAPI
*/API.advancedAPI=function(body){var doSwitch=apiMode===ApiMode.COMPAT;if(doSwitch){advancedAPI.call(this);}if(typeof body!=="function"){return this;}body(this);if(doSwitch){compatAPI.call(this);}return this;};/**
* Switches to "compat" API mode. See {@link advancedAPI} for more details.
*
* @param {ApiSwitchBody=} body When provided, this callback will be called after the API mode has been switched.
* The API mode will be switched back automatically afterwards.
* @return {jsPDF}
* @methodOf jsPDF#
* @name compatApi
*/API.compatAPI=function(body){var doSwitch=apiMode===ApiMode.ADVANCED;if(doSwitch){compatAPI.call(this);}if(typeof body!=="function"){return this;}body(this);if(doSwitch){advancedAPI.call(this);}return this;};/**
* @return {boolean} True iff the current API mode is "advanced". See {@link advancedAPI}.
* @methodOf jsPDF#
* @name isAdvancedAPI
*/API.isAdvancedAPI=function(){return apiMode===ApiMode.ADVANCED;};/**
* Inserts a debug comment into the pdf.
* @param {String} text
* @returns {jsPDF}
* @methodOf jsPDF#
* @name comment
*/API.comment=function(text){out("#"+text);return this;};/**
* An object representing a pdf graphics state.
* @param parameters A parameter object that contains all properties this graphics state wants to set.
* Supported are: opacity, stroke-opacity
* @constructor
*/API.GState=function(parameters){var supported="opacity,stroke-opacity".split(",");for(var p in parameters){if(parameters.hasOwnProperty(p)&&supported.indexOf(p)>=0){this[p]=parameters[p];}}this.id="";// set by addGState()
this.objectNumber=-1;// will be set by putGState()
};API.GState.prototype.equals=function equals(other){var ignore="id,objectNumber,equals";if(!other||_typeof(other)!==_typeof(this))return false;var count=0;for(var p in this){if(ignore.indexOf(p)>=0)continue;if(this.hasOwnProperty(p)&&!other.hasOwnProperty(p))return false;if(this[p]!==other[p])return false;count++;}for(var p in other){if(other.hasOwnProperty(p)&&ignore.indexOf(p)<0)count--;}return count===0;};/**
* Adds a new {@link GState} for later use. See {@link setGState}.
* @param {String} key
* @param {GState} gState
* @function
* @instance
* @returns {jsPDF}
*
* @methodOf jsPDF#
* @name addPage
*/API.addGState=function(key,gState){addGState(key,gState);return this;};/**
* Adds (and transfers the focus to) new page to the PDF document.
* @param {String/Array} format The format of the new page. Can be
a0 - a10
b0 - b10
c0 - c10
c0 - c10
dl
letter
government-letter
legal
junior-legal
ledger
tabloid
credit-card
* Default is "a4". If you want to use your own format just pass instead of one of the above predefined formats the size as an number-array , e.g. [595.28, 841.89]
* @param {string} orientation Orientation of the new page. Possible values are "portrait" or "landscape" (or shortcuts "p" (Default), "l")
* @function
* @instance
* @returns {jsPDF}
*
* @memberOf jsPDF
* @name addPage
*/API.addPage=function(format,orientation){_addPage.apply(this,arguments);return this;};/**
* Adds (and transfers the focus to) new page to the PDF document.
* @function
* @instance
* @returns {jsPDF}
*
* @memberOf jsPDF
* @name setPage
* @param {number} page Switch the active page to the page number specified
* @example
* doc = jsPDF()
* doc.addPage()
* doc.addPage()
* doc.text('I am on page 3', 10, 10)
* doc.setPage(1)
* doc.text('I am on page 1', 10, 10)
*/API.setPage=function(page){_setPage.apply(this,arguments);return this;};/**
* @name insertPage
* @memberOf jsPDF
*
* @function
* @instance
* @param {Object} beforePage
* @returns {jsPDF}
*/API.insertPage=function(beforePage){this.addPage();this.movePage(currentPage,beforePage);return this;};/**
* @name movePage
* @memberOf jsPDF
* @function
* @instance
* @param {Object} targetPage
* @param {Object} beforePage
* @returns {jsPDF}
*/API.movePage=function(targetPage,beforePage){var tmpPagesContext,tmpPagedim,tmpPages,i;if(targetPage>beforePage){tmpPages=pages[targetPage];tmpPagedim=pagedim[targetPage];tmpPagesContext=pagesContext[targetPage];for(i=targetPage;i>beforePage;i--){pages[i]=pages[i-1];pagedim[i]=pagedim[i-1];pagesContext[i]=pagesContext[i-1];}pages[beforePage]=tmpPages;pagedim[beforePage]=tmpPagedim;pagesContext[beforePage]=tmpPagesContext;this.setPage(beforePage);}else if(targetPage} coords Either [x1, y1, x2, y2] for "axial" type describing the two interpolation points
* or [x1, y1, r, x2, y2, r2] for "radial" describing inner and the outer circle.
* @param {Array
* @name annotations
* @module
*//*
Destination Magnification Factors
See PDF 1.3 Page 386 for meanings and options
[supported]
XYZ (options; left top zoom)
Fit (no options)
FitH (options: top)
FitV (options: left)
[not supported]
FitR
FitB
FitBH
FitBV
*/(function(jsPDFAPI){var annotationPlugin={/**
* An array of arrays, indexed by pageNumber.
*/annotations:[],f2:function f2(number){return number.toFixed(2);},notEmpty:function notEmpty(obj){if(typeof obj!="undefined"){if(obj!=""){return true;}}}};jsPDF.API.annotationPlugin=annotationPlugin;jsPDF.API.events.push(["addPage",function(info){this.annotationPlugin.annotations[info.pageNumber]=[];}]);jsPDFAPI.events.push(["putPage",function(info){//TODO store annotations in pageContext so reorder/remove will not affect them.
var pageAnnos=this.annotationPlugin.annotations[info.pageNumber];var found=false;for(var a=0;a>";objText.content=line;var parent=objText.objId+" 0 R";var popoff=30;var rect="/Rect ["+f2((anno.bounds.x+popoff)*k)+" "+f2(pageHeight-(anno.bounds.y+anno.bounds.h)*k)+" "+f2((anno.bounds.x+anno.bounds.w+popoff)*k)+" "+f2((pageHeight-anno.bounds.y)*k)+"] ";//var rect2 = "/Rect [" + f2(anno.bounds.x * k) + " " + f2((pageHeight - anno.bounds.y) * k) + " " + f2(anno.bounds.x + anno.bounds.w * k) + " " + f2(pageHeight - (anno.bounds.y + anno.bounds.h) * k) + "] ";
line="<>";objPopup.content=line;this.internal.write(objText.objId,"0 R",objPopup.objId,"0 R");break;case"freetext":var rect="/Rect ["+f2(anno.bounds.x*k)+" "+f2((pageHeight-anno.bounds.y)*k)+" "+f2(anno.bounds.x+anno.bounds.w*k)+" "+f2(pageHeight-(anno.bounds.y+anno.bounds.h)*k)+"] ";var color=anno.color||"#000000";line="<>";this.internal.write(line);break;case"link":if(anno.options.name){var loc=this.annotations._nameMap[anno.options.name];anno.options.pageNumber=loc.page;anno.options.top=loc.y;}else{if(!anno.options.top){anno.options.top=0;}}var rect="/Rect ["+f2(anno.x*k)+" "+f2((pageHeight-anno.y)*k)+" "+f2((anno.x+anno.w)*k)+" "+f2((pageHeight-(anno.y+anno.h))*k)+"] ";var line="";if(anno.options.url){line="<>";}else if(anno.options.pageNumber){// first page is 0
var info=this.internal.getPageInfo(anno.options.pageNumber);line="<>";this.internal.write(line);}break;}}this.internal.write("]");}]);/**
* @name createAnnotation
* @function
* @param {Object} options
*/jsPDFAPI.createAnnotation=function(options){switch(options.type){case"link":this.link(options.bounds.x,options.bounds.y,options.bounds.w,options.bounds.h,options);break;case"text":case"freetext":this.annotationPlugin.annotations[this.internal.getCurrentPageInfo().pageNumber].push(options);break;}};/**
* Create a link
*
* valid options
*
pageNumber or url [required]
*
If pageNumber is specified, top and zoom may also be specified
The transform() method replaces the current transformation matrix. It multiplies the current transformation matrix with the matrix described by:
a c e
b d f
0 0 1
In other words, the transform() method lets you scale, rotate, move, and skew the current context.
*/transform:function transform(a,b,c,d,e,f){this.ctx._transform=this._matrix_multiply(this.ctx._transform,[a,b,c,d,e,f]);},/**
* Resets the current transform to the identity matrix. Then runs transform()
*
* @name setTransform
* @function
* @param a {Number} Horizontal scaling
* @param b {Number} Horizontal skewing
* @param c {Number} Vertical skewing
* @param d {Number} Vertical scaling
* @param e {Number} Horizontal moving
* @param f {Number} Vertical moving
* @description Each object on the canvas has a current transformation matrix.
The setTransform() method resets the current transform to the identity matrix, and then runs transform() with the same arguments.
In other words, the setTransform() method lets you scale, rotate, move, and skew the current context.
*/setTransform:function setTransform(a,b,c,d,e,f){this.ctx._transform=[a,b,c,d,e,f];},/**
* @name _getTransform
* @function
* @private
* @ignore
*/_getTransform:function _getTransform(){return this.ctx._transform;},lastBreak:0,// Y Position of page breaks.
pageBreaks:[],/**
* Should only be used if pageWrapYEnabled is true
*
* @name _page
* @function
* @private
* @ignore
* @returns One-based Page Number
*/_page:function _page(y){if(this.pageWrapYEnabled){this.lastBreak=0;var manualBreaks=0;var autoBreaks=0;for(var i=0;i=this.pageBreaks[i]){manualBreaks++;if(this.lastBreak===0){autoBreaks++;}var spaceBetweenLastBreak=this.pageBreaks[i]-this.lastBreak;this.lastBreak=this.pageBreaks[i];var pagesSinceLastBreak=Math.floor(spaceBetweenLastBreak/this.pageWrapY);autoBreaks+=pagesSinceLastBreak;}}if(this.lastBreak===0){var pagesSinceLastBreak=Math.floor(y/this.pageWrapY)+1;autoBreaks+=pagesSinceLastBreak;}return autoBreaks+manualBreaks;}else{return this.pdf.internal.getCurrentPageInfo().pageNumber;}},_gotoPage:function _gotoPage(pageOneBased){// This is a stub to be overriden if needed
},/**
* Draws an image, canvas, or video onto the canvas
*
* @function
* @param img {} Specifies the image, canvas, or video element to use
* @param sx {Number} Optional. The x coordinate where to start clipping
* @param sy {Number} Optional. The y coordinate where to start clipping
* @param swidth {Number} Optional. The width of the clipped image
* @param sheight {Number} Optional. The height of the clipped image
* @param x {Number} The x coordinate where to place the image on the canvas
* @param y {Number} The y coordinate where to place the image on the canvas
* @param width {Number} Optional. The width of the image to use (stretch or reduce the image)
* @param height {Number} Optional. The height of the image to use (stretch or reduce the image)
*
*/drawImage:function drawImage(img,x,y,w,h,x2,y2,w2,h2){if(x2!==undefined){x=x2;y=y2;w=w2;h=h2;}x=this._wrapX(x);y=this._wrapY(y);var xRect=this._matrix_map_rect(this.ctx._transform,{x:x,y:y,w:w,h:h});var xRect2=this._matrix_map_rect(this.ctx._transform,{x:x2,y:y2,w:w2,h:h2});// TODO implement source clipping and image scaling
var format;var rx=/data:image\/(\w+).*/i;var m=rx.exec(img);if(m!=null){format=m[1];}else{// format = "jpeg";
format="png";}this.pdf.addImage(img,format,xRect.x,xRect.y,xRect.w,xRect.h);},/**
* Multiply the first matrix by the second
*
* @name matrix_multiply
* @function
* @param m1
* @param m2
* @returns {Array}
* @private
* @ignore
*/_matrix_multiply:function _matrix_multiply(m2,m1){var sx=m1[0];var shy=m1[1];var shx=m1[2];var sy=m1[3];var tx=m1[4];var ty=m1[5];var t0=sx*m2[0]+shy*m2[2];var t2=shx*m2[0]+sy*m2[2];var t4=tx*m2[0]+ty*m2[2]+m2[4];shy=sx*m2[1]+shy*m2[3];sy=shx*m2[1]+sy*m2[3];ty=tx*m2[1]+ty*m2[3]+m2[5];sx=t0;shx=t2;tx=t4;return[sx,shy,shx,sy,tx,ty];},/**
* @name _matrix_rotation
* @function
* @private
* @ignore
*/_matrix_rotation:function _matrix_rotation(m){return Math.atan2(m[2],m[0]);},/**
* @name _matrix_decompose
* @function
* @private
* @ignore
*/_matrix_decompose:function _matrix_decompose(matrix){var a=matrix[0];var b=matrix[1];var c=matrix[2];var d=matrix[3];var scaleX=Math.sqrt(a*a+b*b);a/=scaleX;b/=scaleX;var shear=a*c+b*d;c-=a*shear;d-=b*shear;var scaleY=Math.sqrt(c*c+d*d);c/=scaleY;d/=scaleY;shear/=scaleY;if(a*d>'); // /S /Luminosity will need to define color space
obj2.push('>>'); // add mask to page resources
var gsName = 'MASK' + obj2.objId;
this.pdf.internal.addGraphicsState(gsName, obj2.objId);
var instruction = '/' + gsName + ' gs'; // add mask to page, group, or stream
lines.splice(0, 0, 'q');
lines.splice(1, 0, instruction);
lines.push('Q');
globalObj.outIntercept = obj;
break;
default:
var dictionaryEntry = '/' + this.pdf.internal.blendModeMap[this.ctx.globalCompositeOperation.toUpperCase()];
if (dictionaryEntry) {
this.pdf.internal.out(dictionaryEntry + ' gs');
}
break;
}
}
*/var alpha=this.ctx.globalAlpha;if(this.ctx._fillOpacity<1){// TODO combine this with global opacity
alpha=this.ctx._fillOpacity;}//TODO check for an opacity graphics state that was already created
//TODO do not set opacity if current value is already active
/*
if (v2Support) {
var objOpac = this.pdf.internal.newObject2();
objOpac.push('<>');
var gsName = 'GS_O_' + objOpac.objId;
this.pdf.internal.addGraphicsState(gsName, objOpac.objId);
this.pdf.internal.out('/' + gsName + ' gs');
}
*/var xPath=this.path;for(var i=0;i0){for(iii;iii>0;iii--){if(moves[iii-1].close!==true&&moves[iii-1].begin!==true){moves[iii-1].deltas.push(delta);moves[iii-1].abs.push(pt);break;}}}break;case"bct":var delta=[pt.x1-xPath[i-1].x,pt.y1-xPath[i-1].y,pt.x2-xPath[i-1].x,pt.y2-xPath[i-1].y,pt.x-xPath[i-1].x,pt.y-xPath[i-1].y];moves[moves.length-1].deltas.push(delta);break;case"qct":// convert to bezier
var x1=xPath[i-1].x+2.0/3.0*(pt.x1-xPath[i-1].x);var y1=xPath[i-1].y+2.0/3.0*(pt.y1-xPath[i-1].y);var x2=pt.x+2.0/3.0*(pt.x1-pt.x);var y2=pt.y+2.0/3.0*(pt.y1-pt.y);var x3=pt.x;var y3=pt.y;var delta=[x1-xPath[i-1].x,y1-xPath[i-1].y,x2-xPath[i-1].x,y2-xPath[i-1].y,x3-xPath[i-1].x,y3-xPath[i-1].y];moves[moves.length-1].deltas.push(delta);break;case"arc":moves.push({deltas:[],abs:[]});moves[moves.length-1].arc=true;if(Array.isArray(moves[moves.length-1].abs)){moves[moves.length-1].abs.push(pt);}break;}}var style;if(!isClip){if(isStroke){style="S";}else{style="f";}}else{style=null;}for(var i=0;i 0) {
// lines.push('Q');
// }
},/*
_pushMask: function () {
var v2Support = typeof this.pdf.internal.newObject2 === 'function';
if (!v2Support) {
console.log('jsPDF v2 not enabled')
return;
}
// define a mask stream
var obj = this.pdf.internal.newStreamObject();
// define a mask state
var obj2 = this.pdf.internal.newObject2();
obj2.push('<>'); // /S /Luminosity will need to define color space
obj2.push('>>');
// add mask to page resources
var gsName = 'MASK' + obj2.objId;
this.pdf.internal.addGraphicsState(gsName, obj2.objId);
var instruction = '/' + gsName + ' gs';
this.pdf.internal.out(instruction);
},
*/_getBaseline:function _getBaseline(y){var height=parseInt(this.pdf.internal.getFontSize()/this.pdf.internal.scaleFactor);// TODO Get descent from font descriptor
var descent=height*0.25;switch(this.ctx.textBaseline){case"bottom":return y-descent;case"top":return y+height;case"hanging":return y+height-descent;case"middle":return y+height/2-descent;case"ideographic":// TODO not implemented
return y;case"alphabetic":default:return y;}},createLinearGradient:function createLinearGradient(){var canvasGradient=function canvasGradient(){};canvasGradient.colorStops=[];canvasGradient.addColorStop=function(offset,color){this.colorStops.push([offset,color]);};canvasGradient.getColor=function(){if(this.colorStops.length===0){return"#000000";}return this.colorStops[0][1];};canvasGradient.isCanvasGradient=true;return canvasGradient;},createPattern:function createPattern(){return this.createLinearGradient();},createRadialGradient:function createRadialGradient(){return this.createLinearGradient();}};var c2d=jsPDFAPI.context2d;/**
* Sets or returns the color, gradient, or pattern used to fill the drawing
*
* @name fillStyle
* @default #000000
* @property {(color|gradient|pattern)} value The color of the drawing. Default value is #000000
* A gradient object (linear or radial) used to fill the drawing (not supported by context2d)
* A pattern object to use to fill the drawing (not supported by context2d)
*/Object.defineProperty(c2d,"fillStyle",{set:function set(value){this._setFillStyle(value);},get:function get(){return this.ctx.fillStyle;}});/**
* Sets or returns the color, gradient, or pattern used for strokes
*
* @name strokeStyle
* @default #000000
* @property {color} color A CSS color value that indicates the stroke color of the drawing. Default value is #000000 (not supported by context2d)
* @property {gradient} gradient A gradient object (linear or radial) used to create a gradient stroke (not supported by context2d)
* @property {pattern} pattern A pattern object used to create a pattern stroke (not supported by context2d)
*/Object.defineProperty(c2d,"strokeStyle",{set:function set(value){this._setStrokeStyle(value);},get:function get(){return this.ctx.strokeStyle;}});//Line Styles
/**
* Sets or returns the style of the end caps for a line
*
* @name lineCap
* @default butt
* @property {(butt|round|square)} lineCap butt A flat edge is added to each end of the line
* round A rounded end cap is added to each end of the line
* square A square end cap is added to each end of the line
*/Object.defineProperty(c2d,"lineCap",{set:function set(val){this._setLineCap(val);},get:function get(){return this.ctx.lineCap;}});/**
* Sets or returns the current line width
*
* @name lineWidth
* @default 1
* @property {number} lineWidth The current line width, in pixels
*/Object.defineProperty(c2d,"lineWidth",{set:function set(value){this._setLineWidth(value);},get:function get(){return this.ctx.lineWidth;}});/**
* Sets or returns the type of corner created, when two lines meet
*/Object.defineProperty(c2d,"lineJoin",{set:function set(val){this._setLineJoin(val);},get:function get(){return this.ctx.lineJoin;}});/**
* Sets or returns the maximum miter length
*/Object.defineProperty(c2d,"miterLimit",{set:function set(val){this.ctx.miterLimit=val;},get:function get(){return this.ctx.miterLimit;}});Object.defineProperty(c2d,"textBaseline",{set:function set(value){this._setTextBaseline(value);},get:function get(){return this._getTextBaseline();}});Object.defineProperty(c2d,"textAlign",{set:function set(value){this._setTextAlign(value);},get:function get(){return this._getTextAlign();}});Object.defineProperty(c2d,"font",{set:function set(value){this._setFont(value);},get:function get(){return this.ctx.font;}});Object.defineProperty(c2d,"globalCompositeOperation",{set:function set(value){this.ctx.globalCompositeOperation=value;},get:function get(){return this.ctx.globalCompositeOperation;}});Object.defineProperty(c2d,"globalAlpha",{set:function set(value){this.ctx.globalAlpha=value;},get:function get(){return this.ctx.globalAlpha;}});Object.defineProperty(c2d,"canvas",{get:function get(){return{parentNode:false,style:false};}});// Not HTML API
Object.defineProperty(c2d,"ignoreClearRect",{set:function set(value){this.ctx.ignoreClearRect=value;},get:function get(){return this.ctx.ignoreClearRect;}});// End Not HTML API
c2d.internal={};c2d.internal.rxRgb=/rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/;c2d.internal.rxRgba=/rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d\.]+)\s*\)/;c2d.internal.rxTransparent=/transparent|rgba\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*0+\s*\)/;// http://hansmuller-flex.blogspot.com/2011/10/more-about-approximating-circular-arcs.html
c2d.internal.arc=function(c2d,xc,yc,r,a1,a2,counterclockwise,style){var k=this.pdf.internal.scaleFactor;var pageHeight=this.pdf.internal.pageSize.getHeight();var f2=this.pdf.internal.f2;var a1r=a1*(Math.PI/180);var a2r=a2*(Math.PI/180);var curves=this.createArc(r,a1r,a2r,counterclockwise);for(var i=0;itwoPI){startAngleN=startAngleN%twoPI;}var endAngleN=endAngle;if(endAngleNtwoPI){endAngleN=endAngleN%twoPI;}// Compute the sequence of arc curves, up to PI/2 at a time.
// Total arc angle is less than 2PI.
var curves=[];var piOverTwo=Math.PI/2.0;//var sgn = (startAngle < endAngle) ? +1 : -1; // clockwise or counterclockwise
var sgn=anticlockwise?-1:+1;var a1=startAngle;for(var totalAngle=Math.min(twoPI,Math.abs(endAngleN-startAngleN));totalAngle>EPSILON;){var a2=a1+sgn*Math.min(totalAngle,piOverTwo);curves.push(this.createSmallArc(radius,a1,a2));totalAngle-=Math.abs(a2-a1);a1=a2;}return curves;};c2d.internal.getCurrentPage=function(){return this.pdf.internal.pages[this.pdf.internal.getCurrentPageInfo().pageNumber];};/**
* Cubic bezier approximation of a circular arc centered at the origin, from (radians) a1 to a2, where a2-a1 < pi/2. The arc's radius is r.
*
* Returns an object with four points, where x1,y1 and x4,y4 are the arc's end points and x2,y2 and x3,y3 are the cubic bezier's control points.
*
* This algorithm is based on the approach described in: A. Riškus, "Approximation of a Cubic Bezier Curve by Circular Arcs and Vice Versa," Information Technology and Control, 35(4), 2006 pp. 371-378.
*/c2d.internal.createSmallArc=function(r,a1,a2){// Compute all four points for an arc that subtends the same total angle
// but is centered on the X-axis
var a=(a2-a1)/2.0;var x4=r*Math.cos(a);var y4=r*Math.sin(a);var x1=x4;var y1=-y4;var q1=x1*x1+y1*y1;var q2=q1+x1*x4+y1*y4;var k2=4/3*(Math.sqrt(2*q1*q2)-q2)/(x1*y4-y1*x4);var x2=x1-k2*y1;var y2=y1+k2*x1;var x3=x2;var y3=-y2;// Find the arc points' actual locations by computing x1,y1 and x4,y4
// and rotating the control points by a + a1
var ar=a+a1;var cos_ar=Math.cos(ar);var sin_ar=Math.sin(ar);return{x1:r*Math.cos(a1),y1:r*Math.sin(a1),x2:x2*cos_ar-y2*sin_ar,y2:x2*sin_ar+y2*cos_ar,x3:x3*cos_ar-y3*sin_ar,y3:x3*sin_ar+y3*cos_ar,x4:r*Math.cos(a2),y4:r*Math.sin(a2)};};/**
*
* @function
* @constructor
*/function context(){this._isStrokeTransparent=false;this._strokeOpacity=1;this.strokeStyle="#000000";this.fillStyle="#000000";this._isFillTransparent=false;this._fillOpacity=1;this.font="12pt times";this.textBaseline="alphabetic";// top,bottom,middle,ideographic,alphabetic,hanging
this.textAlign="left";this.lineWidth=1;this.lineJoin="miter";// round, bevel, miter
this.lineCap="butt";// butt, round, square
this._transform=[1,0,0,1,0,0];// sx, shy, shx, sy, tx, ty
this.globalCompositeOperation="normal";this.globalAlpha=1.0;this._clip_path=[];this.currentPoint={x:0,y:0};// TODO miter limit //default 10
// Not HTML API
this.ignoreClearRect=false;this.copy=function(ctx){this._isStrokeTransparent=ctx._isStrokeTransparent;this._strokeOpacity=ctx._strokeOpacity;this.strokeStyle=ctx.strokeStyle;this._isFillTransparent=ctx._isFillTransparent;this._fillOpacity=ctx._fillOpacity;this.fillStyle=ctx.fillStyle;this.font=ctx.font;this.lineWidth=ctx.lineWidth;this.lineJoin=ctx.lineJoin;this.lineCap=ctx.lineCap;this.textBaseline=ctx.textBaseline;this.textAlign=ctx.textAlign;this._fontSize=ctx._fontSize;this._transform=ctx._transform.slice(0);this.globalCompositeOperation=ctx.globalCompositeOperation;this.globalAlpha=ctx.globalAlpha;this._clip_path=ctx._clip_path.slice(0);//TODO deep copy?
this.currentPoint=ctx.currentPoint;// Not HTML API
this.ignoreClearRect=ctx.ignoreClearRect;};}return this;})(jsPDF.API,typeof self!=="undefined"&&self||typeof window!=="undefined"&&window||typeof global!=="undefined"&&global||Function('return typeof this === "object" && this.content')()||Function("return this")());/**
* Copyright (c) 2018 Erik Koopmans
* Released under the MIT License.
*
* Licensed under the MIT License.
* http://opensource.org/licenses/mit-license
*//**
* jsPDF html PlugIn
*
* @name html
* @module
*/(function(jsPDFAPI,global){/**
* Determine the type of a variable/object.
*
* @private
* @ignore
*/var objType=function objType(obj){var type=_typeof(obj);if(type==="undefined")return"undefined";else if(type==="string"||obj instanceof String)return"string";else if(type==="number"||obj instanceof Number)return"number";else if(type==="function"||obj instanceof Function)return"function";else if(!!obj&&obj.constructor===Array)return"array";else if(obj&&obj.nodeType===1)return"element";else if(type==="object")return"object";else return"unknown";};/**
* Create an HTML element with optional className, innerHTML, and style.
*
* @private
* @ignore
*/var createElement=function createElement(tagName,opt){var el=document.createElement(tagName);if(opt.className)el.className=opt.className;if(opt.innerHTML){el.innerHTML=opt.innerHTML;var scripts=el.getElementsByTagName("script");for(var i=scripts.length;i-->0;null){scripts[i].parentNode.removeChild(scripts[i]);}}for(var key in opt.style){el.style[key]=opt.style[key];}return el;};/**
* Deep-clone a node and preserve contents/properties.
*
* @private
* @ignore
*/var cloneNode=function cloneNode(node,javascriptEnabled){// Recursively clone the node.
var clone=node.nodeType===3?document.createTextNode(node.nodeValue):node.cloneNode(false);for(var child=node.firstChild;child;child=child.nextSibling){if(javascriptEnabled===true||child.nodeType!==1||child.nodeName!=="SCRIPT"){clone.appendChild(cloneNode(child,javascriptEnabled));}}if(node.nodeType===1){// Preserve contents/properties of special nodes.
if(node.nodeName==="CANVAS"){clone.width=node.width;clone.height=node.height;clone.getContext("2d").drawImage(node,0,0);}else if(node.nodeName==="TEXTAREA"||node.nodeName==="SELECT"){clone.value=node.value;}// Preserve the node's scroll position when it loads.
clone.addEventListener("load",function(){clone.scrollTop=node.scrollTop;clone.scrollLeft=node.scrollLeft;},true);}// Return the cloned node.
return clone;};/* ----- CONSTRUCTOR ----- */var Worker=function Worker(opt){// Create the root parent for the proto chain, and the starting Worker.
var root=Object.assign(Worker.convert(Promise.resolve()),JSON.parse(JSON.stringify(Worker.template)));var self=Worker.convert(Promise.resolve(),root);// Set progress, optional settings, and return.
self=self.setProgress(1,Worker,1,[Worker]);self=self.set(opt);return self;};// Boilerplate for subclassing Promise.
Worker.prototype=Object.create(Promise.prototype);Worker.prototype.constructor=Worker;// Converts/casts promises into Workers.
Worker.convert=function convert(promise,inherit){// Uses prototypal inheritance to receive changes made to ancestors' properties.
promise.__proto__=inherit||Worker.prototype;return promise;};Worker.template={prop:{src:null,container:null,overlay:null,canvas:null,img:null,pdf:null,pageSize:null,callback:function callback(){}},progress:{val:0,state:null,n:0,stack:[]},opt:{filename:"file.pdf",margin:[0,0,0,0],enableLinks:true,html2canvas:{},jsPDF:{}}};/* ----- FROM / TO ----- */Worker.prototype.from=function from(src,type){function getType(src){switch(objType(src)){case"string":return"string";case"element":return src.nodeName.toLowerCase==="canvas"?"canvas":"element";default:return"unknown";}}return this.then(function from_main(){type=type||getType(src);switch(type){case"string":return this.set({src:createElement("div",{innerHTML:src})});case"element":return this.set({src:src});case"canvas":return this.set({canvas:src});case"img":return this.set({img:src});default:return this.error("Unknown source type.");}});};Worker.prototype.to=function to(target){// Route the 'to' request to the appropriate method.
switch(target){case"container":return this.toContainer();case"canvas":return this.toCanvas();case"img":return this.toImg();case"pdf":return this.toPdf();default:return this.error("Invalid target.");}};Worker.prototype.toContainer=function toContainer(){// Set up function prerequisites.
var prereqs=[function checkSrc(){return this.prop.src||this.error("Cannot duplicate - no source HTML.");},function checkPageSize(){return this.prop.pageSize||this.setPageSize();}];return this.thenList(prereqs).then(function toContainer_main(){// Define the CSS styles for the container and its overlay parent.
var overlayCSS={position:"fixed",overflow:"hidden",zIndex:1000,left:"-100000px",right:0,bottom:0,top:0};var containerCSS={position:"relative",display:"inline-block",width:Math.max(this.prop.src.clientWidth,this.prop.src.scrollWidth,this.prop.src.offsetWidth)+"px",left:0,right:0,top:0,margin:"auto",backgroundColor:"white"};// Set the overlay to hidden (could be changed in the future to provide a print preview).
var source=cloneNode(this.prop.src,this.opt.html2canvas.javascriptEnabled);if(source.tagName==="BODY"){containerCSS.height=Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight)+"px";}this.prop.overlay=createElement("div",{className:"html2pdf__overlay",style:overlayCSS});this.prop.container=createElement("div",{className:"html2pdf__container",style:containerCSS});this.prop.container.appendChild(source);this.prop.container.firstChild.appendChild(createElement("div",{style:{clear:"both",border:"0 none transparent",margin:0,padding:0,height:0}}));this.prop.container.style.float="none";this.prop.overlay.appendChild(this.prop.container);document.body.appendChild(this.prop.overlay);this.prop.container.firstChild.style.position="relative";this.prop.container.height=Math.max(this.prop.container.firstChild.clientHeight,this.prop.container.firstChild.scrollHeight,this.prop.container.firstChild.offsetHeight)+"px";});};Worker.prototype.toCanvas=function toCanvas(){// Set up function prerequisites.
var prereqs=[function checkContainer(){return document.body.contains(this.prop.container)||this.toContainer();}];// Fulfill prereqs then create the canvas.
return this.thenList(prereqs).then(function toCanvas_main(){// Handle old-fashioned 'onrendered' argument.
var options=Object.assign({},this.opt.html2canvas);delete options.onrendered;if(!this.isHtml2CanvasLoaded()){return;}return html2canvas(this.prop.container,options);}).then(function toCanvas_post(canvas){// Handle old-fashioned 'onrendered' argument.
var onRendered=this.opt.html2canvas.onrendered||function(){};onRendered(canvas);this.prop.canvas=canvas;document.body.removeChild(this.prop.overlay);});};Worker.prototype.toContext2d=function toContext2d(){// Set up function prerequisites.
var prereqs=[function checkContainer(){return document.body.contains(this.prop.container)||this.toContainer();}];// Fulfill prereqs then create the canvas.
return this.thenList(prereqs).then(function toContext2d_main(){// Handle old-fashioned 'onrendered' argument.
var pdf=this.opt.jsPDF;var options=Object.assign({async:true,allowTaint:true,backgroundColor:"#ffffff",imageTimeout:15000,logging:true,proxy:null,removeContainer:true,foreignObjectRendering:false,useCORS:false},this.opt.html2canvas);delete options.onrendered;options.windowHeight=options.windowHeight||0;options.windowHeight=options.windowHeight==0?Math.max(this.prop.container.clientHeight,this.prop.container.scrollHeight,this.prop.container.offsetHeight):options.windowHeight;if(!this.isHtml2CanvasLoaded()){return;}return html2canvas(this.prop.container,options);}).then(function toContext2d_post(canvas){// Handle old-fashioned 'onrendered' argument.
var onRendered=this.opt.html2canvas.onrendered||function(){};onRendered(canvas);this.prop.canvas=canvas;document.body.removeChild(this.prop.overlay);});};Worker.prototype.toImg=function toImg(){// Set up function prerequisites.
var prereqs=[function checkCanvas(){return this.prop.canvas||this.toCanvas();}];// Fulfill prereqs then create the image.
return this.thenList(prereqs).then(function toImg_main(){var imgData=this.prop.canvas.toDataURL("image/"+this.opt.image.type,this.opt.image.quality);this.prop.img=document.createElement("img");this.prop.img.src=imgData;});};Worker.prototype.toPdf=function toPdf(){// Set up function prerequisites.
var prereqs=[function checkContext2d(){return this.toContext2d();}//function checkCanvas() { return this.prop.canvas || this.toCanvas(); }
];// Fulfill prereqs then create the image.
return this.thenList(prereqs).then(function toPdf_main(){// Create local copies of frequently used properties.
this.prop.pdf=this.prop.pdf||this.opt.jsPDF;});};/* ----- OUTPUT / SAVE ----- */Worker.prototype.output=function output(type,options,src){// Redirect requests to the correct function (outputPdf / outputImg).
src=src||"pdf";if(src.toLowerCase()==="img"||src.toLowerCase()==="image"){return this.outputImg(type,options);}else{return this.outputPdf(type,options);}};Worker.prototype.outputPdf=function outputPdf(type,options){// Set up function prerequisites.
var prereqs=[function checkPdf(){return this.prop.pdf||this.toPdf();}];// Fulfill prereqs then perform the appropriate output.
return this.thenList(prereqs).then(function outputPdf_main(){/* Currently implemented output types:
* https://rawgit.com/MrRio/jsPDF/master/docs/jspdf.js.html#line992
* save(options), arraybuffer, blob, bloburi/bloburl,
* datauristring/dataurlstring, dataurlnewwindow, datauri/dataurl
*/return this.prop.pdf.output(type,options);});};Worker.prototype.outputImg=function outputImg(type,options){// Set up function prerequisites.
var prereqs=[function checkImg(){return this.prop.img||this.toImg();}];// Fulfill prereqs then perform the appropriate output.
return this.thenList(prereqs).then(function outputImg_main(){switch(type){case undefined:case"img":return this.prop.img;case"datauristring":case"dataurlstring":return this.prop.img.src;case"datauri":case"dataurl":return document.location.href=this.prop.img.src;default:throw'Image output type "'+type+'" is not supported.';}});};Worker.prototype.isHtml2CanvasLoaded=function(){var result=typeof global.html2canvas!=="undefined";if(!result){console.error("html2canvas not loaded.");}return result;};Worker.prototype.save=function save(filename){// Set up function prerequisites.
var prereqs=[function checkPdf(){return this.prop.pdf||this.toPdf();}];if(!this.isHtml2CanvasLoaded()){return;}// Fulfill prereqs, update the filename (if provided), and save the PDF.
return this.thenList(prereqs).set(filename?{filename:filename}:null).then(function save_main(){this.prop.pdf.save(this.opt.filename);});};Worker.prototype.doCallback=function doCallback(filename){// Set up function prerequisites.
var prereqs=[function checkPdf(){return this.prop.pdf||this.toPdf();}];if(!this.isHtml2CanvasLoaded()){return;}// Fulfill prereqs, update the filename (if provided), and save the PDF.
return this.thenList(prereqs).then(function doCallback_main(){this.prop.callback(this.prop.pdf);});};/* ----- SET / GET ----- */Worker.prototype.set=function set(opt){// TODO: Implement ordered pairs?
// Silently ignore invalid or empty input.
if(objType(opt)!=="object"){return this;}// Build an array of setter functions to queue.
var fns=Object.keys(opt||{}).map(function(key){if(key in Worker.template.prop){// Set pre-defined properties.
return function set_prop(){this.prop[key]=opt[key];};}else{switch(key){case"margin":return this.setMargin.bind(this,opt.margin);case"jsPDF":return function set_jsPDF(){this.opt.jsPDF=opt.jsPDF;return this.setPageSize();};case"pageSize":return this.setPageSize.bind(this,opt.pageSize);default:// Set any other properties in opt.
return function set_opt(){this.opt[key]=opt[key];};}}},this);// Set properties within the promise chain.
return this.then(function set_main(){return this.thenList(fns);});};Worker.prototype.get=function get(key,cbk){return this.then(function get_main(){// Fetch the requested property, either as a predefined prop or in opt.
var val=key in Worker.template.prop?this.prop[key]:this.opt[key];return cbk?cbk(val):val;});};Worker.prototype.setMargin=function setMargin(margin){return this.then(function setMargin_main(){// Parse the margin property.
switch(objType(margin)){case"number":margin=[margin,margin,margin,margin];case"array":if(margin.length===2){margin=[margin[0],margin[1],margin[0],margin[1]];}if(margin.length===4){break;}default:return this.error("Invalid margin array.");}// Set the margin property, then update pageSize.
this.opt.margin=margin;}).then(this.setPageSize);};Worker.prototype.setPageSize=function setPageSize(pageSize){function toPx(val,k){return Math.floor(val*k/72*96);}return this.then(function setPageSize_main(){// Retrieve page-size based on jsPDF settings, if not explicitly provided.
pageSize=pageSize||jsPDF.getPageSize(this.opt.jsPDF);// Add 'inner' field if not present.
if(!pageSize.hasOwnProperty("inner")){pageSize.inner={width:pageSize.width-this.opt.margin[1]-this.opt.margin[3],height:pageSize.height-this.opt.margin[0]-this.opt.margin[2]};pageSize.inner.px={width:toPx(pageSize.inner.width,pageSize.k),height:toPx(pageSize.inner.height,pageSize.k)};pageSize.inner.ratio=pageSize.inner.height/pageSize.inner.width;}// Attach pageSize to this.
this.prop.pageSize=pageSize;});};Worker.prototype.setProgress=function setProgress(val,state,n,stack){// Immediately update all progress values.
if(val!=null)this.progress.val=val;if(state!=null)this.progress.state=state;if(n!=null)this.progress.n=n;if(stack!=null)this.progress.stack=stack;this.progress.ratio=this.progress.val/this.progress.state;// Return this for command chaining.
return this;};Worker.prototype.updateProgress=function updateProgress(val,state,n,stack){// Immediately update all progress values, using setProgress.
return this.setProgress(val?this.progress.val+val:null,state?state:null,n?this.progress.n+n:null,stack?this.progress.stack.concat(stack):null);};/* ----- PROMISE MAPPING ----- */Worker.prototype.then=function then(onFulfilled,onRejected){// Wrap `this` for encapsulation.
var self=this;return this.thenCore(onFulfilled,onRejected,function then_main(onFulfilled,onRejected){// Update progress while queuing, calling, and resolving `then`.
self.updateProgress(null,null,1,[onFulfilled]);return Promise.prototype.then.call(this,function then_pre(val){self.updateProgress(null,onFulfilled);return val;}).then(onFulfilled,onRejected).then(function then_post(val){self.updateProgress(1);return val;});});};Worker.prototype.thenCore=function thenCore(onFulfilled,onRejected,thenBase){// Handle optional thenBase parameter.
thenBase=thenBase||Promise.prototype.then;// Wrap `this` for encapsulation and bind it to the promise handlers.
var self=this;if(onFulfilled){onFulfilled=onFulfilled.bind(self);}if(onRejected){onRejected=onRejected.bind(self);}// Cast self into a Promise to avoid polyfills recursively defining `then`.
var isNative=Promise.toString().indexOf("[native code]")!==-1&&Promise.name==="Promise";var selfPromise=isNative?self:Worker.convert(Object.assign({},self),Promise.prototype);// Return the promise, after casting it into a Worker and preserving props.
var returnVal=thenBase.call(selfPromise,onFulfilled,onRejected);return Worker.convert(returnVal,self.__proto__);};Worker.prototype.thenExternal=function thenExternal(onFulfilled,onRejected){// Call `then` and return a standard promise (exits the Worker chain).
return Promise.prototype.then.call(this,onFulfilled,onRejected);};Worker.prototype.thenList=function thenList(fns){// Queue a series of promise 'factories' into the promise chain.
var self=this;fns.forEach(function thenList_forEach(fn){self=self.thenCore(fn);});return self;};Worker.prototype["catch"]=function(onRejected){// Bind `this` to the promise handler, call `catch`, and return a Worker.
if(onRejected){onRejected=onRejected.bind(this);}var returnVal=Promise.prototype["catch"].call(this,onRejected);return Worker.convert(returnVal,this);};Worker.prototype.catchExternal=function catchExternal(onRejected){// Call `catch` and return a standard promise (exits the Worker chain).
return Promise.prototype["catch"].call(this,onRejected);};Worker.prototype.error=function error(msg){// Throw the error in the Promise chain.
return this.then(function error_main(){throw new Error(msg);});};/* ----- ALIASES ----- */Worker.prototype.using=Worker.prototype.set;Worker.prototype.saveAs=Worker.prototype.save;Worker.prototype.export=Worker.prototype.output;Worker.prototype.run=Worker.prototype.then;// Get dimensions of a PDF page, as determined by jsPDF.
jsPDF.getPageSize=function(orientation,unit,format){// Decode options object
if(_typeof(orientation)==="object"){var options=orientation;orientation=options.orientation;unit=options.unit||unit;format=options.format||format;}// Default options
unit=unit||"mm";format=format||"a4";orientation=(""+(orientation||"P")).toLowerCase();var format_as_string=(""+format).toLowerCase();// Size in pt of various paper formats
var pageFormats={a0:[2383.94,3370.39],a1:[1683.78,2383.94],a2:[1190.55,1683.78],a3:[841.89,1190.55],a4:[595.28,841.89],a5:[419.53,595.28],a6:[297.64,419.53],a7:[209.76,297.64],a8:[147.4,209.76],a9:[104.88,147.4],a10:[73.7,104.88],b0:[2834.65,4008.19],b1:[2004.09,2834.65],b2:[1417.32,2004.09],b3:[1000.63,1417.32],b4:[708.66,1000.63],b5:[498.9,708.66],b6:[354.33,498.9],b7:[249.45,354.33],b8:[175.75,249.45],b9:[124.72,175.75],b10:[87.87,124.72],c0:[2599.37,3676.54],c1:[1836.85,2599.37],c2:[1298.27,1836.85],c3:[918.43,1298.27],c4:[649.13,918.43],c5:[459.21,649.13],c6:[323.15,459.21],c7:[229.61,323.15],c8:[161.57,229.61],c9:[113.39,161.57],c10:[79.37,113.39],dl:[311.81,623.62],letter:[612,792],"government-letter":[576,756],legal:[612,1008],"junior-legal":[576,360],ledger:[1224,792],tabloid:[792,1224],"credit-card":[153,243]};// Unit conversion
switch(unit){case"pt":var k=1;break;case"mm":var k=72/25.4;break;case"cm":var k=72/2.54;break;case"in":var k=72;break;case"px":var k=72/96;break;case"pc":var k=12;break;case"em":var k=12;break;case"ex":var k=6;break;default:throw"Invalid unit: "+unit;}// Dimensions are stored as user units and converted to points on output
if(pageFormats.hasOwnProperty(format_as_string)){var pageHeight=pageFormats[format_as_string][1]/k;var pageWidth=pageFormats[format_as_string][0]/k;}else{try{var pageHeight=format[1];var pageWidth=format[0];}catch(err){throw new Error("Invalid format: "+format);}}// Handle page orientation
if(orientation==="p"||orientation==="portrait"){orientation="p";if(pageWidth>pageHeight){var tmp=pageWidth;pageWidth=pageHeight;pageHeight=tmp;}}else if(orientation==="l"||orientation==="landscape"){orientation="l";if(pageHeight>pageWidth){var tmp=pageWidth;pageWidth=pageHeight;pageHeight=tmp;}}else{throw"Invalid orientation: "+orientation;}// Return information (k is the unit conversion ratio from pts)
var info={width:pageWidth,height:pageHeight,unit:unit,k:k};return info;};/**
* Generate a PDF from an HTML element or string using.
*
* @name html
* @function
* @param {Element|string} source The source element or HTML string.
* @param {Object=} options An object of optional settings.
* @description The Plugin needs html2canvas from niklasvh
*/jsPDFAPI.html=function(src,options){options=options||{};options.callback=options.callback||function(){};options.html2canvas=options.html2canvas||{};options.html2canvas.canvas=options.html2canvas.canvas||this.canvas;options.jsPDF=options.jsPDF||this;// Create a new worker with the given options.
var pdf=options.jsPDF;pdf.annotations={_nameMap:[],createAnnotation:function createAnnotation(href,bounds){var x=pdf.context2d._wrapX(bounds.left);var y=pdf.context2d._wrapY(bounds.top);var page=pdf.context2d._page(bounds.top);var options;var index=href.indexOf("#");if(index>=0){options={name:href.substring(index+1)};}else{options={url:href};}pdf.link(x,y,bounds.right-bounds.left,bounds.bottom-bounds.top,options);},setName:function setName(name,bounds){var x=pdf.context2d._wrapX(bounds.left);var y=pdf.context2d._wrapY(bounds.top);var page=pdf.context2d._page(bounds.top);this._nameMap[name]={page:page,x:x,y:y};}};pdf.context2d._pageBreakAt=function(y){this.pageBreaks.push(y);};pdf.context2d._gotoPage=function(pageOneBased){while(pdf.internal.getNumberOfPages()>");this.internal.out("endobj");jsJsObj=this.internal.newObject();this.internal.out("<<");this.internal.out("/S /JavaScript");this.internal.out("/JS ("+text+")");this.internal.out(">>");this.internal.out("endobj");});this.internal.events.subscribe("putCatalog",function(){if(jsNamesObj!==undefined&&jsJsObj!==undefined){this.internal.out("/Names <>");}});return this;};})(jsPDF.API);/**
* @license
* Copyright (c) 2014 Steven Spungin (TwelveTone LLC) steven@twelvetone.tv
*
* Licensed under the MIT License.
* http://opensource.org/licenses/mit-license
*//**
* jsPDF Outline PlugIn
*
* Generates a PDF Outline
* @name outline
* @module
*/(function(jsPDFAPI){jsPDFAPI.events.push(["postPutResources",function(){var pdf=this;var rx=/^(\d+) 0 obj$/;// Write action goto objects for each page
// this.outline.destsGoto = [];
// for (var i = 0; i < totalPages; i++) {
// var id = pdf.internal.newObject();
// this.outline.destsGoto.push(id);
// pdf.internal.write("<> endobj");
// }
//
// for (var i = 0; i < dests.length; i++) {
// pdf.internal.write("(page_" + (i + 1) + ")" + dests[i] + " 0
// R");
// }
//
if(this.outline.root.children.length>0){var lines=pdf.outline.render().split(/\r\n/);for(var i=0;i> endobj");}// assign a name for each destination
var names2Oid=pdf.internal.newObject();pdf.internal.write("<< /Names [ ");for(var i=0;i>","endobj");// var kids = pdf.internal.newObject();
// pdf.internal.write('<< /Kids [ ' + names2Oid + ' 0 R');
// pdf.internal.write(' ] >>', 'endobj');
var namesOid=pdf.internal.newObject();pdf.internal.write("<< /Dests "+names2Oid+" 0 R");pdf.internal.write(">>","endobj");}}]);jsPDFAPI.events.push(["putCatalog",function(){var pdf=this;if(pdf.outline.root.children.length>0){pdf.internal.write("/Outlines",this.outline.makeRef(this.outline.root));if(this.outline.createNamedDestinations){pdf.internal.write("/Names "+namesOid+" 0 R");}// Open with Bookmarks showing
// pdf.internal.write("/PageMode /UseOutlines");
}}]);jsPDFAPI.events.push(["initialized",function(){var pdf=this;pdf.outline={createNamedDestinations:false,root:{children:[]}};/**
* Options: pageNumber
*/pdf.outline.add=function(parent,title,options){var item={title:title,options:options,children:[]};if(parent==null){parent=this.root;}parent.children.push(item);return item;};pdf.outline.render=function(){this.ctx={};this.ctx.val="";this.ctx.pdf=pdf;this.genIds_r(this.root);this.renderRoot(this.root);this.renderItems(this.root);return this.ctx.val;};pdf.outline.genIds_r=function(node){node.id=pdf.internal.newObjectDeferred();for(var i=0;i0){this.line("/First "+this.makeRef(node.children[0]));this.line("/Last "+this.makeRef(node.children[node.children.length-1]));}this.line("/Count "+this.count_r({count:0},node));this.objEnd();};pdf.outline.renderItems=function(node){for(var i=0;i0){this.line("/Prev "+this.makeRef(node.children[i-1]));}if(i0){this.line("/First "+this.makeRef(item.children[0]));this.line("/Last "+this.makeRef(item.children[item.children.length-1]));}var count=this.count=this.count_r({count:0},item);if(count>0){this.line("/Count "+count);}if(item.options){if(item.options.pageNumber){// Explicit Destination
//WARNING this assumes page ids are 3,5,7, etc.
var info=pdf.internal.getPageInfo(item.options.pageNumber);this.line("/Dest "+"["+info.objId+" 0 R /XYZ 0 "+this.ctx.pdf.internal.pageSize.getHeight()*this.ctx.pdf.internal.scaleFactor+" 0]");// this line does not work on all clients (pageNumber instead of page ref)
//this.line('/Dest ' + '[' + (item.options.pageNumber - 1) + ' /XYZ 0 ' + this.ctx.pdf.internal.pageSize.getHeight() + ' 0]');
// Named Destination
// this.line('/Dest (page_' + (item.options.pageNumber) + ')');
// Action Destination
// var id = pdf.internal.newObject();
// pdf.internal.write('<> endobj');
// this.line('/A ' + id + ' 0 R' );
}}this.objEnd();}for(var i=0;i> \r\n"+"endobj"+"\r\n";};pdf.outline.count_r=function(ctx,node){for(var i=0;i>>24&0xff;cmpd[len++]=checksum>>>16&0xff;cmpd[len++]=checksum>>>8&0xff;cmpd[len++]=checksum&0xff;return jsPDFAPI.arrayBufferToBinaryString(cmpd);},createZlibHeader=function createZlibHeader(bytes,level){/*
* @see http://www.ietf.org/rfc/rfc1950.txt for zlib header
*/var cm=8;var cinfo=Math.LOG2E*Math.log(0x8000)-8;var cmf=cinfo<<4|cm;var hdr=cmf<<8;var flevel=Math.min(3,(level-1&0xff)>>1);hdr|=flevel<<6;hdr|=0;//FDICT
hdr+=31-hdr%31;return[cmf,hdr&0xff&0xff];},adler32=function adler32(array,param){var adler=1;var s1=adler&0xffff,s2=adler>>>16&0xffff;var len=array.length;var tlen;var i=0;while(len>0){tlen=len>param?param:len;len-=tlen;do{s1+=array[i++];s2+=s1;}while(--tlen);s1%=65521;s2%=65521;}return(s2<<16|s1)>>>0;},applyPngFilterMethod=function applyPngFilterMethod(bytes,lineLength,colorsPerPixel,filter_method){var lines=bytes.length/lineLength,result=new Uint8Array(bytes.length+lines),filter_methods=getFilterMethods(),i=0,line,prevLine,offset;for(;i>>1)&0xff;}return result;},filterPaeth=function filterPaeth(line,colorsPerPixel,prevLine){var result=[],i=0,len=line.length,left,up,upLeft,paeth;result[0]=4;for(;i>>pbl&0xff;pbl=pbl+img.bits;}alphaData[i]=pixel>>>pbl&0xff;}}/*
* processes 16 bit RGBA and grayscale + alpha images
*/if(img.bits===16){var pixels=new Uint32Array(img.decodePixels().buffer),len=pixels.length,imgData=new Uint8Array(len*(32/img.pixelBitlength)*img.colors),alphaData=new Uint8Array(len*(32/img.pixelBitlength)),hasColors=img.colors>1,i=0,n=0,a=0,pixel;while(i>>0&0xff;if(hasColors){imgData[n++]=pixel>>>16&0xff;pixel=pixels[i++];imgData[n++]=pixel>>>0&0xff;}alphaData[a++]=pixel>>>16&0xff;}bpc=8;}if(canCompress(compression)){imageData=compressBytes(imgData,img.width*img.colors,img.colors,compression);smask=compressBytes(alphaData,img.width,1,compression);}else{imageData=imgData;smask=alphaData;decode=null;}}/*
* Indexed png. Each pixel is a palette index.
*/if(img.colorType===3){colorSpace=this.color_spaces.INDEXED;pal=img.palette;if(img.transparency.indexed){var trans=img.transparency.indexed;var total=0,i=0,len=trans.length;for(;imaxLen){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 splitParagraphIntoLines(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 line=[],lines=[line],line_length=options.textIndent||0,separator_length=0,current_word_length=0,word,widths_array,words=text.split(" "),spaceCharWidth=getCharWidthsArray.apply(this,[" ",options])[0],i,l,tmp,lineIndent;if(options.lineIndent===-1){lineIndent=words[0].length+2;}else{lineIndent=options.lineIndent||0;}if(lineIndent){var pad=Array(lineIndent).join(" "),wrds=[];words.map(function(wrd){wrd=wrd.split(/\s*\n/);if(wrd.length>1){wrds=wrds.concat(wrd.map(function(wrd,idx){return(idx&&wrd.length?"\n":"")+wrd;}));}else{wrds.push(wrd[0]);}});words=wrds;lineIndent=getStringUnitWidth.apply(this,[pad,options]);}for(i=0,l=words.length;imaxlen||force){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.apply(this,[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]?line[0].length:0)));}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+lineIndent;separator_length=spaceCharWidth;}else{line.push(word);line_length+=separator_length+current_word_length;separator_length=spaceCharWidth;}}if(lineIndent){var postProcess=function postProcess(ln,idx){return(idx?pad:"")+ln.join(" ");};}else{var postProcess=function postProcess(ln){return ln.join(" ");};}return lines.map(postProcess);};/**
* 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 available, 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.
*
* @name splitTextToSize
* @public
* @function
* @param {string} text Unencoded, regular JavaScript (Unicode, UTF-16 / UCS-2) string.
* @param {number} size Nominal number, measured in units default to this instance of jsPDF.
* @param {Object} options Optional flags needed for chopper to do the right thing.
* @returns {Array} array Array with strings chopped to size.
*/API.splitTextToSize=function(text,maxlen,options){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{font:f.metadata,fontSize:this.internal.getFontSize(),charSpace:this.internal.getCharSpace()};}}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(Array.isArray(text)){paragraphs=text;}else{paragraphs=text.split(/\r?\n/);}// 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;newOptions.lineIndent=options.lineIndent;var i,l,output=[];for(i=0,l=paragraphs.length;i
* Example: doc.viewerPreferences({"FitWindow":true});
*
* You can set following preferences:
*
* HideToolbar(boolean)
* Default value: false
*
* HideMenubar(boolean)
* Default value: false.
*
* HideWindowUI(boolean)
* Default value: false.
*
* FitWindow(boolean)
* Default value: false.
*
* CenterWindow(boolean)
* Default value: false
*
* DisplayDocTitle(boolean)
* Default value: false.
*
* NonFullScreenPageMode(string)
* Possible values: UseNone, UseOutlines, UseThumbs, UseOC
* Default value: UseNone
*
* Direction(string)
* Possible values: L2R, R2L
* Default value: L2R.
*
* ViewArea(string)
* Possible values: MediaBox, CropBox, TrimBox, BleedBox, ArtBox
* Default value: CropBox.
*
* ViewClip(string)
* Possible values: MediaBox, CropBox, TrimBox, BleedBox, ArtBox
* Default value: CropBox
*
* PrintArea(string)
* Possible values: MediaBox, CropBox, TrimBox, BleedBox, ArtBox
* Default value: CropBox
*
* PrintClip(string)
* Possible values: MediaBox, CropBox, TrimBox, BleedBox, ArtBox
* Default value: CropBox.
*
* PrintScaling(string)
* Possible values: AppDefault, None
* Default value: AppDefault.
*
* Duplex(string)
* Possible values: Simplex, DuplexFlipLongEdge, DuplexFlipShortEdge
* Default value: none
*
* PickTrayByPDFSize(boolean)
* Default value: false
*
* PrintPageRange(Array)
* Example: [[1,5], [7,9]]
* Default value: as defined by PDF viewer application
*
* NumCopies(Number)
* Possible values: 1, 2, 3, 4, 5
* Default value: 1
*
* For more information see the PDF Reference, sixth edition on Page 577
* @param {boolean} doReset True to reset the settings
* @function
* @returns jsPDF jsPDF-instance
* @example
* var doc = new jsPDF()
* doc.text('This is a test', 10, 10)
* doc.viewerPreferences({'FitWindow': true}, true)
* doc.save("viewerPreferences.pdf")
*
* // Example printing 10 copies, using cropbox, and hiding UI.
* doc.viewerPreferences({
* 'HideWindowUI': true,
* 'PrintArea': 'CropBox',
* 'NumCopies': 10
* })
*/jsPDFAPI.viewerPreferences=function(options,doReset){options=options||{};doReset=doReset||false;var configuration;var configurationTemplate={HideToolbar:{defaultValue:false,value:false,type:"boolean",explicitSet:false,valueSet:[true,false],pdfVersion:1.3},HideMenubar:{defaultValue:false,value:false,type:"boolean",explicitSet:false,valueSet:[true,false],pdfVersion:1.3},HideWindowUI:{defaultValue:false,value:false,type:"boolean",explicitSet:false,valueSet:[true,false],pdfVersion:1.3},FitWindow:{defaultValue:false,value:false,type:"boolean",explicitSet:false,valueSet:[true,false],pdfVersion:1.3},CenterWindow:{defaultValue:false,value:false,type:"boolean",explicitSet:false,valueSet:[true,false],pdfVersion:1.3},DisplayDocTitle:{defaultValue:false,value:false,type:"boolean",explicitSet:false,valueSet:[true,false],pdfVersion:1.4},NonFullScreenPageMode:{defaultValue:"UseNone",value:"UseNone",type:"name",explicitSet:false,valueSet:["UseNone","UseOutlines","UseThumbs","UseOC"],pdfVersion:1.3},Direction:{defaultValue:"L2R",value:"L2R",type:"name",explicitSet:false,valueSet:["L2R","R2L"],pdfVersion:1.3},ViewArea:{defaultValue:"CropBox",value:"CropBox",type:"name",explicitSet:false,valueSet:["MediaBox","CropBox","TrimBox","BleedBox","ArtBox"],pdfVersion:1.4},ViewClip:{defaultValue:"CropBox",value:"CropBox",type:"name",explicitSet:false,valueSet:["MediaBox","CropBox","TrimBox","BleedBox","ArtBox"],pdfVersion:1.4},PrintArea:{defaultValue:"CropBox",value:"CropBox",type:"name",explicitSet:false,valueSet:["MediaBox","CropBox","TrimBox","BleedBox","ArtBox"],pdfVersion:1.4},PrintClip:{defaultValue:"CropBox",value:"CropBox",type:"name",explicitSet:false,valueSet:["MediaBox","CropBox","TrimBox","BleedBox","ArtBox"],pdfVersion:1.4},PrintScaling:{defaultValue:"AppDefault",value:"AppDefault",type:"name",explicitSet:false,valueSet:["AppDefault","None"],pdfVersion:1.6},Duplex:{defaultValue:"",value:"none",type:"name",explicitSet:false,valueSet:["Simplex","DuplexFlipShortEdge","DuplexFlipLongEdge","none"],pdfVersion:1.7},PickTrayByPDFSize:{defaultValue:false,value:false,type:"boolean",explicitSet:false,valueSet:[true,false],pdfVersion:1.7},PrintPageRange:{defaultValue:"",value:"",type:"array",explicitSet:false,valueSet:null,pdfVersion:1.7},NumCopies:{defaultValue:1,value:1,type:"integer",explicitSet:false,valueSet:null,pdfVersion:1.7}};var configurationKeys=Object.keys(configurationTemplate);var rangeArray=[];var i=0;var j=0;var k=0;var isValid=true;var method;var value;function arrayContainsElement(array,element){var iterator;var result=false;for(iterator=0;iterator1){for(j=0;j>");}});this.internal.viewerpreferences.isSubscribed=true;}this.internal.viewerpreferences.configuration=configuration;return this;};})(jsPDF.API);/** ====================================================================
* jsPDF XMP metadata plugin
* Copyright (c) 2016 Jussi Utunen, u-jussi@suomi24.fi
*
*
* ====================================================================
*//*global jsPDF *//**
* @name xmp_metadata
* @module
*/(function(jsPDFAPI){var xmpmetadata="";var xmpnamespaceuri="";var metadata_object_number="";/**
* Adds XMP formatted metadata to PDF
*
* @name addMetadata
* @function
* @param {String} metadata The actual metadata to be added. The metadata shall be stored as XMP simple value. Note that if the metadata string contains XML markup characters "<", ">" or "&", those characters should be written using XML entities.
* @param {String} namespaceuri Sets the namespace URI for the metadata. Last character should be slash or hash.
* @returns {jsPDF} jsPDF-instance
*/jsPDFAPI.addMetadata=function(metadata,namespaceuri){xmpnamespaceuri=namespaceuri||"http://jspdf.default.namespaceuri/";//The namespace URI for an XMP name shall not be empty
xmpmetadata=metadata;this.internal.events.subscribe("postPutResources",function(){if(!xmpmetadata){metadata_object_number="";}else{var xmpmeta_beginning='';var rdf_beginning='';var rdf_ending="";var xmpmeta_ending="";var utf8_xmpmeta_beginning=unescape(encodeURIComponent(xmpmeta_beginning));var utf8_rdf_beginning=unescape(encodeURIComponent(rdf_beginning));var utf8_metadata=unescape(encodeURIComponent(xmpmetadata));var utf8_rdf_ending=unescape(encodeURIComponent(rdf_ending));var utf8_xmpmeta_ending=unescape(encodeURIComponent(xmpmeta_ending));var total_len=utf8_rdf_beginning.length+utf8_metadata.length+utf8_rdf_ending.length+utf8_xmpmeta_beginning.length+utf8_xmpmeta_ending.length;metadata_object_number=this.internal.newObject();this.internal.write("<< /Type /Metadata /Subtype /XML /Length "+total_len+" >>");this.internal.write("stream");this.internal.write(utf8_xmpmeta_beginning+utf8_rdf_beginning+utf8_metadata+utf8_rdf_ending+utf8_xmpmeta_ending);this.internal.write("endstream");this.internal.write("endobj");}});this.internal.events.subscribe("putCatalog",function(){if(metadata_object_number){this.internal.write("/Metadata "+metadata_object_number+" 0 R");}});return this;};})(jsPDF.API);/**
* @name utf8
* @module
*/(function(jsPDF,global){var jsPDFAPI=jsPDF.API;/**************************************************//* function : toHex *//* comment : Replace str with a hex string. *//**************************************************/function toHex(str){var hex="";for(var i=0;i> def\n/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n1 begincodespacerange\n<0000>\nendcodespacerange";codes=Object.keys(map).sort(function(a,b){return a-b;});range=[];for(_i=0,_len=codes.length;_i<_len;_i++){code=codes[_i];if(range.length>=100){unicodeMap+="\n"+range.length+" beginbfchar\n"+range.join("\n")+"\nendbfchar";range=[];}unicode=("0000"+map[code].toString(16)).slice(-4);code=("0000"+(+code).toString(16)).slice(-4);range.push("<"+code+"><"+unicode+">");}if(range.length){unicodeMap+="\n"+range.length+" beginbfchar\n"+range.join("\n")+"\nendbfchar\n";}unicodeMap+="endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend";return unicodeMap;};var identityHFunction=function identityHFunction(font,out,newObject,putStream){if(font.metadata instanceof jsPDF.API.TTFFont&&font.encoding==="Identity-H"){//Tag with Identity-H
var widths=font.metadata.Unicode.widths;var data=font.metadata.subset.encode(font.metadata.glyIdsUsed,1);var pdfOutput=data;var pdfOutput2="";for(var i=0;i>");putStream(pdfOutput2);out("endobj");var cmap=newObject();var cmapData=toUnicodeCmap(font.metadata.toUnicode);out("<<");out("/Length "+cmapData.length);out("/Length1 "+cmapData.length);out(">>");putStream(cmapData);out("endobj");var fontDescriptor=newObject();out("<<");out("/Type /FontDescriptor");out("/FontName /"+font.fontName);out("/FontFile2 "+fontTable+" 0 R");out("/FontBBox "+jsPDF.API.PDFObject.convert(font.metadata.bbox));out("/Flags "+font.metadata.flags);out("/StemV "+font.metadata.stemV);out("/ItalicAngle "+font.metadata.italicAngle);out("/Ascent "+font.metadata.ascender);out("/Descent "+font.metadata.decender);out("/CapHeight "+font.metadata.capHeight);out(">>");out("endobj");var DescendantFont=newObject();out("<<");out("/Type /Font");out("/BaseFont /"+font.fontName);out("/FontDescriptor "+fontDescriptor+" 0 R");out("/W "+jsPDF.API.PDFObject.convert(widths));out("/CIDToGIDMap /Identity");out("/DW 1000");out("/Subtype /CIDFontType2");out("/CIDSystemInfo");out("<<");out("/Supplement 0");out("/Registry (Adobe)");out("/Ordering ("+font.encoding+")");out(">>");out(">>");out("endobj");font.objectNumber=newObject();out("<<");out("/Type /Font");out("/Subtype /Type0");out("/ToUnicode "+cmap+" 0 R");out("/BaseFont /"+font.fontName);out("/Encoding /"+font.encoding);out("/DescendantFonts ["+DescendantFont+" 0 R]");out(">>");out("endobj");font.isAlreadyPutted=true;}};jsPDFAPI.events.push(["putFont",function(args){identityHFunction(args.font,args.out,args.newObject,args.putStream);}]);var winAnsiEncodingFunction=function winAnsiEncodingFunction(font,out,newObject,putStream){if(font.metadata instanceof jsPDF.API.TTFFont&&font.encoding==="WinAnsiEncoding"){//Tag with WinAnsi encoding
var widths=font.metadata.Unicode.widths;var data=font.metadata.rawData;var pdfOutput=data;var pdfOutput2="";for(var i=0;i>");out("endobj");font.objectNumber=newObject();for(var i=0;i>");out("endobj");font.isAlreadyPutted=true;}};jsPDFAPI.events.push(["putFont",function(args){winAnsiEncodingFunction(args.font,args.out,args.newObject,args.putStream);}]);var utf8TextFunction=function utf8TextFunction(args){var text=args.text||"";var x=args.x;var y=args.y;var options=args.options||{};var mutex=args.mutex||{};var pdfEscape=mutex.pdfEscape;var activeFontKey=mutex.activeFontKey;var fonts=mutex.fonts;var key,fontSize=mutex.activeFontSize;var str="",s=0,cmapConfirm;var strText="";var key=activeFontKey;var encoding=fonts[key].encoding;if(fonts[key].encoding!=="Identity-H"){return{text:text,x:x,y:y,options:options,mutex:mutex};}strText=text;key=activeFontKey;if(Object.prototype.toString.call(text)==="[object Array]"){strText=text[0];}for(s=0;s1?end:this.data.length),type,this.encoding);};FB_proto.toString=function(){return"[object Blob]";};FB_proto.close=function(){this.size=0;delete this.data;};return FakeBlobBuilder;}(view);view.Blob=function(blobParts,options){var type=options?options.type||"":"";var builder=new BlobBuilder();if(blobParts){for(var i=0,len=blobParts.length;i, 2013.
//
// https://github.com/deanm/omggif
//
//
//
// omggif is a JavaScript implementation of a GIF 89a encoder and decoder,
// including animation and compression. It does not rely on any specific
// underlying system, so should run in the browser, Node, or Plask.
function GifWriter(buf,width,height,gopts){var p=0;var gopts=gopts===undefined?{}:gopts;var loop_count=gopts.loop===undefined?null:gopts.loop;var global_palette=gopts.palette===undefined?null:gopts.palette;if(width<=0||height<=0||width>65535||height>65535)throw"Width/Height invalid.";function check_palette_and_num_colors(palette){var num_colors=palette.length;if(num_colors<2||num_colors>256||num_colors&num_colors-1)throw"Invalid code/color length, must be power of 2 and 2 .. 256.";return num_colors;}// - Header.
buf[p++]=0x47;buf[p++]=0x49;buf[p++]=0x46;// GIF
buf[p++]=0x38;buf[p++]=0x39;buf[p++]=0x61;// 89a
// Handling of Global Color Table (palette) and background index.
var gp_num_colors_pow2=0;var background=0;if(global_palette!==null){var gp_num_colors=check_palette_and_num_colors(global_palette);while(gp_num_colors>>=1){++gp_num_colors_pow2;}gp_num_colors=1<=gp_num_colors)throw"Background index out of range.";// The GIF spec states that a background index of 0 should be ignored, so
// this is probably a mistake and you really want to set it to another
// slot in the palette. But actually in the end most browsers, etc end
// up ignoring this almost completely (including for dispose background).
if(background===0)throw"Background index explicitly passed as 0.";}}// - Logical Screen Descriptor.
// NOTE(deanm): w/h apparently ignored by implementations, but set anyway.
buf[p++]=width&0xff;buf[p++]=width>>8&0xff;buf[p++]=height&0xff;buf[p++]=height>>8&0xff;// NOTE: Indicates 0-bpp original color resolution (unused?).
buf[p++]=(global_palette!==null?0x80:0)|// Global Color Table Flag.
gp_num_colors_pow2;// NOTE: No sort flag (unused?).
buf[p++]=background;// Background Color Index.
buf[p++]=0;// Pixel aspect ratio (unused?).
// - Global Color Table
if(global_palette!==null){for(var i=0,il=global_palette.length;i>16&0xff;buf[p++]=rgb>>8&0xff;buf[p++]=rgb&0xff;}}if(loop_count!==null){// Netscape block for looping.
if(loop_count<0||loop_count>65535)throw"Loop count invalid.";// Extension code, label, and length.
buf[p++]=0x21;buf[p++]=0xff;buf[p++]=0x0b;// NETSCAPE2.0
buf[p++]=0x4e;buf[p++]=0x45;buf[p++]=0x54;buf[p++]=0x53;buf[p++]=0x43;buf[p++]=0x41;buf[p++]=0x50;buf[p++]=0x45;buf[p++]=0x32;buf[p++]=0x2e;buf[p++]=0x30;// Sub-block
buf[p++]=0x03;buf[p++]=0x01;buf[p++]=loop_count&0xff;buf[p++]=loop_count>>8&0xff;buf[p++]=0x00;// Terminator.
}var ended=false;this.addFrame=function(x,y,w,h,indexed_pixels,opts){if(ended===true){--p;ended=false;}// Un-end.
opts=opts===undefined?{}:opts;// TODO(deanm): Bounds check x, y. Do they need to be within the virtual
// canvas width/height, I imagine?
if(x<0||y<0||x>65535||y>65535)throw"x/y invalid.";if(w<=0||h<=0||w>65535||h>65535)throw"Width/Height invalid.";if(indexed_pixels.length>=1){++min_code_size;}num_colors=1<3)// 4-7 is reserved.
throw"Disposal out of range.";var use_transparency=false;var transparent_index=0;if(opts.transparent!==undefined&&opts.transparent!==null){use_transparency=true;transparent_index=opts.transparent;if(transparent_index<0||transparent_index>=num_colors)throw"Transparent color index.";}if(disposal!==0||use_transparency||delay!==0){// - Graphics Control Extension
buf[p++]=0x21;buf[p++]=0xf9;// Extension / Label.
buf[p++]=4;// Byte size.
buf[p++]=disposal<<2|(use_transparency===true?1:0);buf[p++]=delay&0xff;buf[p++]=delay>>8&0xff;buf[p++]=transparent_index;// Transparent color index.
buf[p++]=0;// Block Terminator.
}// - Image Descriptor
buf[p++]=0x2c;// Image Seperator.
buf[p++]=x&0xff;buf[p++]=x>>8&0xff;// Left.
buf[p++]=y&0xff;buf[p++]=y>>8&0xff;// Top.
buf[p++]=w&0xff;buf[p++]=w>>8&0xff;buf[p++]=h&0xff;buf[p++]=h>>8&0xff;// NOTE: No sort flag (unused?).
// TODO(deanm): Support interlace.
buf[p++]=using_local_palette===true?0x80|min_code_size-1:0;// - Local Color Table
if(using_local_palette===true){for(var i=0,il=palette.length;i>16&0xff;buf[p++]=rgb>>8&0xff;buf[p++]=rgb&0xff;}}p=GifWriterOutputLZWCodeStream(buf,p,min_code_size<2?2:min_code_size,indexed_pixels);};this.end=function(){if(ended===false){buf[p++]=0x3b;// Trailer.
ended=true;}return p;};}// Main compression routine, palette indexes -> LZW code stream.
// |index_stream| must have at least one entry.
function GifWriterOutputLZWCodeStream(buf,p,min_code_size,index_stream){buf[p++]=min_code_size;var cur_subblock=p++;// Pointing at the length field.
var clear_code=1<=bit_block_size){buf[p++]=cur&0xff;cur>>=8;cur_shift-=8;if(p===cur_subblock+256){// Finished a subblock.
buf[cur_subblock]=255;cur_subblock=p++;}}}function emit_code(c){cur|=c<=8){buf[p++]=cur&0xff;cur>>=8;cur_shift-=8;if(p===cur_subblock+256){// Finished a subblock.
buf[cur_subblock]=255;cur_subblock=p++;}}if(next_code===4096){// Table full, need a clear.
emit_code(clear_code);next_code=eoi_code+1;cur_code_size=min_code_size+1;code_table={};}else{// Table not full, insert a new entry.
// Increase our variable bit code sizes if necessary. This is a bit
// tricky as it is based on "timing" between the encoding and
// decoder. From the encoders perspective this should happen after
// we've already emitted the index buffer and are about to create the
// first table entry that would overflow our current code bit size.
if(next_code>=1<.
var global_palette_flag=pf0>>7;var num_global_colors_pow2=pf0&0x7;var num_global_colors=1<>2&0x7;p++;// Skip terminator.
break;case 0xfe:// Comment Extension.
while(true){// Seek through subblocks.
var block_size=buf[p++];if(block_size===0)break;// console.log(buf.slice(p, p+block_size).toString('ascii'));
p+=block_size;}break;default:throw"Unknown graphic control label: 0x"+buf[p-1].toString(16);}break;case 0x2c:// Image Descriptor.
var x=buf[p++]|buf[p++]<<8;var y=buf[p++]|buf[p++]<<8;var w=buf[p++]|buf[p++]<<8;var h=buf[p++]|buf[p++]<<8;var pf2=buf[p++];var local_palette_flag=pf2>>7;var interlace_flag=pf2>>6&1;var num_local_colors_pow2=pf2&0x7;var num_local_colors=1<=frames.length)throw"Frame index out of range.";return frames[frame_num];};this.decodeAndBlitFrameBGRA=function(frame_num,pixels){var frame=this.frameInfo(frame_num);var num_pixels=frame.width*frame.height;var index_stream=new Uint8Array(num_pixels);// At most 8-bit indices.
GifReaderLZWOutputIndexStream(buf,frame.data_offset,index_stream,num_pixels);var palette_offset=frame.palette_offset;// NOTE(deanm): It seems to be much faster to compare index to 256 than
// to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in
// the profile, not sure if it's related to using a Uint8Array.
var trans=frame.transparent_index;if(trans===null)trans=256;// We are possibly just blitting to a portion of the entire frame.
// That is a subrect within the framerect, so the additional pixels
// must be skipped over after we finished a scanline.
var framewidth=frame.width;var framestride=width-framewidth;var xleft=framewidth;// Number of subrect pixels left in scanline.
// Output indicies of the top left and bottom right corners of the subrect.
var opbeg=(frame.y*width+frame.x)*4;var opend=((frame.y+frame.height)*width+frame.x)*4;var op=opbeg;var scanstride=framestride*4;// Use scanstride to skip past the rows when interlacing. This is skipping
// 7 rows for the first two passes, then 3 then 1.
if(frame.interlaced===true){scanstride+=(framewidth+framestride)*4*7;// Pass 1.
}var interlaceskip=8;// Tracking the row interval in the current pass.
for(var i=0,il=index_stream.length;i=opend){// Catch the wrap to switch passes when interlacing.
scanstride=framestride+(framewidth+framestride)*4*(interlaceskip-1);// interlaceskip / 2 * 4 is interlaceskip << 1.
op=opbeg+(framewidth+framestride)*(interlaceskip<<1);interlaceskip>>=1;}}if(index===trans){op+=4;}else{var r=buf[palette_offset+index*3];var g=buf[palette_offset+index*3+1];var b=buf[palette_offset+index*3+2];pixels[op++]=b;pixels[op++]=g;pixels[op++]=r;pixels[op++]=255;}--xleft;}};// I will go to copy and paste hell one day...
this.decodeAndBlitFrameRGBA=function(frame_num,pixels){var frame=this.frameInfo(frame_num);var num_pixels=frame.width*frame.height;var index_stream=new Uint8Array(num_pixels);// At most 8-bit indices.
GifReaderLZWOutputIndexStream(buf,frame.data_offset,index_stream,num_pixels);var palette_offset=frame.palette_offset;// NOTE(deanm): It seems to be much faster to compare index to 256 than
// to === null. Not sure why, but CompareStub_EQ_STRICT shows up high in
// the profile, not sure if it's related to using a Uint8Array.
var trans=frame.transparent_index;if(trans===null)trans=256;// We are possibly just blitting to a portion of the entire frame.
// That is a subrect within the framerect, so the additional pixels
// must be skipped over after we finished a scanline.
var framewidth=frame.width;var framestride=width-framewidth;var xleft=framewidth;// Number of subrect pixels left in scanline.
// Output indicies of the top left and bottom right corners of the subrect.
var opbeg=(frame.y*width+frame.x)*4;var opend=((frame.y+frame.height)*width+frame.x)*4;var op=opbeg;var scanstride=framestride*4;// Use scanstride to skip past the rows when interlacing. This is skipping
// 7 rows for the first two passes, then 3 then 1.
if(frame.interlaced===true){scanstride+=(framewidth+framestride)*4*7;// Pass 1.
}var interlaceskip=8;// Tracking the row interval in the current pass.
for(var i=0,il=index_stream.length;i=opend){// Catch the wrap to switch passes when interlacing.
scanstride=framestride+(framewidth+framestride)*4*(interlaceskip-1);// interlaceskip / 2 * 4 is interlaceskip << 1.
op=opbeg+(framewidth+framestride)*(interlaceskip<<1);interlaceskip>>=1;}}if(index===trans){op+=4;}else{var r=buf[palette_offset+index*3];var g=buf[palette_offset+index*3+1];var b=buf[palette_offset+index*3+2];pixels[op++]=r;pixels[op++]=g;pixels[op++]=b;pixels[op++]=255;}--xleft;}};}function GifReaderLZWOutputIndexStream(code_stream,p,output,output_length){var min_code_size=code_stream[p++];var clear_code=1<>=cur_code_size;cur_shift-=cur_code_size;// TODO(deanm): Maybe should check that the first code was a clear code,
// at least this is what you're supposed to do. But actually our encoder
// now doesn't emit a clear code first anyway.
if(code===clear_code){// We don't actually have to clear the table. This could be a good idea
// for greater error checking, but we don't really do any anyway. We
// will just track it with next_code and overwrite old entries.
next_code=eoi_code+1;cur_code_size=min_code_size+1;code_mask=(1<clear_code){chase=code_table[chase]>>8;++chase_length;}var k=chase;var op_end=op+chase_length+(chase_code!==code?1:0);if(op_end>output_length){console.log("Warning, gif stream longer than expected.");return;}// Already have the first byte from the chase, might as well write it fast.
output[op++]=k;op+=chase_length;var b=op;// Track pointer, writing backwards.
if(chase_code!==code)// The case of emitting {CODE-1} + k.
output[op++]=k;chase=chase_code;while(chase_length--){chase=code_table[chase];output[--b]=chase&0xff;// Write backwards.
chase>>=8;// Pull down to the prefix code.
}if(prev_code!==null&&next_code<4096){code_table[next_code++]=prev_code<<8|k;// TODO(deanm): Figure out this clearing vs code growth logic better. I
// have an feeling that it should just happen somewhere else, for now it
// is awkward between when we grow past the max and then hit a clear code.
// For now just check if we hit the max 12-bits (then a clear code should
// follow, also of course encoded in 12-bits).
if(next_code>=code_mask+1&&cur_code_size<12){++cur_code_size;code_mask=code_mask<<1|1;}}prev_code=code;}if(op!==output_length){console.log("Warning, gif stream shorter than expected.");}return output;}try{}catch(e){}// CommonJS.
/*
* Copyright (c) 2012 chick307
*
* Licensed under the MIT License.
* http://opensource.org/licenses/mit-license
*/(function(jsPDF,callback){jsPDF.API.adler32cs=callback();})(jsPDF,function(){var _hasArrayBuffer=typeof ArrayBuffer==="function"&&typeof Uint8Array==="function";var _Buffer=null,_isBuffer=function(){if(!_hasArrayBuffer)return function _isBuffer(){return false;};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>>0;};var _updateUint8Array=function _updateUint8Array(checksum,uint8Array){var a=checksum&0xffff,b=checksum>>>16;for(var i=0,length=uint8Array.length;i>>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;});/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*//**
* @author shaozilee
*
* Bmp format decoder,support 1bit 4bit 8bit 24bit bmp
*
*//*
Copyright (c) 2013 Gildas Lormeau. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*//*
* This program is based on JZlib 1.0.2 ymnk, JCraft,Inc.
* JZlib is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/(function(global){var MAX_BITS=15;var D_CODES=30;var BL_CODES=19;var LENGTH_CODES=29;var LITERALS=256;var L_CODES=LITERALS+1+LENGTH_CODES;var HEAP_SIZE=2*L_CODES+1;var END_BLOCK=256;// Bit length codes must not exceed MAX_BL_BITS bits
var MAX_BL_BITS=7;// repeat previous bit length 3-6 times (2 bits of repeat count)
var REP_3_6=16;// repeat a zero length 3-10 times (3 bits of repeat count)
var REPZ_3_10=17;// repeat a zero length 11-138 times (7 bits of repeat count)
var REPZ_11_138=18;// The lengths of the bit length codes are sent in order of decreasing
// probability, to avoid transmitting the lengths for unused bit
// length codes.
var Buf_size=8*2;// JZlib version : "1.0.2"
var Z_DEFAULT_COMPRESSION=-1;// compression strategy
var Z_FILTERED=1;var Z_HUFFMAN_ONLY=2;var Z_DEFAULT_STRATEGY=0;var Z_NO_FLUSH=0;var Z_PARTIAL_FLUSH=1;var Z_FULL_FLUSH=3;var Z_FINISH=4;var Z_OK=0;var Z_STREAM_END=1;var Z_NEED_DICT=2;var Z_STREAM_ERROR=-2;var Z_DATA_ERROR=-3;var Z_BUF_ERROR=-5;// Tree
// see definition of array dist_code below
var _dist_code=[0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,0,0,16,17,18,18,19,19,20,20,20,20,21,21,21,21,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29];function Tree(){var that=this;// dyn_tree; // the dynamic tree
// max_code; // largest code with non zero frequency
// stat_desc; // the corresponding static tree
// Compute the optimal bit lengths for a tree and update the total bit
// length
// for the current block.
// IN assertion: the fields freq and dad are set, heap[heap_max] and
// above are the tree nodes sorted by increasing frequency.
// OUT assertions: the field len is set to the optimal bit length, the
// array bl_count contains the frequencies for each bit length.
// The length opt_len is updated; static_len is also updated if stree is
// not null.
function gen_bitlen(s){var tree=that.dyn_tree;var stree=that.stat_desc.static_tree;var extra=that.stat_desc.extra_bits;var base=that.stat_desc.extra_base;var max_length=that.stat_desc.max_length;var h;// heap index
var n,m;// iterate over the tree elements
var bits;// bit length
var xbits;// extra bits
var f;// frequency
var overflow=0;// number of elements with bit length too large
for(bits=0;bits<=MAX_BITS;bits++){s.bl_count[bits]=0;}// In a first pass, compute the optimal bit lengths (which may
// overflow in the case of the bit length tree).
tree[s.heap[s.heap_max]*2+1]=0;// root of the heap
for(h=s.heap_max+1;hmax_length){bits=max_length;overflow++;}tree[n*2+1]=bits;// We overwrite tree[n*2+1] which is no longer needed
if(n>that.max_code)continue;// not a leaf node
s.bl_count[bits]++;xbits=0;if(n>=base)xbits=extra[n-base];f=tree[n*2];s.opt_len+=f*(bits+xbits);if(stree)s.static_len+=f*(stree[n*2+1]+xbits);}if(overflow===0)return;// This happens for example on obj2 and pic of the Calgary corpus
// Find the first bit length which could increase:
do{bits=max_length-1;while(s.bl_count[bits]===0){bits--;}s.bl_count[bits]--;// move one leaf down the tree
s.bl_count[bits+1]+=2;// move one overflow item as its brother
s.bl_count[max_length]--;// The brother of the overflow item also moves one step up,
// but this does not affect bl_count[max_length]
overflow-=2;}while(overflow>0);for(bits=max_length;bits!==0;bits--){n=s.bl_count[bits];while(n!==0){m=s.heap[--h];if(m>that.max_code)continue;if(tree[m*2+1]!=bits){s.opt_len+=(bits-tree[m*2+1])*tree[m*2];tree[m*2+1]=bits;}n--;}}}// Reverse the first len bits of a code, using straightforward code (a
// faster
// method would use a table)
// IN assertion: 1 <= len <= 15
function bi_reverse(code,// the value to invert
len// its bit length
){var res=0;do{res|=code&1;code>>>=1;res<<=1;}while(--len>0);return res>>>1;}// Generate the codes for a given tree and bit counts (which need not be
// optimal).
// IN assertion: the array bl_count contains the bit length statistics for
// the given tree and the field len is set for all tree elements.
// OUT assertion: the field code is set for all tree elements of non
// zero code length.
function gen_codes(tree,// the tree to decorate
max_code,// largest code with non zero frequency
bl_count// number of codes at each bit length
){var next_code=[];// next code value for each
// bit length
var code=0;// running code value
var bits;// bit index
var n;// code index
var len;// The distribution counts are first used to generate the code values
// without bit reversal.
for(bits=1;bits<=MAX_BITS;bits++){next_code[bits]=code=code+bl_count[bits-1]<<1;}// Check that the bit counts in bl_count are consistent. The last code
// must be all ones.
// Assert (code + bl_count[MAX_BITS]-1 == (1<=1;n--){s.pqdownheap(tree,n);}// Construct the Huffman tree by repeatedly combining the least two
// frequent nodes.
node=elems;// next internal node of the tree
do{// n = node of least frequency
n=s.heap[1];s.heap[1]=s.heap[s.heap_len--];s.pqdownheap(tree,1);m=s.heap[1];// m = node of next least frequency
s.heap[--s.heap_max]=n;// keep the nodes sorted by frequency
s.heap[--s.heap_max]=m;// Create a new node father of n and m
tree[node*2]=tree[n*2]+tree[m*2];s.depth[node]=Math.max(s.depth[n],s.depth[m])+1;tree[n*2+1]=tree[m*2+1]=node;// and insert the new node in the heap
s.heap[1]=node++;s.pqdownheap(tree,1);}while(s.heap_len>=2);s.heap[--s.heap_max]=s.heap[1];// At this point, the fields freq and dad are set. We can now
// generate the bit lengths.
gen_bitlen(s);// The field len is now set, we can generate the bit codes
gen_codes(tree,that.max_code,s.bl_count);};}Tree._length_code=[0,1,2,3,4,5,6,7,8,8,9,9,10,10,11,11,12,12,12,12,13,13,13,13,14,14,14,14,15,15,15,15,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,28];Tree.base_length=[0,1,2,3,4,5,6,7,8,10,12,14,16,20,24,28,32,40,48,56,64,80,96,112,128,160,192,224,0];Tree.base_dist=[0,1,2,3,4,6,8,12,16,24,32,48,64,96,128,192,256,384,512,768,1024,1536,2048,3072,4096,6144,8192,12288,16384,24576];// Mapping from a distance to a distance code. dist is the distance - 1 and
// must not have side effects. _dist_code[256] and _dist_code[257] are never
// used.
Tree.d_code=function(dist){return dist<256?_dist_code[dist]:_dist_code[256+(dist>>>7)];};// extra bits for each length code
Tree.extra_lbits=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];// extra bits for each distance code
Tree.extra_dbits=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];// extra bits for each bit length code
Tree.extra_blbits=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];Tree.bl_order=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];// StaticTree
function StaticTree(static_tree,extra_bits,extra_base,elems,max_length){var that=this;that.static_tree=static_tree;that.extra_bits=extra_bits;that.extra_base=extra_base;that.elems=elems;that.max_length=max_length;}StaticTree.static_ltree=[12,8,140,8,76,8,204,8,44,8,172,8,108,8,236,8,28,8,156,8,92,8,220,8,60,8,188,8,124,8,252,8,2,8,130,8,66,8,194,8,34,8,162,8,98,8,226,8,18,8,146,8,82,8,210,8,50,8,178,8,114,8,242,8,10,8,138,8,74,8,202,8,42,8,170,8,106,8,234,8,26,8,154,8,90,8,218,8,58,8,186,8,122,8,250,8,6,8,134,8,70,8,198,8,38,8,166,8,102,8,230,8,22,8,150,8,86,8,214,8,54,8,182,8,118,8,246,8,14,8,142,8,78,8,206,8,46,8,174,8,110,8,238,8,30,8,158,8,94,8,222,8,62,8,190,8,126,8,254,8,1,8,129,8,65,8,193,8,33,8,161,8,97,8,225,8,17,8,145,8,81,8,209,8,49,8,177,8,113,8,241,8,9,8,137,8,73,8,201,8,41,8,169,8,105,8,233,8,25,8,153,8,89,8,217,8,57,8,185,8,121,8,249,8,5,8,133,8,69,8,197,8,37,8,165,8,101,8,229,8,21,8,149,8,85,8,213,8,53,8,181,8,117,8,245,8,13,8,141,8,77,8,205,8,45,8,173,8,109,8,237,8,29,8,157,8,93,8,221,8,61,8,189,8,125,8,253,8,19,9,275,9,147,9,403,9,83,9,339,9,211,9,467,9,51,9,307,9,179,9,435,9,115,9,371,9,243,9,499,9,11,9,267,9,139,9,395,9,75,9,331,9,203,9,459,9,43,9,299,9,171,9,427,9,107,9,363,9,235,9,491,9,27,9,283,9,155,9,411,9,91,9,347,9,219,9,475,9,59,9,315,9,187,9,443,9,123,9,379,9,251,9,507,9,7,9,263,9,135,9,391,9,71,9,327,9,199,9,455,9,39,9,295,9,167,9,423,9,103,9,359,9,231,9,487,9,23,9,279,9,151,9,407,9,87,9,343,9,215,9,471,9,55,9,311,9,183,9,439,9,119,9,375,9,247,9,503,9,15,9,271,9,143,9,399,9,79,9,335,9,207,9,463,9,47,9,303,9,175,9,431,9,111,9,367,9,239,9,495,9,31,9,287,9,159,9,415,9,95,9,351,9,223,9,479,9,63,9,319,9,191,9,447,9,127,9,383,9,255,9,511,9,0,7,64,7,32,7,96,7,16,7,80,7,48,7,112,7,8,7,72,7,40,7,104,7,24,7,88,7,56,7,120,7,4,7,68,7,36,7,100,7,20,7,84,7,52,7,116,7,3,8,131,8,67,8,195,8,35,8,163,8,99,8,227,8];StaticTree.static_dtree=[0,5,16,5,8,5,24,5,4,5,20,5,12,5,28,5,2,5,18,5,10,5,26,5,6,5,22,5,14,5,30,5,1,5,17,5,9,5,25,5,5,5,21,5,13,5,29,5,3,5,19,5,11,5,27,5,7,5,23,5];StaticTree.static_l_desc=new StaticTree(StaticTree.static_ltree,Tree.extra_lbits,LITERALS+1,L_CODES,MAX_BITS);StaticTree.static_d_desc=new StaticTree(StaticTree.static_dtree,Tree.extra_dbits,0,D_CODES,MAX_BITS);StaticTree.static_bl_desc=new StaticTree(null,Tree.extra_blbits,0,BL_CODES,MAX_BL_BITS);// Deflate
var MAX_MEM_LEVEL=9;var DEF_MEM_LEVEL=8;function Config(good_length,max_lazy,nice_length,max_chain,func){var that=this;that.good_length=good_length;that.max_lazy=max_lazy;that.nice_length=nice_length;that.max_chain=max_chain;that.func=func;}var STORED=0;var FAST=1;var SLOW=2;var config_table=[new Config(0,0,0,0,STORED),new Config(4,4,8,4,FAST),new Config(4,5,16,8,FAST),new Config(4,6,32,32,FAST),new Config(4,4,16,16,SLOW),new Config(8,16,32,32,SLOW),new Config(8,16,128,128,SLOW),new Config(8,32,128,256,SLOW),new Config(32,128,258,1024,SLOW),new Config(32,258,258,4096,SLOW)];var z_errmsg=["need dictionary",// Z_NEED_DICT
// 2
"stream end",// Z_STREAM_END 1
"",// Z_OK 0
"",// Z_ERRNO (-1)
"stream error",// Z_STREAM_ERROR (-2)
"data error",// Z_DATA_ERROR (-3)
"",// Z_MEM_ERROR (-4)
"buffer error",// Z_BUF_ERROR (-5)
"",// Z_VERSION_ERROR (-6)
""];// block not completed, need more input or more output
var NeedMore=0;// block flush performed
var BlockDone=1;// finish started, need only more output at next deflate
var FinishStarted=2;// finish done, accept no more input or output
var FinishDone=3;// preset dictionary flag in zlib header
var PRESET_DICT=0x20;var INIT_STATE=42;var BUSY_STATE=113;var FINISH_STATE=666;// The deflate compression method
var Z_DEFLATED=8;var STORED_BLOCK=0;var STATIC_TREES=1;var DYN_TREES=2;var MIN_MATCH=3;var MAX_MATCH=258;var MIN_LOOKAHEAD=MAX_MATCH+MIN_MATCH+1;function smaller(tree,n,m,depth){var tn2=tree[n*2];var tm2=tree[m*2];return tn2= hash_bits
var hash_shift;// Window position at the beginning of the current output block. Gets
// negative when the window is moved backwards.
var block_start;var match_length;// length of best match
var prev_match;// previous match
var match_available;// set if previous match exists
var strstart;// start of string to insert
var match_start;// start of matching string
var lookahead;// number of valid bytes ahead in window
// Length of the best match at previous step. Matches not greater than this
// are discarded. This is used in the lazy match evaluation.
var prev_length;// To speed up deflation, hash chains are never searched beyond this
// length. A higher limit improves compression ratio but degrades the speed.
var max_chain_length;// Attempt to find a better match only when the current match is strictly
// smaller than this value. This mechanism is used only for compression
// levels >= 4.
var max_lazy_match;// Insert new strings in the hash table only if the match length is not
// greater than this length. This saves time but degrades compression.
// max_insert_length is used only for compression levels <= 3.
var level;// compression level (1..9)
var strategy;// favor or force Huffman coding
// Use a faster search when the previous match is longer than this
var good_match;// Stop searching when current match exceeds this
var nice_match;var dyn_ltree;// literal and length tree
var dyn_dtree;// distance tree
var bl_tree;// Huffman tree for bit lengths
var l_desc=new Tree();// desc for literal tree
var d_desc=new Tree();// desc for distance tree
var bl_desc=new Tree();// desc for bit length tree
// that.heap_len; // number of elements in the heap
// that.heap_max; // element of largest frequency
// The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
// The same heap array is used to build all trees.
// Depth of each subtree used as tie breaker for trees of equal frequency
that.depth=[];var l_buf;// index for literals or lengths */
// Size of match buffer for literals/lengths. There are 4 reasons for
// limiting lit_bufsize to 64K:
// - frequencies can be kept in 16 bit counters
// - if compression is not successful for the first block, all input
// data is still in the window so we can still emit a stored block even
// when input comes from standard input. (This can also be done for
// all blocks if lit_bufsize is not greater than 32K.)
// - if compression is not successful for a file smaller than 64K, we can
// even emit a stored file instead of a stored block (saving 5 bytes).
// This is applicable only for zip (not gzip or zlib).
// - creating new Huffman trees less frequently may not provide fast
// adaptation to changes in the input data statistics. (Take for
// example a binary file with poorly compressible code followed by
// a highly compressible string table.) Smaller buffer sizes give
// fast adaptation but have of course the overhead of transmitting
// trees more frequently.
// - I can't count above 4
var lit_bufsize;var last_lit;// running index in l_buf
// Buffer for distances. To simplify the code, d_buf and l_buf have
// the same number of elements. To use different lengths, an extra flag
// array would be necessary.
var d_buf;// index of pendig_buf
// that.opt_len; // bit length of current block with optimal trees
// that.static_len; // bit length of current block with static trees
var matches;// number of string matches in current block
var last_eob_len;// bit length of EOB code for last block
// Output buffer. bits are inserted starting at the bottom (least
// significant bits).
var bi_buf;// Number of valid bits in bi_buf. All bits above the last valid bit
// are always zero.
var bi_valid;// number of codes at each bit length for an optimal tree
that.bl_count=[];// heap used to build the Huffman trees
that.heap=[];dyn_ltree=[];dyn_dtree=[];bl_tree=[];function lm_init(){var i;window_size=2*w_size;head[hash_size-1]=0;for(i=0;i=3;max_blindex--){if(bl_tree[Tree.bl_order[max_blindex]*2+1]!==0)break;}// Update opt_len to include the bit length tree and counts
that.opt_len+=3*(max_blindex+1)+5+5+4;return max_blindex;}// Output a byte on the stream.
// IN assertion: there is enough room in pending_buf.
function put_byte(p){that.pending_buf[that.pending++]=p;}function put_short(w){put_byte(w&0xff);put_byte(w>>>8&0xff);}function putShortMSB(b){put_byte(b>>8&0xff);put_byte(b&0xff&0xff);}function send_bits(value,length){var val,len=length;if(bi_valid>Buf_size-len){val=value;// bi_buf |= (val << bi_valid);
bi_buf|=val<>>Buf_size-bi_valid;bi_valid+=len-Buf_size;}else{// bi_buf |= (value) << bi_valid;
bi_buf|=value<= 257, dcodes >= 1, blcodes >= 4.
function send_all_trees(lcodes,dcodes,blcodes){var rank;// index in bl_order
send_bits(lcodes-257,5);// not +255 as stated in appnote.txt
send_bits(dcodes-1,5);send_bits(blcodes-4,4);// not -3 as stated in appnote.txt
for(rank=0;rank=8){put_byte(bi_buf&0xff);bi_buf>>>=8;bi_valid-=8;}}// Send one empty static block to give enough lookahead for inflate.
// This takes 10 bits, of which 7 may remain in the bit buffer.
// The current inflate code requires 9 bits of lookahead. If the
// last two codes for the previous block (real code plus EOB) were coded
// on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
// the last real code. In this case we send two empty static blocks instead
// of one. (There are no problems if the previous block is stored or fixed.)
// To simplify the code, we assume the worst case of last real code encoded
// on one bit only.
function _tr_align(){send_bits(STATIC_TREES<<1,3);send_code(END_BLOCK,StaticTree.static_ltree);bi_flush();// Of the 10 bits for the empty block, we have already sent
// (10 - bi_valid) bits. The lookahead for the last real code (before
// the EOB of the previous block) was thus at least one plus the length
// of the EOB plus what we have just sent of the empty static block.
if(1+last_eob_len+10-bi_valid<9){send_bits(STATIC_TREES<<1,3);send_code(END_BLOCK,StaticTree.static_ltree);bi_flush();}last_eob_len=7;}// Save the match info and tally the frequency counts. Return true if
// the current block must be flushed.
function _tr_tally(dist,// distance of matched string
lc// match length-MIN_MATCH or unmatched char (if dist==0)
){var out_length,in_length,dcode;that.pending_buf[d_buf+last_lit*2]=dist>>>8&0xff;that.pending_buf[d_buf+last_lit*2+1]=dist&0xff;that.pending_buf[l_buf+last_lit]=lc&0xff;last_lit++;if(dist===0){// lc is the unmatched char
dyn_ltree[lc*2]++;}else{matches++;// Here, lc is the match length - MIN_MATCH
dist--;// dist = match distance - 1
dyn_ltree[(Tree._length_code[lc]+LITERALS+1)*2]++;dyn_dtree[Tree.d_code(dist)*2]++;}if((last_lit&0x1fff)===0&&level>2){// Compute an upper bound for the compressed length
out_length=last_lit*8;in_length=strstart-block_start;for(dcode=0;dcode>>=3;if(matches8){put_short(bi_buf);}else if(bi_valid>0){put_byte(bi_buf&0xff);}bi_buf=0;bi_valid=0;}// Copy a stored block, storing first the length and its
// one's complement if requested.
function copy_block(buf,// the input data
len,// its length
header// true if block header must be written
){bi_windup();// align on byte boundary
last_eob_len=8;// enough lookahead for inflate
if(header){put_short(len);put_short(~len);}that.pending_buf.set(window.subarray(buf,buf+len),that.pending);that.pending+=len;}// Send a stored block
function _tr_stored_block(buf,// input block
stored_len,// length of input block
eof// true if this is the last block for a file
){send_bits((STORED_BLOCK<<1)+(eof?1:0),3);// send block type
copy_block(buf,stored_len,true);// with header
}// Determine the best encoding for the current block: dynamic trees, static
// trees or store, and output the encoded block to the zip file.
function _tr_flush_block(buf,// input block, or NULL if too old
stored_len,// length of input block
eof// true if this is the last block for a file
){var opt_lenb,static_lenb;// opt_len and static_len in bytes
var max_blindex=0;// index of last bit length code of non zero freq
// Build the Huffman trees unless a stored block is forced
if(level>0){// Construct the literal and distance trees
l_desc.build_tree(that);d_desc.build_tree(that);// At this point, opt_len and static_len are the total bit lengths
// of
// the compressed block data, excluding the tree representations.
// Build the bit length tree for the above two trees, and get the
// index
// in bl_order of the last bit length code to send.
max_blindex=build_bl_tree();// Determine the best encoding. Compute first the block length in
// bytes
opt_lenb=that.opt_len+3+7>>>3;static_lenb=that.static_len+3+7>>>3;if(static_lenb<=opt_lenb)opt_lenb=static_lenb;}else{opt_lenb=static_lenb=stored_len+5;// force a stored block
}if(stored_len+4<=opt_lenb&&buf!=-1){// 4: two words for the lengths
// The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
// Otherwise we can't have processed more than WSIZE input bytes
// since
// the last block flush, because compression would have been
// successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
// transform a block into a stored block.
_tr_stored_block(buf,stored_len,eof);}else if(static_lenb==opt_lenb){send_bits((STATIC_TREES<<1)+(eof?1:0),3);compress_block(StaticTree.static_ltree,StaticTree.static_dtree);}else{send_bits((DYN_TREES<<1)+(eof?1:0),3);send_all_trees(l_desc.max_code+1,d_desc.max_code+1,max_blindex+1);compress_block(dyn_ltree,dyn_dtree);}// The above check is made mod 2^32, for files larger than 512 MB
// and uLong implemented on 32 bits.
init_block();if(eof){bi_windup();}}function flush_block_only(eof){_tr_flush_block(block_start>=0?block_start:-1,strstart-block_start,eof);block_start=strstart;strm.flush_pending();}// Fill the window when the lookahead becomes insufficient.
// Updates strstart and lookahead.
//
// IN assertion: lookahead < MIN_LOOKAHEAD
// OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
// At least one byte has been read, or avail_in === 0; reads are
// performed for at least two bytes (required for the zip translate_eol
// option -- not supported here).
function fill_window(){var n,m;var p;var more;// Amount of free space at the end of the window.
do{more=window_size-lookahead-strstart;// Deal with !@#$% 64K limit:
if(more===0&&strstart===0&&lookahead===0){more=w_size;}else if(more==-1){// Very unlikely, but possible on 16 bit machine if strstart ==
// 0
// and lookahead == 1 (input done one byte at time)
more--;// If the window is almost full and there is insufficient
// lookahead,
// move the upper half to the lower one to make room in the
// upper half.
}else if(strstart>=w_size+w_size-MIN_LOOKAHEAD){window.set(window.subarray(w_size,w_size+w_size),0);match_start-=w_size;strstart-=w_size;// we now have strstart >= MAX_DIST
block_start-=w_size;// Slide the hash table (could be avoided with 32 bit values
// at the expense of memory usage). We slide even when level ==
// 0
// to keep the hash table consistent if we switch back to level
// > 0
// later. (Using level 0 permanently is not an optimal usage of
// zlib, so we don't care about this pathological case.)
n=hash_size;p=n;do{m=head[--p]&0xffff;head[p]=m>=w_size?m-w_size:0;}while(--n!==0);n=w_size;p=n;do{m=prev[--p]&0xffff;prev[p]=m>=w_size?m-w_size:0;// If n is not on any hash chain, prev[n] is garbage but
// its value will never be used.
}while(--n!==0);more+=w_size;}if(strm.avail_in===0)return;// If there was no sliding:
// strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
// more == window_size - lookahead - strstart
// => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
// => more >= window_size - 2*WSIZE + 2
// In the BIG_MEM or MMAP case (not yet supported),
// window_size == input_size + MIN_LOOKAHEAD &&
// strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
// Otherwise, window_size == 2*WSIZE so more >= 2.
// If there was sliding, more >= WSIZE. So in all cases, more >= 2.
n=strm.read_buf(window,strstart+lookahead,more);lookahead+=n;// Initialize the hash value now that we have some input:
if(lookahead>=MIN_MATCH){ins_h=window[strstart]&0xff;ins_h=(ins_h<pending_buf_size-5){max_block_size=pending_buf_size-5;}// Copy as much as possible from input to output:
while(true){// Fill the window as much as possible:
if(lookahead<=1){fill_window();if(lookahead===0&&flush==Z_NO_FLUSH)return NeedMore;if(lookahead===0)break;// flush the current block
}strstart+=lookahead;lookahead=0;// Emit a stored block if pending_buf will be full:
max_start=block_start+max_block_size;if(strstart===0||strstart>=max_start){// strstart === 0 is possible when wraparound on 16-bit machine
lookahead=strstart-max_start;strstart=max_start;flush_block_only(false);if(strm.avail_out===0)return NeedMore;}// Flush if we may have to slide, otherwise block_start may become
// negative and the data will be gone:
if(strstart-block_start>=w_size-MIN_LOOKAHEAD){flush_block_only(false);if(strm.avail_out===0)return NeedMore;}}flush_block_only(flush==Z_FINISH);if(strm.avail_out===0)return flush==Z_FINISH?FinishStarted:NeedMore;return flush==Z_FINISH?FinishDone:BlockDone;}function longest_match(cur_match){var chain_length=max_chain_length;// max hash chain length
var scan=strstart;// current string
var match;// matched string
var len;// length of current match
var best_len=prev_length;// best match length so far
var limit=strstart>w_size-MIN_LOOKAHEAD?strstart-(w_size-MIN_LOOKAHEAD):0;var _nice_match=nice_match;// Stop when cur_match becomes <= limit. To simplify the code,
// we prevent matches with the string of window index 0.
var wmask=w_mask;var strend=strstart+MAX_MATCH;var scan_end1=window[scan+best_len-1];var scan_end=window[scan+best_len];// The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of
// 16.
// It is easy to get rid of this optimization if necessary.
// Do not waste too much time if we already have a good match:
if(prev_length>=good_match){chain_length>>=2;}// Do not look for matches beyond the end of the input. This is
// necessary
// to make deflate deterministic.
if(_nice_match>lookahead)_nice_match=lookahead;do{match=cur_match;// Skip to next match if the match length cannot increase
// or if the match length is less than 2:
if(window[match+best_len]!=scan_end||window[match+best_len-1]!=scan_end1||window[match]!=window[scan]||window[++match]!=window[scan+1])continue;// The check at best_len-1 can be removed because it will be made
// again later. (This heuristic is not always a win.)
// It is not necessary to compare scan[2] and match[2] since they
// are always equal when the other bytes match, given that
// the hash keys are equal and that HASH_BITS >= 8.
scan+=2;match++;// We check for insufficient lookahead only every 8th comparison;
// the 256th check will be made at strstart+258.
do{}while(window[++scan]==window[++match]&&window[++scan]==window[++match]&&window[++scan]==window[++match]&&window[++scan]==window[++match]&&window[++scan]==window[++match]&&window[++scan]==window[++match]&&window[++scan]==window[++match]&&window[++scan]==window[++match]&&scanbest_len){match_start=cur_match;best_len=len;if(len>=_nice_match)break;scan_end1=window[scan+best_len-1];scan_end=window[scan+best_len];}}while((cur_match=prev[cur_match&wmask]&0xffff)>limit&&--chain_length!==0);if(best_len<=lookahead)return best_len;return lookahead;}// Compress as much as possible from the input stream, return the current
// block state.
// This function does not perform lazy evaluation of matches and inserts
// new strings in the dictionary only for unmatched strings or for short
// matches. It is used only for the fast compression options.
function deflate_fast(flush){// short hash_head = 0; // head of the hash chain
var hash_head=0;// head of the hash chain
var bflush;// set if current block must be flushed
while(true){// Make sure that we always have enough lookahead, except
// at the end of the input file. We need MAX_MATCH bytes
// for the next match, plus MIN_MATCH bytes to insert the
// string following the next match.
if(lookahead=MIN_MATCH){ins_h=(ins_h<=MIN_MATCH){// check_match(strstart, match_start, match_length);
bflush=_tr_tally(strstart-match_start,match_length-MIN_MATCH);lookahead-=match_length;// Insert new strings in the hash table only if the match length
// is not too large. This saves time but degrades compression.
if(match_length<=max_lazy_match&&lookahead>=MIN_MATCH){match_length--;// string at strstart already in hash table
do{strstart++;ins_h=(ins_h<=MIN_MATCH){ins_h=(ins_h<4096)){// If prev_match is also MIN_MATCH, match_start is garbage
// but we will ignore the current match anyway.
match_length=MIN_MATCH-1;}}// If there was a match at the previous step and the current
// match is not better, output the previous match:
if(prev_length>=MIN_MATCH&&match_length<=prev_length){max_insert=strstart+lookahead-MIN_MATCH;// Do not insert strings in hash table beyond this.
// check_match(strstart-1, prev_match, prev_length);
bflush=_tr_tally(strstart-1-prev_match,prev_length-MIN_MATCH);// Insert in hash table all strings up to the end of the match.
// strstart-1 and strstart are already inserted. If there is not
// enough lookahead, the last two strings are not inserted in
// the hash table.
lookahead-=prev_length-1;prev_length-=2;do{if(++strstart<=max_insert){ins_h=(ins_h<MAX_MEM_LEVEL||_method!=Z_DEFLATED||bits<9||bits>15||_level<0||_level>9||_strategy<0||_strategy>Z_HUFFMAN_ONLY){return Z_STREAM_ERROR;}strm.dstate=that;w_bits=bits;w_size=1<9||_strategy<0||_strategy>Z_HUFFMAN_ONLY){return Z_STREAM_ERROR;}if(config_table[level].func!=config_table[_level].func&&strm.total_in!==0){// Flush the last buffer:
err=strm.deflate(Z_PARTIAL_FLUSH);}if(level!=_level){level=_level;max_lazy_match=config_table[level].max_lazy;good_match=config_table[level].good_length;nice_match=config_table[level].nice_length;max_chain_length=config_table[level].max_chain;}strategy=_strategy;return err;};that.deflateSetDictionary=function(strm,dictionary,dictLength){var length=dictLength;var n,index=0;if(!dictionary||status!=INIT_STATE)return Z_STREAM_ERROR;if(lengthw_size-MIN_LOOKAHEAD){length=w_size-MIN_LOOKAHEAD;index=dictLength-length;// use the tail of the dictionary
}window.set(dictionary.subarray(index,index+length),0);strstart=length;block_start=length;// Insert all strings in the hash table (except for the last two bytes).
// s->lookahead stays null, so s->ins_h will be recomputed at the next
// call of fill_window.
ins_h=window[0]&0xff;ins_h=(ins_h<Z_FINISH||flush<0){return Z_STREAM_ERROR;}if(!_strm.next_out||!_strm.next_in&&_strm.avail_in!==0||status==FINISH_STATE&&flush!=Z_FINISH){_strm.msg=z_errmsg[Z_NEED_DICT-Z_STREAM_ERROR];return Z_STREAM_ERROR;}if(_strm.avail_out===0){_strm.msg=z_errmsg[Z_NEED_DICT-Z_BUF_ERROR];return Z_BUF_ERROR;}strm=_strm;// just in case
old_flush=last_flush;last_flush=flush;// Write the zlib header
if(status==INIT_STATE){header=Z_DEFLATED+(w_bits-8<<4)<<8;level_flags=(level-1&0xff)>>1;if(level_flags>3)level_flags=3;header|=level_flags<<6;if(strstart!==0)header|=PRESET_DICT;header+=31-header%31;status=BUSY_STATE;putShortMSB(header);}// Flush as much pending output as possible
if(that.pending!==0){strm.flush_pending();if(strm.avail_out===0){// console.log(" avail_out==0");
// Since avail_out is 0, deflate will be called again with
// more output space, but possibly with both pending and
// avail_in equal to zero. There won't be anything to do,
// but this is not an error situation so make sure we
// return OK instead of BUF_ERROR at next call of deflate:
last_flush=-1;return Z_OK;}// Make sure there is something to do and avoid duplicate
// consecutive
// flushes. For repeated and useless calls with Z_FINISH, we keep
// returning Z_STREAM_END instead of Z_BUFF_ERROR.
}else if(strm.avail_in===0&&flush<=old_flush&&flush!=Z_FINISH){strm.msg=z_errmsg[Z_NEED_DICT-Z_BUF_ERROR];return Z_BUF_ERROR;}// User must not provide more input after the first FINISH:
if(status==FINISH_STATE&&strm.avail_in!==0){_strm.msg=z_errmsg[Z_NEED_DICT-Z_BUF_ERROR];return Z_BUF_ERROR;}// Start a new block or continue the current one.
if(strm.avail_in!==0||lookahead!==0||flush!=Z_NO_FLUSH&&status!=FINISH_STATE){bstate=-1;switch(config_table[level].func){case STORED:bstate=deflate_stored(flush);break;case FAST:bstate=deflate_fast(flush);break;case SLOW:bstate=deflate_slow(flush);break;default:}if(bstate==FinishStarted||bstate==FinishDone){status=FINISH_STATE;}if(bstate==NeedMore||bstate==FinishStarted){if(strm.avail_out===0){last_flush=-1;// avoid BUF_ERROR next call, see above
}return Z_OK;// If flush != Z_NO_FLUSH && avail_out === 0, the next call
// of deflate should use the same flush parameter to make sure
// that the flush is complete. So we don't have to output an
// empty block here, this will be done at next call. This also
// ensures that for a very small output buffer, we emit at most
// one empty block.
}if(bstate==BlockDone){if(flush==Z_PARTIAL_FLUSH){_tr_align();}else{// FULL_FLUSH or SYNC_FLUSH
_tr_stored_block(0,0,false);// For a full flush, this empty block will be recognized
// as a special marker by inflate_sync().
if(flush==Z_FULL_FLUSH){// state.head[s.hash_size-1]=0;
for(i=0;inext_in buffer and copying from it.
// (See also flush_pending()).
read_buf:function read_buf(buf,start,size){var that=this;var len=that.avail_in;if(len>size)len=size;if(len===0)return 0;that.avail_in-=len;buf.set(that.next_in.subarray(that.next_in_index,that.next_in_index+len),start);that.next_in_index+=len;that.total_in+=len;return len;},// Flush as much pending output as possible. All deflate() output goes
// through this function so some applications may wish to modify it
// to avoid allocating a large strm->next_out buffer and copying into it.
// (See also read_buf()).
flush_pending:function flush_pending(){var that=this;var len=that.dstate.pending;if(len>that.avail_out)len=that.avail_out;if(len===0)return;// if (that.dstate.pending_buf.length <= that.dstate.pending_out || that.next_out.length <= that.next_out_index
// || that.dstate.pending_buf.length < (that.dstate.pending_out + len) || that.next_out.length < (that.next_out_index +
// len)) {
// console.log(that.dstate.pending_buf.length + ", " + that.dstate.pending_out + ", " + that.next_out.length + ", " +
// that.next_out_index + ", " + len);
// console.log("avail_out=" + that.avail_out);
// }
that.next_out.set(that.dstate.pending_buf.subarray(that.dstate.pending_out,that.dstate.pending_out+len),that.next_out_index);that.next_out_index+=len;that.dstate.pending_out+=len;that.total_out+=len;that.avail_out-=len;that.dstate.pending-=len;if(that.dstate.pending===0){that.dstate.pending_out=0;}}};// Deflater
function Deflater(options){var that=this;var z=new ZStream();var bufsize=512;var flush=Z_NO_FLUSH;var buf=new Uint8Array(bufsize);var level=options?options.level:Z_DEFAULT_COMPRESSION;if(typeof level=="undefined")level=Z_DEFAULT_COMPRESSION;z.deflateInit(level);z.next_out=buf;that.append=function(data,onprogress){var err,buffers=[],lastIndex=0,bufferIndex=0,bufferSize=0,array;if(!data.length)return;z.next_in_index=0;z.next_in=data;z.avail_in=data.length;do{z.next_out_index=0;z.avail_out=bufsize;err=z.deflate(flush);if(err!=Z_OK)throw new Error("deflating: "+z.msg);if(z.next_out_index)if(z.next_out_index==bufsize)buffers.push(new Uint8Array(buf));else buffers.push(new Uint8Array(buf.subarray(0,z.next_out_index)));bufferSize+=z.next_out_index;if(onprogress&&z.next_in_index>0&&z.next_in_index!=lastIndex){onprogress(z.next_in_index);lastIndex=z.next_in_index;}}while(z.avail_in>0||z.avail_out===0);array=new Uint8Array(bufferSize);buffers.forEach(function(chunk){array.set(chunk,bufferIndex);bufferIndex+=chunk.length;});return array;};that.flush=function(){var err,buffers=[],bufferIndex=0,bufferSize=0,array;do{z.next_out_index=0;z.avail_out=bufsize;err=z.deflate(Z_FINISH);if(err!=Z_STREAM_END&&err!=Z_OK)throw new Error("deflating: "+z.msg);if(bufsize-z.avail_out>0)buffers.push(new Uint8Array(buf.subarray(0,z.next_out_index)));bufferSize+=z.next_out_index;}while(z.avail_in>0||z.avail_out===0);z.deflateEnd();array=new Uint8Array(bufferSize);buffers.forEach(function(chunk){array.set(chunk,bufferIndex);bufferIndex+=chunk.length;});return array;};}// 'zip' may not be defined in z-worker and some tests
var env=global.zip||global;env.Deflater=env._jzlib_Deflater=Deflater;})(typeof self!=="undefined"&&self||typeof window!=="undefined"&&window||typeof global!=="undefined"&&global||Function('return typeof this === "object" && this.content')()||Function("return this")());// `self` is undefined in Firefox for Android content script context
// while `this` is nsIContentFrameMessageManager
// with an attribute `content` that corresponds to the window
/**
* A class to parse color values
* @author Stoyan Stefanov
* @link http://www.phpied.com/rgb-color-parser-in-javascript/
* @license Use it if you like it
*/(function(global){function RGBColor(color_string){this.ok=false;// strip any leading #
if(color_string.charAt(0)=="#"){// remove # if any
color_string=color_string.substr(1,6);}color_string=color_string.replace(/ /g,"");color_string=color_string.toLowerCase();var channels;// before getting into regexps, try simple matches
// and overwrite the input
var simple_colors={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dodgerblue:"1e90ff",feldspar:"d19275",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgrey:"d3d3d3",lightgreen:"90ee90",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslateblue:"8470ff",lightslategray:"778899",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"00ff00",limegreen:"32cd32",linen:"faf0e6",magenta:"ff00ff",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370d8",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"d87093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",red:"ff0000",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",violetred:"d02090",wheat:"f5deb3",white:"ffffff",whitesmoke:"f5f5f5",yellow:"ffff00",yellowgreen:"9acd32"};for(var key in simple_colors){if(color_string==key){color_string=simple_colors[key];}}// emd of simple type-in colors
// array of color definition objects
var color_defs=[{re:/^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,example:["rgb(123, 234, 45)","rgb(255,234,245)"],process:function process(bits){return[parseInt(bits[1]),parseInt(bits[2]),parseInt(bits[3])];}},{re:/^(\w{2})(\w{2})(\w{2})$/,example:["#00ff00","336699"],process:function process(bits){return[parseInt(bits[1],16),parseInt(bits[2],16),parseInt(bits[3],16)];}},{re:/^(\w{1})(\w{1})(\w{1})$/,example:["#fb0","f0f"],process:function process(bits){return[parseInt(bits[1]+bits[1],16),parseInt(bits[2]+bits[2],16),parseInt(bits[3]+bits[3],16)];}}];// search through the definitions to find a match
for(var i=0;i255?255:this.r;this.g=this.g<0||isNaN(this.g)?0:this.g>255?255:this.g;this.b=this.b<0||isNaN(this.b)?0:this.b>255?255:this.b;// some getters
this.toRGB=function(){return"rgb("+this.r+", "+this.g+", "+this.b+")";};this.toHex=function(){var r=this.r.toString(16);var g=this.g.toString(16);var b=this.b.toString(16);if(r.length==1)r="0"+r;if(g.length==1)g="0"+g;if(b.length==1)b="0"+b;return"#"+r+g+b;};// help
this.getHelpXML=function(){var examples=new Array();// add regexps
for(var i=0;i "+list_color.toRGB()+" -> "+list_color.toHex());list_item.appendChild(example_div);list_item.appendChild(list_item_value);xml.appendChild(list_item);}catch(e){}}return xml;};}global.RGBColor=RGBColor;})(typeof self!=="undefined"&&self||typeof window!=="undefined"&&window||typeof global!=="undefined"&&global||Function('return typeof this === "object" && this.content')()||Function("return this")());// `self` is undefined in Firefox for Android content script context
// while `this` is nsIContentFrameMessageManager
// with an attribute `content` that corresponds to the window
/************************************************
* Title : custom font *
* Start Data : 2017. 01. 22. *
* Comment : TEXT API *
************************************************//******************************
* jsPDF extension API Design *
* ****************************/(function(jsPDF){var PLUS="+".charCodeAt(0);var SLASH="/".charCodeAt(0);var NUMBER="0".charCodeAt(0);var LOWER="a".charCodeAt(0);var UPPER="A".charCodeAt(0);var PLUS_URL_SAFE="-".charCodeAt(0);var SLASH_URL_SAFE="_".charCodeAt(0);/*****************************************************************//* function : b64ToByteArray *//* comment : Base64 encoded TTF file contents (b64) are decoded *//* by Byte array and stored. *//*****************************************************************/var b64ToByteArray=function b64ToByteArray(b64){var i,j,l,tmp,placeHolders,arr;if(b64.length%4>0){throw new Error("Invalid string. Length must be a multiple of 4");}// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
var len=b64.length;placeHolders="="===b64.charAt(len-2)?2:"="===b64.charAt(len-1)?1:0;// base64 is 4/3 + up to two characters of the original data
arr=new Uint8Array(b64.length*3/4-placeHolders);// if there are placeholders, only get up to the last complete 4 chars
l=placeHolders>0?b64.length-4:b64.length;var L=0;function push(v){arr[L++]=v;}for(i=0,j=0;i>16);push((tmp&0xff00)>>8);push(tmp&0xff);}if(placeHolders===2){tmp=decode(b64.charAt(i))<<2|decode(b64.charAt(i+1))>>4;push(tmp&0xff);}else if(placeHolders===1){tmp=decode(b64.charAt(i))<<10|decode(b64.charAt(i+1))<<4|decode(b64.charAt(i+2))>>2;push(tmp>>8&0xff);push(tmp&0xff);}return arr;};/***************************************************************//* function : decode *//* comment : Change the base64 encoded font's content to match *//* the base64 index value. *//***************************************************************/var decode=function decode(elt){var code=elt.charCodeAt(0);if(code===PLUS||code===PLUS_URL_SAFE)return 62;// '+'
if(code===SLASH||code===SLASH_URL_SAFE)return 63;// '/'
if(code>16;low=raw&0xff;if(hi&0x8000!==0){hi=-((hi^0xffff)+1);}this.italicAngle=+(""+hi+"."+low);}else{this.italicAngle=0;}this.ascender=Math.round(this.ascender*this.scaleFactor);this.decender=Math.round(this.decender*this.scaleFactor);this.lineGap=Math.round(this.lineGap*this.scaleFactor);this.capHeight=this.os2.exists&&this.os2.capHeight||this.ascender;this.xHeight=this.os2.exists&&this.os2.xHeight||0;this.familyClass=(this.os2.exists&&this.os2.familyClass||0)>>8;this.isSerif=(_ref=this.familyClass)===1||_ref===2||_ref===3||_ref===4||_ref===5||_ref===7;this.isScript=this.familyClass===10;this.flags=0;if(this.post.isFixedPitch){this.flags|=1<<0;}if(this.isSerif){this.flags|=1<<1;}if(this.isScript){this.flags|=1<<3;}if(this.italicAngle!==0){this.flags|=1<<6;}this.flags|=1<<5;if(!this.cmap.unicode){throw new Error("No unicode cmap for font");}};TTFFont.prototype.characterToGlyph=function(character){var _ref;return((_ref=this.cmap.unicode)!=null?_ref.codeMap[character]:void 0)||0;};TTFFont.prototype.widthOfGlyph=function(glyph){var scale;scale=1000.0/this.head.unitsPerEm;return this.hmtx.forGlyph(glyph).advance*scale;};TTFFont.prototype.widthOfString=function(string,size,charSpace){var charCode,i,scale,width,_i,_ref,charSpace;string=""+string;width=0;for(i=_i=0,_ref=string.length;0<=_ref?_i<_ref:_i>_ref;i=0<=_ref?++_i:--_i){charCode=string.charCodeAt(i);width+=this.widthOfGlyph(this.characterToGlyph(charCode))+charSpace*(1000/size)||0;}scale=size/1000;return width*scale;};TTFFont.prototype.lineHeight=function(size,includeGap){var gap;if(includeGap==null){includeGap=false;}gap=includeGap?this.lineGap:0;return(this.ascender+gap-this.decender)/1000*size;};return TTFFont;}();/************************************************************************************************//* function : Data *//* comment : The ttf data decoded and stored in an array is read and written to the Data object.*//************************************************************************************************/var Data=function(){function Data(data){this.data=data!=null?data:[];this.pos=0;this.length=this.data.length;}Data.prototype.readByte=function(){return this.data[this.pos++];};Data.prototype.writeByte=function(byte){return this.data[this.pos++]=byte;};Data.prototype.readUInt32=function(){var b1,b2,b3,b4;b1=this.readByte()*0x1000000;b2=this.readByte()<<16;b3=this.readByte()<<8;b4=this.readByte();return b1+b2+b3+b4;};Data.prototype.writeUInt32=function(val){this.writeByte(val>>>24&0xff);this.writeByte(val>>16&0xff);this.writeByte(val>>8&0xff);return this.writeByte(val&0xff);};Data.prototype.readInt32=function(){var int;int=this.readUInt32();if(int>=0x80000000){return int-0x100000000;}else{return int;}};Data.prototype.writeInt32=function(val){if(val<0){val+=0x100000000;}return this.writeUInt32(val);};Data.prototype.readUInt16=function(){var b1,b2;b1=this.readByte()<<8;b2=this.readByte();return b1|b2;};Data.prototype.writeUInt16=function(val){this.writeByte(val>>8&0xff);return this.writeByte(val&0xff);};Data.prototype.readInt16=function(){var int;int=this.readUInt16();if(int>=0x8000){return int-0x10000;}else{return int;}};Data.prototype.writeInt16=function(val){if(val<0){val+=0x10000;}return this.writeUInt16(val);};Data.prototype.readString=function(length){var i,ret,_i;ret=[];for(i=_i=0;0<=length?_ilength;i=0<=length?++_i:--_i){ret[i]=String.fromCharCode(this.readByte());}return ret.join("");};Data.prototype.writeString=function(val){var i,_i,_ref,_results;_results=[];for(i=_i=0,_ref=val.length;0<=_ref?_i<_ref:_i>_ref;i=0<=_ref?++_i:--_i){_results.push(this.writeByte(val.charCodeAt(i)));}return _results;};/*Data.prototype.stringAt = function (pos, length) {
this.pos = pos;
return this.readString(length);
};*/Data.prototype.readShort=function(){return this.readInt16();};Data.prototype.writeShort=function(val){return this.writeInt16(val);};Data.prototype.readLongLong=function(){var b1,b2,b3,b4,b5,b6,b7,b8;b1=this.readByte();b2=this.readByte();b3=this.readByte();b4=this.readByte();b5=this.readByte();b6=this.readByte();b7=this.readByte();b8=this.readByte();if(b1&0x80){return((b1^0xff)*0x100000000000000+(b2^0xff)*0x1000000000000+(b3^0xff)*0x10000000000+(b4^0xff)*0x100000000+(b5^0xff)*0x1000000+(b6^0xff)*0x10000+(b7^0xff)*0x100+(b8^0xff)+1)*-1;}return b1*0x100000000000000+b2*0x1000000000000+b3*0x10000000000+b4*0x100000000+b5*0x1000000+b6*0x10000+b7*0x100+b8;};Data.prototype.writeLongLong=function(val){var high,low;high=Math.floor(val/0x100000000);low=val&0xffffffff;this.writeByte(high>>24&0xff);this.writeByte(high>>16&0xff);this.writeByte(high>>8&0xff);this.writeByte(high&0xff);this.writeByte(low>>24&0xff);this.writeByte(low>>16&0xff);this.writeByte(low>>8&0xff);return this.writeByte(low&0xff);};Data.prototype.readInt=function(){return this.readInt32();};Data.prototype.writeInt=function(val){return this.writeInt32(val);};/*Data.prototype.slice = function (start, end) {
return this.data.slice(start, end);
};*/Data.prototype.read=function(bytes){var buf,i,_i;buf=[];for(i=_i=0;0<=bytes?_ibytes;i=0<=bytes?++_i:--_i){buf.push(this.readByte());}return buf;};Data.prototype.write=function(bytes){var byte,_i,_len,_results;_results=[];for(_i=0,_len=bytes.length;_i<_len;_i++){byte=bytes[_i];_results.push(this.writeByte(byte));}return _results;};return Data;}();var Directory=function(){var checksum;/*****************************************************************************************************//* function : Directory generator *//* comment : Initialize the offset, tag, length, and checksum for each table for the font to be used.*//*****************************************************************************************************/function Directory(data){var entry,i,_i,_ref;this.scalarType=data.readInt();this.tableCount=data.readShort();this.searchRange=data.readShort();this.entrySelector=data.readShort();this.rangeShift=data.readShort();this.tables={};for(i=_i=0,_ref=this.tableCount;0<=_ref?_i<_ref:_i>_ref;i=0<=_ref?++_i:--_i){entry={tag:data.readString(4),checksum:data.readInt(),offset:data.readInt(),length:data.readInt()};this.tables[entry.tag]=entry;}}/********************************************************************************************************//* function : encode *//* comment : It encodes and stores the font table object and information used for the directory object. *//********************************************************************************************************/Directory.prototype.encode=function(tables){var adjustment,directory,directoryLength,entrySelector,headOffset,log2,offset,rangeShift,searchRange,sum,table,tableCount,tableData,tag;tableCount=Object.keys(tables).length;log2=Math.log(2);searchRange=Math.floor(Math.log(tableCount)/log2)*16;entrySelector=Math.floor(searchRange/log2);rangeShift=tableCount*16-searchRange;directory=new Data();directory.writeInt(this.scalarType);directory.writeShort(tableCount);directory.writeShort(searchRange);directory.writeShort(entrySelector);directory.writeShort(rangeShift);directoryLength=tableCount*16;offset=directory.pos+directoryLength;headOffset=null;tableData=[];for(tag in tables){table=tables[tag];directory.writeString(tag);directory.writeInt(checksum(table));directory.writeInt(offset);directory.writeInt(table.length);tableData=tableData.concat(table);if(tag==="head"){headOffset=offset;}offset+=table.length;while(offset%4){tableData.push(0);offset++;}}directory.write(tableData);sum=checksum(directory.data);adjustment=0xb1b0afba-sum;directory.pos=headOffset+8;directory.writeUInt32(adjustment);return directory.data;};/***************************************************************//* function : checksum *//* comment : Duplicate the table for the tag. *//***************************************************************/checksum=function checksum(data){var i,sum,tmp,_i,_ref;data=__slice.call(data);while(data.length%4){data.push(0);}tmp=new Data(data);sum=0;for(i=_i=0,_ref=data.length;_i<_ref;i=_i+=4){sum+=tmp.readUInt32();}return sum&0xffffffff;};return Directory;}();var Table,__hasProp={}.hasOwnProperty,__extends=function __extends(child,parent){for(var key in parent){if(__hasProp.call(parent,key))child[key]=parent[key];}function ctor(){this.constructor=child;}ctor.prototype=parent.prototype;child.prototype=new ctor();child.__super__=parent.prototype;return child;};/***************************************************************//* function : Table *//* comment : Save info for each table, and parse the table. *//***************************************************************/Table=function(){function Table(file){var info;this.file=file;info=this.file.directory.tables[this.tag];this.exists=!!info;if(info){this.offset=info.offset,this.length=info.length;this.parse(this.file.contents);}}Table.prototype.parse=function(){};Table.prototype.encode=function(){};Table.prototype.raw=function(){if(!this.exists){return null;}this.file.contents.pos=this.offset;return this.file.contents.read(this.length);};return Table;}();var HeadTable=function(_super){__extends(HeadTable,_super);function HeadTable(){return HeadTable.__super__.constructor.apply(this,arguments);}HeadTable.prototype.tag="head";HeadTable.prototype.parse=function(data){data.pos=this.offset;this.version=data.readInt();this.revision=data.readInt();this.checkSumAdjustment=data.readInt();this.magicNumber=data.readInt();this.flags=data.readShort();this.unitsPerEm=data.readShort();this.created=data.readLongLong();this.modified=data.readLongLong();this.xMin=data.readShort();this.yMin=data.readShort();this.xMax=data.readShort();this.yMax=data.readShort();this.macStyle=data.readShort();this.lowestRecPPEM=data.readShort();this.fontDirectionHint=data.readShort();this.indexToLocFormat=data.readShort();return this.glyphDataFormat=data.readShort();};HeadTable.prototype.encode=function(indexToLocFormat){var table;table=new Data();table.writeInt(this.version);table.writeInt(this.revision);table.writeInt(this.checkSumAdjustment);table.writeInt(this.magicNumber);table.writeShort(this.flags);table.writeShort(this.unitsPerEm);table.writeLongLong(this.created);table.writeLongLong(this.modified);table.writeShort(this.xMin);table.writeShort(this.yMin);table.writeShort(this.xMax);table.writeShort(this.yMax);table.writeShort(this.macStyle);table.writeShort(this.lowestRecPPEM);table.writeShort(this.fontDirectionHint);table.writeShort(indexToLocFormat);table.writeShort(this.glyphDataFormat);return table.data;};return HeadTable;}(Table);/************************************************************************************//* function : CmapEntry *//* comment : Cmap Initializes and encodes object information (required by pdf spec).*//************************************************************************************/var CmapEntry=function(){function CmapEntry(data,offset){var code,count,endCode,glyphId,glyphIds,i,idDelta,idRangeOffset,index,saveOffset,segCount,segCountX2,start,startCode,tail,_i,_j,_k,_len;this.platformID=data.readUInt16();this.encodingID=data.readShort();this.offset=offset+data.readInt();saveOffset=data.pos;data.pos=this.offset;this.format=data.readUInt16();this.length=data.readUInt16();this.language=data.readUInt16();this.isUnicode=this.platformID===3&&this.encodingID===1&&this.format===4||this.platformID===0&&this.format===4;this.codeMap={};switch(this.format){case 0:for(i=_i=0;_i<256;i=++_i){this.codeMap[i]=data.readByte();}break;case 4:segCountX2=data.readUInt16();segCount=segCountX2/2;data.pos+=6;endCode=function(){var _j,_results;_results=[];for(i=_j=0;0<=segCount?_jsegCount;i=0<=segCount?++_j:--_j){_results.push(data.readUInt16());}return _results;}();data.pos+=2;startCode=function(){var _j,_results;_results=[];for(i=_j=0;0<=segCount?_jsegCount;i=0<=segCount?++_j:--_j){_results.push(data.readUInt16());}return _results;}();idDelta=function(){var _j,_results;_results=[];for(i=_j=0;0<=segCount?_jsegCount;i=0<=segCount?++_j:--_j){_results.push(data.readUInt16());}return _results;}();idRangeOffset=function(){var _j,_results;_results=[];for(i=_j=0;0<=segCount?_jsegCount;i=0<=segCount?++_j:--_j){_results.push(data.readUInt16());}return _results;}();count=(this.length-data.pos+this.offset)/2;glyphIds=function(){var _j,_results;_results=[];for(i=_j=0;0<=count?_jcount;i=0<=count?++_j:--_j){_results.push(data.readUInt16());}return _results;}();for(i=_j=0,_len=endCode.length;_j<_len;i=++_j){tail=endCode[i];start=startCode[i];for(code=_k=start;start<=tail?_k<=tail:_k>=tail;code=start<=tail?++_k:--_k){if(idRangeOffset[i]===0){glyphId=code+idDelta[i];}else{index=idRangeOffset[i]/2+(code-start)-(segCount-i);glyphId=glyphIds[index]||0;if(glyphId!==0){glyphId+=idDelta[i];}}this.codeMap[code]=glyphId&0xffff;}}}data.pos=saveOffset;}CmapEntry.encode=function(charmap,encoding){var charMap,code,codeMap,codes,delta,deltas,diff,endCode,endCodes,entrySelector,glyphIDs,i,id,indexes,last,map,nextID,offset,old,rangeOffsets,rangeShift,result,searchRange,segCount,segCountX2,startCode,startCodes,startGlyph,subtable,_i,_j,_k,_l,_len,_len1,_len2,_len3,_len4,_len5,_len6,_len7,_m,_n,_name,_o,_p,_q;subtable=new Data();codes=Object.keys(charmap).sort(function(a,b){return a-b;});switch(encoding){case"macroman":id=0;indexes=function(){var _i,_results;_results=[];for(i=_i=0;_i<256;i=++_i){_results.push(0);}return _results;}();map={0:0};codeMap={};for(_i=0,_len=codes.length;_i<_len;_i++){code=codes[_i];if(map[_name=charmap[code]]==null){map[_name]=++id;}codeMap[code]={old:charmap[code],new:map[charmap[code]]};indexes[code]=map[charmap[code]];}subtable.writeUInt16(1);subtable.writeUInt16(0);subtable.writeUInt32(12);subtable.writeUInt16(0);subtable.writeUInt16(262);subtable.writeUInt16(0);subtable.write(indexes);return result={charMap:codeMap,subtable:subtable.data,maxGlyphID:id+1};case"unicode":startCodes=[];endCodes=[];nextID=0;map={};charMap={};last=diff=null;for(_j=0,_len1=codes.length;_j<_len1;_j++){code=codes[_j];old=charmap[code];if(map[old]==null){map[old]=++nextID;}charMap[code]={old:old,new:map[old]};delta=map[old]-code;if(last==null||delta!==diff){if(last){endCodes.push(last);}startCodes.push(code);diff=delta;}last=code;}if(last){endCodes.push(last);}endCodes.push(0xffff);startCodes.push(0xffff);segCount=startCodes.length;segCountX2=segCount*2;searchRange=2*Math.pow(Math.log(segCount)/Math.LN2,2);entrySelector=Math.log(searchRange/2)/Math.LN2;rangeShift=2*segCount-searchRange;deltas=[];rangeOffsets=[];glyphIDs=[];for(i=_k=0,_len2=startCodes.length;_k<_len2;i=++_k){startCode=startCodes[i];endCode=endCodes[i];if(startCode===0xffff){deltas.push(0);rangeOffsets.push(0);break;}startGlyph=charMap[startCode]["new"];if(startCode-startGlyph>=0x8000){deltas.push(0);rangeOffsets.push(2*(glyphIDs.length+segCount-i));for(code=_l=startCode;startCode<=endCode?_l<=endCode:_l>=endCode;code=startCode<=endCode?++_l:--_l){glyphIDs.push(charMap[code]["new"]);}}else{deltas.push(startGlyph-startCode);rangeOffsets.push(0);}}subtable.writeUInt16(3);subtable.writeUInt16(1);subtable.writeUInt32(12);subtable.writeUInt16(4);subtable.writeUInt16(16+segCount*8+glyphIDs.length*2);subtable.writeUInt16(0);subtable.writeUInt16(segCountX2);subtable.writeUInt16(searchRange);subtable.writeUInt16(entrySelector);subtable.writeUInt16(rangeShift);for(_m=0,_len3=endCodes.length;_m<_len3;_m++){code=endCodes[_m];subtable.writeUInt16(code);}subtable.writeUInt16(0);for(_n=0,_len4=startCodes.length;_n<_len4;_n++){code=startCodes[_n];subtable.writeUInt16(code);}for(_o=0,_len5=deltas.length;_o<_len5;_o++){delta=deltas[_o];subtable.writeUInt16(delta);}for(_p=0,_len6=rangeOffsets.length;_p<_len6;_p++){offset=rangeOffsets[_p];subtable.writeUInt16(offset);}for(_q=0,_len7=glyphIDs.length;_q<_len7;_q++){id=glyphIDs[_q];subtable.writeUInt16(id);}return result={charMap:charMap,subtable:subtable.data,maxGlyphID:nextID+1};}};return CmapEntry;}();var CmapTable=function(_super){__extends(CmapTable,_super);function CmapTable(){return CmapTable.__super__.constructor.apply(this,arguments);}CmapTable.prototype.tag="cmap";CmapTable.prototype.parse=function(data){var entry,i,tableCount,_i;data.pos=this.offset;this.version=data.readUInt16();tableCount=data.readUInt16();this.tables=[];this.unicode=null;for(i=_i=0;0<=tableCount?_itableCount;i=0<=tableCount?++_i:--_i){entry=new CmapEntry(data,this.offset);this.tables.push(entry);if(entry.isUnicode){if(this.unicode==null){this.unicode=entry;}}}return true;};/*************************************************************************//* function : encode *//* comment : Encode the cmap table corresponding to the input character. *//*************************************************************************/CmapTable.encode=function(charmap,encoding){var result,table;if(encoding==null){encoding="macroman";}result=CmapEntry.encode(charmap,encoding);table=new Data();table.writeUInt16(0);table.writeUInt16(1);result.table=table.data.concat(result.subtable);return result;};return CmapTable;}(Table);var HheaTable=function(_super){__extends(HheaTable,_super);function HheaTable(){return HheaTable.__super__.constructor.apply(this,arguments);}HheaTable.prototype.tag="hhea";HheaTable.prototype.parse=function(data){data.pos=this.offset;this.version=data.readInt();this.ascender=data.readShort();this.decender=data.readShort();this.lineGap=data.readShort();this.advanceWidthMax=data.readShort();this.minLeftSideBearing=data.readShort();this.minRightSideBearing=data.readShort();this.xMaxExtent=data.readShort();this.caretSlopeRise=data.readShort();this.caretSlopeRun=data.readShort();this.caretOffset=data.readShort();data.pos+=4*2;this.metricDataFormat=data.readShort();return this.numberOfMetrics=data.readUInt16();};/*HheaTable.prototype.encode = function (ids) {
var i, table, _i, _ref;
table = new Data;
table.writeInt(this.version);
table.writeShort(this.ascender);
table.writeShort(this.decender);
table.writeShort(this.lineGap);
table.writeShort(this.advanceWidthMax);
table.writeShort(this.minLeftSideBearing);
table.writeShort(this.minRightSideBearing);
table.writeShort(this.xMaxExtent);
table.writeShort(this.caretSlopeRise);
table.writeShort(this.caretSlopeRun);
table.writeShort(this.caretOffset);
for (i = _i = 0, _ref = 4 * 2; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
table.writeByte(0);
}
table.writeShort(this.metricDataFormat);
table.writeUInt16(ids.length);
return table.data;
};*/return HheaTable;}(Table);var OS2Table=function(_super){__extends(OS2Table,_super);function OS2Table(){return OS2Table.__super__.constructor.apply(this,arguments);}OS2Table.prototype.tag="OS/2";OS2Table.prototype.parse=function(data){var i;data.pos=this.offset;this.version=data.readUInt16();this.averageCharWidth=data.readShort();this.weightClass=data.readUInt16();this.widthClass=data.readUInt16();this.type=data.readShort();this.ySubscriptXSize=data.readShort();this.ySubscriptYSize=data.readShort();this.ySubscriptXOffset=data.readShort();this.ySubscriptYOffset=data.readShort();this.ySuperscriptXSize=data.readShort();this.ySuperscriptYSize=data.readShort();this.ySuperscriptXOffset=data.readShort();this.ySuperscriptYOffset=data.readShort();this.yStrikeoutSize=data.readShort();this.yStrikeoutPosition=data.readShort();this.familyClass=data.readShort();this.panose=function(){var _i,_results;_results=[];for(i=_i=0;_i<10;i=++_i){_results.push(data.readByte());}return _results;}();this.charRange=function(){var _i,_results;_results=[];for(i=_i=0;_i<4;i=++_i){_results.push(data.readInt());}return _results;}();this.vendorID=data.readString(4);this.selection=data.readShort();this.firstCharIndex=data.readShort();this.lastCharIndex=data.readShort();if(this.version>0){this.ascent=data.readShort();this.descent=data.readShort();this.lineGap=data.readShort();this.winAscent=data.readShort();this.winDescent=data.readShort();this.codePageRange=function(){var _i,_results;_results=[];for(i=_i=0;_i<2;i=++_i){_results.push(data.readInt());}return _results;}();if(this.version>1){this.xHeight=data.readShort();this.capHeight=data.readShort();this.defaultChar=data.readShort();this.breakChar=data.readShort();return this.maxContext=data.readShort();}}};/*OS2Table.prototype.encode = function () {
return this.raw();
};*/return OS2Table;}(Table);var PostTable=function(_super){__extends(PostTable,_super);function PostTable(){return PostTable.__super__.constructor.apply(this,arguments);}PostTable.prototype.tag="post";PostTable.prototype.parse=function(data){var i,length,numberOfGlyphs,_i,_results;data.pos=this.offset;this.format=data.readInt();this.italicAngle=data.readInt();this.underlinePosition=data.readShort();this.underlineThickness=data.readShort();this.isFixedPitch=data.readInt();this.minMemType42=data.readInt();this.maxMemType42=data.readInt();this.minMemType1=data.readInt();this.maxMemType1=data.readInt();switch(this.format){case 0x00010000:break;case 0x00020000:numberOfGlyphs=data.readUInt16();this.glyphNameIndex=[];for(i=_i=0;0<=numberOfGlyphs?_inumberOfGlyphs;i=0<=numberOfGlyphs?++_i:--_i){this.glyphNameIndex.push(data.readUInt16());}this.names=[];_results=[];while(data.pos_ref;i=0<=_ref?++_j:--_j){_results1.push(data.readUInt32());}return _results1;}.call(this);}};return PostTable;}(Table);/*********************************************************************************************************//* function : NameEntry *//* comment : Store copyright information, platformID, encodingID, and languageID in the NameEntry object.*//*********************************************************************************************************/var NameEntry=function(){function NameEntry(raw,entry){this.raw=raw;this.length=raw.length;this.platformID=entry.platformID;this.encodingID=entry.encodingID;this.languageID=entry.languageID;}return NameEntry;}();var NameTable=function(_super){__extends(NameTable,_super);function NameTable(){return NameTable.__super__.constructor.apply(this,arguments);}NameTable.prototype.tag="name";NameTable.prototype.parse=function(data){var count,entries,entry,format,i,name,stringOffset,strings,text,_i,_j,_len,_name;data.pos=this.offset;format=data.readShort();count=data.readShort();stringOffset=data.readShort();entries=[];for(i=_i=0;0<=count?_icount;i=0<=count?++_i:--_i){entries.push({platformID:data.readShort(),encodingID:data.readShort(),languageID:data.readShort(),nameID:data.readShort(),length:data.readShort(),offset:this.offset+stringOffset+data.readShort()});}strings={};for(i=_j=0,_len=entries.length;_j<_len;i=++_j){entry=entries[i];data.pos=entry.offset;text=data.readString(entry.length);name=new NameEntry(text,entry);if(strings[_name=entry.nameID]==null){strings[_name]=[];}strings[entry.nameID].push(name);}this.strings=strings;this.copyright=strings[0];this.fontFamily=strings[1];this.fontSubfamily=strings[2];this.uniqueSubfamily=strings[3];this.fontName=strings[4];this.version=strings[5];try{this.postscriptName=strings[6][0].raw.replace(/[\x00-\x19\x80-\xff]/g,"");}catch(e){this.postscriptName=strings[4][0].raw.replace(/[\x00-\x19\x80-\xff]/g,"");}this.trademark=strings[7];this.manufacturer=strings[8];this.designer=strings[9];this.description=strings[10];this.vendorUrl=strings[11];this.designerUrl=strings[12];this.license=strings[13];this.licenseUrl=strings[14];this.preferredFamily=strings[15];this.preferredSubfamily=strings[17];this.compatibleFull=strings[18];return this.sampleText=strings[19];};/*NameTable.prototype.encode = function () {
var id, list, nameID, nameTable, postscriptName, strCount, strTable, string, strings, table, val, _i, _len, _ref;
strings = {};
_ref = this.strings;
for (id in _ref) {
val = _ref[id];
strings[id] = val;
}
postscriptName = new NameEntry("" + subsetTag + "+" + this.postscriptName, {
platformID: 1
, encodingID: 0
, languageID: 0
});
strings[6] = [postscriptName];
subsetTag = successorOf(subsetTag);
strCount = 0;
for (id in strings) {
list = strings[id];
if (list != null) {
strCount += list.length;
}
}
table = new Data;
strTable = new Data;
table.writeShort(0);
table.writeShort(strCount);
table.writeShort(6 + 12 * strCount);
for (nameID in strings) {
list = strings[nameID];
if (list != null) {
for (_i = 0, _len = list.length; _i < _len; _i++) {
string = list[_i];
table.writeShort(string.platformID);
table.writeShort(string.encodingID);
table.writeShort(string.languageID);
table.writeShort(nameID);
table.writeShort(string.length);
table.writeShort(strTable.pos);
strTable.writeString(string.raw);
}
}
}
return nameTable = {
postscriptName: postscriptName.raw
, table: table.data.concat(strTable.data)
};
};*/return NameTable;}(Table);var MaxpTable=function(_super){__extends(MaxpTable,_super);function MaxpTable(){return MaxpTable.__super__.constructor.apply(this,arguments);}MaxpTable.prototype.tag="maxp";MaxpTable.prototype.parse=function(data){data.pos=this.offset;this.version=data.readInt();this.numGlyphs=data.readUInt16();this.maxPoints=data.readUInt16();this.maxContours=data.readUInt16();this.maxCompositePoints=data.readUInt16();this.maxComponentContours=data.readUInt16();this.maxZones=data.readUInt16();this.maxTwilightPoints=data.readUInt16();this.maxStorage=data.readUInt16();this.maxFunctionDefs=data.readUInt16();this.maxInstructionDefs=data.readUInt16();this.maxStackElements=data.readUInt16();this.maxSizeOfInstructions=data.readUInt16();this.maxComponentElements=data.readUInt16();return this.maxComponentDepth=data.readUInt16();};/*MaxpTable.prototype.encode = function (ids) {
var table;
table = new Data;
table.writeInt(this.version);
table.writeUInt16(ids.length);
table.writeUInt16(this.maxPoints);
table.writeUInt16(this.maxContours);
table.writeUInt16(this.maxCompositePoints);
table.writeUInt16(this.maxComponentContours);
table.writeUInt16(this.maxZones);
table.writeUInt16(this.maxTwilightPoints);
table.writeUInt16(this.maxStorage);
table.writeUInt16(this.maxFunctionDefs);
table.writeUInt16(this.maxInstructionDefs);
table.writeUInt16(this.maxStackElements);
table.writeUInt16(this.maxSizeOfInstructions);
table.writeUInt16(this.maxComponentElements);
table.writeUInt16(this.maxComponentDepth);
return table.data;
};*/return MaxpTable;}(Table);var HmtxTable=function(_super){__extends(HmtxTable,_super);function HmtxTable(){return HmtxTable.__super__.constructor.apply(this,arguments);}HmtxTable.prototype.tag="hmtx";HmtxTable.prototype.parse=function(data){var i,last,lsbCount,m,_i,_j,_ref,_results;data.pos=this.offset;this.metrics=[];for(i=_i=0,_ref=this.file.hhea.numberOfMetrics;0<=_ref?_i<_ref:_i>_ref;i=0<=_ref?++_i:--_i){this.metrics.push({advance:data.readUInt16(),lsb:data.readInt16()});}lsbCount=this.file.maxp.numGlyphs-this.file.hhea.numberOfMetrics;this.leftSideBearings=function(){var _j,_results;_results=[];for(i=_j=0;0<=lsbCount?_jlsbCount;i=0<=lsbCount?++_j:--_j){_results.push(data.readInt16());}return _results;}();this.widths=function(){var _j,_len,_ref1,_results;_ref1=this.metrics;_results=[];for(_j=0,_len=_ref1.length;_j<_len;_j++){m=_ref1[_j];_results.push(m.advance);}return _results;}.call(this);last=this.widths[this.widths.length-1];_results=[];for(i=_j=0;0<=lsbCount?_jlsbCount;i=0<=lsbCount?++_j:--_j){_results.push(this.widths.push(last));}return _results;};/***************************************************************//* function : forGlyph *//* comment : Returns the advance width and lsb for this glyph. *//***************************************************************/HmtxTable.prototype.forGlyph=function(id){var metrics;if(id in this.metrics){return this.metrics[id];}return metrics={advance:this.metrics[this.metrics.length-1].advance,lsb:this.leftSideBearings[id-this.metrics.length]};};/*HmtxTable.prototype.encode = function (mapping) {
var id, metric, table, _i, _len;
table = new Data;
for (_i = 0, _len = mapping.length; _i < _len; _i++) {
id = mapping[_i];
metric = this.forGlyph(id);
table.writeUInt16(metric.advance);
table.writeUInt16(metric.lsb);
}
return table.data;
};*/return HmtxTable;}(Table);var __slice=[].slice;var GlyfTable=function(_super){__extends(GlyfTable,_super);function GlyfTable(){return GlyfTable.__super__.constructor.apply(this,arguments);}GlyfTable.prototype.tag="glyf";GlyfTable.prototype.parse=function(data){return this.cache={};};GlyfTable.prototype.glyphFor=function(id){id=id;var data,index,length,loca,numberOfContours,raw,xMax,xMin,yMax,yMin;if(id in this.cache){return this.cache[id];}loca=this.file.loca;data=this.file.contents;index=loca.indexOf(id);length=loca.lengthOf(id);if(length===0){return this.cache[id]=null;}data.pos=this.offset+index;raw=new Data(data.read(length));numberOfContours=raw.readShort();xMin=raw.readShort();yMin=raw.readShort();xMax=raw.readShort();yMax=raw.readShort();if(numberOfContours===-1){this.cache[id]=new CompoundGlyph(raw,xMin,yMin,xMax,yMax);}else{this.cache[id]=new SimpleGlyph(raw,numberOfContours,xMin,yMin,xMax,yMax);}return this.cache[id];};GlyfTable.prototype.encode=function(glyphs,mapping,old2new){var glyph,id,offsets,table,_i,_len;table=[];offsets=[];for(_i=0,_len=mapping.length;_i<_len;_i++){id=mapping[_i];glyph=glyphs[id];offsets.push(table.length);if(glyph){table=table.concat(glyph.encode(old2new));}}offsets.push(table.length);return{table:table,offsets:offsets};};return GlyfTable;}(Table);var SimpleGlyph=function(){/**************************************************************************//* function : SimpleGlyph *//* comment : Stores raw, xMin, yMin, xMax, and yMax values for this glyph.*//**************************************************************************/function SimpleGlyph(raw,numberOfContours,xMin,yMin,xMax,yMax){this.raw=raw;this.numberOfContours=numberOfContours;this.xMin=xMin;this.yMin=yMin;this.xMax=xMax;this.yMax=yMax;this.compound=false;}SimpleGlyph.prototype.encode=function(){return this.raw.data;};return SimpleGlyph;}();var CompoundGlyph=function(){var ARG_1_AND_2_ARE_WORDS,MORE_COMPONENTS,WE_HAVE_AN_X_AND_Y_SCALE,WE_HAVE_A_SCALE,WE_HAVE_A_TWO_BY_TWO;ARG_1_AND_2_ARE_WORDS=0x0001;WE_HAVE_A_SCALE=0x0008;MORE_COMPONENTS=0x0020;WE_HAVE_AN_X_AND_Y_SCALE=0x0040;WE_HAVE_A_TWO_BY_TWO=0x0080;/********************************************************************************************************************//* function : CompoundGlypg generator *//* comment : It stores raw, xMin, yMin, xMax, yMax, glyph id, and glyph offset for the corresponding compound glyph.*//********************************************************************************************************************/function CompoundGlyph(raw,xMin,yMin,xMax,yMax){var data,flags;this.raw=raw;this.xMin=xMin;this.yMin=yMin;this.xMax=xMax;this.yMax=yMax;this.compound=true;this.glyphIDs=[];this.glyphOffsets=[];data=this.raw;while(true){flags=data.readShort();this.glyphOffsets.push(data.pos);this.glyphIDs.push(data.readShort());if(!(flags&MORE_COMPONENTS)){break;}if(flags&ARG_1_AND_2_ARE_WORDS){data.pos+=4;}else{data.pos+=2;}if(flags&WE_HAVE_A_TWO_BY_TWO){data.pos+=8;}else if(flags&WE_HAVE_AN_X_AND_Y_SCALE){data.pos+=4;}else if(flags&WE_HAVE_A_SCALE){data.pos+=2;}}}/****************************************************************************************************************//* function : CompoundGlypg encode *//* comment : After creating a table for the characters you typed, you call directory.encode to encode the table.*//****************************************************************************************************************/CompoundGlyph.prototype.encode=function(mapping){var i,id,result,_i,_len,_ref;result=new Data(__slice.call(this.raw.data));_ref=this.glyphIDs;for(i=_i=0,_len=_ref.length;_i<_len;i=++_i){id=_ref[i];result.pos=this.glyphOffsets[i];}return result.data;};return CompoundGlyph;}();var LocaTable=function(_super){__extends(LocaTable,_super);function LocaTable(){return LocaTable.__super__.constructor.apply(this,arguments);}LocaTable.prototype.tag="loca";LocaTable.prototype.parse=function(data){var format,i;data.pos=this.offset;format=this.file.head.indexToLocFormat;if(format===0){return this.offsets=function(){var _i,_ref,_results;_results=[];for(i=_i=0,_ref=this.length;_i<_ref;i=_i+=2){_results.push(data.readUInt16()*2);}return _results;}.call(this);}else{return this.offsets=function(){var _i,_ref,_results;_results=[];for(i=_i=0,_ref=this.length;_i<_ref;i=_i+=4){_results.push(data.readUInt32());}return _results;}.call(this);}};LocaTable.prototype.indexOf=function(id){return this.offsets[id];};LocaTable.prototype.lengthOf=function(id){return this.offsets[id+1]-this.offsets[id];};LocaTable.prototype.encode=function(offsets,activeGlyphs){var LocaTable=new Uint32Array(this.offsets.length);var glyfPtr=0;var listGlyf=0;for(var k=0;k0){glyfPtr+=len;}}}var newLocaTable=new Array(LocaTable.length*4);for(var j=0;j>8;newLocaTable[4*j+1]=(LocaTable[j]&0x00ff0000)>>16;newLocaTable[4*j]=(LocaTable[j]&0xff000000)>>24;}return newLocaTable;};return LocaTable;}(Table);/************************************************************************************//* function : invert *//* comment : Change the object's (key: value) to create an object with (value: key).*//************************************************************************************/var invert=function invert(object){var key,ret,val;ret={};for(key in object){val=object[key];ret[val]=key;}return ret;};/*var successorOf = function (input) {
var added, alphabet, carry, i, index, isUpperCase, last, length, next, result;
alphabet = 'abcdefghijklmnopqrstuvwxyz';
length = alphabet.length;
result = input;
i = input.length;
while (i >= 0) {
last = input.charAt(--i);
if (isNaN(last)) {
index = alphabet.indexOf(last.toLowerCase());
if (index === -1) {
next = last;
carry = true;
}
else {
next = alphabet.charAt((index + 1) % length);
isUpperCase = last === last.toUpperCase();
if (isUpperCase) {
next = next.toUpperCase();
}
carry = index + 1 >= length;
if (carry && i === 0) {
added = isUpperCase ? 'A' : 'a';
result = added + next + result.slice(1);
break;
}
}
}
else {
next = +last + 1;
carry = next > 9;
if (carry) {
next = 0;
}
if (carry && i === 0) {
result = '1' + next + result.slice(1);
break;
}
}
result = result.slice(0, i) + next + result.slice(i + 1);
if (!carry) {
break;
}
}
return result;
};*/var Subset=function(){function Subset(font){this.font=font;this.subset={};this.unicodes={};this.next=33;}/*Subset.prototype.use = function (character) {
var i, _i, _ref;
if (typeof character === 'string') {
for (i = _i = 0, _ref = character.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
this.use(character.charCodeAt(i));
}
return;
}
if (!this.unicodes[character]) {
this.subset[this.next] = character;
return this.unicodes[character] = this.next++;
}
};*//*Subset.prototype.encodeText = function (text) {
var char, i, string, _i, _ref;
string = '';
for (i = _i = 0, _ref = text.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) {
char = this.unicodes[text.charCodeAt(i)];
string += String.fromCharCode(char);
}
return string;
};*//***************************************************************//* function : generateCmap *//* comment : Returns the unicode cmap for this font. *//***************************************************************/Subset.prototype.generateCmap=function(){var mapping,roman,unicode,unicodeCmap,_ref;unicodeCmap=this.font.cmap.tables[0].codeMap;mapping={};_ref=this.subset;for(roman in _ref){unicode=_ref[roman];mapping[roman]=unicodeCmap[unicode];}return mapping;};/*Subset.prototype.glyphIDs = function () {
var ret, roman, unicode, unicodeCmap, val, _ref;
unicodeCmap = this.font.cmap.tables[0].codeMap;
ret = [0];
_ref = this.subset;
for (roman in _ref) {
unicode = _ref[roman];
val = unicodeCmap[unicode];
if ((val != null) && __indexOf.call(ret, val) < 0) {
ret.push(val);
}
}
return ret.sort();
};*//******************************************************************//* function : glyphsFor *//* comment : Returns simple glyph objects for the input character.*//******************************************************************/Subset.prototype.glyphsFor=function(glyphIDs){var additionalIDs,glyph,glyphs,id,_i,_len,_ref;glyphs={};for(_i=0,_len=glyphIDs.length;_i<_len;_i++){id=glyphIDs[_i];glyphs[id]=this.font.glyf.glyphFor(id);}additionalIDs=[];for(id in glyphs){glyph=glyphs[id];if(glyph!=null?glyph.compound:void 0){additionalIDs.push.apply(additionalIDs,glyph.glyphIDs);}}if(additionalIDs.length>0){_ref=this.glyphsFor(additionalIDs);for(id in _ref){glyph=_ref[id];glyphs[id]=glyph;}}return glyphs;};/***************************************************************//* function : encode *//* comment : Encode various tables for the characters you use. *//***************************************************************/Subset.prototype.encode=function(glyID,indexToLocFormat){var cmap,code,glyf,glyphs,id,ids,loca,new2old,newIDs,nextGlyphID,old2new,oldID,oldIDs,tables,_ref;cmap=CmapTable.encode(this.generateCmap(),"unicode");glyphs=this.glyphsFor(glyID);old2new={0:0};_ref=cmap.charMap;for(code in _ref){ids=_ref[code];old2new[ids.old]=ids["new"];}nextGlyphID=cmap.maxGlyphID;for(oldID in glyphs){if(!(oldID in old2new)){old2new[oldID]=nextGlyphID++;}}new2old=invert(old2new);newIDs=Object.keys(new2old).sort(function(a,b){return a-b;});oldIDs=function(){var _i,_len,_results;_results=[];for(_i=0,_len=newIDs.length;_i<_len;_i++){id=newIDs[_i];_results.push(new2old[id]);}return _results;}();glyf=this.font.glyf.encode(glyphs,oldIDs,old2new);loca=this.font.loca.encode(glyf.offsets,oldIDs);tables={cmap:this.font.cmap.raw(),glyf:glyf.table,loca:loca,hmtx:this.font.hmtx.raw(),hhea:this.font.hhea.raw(),maxp:this.font.maxp.raw(),post:this.font.post.raw(),name:this.font.name.raw(),head:this.font.head.encode(indexToLocFormat)};if(this.font.os2.exists){tables["OS/2"]=this.font.os2.raw();}return this.font.directory.encode(tables);};return Subset;}();jsPDF.API.PDFObject=function(){var pad;function PDFObject(){}pad=function pad(str,length){return(Array(length+1).join("0")+str).slice(-length);};/*****************************************************************************//* function : convert *//* comment :Converts pdf tag's / FontBBox and array values in / W to strings *//*****************************************************************************/PDFObject.convert=function(object){var e,items,key,out,val;if(Array.isArray(object)){items=function(){var _i,_len,_results;_results=[];for(_i=0,_len=object.length;_i<_len;_i++){e=object[_i];_results.push(PDFObject.convert(e));}return _results;}().join(" ");return"["+items+"]";}else if(typeof object==="string"){return"/"+object;}else if(object!=null?object.isString:void 0){return"("+object+")";}else if(object instanceof Date){return"(D:"+pad(object.getUTCFullYear(),4)+pad(object.getUTCMonth(),2)+pad(object.getUTCDate(),2)+pad(object.getUTCHours(),2)+pad(object.getUTCMinutes(),2)+pad(object.getUTCSeconds(),2)+"Z)";}else if({}.toString.call(object)==="[object Object]"){out=["<<"];for(key in object){val=object[key];out.push("/"+key+" "+PDFObject.convert(val));}out.push(">>");return out.join("\n");}else{return""+object;}};return PDFObject;}();})(jsPDF);// Generated by CoffeeScript 1.4.0
/*
# PNG.js
# Copyright (c) 2011 Devon Govett
# MIT LICENSE
#
#
*/(function(global){var PNG;PNG=function(){var APNG_BLEND_OP_SOURCE,APNG_DISPOSE_OP_BACKGROUND,APNG_DISPOSE_OP_PREVIOUS,makeImage,scratchCanvas,scratchCtx;PNG.load=function(url,canvas,callback){var xhr;if(typeof canvas==="function"){callback=canvas;}xhr=new XMLHttpRequest();xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=function(){var data,png;data=new Uint8Array(xhr.response||xhr.mozResponseArrayBuffer);png=new PNG(data);if(typeof(canvas!=null?canvas.getContext:void 0)==="function"){png.render(canvas);}return typeof callback==="function"?callback(png):void 0;};return xhr.send(null);};APNG_DISPOSE_OP_BACKGROUND=1;APNG_DISPOSE_OP_PREVIOUS=2;APNG_BLEND_OP_SOURCE=0;function PNG(data){var chunkSize,colors,palLen,delayDen,delayNum,frame,i,index,key,section,palShort,text,_i,_j,_ref;this.data=data;this.pos=8;this.palette=[];this.imgData=[];this.transparency={};this.animation=null;this.text={};frame=null;while(true){chunkSize=this.readUInt32();section=function(){var _i,_results;_results=[];for(i=_i=0;_i<4;i=++_i){_results.push(String.fromCharCode(this.data[this.pos++]));}return _results;}.call(this).join("");switch(section){case"IHDR":this.width=this.readUInt32();this.height=this.readUInt32();this.bits=this.data[this.pos++];this.colorType=this.data[this.pos++];this.compressionMethod=this.data[this.pos++];this.filterMethod=this.data[this.pos++];this.interlaceMethod=this.data[this.pos++];break;case"acTL":this.animation={numFrames:this.readUInt32(),numPlays:this.readUInt32()||Infinity,frames:[]};break;case"PLTE":this.palette=this.read(chunkSize);break;case"fcTL":if(frame){this.animation.frames.push(frame);}this.pos+=4;frame={width:this.readUInt32(),height:this.readUInt32(),xOffset:this.readUInt32(),yOffset:this.readUInt32()};delayNum=this.readUInt16();delayDen=this.readUInt16()||100;frame.delay=1000*delayNum/delayDen;frame.disposeOp=this.data[this.pos++];frame.blendOp=this.data[this.pos++];frame.data=[];break;case"IDAT":case"fdAT":if(section==="fdAT"){this.pos+=4;chunkSize-=4;}data=(frame!=null?frame.data:void 0)||this.imgData;for(i=_i=0;0<=chunkSize?_ichunkSize;i=0<=chunkSize?++_i:--_i){data.push(this.data[this.pos++]);}break;case"tRNS":this.transparency={};switch(this.colorType){case 3:palLen=this.palette.length/3;this.transparency.indexed=this.read(chunkSize);if(this.transparency.indexed.length>palLen)throw new Error("More transparent colors than palette size");/*
* According to the PNG spec trns should be increased to the same size as palette if shorter
*///palShort = 255 - this.transparency.indexed.length;
palShort=palLen-this.transparency.indexed.length;if(palShort>0){for(i=_j=0;0<=palShort?_jpalShort;i=0<=palShort?++_j:--_j){this.transparency.indexed.push(255);}}break;case 0:this.transparency.grayscale=this.read(chunkSize)[0];break;case 2:this.transparency.rgb=this.read(chunkSize);}break;case"tEXt":text=this.read(chunkSize);index=text.indexOf(0);key=String.fromCharCode.apply(String,text.slice(0,index));this.text[key]=String.fromCharCode.apply(String,text.slice(index+1));break;case"IEND":if(frame){this.animation.frames.push(frame);}this.colors=function(){switch(this.colorType){case 0:case 3:case 4:return 1;case 2:case 6:return 3;}}.call(this);this.hasAlphaChannel=(_ref=this.colorType)===4||_ref===6;colors=this.colors+(this.hasAlphaChannel?1:0);this.pixelBitlength=this.bits*colors;this.colorSpace=function(){switch(this.colors){case 1:return"DeviceGray";case 3:return"DeviceRGB";}}.call(this);this.imgData=new Uint8Array(this.imgData);return;default:this.pos+=chunkSize;}this.pos+=4;if(this.pos>this.data.length){throw new Error("Incomplete or corrupt PNG file");}}return;}PNG.prototype.read=function(bytes){var i,_i,_results;_results=[];for(i=_i=0;0<=bytes?_ibytes;i=0<=bytes?++_i:--_i){_results.push(this.data[this.pos++]);}return _results;};PNG.prototype.readUInt32=function(){var b1,b2,b3,b4;b1=this.data[this.pos++]<<24;b2=this.data[this.pos++]<<16;b3=this.data[this.pos++]<<8;b4=this.data[this.pos++];return b1|b2|b3|b4;};PNG.prototype.readUInt16=function(){var b1,b2;b1=this.data[this.pos++]<<8;b2=this.data[this.pos++];return b1|b2;};PNG.prototype.decodePixels=function(data){var pixelBytes=this.pixelBitlength/8;var fullPixels=new Uint8Array(this.width*this.height*pixelBytes);var pos=0;var _this=this;if(data==null){data=this.imgData;}if(data.length===0){return new Uint8Array(0);}data=new FlateStream(data);data=data.getBytes();function pass(x0,y0,dx,dy){var abyte,c,col,i,left,length,p,pa,paeth,pb,pc,pixels,row,scanlineLength,upper,upperLeft,_i,_j,_k,_l,_m;var w=Math.ceil((_this.width-x0)/dx),h=Math.ceil((_this.height-y0)/dy);var isFull=_this.width==w&&_this.height==h;scanlineLength=pixelBytes*w;pixels=isFull?fullPixels:new Uint8Array(scanlineLength*h);length=data.length;row=0;c=0;while(row1&&frameNumber/numFrames
* Chris G Jones
* Shaon Barman
* Vivien Nicolas <21@vingtetun.org>
* Justin D'Arcangelo
* Yury Delendik
*
*
*/var DecodeStream=function(){function constructor(){this.pos=0;this.bufferLength=0;this.eof=false;this.buffer=null;}constructor.prototype={ensureBuffer:function decodestream_ensureBuffer(requested){var buffer=this.buffer;var current=buffer?buffer.byteLength:0;if(requestedbufEnd)end=bufEnd;}else{while(!this.eof){this.readBlock();}var end=this.bufferLength;}this.pos=end;return this.buffer.subarray(pos,end);},lookChar:function decodestream_lookChar(){var pos=this.pos;while(this.bufferLength<=pos){if(this.eof)return null;this.readBlock();}return String.fromCharCode(this.buffer[this.pos]);},getChar:function decodestream_getChar(){var pos=this.pos;while(this.bufferLength<=pos){if(this.eof)return null;this.readBlock();}return String.fromCharCode(this.buffer[this.pos++]);},makeSubStream:function decodestream_makeSubstream(start,length,dict){var end=start+length;while(this.bufferLength<=end&&!this.eof){this.readBlock();}return new Stream(this.buffer,start,length,dict);},skip:function decodestream_skip(n){if(!n)n=1;this.pos+=n;},reset:function decodestream_reset(){this.pos=0;}};return constructor;}();var FlateStream=function(){if(typeof Uint32Array==="undefined"){return undefined;}var codeLenCodeMap=new Uint32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);var lengthDecode=new Uint32Array([0x00003,0x00004,0x00005,0x00006,0x00007,0x00008,0x00009,0x0000a,0x1000b,0x1000d,0x1000f,0x10011,0x20013,0x20017,0x2001b,0x2001f,0x30023,0x3002b,0x30033,0x3003b,0x40043,0x40053,0x40063,0x40073,0x50083,0x500a3,0x500c3,0x500e3,0x00102,0x00102,0x00102]);var distDecode=new Uint32Array([0x00001,0x00002,0x00003,0x00004,0x10005,0x10007,0x20009,0x2000d,0x30011,0x30019,0x40021,0x40031,0x50041,0x50061,0x60081,0x600c1,0x70101,0x70181,0x80201,0x80301,0x90401,0x90601,0xa0801,0xa0c01,0xb1001,0xb1801,0xc2001,0xc3001,0xd4001,0xd6001]);var fixedLitCodeTab=[new Uint32Array([0x70100,0x80050,0x80010,0x80118,0x70110,0x80070,0x80030,0x900c0,0x70108,0x80060,0x80020,0x900a0,0x80000,0x80080,0x80040,0x900e0,0x70104,0x80058,0x80018,0x90090,0x70114,0x80078,0x80038,0x900d0,0x7010c,0x80068,0x80028,0x900b0,0x80008,0x80088,0x80048,0x900f0,0x70102,0x80054,0x80014,0x8011c,0x70112,0x80074,0x80034,0x900c8,0x7010a,0x80064,0x80024,0x900a8,0x80004,0x80084,0x80044,0x900e8,0x70106,0x8005c,0x8001c,0x90098,0x70116,0x8007c,0x8003c,0x900d8,0x7010e,0x8006c,0x8002c,0x900b8,0x8000c,0x8008c,0x8004c,0x900f8,0x70101,0x80052,0x80012,0x8011a,0x70111,0x80072,0x80032,0x900c4,0x70109,0x80062,0x80022,0x900a4,0x80002,0x80082,0x80042,0x900e4,0x70105,0x8005a,0x8001a,0x90094,0x70115,0x8007a,0x8003a,0x900d4,0x7010d,0x8006a,0x8002a,0x900b4,0x8000a,0x8008a,0x8004a,0x900f4,0x70103,0x80056,0x80016,0x8011e,0x70113,0x80076,0x80036,0x900cc,0x7010b,0x80066,0x80026,0x900ac,0x80006,0x80086,0x80046,0x900ec,0x70107,0x8005e,0x8001e,0x9009c,0x70117,0x8007e,0x8003e,0x900dc,0x7010f,0x8006e,0x8002e,0x900bc,0x8000e,0x8008e,0x8004e,0x900fc,0x70100,0x80051,0x80011,0x80119,0x70110,0x80071,0x80031,0x900c2,0x70108,0x80061,0x80021,0x900a2,0x80001,0x80081,0x80041,0x900e2,0x70104,0x80059,0x80019,0x90092,0x70114,0x80079,0x80039,0x900d2,0x7010c,0x80069,0x80029,0x900b2,0x80009,0x80089,0x80049,0x900f2,0x70102,0x80055,0x80015,0x8011d,0x70112,0x80075,0x80035,0x900ca,0x7010a,0x80065,0x80025,0x900aa,0x80005,0x80085,0x80045,0x900ea,0x70106,0x8005d,0x8001d,0x9009a,0x70116,0x8007d,0x8003d,0x900da,0x7010e,0x8006d,0x8002d,0x900ba,0x8000d,0x8008d,0x8004d,0x900fa,0x70101,0x80053,0x80013,0x8011b,0x70111,0x80073,0x80033,0x900c6,0x70109,0x80063,0x80023,0x900a6,0x80003,0x80083,0x80043,0x900e6,0x70105,0x8005b,0x8001b,0x90096,0x70115,0x8007b,0x8003b,0x900d6,0x7010d,0x8006b,0x8002b,0x900b6,0x8000b,0x8008b,0x8004b,0x900f6,0x70103,0x80057,0x80017,0x8011f,0x70113,0x80077,0x80037,0x900ce,0x7010b,0x80067,0x80027,0x900ae,0x80007,0x80087,0x80047,0x900ee,0x70107,0x8005f,0x8001f,0x9009e,0x70117,0x8007f,0x8003f,0x900de,0x7010f,0x8006f,0x8002f,0x900be,0x8000f,0x8008f,0x8004f,0x900fe,0x70100,0x80050,0x80010,0x80118,0x70110,0x80070,0x80030,0x900c1,0x70108,0x80060,0x80020,0x900a1,0x80000,0x80080,0x80040,0x900e1,0x70104,0x80058,0x80018,0x90091,0x70114,0x80078,0x80038,0x900d1,0x7010c,0x80068,0x80028,0x900b1,0x80008,0x80088,0x80048,0x900f1,0x70102,0x80054,0x80014,0x8011c,0x70112,0x80074,0x80034,0x900c9,0x7010a,0x80064,0x80024,0x900a9,0x80004,0x80084,0x80044,0x900e9,0x70106,0x8005c,0x8001c,0x90099,0x70116,0x8007c,0x8003c,0x900d9,0x7010e,0x8006c,0x8002c,0x900b9,0x8000c,0x8008c,0x8004c,0x900f9,0x70101,0x80052,0x80012,0x8011a,0x70111,0x80072,0x80032,0x900c5,0x70109,0x80062,0x80022,0x900a5,0x80002,0x80082,0x80042,0x900e5,0x70105,0x8005a,0x8001a,0x90095,0x70115,0x8007a,0x8003a,0x900d5,0x7010d,0x8006a,0x8002a,0x900b5,0x8000a,0x8008a,0x8004a,0x900f5,0x70103,0x80056,0x80016,0x8011e,0x70113,0x80076,0x80036,0x900cd,0x7010b,0x80066,0x80026,0x900ad,0x80006,0x80086,0x80046,0x900ed,0x70107,0x8005e,0x8001e,0x9009d,0x70117,0x8007e,0x8003e,0x900dd,0x7010f,0x8006e,0x8002e,0x900bd,0x8000e,0x8008e,0x8004e,0x900fd,0x70100,0x80051,0x80011,0x80119,0x70110,0x80071,0x80031,0x900c3,0x70108,0x80061,0x80021,0x900a3,0x80001,0x80081,0x80041,0x900e3,0x70104,0x80059,0x80019,0x90093,0x70114,0x80079,0x80039,0x900d3,0x7010c,0x80069,0x80029,0x900b3,0x80009,0x80089,0x80049,0x900f3,0x70102,0x80055,0x80015,0x8011d,0x70112,0x80075,0x80035,0x900cb,0x7010a,0x80065,0x80025,0x900ab,0x80005,0x80085,0x80045,0x900eb,0x70106,0x8005d,0x8001d,0x9009b,0x70116,0x8007d,0x8003d,0x900db,0x7010e,0x8006d,0x8002d,0x900bb,0x8000d,0x8008d,0x8004d,0x900fb,0x70101,0x80053,0x80013,0x8011b,0x70111,0x80073,0x80033,0x900c7,0x70109,0x80063,0x80023,0x900a7,0x80003,0x80083,0x80043,0x900e7,0x70105,0x8005b,0x8001b,0x90097,0x70115,0x8007b,0x8003b,0x900d7,0x7010d,0x8006b,0x8002b,0x900b7,0x8000b,0x8008b,0x8004b,0x900f7,0x70103,0x80057,0x80017,0x8011f,0x70113,0x80077,0x80037,0x900cf,0x7010b,0x80067,0x80027,0x900af,0x80007,0x80087,0x80047,0x900ef,0x70107,0x8005f,0x8001f,0x9009f,0x70117,0x8007f,0x8003f,0x900df,0x7010f,0x8006f,0x8002f,0x900bf,0x8000f,0x8008f,0x8004f,0x900ff]),9];var fixedDistCodeTab=[new Uint32Array([0x50000,0x50010,0x50008,0x50018,0x50004,0x50014,0x5000c,0x5001c,0x50002,0x50012,0x5000a,0x5001a,0x50006,0x50016,0x5000e,0x00000,0x50001,0x50011,0x50009,0x50019,0x50005,0x50015,0x5000d,0x5001d,0x50003,0x50013,0x5000b,0x5001b,0x50007,0x50017,0x5000f,0x00000]),5];function error(e){throw new Error(e);}function constructor(bytes){//var bytes = stream.getBytes();
var bytesPos=0;var cmf=bytes[bytesPos++];var flg=bytes[bytesPos++];if(cmf==-1||flg==-1)error("Invalid header in flate stream");if((cmf&0x0f)!=0x08)error("Unknown compression method in flate stream");if(((cmf<<8)+flg)%31!=0)error("Bad FCHECK in flate stream");if(flg&0x20)error("FDICT bit set in flate stream");this.bytes=bytes;this.bytesPos=bytesPos;this.codeSize=0;this.codeBuf=0;DecodeStream.call(this);}constructor.prototype=Object.create(DecodeStream.prototype);constructor.prototype.getBits=function(bits){var codeSize=this.codeSize;var codeBuf=this.codeBuf;var bytes=this.bytes;var bytesPos=this.bytesPos;var b;while(codeSize>bits;this.codeSize=codeSize-=bits;this.bytesPos=bytesPos;return b;};constructor.prototype.getCode=function(table){var codes=table[0];var maxLen=table[1];var codeSize=this.codeSize;var codeBuf=this.codeBuf;var bytes=this.bytes;var bytesPos=this.bytesPos;while(codeSize>16;var codeVal=code&0xffff;if(codeSize==0||codeSize>codeLen;this.codeSize=codeSize-codeLen;this.bytesPos=bytesPos;return codeVal;};constructor.prototype.generateHuffmanTable=function(lengths){var n=lengths.length;// find max code length
var maxLen=0;for(var i=0;imaxLen)maxLen=lengths[i];}// build the table
var size=1<>=1;}// fill the table entries
for(var i=code2;i0){array[i++]=what;}}// read block header
var hdr=this.getBits(3);if(hdr&1)this.eof=true;hdr>>=1;if(hdr==0){// uncompressed block
var bytes=this.bytes;var bytesPos=this.bytesPos;var b;if(typeof(b=bytes[bytesPos++])=="undefined")error("Bad block header in flate stream");var blockLen=b;if(typeof(b=bytes[bytesPos++])=="undefined")error("Bad block header in flate stream");blockLen|=b<<8;if(typeof(b=bytes[bytesPos++])=="undefined")error("Bad block header in flate stream");var check=b;if(typeof(b=bytes[bytesPos++])=="undefined")error("Bad block header in flate stream");check|=b<<8;if(check!=(~blockLen&0xffff))error("Bad uncompressed block length in flate stream");this.codeBuf=0;this.codeSize=0;var bufferLength=this.bufferLength;var buffer=this.ensureBuffer(bufferLength+blockLen);var end=bufferLength+blockLen;this.bufferLength=end;for(var n=bufferLength;n=limit){buffer=this.ensureBuffer(pos+1);limit=buffer.length;}buffer[pos++]=code1;continue;}if(code1==256){this.bufferLength=pos;return;}code1-=257;code1=lengthDecode[code1];var code2=code1>>16;if(code2>0)code2=this.getBits(code2);var len=(code1&0xffff)+code2;code1=this.getCode(distCodeTable);code1=distDecode[code1];code2=code1>>16;if(code2>0)code2=this.getBits(code2);var dist=(code1&0xffff)+code2;if(pos+len>=limit){buffer=this.ensureBuffer(pos+len);limit=buffer.length;}for(var k=0;k