shrekbytes_advanced-pdf-export/main.js
2026-06-24 15:49:18 +06:00

251 lines
57 KiB
JavaScript

var K=Object.defineProperty;var de=Object.getOwnPropertyDescriptor;var ce=Object.getOwnPropertyNames;var ge=Object.prototype.hasOwnProperty;var me=(o,t)=>{for(var e in t)K(o,e,{get:t[e],enumerable:!0})},pe=(o,t,e,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of ce(t))!ge.call(o,i)&&i!==e&&K(o,i,{get:()=>t[i],enumerable:!(a=de(t,i))||a.enumerable});return o};var he=o=>pe(K({},"__esModule",{value:!0}),o);var Je={};me(Je,{default:()=>G});module.exports=he(Je);var s=require("obsidian"),_={A4:{w:794,h:1123},A3:{w:1123,h:1587},Letter:{w:816,h:1056},Legal:{w:816,h:1344},A5:{w:559,h:794}},U={default:{name:"Default",fontFamily:"Georgia, serif",fontSize:13,lineHeight:1.85,paragraphSpacing:.65,headingScale:1,accentColor:"#7c6af7",bodyColor:"#1a1a2e",headingColor:"#0d0d1a",h1BorderBottom:!1,h2BorderBottom:!0,centerH1:!1,blockquoteBg:"transparent",blockquoteBorderColor:"#7c6af7",codeBackground:"#f0f0f8",codeFontSize:.85,codeTheme:"github-light",tableHeaderBg:"#f0f0f8",tableStriped:!0,pageBackground:"#ffffff",marginTop:20,marginBottom:20,marginLeft:25,marginRight:25},minimal:{name:"Minimal",fontFamily:"'Helvetica Neue', Helvetica, sans-serif",fontSize:12,lineHeight:1.6,paragraphSpacing:.45,headingScale:.88,accentColor:"#333",bodyColor:"#222",headingColor:"#111",h1BorderBottom:!1,h2BorderBottom:!1,centerH1:!1,blockquoteBg:"#f8f8f8",blockquoteBorderColor:"#ccc",codeBackground:"#f4f4f4",codeFontSize:.82,codeTheme:"none",tableHeaderBg:"#efefef",tableStriped:!1,pageBackground:"#ffffff",marginTop:16,marginBottom:16,marginLeft:20,marginRight:20},academic:{name:"Academic",fontFamily:"'Times New Roman', Times, serif",fontSize:12,lineHeight:2,paragraphSpacing:0,headingScale:.95,accentColor:"#1a3a6b",bodyColor:"#000",headingColor:"#000",h1BorderBottom:!0,h2BorderBottom:!0,centerH1:!0,blockquoteBg:"transparent",blockquoteBorderColor:"#999",codeBackground:"#f9f9f9",codeFontSize:.88,codeTheme:"solarized-light",tableHeaderBg:"#e8e8e8",tableStriped:!1,pageBackground:"#ffffff",marginTop:25,marginBottom:25,marginLeft:30,marginRight:30},colorful:{name:"Colorful",fontFamily:"Georgia, serif",fontSize:13,lineHeight:1.85,paragraphSpacing:.65,headingScale:1.05,accentColor:"#e84393",bodyColor:"#1a1a2e",headingColor:"#2d0a4e",h1BorderBottom:!1,h2BorderBottom:!1,centerH1:!1,blockquoteBg:"#fdf0f8",blockquoteBorderColor:"#e84393",codeBackground:"#f0eaff",codeFontSize:.85,codeTheme:"dracula",tableHeaderBg:"#2d0a4e",tableStriped:!0,pageBackground:"#ffffff",marginTop:20,marginBottom:20,marginLeft:25,marginRight:25},modern:{name:"Modern",fontFamily:"Arial, sans-serif",fontSize:13,lineHeight:1.75,paragraphSpacing:.6,headingScale:1,accentColor:"#0070f3",bodyColor:"#111",headingColor:"#000",h1BorderBottom:!1,h2BorderBottom:!1,centerH1:!1,blockquoteBg:"#f0f7ff",blockquoteBorderColor:"#0070f3",codeBackground:"#f1f5f9",codeFontSize:.85,codeTheme:"github-dark",tableHeaderBg:"#0070f3",tableStriped:!0,pageBackground:"#ffffff",marginTop:20,marginBottom:20,marginLeft:25,marginRight:25},newspaper:{name:"Newspaper",fontFamily:"Georgia, serif",fontSize:12,lineHeight:1.7,paragraphSpacing:.4,headingScale:1.1,accentColor:"#111",bodyColor:"#111",headingColor:"#000",h1BorderBottom:!0,h2BorderBottom:!0,centerH1:!0,blockquoteBg:"transparent",blockquoteBorderColor:"#111",codeBackground:"#f4f4f4",codeFontSize:.82,codeTheme:"none",tableHeaderBg:"#111",tableStriped:!1,pageBackground:"#ffffff",marginTop:18,marginBottom:18,marginLeft:20,marginRight:20},dark:{name:"Dark",fontFamily:"Georgia, serif",fontSize:13,lineHeight:1.85,paragraphSpacing:.65,headingScale:1,accentColor:"#818cf8",bodyColor:"#d1d5db",headingColor:"#f1f5f9",h1BorderBottom:!1,h2BorderBottom:!0,centerH1:!1,blockquoteBg:"#1e293b",blockquoteBorderColor:"#818cf8",codeBackground:"#0f172a",codeFontSize:.85,codeTheme:"tokyo-night",tableHeaderBg:"#1e293b",tableStriped:!0,pageBackground:"#111827",marginTop:20,marginBottom:20,marginLeft:25,marginRight:25}},oe={pageSize:"A4",orientation:"portrait",preset:"default",...U.default,headerText:"",footerText:"",showHeader:!0,showFooter:!0,showHeaderBorder:!1,showFooterBorder:!1,showPageNumbers:!0,pageNumberPosition:"right",pageNumberStart:1,showHeaderOnFirstPage:!0,showFooterOnFirstPage:!0,headerAlignment:"right",footerTextAlignment:"left",headerFontSize:9,headerFontColor:"#999999",footerFontSize:9,footerFontColor:"#aaaaaa",linkUnderline:!0,frameEnabled:!1,frameColor:"#000000",frameThickness:4,frameMargin:8,frameStyle:"solid",hideFrontmatter:!1,customFontName:"",autoBreakH1:!1,autoBreakH2:!1,includeFilenameAsTitle:!1,previewScale:.9,customPageWidth:210,customPageHeight:297,headerHeight:0,footerHeight:0,headerImagePath:"",headerImageMargin:0,footerImagePath:"",footerImageMargin:0,backgroundImageEnabled:!1,backgroundImagePath:"",backgroundImageSize:"cover",backgroundImageScope:"full-page",backgroundImageOpacity:1},V=o=>o/25.4*96;function ue(o){return o.pageSize==="Custom"?{w:Math.max(1,Math.round(V(o.customPageWidth))),h:Math.max(1,Math.round(V(o.customPageHeight)))}:_[o.pageSize]??_.A4}function W(o){return o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function fe(o){return o.replace(/<\/style/gi,"<\\/style")}function O(o,t){let e=t.trim();if(!e)return"";if(/^(https?:|data:)/i.test(e))return e;let a=o.vault.getAbstractFileByPath(e);if(a instanceof s.TFile)return o.vault.getResourcePath(a);let i=o.metadataCache.getFirstLinkpathDest(e,"");return i instanceof s.TFile?o.vault.getResourcePath(i):e}var be=/[\u0590-\u08FF\uFB1D-\uFDFD\uFE70-\uFEFC]/g,we=/[A-Za-z\u0590-\u08FF\uFB1D-\uFDFD\uFE70-\uFEFC]/g;function Se(o){let t=(o.match(be)??[]).length,e=(o.match(we)??[]).length;return e>0&&t/e>.1}function xe(o){return o.replace(/\r\n/g,`
`)}function ve(o){return o.replace(/^---[ \t]*\n[\s\S]*?\n---[ \t]*(\n|$)/,"")}function Ce(o){return o.split(/^\/\/\/\s*$/m).map(t=>t.trim()).filter(Boolean)}async function ke(o,t,e,a){let i=activeDocument.createElement("div");i.setCssStyles({position:"fixed",top:"0",left:"-99999px",visibility:"hidden",pointerEvents:"none"}),activeDocument.body.appendChild(i);try{await s.MarkdownRenderer.render(o,t,i,e,a),await Te(i)}finally{activeDocument.body.removeChild(i)}return ye(i),i}function ne(o){return o.toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-")}function ye(o){let t=new Map;o.querySelectorAll("h1,h2,h3,h4,h5,h6").forEach(e=>{let a=e.textContent||"",i=ne(a);if(!i)return;let l=t.get(i)??0;t.set(i,l+1),e.id=l===0?i:`${i}-${l}`}),o.querySelectorAll("a").forEach(e=>{e.classList.remove("external-link");let a=e.getAttribute("data-href")??e.getAttribute("href");a?.startsWith("#")&&e.setAttribute("href","#"+ne(a.slice(1)))}),o.querySelectorAll(".copy-code-button").forEach(e=>e.remove()),o.querySelectorAll(".callout").forEach(e=>{e.removeAttribute("data-callout-fold"),e.classList.remove("is-collapsed"),e.querySelectorAll(".callout-fold").forEach(a=>a.remove())}),o.querySelectorAll("style, script").forEach(e=>{e.closest("svg")||e.remove()})}async function Te(o){let t=Array.from(o.querySelectorAll(".mermaid"));if(t.length===0)return;let e=5e3;await Promise.all(t.map(a=>new Promise(i=>{if(a.querySelector("svg")){i();return}let l=window.setTimeout(()=>{d.disconnect(),i()},e),d=new MutationObserver(()=>{a.querySelector("svg")&&(window.clearTimeout(l),d.disconnect(),i())});d.observe(a,{childList:!0,subtree:!0})})))}var Ee={comment:["comment","prolog","doctype","cdata"],punctuation:["punctuation"],property:["property","tag","boolean","number","constant","symbol","deleted","attr-name"],selector:["selector","string","char","builtin","inserted","attr-value"],operator:["operator","entity","url"],keyword:["atrule","keyword","important"],function:["function","class-name"],regex:["regex","variable"]},Z={none:{name:"None (plain)"},"github-light":{name:"GitHub Light",background:"#f6f8fa",text:"#24292e",tokens:{comment:"#6a737d",punctuation:"#24292e",property:"#005cc5",selector:"#032f62",operator:"#d73a49",keyword:"#d73a49",function:"#6f42c1",regex:"#032f62"}},"github-dark":{name:"GitHub Dark",background:"#0d1117",text:"#c9d1d9",tokens:{comment:"#8b949e",punctuation:"#c9d1d9",property:"#79c0ff",selector:"#a5d6ff",operator:"#ff7b72",keyword:"#ff7b72",function:"#d2a8ff",regex:"#a5d6ff"}},"atom-one-light":{name:"Atom One Light",background:"#fafafa",text:"#383a42",tokens:{comment:"#a0a1a7",punctuation:"#383a42",property:"#986801",selector:"#50a14f",operator:"#0184bc",keyword:"#a626a4",function:"#4078f2",regex:"#50a14f"}},"atom-one-dark":{name:"Atom One Dark",background:"#282c34",text:"#abb2bf",tokens:{comment:"#5c6370",punctuation:"#abb2bf",property:"#d19a66",selector:"#98c379",operator:"#56b6c2",keyword:"#c678dd",function:"#61afef",regex:"#98c379"}},monokai:{name:"Monokai",background:"#272822",text:"#f8f8f2",tokens:{comment:"#75715e",punctuation:"#f8f8f2",property:"#ae81ff",selector:"#e6db74",operator:"#f92672",keyword:"#f92672",function:"#a6e22e",regex:"#e6db74"}},dracula:{name:"Dracula",background:"#282a36",text:"#f8f8f2",tokens:{comment:"#6272a4",punctuation:"#f8f8f2",property:"#bd93f9",selector:"#f1fa8c",operator:"#ff79c6",keyword:"#ff79c6",function:"#50fa7b",regex:"#ff79c6"}},"tokyo-night":{name:"Tokyo Night",background:"#1a1b26",text:"#a9b1d6",tokens:{comment:"#565f89",punctuation:"#89ddff",property:"#ff9e64",selector:"#9ece6a",operator:"#89ddff",keyword:"#bb9af7",function:"#7aa2f7",regex:"#b4f9f8"}},"solarized-light":{name:"Solarized Light",background:"#fdf6e3",text:"#586e75",tokens:{comment:"#93a1a1",punctuation:"#586e75",property:"#cb4b16",selector:"#2aa198",operator:"#859900",keyword:"#859900",function:"#268bd2",regex:"#2aa198"}},"catppuccin-macchiato":{name:"Catppuccin Macchiato",background:"#24273a",text:"#cad3f5",tokens:{comment:"#939ab7",punctuation:"#b8c0e0",property:"#f5a97f",selector:"#a6da95",operator:"#91d7e3",keyword:"#c6a0f6",function:"#8aadf4",regex:"#f5bde6"}},"catppuccin-mocha":{name:"Catppuccin Mocha",background:"#1e1e2e",text:"#cdd6f4",tokens:{comment:"#9399b2",punctuation:"#bac2de",property:"#fab387",selector:"#a6e3a1",operator:"#89dceb",keyword:"#cba6f7",function:"#89b4fa",regex:"#f5c2e7"}}};function He(o){let t=Z[o.codeTheme]??Z.none,e=t.background??o.codeBackground,a=t.text??o.bodyColor,i=Object.entries(t.tokens??{}).map(([l,d])=>`${Ee[l].map(c=>`.mpdf-doc pre code .token.${c}`).join(", ")} { color: ${d};${l==="comment"?" font-style: italic;":""} }`).join(`
`);return`
.mpdf-doc pre {
background: ${e};
border-radius: 4px;
padding: 10px 12px;
margin: 0 0 ${o.paragraphSpacing}em;
overflow: hidden;
}
.mpdf-doc pre code {
font-family: 'Courier New', monospace;
font-size: ${o.codeFontSize}em;
color: ${a};
white-space: pre-wrap;
overflow-wrap: break-word;
background: none;
padding: 0;
}
${i}`}function Fe(o){let t=o.replace(/^#([\da-f])([\da-f])([\da-f])$/i,(d,p,m,c)=>`#${p}${p}${m}${m}${c}${c}`);if(!/^#[\da-f]{6}$/i.test(t))return 1;let e=d=>d<=.04045?d/12.92:((d+.055)/1.055)**2.4,a=e(parseInt(t.slice(1,3),16)/255),i=e(parseInt(t.slice(3,5),16)/255),l=e(parseInt(t.slice(5,7),16)/255);return .2126*a+.7152*i+.0722*l}function ie(o){return o.fontFamily==="__custom__"?o.customFontName.trim()||"inherit":o.fontFamily}function Be(o,t=!1){let e=o.headingScale,a=ie(o),i=Fe(o.tableHeaderBg)<.35?"#fff":o.headingColor;return`
.mpdf-doc {
font-family: ${a};
font-size: ${o.fontSize}px;
line-height: ${o.lineHeight};
color: ${o.bodyColor};
box-sizing: border-box;
${t?"direction: rtl;":""}
}
.mpdf-doc *, .mpdf-doc *::before, .mpdf-doc *::after { box-sizing: border-box; }
.mpdf-doc strong, .mpdf-doc b { font-weight: 700; font-style: normal; }
.mpdf-doc em, .mpdf-doc i { font-style: italic; font-weight: inherit; }
.mpdf-doc mark { background: #ffe066; color: inherit; padding: 0 2px; border-radius: 2px; }
.mpdf-doc del, .mpdf-doc s { text-decoration: line-through; }
.mpdf-doc h1 {
font-size: ${Math.round(22*e)}px;
font-weight: 700;
color: ${o.headingColor};
margin: 0 0 ${Math.round(12*e)}px;
line-height: 1.2;
${o.h1BorderBottom?`border-bottom: 2px solid ${o.accentColor}; padding-bottom: 6px;`:""}
${o.centerH1?"text-align: center;":""}
}
.mpdf-doc h2 {
font-size: ${Math.round(17*e)}px;
font-weight: 600;
color: ${o.headingColor};
margin: ${Math.round(20*e)}px 0 ${Math.round(10*e)}px;
${o.h2BorderBottom?`border-bottom: 0.5px solid ${o.accentColor}55; padding-bottom: 5px;`:""}
}
.mpdf-doc h3 {
font-size: ${Math.round(15*e)}px;
font-weight: 700;
color: ${o.headingColor};
margin: ${Math.round(16*e)}px 0 ${Math.round(8*e)}px;
letter-spacing: 0.01em;
}
.mpdf-doc h4 { font-size: ${Math.round(13*e)}px; font-weight: 700; color: ${o.headingColor}; margin: 12px 0 6px; text-transform: uppercase; letter-spacing: 0.04em; }
.mpdf-doc h5 { font-size: ${Math.round(12*e)}px; font-weight: 600; color: ${o.headingColor}; margin: 10px 0 4px; font-style: italic; }
.mpdf-doc h6 { font-size: ${Math.round(11*e)}px; font-weight: 600; color: ${o.bodyColor}; margin: 8px 0 4px; font-style: italic; opacity: 0.75; }
.mpdf-doc p { margin: 0 0 ${o.paragraphSpacing}em; }
.mpdf-doc ul, .mpdf-doc ol { padding-inline-start: 1.4em; margin: 0 0 ${o.paragraphSpacing}em; }
.mpdf-doc li { margin-bottom: 0.2em; line-height: ${o.lineHeight}; }
.mpdf-doc blockquote {
border-inline-start: 3px solid ${o.blockquoteBorderColor};
background: ${o.blockquoteBg};
padding-block: 4px;
padding-inline: 1em 0;
margin: ${o.paragraphSpacing}em 0;
font-style: italic;
color: ${o.bodyColor}cc;
}
.mpdf-doc code {
font-family: 'Courier New', monospace;
font-size: ${o.codeFontSize}em;
background: ${o.codeBackground};
padding: 1px 4px;
border-radius: 3px;
color: ${o.accentColor};
}
${He(o)}
.mpdf-doc hr {
border: none;
border-top: 0.5px solid ${o.accentColor}44;
margin: ${o.paragraphSpacing*1.5}em 0;
}
.mpdf-doc img { max-width: 100%; height: auto; display: block; margin: ${o.paragraphSpacing}em auto; }
.mpdf-doc a { color: ${o.accentColor}; ${o.linkUnderline?"":"text-decoration: none;"} }
.mpdf-doc a.external-link::after { display: none !important; content: none !important; }
/* Hide copy-code buttons that survive postProcessRenderedHTML (e.g. re-injected by themes). */
.mpdf-doc .copy-code-button { display: none !important; }
.mpdf-doc table { width: 100%; border-collapse: collapse; margin: 0 0 ${o.paragraphSpacing}em; font-size: 0.92em; }
.mpdf-doc th {
background: ${o.tableHeaderBg};
color: ${i};
padding: 6px 10px;
text-align: start;
font-weight: 600;
border: 0.5px solid ${o.accentColor}33;
font-size: 0.9em;
}
.mpdf-doc td { padding: 5px 10px; border: 0.5px solid ${o.bodyColor}22; vertical-align: top; }
${o.tableStriped?`.mpdf-doc tbody tr:nth-child(even) { background: ${o.tableHeaderBg}55; }`:""}
/* Callouts \u2014 override theme styles with !important so preview and export are
* identical regardless of the active Obsidian theme. */
.mpdf-doc .callout {
border-inline-start: 4px solid ${o.accentColor} !important;
border-start-start-radius: 0 !important;
border-start-end-radius: 5px !important;
border-end-end-radius: 5px !important;
border-end-start-radius: 0 !important;
background: ${o.accentColor}12 !important;
margin: ${o.paragraphSpacing*1.2}em 0 !important;
padding: 0 !important;
overflow: hidden !important;
box-shadow: inset 0 0 0 1px ${o.accentColor}22 !important;
font-style: normal !important;
}
.mpdf-doc .callout-title {
display: flex !important;
align-items: center !important;
gap: 7px !important;
padding: 7px 12px !important;
background: ${o.accentColor}28 !important;
border-bottom: 1px solid ${o.accentColor}33 !important;
font-family: ${a} !important;
font-size: 0.8em !important;
font-weight: 800 !important;
font-style: normal !important;
letter-spacing: 0.08em !important;
text-transform: uppercase !important;
color: ${o.accentColor} !important;
line-height: 1.3 !important;
}
.mpdf-doc .callout-icon {
display: inline-flex !important;
align-items: center !important;
flex-shrink: 0 !important;
width: 15px !important;
height: 15px !important;
color: ${o.accentColor} !important;
}
.mpdf-doc .callout-icon svg {
width: 15px !important;
height: 15px !important;
stroke: ${o.accentColor} !important;
fill: none !important;
stroke-width: 2 !important;
}
.mpdf-doc .callout-title-inner {
flex: 1 !important;
min-width: 0 !important;
}
.mpdf-doc .callout-fold { display: none !important; }
.mpdf-doc .callout-content {
padding: 9px 14px !important;
color: ${o.bodyColor} !important;
font-style: normal !important;
background: transparent !important;
}
.mpdf-doc .callout-content > p:first-child { margin-top: 0 !important; }
.mpdf-doc .callout-content > p:last-child { margin-bottom: 0 !important; }
/* Nested blockquotes inside callout content keep a subtler indent */
.mpdf-doc .callout-content blockquote {
border-inline-start-color: ${o.accentColor}66 !important;
background: transparent !important;
}
/* Mermaid diagrams \u2014 centre the SVG and prevent it overflowing the content
* column. The <style> block inside the SVG is intentionally left untouched;
* mermaid embeds its own theme CSS there. */
.mpdf-doc .mermaid {
display: flex;
justify-content: center;
margin: ${o.paragraphSpacing}em 0;
overflow: hidden;
}
.mpdf-doc .mermaid svg {
max-width: 100%;
height: auto;
display: block;
}
`.trim()}function Le(o){return{name:o.name,fontFamily:o.fontFamily,fontSize:o.fontSize,lineHeight:o.lineHeight,paragraphSpacing:o.paragraphSpacing,headingScale:o.headingScale,accentColor:o.accentColor,bodyColor:o.bodyColor,headingColor:o.headingColor,h1BorderBottom:o.h1BorderBottom,h2BorderBottom:o.h2BorderBottom,centerH1:o.centerH1,blockquoteBg:o.blockquoteBg,blockquoteBorderColor:o.blockquoteBorderColor,codeBackground:o.codeBackground,codeFontSize:o.codeFontSize,codeTheme:o.codeTheme,tableHeaderBg:o.tableHeaderBg,tableStriped:o.tableStriped,pageBackground:o.pageBackground,marginTop:o.marginTop,marginBottom:o.marginBottom,marginLeft:o.marginLeft,marginRight:o.marginRight}}function De(){return Array.from(activeDocument.head.querySelectorAll("style[id^='MJX-']")).map(o=>o.textContent??"").join(`
`)}var Pe=new Set(["P","LI","BLOCKQUOTE","TD","TH"]),$e=new Set(["P","DIV","SECTION","ARTICLE","ASIDE","NAV","HEADER","FOOTER","UL","OL","LI","TABLE","THEAD","TBODY","TFOOT","TR","TD","TH","PRE","BLOCKQUOTE","HR","IMG","H1","H2","H3","H4","H5","H6"]),Me=new Set(["CODE","IMG","HR","H1","H2","H3","H4","H5","H6"]),Ne=2;function Ie(o,t){t.empty();for(let e of o)t.appendChild(e.cloneNode(!0));return t.getBoundingClientRect().height}function ze(o,t,e){return a=>Ie([...o,a],t)<=e-Ne}function Ae(o){let t=activeDocument.createTreeWalker(o,NodeFilter.SHOW_TEXT);for(;t.nextNode();){let e=t.currentNode,a=(e.textContent??"").replace(/^\s+/,"");if(a!==e.textContent&&(e.textContent=a),a.length>0)break}}function q(o,t,e=!0){let a=activeDocument.createTreeWalker(o,NodeFilter.SHOW_TEXT),i=0,l=null,d=0;for(;a.nextNode();){let u=a.currentNode,f=u.textContent?.length??0;if(i+f>=t){l=u,d=t-i;break}i+=f}if(!l)return null;let p=activeDocument.createRange();p.selectNodeContents(o),p.setEnd(l,d);let m=activeDocument.createRange();m.selectNodeContents(o),m.setStart(l,d);let c=o.cloneNode(!1);c.appendChild(p.cloneContents());let g=o.cloneNode(!1);return g.appendChild(m.cloneContents()),e&&Ae(g),[c,g]}function Re(o){let t=[],e=/\s+/g,a;for(;a=e.exec(o);)a.index>0&&a.index<o.length&&t.push(a.index);return t}function Oe(o,t,e){let a=o.textContent??"";if(a.length<2)return null;let i=Re(a);if(i.length>0){let m=0,c=i.length-1,g=-1;for(;m<=c;){let u=Math.floor((m+c)/2),f=q(o,i[u]);if(!f){c=u-1;continue}t(f[0])?(g=u,m=u+1):c=u-1}if(g>=0)return q(o,i[g]);if(!e)return null}let l=1,d=a.length-1,p=0;for(;l<=d;){let m=Math.floor((l+d)/2),c=q(o,m);if(!c){d=m-1;continue}t(c[0])?(p=m,l=m+1):d=m-1}return p>0?q(o,p):null}function X(o,t,e){let a=o.cloneNode(!1);o.tagName==="OL"&&e!==void 0&&e>1&&(a.start=e);for(let i of t)a.appendChild(i.cloneNode(!0));return a}function Ve(o,t,e){let a=Array.from(o.children).filter(d=>d.tagName==="LI");if(a.length===0)return null;let i=o.tagName==="OL"?o.start??1:1,l=0;for(let d=0;d<a.length&&t(X(o,a.slice(0,d+1),i));d++)l=d+1;if(l<=0){if(!e||a.length<2)return null;l=1}return l>=a.length?null:[X(o,a.slice(0,l),i),X(o,a.slice(l),i+l)]}function Y(o,t){let e=o.cloneNode(!1),a=o.querySelector("caption");a&&e.appendChild(a.cloneNode(!0));let i=o.querySelector("colgroup");i&&e.appendChild(i.cloneNode(!0)),o.tHead&&e.appendChild(o.tHead.cloneNode(!0));let l=activeDocument.createElement("tbody");for(let d of t)l.appendChild(d.cloneNode(!0));return e.appendChild(l),e}function qe(o,t,e){let a=o.tBodies[0],i=a?Array.from(a.rows):Array.from(o.rows).filter(d=>d.parentElement?.tagName!=="THEAD");if(i.length===0)return null;let l=0;for(let d=0;d<i.length&&t(Y(o,i.slice(0,d+1)));d++)l=d+1;if(l<=0){if(!e||i.length<2)return null;l=1}return l>=i.length?null:[Y(o,i.slice(0,l)),Y(o,i.slice(l))]}function Ue(o){let t=[],e=0;for(let a of o)e+=a.length+1,t.push(e);return t}function We(o,t,e){let a=o.querySelector("code"),i=(a??o).textContent?.split(`
`)??[];if(i.length>1&&i[i.length-1]===""&&i.pop(),i.length<2)return null;let l=Ue(i),d=c=>{if(!a){let v=y=>{let C=o.cloneNode(!1);return C.textContent=y,C};return[v(i.slice(0,c).join(`
`)),v(i.slice(c).join(`
`))]}let g=q(a,l[c-1],!1);if(!g)return null;let u=o.cloneNode(!1);u.appendChild(g[0]);let f=o.cloneNode(!1);return f.appendChild(g[1]),[u,f]},p=null,m=0;for(let c=1;c<=i.length;c++){let g=d(c);if(!g||!t(g[0]))break;p=g,m=c}if(m<=0){if(!e)return null;p=d(1),m=1}return m>=i.length||!p?null:p}function _e(o){if(!Pe.has(o.tagName))return!1;for(let t of Array.from(o.childNodes))if(t.nodeType===Node.ELEMENT_NODE&&$e.has(t.tagName))return!1;return!0}function Ge(o,t,e){return Me.has(o.tagName)?null:o.tagName==="PRE"?We(o,t,e):o.tagName==="TABLE"?qe(o,t,e):o.tagName==="UL"||o.tagName==="OL"?Ve(o,t,e):_e(o)?Oe(o,t,e):null}function je(o,t,e,a){let i=activeDocument.createElement("div");i.setCssStyles({position:"fixed",top:"0",left:"-99999px",width:`${t}px`,visibility:"hidden",pointerEvents:"none",zIndex:"-1"});let l=i.attachShadow({mode:"open"}),d=new CSSStyleSheet;d.replaceSync(a),l.adoptedStyleSheets=[d];let p=activeDocument.createElement("div");p.className="mpdf-doc";for(let g of Array.from(o.children))p.appendChild(g.cloneNode(!0));l.appendChild(p);let m=activeDocument.createElement("div");m.className="mpdf-doc",m.setCssStyles({position:"absolute",top:"0",left:"0",width:`${t}px`,visibility:"hidden"}),l.appendChild(m),activeDocument.body.appendChild(i);let c=[];try{let g=[],u=Array.from(p.children),f=0;for(;f<u.length;){let v=u[f],y=ze(g,m,e);if(y(v)){g.push(v.cloneNode(!0)),f++;continue}let C=g.length===0,H=Ge(v,y,C);if(H){g.push(H[0]),c.push(g),g=[];let S=H[1];S.textContent?.trim()||S.children.length>0?u[f]=S:f++;continue}if(g.length>0){c.push(g),g=[];continue}g.push(v.cloneNode(!0)),c.push(g),g=[],f++}g.length>0&&c.push(g)}finally{activeDocument.body.removeChild(i)}return c.length>0?c:[[]]}function Ke(o,t){let e=o.length;return o.map((a,i)=>{let l=i+1,d=t.showHeaderOnFirstPage||i>0,p=t.showFooterOnFirstPage||i>0,m=t.showFooterOnFirstPage?t.pageNumberStart+i:t.pageNumberStart+(i-1),c=t.showFooterOnFirstPage?t.pageNumberStart+e-1:t.pageNumberStart+e-2,g=`${m} / ${c}`,u="",f="",v="",y="",C="",H="";if(p&&(t.footerText&&(t.footerTextAlignment==="center"?v=t.footerText:t.footerTextAlignment==="left"?u=t.footerText:f=t.footerText),t.showPageNumbers)){let S=n=>n?n+" \u2014 "+g:g;t.pageNumberPosition==="center"?v=S(v):t.pageNumberPosition==="left"?u=S(u):f=S(f)}return d&&t.headerText&&(t.headerAlignment==="center"?C=t.headerText:t.headerAlignment==="left"?y=t.headerText:H=t.headerText),{pageNodes:a,pageNum:l,totalPages:e,headerLeft:y,headerCenter:C,headerRight:H,footerLeft:u,footerRight:f,footerCenter:v}})}function se(o){return`${o.frameThickness}px ${o.frameStyle} ${o.frameColor}`}function Xe(o){if(!o.frameEnabled)return null;let t=`${o.frameMargin}px`,e=activeDocument.createElement("div");return e.setCssStyles({position:"absolute",top:t,left:t,right:t,bottom:t,pointerEvents:"none",boxSizing:"border-box",border:se(o)}),e}function Ye(o){if(!o.frameEnabled)return"";let t=`${o.frameMargin}px`;return`<div style="position:absolute;top:${t};left:${t};right:${t};bottom:${t};pointer-events:none;box-sizing:border-box;border:${se(o)};"></div>`}function re(o,t,e,a){if(!(!t&&!e&&!a))if(t){let i=activeDocument.createElement("span");i.className="mpdf-hf-center",i.textContent=t,o.appendChild(i)}else{let i=activeDocument.createElement("span");i.textContent=e,o.appendChild(i);let l=activeDocument.createElement("span");l.className="mpdf-hf-right",l.textContent=a,o.appendChild(l)}}function ae(o,t,e){return!o&&!t&&!e?"":o?`<span style="flex:1;text-align:center;">${W(o)}</span>`:`<span>${W(t)}</span><span style="margin-left:auto;">${W(e)}</span>`}var G=class extends s.Plugin{activeModal=null;presetSnapshots={};async onload(){await this.loadSettings(),this.addCommand({id:"open-panel",name:"Open Panel",callback:()=>this.openModal()}),this.registerEvent(this.app.workspace.on("file-menu",(t,e)=>{!(e instanceof s.TFile)||e.extension!=="md"||t.addItem(a=>a.setTitle("Advanced PDF Export: Open Panel").setIcon("file-output").onClick(()=>this.openModal(e)))})),this.addSettingTab(new Q(this.app,this))}onunload(){this.activeModal?.close()}openModal(t){this.activeModal&&this.activeModal.close(),new J(this.app,this,t).open()}async loadSettings(){let t=await this.loadData()??{};this.settings=Object.assign({},oe,t),t.codeTheme===void 0&&(this.settings.codeTheme=U[this.settings.preset]?.codeTheme??oe.codeTheme),this.presetSnapshots=t.presetSnapshots??{}}async saveSettings(){await this.saveData({...this.settings,presetSnapshots:this.presetSnapshots})}async saveSettingsAndRender(){await this.saveSettings(),this.activeModal?.render()}applyPreset(t,e=!1){let a=U[t];a&&(e?delete this.presetSnapshots[t]:this.presetSnapshots[this.settings.preset]=Le(this.settings),this.settings.preset=t,Object.assign(this.settings,a,e?{}:this.presetSnapshots[t]??{}))}};function Ze(o,t){if(t)return t;let e=o.workspace.getActiveViewOfType(s.MarkdownView)?.file;if(e)return e;let a=o.workspace.getActiveFile();if(a?.extension==="md")return a;let i=o.workspace.getMostRecentLeaf();return i?.view instanceof s.MarkdownView?i.view.file??null:null}var J=class o extends s.Modal{plugin;editorEl;previewEl;pageCountEl;noteTitleEl;renderBtn;exportBtn;loadingOverlayEl;renderComponent=new s.Component;initialFile;currentFile=null;renderToken=0;layoutCache=null;renderDebounceTimer=null;constructor(t,e,a){super(t),this.plugin=e,this.initialFile=a??null}async onOpen(){this.plugin.activeModal=this,this.renderComponent.load(),this.modalEl.addClass("mpdf-modal"),this.buildUI(this.contentEl);let t=Ze(this.app,this.initialFile);if(t){this.currentFile=t;let e=await this.app.vault.read(t);this.editorEl.value=e,this.noteTitleEl.textContent=t.basename,this.noteTitleEl.title=t.path,this.render(!0)}}onClose(){this.renderDebounceTimer!==null&&(window.clearTimeout(this.renderDebounceTimer),this.renderDebounceTimer=null),this.renderComponent.unload(),this.plugin.activeModal=null,this.currentFile=null,this.layoutCache=null}buildUI(t){let e=this.plugin.settings;this.buildTopbar(t.createEl("div",{cls:"mpdf-topbar"}),e);let a=t.createEl("div",{cls:"mpdf-main"}),i=a.createEl("div",{cls:"mpdf-editor-panel"});this.editorEl=i.createEl("textarea",{cls:"mpdf-editor"}),this.editorEl.placeholder=`Type or paste markdown here to preview and export as PDF.
Tip: open this panel from a note's right-click menu, command palette,
or keyboard shortcut to auto-load the active note.
Use /// on its own line for a manual page break.
Use --- for a horizontal rule.
Mermaid diagrams are supported:
\`\`\`mermaid
flowchart LR
A --> B --> C
\`\`\`
Markdown tables:
| Col A | Col B |
|-------|-------|
| Cell | Cell |`;let l=a.createEl("div",{cls:"mpdf-preview-container"});this.previewEl=l.createEl("div",{cls:"mpdf-preview"}),this.loadingOverlayEl=l.createEl("div",{cls:"mpdf-loading-overlay"}),this.loadingOverlayEl.createEl("div",{cls:"mpdf-spinner"}),this.loadingOverlayEl.createEl("span",{cls:"mpdf-loading-text",text:"Rendering\u2026"}),this.editorEl.addEventListener("keydown",d=>{d.key==="Enter"&&(d.ctrlKey||d.metaKey)&&(d.preventDefault(),this.render(!0))})}buildTopbar(t,e){let a=t.createEl("div",{cls:"mpdf-topbar-left"}),i=t.createEl("div",{cls:"mpdf-topbar-right"}),l=(h,k,T,b)=>{let B=a.createEl("div",{cls:"mpdf-ctrl"});B.createEl("span",{cls:"mpdf-ctrl-label",text:h});let L=B.createEl("select",{cls:"mpdf-select"});for(let[$,x]of Object.entries(k)){let F=L.createEl("option",{text:x,value:$});$===T&&(F.selected=!0)}L.addEventListener("change",()=>void b(L.value))},d={};Object.entries(U).forEach(([h,k])=>d[h]=k.name),l("Style",d,e.preset,async h=>{this.plugin.applyPreset(h),await this.plugin.saveSettingsAndRender()});let p={};Object.keys(_).forEach(h=>p[h]=h),p.Custom="Custom";let m=a.createEl("div",{cls:"mpdf-ctrl"});m.createEl("span",{cls:"mpdf-ctrl-label",text:"Size"});let c=m.createEl("select",{cls:"mpdf-select"});for(let[h,k]of Object.entries(p)){let T=c.createEl("option",{text:k,value:h});h===e.pageSize&&(T.selected=!0)}let g=a.createEl("div",{cls:"mpdf-ctrl"});g.toggleClass("mpdf-is-hidden",e.pageSize!=="Custom");let u=(h,k)=>{g.createEl("span",{cls:"mpdf-ctrl-label",text:h});let T=g.createEl("input",{cls:"mpdf-custom-size-input"});return T.type="number",T.min="10",T.step="1",T.value=String(k),T},f=u("W",e.customPageWidth),v=u("H",e.customPageHeight);g.createEl("span",{cls:"mpdf-ctrl-label",text:"mm"}),c.addEventListener("change",()=>{this.plugin.settings.pageSize=c.value,g.toggleClass("mpdf-is-hidden",c.value!=="Custom"),this.plugin.saveSettingsAndRender()});let y=async()=>{this.plugin.settings.customPageWidth=Math.max(10,parseFloat(f.value)||210),this.plugin.settings.customPageHeight=Math.max(10,parseFloat(v.value)||297),await this.plugin.saveSettingsAndRender()};f.addEventListener("change",()=>void y()),v.addEventListener("change",()=>void y()),l("",{portrait:"Portrait",landscape:"Landscape"},e.orientation,async h=>{this.plugin.settings.orientation=h,await this.plugin.saveSettingsAndRender()});let C=a.createEl("div",{cls:"mpdf-ctrl"});C.createEl("span",{cls:"mpdf-ctrl-label",text:"Zoom"});let H=C.createEl("span",{cls:"mpdf-ctrl-label",text:Math.round(e.previewScale*100)+"%"}),S=C.createEl("input");S.type="range",S.min="0.35",S.max="1.0",S.step="0.05",S.value=String(e.previewScale),S.addClass("mpdf-zoom-slider"),S.addEventListener("input",()=>{let h=parseFloat(S.value);this.plugin.settings.previewScale=h,H.textContent=Math.round(h*100)+"%",this.plugin.saveSettings().then(()=>{this.renderPreviewOnly()})});let n=a.createEl("button",{cls:"mpdf-btn",text:"Insert Page Break"});n.title="Insert page break (///)",n.addEventListener("click",()=>this.insertAtCursor(`
///
`)),this.noteTitleEl=a.createEl("div",{cls:"mpdf-topbar-title",text:"\u2014"}),this.pageCountEl=i.createEl("span",{cls:"mpdf-page-count",text:"\u2014 pages"});let r=i.createEl("button",{cls:"mpdf-btn mpdf-btn-icon"});r.setAttr("aria-label","Open Advanced PDF Export settings"),(0,s.setIcon)(r,"settings"),r.addEventListener("click",()=>{let h=this.app.setting;h?.open?.(),h?.openTabById?.("advanced-pdf-export")}),this.renderBtn=i.createEl("button",{cls:"mpdf-btn",text:"\u27F3 Render PDF"}),this.renderBtn.title="Render preview (Ctrl+Enter)",this.renderBtn.addEventListener("click",()=>this.render(!0)),this.exportBtn=i.createEl("button",{cls:"mpdf-btn mpdf-btn-primary",text:"\u2B07 Export PDF"}),this.exportBtn.addEventListener("click",()=>void this.exportPDF())}insertAtCursor(t){let e=this.editorEl,a=e.selectionStart,i=e.selectionEnd;e.value=e.value.slice(0,a)+t+e.value.slice(i),e.selectionStart=e.selectionEnd=a+t.length,e.focus()}render(t=!1){let e=++this.renderToken;this.renderDebounceTimer!==null&&(window.clearTimeout(this.renderDebounceTimer),this.renderDebounceTimer=null),this.showLoading();let a=()=>this.doRender(e).catch(i=>{let l=i instanceof Error?i.message:String(i);console.error("[advanced-pdf-export] render error:",i),this.hideLoading(),new s.Notice("Render error: "+l)});t?window.requestAnimationFrame(()=>window.requestAnimationFrame(()=>void a())):this.renderDebounceTimer=window.setTimeout(()=>{this.renderDebounceTimer=null,window.requestAnimationFrame(()=>window.requestAnimationFrame(()=>void a()))},150)}static insertAutoBreaks(t,e,a){if(!e&&!a)return t;let i=t.split(`
`),l=[],d=!1,p="";for(let m of i){if(d){let c=m.match(/^(`{3,}|~{3,})\s*$/);c&&c[1][0]===p[0]&&c[1].length>=p.length&&(d=!1,p="")}else{let c=m.match(/^(`{3,}|~{3,})/);c?(d=!0,p=c[1]):l.length>0&&(e&&/^# /.test(m)||a&&/^## /.test(m))&&l.push("///")}l.push(m)}return l.join(`
`)}async doRender(t){let e=this.plugin.settings,a=xe(this.editorEl.value);e.hideFrontmatter&&(a=ve(a)),e.includeFilenameAsTitle&&this.currentFile&&(a=`# ${this.currentFile.basename}
${a}`),a=o.insertAutoBreaks(a,e.autoBreakH1,e.autoBreakH2);let i=Ce(a),l=ue(e),d=e.orientation==="landscape"?l.h:l.w,p=e.orientation==="landscape"?l.w:l.h,m=V(e.marginTop),c=V(e.marginBottom),g=V(e.marginLeft),u=V(e.marginRight),f=e.showFooter&&(e.showPageNumbers||e.footerText||e.showFooterBorder||e.footerImagePath)?e.footerHeight>0?e.footerHeight:Math.max(28,e.footerFontSize+14):0,v=e.showHeader&&(e.headerText||e.showHeaderBorder||e.headerImagePath)?e.headerHeight>0?e.headerHeight:Math.max(20,e.headerFontSize+10):0,y=Math.max(1,d-g-u),C=Math.max(1,p-m-c-f-v),H=Se(this.editorEl.value),S=Be(e,H),n=this.currentFile?.path??"pdf-export",r=await Promise.all(i.map(B=>ke(this.app,B,n,this.renderComponent)));if(t!==this.renderToken)return;let h=De(),k=h?`${h}
${S}`:S,T=[];for(let B of r)T.push(...je(B,y,C,k));let b=Ke(T,e);this.layoutCache={layouts:b,pw:d,ph:p,mTop:m,mLeft:g,mRight:u,footerH:f,headerH:v,contentW:y,contentH:C,docCSS:k,fontFamily:ie(e),accentColor:e.accentColor,pageBackground:e.pageBackground,isRTL:H},this.drawPreview(this.layoutCache,e.previewScale),this.pageCountEl.textContent=`${b.length} page${b.length!==1?"s":""}`,this.hideLoading()}renderPreviewOnly(){this.layoutCache&&this.drawPreview(this.layoutCache,this.plugin.settings.previewScale)}showLoading(){this.loadingOverlayEl.addClass("mpdf-is-active"),this.renderBtn.disabled=!0,this.renderBtn.textContent="Rendering\u2026"}hideLoading(){this.loadingOverlayEl.removeClass("mpdf-is-active"),this.renderBtn.disabled=!1,this.renderBtn.textContent="\u27F3 Render PDF"}drawPreview(t,e){let{layouts:a,pw:i,ph:l,mTop:d,mLeft:p,mRight:m,footerH:c,headerH:g,contentW:u,contentH:f,docCSS:v,fontFamily:y,accentColor:C,pageBackground:H,isRTL:S}=t,n=this.plugin.settings;this.previewEl.empty();let r=new Map;a.forEach((b,B)=>{for(let L of b.pageNodes)L.querySelectorAll("[id]").forEach($=>{r.has($.id)||r.set($.id,B)}),L.id&&!r.has(L.id)&&r.set(L.id,B)});let h=[],k=`
:host {
display: block;
width: ${i}px;
height: ${l}px;
background: ${H};
box-shadow: 0 2px 8px rgba(0,0,0,.30), 0 8px 32px rgba(0,0,0,.25);
overflow: hidden;
position: relative;
box-sizing: border-box;
}
*, *::before, *::after { box-sizing: border-box; }
.mpdf-hf-center { flex: 1; text-align: center; }
.mpdf-hf-right { margin-left: auto; }
${v}
`,T=new CSSStyleSheet;T.replaceSync(k);for(let b of a){let B=Math.round(i*e),L=Math.round(l*e),$=this.previewEl.createEl("div",{cls:"mpdf-page-wrap"});$.setCssStyles({width:`${B}px`,height:`${L}px`}),$.createEl("div",{cls:"mpdf-page-label",text:`Page ${b.pageNum} of ${b.totalPages}`}),h.push($);let x=$.createEl("div",{cls:"mpdf-page-scale"});x.setCssStyles({width:`${B}px`,height:`${L}px`});let F=activeDocument.createElement("div");F.addClass("mpdf-shadow-host"),F.setCssStyles({width:`${i}px`,height:`${l}px`,transform:`scale(${e})`}),x.appendChild(F);let E=F.attachShadow({mode:"open"});if(E.adoptedStyleSheets=[T],n.backgroundImageEnabled&&n.backgroundImagePath){let w=O(this.app,n.backgroundImagePath);if(w){let D=n.backgroundImageScope==="content-only",z=activeDocument.createElement("div");z.setCssStyles({position:"absolute",...D?{top:`${d+g}px`,left:`${p}px`,width:`${u}px`,height:`${f}px`}:{inset:"0"},backgroundImage:`url('${w}')`,backgroundRepeat:n.backgroundImageSize==="tile"?"repeat":"no-repeat",backgroundSize:n.backgroundImageSize==="cover"?"cover":n.backgroundImageSize==="contain"?"contain":n.backgroundImageSize==="fill"?"100% 100%":"auto",backgroundPosition:"center",opacity:String(n.backgroundImageOpacity),pointerEvents:"none"}),E.appendChild(z)}}let M=n.showHeaderOnFirstPage||b.pageNum>1,A=n.showFooterOnFirstPage||b.pageNum>1;if(M&&n.showHeader&&n.headerImagePath){let w=O(this.app,n.headerImagePath);if(w){let D=activeDocument.createElement("div");D.setCssStyles({position:"absolute",top:`${d*.4}px`,left:`${n.headerImageMargin}px`,right:`${n.headerImageMargin}px`,height:`${g}px`,backgroundImage:`url('${w}')`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",pointerEvents:"none"}),E.appendChild(D)}}if(n.showHeader&&M&&(b.headerLeft||b.headerCenter||b.headerRight||n.showHeaderBorder)){let w=activeDocument.createElement("div");w.setCssStyles({position:"absolute",top:`${d*.4}px`,left:`${p}px`,right:`${m}px`,height:`${g}px`,display:"flex",alignItems:"center",fontSize:`${n.headerFontSize}px`,color:n.headerFontColor,fontFamily:y,whiteSpace:"nowrap",...n.showHeaderBorder?{borderBottom:`0.5px solid ${C}33`}:{}}),re(w,b.headerCenter,b.headerLeft,b.headerRight),E.appendChild(w)}let P=activeDocument.createElement("div");P.className="mpdf-doc",S&&P.setAttribute("dir","rtl"),P.setCssStyles({position:"absolute",top:`${d+g}px`,left:`${p}px`,width:`${u}px`});for(let w of b.pageNodes)P.appendChild(w.cloneNode(!0));if(E.appendChild(P),P.querySelectorAll("a[href^='#']").forEach(w=>{let D=decodeURIComponent(w.getAttribute("href").slice(1)),z=r.get(D);z!==void 0&&(w.title=`Go to page ${z+1}`,w.addEventListener("click",j=>{j.preventDefault(),h[z]?.scrollIntoView({behavior:"smooth",block:"start"})}))}),A&&n.showFooter&&n.footerImagePath){let w=O(this.app,n.footerImagePath);if(w){let D=activeDocument.createElement("div");D.setCssStyles({position:"absolute",bottom:"0",left:`${n.footerImageMargin}px`,right:`${n.footerImageMargin}px`,height:`${c}px`,backgroundImage:`url('${w}')`,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",pointerEvents:"none"}),E.appendChild(D)}}if(n.showFooter&&A&&(b.footerLeft||b.footerRight||b.footerCenter||n.showFooterBorder)){let w=activeDocument.createElement("div");w.setCssStyles({position:"absolute",bottom:"0",left:"0",right:"0",height:`${c}px`,display:"flex",alignItems:"center",...n.showFooterBorder?{borderTop:`0.5px solid ${C}33`}:{},padding:`0 ${m}px 0 ${p}px`,fontSize:`${n.footerFontSize}px`,color:n.footerFontColor,fontFamily:y}),re(w,b.footerCenter,b.footerLeft,b.footerRight),E.appendChild(w)}let N=Xe(n);N&&E.appendChild(N)}}async exportPDF(){let t=this.plugin.settings;this.exportBtn.disabled=!0,this.exportBtn.textContent="\u2B07 Exporting\u2026";let e=()=>{this.exportBtn.disabled=!1,this.exportBtn.textContent="\u2B07 Export PDF"};if(!this.layoutCache){this.renderDebounceTimer!==null&&(window.clearTimeout(this.renderDebounceTimer),this.renderDebounceTimer=null);let x=++this.renderToken;this.showLoading();try{await this.doRender(x)}catch(F){let E=F instanceof Error?F.message:String(F);new s.Notice("Render error: "+E),this.hideLoading(),e();return}}let a=this.layoutCache;if(!a||a.layouts.length===0){new s.Notice("Nothing to export."),e();return}let{layouts:i,pw:l,ph:d,mTop:p,mLeft:m,mRight:c,footerH:g,headerH:u,contentW:f,contentH:v,docCSS:y,fontFamily:C,accentColor:H,pageBackground:S,isRTL:n}=a,r=Ye(t),h=t.showHeader&&t.headerImagePath?O(this.app,t.headerImagePath):"",k=t.showFooter&&t.footerImagePath?O(this.app,t.footerImagePath):"",T=t.backgroundImageEnabled&&t.backgroundImagePath?O(this.app,t.backgroundImagePath):"",b=T?(()=>{let x=t.backgroundImageSize==="cover"?"cover":t.backgroundImageSize==="contain"?"contain":t.backgroundImageSize==="fill"?"100% 100%":"auto",F=t.backgroundImageSize==="tile"?"repeat":"no-repeat",E=t.backgroundImageScope==="content-only"?`top:${p+u}px;left:${m}px;width:${f}px;height:${v}px;`:"inset:0;",M=`background-image:url('${T}');background-size:${x};background-repeat:${F};background-position:center;opacity:${t.backgroundImageOpacity};pointer-events:none;`;return`<div style="position:absolute;${E}${M}"></div>`})():"",B=i.map(x=>{let F=x.pageNodes.map(le=>{let ee=le.cloneNode(!0);return ee.querySelectorAll("style, script").forEach(te=>{te.closest("svg")||te.remove()}),ee.outerHTML}).join(`
`),E=t.showHeaderOnFirstPage||x.pageNum>1,M=t.showFooterOnFirstPage||x.pageNum>1,A=t.showHeader&&E&&(x.headerLeft||x.headerCenter||x.headerRight||t.showHeaderBorder),I=t.showHeaderBorder?`border-bottom:0.5px solid ${H}33;`:"",P=A?`<div style="position:absolute;top:${p*.4}px;left:${m}px;right:${c}px;display:flex;align-items:center;font-size:${t.headerFontSize}px;color:${t.headerFontColor};font-family:${C};white-space:nowrap;${I}">${ae(x.headerCenter,x.headerLeft,x.headerRight)}</div>`:"",R=t.showFooter&&M&&(x.footerLeft||x.footerRight||x.footerCenter||t.showFooterBorder),N=t.showFooterBorder?`border-top:0.5px solid ${H}33;`:"",w=R?`<div style="position:absolute;bottom:0;left:0;right:0;height:${g}px;display:flex;align-items:center;${N}padding:0 ${c}px 0 ${m}px;font-size:${t.footerFontSize}px;color:${t.footerFontColor};font-family:${C};">${ae(x.footerCenter,x.footerLeft,x.footerRight)}</div>`:"",D=`<div class="mpdf-doc"${n?' dir="rtl"':""} style="position:absolute;top:${p+u}px;left:${m}px;width:${f}px;">${F}</div>`,z=E&&h?`<div style="position:absolute;top:${p*.4}px;left:${t.headerImageMargin}px;right:${t.headerImageMargin}px;height:${u}px;background-image:url('${h}');background-size:cover;background-position:center;background-repeat:no-repeat;pointer-events:none;"></div>`:"",j=M&&k?`<div style="position:absolute;bottom:0;left:${t.footerImageMargin}px;right:${t.footerImageMargin}px;height:${g}px;background-image:url('${k}');background-size:cover;background-position:center;background-repeat:no-repeat;pointer-events:none;"></div>`:"";return`<div class="mpdf-export-page">${b}${z}${P}${D}${j}${w}${r}</div>`}),L=`
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
@page { size: ${l}px ${d}px; margin: 0; }
html, body { margin: 0; padding: 0; background: ${S}; }
.mpdf-export-page {
position: relative;
width: ${l}px; height: ${d}px;
overflow: hidden;
background: ${S};
page-break-after: always; break-after: page;
}
.mpdf-export-page:last-child { page-break-after: avoid; break-after: avoid; }
${y}
`,$=`<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>${W(this.currentFile?.basename??"Export")}</title>
<style>${fe(L)}</style>
</head>
<body>
${B.join(`
`)}
</body>
</html>`;try{let x=window,F=x.require("@electron/remote");if(!F?.dialog)throw new Error("no remote");let E=await F.dialog.showSaveDialog({title:"Save PDF",defaultPath:(this.currentFile?.basename??"export")+".pdf",filters:[{name:"PDF",extensions:["pdf"]}]});if(E.canceled||!E.filePath){e();return}new s.Notice("Generating PDF\u2026");let M=new Blob([$],{type:"text/html"}),A=URL.createObjectURL(M),I=new F.BrowserWindow({show:!1,webPreferences:{nodeIntegration:!1}});I.loadURL(A);let P=!1,R=()=>{URL.revokeObjectURL(A),I.close(),e()};I.webContents.once("did-fail-load",(N,w,D)=>{P||(P=!0,new s.Notice("PDF load error: "+D),R())}),I.webContents.once("did-finish-load",()=>{if(P)return;P=!0;let N=t.pageSize==="Custom";I.webContents.printToPDF({pageSize:N?"A4":t.pageSize,landscape:!N&&t.orientation==="landscape",preferCSSPageSize:N,printBackground:!0,margins:{marginType:"none"}}).then(w=>{x.require("fs").writeFile(E.filePath,w,D=>{D?new s.Notice("Error saving PDF: "+D.message):new s.Notice("\u2713 PDF saved: "+E.filePath),R()})}).catch(w=>{new s.Notice("PDF render error: "+w.message),R()})})}catch{new s.Notice("Advanced PDF export requires the Obsidian desktop app."),e()}}},Q=class extends s.PluginSettingTab{plugin;dirty=!1;constructor(t,e){super(t,e),this.plugin=e}display(){this.dirty=!1,this.buildSettings()}hide(){this.dirty&&(this.dirty=!1,this.plugin.activeModal?.render(!0))}async markDirty(){this.dirty=!0,await this.plugin.saveSettings()}buildSettings(){let{containerEl:t}=this;t.empty();let e=this.plugin.settings,a=(n,r,h,k)=>{let T=new s.Setting(t).setName(n);return k&&T.setDesc(k),T.addText(b=>b.setValue(String(e[r])).onChange(B=>{let L=parseInt(B,10)||0;e[r]=h!==void 0?Math.max(h,L):L,this.markDirty()}))},i=(n,r)=>new s.Setting(t).setName(n).addColorPicker(h=>h.setValue(e[r]).onChange(k=>{e[r]=k,this.markDirty()}));new s.Setting(t).setName("Style Preset").setHeading(),new s.Setting(t).setName("Preset").setDesc("Pick a preset to configure the overall document style. Fine-tune any setting below.").addDropdown(n=>{Object.entries(U).forEach(([r,h])=>{n.addOption(r,h.name)}),n.setValue(e.preset).onChange(r=>{this.plugin.applyPreset(r),this.markDirty().then(()=>{this.buildSettings()})})}).addButton(n=>n.setButtonText("Reset Preset").setTooltip("Reset current preset to its default values").onClick(()=>{this.plugin.applyPreset(e.preset,!0),this.markDirty().then(()=>{this.buildSettings()})})),new s.Setting(t).setName("Page").setHeading();let l;new s.Setting(t).setName("Page size").addDropdown(n=>{Object.keys(_).forEach(r=>{n.addOption(r,r)}),n.addOption("Custom","Custom\u2026"),n.setValue(e.pageSize).onChange(r=>{e.pageSize=r,l.settingEl.toggleClass("mpdf-is-hidden",r!=="Custom"),this.markDirty()})}),l=new s.Setting(t).setName("Custom page size (mm)").setDesc("Width \xD7 Height in millimetres.").addText(n=>n.setPlaceholder("Width").setValue(String(e.customPageWidth)).onChange(r=>{e.customPageWidth=Math.max(1,parseFloat(r)||210),this.markDirty()})).addText(n=>n.setPlaceholder("Height").setValue(String(e.customPageHeight)).onChange(r=>{e.customPageHeight=Math.max(1,parseFloat(r)||297),this.markDirty()})),l.settingEl.toggleClass("mpdf-is-hidden",e.pageSize!=="Custom"),new s.Setting(t).setName("Orientation").addDropdown(n=>n.addOptions({portrait:"Portrait",landscape:"Landscape"}).setValue(e.orientation).onChange(r=>{e.orientation=r,this.markDirty()})),new s.Setting(t).setName("Margin & Frame").setHeading(),new s.Setting(t).setName("Margins").setDesc("Top \xB7 Bottom \xB7 Left \xB7 Right").addText(n=>n.setPlaceholder("Top").setValue(String(e.marginTop)).onChange(r=>{e.marginTop=parseInt(r,10)||0,this.markDirty()})).addText(n=>n.setPlaceholder("Bottom").setValue(String(e.marginBottom)).onChange(r=>{e.marginBottom=parseInt(r,10)||0,this.markDirty()})).addText(n=>n.setPlaceholder("Left").setValue(String(e.marginLeft)).onChange(r=>{e.marginLeft=parseInt(r,10)||0,this.markDirty()})).addText(n=>n.setPlaceholder("Right").setValue(String(e.marginRight)).onChange(r=>{e.marginRight=parseInt(r,10)||0,this.markDirty()}));let d,p,m,c,g=n=>{[d,p,m,c].forEach(r=>r.settingEl.toggleClass("mpdf-is-hidden",!n))};new s.Setting(t).setName("Enable frame").setDesc("Draws a border around the outer edge of every page.").addToggle(n=>n.setValue(e.frameEnabled).onChange(r=>{e.frameEnabled=r,g(r),this.markDirty()})),d=i("Frame color","frameColor"),p=a("Frame thickness (px)","frameThickness",1),m=a("Frame margin (px)","frameMargin",0,"Gap between the page edge and the frame, applied equally on all four sides."),c=new s.Setting(t).setName("Frame style").addDropdown(n=>n.addOptions({solid:"Solid",dashed:"Dashed",dotted:"Dotted",double:"Double",groove:"Groove",ridge:"Ridge"}).setValue(e.frameStyle).onChange(r=>{e.frameStyle=r,this.markDirty()})),g(e.frameEnabled),new s.Setting(t).setName("Typography").setHeading();let u;new s.Setting(t).setName("Font family").addDropdown(n=>n.addOptions({"Georgia, serif":"Georgia (Serif)","'Times New Roman', Times, serif":"Times New Roman","'Palatino Linotype', Palatino, serif":"Palatino","Arial, sans-serif":"Arial","'Helvetica Neue', Helvetica, sans-serif":"Helvetica","'Trebuchet MS', sans-serif":"Trebuchet","'Courier New', monospace":"Courier New",__custom__:"Custom\u2026"}).setValue(e.fontFamily).onChange(r=>{e.fontFamily=r,u.settingEl.toggleClass("mpdf-is-hidden",r!=="__custom__"),this.markDirty()})),u=new s.Setting(t).setName("Custom font name").setDesc('CSS font-family value \u2014 e.g. "Inter, sans-serif". The font must be installed on your system.').addText(n=>n.setPlaceholder("e.g. Inter, sans-serif").setValue(e.customFontName).onChange(r=>{e.customFontName=r,this.markDirty()})),u.settingEl.toggleClass("mpdf-is-hidden",e.fontFamily!=="__custom__"),new s.Setting(t).setName("Font size (px)").addDropdown(n=>{["10","11","12","13","14","15","16"].forEach(r=>{n.addOption(r,r+"px")}),n.setValue(String(e.fontSize)).onChange(r=>{e.fontSize=parseInt(r),this.markDirty()})}),new s.Setting(t).setName("Code font size").addDropdown(n=>n.addOptions({"0.75":"0.75em","0.80":"0.80em","0.82":"0.82em","0.85":"0.85em","0.88":"0.88em","0.90":"0.90em","1.0":"1.00em"}).setValue(String(e.codeFontSize)).onChange(r=>{e.codeFontSize=parseFloat(r),this.markDirty()})),new s.Setting(t).setName("Line height").addDropdown(n=>n.addOptions({"1.4":"Tight (1.4)","1.6":"Compact (1.6)","1.75":"Normal (1.75)","1.85":"Relaxed (1.85)","2.0":"Double (2.0)"}).setValue(String(e.lineHeight)).onChange(r=>{e.lineHeight=parseFloat(r),this.markDirty()})),new s.Setting(t).setName("Paragraph spacing").addDropdown(n=>n.addOptions({0:"None","0.3":"Tight (0.3em)","0.5":"Normal (0.5em)","0.65":"Relaxed (0.65em)","1.0":"Wide (1em)"}).setValue(String(e.paragraphSpacing)).onChange(r=>{e.paragraphSpacing=parseFloat(r),this.markDirty()})),new s.Setting(t).setName("Heading scale").setDesc("Multiplier applied to all heading sizes.").addDropdown(n=>n.addOptions({"0.8":"Small (0.8\xD7)","0.88":"0.88\xD7","0.9":"Compact (0.9\xD7)","0.95":"0.95\xD7","1.0":"Normal (1.0\xD7)","1.05":"1.05\xD7","1.1":"Large (1.1\xD7)","1.2":"XLarge (1.2\xD7)"}).setValue(String(e.headingScale)).onChange(r=>{e.headingScale=parseFloat(r),this.markDirty()})),new s.Setting(t).setName("Background").setHeading();let f,v,y,C,H,S=n=>{f.settingEl.toggleClass("mpdf-is-hidden",n),[v,y,C,H].forEach(r=>r.settingEl.toggleClass("mpdf-is-hidden",!n))};new s.Setting(t).setName("Use image background").setDesc("When on, a background image is used instead of the solid background color.").addToggle(n=>n.setValue(e.backgroundImageEnabled).onChange(r=>{e.backgroundImageEnabled=r,S(r),this.markDirty()})),f=new s.Setting(t).setName("Page background color").addColorPicker(n=>n.setValue(e.pageBackground).onChange(r=>{e.pageBackground=r,this.markDirty()})),v=new s.Setting(t).setName("Background image").setDesc("Vault-relative path or https:// URL.").addText(n=>n.setPlaceholder("assets/background.png").setValue(e.backgroundImagePath).onChange(r=>{e.backgroundImagePath=r,this.markDirty()})),y=new s.Setting(t).setName("Fit").addDropdown(n=>n.addOptions({cover:"Cover (fill, crop edges)",contain:"Contain (fit, show gaps)",fill:"Fill (stretch to exact size)",tile:"Tile (repeat)"}).setValue(e.backgroundImageSize).onChange(r=>{e.backgroundImageSize=r,this.markDirty()})),C=new s.Setting(t).setName("Scope").setDesc("Full page includes header and footer bands. Content area only restricts the background to the text zone between them.").addDropdown(n=>n.addOptions({"full-page":"Full page","content-only":"Content area only"}).setValue(e.backgroundImageScope).onChange(r=>{e.backgroundImageScope=r,this.markDirty()})),H=new s.Setting(t).setName("Opacity").addDropdown(n=>n.addOptions({"0.05":"5%","0.1":"10%","0.15":"15%","0.2":"20%","0.3":"30%","0.4":"40%","0.5":"50%","0.6":"60%","0.7":"70%","0.8":"80%","0.9":"90%",1:"100%"}).setValue(String(e.backgroundImageOpacity)).onChange(r=>{e.backgroundImageOpacity=parseFloat(r),this.markDirty()})),S(e.backgroundImageEnabled),new s.Setting(t).setName("Colors").setHeading(),i("Accent color","accentColor"),i("Body text color","bodyColor"),i("Heading color","headingColor"),i("Blockquote background","blockquoteBg"),i("Blockquote border","blockquoteBorderColor"),i("Table header background","tableHeaderBg"),i("Code background","codeBackground"),new s.Setting(t).setName("Code syntax theme").setDesc('Independent of your Obsidian theme. "None" uses the body text color and code background above with no highlighting.').addDropdown(n=>{let r={};for(let[h,k]of Object.entries(Z))r[h]=k.name;n.addOptions(r).setValue(e.codeTheme).onChange(h=>{e.codeTheme=h,this.markDirty()})}),new s.Setting(t).setName("Header").setHeading(),new s.Setting(t).setName("Show header").addToggle(n=>n.setValue(e.showHeader).onChange(r=>{e.showHeader=r,this.markDirty()})),new s.Setting(t).setName("Show on first page").setDesc("When off, the header is hidden on page 1. Useful for title pages.").addToggle(n=>n.setValue(e.showHeaderOnFirstPage).onChange(r=>{e.showHeaderOnFirstPage=r,this.markDirty()})),new s.Setting(t).setName("Header text").addText(n=>n.setValue(e.headerText).onChange(r=>{e.headerText=r,this.markDirty()})),new s.Setting(t).setName("Alignment").addDropdown(n=>n.addOptions({left:"Left",center:"Center",right:"Right"}).setValue(e.headerAlignment).onChange(r=>{e.headerAlignment=r,this.markDirty()})),a("Font size (px)","headerFontSize",1),a("Height (px)","headerHeight",0,"Explicit band height (0 = auto)."),i("Font color","headerFontColor"),new s.Setting(t).setName("Border").setDesc("Separator line below the header.").addToggle(n=>n.setValue(e.showHeaderBorder).onChange(r=>{e.showHeaderBorder=r,this.markDirty()})),new s.Setting(t).setName("Image").setDesc("Vault-relative path or https:// URL. Fills the header band as a background banner.").addText(n=>n.setPlaceholder("assets/header-banner.png").setValue(e.headerImagePath).onChange(r=>{e.headerImagePath=r,this.markDirty()})),a("Image left/right margin (px)","headerImageMargin",0,"Insets the banner from the left and right page edges."),new s.Setting(t).setName("Footer").setHeading(),new s.Setting(t).setName("Show footer").addToggle(n=>n.setValue(e.showFooter).onChange(r=>{e.showFooter=r,this.markDirty()})),new s.Setting(t).setName("Show on first page").setDesc("When off, the footer and page numbers are hidden on page 1. Page numbering starts from page 2.").addToggle(n=>n.setValue(e.showFooterOnFirstPage).onChange(r=>{e.showFooterOnFirstPage=r,this.markDirty()})),new s.Setting(t).setName("Footer text").addText(n=>n.setValue(e.footerText).onChange(r=>{e.footerText=r,this.markDirty()})),new s.Setting(t).setName("Alignment").addDropdown(n=>n.addOptions({left:"Left",center:"Center",right:"Right"}).setValue(e.footerTextAlignment).onChange(r=>{e.footerTextAlignment=r,this.markDirty()})),a("Font size (px)","footerFontSize",1),a("Height (px)","footerHeight",0,"Explicit band height (0 = auto)."),i("Font color","footerFontColor"),new s.Setting(t).setName("Border").setDesc("Separator line above the footer.").addToggle(n=>n.setValue(e.showFooterBorder).onChange(r=>{e.showFooterBorder=r,this.markDirty()})),new s.Setting(t).setName("Image").setDesc("Vault-relative path or https:// URL. Fills the footer band as a background banner.").addText(n=>n.setPlaceholder("assets/footer-banner.png").setValue(e.footerImagePath).onChange(r=>{e.footerImagePath=r,this.markDirty()})),a("Image left/right margin (px)","footerImageMargin",0,"Insets the banner from the left and right page edges."),new s.Setting(t).setName("Show page numbers").addToggle(n=>n.setValue(e.showPageNumbers).onChange(r=>{e.showPageNumbers=r,this.markDirty()})),new s.Setting(t).setName("Page number position").addDropdown(n=>n.addOptions({left:"Left",center:"Center",right:"Right"}).setValue(e.pageNumberPosition).onChange(r=>{e.pageNumberPosition=r,this.markDirty()})),new s.Setting(t).setName("Page number start").setDesc("Number assigned to the first visible page number.").addText(n=>n.setValue(String(e.pageNumberStart)).onChange(r=>{e.pageNumberStart=parseInt(r,10)||1,this.markDirty()})),new s.Setting(t).setName("Behaviour").setHeading(),new s.Setting(t).setName("Hide frontmatter").setDesc("Strip the YAML frontmatter block (--- \u2026 ---) from the preview and exported PDF.").addToggle(n=>n.setValue(e.hideFrontmatter).onChange(r=>{e.hideFrontmatter=r,this.markDirty()})),new s.Setting(t).setName("Include file name as title").setDesc("Prepend the note's file name as an H1 heading at the top of the PDF.").addToggle(n=>n.setValue(e.includeFilenameAsTitle).onChange(r=>{e.includeFilenameAsTitle=r,this.markDirty()})),new s.Setting(t).setName("Underline links").setDesc("Applies to both internal and external links.").addToggle(n=>n.setValue(e.linkUnderline).onChange(r=>{e.linkUnderline=r,this.markDirty()})),new s.Setting(t).setName("Auto page break before H1").addToggle(n=>n.setValue(e.autoBreakH1).onChange(r=>{e.autoBreakH1=r,this.markDirty()})),new s.Setting(t).setName("Auto page break before H2").addToggle(n=>n.setValue(e.autoBreakH2).onChange(r=>{e.autoBreakH2=r,this.markDirty()})),new s.Setting(t).setName("H1 bottom border").addToggle(n=>n.setValue(e.h1BorderBottom).onChange(r=>{e.h1BorderBottom=r,this.markDirty()})),new s.Setting(t).setName("H2 bottom border").addToggle(n=>n.setValue(e.h2BorderBottom).onChange(r=>{e.h2BorderBottom=r,this.markDirty()})),new s.Setting(t).setName("Center H1").addToggle(n=>n.setValue(e.centerH1).onChange(r=>{e.centerH1=r,this.markDirty()})),new s.Setting(t).setName("Striped table rows").addToggle(n=>n.setValue(e.tableStriped).onChange(r=>{e.tableStriped=r,this.markDirty()}))}};