jspdf-md-renderer 3.4.1 → 3.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,1701 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require(`marked`),l=require(`jspdf-autotable`);l=s(l);var u=function(e){return e.Heading=`heading`,e.Paragraph=`paragraph`,e.List=`list`,e.ListItem=`list_item`,e.Blockquote=`blockquote`,e.Code=`code`,e.CodeSpan=`codespan`,e.Table=`table`,e.Html=`html`,e.Hr=`hr`,e.Image=`image`,e.Link=`link`,e.Strong=`strong`,e.Em=`em`,e.TableHeader=`table_header`,e.TableCell=`table_cell`,e.Raw=`raw`,e.Text=`text`,e.Br=`br`,e}({}),d=`__jmr_`,f=/(!\[[^\]]*\]\()([^)]+)(\))\s*\{([^}]+)\}/g,p=/(\w+)\s*=\s*(\w+)/g,m=[`left`,`center`,`right`],h=e=>{let t=[];return e.width!==void 0&&t.push(`w=${e.width}`),e.height!==void 0&&t.push(`h=${e.height}`),e.align&&t.push(`a=${e.align}`),t.length>0?`#${d}${t.join(`&`)}`:``},g=e=>{let t={},n;for(;(n=p.exec(e))!==null;){let e=n[1].toLowerCase(),r=n[2];switch(e){case`width`:case`w`:{let e=parseInt(r,10);!isNaN(e)&&e>0&&(t.width=e);break}case`height`:case`h`:{let e=parseInt(r,10);!isNaN(e)&&e>0&&(t.height=e);break}case`align`:{let e=r.toLowerCase();m.includes(e)&&(t.align=e);break}}}return t},_=e=>e.replace(f,(e,t,n,r,i)=>`${t}${n}${h(g(i))}${r}`),v=e=>{let t=e.indexOf(`#${d}`);if(t===-1)return{cleanHref:e,attrs:{}};let n=e.substring(0,t),r=e.substring(t+1+6),i={},a=r.split(`&`);for(let e of a){let[t,n]=e.split(`=`);switch(t){case`w`:{let e=parseInt(n,10);!isNaN(e)&&e>0&&(i.width=e);break}case`h`:{let e=parseInt(n,10);!isNaN(e)&&e>0&&(i.height=e);break}case`a`:m.includes(n)&&(i.align=n);break}}return{cleanHref:n,attrs:i}},y=async e=>{let t=_(e);return b(await c.marked.lexer(t,{async:!0,gfm:!0}))},b=e=>{let t=[];return e.forEach(e=>{try{let n=x[e.type];n?t.push(n(e)):t.push({type:u.Raw,content:e.raw})}catch(t){console.error(`Failed to handle token ==>`,e,t)}}),t},x={[u.Heading]:e=>({type:u.Heading,depth:e.depth,content:e.text,items:e.tokens?b(e.tokens):[]}),[u.Paragraph]:e=>({type:u.Paragraph,content:e.text,items:e.tokens?b(e.tokens):[]}),[u.List]:e=>({type:u.List,ordered:e.ordered,start:e.start,items:e.items?b(e.items):[]}),[u.ListItem]:e=>({type:u.ListItem,content:e.text,items:e.tokens?b(e.tokens):[]}),[u.Code]:e=>({type:u.Code,lang:e.lang,code:e.text}),[u.Table]:e=>({type:u.Table,header:e.header.map(e=>({type:u.TableHeader,content:e.text})),rows:e.rows.map(e=>e.map(e=>({type:u.TableCell,content:e.text})))}),[u.Image]:e=>{let{cleanHref:t,attrs:n}=v(e.href);return{type:u.Image,src:t,alt:e.text,width:n.width,height:n.height,align:n.align}},[u.Link]:e=>({type:u.Link,href:e.href,text:e.text,items:e.tokens?b(e.tokens):[]}),[u.Strong]:e=>({type:u.Strong,content:e.text,items:e.tokens?b(e.tokens):[]}),[u.Em]:e=>({type:u.Em,content:e.text,items:e.tokens?b(e.tokens):[]}),[u.Text]:e=>({type:u.Text,content:e.text,items:e.tokens?b(e.tokens):[]}),[u.Hr]:e=>({type:u.Hr,content:e.raw,items:e.tokens?b(e.tokens):[]}),[u.CodeSpan]:e=>({type:u.CodeSpan,content:e.text,items:e.tokens?b(e.tokens):[]}),[u.Blockquote]:e=>({type:u.Blockquote,content:e.text,items:e.tokens?b(e.tokens):[]}),[u.Html]:e=>{let t=String(e.raw??e.text??``).trim();return/^<br\s*\/?>$/i.test(t)?{type:u.Br,content:`
2
- `}:{type:u.Raw,content:e.raw??e.text??``}},[u.Br]:()=>({type:u.Br,content:`
3
- `})},S=e=>e.getTextDimensions(`H`).h,C=e=>e.getTextDimensions(`H`).w,w=(e,t,n,r,i)=>{let a=6-(t?.depth??0)>0?6-(t?.depth??0):1;if(e.setFontSize(r.options.page.defaultFontSize+a),t?.items&&t?.items.length>0)for(let e of t?.items??[])i(e,n,r,!1);else{let i=S(e);e.text(t?.content??``,r.X+n,r.Y,{align:`left`,maxWidth:r.options.page.maxContentWidth-n,baseline:`top`}),r.recordContentY(r.Y+i),r.updateY(S(e),`add`)}e.setFontSize(r.options.page.defaultFontSize),r.updateX(r.options.page.xpading,`set`)},T=(e,t)=>{typeof t.options.pageBreakHandler==`function`?t.options.pageBreakHandler(e):e.addPage(t.options.page?.format,t.options.page?.orientation),t.updateY(t.options.page.topmargin),t.updateX(t.options.page.xpading)},E=96,D=(e,t=`mm`)=>{switch(t){case`pt`:return e*72/E;case`in`:return e/E;case`px`:return e;default:return e*25.4/E}},O=e=>{try{let t=``;if(e.includes(`base64,`)){let n=e.split(`base64,`)[1];t=typeof window<`u`&&typeof window.atob==`function`?decodeURIComponent(escape(window.atob(n))):typeof Buffer<`u`?Buffer.from(n,`base64`).toString(`utf-8`):decodeURIComponent(escape(atob(n)))}else t=decodeURIComponent(e.split(`,`)[1]||``);let n=t.match(/<svg[^>]*\swidth=(?:'|")([0-9.]+)[a-zA-Z]*(?:'|")/i),r=t.match(/<svg[^>]*\sheight=(?:'|")([0-9.]+)[a-zA-Z]*(?:'|")/i),i=t.match(/<svg[^>]*\sviewBox=(?:'|")[^'"]*(?:'|")/i),a=n?parseFloat(n[1]):0,o=r?parseFloat(r[1]):0;if((!a||!o)&&i){let e=i[0].match(/viewBox=(?:'|")([^'"]+)(?:'|")/i);if(e){let t=e[1].split(/[ ,]+/).filter(Boolean).map(parseFloat);t.length>=4&&(a||=t[2],o||=t[3])}}if(a>0&&o>0)return{width:a,height:o}}catch(e){console.warn(`Failed to extract SVG dimensions:`,e)}return null},k=(e,t,n,r,i=`mm`)=>{if(!t.data)return{finalWidth:0,finalHeight:0};let a=t.naturalWidth||0,o=t.naturalHeight||0;if(!a||!o)if(t.data.startsWith(`data:image/svg`)){let e=O(t.data);e&&(a=e.width,o=e.height)}else try{let n=e.getImageProperties(t.data);a=n.width,o=n.height}catch(e){console.warn(`Failed to get image properties for intrinsic sizing:`,e)}let s=o>0?a/o:1,c,l;if(t.width&&t.height?(c=D(t.width,i),l=D(t.height,i)):t.width?(c=D(t.width,i),l=c/s):t.height?(l=D(t.height,i),c=l*s):(c=D(a,i),l=D(o,i)),c>n){let e=n/c;c=n,l*=e}if(l>r){let e=r/l;l=r,c*=e}return{finalWidth:c,finalHeight:l}},A=async e=>{for(let t of e){if(t.type===u.Image&&t.src)try{if(t.src.startsWith(`data:`))t.data=t.src;else{let e=await fetch(t.src);if(!e.ok)throw Error(`Failed to fetch image: ${e.statusText}`);let n=await e.blob();t.data=await new Promise((e,t)=>{let r=new FileReader;r.onloadend=()=>{typeof r.result==`string`?e(r.result):t(Error(`Failed to convert image to base64 string`))},r.onerror=t,r.readAsDataURL(n)})}t.data&&t.data.startsWith(`data:image/svg`)&&typeof window<`u`&&typeof document<`u`&&(t.data=await new Promise(e=>{let n=new Image;n.onload=()=>{let r=document.createElement(`canvas`),i=O(t.data),a=i?i.width:n.width||300,o=i?i.height:n.height||150;t.naturalWidth=a,t.naturalHeight=o,r.width=a*4,r.height=o*4;let s=r.getContext(`2d`);s?(s.scale(4,4),s.drawImage(n,0,0,a,o),e(r.toDataURL(`image/png`))):e(t.data)},n.onerror=()=>e(t.data),n.src=t.data}))}catch(e){console.warn(`[jspdf-md-renderer] Warning: Failed to load image at ${t.src}. It will be skipped.`,e)}t.items&&t.items.length>0&&await A(t.items)}},j=class{static getCodespanOptions(e){let t=e.options.codespan??{};return{backgroundColor:t.backgroundColor??`#EEEEEE`,padding:t.padding??.5,showBackground:t.showBackground!==!1,fontSizeScale:t.fontSizeScale??.9}}static applyStyle(e,t,n){let r=e.getFont().fontName,i=e.getFontSize(),a=()=>{let e=n.options.font.bold?.name;return e&&e!==``?e:r},o=()=>{let e=n.options.font.regular?.name;return e&&e!==``?e:r};switch(t){case`bold`:e.setFont(a(),n.options.font.bold?.style||`bold`);break;case`italic`:e.setFont(o(),`italic`);break;case`bolditalic`:e.setFont(a(),`bolditalic`);break;case`codespan`:e.setFont(`courier`,`normal`),e.setFontSize(i*this.getCodespanOptions(n).fontSizeScale);break;default:e.setFont(o(),e.getFont().fontStyle);break}}static measureWordWidth(e,t,n,r){let i=e.getFont(),a=e.getFontSize();this.applyStyle(e,n,r);let o=e.getTextWidth(t),s=e.getCharSpace?.()??0,c=o+t.length*s;return e.setFont(i.fontName,i.fontStyle),e.setFontSize(a),c}static getStyleFromType(e,t){switch(e){case`strong`:return t===`italic`?`bolditalic`:`bold`;case`em`:return t===`bold`?`bolditalic`:`italic`;case`codespan`:return`codespan`;default:return t||`normal`}}static flattenToWords(e,t,n,r=`normal`,i=!1,a){let o=[];for(let s of t){let t=this.getStyleFromType(s.type,r),c=s.type===`link`||i,l=s.href||a;if(s.items&&s.items.length>0){let r=this.flattenToWords(e,s.items,n,t,c,l);o.push(...r)}else if(s.type===`image`){let r=n.options.page.maxContentHeight-n.options.page.topmargin,{finalWidth:i,finalHeight:a}=k(e,s,n.options.page.maxContentWidth-n.options.page.indent*0,r,n.options.page.unit||`mm`);o.push({text:``,width:i,style:t,isLink:c,href:l,linkColor:c?n.options.link?.linkColor||[0,0,255]:void 0,isImage:!0,imageElement:s,imageHeight:a})}else if(s.type===`br`)o.push({text:``,width:0,style:t,isBr:!0});else{let r=s.content||s.text||``;if(!r)continue;if(/^\s/.test(r)&&o.length>0&&(o[o.length-1].hasTrailingSpace=!0),t===`codespan`){let i=r.trim();i&&o.push({text:i,width:this.measureWordWidth(e,i,t,n),style:t,isLink:c,href:l,linkColor:c?n.options.link?.linkColor||[0,0,255]:void 0,hasTrailingSpace:/\s$/.test(r)});continue}let i=r.trim().split(/\s+/).filter(e=>e.length>0);for(let a=0;a<i.length;a++){let s=a!==i.length-1||/\s$/.test(r);o.push({text:i[a],width:this.measureWordWidth(e,i[a],t,n),style:t,isLink:c,href:l,linkColor:c?n.options.link?.linkColor||[0,0,255]:void 0,hasTrailingSpace:s})}}}return o}static breakIntoLines(e,t,n,r){let i=[],a=[],o=0,s=0,c=S(e)*r.options.page.defaultLineHeightFactor,l=e.getTextWidth(` `);for(let u=0;u<t.length;u++){let d=t[u],f=a[a.length-1]?.hasTrailingSpace?l+d.width:d.width,p=d.isImage&&d.imageHeight?d.imageHeight:S(e)*r.options.page.defaultLineHeightFactor;if(d.isBr){i.push({words:a,totalTextWidth:o,isLastLine:!0,lineHeight:c}),a=[],o=0,s=0,c=S(e)*r.options.page.defaultLineHeightFactor;continue}s+f>n&&a.length>0?(i.push({words:a,totalTextWidth:o,isLastLine:!1,lineHeight:c}),a=[d],o=d.width,s=d.width,c=p):(a.push(d),o+=d.width,s+=f,c=Math.max(c,p))}return a.length>0&&i.push({words:a,totalTextWidth:o,isLastLine:!0,lineHeight:c}),i}static renderWord(e,t,n,r,i){let a=e.getFont(),o=e.getFontSize(),s=e.getTextColor();if(this.applyStyle(e,t.style,i),t.isLink&&t.linkColor&&e.setTextColor(...t.linkColor),t.isImage&&t.imageElement&&t.imageElement.data)try{let i=`JPEG`;if(t.imageElement.data.startsWith(`data:image/png`))i=`PNG`;else if(t.imageElement.data.startsWith(`data:image/webp`))i=`WEBP`;else if(t.imageElement.data.startsWith(`data:image/gif`))i=`GIF`;else if(t.imageElement.src){let e=t.imageElement.src.split(`?`)[0].split(`#`)[0].split(`.`).pop()?.toUpperCase();e&&[`PNG`,`JPEG`,`JPG`,`WEBP`,`GIF`].includes(e)&&(i=e===`JPG`?`JPEG`:e)}if(t.width>0&&(t.imageHeight||0)>0){let a=t.imageHeight||0,o=r;e.addImage(t.imageElement.data,i,n,o,t.width,a)}}catch(e){console.warn(`Failed to render inline image`,e)}else{if(t.style===`codespan`){let a=this.getCodespanOptions(i);if(a.showBackground){let i=S(e),o=a.padding;e.setFillColor(a.backgroundColor),e.rect(n-o,r-o,t.width+o*2,i+o*2,`F`),e.setFillColor(`#000000`)}}e.text(t.text,n,r,{baseline:`top`})}if(t.isLink&&t.href){let i=t.isImage&&t.imageHeight?t.imageHeight:S(e);e.link(n,r,t.width,i,{url:t.href})}e.setFont(a.fontName,a.fontStyle),e.setFontSize(o),e.setTextColor(s)}static renderAlignedLine(e,t,n,r,i,a,o=`left`){let{words:s,totalTextWidth:c,isLastLine:l}=t;if(s.length===0)return;let u=e.getTextWidth(` `),d=n,f=u,p=c,m=0;for(let e=0;e<s.length-1;e++)s[e].hasTrailingSpace&&(p+=u,m++);switch(o){case`right`:d=n+i-p;break;case`center`:d=n+(i-p)/2;break;case`justify`:!l&&m>0&&(f=(i-c)/m);break;default:break}let h=d,g=S(e)*a.options.page.defaultLineHeightFactor;for(let n=0;n<s.length;n++){let i=s[n],o=r,c=i.isImage&&i.imageHeight?i.imageHeight:g;i.isImage?o=r:c<t.lineHeight&&(o=r+(t.lineHeight-c)),this.renderWord(e,i,h,o,a),h+=i.width,n<s.length-1&&i.hasTrailingSpace&&(h+=f)}}static renderStyledParagraph(e,t,n,r,i,a,o){let s=o??a.options.content?.textAlignment??`left`,c=this.flattenToWords(e,t,a);if(c.length===0)return;let l=this.breakIntoLines(e,c,i,a),u=r;for(let t of l)u+t.lineHeight>a.options.page.maxContentHeight&&(T(e,a),u=a.Y),this.renderAlignedLine(e,t,n,u,i,a,s),a.recordContentY(u+t.lineHeight),u+=t.lineHeight,a.updateY(t.lineHeight,`add`);let d=l[l.length-1];if(d){let t=0;for(let e=0;e<d.words.length-1;e++)d.words[e].hasTrailingSpace&&t++;let r=d.totalTextWidth+t*e.getTextWidth(` `);a.updateX(n+r,`set`)}}static renderJustifiedParagraph(e,t,n,r,i,a){this.renderStyledParagraph(e,t,n,r,i,a)}},M=class{static renderText(e,t,n,r=n.X,i=n.Y,a,o=!1){let s=e.splitTextToSize(t,a),c=S(e),l=c*n.options.page.defaultLineHeightFactor,u=i;for(let t=0;t<s.length;t++){let i=s[t];u+l>n.options.page.maxContentHeight&&(T(e,n),u=n.Y),o?t===s.length-1?e.text(i,r,u,{baseline:`top`}):e.text(i,r,u,{maxWidth:a,align:`justify`,baseline:`top`}):e.text(i,r,u,{baseline:`top`}),n.recordContentY(u+c),u+=l,n.updateY(l,`add`)}return u}},N=(e,t,n,r,i)=>{r.activateInlineLock(),e.setFontSize(r.options.page.defaultFontSize);let a=r.options.page.maxContentWidth-n;if(t?.items&&t?.items.length>0){if(t.items.length===1&&t.items[0].type===`image`){i(t.items[0],n,r,!1),r.updateX(r.options.page.xpading),r.deactivateInlineLock();return}let o=[u.Strong,u.Em,u.Text,u.CodeSpan,u.Link,u.Image,u.Br];if(t.items.some(e=>!o.includes(e.type))){let s=[],c=()=>{s.length>0&&(j.renderStyledParagraph(e,s,r.X+n,r.Y,a,r),s.length=0)};for(let e of t.items)o.includes(e.type)?s.push(e):(c(),i(e,n,r,!1));c()}else j.renderStyledParagraph(e,t.items,r.X+n,r.Y,a,r)}else{let i=t.content??``,o=r.options.content?.textAlignment??`left`;i.trim()&&M.renderText(e,i,r,r.X+n,r.Y,a,o===`justify`)}r.updateX(r.options.page.xpading),r.deactivateInlineLock()},P=(e,t,n,r,i)=>{e.setFontSize(r.options.page.defaultFontSize);for(let[e,a]of t?.items?.entries()??[]){let o=t.ordered?(t.start??0)+e:t.start;i(a,n+1,r,!0,o,t.ordered)}},F=(e,t,n,r,i,a,o)=>{r.Y+S(e)>=r.options.page.maxContentHeight&&T(e,r);let s=r.options,c=n*s.page.indent,l=o?`${a}. `:`• `,d=s.page.xpading;r.updateX(d,`set`),e.setFont(s.font.regular.name,s.font.regular.style),e.text(l,d+c,r.Y,{baseline:`top`});let f=e.getTextWidth(l),p=d+c+f,m=s.page.maxContentWidth-c-f;if(t.items&&t.items.length>0){let s=[],c=()=>{s.length>0&&(j.renderStyledParagraph(e,s,p,r.Y,m,r),s.length=0,r.updateX(d,`set`))};for(let e of t.items)e.type===u.List?(c(),i(e,n,r,!0,a,e.ordered??!1)):e.type===u.ListItem?(c(),i(e,n,r,!0,a,o)):s.push(e);c()}else if(t.content){let n=s.content?.textAlignment??`left`;M.renderText(e,t.content,r,p,r.Y,m,n===`justify`)}},I=(e,t,n,r,i,a,o,s,c=!0)=>{if(t?.items&&t?.items.length>0)for(let e of t?.items??[])a(e,n,r,i,o,s,c);else{let a=r.options,l=n*a.page.indent,u=i?s?`${o}. `:`• `:``,d=t.content||``,f=a.page.xpading;if(!d&&!u)return;if(!d.trim()&&!u){let t=(d.match(/\n/g)||[]).length;if(t>1){let n=(t-1)*(e.getTextDimensions(`A`).h*a.page.defaultLineHeightFactor);r.Y+n>a.page.maxContentHeight?T(e,r):(r.updateY(n,`add`),r.recordContentY(r.Y))}return}if(r.updateX(f,`set`),i&&u){let t=e.getTextWidth(u),n=a.page.maxContentWidth-l-t;e.setFont(a.font.regular.name,a.font.regular.style),e.text(u,f+l,r.Y,{baseline:`top`}),M.renderText(e,d,r,f+l+t,r.Y,n,c)}else{let t=a.page.maxContentWidth-l;M.renderText(e,d,r,f+l,r.Y,t,c)}r.updateX(f,`set`)}},L=(e,t)=>{let n=e.internal.pageSize.getWidth();e.setLineDashPattern([1,1],0),e.setLineWidth(.1),e.line(t.options.page.xpading,t.Y,n-t.options.page.xpading,t.Y),e.setLineWidth(.1),e.setLineDashPattern([],0),t.updateY(S(e),`add`)},R=(e,t,n,r)=>{let i=e.getFont(),a=e.getFontSize();e.setFont(`courier`,`normal`);let o=r.options.page.defaultFontSize*.9;e.setFontSize(o);let s=n*r.options.page.indent,c=r.options.page.maxContentWidth-s-8,l=e.getLineHeightFactor(),u=o/e.internal.scaleFactor*l,d=(t.code??``).replace(/[\r\n\s]+$/,``);if(!d){e.setFont(i.fontName,i.fontStyle),e.setFontSize(a);return}let f=e.splitTextToSize(d,c);for(;f.length>0&&f[f.length-1].trim()===``;)f.pop();if(f.length===0){e.setFont(i.fontName,i.fontStyle),e.setFontSize(a);return}let p=0;for(;p<f.length;){let n=r.options.page.maxContentHeight-r.Y,i=f.length-p,a=n-8,o=Math.floor(a/u);if(o<=0){T(e,r);continue}o>i&&(o=i);let s=f.slice(p,p+o),c=p===0,l=p+o>=f.length,d=o*u;if(c&&r.updateY(4,`add`),e.setFillColor(`#EEEEEE`),e.setDrawColor(`#DDDDDD`),e.roundedRect(r.X,r.Y-4,r.options.page.maxContentWidth,d+(c?4:0)+(l?4:0),2,2,`FD`),c&&t.lang){let n=e.getFontSize();e.setFontSize(10),e.setTextColor(`#666666`),e.text(t.lang,r.X+r.options.page.maxContentWidth-e.getTextWidth(t.lang)-4,r.Y,{baseline:`top`}),e.setFontSize(n),e.setTextColor(`#000000`)}let m=r.Y;for(let t of s)e.text(t,r.X+4,m,{baseline:`top`}),m+=u;r.updateY(d,`add`),r.recordContentY(r.Y+(l?4:0)),l&&r.updateY(4,`add`),p+=o,p<f.length&&T(e,r)}e.setFont(i.fontName,i.fontStyle),e.setFontSize(a)},z=(e,t,n,r)=>{let i=e.getFont().fontName,a=e.getFont().fontStyle,o=e.getFontSize(),s=e=>{switch(e){case`normal`:return 0;case`bold`:return 1;case`italic`:return 1.5;case`bolditalic`:return 1.5;case`codespan`:return .5;default:return 0}},c=(t,c)=>{c===`bold`?e.setFont(r.options.font.bold.name&&r.options.font.bold.name!==``?r.options.font.bold.name:i,r.options.font.bold.style||`bold`):c===`italic`?e.setFont(r.options.font.regular.name,`italic`):c===`bolditalic`?e.setFont(r.options.font.bold.name&&r.options.font.bold.name!==``?r.options.font.bold.name:i,`bolditalic`):c===`codespan`?(e.setFont(`courier`,`normal`),e.setFontSize(o*.9)):e.setFont(r.options.font.regular.name,a);let l=r.options.page.maxContentWidth-n-r.X,u=e.splitTextToSize(t,l),d=c===`codespan`,f=`#EEEEEE`;if(r.isInlineLockActive)for(let t=0;t<u.length;t++){if(d){let i=e.getTextWidth(u[t])+C(e),a=S(e);e.setFillColor(f),e.roundedRect(r.X+n-1,r.Y-1,i+2,a+2,2,2,`F`),e.setFillColor(`#000000`)}e.text(u[t],r.X+n,r.Y,{baseline:`top`,maxWidth:l}),r.updateX(e.getTextDimensions(u[t]).w+(d?2:1),`add`),t<u.length-1&&(r.updateY(S(e),`add`),r.updateX(r.options.page.xpading,`set`))}else if(u.length>1){let t=u[0],i=u?.slice(1)?.join(` `);if(d){let i=e.getTextWidth(t)+C(e),a=S(e);e.setFillColor(f),e.roundedRect(r.X+(n>=2?n+2:0)-1,r.Y-1,i+2,a+2,2,2,`F`),e.setFillColor(`#000000`)}e.text(t,r.X+(n>=2?n+2*s(c):0),r.Y,{baseline:`top`,maxWidth:l}),r.updateX(r.options.page.xpading+n),r.updateY(S(e),`add`);let a=r.options.page.maxContentWidth-n-r.options.page.xpading;e.splitTextToSize(i,a).forEach(t=>{if(d){let n=e.getTextWidth(t)+C(e),i=S(e);e.setFillColor(f),e.roundedRect(r.X+C(e)-1,r.Y-1,n+2,i+2,2,2,`F`),e.setFillColor(`#000000`)}e.text(t,r.X+C(e),r.Y,{baseline:`top`,maxWidth:a})})}else{if(d){let i=e.getTextWidth(t)+C(e),a=S(e);e.setFillColor(f),e.roundedRect(r.X+n-1,r.Y-1,i+2,a+2,2,2,`F`),e.setFillColor(`#000000`)}e.text(t,r.X+n,r.Y,{baseline:`top`,maxWidth:l}),r.updateX(e.getTextDimensions(t).w+(n>=2?t.split(` `).length+2:2)*s(c)*.5+(d?2:0),`add`)}};if(t.type===`text`&&t.items&&t.items.length>0)for(let e of t.items)if(e.type===`codespan`)c(e.content||``,`codespan`);else if(e.type===`em`||e.type===`strong`){let t=e.type===`em`?`italic`:`bold`;if(e.items&&e.items.length>0)for(let n of e.items)n.type===`strong`&&t===`italic`||n.type===`em`&&t===`bold`?c(n.content||``,`bolditalic`):c(n.content||``,t);else c(e.content||``,t)}else c(e.content||``,`normal`);else t.type===`em`?c(t.content||``,`italic`):t.type===`strong`?c(t.content||``,`bold`):t.type===`codespan`?c(t.content||``,`codespan`):c(t.content||``,`normal`);e.setFont(i,a),e.setFontSize(o)},B=(e,t,n,r)=>{let i=e.getFont().fontName,a=e.getFont().fontStyle,o=e.getFontSize(),s=e.getTextColor(),c=r.options.link?.linkColor||[0,0,255];e.setTextColor(...c);let l=r.options.page.maxContentWidth-n-r.X,u=t.text||t.content||``,d=t.href||``,f=e.splitTextToSize(u,l);if(r.isInlineLockActive)for(let t=0;t<f.length;t++){let i=e.getTextDimensions(f[t]).w,a=S(e)/2;e.link(r.X+n,r.Y,i,a,{url:d}),e.text(f[t],r.X+n,r.Y,{baseline:`top`,maxWidth:l}),r.updateX(i+1,`add`),r.X+i>r.options.page.maxContentWidth-n&&(r.updateY(a,`add`),r.updateX(r.options.page.xpading+n,`set`)),t<f.length-1&&(r.updateY(a,`add`),r.updateX(r.options.page.xpading+n,`set`))}else if(f.length>1){let t=f[0],i=f?.slice(1)?.join(` `),a=e.getTextDimensions(t).w,o=S(e)/2;e.link(r.X+n,r.Y,a,o,{url:d}),e.text(t,r.X+n,r.Y,{baseline:`top`,maxWidth:l}),r.updateX(r.options.page.xpading+n),r.updateY(o,`add`);let s=r.options.page.maxContentWidth-n-r.options.page.xpading;e.splitTextToSize(i,s).forEach(t=>{let n=e.getTextDimensions(t).w;e.link(r.X+C(e),r.Y,n,o,{url:d}),e.text(t,r.X+C(e),r.Y,{baseline:`top`,maxWidth:s})})}else{let t=e.getTextDimensions(u).w,i=S(e)/2;e.link(r.X+n,r.Y,t,i,{url:d}),e.text(u,r.X+n,r.Y,{baseline:`top`,maxWidth:l}),r.updateX(t+2,`add`)}e.setFont(i,a),e.setFontSize(o),e.setTextColor(s)},V=(e,t,n,r,i)=>{let a=r.options,o=n+1,s=r.X+n*a.page.indent,c=r.Y,l=s+a.page.indent/2,u=c,d=e.internal.getCurrentPageInfo().pageNumber;t.items&&t.items.length>0&&t.items.forEach(e=>{i(e,o,r)});let f=r.Y,p=e.internal.getCurrentPageInfo().pageNumber;e.setDrawColor(100),e.setLineWidth(1);for(let t=d;t<=p;t++){e.setPage(t);let n=t===d,r=t===p,i=n?u:a.page.topmargin,o=r?f:a.page.maxContentHeight;e.line(l,i,l,o)}r.recordContentY(),e.setPage(p)},H=e=>{if(e.data){if(e.data.startsWith(`data:image/png`))return`PNG`;if(e.data.startsWith(`data:image/jpeg`)||e.data.startsWith(`data:image/jpg`))return`JPEG`;if(e.data.startsWith(`data:image/webp`)||e.data.startsWith(`data:image/webp`))return`WEBP`;if(e.data.startsWith(`data:image/gif`))return`GIF`}if(e.src){let t=e.src.split(`?`)[0].split(`#`)[0].split(`.`).pop()?.toUpperCase();if(t&&[`PNG`,`JPEG`,`JPG`,`WEBP`,`GIF`].includes(t))return t===`JPG`?`JPEG`:t}return`JPEG`},U=(e,t,n,r)=>{if(!t.data)return;let i=r.options,a=i.page.unit||`mm`,o=n*i.page.indent,s=i.page.maxContentWidth-o,c=r.X+o,l=r.Y;try{let{finalWidth:n,finalHeight:o}=k(e,t,s,i.page.maxContentHeight-i.page.topmargin,a);l+o>i.page.maxContentHeight&&(T(e,r),l=r.Y);let u=t.align||i.image?.defaultAlign||`left`,d;switch(u){case`right`:d=c+s-n;break;case`center`:d=c+(s-n)/2;break;default:d=c;break}let f=H(t);n>0&&o>0&&e.addImage(t.data,f,d,l,n,o),r.updateY(o,`add`),r.recordContentY()}catch(e){console.warn(`Failed to render image`,e)}},W=()=>{let e=l.default;if(typeof l.default==`function`)return l.default;if(typeof e.default==`function`)return e.default;if(typeof e.autoTable==`function`)return e.autoTable;throw Error(`Could not resolve jspdf-autotable export. Expected a callable export.`)},G=(e,t,n,r)=>{if(!t.header||!t.rows)return;let i=r.options,a=i.page.xmargin+n*i.page.indent,o=[t.header.map(e=>e.content||``)],s=t.rows.map(e=>e.map(e=>e.content||``)),c=i.table||{};W()(e,{head:o,body:s,startY:r.Y,margin:{left:a,right:i.page.xmargin},...c,didDrawPage:e=>{c.didDrawPage&&c.didDrawPage(e)},didDrawCell:e=>{c.didDrawCell&&c.didDrawCell(e)}});let l=e.lastAutoTable?.finalY;typeof l==`number`&&(r.updateY(l+i.page.lineSpace,`set`),r.updateX(i.page.xpading,`set`),r.recordContentY())},K=class{constructor(e){this.cursor={x:0,y:0},this.lastContentY_=0,this.inlineLock=!1,this.options_=e,this.cursor={x:e.cursor.x,y:e.cursor.y},this.lastContentY_=e.cursor.y}getCursor(){return this.cursor}setCursor(e){this.cursor=e}get options(){return this.options_}get isInlineLockActive(){return this.inlineLock}activateInlineLock(){this.inlineLock=!0}deactivateInlineLock(){this.inlineLock=!1}updateX(e,t=`set`){t===`set`?this.cursor.x=e:t===`add`&&(this.cursor.x+=e)}updateY(e,t=`set`){t===`set`?this.cursor.y=e:t===`add`&&(this.cursor.y+=e)}recordContentY(e){this.lastContentY_=e===void 0?this.cursor.y:e}get lastContentY(){return this.lastContentY_}get X(){return this.cursor.x}get Y(){return this.cursor.y}},q={page:{indent:10,maxContentWidth:190,maxContentHeight:277,lineSpace:1.5,defaultLineHeightFactor:1.2,defaultFontSize:12,defaultTitleFontSize:14,topmargin:10,xpading:10,xmargin:10,format:`a4`,orientation:`p`},font:{bold:{name:`helvetica`,style:`bold`},regular:{name:`helvetica`,style:`normal`},light:{name:`helvetica`,style:`light`}},image:{defaultAlign:`left`}},J=e=>{if(!e)throw Error(`RenderOption is required`);let t={...q.page,...e.page},n={...q.font,...e.font},r={...q.image,...e.image};return t.maxContentWidth||=190,t.maxContentHeight||=277,{...e,page:t,font:n,image:r}},Y=async(e,t,n)=>{let r=J(n),i=new K(r),a=await y(t);await A(a);let o=(t,n=0,i,a=!1,s=0,c=!1)=>{let l=n*r.page.indent;switch(t.type){case u.Heading:w(e,t,l,i,o);break;case u.Paragraph:N(e,t,l,i,o);break;case u.List:P(e,t,n,i,o);break;case u.ListItem:F(e,t,n,i,o,s,c);break;case u.Hr:L(e,i);break;case u.Code:R(e,t,n,i);break;case u.Strong:case u.Em:case u.CodeSpan:z(e,t,l,i);break;case u.Link:B(e,t,l,i);break;case u.Blockquote:V(e,t,n,i,o);break;case u.Image:U(e,t,n,i);break;case u.Br:{i.updateX(r.page.xpading,`set`);let t=S(e)*r.page.defaultLineHeightFactor;i.Y+t>r.page.maxContentHeight?T(e,i):i.updateY(t,`add`),i.recordContentY();break}case u.Table:G(e,t,n,i);break;case u.Raw:case u.Text:I(e,t,n,i,a,o,s,c,r.content?.textAlignment===`justify`);break;default:console.warn(`Warning: Unsupported element type encountered: ${t.type}.
1
+ /*!
2
+ * jspdf-md-renderer
3
+ *
4
+ * MIT License
5
+ *
6
+ * Copyright (c) 2026 Jeel Gajera
7
+ *
8
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ * of this software and associated documentation files (the "Software"), to deal
10
+ * in the Software without restriction, including without limitation the rights
11
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ * copies of the Software, and to permit persons to whom the Software is
13
+ * furnished to do so, subject to the following conditions:
14
+ *
15
+ * The above copyright notice and this permission notice shall be included in all
16
+ * copies or substantial portions of the Software.
17
+ *
18
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ * SOFTWARE.
25
+ *
26
+ */
27
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
28
+ //#region \0rolldown/runtime.js
29
+ var __create = Object.create;
30
+ var __defProp = Object.defineProperty;
31
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
32
+ var __getOwnPropNames = Object.getOwnPropertyNames;
33
+ var __getProtoOf = Object.getPrototypeOf;
34
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
35
+ var __copyProps = (to, from, except, desc) => {
36
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
37
+ key = keys[i];
38
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
39
+ get: ((k) => from[k]).bind(null, key),
40
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
41
+ });
42
+ }
43
+ return to;
44
+ };
45
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
46
+ value: mod,
47
+ enumerable: true
48
+ }) : target, mod));
49
+ //#endregion
50
+ let marked = require("marked");
51
+ let jspdf_autotable = require("jspdf-autotable");
52
+ jspdf_autotable = __toESM(jspdf_autotable);
53
+ //#region src/parser/imageExtension.ts
54
+ /**
55
+ * Internal hash prefix used to encode image attributes in the URL fragment.
56
+ * This is stripped during token conversion and never reaches the image fetcher.
57
+ */
58
+ const ATTR_HASH_PREFIX = "__jmr_";
59
+ /**
60
+ * Regex to match an image tag followed by an attribute block.
61
+ * Captures:
62
+ * Group 1: Everything before the closing `)` (i.e., `![alt](url`)
63
+ * Group 2: The image URL inside the parentheses
64
+ * Group 3: The attribute block content (e.g., `width=200 height=150 align=center`)
65
+ *
66
+ * Pattern: ![...](url){key=value ...}
67
+ */
68
+ const IMAGE_WITH_ATTRS_REGEX = /(!\[[^\]]*\]\()([^)]+)(\))\s*\{([^}]+)\}/g;
69
+ /**
70
+ * Regex to extract individual key=value pairs from the attribute block.
71
+ */
72
+ const ATTR_PAIR_REGEX = /(\w+)\s*=\s*(\w+)/g;
73
+ /** Valid alignment values */
74
+ const VALID_ALIGNMENTS = [
75
+ "left",
76
+ "center",
77
+ "right"
78
+ ];
79
+ /**
80
+ * Encodes image attributes into a URL hash fragment.
81
+ * Example: {width: 200, height: 100, align: 'center'} → '#__jmr_w=200&h=100&a=center'
82
+ */
83
+ const encodeAttrsToFragment = (attrs) => {
84
+ const parts = [];
85
+ if (attrs.width !== void 0) parts.push(`w=${attrs.width}`);
86
+ if (attrs.height !== void 0) parts.push(`h=${attrs.height}`);
87
+ if (attrs.align) parts.push(`a=${attrs.align}`);
88
+ return parts.length > 0 ? `#${ATTR_HASH_PREFIX}${parts.join("&")}` : "";
89
+ };
90
+ /**
91
+ * Parses an attribute string like "width=200 height=150 align=center"
92
+ * into a structured object.
93
+ */
94
+ const parseRawAttributes = (attrString) => {
95
+ const attrs = {};
96
+ let match;
97
+ while ((match = ATTR_PAIR_REGEX.exec(attrString)) !== null) {
98
+ const key = match[1].toLowerCase();
99
+ const value = match[2];
100
+ switch (key) {
101
+ case "width":
102
+ case "w": {
103
+ const num = parseInt(value, 10);
104
+ if (!isNaN(num) && num > 0) attrs.width = num;
105
+ break;
106
+ }
107
+ case "height":
108
+ case "h": {
109
+ const num = parseInt(value, 10);
110
+ if (!isNaN(num) && num > 0) attrs.height = num;
111
+ break;
112
+ }
113
+ case "align": {
114
+ const alignVal = value.toLowerCase();
115
+ if (VALID_ALIGNMENTS.includes(alignVal)) attrs.align = alignVal;
116
+ break;
117
+ }
118
+ }
119
+ }
120
+ return attrs;
121
+ };
122
+ /**
123
+ * Pre-processes markdown text to embed image attributes into URL fragments.
124
+ *
125
+ * Transforms `![alt](url){width=200 align=center}` into
126
+ * `![alt](url#__jmr_w=200&a=center)` so that each image token
127
+ * carries its own attributes — no shared state needed.
128
+ *
129
+ * Supported attributes:
130
+ * - `width` or `w`: Image width in pixels (number)
131
+ * - `height` or `h`: Image height in pixels (number)
132
+ * - `align`: Image alignment - 'left', 'center', or 'right'
133
+ *
134
+ * @param text - The raw markdown text
135
+ * @returns The cleaned markdown text with attributes encoded in URLs
136
+ */
137
+ const preprocessImageAttributes = (text) => {
138
+ return text.replace(IMAGE_WITH_ATTRS_REGEX, (_fullMatch, before, url, closeParen, attrsContent) => {
139
+ return `${before}${url}${encodeAttrsToFragment(parseRawAttributes(attrsContent))}${closeParen}`;
140
+ });
141
+ };
142
+ /**
143
+ * Extracts image attributes from a URL that may contain an encoded fragment.
144
+ * Returns the clean URL (without the attribute fragment) and parsed attributes.
145
+ *
146
+ * @param href - The image URL, possibly containing `#__jmr_...` fragment
147
+ * @returns Object with cleanHref and parsed attrs
148
+ */
149
+ const parseImageAttrsFromHref = (href) => {
150
+ const fragmentIdx = href.indexOf(`#${ATTR_HASH_PREFIX}`);
151
+ if (fragmentIdx === -1) return {
152
+ cleanHref: href,
153
+ attrs: {}
154
+ };
155
+ const cleanHref = href.substring(0, fragmentIdx);
156
+ const fragment = href.substring(fragmentIdx + 1 + 6);
157
+ const attrs = {};
158
+ const pairs = fragment.split("&");
159
+ for (const pair of pairs) {
160
+ const [key, value] = pair.split("=");
161
+ switch (key) {
162
+ case "w": {
163
+ const num = parseInt(value, 10);
164
+ if (!isNaN(num) && num > 0) attrs.width = num;
165
+ break;
166
+ }
167
+ case "h": {
168
+ const num = parseInt(value, 10);
169
+ if (!isNaN(num) && num > 0) attrs.height = num;
170
+ break;
171
+ }
172
+ case "a":
173
+ if (VALID_ALIGNMENTS.includes(value)) attrs.align = value;
174
+ break;
175
+ }
176
+ }
177
+ return {
178
+ cleanHref,
179
+ attrs
180
+ };
181
+ };
182
+ //#endregion
183
+ //#region src/parser/MdTextParser.ts
184
+ /**
185
+ * Parses markdown into tokens and converts to a custom parsed structure.
186
+ *
187
+ * @param text - The markdown content to parse.
188
+ * @returns Parsed markdown elements.
189
+ */
190
+ const MdTextParser = async (text) => {
191
+ const processedText = preprocessImageAttributes(text);
192
+ return convertTokens(await marked.marked.lexer(processedText, {
193
+ async: true,
194
+ gfm: true
195
+ }));
196
+ };
197
+ /**
198
+ * Convert the markdown tokens to ParsedElements.
199
+ *
200
+ * @param tokens - The list of markdown tokens.
201
+ * @returns Parsed elements in a custom structure.
202
+ */
203
+ const convertTokens = (tokens) => {
204
+ const parsedElements = [];
205
+ tokens.forEach((token) => {
206
+ try {
207
+ const handler = tokenHandlers[token.type];
208
+ if (handler) parsedElements.push(handler(token));
209
+ else parsedElements.push({
210
+ type: "raw",
211
+ content: token.raw
212
+ });
213
+ } catch (error) {
214
+ console.error("Failed to handle token ==>", token, error);
215
+ }
216
+ });
217
+ return parsedElements;
218
+ };
219
+ /**
220
+ * Map each token type to its handler function.
221
+ */
222
+ const tokenHandlers = {
223
+ ["heading"]: (token) => ({
224
+ type: "heading",
225
+ depth: token.depth,
226
+ content: token.text,
227
+ items: token.tokens ? convertTokens(token.tokens) : []
228
+ }),
229
+ ["paragraph"]: (token) => ({
230
+ type: "paragraph",
231
+ content: token.text,
232
+ items: token.tokens ? convertTokens(token.tokens) : []
233
+ }),
234
+ ["list"]: (token) => ({
235
+ type: "list",
236
+ ordered: token.ordered,
237
+ start: token.start,
238
+ items: token.items ? convertTokens(token.items) : []
239
+ }),
240
+ ["list_item"]: (token) => ({
241
+ type: "list_item",
242
+ content: token.text,
243
+ items: token.tokens ? convertTokens(token.tokens) : []
244
+ }),
245
+ ["code"]: (token) => ({
246
+ type: "code",
247
+ lang: token.lang,
248
+ code: token.text
249
+ }),
250
+ ["table"]: (token) => ({
251
+ type: "table",
252
+ header: token.header.map((header) => ({
253
+ type: "table_header",
254
+ content: header.text
255
+ })),
256
+ rows: token.rows.map((row) => row.map((cell) => ({
257
+ type: "table_cell",
258
+ content: cell.text
259
+ })))
260
+ }),
261
+ ["image"]: (token) => {
262
+ const { cleanHref, attrs } = parseImageAttrsFromHref(token.href);
263
+ return {
264
+ type: "image",
265
+ src: cleanHref,
266
+ alt: token.text,
267
+ width: attrs.width,
268
+ height: attrs.height,
269
+ align: attrs.align
270
+ };
271
+ },
272
+ ["link"]: (token) => ({
273
+ type: "link",
274
+ href: token.href,
275
+ text: token.text,
276
+ items: token.tokens ? convertTokens(token.tokens) : []
277
+ }),
278
+ ["strong"]: (token) => ({
279
+ type: "strong",
280
+ content: token.text,
281
+ items: token.tokens ? convertTokens(token.tokens) : []
282
+ }),
283
+ ["em"]: (token) => ({
284
+ type: "em",
285
+ content: token.text,
286
+ items: token.tokens ? convertTokens(token.tokens) : []
287
+ }),
288
+ ["text"]: (token) => ({
289
+ type: "text",
290
+ content: token.text,
291
+ items: token.tokens ? convertTokens(token.tokens) : []
292
+ }),
293
+ ["hr"]: (token) => ({
294
+ type: "hr",
295
+ content: token.raw,
296
+ items: token.tokens ? convertTokens(token.tokens) : []
297
+ }),
298
+ ["codespan"]: (token) => ({
299
+ type: "codespan",
300
+ content: token.text,
301
+ items: token.tokens ? convertTokens(token.tokens) : []
302
+ }),
303
+ ["blockquote"]: (token) => ({
304
+ type: "blockquote",
305
+ content: token.text,
306
+ items: token.tokens ? convertTokens(token.tokens) : []
307
+ }),
308
+ ["html"]: (token) => {
309
+ const rawHtml = String(token.raw ?? token.text ?? "").trim();
310
+ if (/^<br\s*\/?>$/i.test(rawHtml)) return {
311
+ type: "br",
312
+ content: "\n"
313
+ };
314
+ return {
315
+ type: "raw",
316
+ content: token.raw ?? token.text ?? ""
317
+ };
318
+ },
319
+ ["br"]: () => ({
320
+ type: "br",
321
+ content: "\n"
322
+ })
323
+ };
324
+ //#endregion
325
+ //#region src/utils/doc-helpers.ts
326
+ const getCharHight = (doc) => {
327
+ return doc.getTextDimensions("H").h;
328
+ };
329
+ const getCharWidth = (doc) => {
330
+ return doc.getTextDimensions("H").w;
331
+ };
332
+ //#endregion
333
+ //#region src/utils/handlePageBreak.ts
334
+ const HandlePageBreaks = (doc, store) => {
335
+ if (typeof store.options.pageBreakHandler === "function") store.options.pageBreakHandler(doc);
336
+ else doc.addPage(store.options.page?.format, store.options.page?.orientation);
337
+ store.updateY(store.options.page.topmargin);
338
+ store.updateX(store.options.page.xpading);
339
+ };
340
+ //#endregion
341
+ //#region src/utils/image-utils.ts
342
+ /**
343
+ * Standard DPI for web/screen pixels.
344
+ */
345
+ const DEFAULT_DPI = 96;
346
+ /**
347
+ * Converts pixel values to the document's unit system.
348
+ * Uses 96 DPI as the standard web pixel density.
349
+ *
350
+ * @param px - Value in pixels
351
+ * @param unit - The document unit ('mm' | 'pt' | 'in' | 'px')
352
+ * @returns Value in document units
353
+ */
354
+ const pxToDocUnit = (px, unit = "mm") => {
355
+ switch (unit) {
356
+ case "pt": return px * 72 / DEFAULT_DPI;
357
+ case "in": return px / DEFAULT_DPI;
358
+ case "px": return px;
359
+ default: return px * 25.4 / DEFAULT_DPI;
360
+ }
361
+ };
362
+ /**
363
+ * Extracts width and height from an SVG data URI if possible.
364
+ */
365
+ const extractSvgDimensions = (dataUri) => {
366
+ try {
367
+ let svgString = "";
368
+ if (dataUri.includes("base64,")) {
369
+ const base64 = dataUri.split("base64,")[1];
370
+ if (typeof window !== "undefined" && typeof window.atob === "function") svgString = decodeURIComponent(escape(window.atob(base64)));
371
+ else if (typeof Buffer !== "undefined") svgString = Buffer.from(base64, "base64").toString("utf-8");
372
+ else svgString = decodeURIComponent(escape(atob(base64)));
373
+ } else svgString = decodeURIComponent(dataUri.split(",")[1] || "");
374
+ const widthMatch = svgString.match(/<svg[^>]*\swidth=(?:'|")([0-9.]+)[a-zA-Z]*(?:'|")/i);
375
+ const heightMatch = svgString.match(/<svg[^>]*\sheight=(?:'|")([0-9.]+)[a-zA-Z]*(?:'|")/i);
376
+ const viewBoxMatch = svgString.match(/<svg[^>]*\sviewBox=(?:'|")[^'"]*(?:'|")/i);
377
+ let w = widthMatch ? parseFloat(widthMatch[1]) : 0;
378
+ let h = heightMatch ? parseFloat(heightMatch[1]) : 0;
379
+ if ((!w || !h) && viewBoxMatch) {
380
+ const viewBoxStr = viewBoxMatch[0].match(/viewBox=(?:'|")([^'"]+)(?:'|")/i);
381
+ if (viewBoxStr) {
382
+ const parts = viewBoxStr[1].split(/[ ,]+/).filter(Boolean).map(parseFloat);
383
+ if (parts.length >= 4) {
384
+ w = w || parts[2];
385
+ h = h || parts[3];
386
+ }
387
+ }
388
+ }
389
+ if (w > 0 && h > 0) return {
390
+ width: w,
391
+ height: h
392
+ };
393
+ } catch (e) {
394
+ console.warn("Failed to extract SVG dimensions:", e);
395
+ }
396
+ return null;
397
+ };
398
+ /**
399
+ * Calculates final dimensions for an image, respecting intrinsic size,
400
+ * user-specified attributes, and page bounds.
401
+ */
402
+ const calculateImageDimensions = (doc, element, maxWidth, maxHeight, docUnit = "mm") => {
403
+ if (!element.data) return {
404
+ finalWidth: 0,
405
+ finalHeight: 0
406
+ };
407
+ let intrinsicPxW = element.naturalWidth || 0;
408
+ let intrinsicPxH = element.naturalHeight || 0;
409
+ if (!intrinsicPxW || !intrinsicPxH) if (!element.data.startsWith("data:image/svg")) try {
410
+ const props = doc.getImageProperties(element.data);
411
+ intrinsicPxW = props.width;
412
+ intrinsicPxH = props.height;
413
+ } catch (e) {
414
+ console.warn("Failed to get image properties for intrinsic sizing:", e);
415
+ }
416
+ else {
417
+ const svgDims = extractSvgDimensions(element.data);
418
+ if (svgDims) {
419
+ intrinsicPxW = svgDims.width;
420
+ intrinsicPxH = svgDims.height;
421
+ }
422
+ }
423
+ const aspectRatio = intrinsicPxH > 0 ? intrinsicPxW / intrinsicPxH : 1;
424
+ let finalWidth;
425
+ let finalHeight;
426
+ if (element.width && element.height) {
427
+ finalWidth = pxToDocUnit(element.width, docUnit);
428
+ finalHeight = pxToDocUnit(element.height, docUnit);
429
+ } else if (element.width) {
430
+ finalWidth = pxToDocUnit(element.width, docUnit);
431
+ finalHeight = finalWidth / aspectRatio;
432
+ } else if (element.height) {
433
+ finalHeight = pxToDocUnit(element.height, docUnit);
434
+ finalWidth = finalHeight * aspectRatio;
435
+ } else {
436
+ finalWidth = pxToDocUnit(intrinsicPxW, docUnit);
437
+ finalHeight = pxToDocUnit(intrinsicPxH, docUnit);
438
+ }
439
+ if (finalWidth > maxWidth) {
440
+ const scale = maxWidth / finalWidth;
441
+ finalWidth = maxWidth;
442
+ finalHeight = finalHeight * scale;
443
+ }
444
+ if (finalHeight > maxHeight) {
445
+ const scale = maxHeight / finalHeight;
446
+ finalHeight = maxHeight;
447
+ finalWidth = finalWidth * scale;
448
+ }
449
+ return {
450
+ finalWidth,
451
+ finalHeight
452
+ };
453
+ };
454
+ /**
455
+ * Recursively traverses parsed elements and loads image data for Image tokens.
456
+ * @param elements - The parsed elements to process.
457
+ */
458
+ const prefetchImages = async (elements) => {
459
+ for (const element of elements) {
460
+ if (element.type === "image" && element.src) try {
461
+ if (element.src.startsWith("data:")) element.data = element.src;
462
+ else {
463
+ const response = await fetch(element.src);
464
+ if (!response.ok) throw new Error(`Failed to fetch image: ${response.statusText}`);
465
+ const blob = await response.blob();
466
+ element.data = await new Promise((resolve, reject) => {
467
+ const reader = new FileReader();
468
+ reader.onloadend = () => {
469
+ if (typeof reader.result === "string") resolve(reader.result);
470
+ else reject(/* @__PURE__ */ new Error("Failed to convert image to base64 string"));
471
+ };
472
+ reader.onerror = reject;
473
+ reader.readAsDataURL(blob);
474
+ });
475
+ }
476
+ if (element.data && element.data.startsWith("data:image/svg")) {
477
+ if (typeof window !== "undefined" && typeof document !== "undefined") element.data = await new Promise((resolve) => {
478
+ const img = new Image();
479
+ img.onload = () => {
480
+ const canvas = document.createElement("canvas");
481
+ const dims = extractSvgDimensions(element.data);
482
+ const w = dims ? dims.width : img.width || 300;
483
+ const h = dims ? dims.height : img.height || 150;
484
+ element.naturalWidth = w;
485
+ element.naturalHeight = h;
486
+ const scale = 4;
487
+ canvas.width = w * scale;
488
+ canvas.height = h * scale;
489
+ const ctx = canvas.getContext("2d");
490
+ if (ctx) {
491
+ ctx.scale(scale, scale);
492
+ ctx.drawImage(img, 0, 0, w, h);
493
+ resolve(canvas.toDataURL("image/png"));
494
+ } else resolve(element.data);
495
+ };
496
+ img.onerror = () => resolve(element.data);
497
+ img.src = element.data;
498
+ });
499
+ }
500
+ } catch (error) {
501
+ console.warn(`[jspdf-md-renderer] Warning: Failed to load image at ${element.src}. It will be skipped.`, error);
502
+ }
503
+ if (element.items && element.items.length > 0) await prefetchImages(element.items);
504
+ }
505
+ };
506
+ //#endregion
507
+ //#region src/utils/justifiedTextRenderer.ts
508
+ /**
509
+ * JustifiedTextRenderer - Renders mixed inline elements with proper alignment.
510
+ *
511
+ * Features:
512
+ * - Handles bold, italic, codespan, links mixed in paragraph
513
+ * - Proper word spacing distribution for justified alignment
514
+ * - Supports left, right, center, and justify alignments
515
+ * - Page break handling
516
+ * - Preserves link clickability
517
+ * - Codespan background rendering
518
+ */
519
+ var JustifiedTextRenderer = class {
520
+ static getCodespanOptions(store) {
521
+ const opts = store.options.codespan ?? {};
522
+ return {
523
+ backgroundColor: opts.backgroundColor ?? "#EEEEEE",
524
+ padding: opts.padding ?? .5,
525
+ showBackground: opts.showBackground !== false,
526
+ fontSizeScale: opts.fontSizeScale ?? .9
527
+ };
528
+ }
529
+ /**
530
+ * Apply font style to the jsPDF document.
531
+ */
532
+ static applyStyle(doc, style, store) {
533
+ const currentFont = doc.getFont().fontName;
534
+ const currentFontSize = doc.getFontSize();
535
+ const getBoldFont = () => {
536
+ const boldName = store.options.font.bold?.name;
537
+ return boldName && boldName !== "" ? boldName : currentFont;
538
+ };
539
+ const getRegularFont = () => {
540
+ const regularName = store.options.font.regular?.name;
541
+ return regularName && regularName !== "" ? regularName : currentFont;
542
+ };
543
+ switch (style) {
544
+ case "bold":
545
+ doc.setFont(getBoldFont(), store.options.font.bold?.style || "bold");
546
+ break;
547
+ case "italic":
548
+ doc.setFont(getRegularFont(), "italic");
549
+ break;
550
+ case "bolditalic":
551
+ doc.setFont(getBoldFont(), "bolditalic");
552
+ break;
553
+ case "codespan":
554
+ const codeFont = store.options.font.code || {
555
+ name: "courier",
556
+ style: "normal"
557
+ };
558
+ doc.setFont(codeFont.name, codeFont.style);
559
+ doc.setFontSize(currentFontSize * this.getCodespanOptions(store).fontSizeScale);
560
+ break;
561
+ default:
562
+ doc.setFont(getRegularFont(), doc.getFont().fontStyle);
563
+ break;
564
+ }
565
+ }
566
+ /**
567
+ * Measure word width with a specific style applied.
568
+ * NOTE: jsPDF's getTextWidth() does NOT include charSpace in its calculation,
569
+ * so we must manually add it: effectiveWidth = getTextWidth(text) + (text.length * charSpace)
570
+ */
571
+ static measureWordWidth(doc, text, style, store) {
572
+ const savedFont = doc.getFont();
573
+ const savedSize = doc.getFontSize();
574
+ this.applyStyle(doc, style, store);
575
+ const baseWidth = doc.getTextWidth(text);
576
+ const charSpace = doc.getCharSpace?.() ?? 0;
577
+ const effectiveWidth = baseWidth + text.length * charSpace;
578
+ doc.setFont(savedFont.fontName, savedFont.fontStyle);
579
+ doc.setFontSize(savedSize);
580
+ return effectiveWidth;
581
+ }
582
+ /**
583
+ * Extract style from element type string.
584
+ */
585
+ static getStyleFromType(type, parentStyle) {
586
+ switch (type) {
587
+ case "strong":
588
+ if (parentStyle === "italic") return "bolditalic";
589
+ return "bold";
590
+ case "em":
591
+ if (parentStyle === "bold") return "bolditalic";
592
+ return "italic";
593
+ case "codespan": return "codespan";
594
+ default: return parentStyle || "normal";
595
+ }
596
+ }
597
+ /**
598
+ * Flatten ParsedElement tree into an array of StyledWordInfo.
599
+ * Handles nested inline elements.
600
+ */
601
+ static flattenToWords(doc, elements, store, parentStyle = "normal", isLink = false, href) {
602
+ const result = [];
603
+ for (const el of elements) {
604
+ const style = this.getStyleFromType(el.type, parentStyle);
605
+ const elIsLink = el.type === "link" || isLink;
606
+ const elHref = el.href || href;
607
+ if (el.items && el.items.length > 0) {
608
+ const nested = this.flattenToWords(doc, el.items, store, style, elIsLink, elHref);
609
+ result.push(...nested);
610
+ } else if (el.type === "image") {
611
+ const maxH = store.options.page.maxContentHeight - store.options.page.topmargin;
612
+ const { finalWidth, finalHeight } = calculateImageDimensions(doc, el, store.options.page.maxContentWidth - store.options.page.indent * 0, maxH, store.options.page.unit || "mm");
613
+ result.push({
614
+ text: "",
615
+ width: finalWidth,
616
+ style,
617
+ isLink: elIsLink,
618
+ href: elHref,
619
+ linkColor: elIsLink ? store.options.link?.linkColor || [
620
+ 0,
621
+ 0,
622
+ 255
623
+ ] : void 0,
624
+ isImage: true,
625
+ imageElement: el,
626
+ imageHeight: finalHeight
627
+ });
628
+ } else if (el.type === "br") result.push({
629
+ text: "",
630
+ width: 0,
631
+ style,
632
+ isBr: true
633
+ });
634
+ else {
635
+ const text = el.content || el.text || "";
636
+ if (!text) continue;
637
+ if (/^\s/.test(text) && result.length > 0) result[result.length - 1].hasTrailingSpace = true;
638
+ if (style === "codespan") {
639
+ const trimmedText = text.trim();
640
+ if (trimmedText) result.push({
641
+ text: trimmedText,
642
+ width: this.measureWordWidth(doc, trimmedText, style, store),
643
+ style,
644
+ isLink: elIsLink,
645
+ href: elHref,
646
+ linkColor: elIsLink ? store.options.link?.linkColor || [
647
+ 0,
648
+ 0,
649
+ 255
650
+ ] : void 0,
651
+ hasTrailingSpace: /\s$/.test(text)
652
+ });
653
+ continue;
654
+ }
655
+ const lines = text.split("\n");
656
+ for (let partIndex = 0; partIndex < lines.length; partIndex++) {
657
+ const lineStr = lines[partIndex];
658
+ const words = lineStr.trim().split(/[ \t\r\v\f]+/).filter((w) => w.length > 0);
659
+ for (let i = 0; i < words.length; i++) {
660
+ const hasTrailingSpace = !(i === words.length - 1) || /[ \t\r\v\f]$/.test(lineStr);
661
+ result.push({
662
+ text: words[i],
663
+ width: this.measureWordWidth(doc, words[i], style, store),
664
+ style,
665
+ isLink: elIsLink,
666
+ href: elHref,
667
+ linkColor: elIsLink ? store.options.link?.linkColor || [
668
+ 0,
669
+ 0,
670
+ 255
671
+ ] : void 0,
672
+ hasTrailingSpace
673
+ });
674
+ }
675
+ if (partIndex < lines.length - 1) result.push({
676
+ text: "",
677
+ width: 0,
678
+ style,
679
+ isBr: true
680
+ });
681
+ }
682
+ }
683
+ }
684
+ return result;
685
+ }
686
+ /**
687
+ * Break a flat list of words into lines that fit within maxWidth.
688
+ * Correctly tracks totalTextWidth (sum of word widths only) for justification.
689
+ */
690
+ static breakIntoLines(doc, words, maxWidth, store) {
691
+ const lines = [];
692
+ let currentLine = [];
693
+ let currentTextWidth = 0;
694
+ let currentLineWidth = 0;
695
+ let currentLineHeight = getCharHight(doc) * store.options.page.defaultLineHeightFactor;
696
+ const spaceWidth = doc.getTextWidth(" ");
697
+ for (let i = 0; i < words.length; i++) {
698
+ const word = words[i];
699
+ const neededWidthWithSpace = currentLine[currentLine.length - 1]?.hasTrailingSpace ? spaceWidth + word.width : word.width;
700
+ const itemHeight = word.isImage && word.imageHeight ? word.imageHeight : getCharHight(doc) * store.options.page.defaultLineHeightFactor;
701
+ if (word.isBr) {
702
+ lines.push({
703
+ words: currentLine,
704
+ totalTextWidth: currentTextWidth,
705
+ isLastLine: true,
706
+ lineHeight: currentLineHeight
707
+ });
708
+ currentLine = [];
709
+ currentTextWidth = 0;
710
+ currentLineWidth = 0;
711
+ currentLineHeight = getCharHight(doc) * store.options.page.defaultLineHeightFactor;
712
+ continue;
713
+ }
714
+ if (currentLineWidth + neededWidthWithSpace > maxWidth && currentLine.length > 0) {
715
+ lines.push({
716
+ words: currentLine,
717
+ totalTextWidth: currentTextWidth,
718
+ isLastLine: false,
719
+ lineHeight: currentLineHeight
720
+ });
721
+ currentLine = [word];
722
+ currentTextWidth = word.width;
723
+ currentLineWidth = word.width;
724
+ currentLineHeight = itemHeight;
725
+ } else {
726
+ currentLine.push(word);
727
+ currentTextWidth += word.width;
728
+ currentLineWidth += neededWidthWithSpace;
729
+ currentLineHeight = Math.max(currentLineHeight, itemHeight);
730
+ }
731
+ }
732
+ if (currentLine.length > 0) lines.push({
733
+ words: currentLine,
734
+ totalTextWidth: currentTextWidth,
735
+ isLastLine: true,
736
+ lineHeight: currentLineHeight
737
+ });
738
+ return lines;
739
+ }
740
+ /**
741
+ * Render a single word with its style applied.
742
+ */
743
+ static renderWord(doc, word, x, y, store) {
744
+ const savedFont = doc.getFont();
745
+ const savedSize = doc.getFontSize();
746
+ const savedColor = doc.getTextColor();
747
+ this.applyStyle(doc, word.style, store);
748
+ if (word.isLink && word.linkColor) doc.setTextColor(...word.linkColor);
749
+ if (word.isImage && word.imageElement && word.imageElement.data) try {
750
+ let imgFormat = "JPEG";
751
+ if (word.imageElement.data.startsWith("data:image/png")) imgFormat = "PNG";
752
+ else if (word.imageElement.data.startsWith("data:image/webp")) imgFormat = "WEBP";
753
+ else if (word.imageElement.data.startsWith("data:image/gif")) imgFormat = "GIF";
754
+ else if (word.imageElement.src) {
755
+ const ext = word.imageElement.src.split("?")[0].split("#")[0].split(".").pop()?.toUpperCase();
756
+ if (ext && [
757
+ "PNG",
758
+ "JPEG",
759
+ "JPG",
760
+ "WEBP",
761
+ "GIF"
762
+ ].includes(ext)) imgFormat = ext === "JPG" ? "JPEG" : ext;
763
+ }
764
+ if (word.width > 0 && (word.imageHeight || 0) > 0) {
765
+ const imgH = word.imageHeight || 0;
766
+ const imgY = y;
767
+ doc.addImage(word.imageElement.data, imgFormat, x, imgY, word.width, imgH);
768
+ }
769
+ } catch (e) {
770
+ console.warn("Failed to render inline image", e);
771
+ }
772
+ else {
773
+ if (word.style === "codespan") {
774
+ const codespanOpts = this.getCodespanOptions(store);
775
+ if (codespanOpts.showBackground) {
776
+ const h = getCharHight(doc);
777
+ const pad = codespanOpts.padding;
778
+ doc.setFillColor(codespanOpts.backgroundColor);
779
+ doc.rect(x - pad, y - pad, word.width + pad * 2, h + pad * 2, "F");
780
+ doc.setFillColor("#000000");
781
+ }
782
+ }
783
+ doc.text(word.text, x, y, { baseline: "top" });
784
+ }
785
+ if (word.isLink && word.href) {
786
+ const h = word.isImage && word.imageHeight ? word.imageHeight : getCharHight(doc);
787
+ doc.link(x, y, word.width, h, { url: word.href });
788
+ }
789
+ doc.setFont(savedFont.fontName, savedFont.fontStyle);
790
+ doc.setFontSize(savedSize);
791
+ doc.setTextColor(savedColor);
792
+ }
793
+ /**
794
+ * Render a single line with specified alignment.
795
+ */
796
+ static renderAlignedLine(doc, line, x, y, maxWidth, store, alignment = "left") {
797
+ const { words, totalTextWidth, isLastLine } = line;
798
+ if (words.length === 0) return;
799
+ const normalSpaceWidth = doc.getTextWidth(" ");
800
+ let startX = x;
801
+ let wordSpacing = normalSpaceWidth;
802
+ let lineWidthWithNormalSpaces = totalTextWidth;
803
+ let expandableSpacesCount = 0;
804
+ for (let i = 0; i < words.length - 1; i++) if (words[i].hasTrailingSpace) {
805
+ lineWidthWithNormalSpaces += normalSpaceWidth;
806
+ expandableSpacesCount++;
807
+ }
808
+ switch (alignment) {
809
+ case "right":
810
+ startX = x + maxWidth - lineWidthWithNormalSpaces;
811
+ break;
812
+ case "center":
813
+ startX = x + (maxWidth - lineWidthWithNormalSpaces) / 2;
814
+ break;
815
+ case "justify":
816
+ if (!isLastLine && expandableSpacesCount > 0) wordSpacing = (maxWidth - totalTextWidth) / expandableSpacesCount;
817
+ break;
818
+ default: break;
819
+ }
820
+ let currentX = startX;
821
+ const textHeight = getCharHight(doc) * store.options.page.defaultLineHeightFactor;
822
+ for (let i = 0; i < words.length; i++) {
823
+ const word = words[i];
824
+ let drawY = y;
825
+ const elementHeight = word.isImage && word.imageHeight ? word.imageHeight : textHeight;
826
+ if (word.isImage) drawY = y;
827
+ else if (elementHeight < line.lineHeight) drawY = y + (line.lineHeight - elementHeight);
828
+ this.renderWord(doc, word, currentX, drawY, store);
829
+ currentX += word.width;
830
+ if (i < words.length - 1 && word.hasTrailingSpace) currentX += wordSpacing;
831
+ }
832
+ }
833
+ /**
834
+ * Main entry point: Render a paragraph with mixed inline elements.
835
+ * Respects user's textAlignment option from store.
836
+ *
837
+ * @param doc jsPDF instance
838
+ * @param elements Array of ParsedElement (inline items in a paragraph)
839
+ * @param x Starting X coordinate
840
+ * @param y Starting Y coordinate
841
+ * @param maxWidth Maximum width for text wrapping
842
+ * @param store RenderStore instance to use
843
+ * @param alignment Optional alignment override (defaults to store option)
844
+ */
845
+ static renderStyledParagraph(doc, elements, x, y, maxWidth, store, alignment) {
846
+ const textAlignment = alignment ?? store.options.content?.textAlignment ?? "left";
847
+ const words = this.flattenToWords(doc, elements, store);
848
+ if (words.length === 0) return;
849
+ const lines = this.breakIntoLines(doc, words, maxWidth, store);
850
+ let currentY = y;
851
+ for (const line of lines) {
852
+ if (currentY + line.lineHeight > store.options.page.maxContentHeight) {
853
+ HandlePageBreaks(doc, store);
854
+ currentY = store.Y;
855
+ }
856
+ this.renderAlignedLine(doc, line, x, currentY, maxWidth, store, textAlignment);
857
+ store.recordContentY(currentY + line.lineHeight);
858
+ currentY += line.lineHeight;
859
+ store.updateY(line.lineHeight, "add");
860
+ }
861
+ const lastLine = lines[lines.length - 1];
862
+ if (lastLine) {
863
+ let actualSpacesCount = 0;
864
+ for (let i = 0; i < lastLine.words.length - 1; i++) if (lastLine.words[i].hasTrailingSpace) actualSpacesCount++;
865
+ const lastLineWidth = lastLine.totalTextWidth + actualSpacesCount * doc.getTextWidth(" ");
866
+ store.updateX(x + lastLineWidth, "set");
867
+ }
868
+ }
869
+ /**
870
+ * @deprecated Use renderStyledParagraph instead
871
+ */
872
+ static renderJustifiedParagraph(doc, elements, x, y, maxWidth, store) {
873
+ this.renderStyledParagraph(doc, elements, x, y, maxWidth, store);
874
+ }
875
+ };
876
+ //#endregion
877
+ //#region src/renderer/components/heading.ts
878
+ /**
879
+ * Renders heading elements.
880
+ */
881
+ const renderHeading = (doc, element, indent, store, parentElementRenderer) => {
882
+ const size = 6 - (element?.depth ?? 0) > 0 ? 6 - (element?.depth ?? 0) : 1;
883
+ doc.setFontSize(store.options.page.defaultFontSize + size);
884
+ if (element?.items && element?.items.length > 0) {
885
+ const originalLineHeightFactor = store.options.page.defaultLineHeightFactor;
886
+ store.options.page.defaultLineHeightFactor = 1;
887
+ JustifiedTextRenderer.renderStyledParagraph(doc, element.items, store.X + indent, store.Y, store.options.page.maxContentWidth - indent, store, "left");
888
+ store.options.page.defaultLineHeightFactor = originalLineHeightFactor;
889
+ } else {
890
+ const charHeight = getCharHight(doc);
891
+ doc.text(element?.content ?? "", store.X + indent, store.Y, {
892
+ align: "left",
893
+ maxWidth: store.options.page.maxContentWidth - indent,
894
+ baseline: "top"
895
+ });
896
+ store.recordContentY(store.Y + charHeight);
897
+ store.updateY(getCharHight(doc), "add");
898
+ }
899
+ doc.setFontSize(store.options.page.defaultFontSize);
900
+ store.updateX(store.options.page.xpading, "set");
901
+ };
902
+ //#endregion
903
+ //#region src/utils/text-renderer.ts
904
+ var TextRenderer = class {
905
+ /**
906
+ * Renders text with automatic line wrapping and page breaking.
907
+ * @param doc jsPDF instance
908
+ * @param text Text to render
909
+ * @param store RenderStore instance to use
910
+ * @param x X coordinate (if not provided, uses store.X)
911
+ * @param y Y coordinate (if not provided, uses store.Y)
912
+ * @param maxWidth Max width for text wrapping
913
+ * @param justify Whether to justify the text
914
+ */
915
+ static renderText(doc, text, store, x = store.X, y = store.Y, maxWidth, justify = false) {
916
+ const lines = doc.splitTextToSize(text, maxWidth);
917
+ const charHeight = getCharHight(doc);
918
+ const lineHeight = charHeight * store.options.page.defaultLineHeightFactor;
919
+ let currentY = y;
920
+ for (let i = 0; i < lines.length; i++) {
921
+ const line = lines[i];
922
+ if (currentY + lineHeight > store.options.page.maxContentHeight) {
923
+ HandlePageBreaks(doc, store);
924
+ currentY = store.Y;
925
+ }
926
+ if (justify) if (i === lines.length - 1) doc.text(line, x, currentY, { baseline: "top" });
927
+ else doc.text(line, x, currentY, {
928
+ maxWidth,
929
+ align: "justify",
930
+ baseline: "top"
931
+ });
932
+ else doc.text(line, x, currentY, { baseline: "top" });
933
+ store.recordContentY(currentY + charHeight);
934
+ currentY += lineHeight;
935
+ store.updateY(lineHeight, "add");
936
+ }
937
+ return currentY;
938
+ }
939
+ };
940
+ //#endregion
941
+ //#region src/renderer/components/paragraph.ts
942
+ /**
943
+ * Renders paragraph elements with proper text alignment.
944
+ * Handles mixed inline styles (bold, italic, codespan) and links.
945
+ * Respects user's textAlignment option from RenderStore.
946
+ */
947
+ const renderParagraph = (doc, element, indent, store, parentElementRenderer) => {
948
+ store.activateInlineLock();
949
+ doc.setFontSize(store.options.page.defaultFontSize);
950
+ const maxWidth = store.options.page.maxContentWidth - indent;
951
+ if (element?.items && element?.items.length > 0) {
952
+ if (element.items.length === 1 && element.items[0].type === "image") {
953
+ parentElementRenderer(element.items[0], indent, store, false);
954
+ store.updateX(store.options.page.xpading);
955
+ store.deactivateInlineLock();
956
+ return;
957
+ }
958
+ const inlineTypes = [
959
+ "strong",
960
+ "em",
961
+ "text",
962
+ "codespan",
963
+ "link",
964
+ "image",
965
+ "br"
966
+ ];
967
+ if (element.items.some((item) => !inlineTypes.includes(item.type))) {
968
+ const inlineBuffer = [];
969
+ const flushInlineBuffer = () => {
970
+ if (inlineBuffer.length > 0) {
971
+ JustifiedTextRenderer.renderStyledParagraph(doc, inlineBuffer, store.X + indent, store.Y, maxWidth, store);
972
+ inlineBuffer.length = 0;
973
+ }
974
+ };
975
+ for (const item of element.items) if (inlineTypes.includes(item.type)) inlineBuffer.push(item);
976
+ else {
977
+ flushInlineBuffer();
978
+ parentElementRenderer(item, indent, store, false);
979
+ }
980
+ flushInlineBuffer();
981
+ } else JustifiedTextRenderer.renderStyledParagraph(doc, element.items, store.X + indent, store.Y, maxWidth, store);
982
+ } else {
983
+ const content = element.content ?? "";
984
+ const textAlignment = store.options.content?.textAlignment ?? "left";
985
+ if (content.trim()) TextRenderer.renderText(doc, content, store, store.X + indent, store.Y, maxWidth, textAlignment === "justify");
986
+ }
987
+ store.updateX(store.options.page.xpading);
988
+ store.deactivateInlineLock();
989
+ };
990
+ //#endregion
991
+ //#region src/renderer/components/list.ts
992
+ const renderList = (doc, element, indentLevel, store, parentElementRenderer) => {
993
+ doc.setFontSize(store.options.page.defaultFontSize);
994
+ for (const [i, point] of element?.items?.entries() ?? []) {
995
+ const _start = element.ordered ? (element.start ?? 0) + i : element.start;
996
+ parentElementRenderer(point, indentLevel + 1, store, true, _start, element.ordered);
997
+ }
998
+ };
999
+ //#endregion
1000
+ //#region src/renderer/components/listItem.ts
1001
+ /**
1002
+ * Render a single list item, including bullets/numbering, inline text, and any nested lists.
1003
+ */
1004
+ const renderListItem = (doc, element, indentLevel, store, parentElementRenderer, start, ordered) => {
1005
+ if (store.Y + getCharHight(doc) >= store.options.page.maxContentHeight) HandlePageBreaks(doc, store);
1006
+ const options = store.options;
1007
+ const baseIndent = indentLevel * options.page.indent;
1008
+ const bullet = ordered ? `${start}. ` : "• ";
1009
+ const xLeft = options.page.xpading;
1010
+ store.updateX(xLeft, "set");
1011
+ doc.setFont(options.font.regular.name, options.font.regular.style);
1012
+ doc.text(bullet, xLeft + baseIndent, store.Y, { baseline: "top" });
1013
+ const bulletWidth = doc.getTextWidth(bullet);
1014
+ const contentX = xLeft + baseIndent + bulletWidth;
1015
+ const textMaxWidth = options.page.maxContentWidth - baseIndent - bulletWidth;
1016
+ if (element.items && element.items.length > 0) {
1017
+ const inlineBuffer = [];
1018
+ const flushInlineBuffer = () => {
1019
+ if (inlineBuffer.length > 0) {
1020
+ JustifiedTextRenderer.renderStyledParagraph(doc, inlineBuffer, contentX, store.Y, textMaxWidth, store);
1021
+ inlineBuffer.length = 0;
1022
+ store.updateX(xLeft, "set");
1023
+ }
1024
+ };
1025
+ for (const subItem of element.items) if (subItem.type === "list") {
1026
+ flushInlineBuffer();
1027
+ parentElementRenderer(subItem, indentLevel, store, true, start, subItem.ordered ?? false);
1028
+ } else if (subItem.type === "list_item") {
1029
+ flushInlineBuffer();
1030
+ parentElementRenderer(subItem, indentLevel, store, true, start, ordered);
1031
+ } else inlineBuffer.push(subItem);
1032
+ flushInlineBuffer();
1033
+ } else if (element.content) {
1034
+ const textAlignment = options.content?.textAlignment ?? "left";
1035
+ TextRenderer.renderText(doc, element.content, store, contentX, store.Y, textMaxWidth, textAlignment === "justify");
1036
+ }
1037
+ };
1038
+ //#endregion
1039
+ //#region src/renderer/components/rawItem.ts
1040
+ const renderRawItem = (doc, element, indentLevel, store, hasRawBullet, parentElementRenderer, start, ordered, justify = true) => {
1041
+ if (element?.items && element?.items.length > 0) for (const item of element?.items ?? []) parentElementRenderer(item, indentLevel, store, hasRawBullet, start, ordered, justify);
1042
+ else {
1043
+ const options = store.options;
1044
+ const indent = indentLevel * options.page.indent;
1045
+ const bullet = hasRawBullet ? ordered ? `${start}. ` : "• " : "";
1046
+ const content = element.content || "";
1047
+ const xLeft = options.page.xpading;
1048
+ if (!content && !bullet) return;
1049
+ if (!content.trim() && !bullet) {
1050
+ const newlines = (content.match(/\n/g) || []).length;
1051
+ if (newlines > 1) {
1052
+ const addedHeight = (newlines - 1) * (doc.getTextDimensions("A").h * options.page.defaultLineHeightFactor);
1053
+ if (store.Y + addedHeight > options.page.maxContentHeight) HandlePageBreaks(doc, store);
1054
+ else {
1055
+ store.updateY(addedHeight, "add");
1056
+ store.recordContentY(store.Y);
1057
+ }
1058
+ }
1059
+ return;
1060
+ }
1061
+ store.updateX(xLeft, "set");
1062
+ if (hasRawBullet && bullet) {
1063
+ const bulletWidth = doc.getTextWidth(bullet);
1064
+ const textMaxWidth = options.page.maxContentWidth - indent - bulletWidth;
1065
+ doc.setFont(options.font.regular.name, options.font.regular.style);
1066
+ doc.text(bullet, xLeft + indent, store.Y, { baseline: "top" });
1067
+ TextRenderer.renderText(doc, content, store, xLeft + indent + bulletWidth, store.Y, textMaxWidth, justify);
1068
+ } else {
1069
+ const textMaxWidth = options.page.maxContentWidth - indent;
1070
+ TextRenderer.renderText(doc, content, store, xLeft + indent, store.Y, textMaxWidth, justify);
1071
+ }
1072
+ store.updateX(xLeft, "set");
1073
+ }
1074
+ };
1075
+ //#endregion
1076
+ //#region src/renderer/components/hr.ts
1077
+ const renderHR = (doc, store) => {
1078
+ const pageWidth = doc.internal.pageSize.getWidth();
1079
+ doc.setLineDashPattern([1, 1], 0);
1080
+ doc.setLineWidth(.1);
1081
+ doc.line(store.options.page.xpading, store.Y, pageWidth - store.options.page.xpading, store.Y);
1082
+ doc.setLineWidth(.1);
1083
+ doc.setLineDashPattern([], 0);
1084
+ store.updateY(getCharHight(doc), "add");
1085
+ };
1086
+ //#endregion
1087
+ //#region src/renderer/components/code.ts
1088
+ const renderCodeBlock = (doc, element, indentLevel, store) => {
1089
+ const savedFont = doc.getFont();
1090
+ const savedFontSize = doc.getFontSize();
1091
+ const codeFont = store.options.font.code || {
1092
+ name: "courier",
1093
+ style: "normal"
1094
+ };
1095
+ doc.setFont(codeFont.name, codeFont.style);
1096
+ const codeFontSize = store.options.page.defaultFontSize * .9;
1097
+ doc.setFontSize(codeFontSize);
1098
+ const indent = indentLevel * store.options.page.indent;
1099
+ const maxWidth = store.options.page.maxContentWidth - indent - 8;
1100
+ const lineHeightFactor = doc.getLineHeightFactor();
1101
+ const lineHeight = codeFontSize / doc.internal.scaleFactor * lineHeightFactor;
1102
+ const content = (element.code ?? "").replace(/[\r\n\s]+$/, "");
1103
+ if (!content) {
1104
+ doc.setFont(savedFont.fontName, savedFont.fontStyle);
1105
+ doc.setFontSize(savedFontSize);
1106
+ return;
1107
+ }
1108
+ const lines = doc.splitTextToSize(content, maxWidth);
1109
+ while (lines.length > 0 && lines[lines.length - 1].trim() === "") lines.pop();
1110
+ if (lines.length === 0) {
1111
+ doc.setFont(savedFont.fontName, savedFont.fontStyle);
1112
+ doc.setFontSize(savedFontSize);
1113
+ return;
1114
+ }
1115
+ const padding = 4;
1116
+ const bgColor = "#EEEEEE";
1117
+ const drawColor = "#DDDDDD";
1118
+ let currentLineIndex = 0;
1119
+ while (currentLineIndex < lines.length) {
1120
+ const availableHeight = store.options.page.maxContentHeight - store.Y;
1121
+ const remainingLines = lines.length - currentLineIndex;
1122
+ const effectiveAvailable = availableHeight - padding * 2;
1123
+ let linesToRenderCount = Math.floor(effectiveAvailable / lineHeight);
1124
+ if (linesToRenderCount <= 0) {
1125
+ HandlePageBreaks(doc, store);
1126
+ continue;
1127
+ }
1128
+ if (linesToRenderCount > remainingLines) linesToRenderCount = remainingLines;
1129
+ const linesToRender = lines.slice(currentLineIndex, currentLineIndex + linesToRenderCount);
1130
+ const isFirstChunk = currentLineIndex === 0;
1131
+ const isLastChunk = currentLineIndex + linesToRenderCount >= lines.length;
1132
+ const textBlockHeight = linesToRenderCount * lineHeight;
1133
+ if (isFirstChunk) store.updateY(padding, "add");
1134
+ doc.setFillColor(bgColor);
1135
+ doc.setDrawColor(drawColor);
1136
+ doc.roundedRect(store.X, store.Y - padding, store.options.page.maxContentWidth, textBlockHeight + (isFirstChunk ? padding : 0) + (isLastChunk ? padding : 0), 2, 2, "FD");
1137
+ if (isFirstChunk && element.lang) {
1138
+ const savedCodeFontSize = doc.getFontSize();
1139
+ doc.setFontSize(10);
1140
+ doc.setTextColor("#666666");
1141
+ doc.text(element.lang, store.X + store.options.page.maxContentWidth - doc.getTextWidth(element.lang) - 4, store.Y, { baseline: "top" });
1142
+ doc.setFontSize(savedCodeFontSize);
1143
+ doc.setTextColor("#000000");
1144
+ }
1145
+ let yPos = store.Y;
1146
+ for (const line of linesToRender) {
1147
+ doc.text(line, store.X + 4, yPos, { baseline: "top" });
1148
+ yPos += lineHeight;
1149
+ }
1150
+ store.updateY(textBlockHeight, "add");
1151
+ store.recordContentY(store.Y + (isLastChunk ? padding : 0));
1152
+ if (isLastChunk) store.updateY(padding, "add");
1153
+ currentLineIndex += linesToRenderCount;
1154
+ if (currentLineIndex < lines.length) HandlePageBreaks(doc, store);
1155
+ }
1156
+ doc.setFont(savedFont.fontName, savedFont.fontStyle);
1157
+ doc.setFontSize(savedFontSize);
1158
+ };
1159
+ //#endregion
1160
+ //#region src/renderer/components/inlineText.ts
1161
+ /**
1162
+ * Renders inline text elements (Strong, Em, and Text) with proper inline styling.
1163
+ */
1164
+ const renderInlineText = (doc, element, indent, store) => {
1165
+ const currentFont = doc.getFont().fontName;
1166
+ const currentFontStyle = doc.getFont().fontStyle;
1167
+ const currentFontSize = doc.getFontSize();
1168
+ const spaceMultiplier = (style) => {
1169
+ switch (style) {
1170
+ case "normal": return 0;
1171
+ case "bold": return 1;
1172
+ case "italic": return 1.5;
1173
+ case "bolditalic": return 1.5;
1174
+ case "codespan": return .5;
1175
+ default: return 0;
1176
+ }
1177
+ };
1178
+ const renderTextWithStyle = (text, style) => {
1179
+ if (style === "bold") doc.setFont(store.options.font.bold.name && store.options.font.bold.name !== "" ? store.options.font.bold.name : currentFont, store.options.font.bold.style || "bold");
1180
+ else if (style === "italic") doc.setFont(store.options.font.regular.name, "italic");
1181
+ else if (style === "bolditalic") doc.setFont(store.options.font.bold.name && store.options.font.bold.name !== "" ? store.options.font.bold.name : currentFont, "bolditalic");
1182
+ else if (style === "codespan") {
1183
+ const codeFont = store.options.font.code || {
1184
+ name: "courier",
1185
+ style: "normal"
1186
+ };
1187
+ doc.setFont(codeFont.name, codeFont.style);
1188
+ doc.setFontSize(currentFontSize * .9);
1189
+ } else doc.setFont(store.options.font.regular.name, currentFontStyle);
1190
+ const availableWidth = store.options.page.maxContentWidth - indent - store.X;
1191
+ const textLines = doc.splitTextToSize(text, availableWidth);
1192
+ const isCodeSpan = style === "codespan";
1193
+ const codePadding = 1;
1194
+ const codeBgColor = "#EEEEEE";
1195
+ if (store.isInlineLockActive) for (let i = 0; i < textLines.length; i++) {
1196
+ if (isCodeSpan) {
1197
+ const lineWidth = doc.getTextWidth(textLines[i]) + getCharWidth(doc);
1198
+ const lineHeight = getCharHight(doc);
1199
+ doc.setFillColor(codeBgColor);
1200
+ doc.roundedRect(store.X + indent - codePadding, store.Y - codePadding, lineWidth + codePadding * 2, lineHeight + codePadding * 2, 2, 2, "F");
1201
+ doc.setFillColor("#000000");
1202
+ }
1203
+ doc.text(textLines[i], store.X + indent, store.Y, {
1204
+ baseline: "top",
1205
+ maxWidth: availableWidth
1206
+ });
1207
+ store.updateX(doc.getTextDimensions(textLines[i]).w + (isCodeSpan ? codePadding * 2 : 1), "add");
1208
+ if (i < textLines.length - 1) {
1209
+ store.updateY(getCharHight(doc), "add");
1210
+ store.updateX(store.options.page.xpading, "set");
1211
+ }
1212
+ }
1213
+ else if (textLines.length > 1) {
1214
+ const firstLine = textLines[0];
1215
+ const restContent = textLines?.slice(1)?.join(" ");
1216
+ if (isCodeSpan) {
1217
+ const w = doc.getTextWidth(firstLine) + getCharWidth(doc);
1218
+ const h = getCharHight(doc);
1219
+ doc.setFillColor(codeBgColor);
1220
+ doc.roundedRect(store.X + (indent >= 2 ? indent + 2 : 0) - codePadding, store.Y - codePadding, w + codePadding * 2, h + codePadding * 2, 2, 2, "F");
1221
+ doc.setFillColor("#000000");
1222
+ }
1223
+ doc.text(firstLine, store.X + (indent >= 2 ? indent + 2 * spaceMultiplier(style) : 0), store.Y, {
1224
+ baseline: "top",
1225
+ maxWidth: availableWidth
1226
+ });
1227
+ store.updateX(store.options.page.xpading + indent);
1228
+ store.updateY(getCharHight(doc), "add");
1229
+ const maxWidthForRest = store.options.page.maxContentWidth - indent - store.options.page.xpading;
1230
+ doc.splitTextToSize(restContent, maxWidthForRest).forEach((line) => {
1231
+ if (isCodeSpan) {
1232
+ const w = doc.getTextWidth(line) + getCharWidth(doc);
1233
+ const h = getCharHight(doc);
1234
+ doc.setFillColor(codeBgColor);
1235
+ doc.roundedRect(store.X + getCharWidth(doc) - codePadding, store.Y - codePadding, w + codePadding * 2, h + codePadding * 2, 2, 2, "F");
1236
+ doc.setFillColor("#000000");
1237
+ }
1238
+ doc.text(line, store.X + getCharWidth(doc), store.Y, {
1239
+ baseline: "top",
1240
+ maxWidth: maxWidthForRest
1241
+ });
1242
+ });
1243
+ } else {
1244
+ if (isCodeSpan) {
1245
+ const w = doc.getTextWidth(text) + getCharWidth(doc);
1246
+ const h = getCharHight(doc);
1247
+ doc.setFillColor(codeBgColor);
1248
+ doc.roundedRect(store.X + indent - codePadding, store.Y - codePadding, w + codePadding * 2, h + codePadding * 2, 2, 2, "F");
1249
+ doc.setFillColor("#000000");
1250
+ }
1251
+ doc.text(text, store.X + indent, store.Y, {
1252
+ baseline: "top",
1253
+ maxWidth: availableWidth
1254
+ });
1255
+ store.updateX(doc.getTextDimensions(text).w + (indent >= 2 ? text.split(" ").length + 2 : 2) * spaceMultiplier(style) * .5 + (isCodeSpan ? codePadding * 2 : 0), "add");
1256
+ }
1257
+ };
1258
+ if (element.type === "text" && element.items && element.items.length > 0) for (const item of element.items) if (item.type === "codespan") renderTextWithStyle(item.content || "", "codespan");
1259
+ else if (item.type === "em" || item.type === "strong") {
1260
+ const baseStyle = item.type === "em" ? "italic" : "bold";
1261
+ if (item.items && item.items.length > 0) for (const subItem of item.items) if (subItem.type === "strong" && baseStyle === "italic") renderTextWithStyle(subItem.content || "", "bolditalic");
1262
+ else if (subItem.type === "em" && baseStyle === "bold") renderTextWithStyle(subItem.content || "", "bolditalic");
1263
+ else renderTextWithStyle(subItem.content || "", baseStyle);
1264
+ else renderTextWithStyle(item.content || "", baseStyle);
1265
+ } else renderTextWithStyle(item.content || "", "normal");
1266
+ else if (element.type === "em") renderTextWithStyle(element.content || "", "italic");
1267
+ else if (element.type === "strong") renderTextWithStyle(element.content || "", "bold");
1268
+ else if (element.type === "codespan") renderTextWithStyle(element.content || "", "codespan");
1269
+ else renderTextWithStyle(element.content || "", "normal");
1270
+ doc.setFont(currentFont, currentFontStyle);
1271
+ doc.setFontSize(currentFontSize);
1272
+ };
1273
+ //#endregion
1274
+ //#region src/renderer/components/link.ts
1275
+ /**
1276
+ * Renders link elements with proper styling and URL handling.
1277
+ * Links are rendered in blue color and underlined to distinguish them from regular text.
1278
+ */
1279
+ const renderLink = (doc, element, indent, store) => {
1280
+ const currentFont = doc.getFont().fontName;
1281
+ const currentFontStyle = doc.getFont().fontStyle;
1282
+ const currentFontSize = doc.getFontSize();
1283
+ const currentTextColor = doc.getTextColor();
1284
+ const linkColor = store.options.link?.linkColor || [
1285
+ 0,
1286
+ 0,
1287
+ 255
1288
+ ];
1289
+ doc.setTextColor(...linkColor);
1290
+ const availableWidth = store.options.page.maxContentWidth - indent - store.X;
1291
+ const linkText = element.text || element.content || "";
1292
+ const linkUrl = element.href || "";
1293
+ const textLines = doc.splitTextToSize(linkText, availableWidth);
1294
+ if (store.isInlineLockActive) for (let i = 0; i < textLines.length; i++) {
1295
+ const textWidth = doc.getTextDimensions(textLines[i]).w;
1296
+ const textHeight = getCharHight(doc) / 2;
1297
+ doc.link(store.X + indent, store.Y, textWidth, textHeight, { url: linkUrl });
1298
+ doc.text(textLines[i], store.X + indent, store.Y, {
1299
+ baseline: "top",
1300
+ maxWidth: availableWidth
1301
+ });
1302
+ store.updateX(textWidth + 1, "add");
1303
+ if (store.X + textWidth > store.options.page.maxContentWidth - indent) {
1304
+ store.updateY(textHeight, "add");
1305
+ store.updateX(store.options.page.xpading + indent, "set");
1306
+ }
1307
+ if (i < textLines.length - 1) {
1308
+ store.updateY(textHeight, "add");
1309
+ store.updateX(store.options.page.xpading + indent, "set");
1310
+ }
1311
+ }
1312
+ else if (textLines.length > 1) {
1313
+ const firstLine = textLines[0];
1314
+ const restContent = textLines?.slice(1)?.join(" ");
1315
+ const firstLineWidth = doc.getTextDimensions(firstLine).w;
1316
+ const textHeight = getCharHight(doc) / 2;
1317
+ doc.link(store.X + indent, store.Y, firstLineWidth, textHeight, { url: linkUrl });
1318
+ doc.text(firstLine, store.X + indent, store.Y, {
1319
+ baseline: "top",
1320
+ maxWidth: availableWidth
1321
+ });
1322
+ store.updateX(store.options.page.xpading + indent);
1323
+ store.updateY(textHeight, "add");
1324
+ const maxWidthForRest = store.options.page.maxContentWidth - indent - store.options.page.xpading;
1325
+ doc.splitTextToSize(restContent, maxWidthForRest).forEach((line) => {
1326
+ const lineWidth = doc.getTextDimensions(line).w;
1327
+ doc.link(store.X + getCharWidth(doc), store.Y, lineWidth, textHeight, { url: linkUrl });
1328
+ doc.text(line, store.X + getCharWidth(doc), store.Y, {
1329
+ baseline: "top",
1330
+ maxWidth: maxWidthForRest
1331
+ });
1332
+ });
1333
+ } else {
1334
+ const textWidth = doc.getTextDimensions(linkText).w;
1335
+ const textHeight = getCharHight(doc) / 2;
1336
+ doc.link(store.X + indent, store.Y, textWidth, textHeight, { url: linkUrl });
1337
+ doc.text(linkText, store.X + indent, store.Y, {
1338
+ baseline: "top",
1339
+ maxWidth: availableWidth
1340
+ });
1341
+ store.updateX(textWidth + 2, "add");
1342
+ }
1343
+ doc.setFont(currentFont, currentFontStyle);
1344
+ doc.setFontSize(currentFontSize);
1345
+ doc.setTextColor(currentTextColor);
1346
+ };
1347
+ //#endregion
1348
+ //#region src/renderer/components/blockquote.ts
1349
+ const renderBlockquote = (doc, element, indentLevel, store, renderElement) => {
1350
+ const options = store.options;
1351
+ const blockquoteIndent = indentLevel + 1;
1352
+ const currentX = store.X + indentLevel * options.page.indent;
1353
+ const currentY = store.Y;
1354
+ const barX = currentX + options.page.indent / 2;
1355
+ const startY = currentY;
1356
+ const startPage = doc.internal.getCurrentPageInfo().pageNumber;
1357
+ if (element.items && element.items.length > 0) element.items.forEach((item) => {
1358
+ renderElement(item, blockquoteIndent, store);
1359
+ });
1360
+ const endY = store.Y;
1361
+ const endPage = doc.internal.getCurrentPageInfo().pageNumber;
1362
+ doc.setDrawColor(100);
1363
+ doc.setLineWidth(1);
1364
+ for (let p = startPage; p <= endPage; p++) {
1365
+ doc.setPage(p);
1366
+ const isStart = p === startPage;
1367
+ const isEnd = p === endPage;
1368
+ const lineTop = isStart ? startY : options.page.topmargin;
1369
+ const lineBottom = isEnd ? endY : options.page.maxContentHeight;
1370
+ doc.line(barX, lineTop, barX, lineBottom);
1371
+ }
1372
+ store.recordContentY();
1373
+ doc.setPage(endPage);
1374
+ };
1375
+ //#endregion
1376
+ //#region src/renderer/components/image.ts
1377
+ /**
1378
+ * Detects the image format from element data and source.
1379
+ */
1380
+ const detectImageFormat = (element) => {
1381
+ if (element.data) {
1382
+ if (element.data.startsWith("data:image/png")) return "PNG";
1383
+ if (element.data.startsWith("data:image/jpeg") || element.data.startsWith("data:image/jpg")) return "JPEG";
1384
+ if (element.data.startsWith("data:image/webp")) return "WEBP";
1385
+ if (element.data.startsWith("data:image/webp")) return "WEBP";
1386
+ if (element.data.startsWith("data:image/gif")) return "GIF";
1387
+ }
1388
+ if (element.src) {
1389
+ const ext = element.src.split("?")[0].split("#")[0].split(".").pop()?.toUpperCase();
1390
+ if (ext && [
1391
+ "PNG",
1392
+ "JPEG",
1393
+ "JPG",
1394
+ "WEBP",
1395
+ "GIF"
1396
+ ].includes(ext)) return ext === "JPG" ? "JPEG" : ext;
1397
+ }
1398
+ return "JPEG";
1399
+ };
1400
+ /**
1401
+ * Renders an image element into the jsPDF document with smart sizing and alignment.
1402
+ *
1403
+ * Sizing logic (in order of priority):
1404
+ * 1. If both width & height are specified by user → convert from px, use as-is
1405
+ * 2. If only width is specified → convert from px, calculate height from aspect ratio
1406
+ * 3. If only height is specified → convert from px, calculate width from aspect ratio
1407
+ * 4. If nothing specified → use intrinsic dimensions (converted from px to doc units)
1408
+ * 5. Always clamp to page bounds (scale down proportionally if needed)
1409
+ *
1410
+ * Alignment: 'left' (default) | 'center' | 'right'
1411
+ * Can be set per-image via markdown attributes or globally via RenderOption.image.defaultAlign
1412
+ */
1413
+ const renderImage = (doc, element, indentLevel, store) => {
1414
+ if (!element.data) return;
1415
+ const options = store.options;
1416
+ const docUnit = options.page.unit || "mm";
1417
+ const indent = indentLevel * options.page.indent;
1418
+ const maxWidth = options.page.maxContentWidth - indent;
1419
+ const pageLeftX = store.X + indent;
1420
+ let currentY = store.Y;
1421
+ try {
1422
+ const { finalWidth, finalHeight } = calculateImageDimensions(doc, element, maxWidth, options.page.maxContentHeight - options.page.topmargin, docUnit);
1423
+ if (currentY + finalHeight > options.page.maxContentHeight) {
1424
+ HandlePageBreaks(doc, store);
1425
+ currentY = store.Y;
1426
+ }
1427
+ const align = element.align || options.image?.defaultAlign || "left";
1428
+ let drawX;
1429
+ switch (align) {
1430
+ case "right":
1431
+ drawX = pageLeftX + maxWidth - finalWidth;
1432
+ break;
1433
+ case "center":
1434
+ drawX = pageLeftX + (maxWidth - finalWidth) / 2;
1435
+ break;
1436
+ default:
1437
+ drawX = pageLeftX;
1438
+ break;
1439
+ }
1440
+ const imgFormat = detectImageFormat(element);
1441
+ if (finalWidth > 0 && finalHeight > 0) doc.addImage(element.data, imgFormat, drawX, currentY, finalWidth, finalHeight);
1442
+ store.updateY(finalHeight, "add");
1443
+ store.recordContentY();
1444
+ } catch (e) {
1445
+ console.warn("Failed to render image", e);
1446
+ }
1447
+ };
1448
+ //#endregion
1449
+ //#region src/renderer/components/table.ts
1450
+ const resolveAutoTable = () => {
1451
+ const autoTableCandidate = jspdf_autotable.default;
1452
+ if (typeof jspdf_autotable.default === "function") return jspdf_autotable.default;
1453
+ if (typeof autoTableCandidate.default === "function") return autoTableCandidate.default;
1454
+ if (typeof autoTableCandidate.autoTable === "function") return autoTableCandidate.autoTable;
1455
+ throw new Error("Could not resolve jspdf-autotable export. Expected a callable export.");
1456
+ };
1457
+ const renderTable = (doc, element, indentLevel, store) => {
1458
+ if (!element.header || !element.rows) return;
1459
+ const options = store.options;
1460
+ const marginLeft = options.page.xmargin + indentLevel * options.page.indent;
1461
+ const head = [element.header.map((h) => h.content || "")];
1462
+ const body = element.rows.map((row) => row.map((cell) => cell.content || ""));
1463
+ const userTableOptions = options.table || {};
1464
+ resolveAutoTable()(doc, {
1465
+ head,
1466
+ body,
1467
+ startY: store.Y,
1468
+ margin: {
1469
+ left: marginLeft,
1470
+ right: options.page.xmargin
1471
+ },
1472
+ ...userTableOptions,
1473
+ didDrawPage: (data) => {
1474
+ if (userTableOptions.didDrawPage) userTableOptions.didDrawPage(data);
1475
+ },
1476
+ didDrawCell: (data) => {
1477
+ if (userTableOptions.didDrawCell) userTableOptions.didDrawCell(data);
1478
+ }
1479
+ });
1480
+ const finalY = doc.lastAutoTable?.finalY;
1481
+ if (typeof finalY === "number") {
1482
+ store.updateY(finalY + options.page.lineSpace, "set");
1483
+ store.updateX(options.page.xpading, "set");
1484
+ store.recordContentY();
1485
+ }
1486
+ };
1487
+ //#endregion
1488
+ //#region src/store/renderStore.ts
1489
+ var RenderStore = class {
1490
+ constructor(options) {
1491
+ this.cursor = {
1492
+ x: 0,
1493
+ y: 0
1494
+ };
1495
+ this.lastContentY_ = 0;
1496
+ this.inlineLock = false;
1497
+ this.options_ = options;
1498
+ this.cursor = {
1499
+ x: options.cursor.x,
1500
+ y: options.cursor.y
1501
+ };
1502
+ this.lastContentY_ = options.cursor.y;
1503
+ }
1504
+ getCursor() {
1505
+ return this.cursor;
1506
+ }
1507
+ setCursor(newCursor) {
1508
+ this.cursor = newCursor;
1509
+ }
1510
+ get options() {
1511
+ return this.options_;
1512
+ }
1513
+ get isInlineLockActive() {
1514
+ return this.inlineLock;
1515
+ }
1516
+ activateInlineLock() {
1517
+ this.inlineLock = true;
1518
+ }
1519
+ deactivateInlineLock() {
1520
+ this.inlineLock = false;
1521
+ }
1522
+ /**
1523
+ * Updates the x pointer of the cursor.
1524
+ * @param value The value to set or add.
1525
+ * @param operation 'set' to assign a new value, 'add' to increment the current value.
1526
+ * @default operation = 'set'
1527
+ */
1528
+ updateX(value, operation = "set") {
1529
+ if (operation === "set") this.cursor.x = value;
1530
+ else if (operation === "add") this.cursor.x += value;
1531
+ }
1532
+ /**
1533
+ * Updates the y pointer of the cursor.
1534
+ * @param value The value to set or add.
1535
+ * @param operation 'set' to assign a new value, 'add' to increment the current value.
1536
+ * @default operation = 'set'
1537
+ */
1538
+ updateY(value, operation = "set") {
1539
+ if (operation === "set") this.cursor.y = value;
1540
+ else if (operation === "add") this.cursor.y += value;
1541
+ }
1542
+ /**
1543
+ * Records a Y position as the bottom of rendered content.
1544
+ * This is useful for container components (like blockquotes) to know
1545
+ * where their actual text content ends, ignoring any trailing margins.
1546
+ * @param specificY Optional Y value to record. Defaults to current cursor Y.
1547
+ */
1548
+ recordContentY(specificY) {
1549
+ this.lastContentY_ = specificY !== void 0 ? specificY : this.cursor.y;
1550
+ }
1551
+ /**
1552
+ * Gets the last Y position recorded as content bottom.
1553
+ */
1554
+ get lastContentY() {
1555
+ return this.lastContentY_;
1556
+ }
1557
+ get X() {
1558
+ return this.cursor.x;
1559
+ }
1560
+ get Y() {
1561
+ return this.cursor.y;
1562
+ }
1563
+ };
1564
+ //#endregion
1565
+ //#region src/utils/options-validation.ts
1566
+ const defaultOptions = {
1567
+ page: {
1568
+ indent: 10,
1569
+ maxContentWidth: 190,
1570
+ maxContentHeight: 277,
1571
+ lineSpace: 1.5,
1572
+ defaultLineHeightFactor: 1.2,
1573
+ defaultFontSize: 12,
1574
+ defaultTitleFontSize: 14,
1575
+ topmargin: 10,
1576
+ xpading: 10,
1577
+ xmargin: 10,
1578
+ format: "a4",
1579
+ orientation: "p"
1580
+ },
1581
+ font: {
1582
+ bold: {
1583
+ name: "helvetica",
1584
+ style: "bold"
1585
+ },
1586
+ regular: {
1587
+ name: "helvetica",
1588
+ style: "normal"
1589
+ },
1590
+ light: {
1591
+ name: "helvetica",
1592
+ style: "light"
1593
+ },
1594
+ code: {
1595
+ name: "courier",
1596
+ style: "normal"
1597
+ }
1598
+ },
1599
+ image: { defaultAlign: "left" }
1600
+ };
1601
+ const validateOptions = (options) => {
1602
+ if (!options) throw new Error("RenderOption is required");
1603
+ const mergedPage = {
1604
+ ...defaultOptions.page,
1605
+ ...options.page
1606
+ };
1607
+ const mergedFont = {
1608
+ ...defaultOptions.font,
1609
+ ...options.font
1610
+ };
1611
+ const mergedImage = {
1612
+ ...defaultOptions.image,
1613
+ ...options.image
1614
+ };
1615
+ if (!mergedPage.maxContentWidth) mergedPage.maxContentWidth = 190;
1616
+ if (!mergedPage.maxContentHeight) mergedPage.maxContentHeight = 277;
1617
+ return {
1618
+ ...options,
1619
+ page: mergedPage,
1620
+ font: mergedFont,
1621
+ image: mergedImage
1622
+ };
1623
+ };
1624
+ //#endregion
1625
+ //#region src/renderer/MdTextRender.ts
1626
+ /**
1627
+ * Renders parsed markdown text into jsPDF document.
1628
+ *
1629
+ * @param doc - The jsPDF document.
1630
+ * @param text - The markdown content to render.
1631
+ * @param options - The render options (fonts, page margins, etc.).
1632
+ */
1633
+ const MdTextRender = async (doc, text, options) => {
1634
+ const validOptions = validateOptions(options);
1635
+ const store = new RenderStore(validOptions);
1636
+ const parsedElements = await MdTextParser(text);
1637
+ await prefetchImages(parsedElements);
1638
+ const renderElement = (element, indentLevel = 0, store, hasRawBullet = false, start = 0, ordered = false) => {
1639
+ const indent = indentLevel * validOptions.page.indent;
1640
+ switch (element.type) {
1641
+ case "heading":
1642
+ renderHeading(doc, element, indent, store, renderElement);
1643
+ break;
1644
+ case "paragraph":
1645
+ renderParagraph(doc, element, indent, store, renderElement);
1646
+ break;
1647
+ case "list":
1648
+ renderList(doc, element, indentLevel, store, renderElement);
1649
+ break;
1650
+ case "list_item":
1651
+ renderListItem(doc, element, indentLevel, store, renderElement, start, ordered);
1652
+ break;
1653
+ case "hr":
1654
+ renderHR(doc, store);
1655
+ break;
1656
+ case "code":
1657
+ renderCodeBlock(doc, element, indentLevel, store);
1658
+ break;
1659
+ case "strong":
1660
+ case "em":
1661
+ case "codespan":
1662
+ renderInlineText(doc, element, indent, store);
1663
+ break;
1664
+ case "link":
1665
+ renderLink(doc, element, indent, store);
1666
+ break;
1667
+ case "blockquote":
1668
+ renderBlockquote(doc, element, indentLevel, store, renderElement);
1669
+ break;
1670
+ case "image":
1671
+ renderImage(doc, element, indentLevel, store);
1672
+ break;
1673
+ case "br": {
1674
+ store.updateX(validOptions.page.xpading, "set");
1675
+ const brHeight = getCharHight(doc) * validOptions.page.defaultLineHeightFactor;
1676
+ if (store.Y + brHeight > validOptions.page.maxContentHeight) HandlePageBreaks(doc, store);
1677
+ else store.updateY(brHeight, "add");
1678
+ store.recordContentY();
1679
+ break;
1680
+ }
1681
+ case "table":
1682
+ renderTable(doc, element, indentLevel, store);
1683
+ break;
1684
+ case "raw":
1685
+ case "text":
1686
+ renderRawItem(doc, element, indentLevel, store, hasRawBullet, renderElement, start, ordered, validOptions.content?.textAlignment === "justify");
1687
+ break;
1688
+ default:
1689
+ console.warn(`Warning: Unsupported element type encountered: ${element.type}.
4
1690
  If you believe this element type should be supported, please create an issue at:
5
1691
  https://github.com/JeelGajera/jspdf-md-renderer/issues
6
- with details of the element and expected behavior. Thanks for helping to improve this library!`);break}};for(let e of a)o(e,0,i);r.endCursorYHandler(i.Y)};exports.MdTextParser=y,exports.MdTextRender=Y;
1692
+ with details of the element and expected behavior. Thanks for helping to improve this library!`);
1693
+ break;
1694
+ }
1695
+ };
1696
+ for (const item of parsedElements) renderElement(item, 0, store);
1697
+ validOptions.endCursorYHandler(store.Y);
1698
+ };
1699
+ //#endregion
1700
+ exports.MdTextParser = MdTextParser;
1701
+ exports.MdTextRender = MdTextRender;