/* * * A canvas to PDF converter. Uses a mock canvas context to build a PDF document. * * Licensed under the MIT license: * http://www.opensource.org/licenses/mit-license.php * * Author: * Joshua Gould * * @license Copyright (c) 2017 Joshua Gould */ (function(global){"use strict";var canvas2pdf=typeof canvas2pdf!=="undefined"?canvas2pdf:{};global.canvas2pdf=canvas2pdf;const pendingFonts=new Set;const fonts={};const fontsLoadedCallbacks=[];canvas2pdf.setFontPath=function(fontPath){canvas2pdf.fontPath=fontPath};canvas2pdf.runAfterFontsLoaded=function(callback){try{callback()}catch(e){console.log("will retry after fonts loaded: "+e);fontsLoadedCallbacks.push(callback)}};canvas2pdf.addFonts=function(json){Object.assign(fonts,json);Object.keys(json).forEach((name=>pendingFonts.delete(name)));if(!pendingFonts.size){const callbacks=[...fontsLoadedCallbacks];fontsLoadedCallbacks.splice(0);callbacks.forEach(canvas2pdf.runAfterFontsLoaded)}};function hslToHex(h,s,l,a){h=h%360+(h<0)*360;s=isNaN(h)||isNaN(s)?0:s;var m2=l+(l<.5?l:1-l)*s;var m1=2*l-m2;return rgbToPdf(hsl2rgb(h>=240?h-240:h+120,m1,m2),hsl2rgb(h,m1,m2),hsl2rgb(h<120?h+240:h-120,m1,m2),a)}function hsl2rgb(h,m1,m2){return(h<60?m1+(m2-m1)*h/60:h<180?m2:h<240?m1+(m2-m1)*(240-h)/60:m1)*255}var reI="\\s*([+-]?\\d+)\\s*",reN="\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*",reP="\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*",reRgbInteger=new RegExp("^rgb\\("+[reI,reI,reI]+"\\)$"),reRgbPercent=new RegExp("^rgb\\("+[reP,reP,reP]+"\\)$"),reRgbaInteger=new RegExp("^rgba\\("+[reI,reI,reI,reN]+"\\)$"),reRgbaPercent=new RegExp("^rgba\\("+[reP,reP,reP,reN]+"\\)$"),reHslPercent=new RegExp("^hsl\\("+[reN,reP,reP]+"\\)$"),reHslaPercent=new RegExp("^hsla\\("+[reN,reP,reP,reN]+"\\)$");var rgbToPdf=function(r,g,b,a){return{c:r/255+" "+g/255+" "+b/255,a:a}};var fixColor=function(value){if(!value){return{c:"0 0 0",a:1}}if(!value.toString().startsWith("rgb")&&!value.toString().startsWith("hsl")){var d=document.createElement("div");d.style.color=value;document.body.appendChild(d);value=window.getComputedStyle(d).color+"";document.body.removeChild(d)}value=value.replace(/\s/g,"");var m;var format=(value+"").trim().toLowerCase();if(m=reRgbInteger.exec(format)){return rgbToPdf(m[1],m[2],m[3],1)}else if(m=reRgbPercent.exec(format)){return rgbToPdf(m[1]*255/100,m[2]*255/100,m[3]*255/100,1)}else if(m=reRgbaInteger.exec(format)){return rgbToPdf(m[1],m[2],m[3],m[4])}else if(m=reRgbaPercent.exec(format)){return rgbToPdf(m[1]*255/100,m[2]*255/100,m[3]*255/100,m[4])}else if(m=reHslPercent.exec(format)){return hslToHex(m[1],m[2]/100,m[3]/100)}else if(m=reHslaPercent.exec(format)){return hslToHex(m[1],m[2]/100,m[3]/100,m[4])}else{return{c:value,a:1}}};canvas2pdf.PdfContext=function(width,height,pageOptions){var _this=this;var doc=new PDFKitMini;this.doc=doc;var canvas=document.createElement("canvas");this.context=canvas.getContext("2d");doc.pageSetWidth(width/72);doc.pageSetHeight(height/72);doc.addPage(pageOptions);var fontValue="10px Helvetica";this.textAlign="left";this.textBaseline="alphabetic";var parseFont=function(){var regex=/^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-_,\'\"\sa-z0-9]+?)\s*$/i;var fontPart=regex.exec(_this.font);if(!fontPart){console.log("error parsing font "+_this.font);fontPart=regex.exec("10px Helvetica")}if(fontPart[6].indexOf("sans-serif")>-1){fontPart[6]="Helvetica"}if(fontPart[6].indexOf("serif")>-1){fontPart[6]="Times-Roman"}var data={style:fontPart[1]||"normal",size:parseInt(fontPart[4])||10,family:fontPart[6]||"Helvetica",weight:fontPart[3]||"normal"};return data};Object.defineProperty(this,"fillStyle",{get:function(){return this.fillColor},set:function(value){this.fillColor=value;if(value instanceof PDFGradientFill){console.log("TODO",_this.doc)}else if(value.toString().startsWith("rgb")||value.toString().startsWith("hsl")){var color=fixColor(value);_this.doc.fillColor(color.c,color.a)}}});Object.defineProperty(this,"strokeStyle",{get:function(){return _this.doc.strokeColor()},set:function(value){var color=fixColor(value);_this.doc.strokeColor(color.c,color.a)}});Object.defineProperty(this,"lineWidth",{get:function(){return _this.doc.setLineWidth()},set:function(value){_this.doc.setLineWidth(value)}});Object.defineProperty(this,"lineCap",{get:function(){return"butt"},set:function(value){_this.doc.lineCap(value)}});Object.defineProperty(this,"lineJoin",{get:function(){return"miter"},set:function(value){_this.doc.lineJoin(value)}});Object.defineProperty(this,"miterLimit",{get:function(){return 10},set:function(){}});Object.defineProperty(this,"globalAlpha",{get:function(){return _this.doc.opacity()},set:function(value){_this.doc.opacity(value)}});Object.defineProperty(this,"font",{get:function(){return fontValue},set:function(value){this.context.font=value;fontValue=value;var parsedFont=parseFont(value);_this.doc.fontSize(parsedFont.size);_this.doc.font(parsedFont.family);_this.doc.setFontStyle(parsedFont.weight!="normal",parsedFont.style!="normal",false)}});this.font=fontValue;this.strokeStyle="rgb(0,0,0)";this.fillStyle="rgb(0,0,0)"};canvas2pdf.PdfContext.prototype.end=function(){this.doc.end()};canvas2pdf.PdfContext.prototype.addPage=function(pageOptions){this.doc.addPage(pageOptions)};canvas2pdf.PdfContext.prototype.save=function(){this.doc.save()};canvas2pdf.PdfContext.prototype.restore=function(){this.doc.restore()};canvas2pdf.PdfContext.prototype.transform=function(a,b,c,d,e,f){this.doc.transform(a,b,c,d,e,f)};canvas2pdf.PdfContext.prototype.scale=function(x,y){this.doc.scale(x,y)};canvas2pdf.PdfContext.prototype.rotate=function(angle){var degrees=angle*180/Math.PI;this.doc.rotate(degrees)};canvas2pdf.PdfContext.prototype.translate=function(x,y){this.doc.translate(x,y)};canvas2pdf.PdfContext.prototype.beginPath=function(){this.doc.beginPath()};canvas2pdf.PdfContext.prototype.moveTo=function(x,y){this.doc.moveTo(x,y)};canvas2pdf.PdfContext.prototype.closePath=function(){this.doc.closePath()};canvas2pdf.PdfContext.prototype.lineTo=function(x,y){this.doc.lineTo(x,y)};canvas2pdf.PdfContext.prototype.stroke=function(){this.doc.stroke()};canvas2pdf.PdfContext.prototype.fill=function(rule){this.doc.fill(rule)};canvas2pdf.PdfContext.prototype.rect=function(x,y,width,height){this.doc.rect(x,y,width,height)};canvas2pdf.PdfContext.prototype.fillRect=function(x,y,width,height){this.doc.beginPath();this.doc.rect(x,y,width,height);this.doc.fill()};canvas2pdf.PdfContext.prototype.strokeRect=function(x,y,width,height){this.doc.beginPath();this.doc.rect(x,y,width,height);this.doc.stroke()};canvas2pdf.PdfContext.prototype.clearRect=function(x,y,width,height){var oldFill=this.doc.fillColor();this.doc.fillColor("white");this.doc.rect(x,y,width,height);this.doc.fill();this.doc.fillColor(oldFill)};canvas2pdf.PdfContext.prototype.arc=function(x,y,r,a0,a1,ccw){this.doc.arc(x,y,r,a0,a1,ccw)};canvas2pdf.PdfContext.prototype.bezierCurveTo=function(cp1x,cp1y,cp2x,cp2y,x,y){this.doc.bezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y)};canvas2pdf.PdfContext.prototype.quadraticCurveTo=function(cpx,cpy,x,y){this.doc.quadraticCurveTo(cpx,cpy,x,y)};canvas2pdf.PdfContext.prototype.createLinearGradient=function(x1,y1,x2,y2){return this.doc.linearGradient(x1,y1,x2,y2)};canvas2pdf.PdfContext.prototype.createRadialGradient=function(x0,y0,r0,x1,y1,r1){var gradient=this.doc.radialGradient(x0,y0,r0,x1,y1,r1);gradient.addColorStop=function(offset,color){var fixedColor=fixColor(color);gradient.stop(offset,fixedColor.c,fixedColor.a)};return gradient};canvas2pdf.PdfContext.prototype.fillText=function(text,x,y){if(text&&text.trim().length){this.doc.textAdd(x,y,text)}};canvas2pdf.PdfContext.prototype.strokeText=function(){console.log("strokeText not implemented, use fillText")};canvas2pdf.PdfContext.prototype.measureText=function(text){return this.context.measureText(text+"")};canvas2pdf.PdfContext.prototype.clip=function(){this.doc.clip()};canvas2pdf.PdfContext.prototype.getPDFbase64=function(){return this.doc.getBase64Text()};canvas2pdf.PdfContext.prototype.getPDFtext=function(){return this.doc.getText()};canvas2pdf.PdfContext.prototype.drawImage=function(img,x,y,w,h){var ctm=this.doc.currentPage._ctm;var det=ctm[0]*ctm[3]-ctm[1]*ctm[2];return this.doc.drawImage(img,x,y,w,h,Math.sqrt(Math.abs(det)))};canvas2pdf.PdfContext.prototype.setLineDash=function(dashArray){return this.doc.setLineDash(dashArray)};canvas2pdf.PdfContext.prototype.createPattern=function(image){var tile=this.doc.imageTileLoad(image);return{setTransform:matrix=>{tile.matrix=matrix}}};canvas2pdf.PdfContext.prototype.setTransform=function(){console.log("setTransform not implemented")};canvas2pdf.PdfContext.prototype.drawFocusRing=function(){console.log("drawFocusRing not implemented")};canvas2pdf.PdfContext.prototype.createImageData=function(){console.log("drawFocusRing not implemented")};canvas2pdf.PdfContext.prototype.getImageData=function(){console.log("getImageData not implemented")};canvas2pdf.PdfContext.prototype.putImageData=function(){console.log("putImageData not implemented")};canvas2pdf.PdfContext.prototype.globalCompositeOperation=function(){console.log("globalCompositeOperation not implemented")};canvas2pdf.PdfContext.prototype.arcTo=function(){console.log("arcTo not implemented")}; /* @license MIT LICENSE Copyright (c) 2014 Devon Govett Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */function PDFKitMini(){this.objects=[];this.catalog=this.add(new PDFCatalog);this.pages=this.add(new PDFPages);this.catalog.setPages(this.pages);this.pageWidth=8.27;this.pageHeight=11.69;this.textStyle=new PDFTextStyle;this.fonts=[];this.lineWidth=1;this.lineEndType=0;this.alpha=1;canvas2pdf.useFlateDecode=!!window.pako||!!window.fflate;canvas2pdf.deflate=function(stringOrArray){var input=stringOrArray;if(window.pako){return window.pako.deflate(input)}if(window.fflate){if(typeof input=="string"){var enc=new TextEncoder;input=enc.encode(input)}return window.fflate.zlibSync(input)}return input}}PDFKitMini.prototype.add=function(a){this.objects.push(a);a.id=this.objects.length;return a};PDFKitMini.prototype.pageSetWidth=function(w){this.pageWidth=w};PDFKitMini.prototype.pageSetHeight=function(h){this.pageHeight=h};PDFKitMini.prototype.addPage=function(pageOptions){this.currentPage=new PDFPage(this,this.pageWidth,this.pageHeight,this.pages);this.currentPage.dpi=pageOptions?.dpi||72;this.add(this.currentPage);this.pages.addPage(this.currentPage);var a=new PDFStream;this.add(a);this.currentPage.setStream(a);if(!(pageOptions&&pageOptions.verticalFlip)){this.currentPage.transform(1,0,0,-1,0,this.currentPage.height)}};PDFKitMini.prototype.font=function(font){this.currentPage.setFontName(font)};PDFKitMini.prototype.fontSize=function(size){this.currentPage.setFontSize(size)};PDFKitMini.prototype.lineJoin=function(style){this.currentPage.setLineJoin(style)};PDFKitMini.prototype.lineCap=function(style){this.currentPage.setLineCap(style)};PDFKitMini.prototype.setLineWidth=function(width){this.currentPage.setLineWidth(width)};PDFKitMini.prototype.strokeColor=function(color,alpha){this.currentPage.setStrokeColor(color,alpha)};PDFKitMini.prototype.fillColor=function(color,alpha){this.currentPage.setFillColor(color,alpha)};PDFKitMini.prototype.pageSetCurrent=function(page){this.currentPage=page};PDFKitMini.prototype.font=function(font){this.textStyle.setFontName(font)};PDFKitMini.prototype.fontSetSize=function(size){this.textStyle.fontSetSize(size)};PDFKitMini.prototype.setFontStyle=function(bold,italic){this.textStyle.setFontStyle(bold,italic)};PDFKitMini.prototype.setFont=function(a){var b=a.getFontName();if(null!=b){var c=null,d;for(d=0;dr.charCodeAt(0)>127))){state.setFontName(state.fontName.startsWith("Times")?"RobotoSerif":"Roboto");this.currentPage.isUnicode=true}this.setFont(state);this.currentPage.textAdd(x,y,text,state)};PDFKitMini.prototype.imageLoadFromCanvas=function(a,scale){a=new PDFImage(a);a.scale=scale;this.add(a);if(a.mask){this.add(a.mask)}this.currentImage=a};PDFKitMini.prototype.imageTileLoadFromCanvas=function(a){a=new PDFImageTile(a,this.currentPage.fillColor,this.currentPage.alpha*1);if(a.vectorPattern){this.add(a.vectorPattern)}this.add(a);this.currentPage.currentImageTile=a;return a};PDFKitMini.prototype.linearGradient=function(x1,y1,x2,y2){var a=new PDFGradientFill(x1,y1,x2,y2,this.currentPage);this.add(a);this.currentPage.currentImageTile=a;this.addPatternToPage(a);return a};PDFKitMini.prototype.doDrawImage=function(x,y,width,height){this.currentPage.drawImage(x,y,this.currentImage,this.alpha,width,height)};PDFKitMini.prototype.addPatternToPage=function(img){this.currentPage.addPatternToPage(img)};PDFKitMini.prototype.moveTo=function(x,y){this.currentPage.moveTo(x,y)};PDFKitMini.prototype.lineTo=function(x,y){this.currentPage.lineTo(x,y)};PDFKitMini.prototype.bezierCurveTo=function(cp1x,cp1y,cp2x,cp2y,x,y){this.currentPage.bezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y)};PDFKitMini.prototype.translate=function(x,y){this.currentPage.translate(x,y)};PDFKitMini.prototype.transform=function(m0,m1,m2,m3,m4,m5){this.currentPage.transform(m0,m1,m2,m3,m4,m5)};PDFKitMini.prototype.drawImage=function(img,x,y,w,h,contextScale){var scale=1;if(img.nodeName.toLowerCase()=="img"){var canvas=document.createElement("canvas");if(img.src.startsWith&&img.src.startsWith("data:image/svg")){scale=2*Math.max(1,contextScale||1)*this.currentPage.dpi/72}canvas.width=img.width*scale;canvas.height=img.height*scale;var context=canvas.getContext("2d");context.drawImage(img,0,0,img.width,img.height,0,0,canvas.width,canvas.height);img=canvas}this.imageLoadFromCanvas(img,scale);this.doDrawImage(x,y,img.width,img.height)};PDFKitMini.prototype.imageTileLoad=function(img){if(img.nodeName&&img.nodeName.toLowerCase()=="img"){var canvas=document.createElement("canvas");canvas.width=img.width;canvas.height=img.height;var context=canvas.getContext("2d");context.drawImage(img,0,0);img=canvas}var tile=this.imageTileLoadFromCanvas(img);this.addPatternToPage(this.currentPage.currentImageTile);return tile};PDFKitMini.prototype.scale=function(xFactor,yFactor,options){this.currentPage.scale(xFactor,yFactor,options)};PDFKitMini.prototype.rotate=function(angle,options){this.currentPage.rotate(angle,options)};PDFKitMini.prototype.beginPath=function(){this.currentPage.beginPath()};PDFKitMini.prototype.arc=function(x,y,r,startAngle,arcAngle,counterclockwise){this.currentPage.arc(x,y,r,startAngle,arcAngle,counterclockwise)};PDFKitMini.prototype.closePath=function(){this.currentPage.closePath()};PDFKitMini.prototype.stroke=function(){this.currentPage.stroke()};PDFKitMini.prototype.clip=function(rule){this.currentPage.clip(rule)};PDFKitMini.prototype.opacity=function(alpha){if(typeof alpha=="undefined"){return this.currentPage.currentAlpha}this.currentPage.setAlpha(alpha)};PDFKitMini.prototype.setLineDash=function(dash){this.currentPage.setLineDash(dash)};PDFKitMini.prototype.save=function(){this.currentPage.saveContext()};PDFKitMini.prototype.restore=function(){this.currentPage.restoreContext()};PDFKitMini.prototype.fill=function(rule){this.currentPage.fill(rule)};PDFKitMini.prototype.rect=function(a,b,c,d){this.currentPage.rect(a,b,c,d)};PDFKitMini.prototype.quadraticCurveTo=function(a,b,c,d){this.currentPage.quadraticCurveTo(a,b,c,d)};PDFKitMini.prototype.graphicsSetAlpha=function(a){this.alpha=Math.floor(100*a/255)/100;this.textStyle.setAlpha(a)};PDFKitMini.prototype.graphicsSetLineEndType=function(a){this.lineEndType=a};PDFKitMini.prototype._write=function(a){this.stream+=a+"\n"};PDFKitMini.prototype.getObject=function(a){this.stream="";this._write("%PDF-1.7");var _i,d;for(_i=0;_i0){for(var c=0;c0){for(c=0;c0){for(var d=0;d0){for(d=0;d0){props["Resources"]["Font"]=fontProps}if(this.alphas.length>0){props["Resources"]["ExtGState"]=alphaProps}if(this.fillImages.length>0){props["Resources"]["Pattern"]=patternProps}if(this.images.length>0){props["Resources"]["XObject"]=imageProps}return PDFObject.makeObject(props,this.id)};function PDFUnicodeMapping(spec){const bfchars=spec.unicodes.map(((unicode,gid)=>`<${PDFObject.toHex(gid)}><${PDFObject.toHex(unicode)}>`)).join("\n");this.stream=`/CIDInit /ProcSet findresource begin\n 10 dict begin\n begincmap\n /CIDSystemInfo\n << /Registry (Adobe)\n /Ordering (UCS)\n /Supplement 0\n >> def\n /CMapName /Adobe-Identity-UCS def\n /CMapType 2 def\n 1 begincodespacerange\n <0000> \n endcodespacerange\n ${spec.unicodes.length} beginbfchar\n ${bfchars}\n endbfchar\n endcmap\n CMapName currentdict /CMap defineresource pop\n end\n end`}PDFUnicodeMapping.prototype.getObject=function(){var stream=bufferToString(this.stream);var props={Length:stream.length};return PDFObject.makeObject(props,this.id,stream)};function PDFSystemInfo(){}PDFSystemInfo.prototype.getObject=function(){const props={Supplement:0,Registry:new PDFReference("(Adobe)"),Ordering:new PDFReference("(Identity)")};return PDFObject.makeObject(props,this.id)};function PDFFontDescriptor(){}PDFFontDescriptor.prototype.getObject=function(){const props={CapHeight:939,StemV:56,FontBBox:this.spec.bbox,FontFile2:PDFReference.of(this.fontFile),Descent:this.spec.bbox[2],Type:"FontDescriptor",Flags:32,FontName:"Unicode",ItalicAngle:0,Ascent:this.spec.bbox[3]};return PDFObject.makeObject(props,this.id)};function PDFFontFile(spec){this.buffer=atob(spec.base64)}PDFFontFile.prototype.getObject=function(){const props={Length:this.buffer.length,Length1:this.buffer.length};return PDFObject.makeObject(props,this.id,this.buffer)};function PDFFont(a){this.fontName=a;this.descendantFonts=[];this.subtype="Type1";this.encoding="WinAnsiEncoding"}PDFFont.TIMES=["Times-Roman","Times-Italic","Times-Bold","Times-BoldItalic"];PDFFont.HELVETICA=["Helvetica","Helvetica-Oblique","Helvetica-Bold","Helvetica-BoldOblique"];PDFFont.ROBOTO=["Roboto-Regular","Roboto-Italic","Roboto-Bold","Roboto-BoldItalic"];PDFFont.ROBOTO_SERIF=["RobotoSerif-Regular","RobotoSerif-Italic","RobotoSerif-Bold","RobotoSerif-BoldItalic"];PDFFont.getPDFName=function(font,bold,italic){var index=(bold?2:0)+(italic?1:0);if(font=="Helvetica"){return PDFFont.HELVETICA[index]}if(font=="Roboto"){return PDFFont.ROBOTO[index]}if(font=="RobotoSerif"){return PDFFont.ROBOTO_SERIF[index]}return PDFFont.TIMES[index]};PDFFont.prototype.getObject=function(){var props={Subtype:this.subtype,Name:"F"+this.id,BaseFont:this.baseFont||this.fontName,Encoding:this.encoding,Type:"Font",DescendantFonts:this.descendantFonts.map((f=>PDFReference.of(f)))};if(this.toUnicode){props["ToUnicode"]=PDFReference.of(this.toUnicode)}if(this.systemInfo){props["CIDSystemInfo"]=PDFReference.of(this.systemInfo)}if(this.fontDescriptor){props["FontDescriptor"]=PDFReference.of(this.fontDescriptor)}if(this.cidToGidMap){props["FontMatrix"]=this.spec.matrix;props["FontBBox"]=this.spec.bbox;const ratio=this.spec.matrix[0]/.001;props["W"]=new PDFReference("["+this.spec.widths.map(((width,idx)=>width&&idx?`${idx} [${Math.round(width*ratio)}]`:"")).join("")+"]");props["CIDToGIDMap"]=this.cidToGidMap}return PDFObject.makeObject(props,this.id)};function PDFStream(){this.stream=""}PDFStream.prototype.addText=function(text){this.stream+=text};PDFStream.prototype.addTextCheckMerge=function(a){function endsWith(str,suffix){return str.indexOf(suffix,str.length-suffix.length)!==-1}if(a=="f* "&&endsWith(this.stream," S ")){this.stream=this.stream.substring(0,this.stream.length-3)+" B* "}else if(a=="S "&&endsWith(this.stream," f* ")){this.stream=this.stream.substring(0,this.stream.length-4)+" B* "}else if(a=="f "&&endsWith(this.stream," S ")){this.stream=this.stream.substring(0,this.stream.length-3)+" B "}else if(a=="S "&&endsWith(this.stream," f ")){this.stream=this.stream.substring(0,this.stream.length-3)+" B "}else{this.stream+=a}};PDFStream.prototype.replaceText=function(a,b){this.stream=this.stream.replace(a,b)};PDFStream.prototype.getObject=function(){var stream=bufferToString(this.stream);var props={Length:stream.length};if(canvas2pdf.useFlateDecode){props["Filter"]="FlateDecode"}return PDFObject.makeObject(props,this.id,stream)};var bufferToString=function(buffer){if(canvas2pdf.useFlateDecode){buffer=canvas2pdf.deflate(buffer)}else if(typeof buffer==="string"){return buffer}var buffer2=[];for(var i=0;ivalue*(1-fillAlpha)+fillAlpha));var rgbBuffer=new Uint8Array(this.width*this.height*3);var idx=0;for(var y=this.height-1;y>=0;y--)for(var x=0;xMath.round(parseFloat(value)/255*alpha+fillRGB[idx]*(255-alpha))));rgbBuffer[idx++]=red;rgbBuffer[idx++]=green;rgbBuffer[idx++]=blue}if(canvas2pdf.useFlateDecode){buffer.push("/Filter /FlateDecode ")}this.stream=buffer.join("")+"ID\n"+bufferToString(rgbBuffer)+"\nEI\n"}else{var patternPage=canvas.doc.currentPage;this.boundingBox=canvas.boundingBox||[0,0,patternPage.pdf.pageWidth*72,patternPage.pdf.pageHeight*72];this.alphas=patternPage.alphas;this.vectorPattern=new PDFImageTileContent(patternPage.pdfStream.stream,this.boundingBox)}}PDFImageTile.prototype.writeImage=function(a){this.stream=a};PDFImageTile.prototype.getObject=function(){var vectorRef={};var matrix=[this.matrix?this.matrix.m11:1,0,0,this.matrix?this.matrix.m22:1,0,0];if(this.vectorPattern){this.stream=`/x${this.vectorPattern.id} Do`;vectorRef[`x${this.vectorPattern.id}`]=PDFReference.of(this.vectorPattern);matrix=[1,0,0,-1,0,0]}var props={Type:"Pattern",PatternType:1,PaintType:1,TilingType:1,BBox:this.boundingBox,XStep:this.boundingBox[2]-this.boundingBox[0],YStep:this.boundingBox[3]-this.boundingBox[1],Length:this.stream.length,Matrix:matrix,Resources:this.vectorPattern?{XObject:vectorRef}:{ProcSet:["PDF","ImageC"]}};return PDFObject.makeObject(props,this.id,this.stream)};function PDFTextStyle(){this.fontName="Helvetica";this.fontSize=12;this.italic=false;this.bold=false;this.font=undefined;this.alpha=1}PDFTextStyle.prototype.setFontName=function(a){this.fontName=a;this.font=undefined};PDFTextStyle.prototype.fontSetSize=function(a){this.fontSize=a};PDFTextStyle.prototype.setFontStyle=function(b,i){this.bold=b;this.italic=i};PDFTextStyle.prototype.setColor=function(col){this.color=col};PDFTextStyle.prototype.setAlpha=function(a){this.alpha=a};PDFTextStyle.prototype.getFontName=function(){return PDFFont.getPDFName(this.fontName,this.bold,this.italic)};PDFTextStyle.prototype.setFont=function(font){this.font=font};PDFTextStyle.prototype.clone=function(){var a=new PDFTextStyle;a.fontName=this.fontName;a.fontSize=this.fontSize;a.bold=this.bold;a.italic=this.italic;a.color=this.color;a.alpha=this.alpha;a.font=this.font;return a};var PDFObject,PDFReference;PDFObject=function(){var escapable,escapableRe,pad;function PDFObject(){}pad=function(str,length){return(Array(length+1).join("0")+str).slice(-length)};escapableRe=/[\n\r\t\b\f()\\]/g;escapable={"\n":"\\n","\r":"\\r","\t":"\\t","\b":"\\b","\f":"\\f","\\":"\\\\","(":"\\(",")":"\\)"};PDFObject.makeObject=function(props,id,stream){var ret=id+" 0 obj\n"+PDFObject.convert(props);if(stream){ret+="\nstream\n"+stream+"\nendstream\n"}ret+="endobj\n";return ret};PDFObject.toHex=function(num){return num.toString(16).padStart(4,"0")};PDFObject.fromUnicode=function(num,spec){const index=spec.unicodes.indexOf(num);return index<=0?spec.unicodes.indexOf(63):index};PDFObject.convert=function(object,currentFontSpec){var e,i,items,key,out,string,val,_i,_ref;if(typeof object==="string"){return"/"+object}else if(object instanceof String){string=object;const isUnicode=!!currentFontSpec||[...string].find((r=>r.charCodeAt(0)>127));if(isUnicode){var newString="";for(i=_i=0,_ref=string.length;_i<_ref;i=_i+=1){const hexChar=PDFObject.toHex(PDFObject.fromUnicode(string.codePointAt(i),currentFontSpec));newString+=hexChar}return"<"+newString+">"}else{string=object.replace(escapableRe,(function(c){return escapable[c]}));return"("+string+")"}}else if(object instanceof PDFReference){return object.toString()}else if(object instanceof Date){return"(D:"+pad(object.getUTCFullYear(),4)+pad(object.getUTCMonth()+1,2)+pad(object.getUTCDate(),2)+pad(object.getUTCHours(),2)+pad(object.getUTCMinutes(),2)+pad(object.getUTCSeconds(),2)+"Z)"}else if(Array.isArray(object)){items=function(){var _j,_len,_results;_results=[];for(_j=0,_len=object.length;_j<_len;_j++){e=object[_j];_results.push(PDFObject.convert(e))}return _results}().join(" ");return"["+items+"]"}else if({}.toString.call(object)==="[object Object]"){out=["<<"];for(key in object){val=object[key];out.push("/"+key+" "+PDFObject.convert(val)+"\n")}out.push(">>");return out.join("")+"\n"}else{return""+object}};return PDFObject}();PDFReference=function(){function PDFReference(s){this.str=s}PDFReference.prototype.toString=function(){return this.str};PDFReference.of=function(obj){return new PDFReference(obj.id+" 0 R")};return PDFReference}()})(typeof window!=="undefined"?window:this);