{"version":3,"file":"pdf.cjs","names":["ARABIC_FORMS","Map","LAM_ALEF","LAM","MIRRORED","ZWNJ","ZWJ","isMark","code","isRtlLetter","isArabicIndicDigit","hasRtlText","text","ch","codePointAt","LETTER_OR_DIGIT","bidiClassOf","test","String","fromCodePoint","joiningOf","forms","get","length","toClusters","clusters","last","at","marks","push","base","cls","join","drawn","level","joinsForward","cluster","joinsBackward","shapeOne","before","after","hasGlyph","linkBefore","linkAfter","form","applyLamAlef","out","i","lam","alef","ligature","undefined","shapeArabic","folded","map","index","isolated","final","useFinal","levelFor","strongSideOf","assignLevels","sides","entries","paragraph","resolved","reorder","max","reduce","high","Math","start","inRun","run","slice","reverse","splice","toDrawingOrder","options","rtl","ordered","mirrored","mark","KEPT_TABLES","ARG_1_AND_2_ARE_WORDS","WE_HAVE_A_SCALE","MORE_COMPONENTS","WE_HAVE_AN_X_AND_Y_SCALE","WE_HAVE_A_TWO_BY_TWO","bytesOf","source","Uint8Array","viewOf","bytes","DataView","buffer","byteOffset","byteLength","tagAt","at","String","fromCodePoint","readTables","view","count","getUint16","tables","Map","i","set","offset","getUint32","length","readNameText","platform","step","name","code","getUint8","readPostScriptName","table","base","stringsAt","cmap4Glyph","segment","rangeOffset","delta","rangeAt","start","raw","readCmap4","into","segCount","endsAt","startsAt","deltasAt","rangesAt","seg","end","getInt16","glyph","readCmap12","groups","g","last","Math","min","readCmap","map","best","bestScore","encoding","score","format","readMetrics","hmtx","numberOfHMetrics","numGlyphs","advances","lsbs","Array","fill","shortAt","long","push","bearingAt","requiredTable","tag","get","Error","parseSfnt","version","isTrueType","has","head","hhea","maxp","os2","post","unitsPerEm","metrics","cmap","familyClass","postScriptName","ascent","descent","capHeight","round","italicAngle","getInt32","bbox","isFixedPitch","isSerif","glyphFor","codePoint","advanceOf","bearingOf","longLoca","glyphRange","font","index","loca","glyf","read","componentsOf","out","cursor","flags","withComponents","used","order","seen","Set","part","add","renumberComposite","data","newIndexOf","original","setUint16","buildGlyf","full","pieces","offsets","total","slice","piece","locaView","forEach","setUint32","buildHmtx","setInt16","copyTable","undefined","patchedHead","patchedHhea","glyphCount","patchedMaxp","checksum","sum","words","floor","tail","padded","subsetSfnt","built","copy","tags","filter","entrySelector","searchRange","header","headerView","body","codePointAt","block","headTable","indexOf","headAt","toDrawingOrder","subsetSfnt","WIN1252","Map","hex4","value","toString","toUpperCase","padStart","winAnsiByte","code","get","helveticaWidth","byte","undefined","octalByte","pdfLiteral","text","out","ch","codePointAt","String","raw","fromCodePoint","standardFace","embedded","measure","size","units","order","operand","fontRef","bold","boldRun","open","close","fontResources","extraObjects","FALLBACK","subsetTag","name","glyphs","hash","seed","join","i","length","Math","imul","tag","floor","toUnicodeCmap","entries","chunks","at","block","slice","lines","map","glyph","push","streamBody","head","bytes","prefix","TextEncoder","encode","suffix","Uint8Array","byteLength","set","descriptorFlags","font","SYMBOLIC","flags","isFixedPitch","isSerif","italicAngle","embeddedFace","scale","unitsPerEm","indexOf","unicodeOf","substitute","glyphFor","assign","existing","next","widthOf","advanceOf","rtl","hasGlyph","hex","firstId","subset","postScriptName","baseFont","descendantId","descriptorId","fileId","unicodeId","widths","round","bbox","cmap","ascent","descent","capHeight","isBrowser","buildExportTable","resolvePrintDirection","direction","document","documentElement","getAttribute","isDateOnly","date","getUTCHours","getUTCMinutes","getUTCSeconds","getUTCMilliseconds","getHours","getMinutes","getSeconds","getMilliseconds","safeText","text","out","ch","exportCellText","value","Number","isFinite","String","Date","isNaN","getTime","toISOString","slice","replace","html","replaceAll","pageSizeCss","size","colPercents","table","count","headers","length","weights","map","_","index","stated","widths","undefined","sum","reduce","total","weight","colGroup","percents","cols","percent","width","Math","round","toString","join","firstCellTag","role","column","tag","scope","cellHtml","level","indent","dataRow","row","meta","rowMeta","cells","flushGroup","chunks","rows","open","push","tableBodies","forEach","rowLevel","headerRow","fontDataUrl","font","bytes","Uint8Array","CHUNK","binary","at","byteLength","fromCodePoint","subarray","btoa","printStyles","options","paper","pageSize","face","family","groupBreak","pageBreak","buildPrintTableHtml","captionText","caption","title","breakClass","buildPrintDocument","lang","openPrintLayout","iframe","createElement","setAttribute","style","position","insetInlineEnd","insetBlockEnd","height","border","cleanup","remove","addEventListener","frameWindow","contentWindow","focus","print","srcdoc","body","appendChild","printTable","columns","view","summary","buildExportTable","embeddedFace","hex4","pdfLiteral","standardFace","exportCellText","resolvePrintDirection","parseSfnt","MARGIN","FONT_SIZE","ROW_H","HEADER_H","TITLE_H","FOOTER","CELL_PAD","INDENT","HEADER_FILL","GROUP_FILL","pageBox","size","width","height","num","value","String","Math","round","ascii","text","TextEncoder","encode","concatBytes","chunks","total","chunk","byteLength","out","Uint8Array","at","set","utf16BeHex","hex","ch","code","codePointAt","u","drawnWidth","fontSize","ctx","face","measure","order","rtl","fitText","maxPt","ellipsis","end","length","slice","contentTop","box","titled","columnWidths","table","usable","count","headers","weights","map","_","index","stated","widths","undefined","sum","reduce","weight","columnXs","left","x","paginate","rowCount","roles","pageBreak","pages","current","y","bottom","role","level","force","overflow","orphan","push","fillRow","rgb","colXs","min","colWidths","col","cellBox","w","h","cellText","indent","bold","max","shown","ordered","drawn","tx","ty","boldRun","fontRef","open","operand","close","drawCells","values","style","parts","fill","i","join","drawTitle","title","drawFooter","page","pageCount","label","drawHeaderRow","drawBodyRow","meta","rowMeta","chrome","rows","pageStream","rowIndices","extras","Boolean","xrefLine","offset","gen","inUse","off","padStart","g","flag","streamObject","body","bytes","pageObject","contentId","fontResources","infoTitle","embedded","compilePdf","streams","kids","pageBodies","firstFontId","forEach","stream","pageId","extraObjects","objects","header","offsets","xref","trailer","makeContext","faceFor","font","pdfBytes","options","pageSize","direction","titleFromFilename","filename","stem","replace","buildTablePdf","columns","view","summary","PDF_MIME","pdfWriter","extension","build","mimeType"],"sources":["../src/export/arabicText.ts","../src/export/sfnt.ts","../src/export/pdfFont.ts","../src/export/printLayout.ts","../src/export/pdf.ts"],"sourcesContent":["/**\n * Arabic letter forms and bidirectional order, for a writer that has no\n * text engine underneath it.\n *\n * A browser is given `مرحبا` and does two things before a pixel is drawn:\n * it picks a different shape for each letter depending on its neighbours,\n * and it lays the letters out right to left. A PDF content stream does\n * neither. It draws the glyphs it is handed, left to right, in the order\n * they arrive — so the file has to arrive already shaped and already\n * reversed, or the word comes out as disconnected letters running the\n * wrong way.\n *\n * Two dependency-free pieces do that here.\n *\n * **Forms** come from the Unicode presentation-forms blocks. Every Arabic\n * letter has up to four shapes — isolated, final, initial, medial — and\n * they exist as their own code points precisely because systems without a\n * shaping engine needed somewhere to put them. Choosing between them is a\n * look at the two neighbours: whether the letter before can join forward\n * and the letter after can join back. Marks are transparent to that\n * question, which is why they travel attached to their base here rather\n * than as characters of their own.\n *\n * **Order** is the Unicode bidirectional algorithm's reordering rule, and\n * only that rule. Characters get a level — right-to-left runs one above\n * left-to-right, numbers one above the run they sit in — neutral\n * characters take the direction they are surrounded by, and then each run\n * is reversed from the deepest level outward. That is enough for a table\n * cell: an Arabic sentence, a Latin product name inside it, a date, a\n * price. It is not a full implementation — no explicit embedding controls,\n * no isolates — and it does not try to be.\n *\n * What is deliberately absent is OpenType shaping. Real Arabic\n * typography wants GSUB: contextual alternates, stacked ligatures, the\n * mark positioning a font's own tables describe. That is a shaping engine,\n * and importing one to print a table is the wrong trade. The presentation\n * forms give correct, readable, connected Arabic; a font whose design\n * needs GSUB to look right will look plain here, not wrong.\n *\n * The logical string is never lost. It travels in `/ActualText` and in\n * the font's `/ToUnicode` map, so copy-paste and a screen reader read the\n * sentence the way it was written, whatever order it was drawn in.\n */\n\n/**\n * Letter shapes, keyed by the letter.\n *\n * The entry's length is also its joining class, because the two are the\n * same fact: a letter with only an isolated form joins nothing, one with\n * a final form joins to the right, and one with all four joins on both\n * sides.\n */\ntype FormSet =\n  | readonly [isolated: number]\n  | readonly [isolated: number, final: number]\n  | readonly [isolated: number, final: number, initial: number, medial: number];\n\nconst ARABIC_FORMS = new Map<number, FormSet>([\n  [0x0621, [0xfe80]], // hamza\n  [0x0622, [0xfe81, 0xfe82]], // alef with madda\n  [0x0623, [0xfe83, 0xfe84]], // alef with hamza above\n  [0x0624, [0xfe85, 0xfe86]], // waw with hamza\n  [0x0625, [0xfe87, 0xfe88]], // alef with hamza below\n  [0x0626, [0xfe89, 0xfe8a, 0xfe8b, 0xfe8c]], // yeh with hamza\n  [0x0627, [0xfe8d, 0xfe8e]], // alef\n  [0x0628, [0xfe8f, 0xfe90, 0xfe91, 0xfe92]], // beh\n  [0x0629, [0xfe93, 0xfe94]], // teh marbuta\n  [0x062a, [0xfe95, 0xfe96, 0xfe97, 0xfe98]], // teh\n  [0x062b, [0xfe99, 0xfe9a, 0xfe9b, 0xfe9c]], // theh\n  [0x062c, [0xfe9d, 0xfe9e, 0xfe9f, 0xfea0]], // jeem\n  [0x062d, [0xfea1, 0xfea2, 0xfea3, 0xfea4]], // hah\n  [0x062e, [0xfea5, 0xfea6, 0xfea7, 0xfea8]], // khah\n  [0x062f, [0xfea9, 0xfeaa]], // dal\n  [0x0630, [0xfeab, 0xfeac]], // thal\n  [0x0631, [0xfead, 0xfeae]], // reh\n  [0x0632, [0xfeaf, 0xfeb0]], // zain\n  [0x0633, [0xfeb1, 0xfeb2, 0xfeb3, 0xfeb4]], // seen\n  [0x0634, [0xfeb5, 0xfeb6, 0xfeb7, 0xfeb8]], // sheen\n  [0x0635, [0xfeb9, 0xfeba, 0xfebb, 0xfebc]], // sad\n  [0x0636, [0xfebd, 0xfebe, 0xfebf, 0xfec0]], // dad\n  [0x0637, [0xfec1, 0xfec2, 0xfec3, 0xfec4]], // tah\n  [0x0638, [0xfec5, 0xfec6, 0xfec7, 0xfec8]], // zah\n  [0x0639, [0xfec9, 0xfeca, 0xfecb, 0xfecc]], // ain\n  [0x063a, [0xfecd, 0xfece, 0xfecf, 0xfed0]], // ghain\n  [0x0640, [0x0640, 0x0640, 0x0640, 0x0640]], // tatweel joins, unchanged\n  [0x0641, [0xfed1, 0xfed2, 0xfed3, 0xfed4]], // feh\n  [0x0642, [0xfed5, 0xfed6, 0xfed7, 0xfed8]], // qaf\n  [0x0643, [0xfed9, 0xfeda, 0xfedb, 0xfedc]], // kaf\n  [0x0644, [0xfedd, 0xfede, 0xfedf, 0xfee0]], // lam\n  [0x0645, [0xfee1, 0xfee2, 0xfee3, 0xfee4]], // meem\n  [0x0646, [0xfee5, 0xfee6, 0xfee7, 0xfee8]], // noon\n  [0x0647, [0xfee9, 0xfeea, 0xfeeb, 0xfeec]], // heh\n  [0x0648, [0xfeed, 0xfeee]], // waw\n  [0x0649, [0xfeef, 0xfef0]], // alef maksura\n  [0x064a, [0xfef1, 0xfef2, 0xfef3, 0xfef4]], // yeh\n  // Persian, Urdu and Sindhi letters, from the FB50 block.\n  [0x0679, [0xfb66, 0xfb67, 0xfb68, 0xfb69]], // tteh\n  [0x067e, [0xfb56, 0xfb57, 0xfb58, 0xfb59]], // peh\n  [0x0686, [0xfb7a, 0xfb7b, 0xfb7c, 0xfb7d]], // tcheh\n  [0x0688, [0xfb88, 0xfb89]], // ddal\n  [0x0698, [0xfb8a, 0xfb8b]], // jeh\n  [0x06a9, [0xfb8e, 0xfb8f, 0xfb90, 0xfb91]], // keheh\n  [0x06af, [0xfb92, 0xfb93, 0xfb94, 0xfb95]], // gaf\n  [0x06ba, [0xfb9e, 0xfb9f]], // noon ghunna\n  [0x06be, [0xfbaa, 0xfbab, 0xfbac, 0xfbad]], // heh doachashmee\n  [0x06c1, [0xfba6, 0xfba7, 0xfba8, 0xfba9]], // heh goal\n  [0x06cc, [0xfbfc, 0xfbfd, 0xfbfe, 0xfbff]], // farsi yeh\n  [0x06d2, [0xfbae, 0xfbaf]], // yeh barree\n]);\n\n/**\n * Lam followed by an alef is written as one glyph, not two.\n *\n * This is the one ligature Arabic requires rather than prefers — a lam\n * and an alef side by side is simply not how the pair is written — so it\n * is the one ligature applied here.\n */\nconst LAM_ALEF = new Map<number, readonly [isolated: number, final: number]>([\n  [0x0622, [0xfef5, 0xfef6]],\n  [0x0623, [0xfef7, 0xfef8]],\n  [0x0625, [0xfef9, 0xfefa]],\n  [0x0627, [0xfefb, 0xfefc]],\n]);\n\nconst LAM = 0x0644;\n\n/** Bracket-like characters, which point the other way in an RTL run. */\nconst MIRRORED = new Map<number, number>([\n  [0x0028, 0x0029],\n  [0x0029, 0x0028],\n  [0x005b, 0x005d],\n  [0x005d, 0x005b],\n  [0x007b, 0x007d],\n  [0x007d, 0x007b],\n  [0x003c, 0x003e],\n  [0x003e, 0x003c],\n  [0x00ab, 0x00bb],\n  [0x00bb, 0x00ab],\n  [0x2039, 0x203a],\n  [0x203a, 0x2039],\n  [0x201c, 0x201d],\n  [0x201d, 0x201c],\n  [0x2018, 0x2019],\n  [0x2019, 0x2018],\n]);\n\nconst ZWNJ = 0x200c;\nconst ZWJ = 0x200d;\n\n/** A combining mark: it hangs off the letter before it and joins nothing. */\nfunction isMark(code: number): boolean {\n  return (\n    (code >= 0x0300 && code <= 0x036f) ||\n    (code >= 0x0610 && code <= 0x061a) ||\n    (code >= 0x064b && code <= 0x065f) ||\n    code === 0x0670 ||\n    (code >= 0x06d6 && code <= 0x06dc) ||\n    (code >= 0x06df && code <= 0x06e4) ||\n    (code >= 0x06e7 && code <= 0x06e8) ||\n    (code >= 0x06ea && code <= 0x06ed)\n  );\n}\n\n/** True for any script written right to left. */\nfunction isRtlLetter(code: number): boolean {\n  return (\n    (code >= 0x0590 && code <= 0x05ff) ||\n    (code >= 0x0600 && code <= 0x07bf) ||\n    (code >= 0x0860 && code <= 0x08ff) ||\n    (code >= 0xfb1d && code <= 0xfdff) ||\n    (code >= 0xfe70 && code <= 0xfeff)\n  );\n}\n\nfunction isArabicIndicDigit(code: number): boolean {\n  return (\n    (code >= 0x0660 && code <= 0x0669) ||\n    (code >= 0x06f0 && code <= 0x06f9) ||\n    code === 0x066b ||\n    code === 0x066c\n  );\n}\n\n/** True when the string holds anything this module needs to act on. */\nfunction hasRtlText(text: string): boolean {\n  for (const ch of text) {\n    if (isRtlLetter(ch.codePointAt(0) ?? 0)) return true;\n  }\n  return false;\n}\n\n/**\n * The bidirectional classes this reordering distinguishes.\n *\n * The algorithm names two dozen; these five are the ones that change the\n * outcome once explicit embedding controls are out of scope.\n */\ntype BidiClass = \"L\" | \"R\" | \"EN\" | \"AN\" | \"N\";\n\nconst LETTER_OR_DIGIT = /[\\p{L}\\p{N}]/u;\n\nfunction bidiClassOf(code: number): BidiClass {\n  if (code >= 0x30 && code <= 0x39) return \"EN\";\n  if (isArabicIndicDigit(code)) return \"AN\";\n  if (isRtlLetter(code)) return \"R\";\n  return LETTER_OR_DIGIT.test(String.fromCodePoint(code)) ? \"L\" : \"N\";\n}\n\n/**\n * How a character joins to its neighbours: both sides, the right only, or\n * neither. It comes from the shape table, since a letter with four forms\n * is by definition one that joins on both sides.\n */\ntype Joining = \"dual\" | \"right\" | \"none\";\n\nfunction joiningOf(code: number): Joining {\n  if (code === ZWJ) return \"dual\";\n  if (code === ZWNJ) return \"none\";\n  const forms = ARABIC_FORMS.get(code)?.length ?? 0;\n  if (forms === 4) return \"dual\";\n  return forms >= 2 ? \"right\" : \"none\";\n}\n\n/**\n * A base character and the marks riding on it.\n *\n * Reordering moves clusters, never their pieces: a mark drawn before its\n * letter would attach itself to whatever came earlier, since marks have\n * no width of their own to separate them.\n */\ninterface Cluster {\n  base: number;\n  marks: number[];\n  cls: BidiClass;\n  join: Joining;\n  /**\n   * The lam-alef ligature this cluster stands for, isolated and final\n   * form. Resolved once the letter before the lam is known.\n   */\n  ligature?: readonly [isolated: number, final: number];\n  /**\n   * False for the joining controls, which decide how their neighbours\n   * connect and are then not drawn.\n   */\n  drawn: boolean;\n  level: number;\n}\n\nfunction toClusters(text: string): Cluster[] {\n  const clusters: Cluster[] = [];\n  for (const ch of text) {\n    const code = ch.codePointAt(0) ?? 0;\n    const last = clusters.at(-1);\n    if (isMark(code) && last) {\n      last.marks.push(code);\n      continue;\n    }\n    clusters.push({\n      base: code,\n      marks: [],\n      cls: bidiClassOf(code),\n      join: joiningOf(code),\n      drawn: code !== ZWNJ && code !== ZWJ,\n      level: 0,\n    });\n  }\n  return clusters;\n}\n\n/** Can this letter join to the one after it? */\nfunction joinsForward(cluster: Cluster | undefined): boolean {\n  return cluster?.join === \"dual\";\n}\n\n/** Can this letter join to the one before it? */\nfunction joinsBackward(cluster: Cluster | undefined): boolean {\n  return cluster?.join === \"dual\" || cluster?.join === \"right\";\n}\n\n/**\n * Pick a letter's shape from its neighbours.\n *\n * `hasGlyph` has the last word: a font that omits a presentation form —\n * some Kufic and display faces do — is better served the plain letter\n * than a missing-glyph box.\n */\nfunction shapeOne(\n  cluster: Cluster,\n  before: Cluster | undefined,\n  after: Cluster | undefined,\n  hasGlyph: (code: number) => boolean\n): number {\n  const forms = ARABIC_FORMS.get(cluster.base);\n  if (!forms) return cluster.base;\n  const linkBefore = joinsForward(before);\n  const linkAfter = joinsBackward(after);\n  let form: number;\n  if (forms.length === 4) {\n    if (linkBefore && linkAfter) form = forms[3];\n    else if (linkBefore) form = forms[1];\n    else if (linkAfter) form = forms[2];\n    else form = forms[0];\n  } else if (forms.length === 2) {\n    form = linkBefore ? forms[1] : forms[0];\n  } else {\n    form = forms[0];\n  }\n  return hasGlyph(form) ? form : cluster.base;\n}\n\n/** Fold every lam-alef pair into one cluster carrying both its forms. */\nfunction applyLamAlef(\n  clusters: readonly Cluster[],\n  hasGlyph: (code: number) => boolean\n): Cluster[] {\n  const out: Cluster[] = [];\n  let i = 0;\n  while (i < clusters.length) {\n    const lam = clusters[i];\n    if (!lam) break;\n    const alef = clusters[i + 1];\n    const ligature =\n      lam.base === LAM && alef ? LAM_ALEF.get(alef.base) : undefined;\n    if (!ligature || !hasGlyph(ligature[0])) {\n      out.push(lam);\n      i += 1;\n      continue;\n    }\n    // The pair joins backwards only, exactly as a bare alef does.\n    out.push({\n      ...lam,\n      marks: [...lam.marks, ...(alef?.marks ?? [])],\n      join: \"right\",\n      ligature,\n    });\n    i += 2;\n  }\n  return out;\n}\n\n/** Resolve the shape of every cluster, ligatures included. */\nfunction shapeArabic(\n  clusters: readonly Cluster[],\n  hasGlyph: (code: number) => boolean\n): Cluster[] {\n  const folded = applyLamAlef(clusters, hasGlyph);\n  return folded.map((cluster, index) => {\n    const before = folded[index - 1];\n    const after = folded[index + 1];\n    if (cluster.ligature) {\n      const [isolated, final] = cluster.ligature;\n      const useFinal = joinsForward(before) && hasGlyph(final);\n      return { ...cluster, base: useFinal ? final : isolated };\n    }\n    return { ...cluster, base: shapeOne(cluster, before, after, hasGlyph) };\n  });\n}\n\n/** The level a strong class sits at inside a paragraph of `base` level. */\nfunction levelFor(cls: BidiClass, base: number): number {\n  if (cls === \"R\") return 1;\n  if (cls === \"AN\") return 2;\n  if (cls === \"EN\") return base === 1 ? 2 : 0;\n  return base === 1 ? 2 : 0;\n}\n\n/**\n * Which side of the line a character pulls towards, or nothing when it is\n * a neutral with no direction of its own.\n */\ntype NeutralSide = \"L\" | \"R\" | undefined;\n\n/** The direction a neutral inherits: numbers count as right-to-left. */\nfunction strongSideOf(cls: BidiClass): NeutralSide {\n  if (cls === \"L\") return \"L\";\n  if (cls === \"R\" || cls === \"EN\" || cls === \"AN\") return \"R\";\n  return undefined;\n}\n\n/**\n * Levels for every cluster.\n *\n * Strong characters take theirs from their class; a neutral run takes the\n * direction it is surrounded by, and the paragraph's own direction when\n * the two sides disagree — which is what puts a space between an Arabic\n * word and a Latin one on the side the reader expects. A run of neutrals\n * at either end has only one side, so it takes the paragraph's direction\n * too, and trailing whitespace lands where the line ends.\n */\nfunction assignLevels(clusters: readonly Cluster[], base: number): void {\n  const sides = clusters.map((cluster) => strongSideOf(cluster.cls));\n  for (const [index, cluster] of clusters.entries()) {\n    if (cluster.cls !== \"N\") {\n      cluster.level = levelFor(cluster.cls, base);\n      continue;\n    }\n    let before: NeutralSide;\n    for (let i = index - 1; i >= 0 && !before; i--) before = sides[i];\n    let after: NeutralSide;\n    for (let i = index + 1; i < clusters.length && !after; i++)\n      after = sides[i];\n    const paragraph = base === 1 ? \"R\" : \"L\";\n    const resolved = before === after && before ? before : paragraph;\n    cluster.level = levelFor(resolved, base);\n  }\n}\n\n/**\n * The reordering rule: from the deepest level outward, reverse every run\n * that reaches it. Two reversals cancel, which is exactly how a Latin\n * phrase inside an Arabic sentence comes back out reading forwards.\n */\nfunction reorder(clusters: Cluster[]): Cluster[] {\n  const max = clusters.reduce(\n    (high, cluster) => Math.max(high, cluster.level),\n    0\n  );\n  const out = [...clusters];\n  for (let level = max; level >= 1; level--) {\n    let start = -1;\n    for (let i = 0; i <= out.length; i++) {\n      const inRun = i < out.length && (out[i]?.level ?? 0) >= level;\n      if (inRun && start < 0) start = i;\n      else if (!inRun && start >= 0) {\n        const run = out.slice(start, i).reverse();\n        out.splice(start, run.length, ...run);\n        start = -1;\n      }\n    }\n  }\n  return out;\n}\n\n/** Options for {@link toDrawingOrder}. */\nexport interface DrawingOrderOptions {\n  /** The paragraph direction the cell is laid out in. */\n  rtl: boolean;\n  /**\n   * Whether the font can draw a code point. Presentation forms and\n   * ligatures fall back to the plain letter when it cannot.\n   */\n  hasGlyph?: (code: number) => boolean;\n}\n\n/**\n * Turn logical text into the sequence of code points to draw, left to\n * right.\n *\n * Latin-only text comes back unchanged, so a table with no Arabic in it\n * pays nothing and produces the same bytes it always did.\n *\n * @param text - The text as it was written.\n * @param options - Paragraph direction, and what the font can draw.\n * @returns The same characters, shaped and in drawing order.\n */\nexport function toDrawingOrder(\n  text: string,\n  options: DrawingOrderOptions\n): string {\n  if (text === \"\") return \"\";\n  const hasGlyph = options.hasGlyph ?? (() => true);\n  if (!options.rtl && !hasRtlText(text)) return text;\n  const clusters = shapeArabic(toClusters(text), hasGlyph);\n  const base = options.rtl ? 1 : 0;\n  assignLevels(clusters, base);\n  const ordered = reorder(clusters);\n  let out = \"\";\n  for (const cluster of ordered) {\n    if (!cluster.drawn) continue;\n    const mirrored =\n      cluster.level % 2 === 1 ? MIRRORED.get(cluster.base) : undefined;\n    out += String.fromCodePoint(mirrored ?? cluster.base);\n    for (const mark of cluster.marks) out += String.fromCodePoint(mark);\n  }\n  return out;\n}\n","/**\n * TrueType tables, read and rewritten by hand.\n *\n * A PDF that draws Arabic or Chinese has to carry the font, and carrying a\n * whole font is not an option: Noto Sans SC is 10 MB, and a download that\n * ships 10 MB to print twelve rows is broken even though it renders. So\n * this reads the sfnt container, keeps the glyphs the document actually\n * used, and writes a new font around them — usually a few kilobytes.\n *\n * The reader only ever needs a handful of tables. `glyf` holds the\n * outlines and `loca` says where each one starts; `head`, `hhea`, `maxp`\n * and `hmtx` describe the metrics; `cvt `/`fpgm`/`prep` are the hinting\n * programs, copied through untouched because they are small and dropping\n * them makes small text muddier. `cmap` is read to find glyphs but is not\n * written back: the PDF addresses glyphs by index through Identity-H, so\n * the embedded font needs no character map of its own.\n *\n * Glyphs are renumbered rather than kept at their original indices. A CJK\n * font has 65 000 of them, and holding the numbering would mean a `loca`\n * table with 65 001 entries — a quarter of a megabyte to describe glyphs\n * that are not there. The caller assigns new indices as it encodes text\n * and writes those indices into the content stream, which keeps\n * `/CIDToGIDMap /Identity` honest.\n *\n * Only outline (`glyf`) fonts subset here. A CFF-flavoured OpenType file\n * stores its outlines as PostScript charstrings — a different format with\n * its own interpreter — and quietly embedding one whole would put the\n * megabytes back. {@link parseSfnt} rejects it with a message that says\n * so, because the same family almost always ships a `.ttf` too.\n */\n\n/** Where one table sits in the file. */\ninterface TableRecord {\n  offset: number;\n  length: number;\n}\n\n/** A parsed font, and the few questions the PDF writer asks of it. */\nexport interface Sfnt {\n  /** Design units per em — 1000 for most, 2048 for many TrueType fonts. */\n  readonly unitsPerEm: number;\n  readonly numGlyphs: number;\n  /** PostScript name, used for `/BaseFont` after the subset tag. */\n  readonly postScriptName: string;\n  readonly ascent: number;\n  readonly descent: number;\n  readonly capHeight: number;\n  readonly italicAngle: number;\n  /** `[xMin, yMin, xMax, yMax]` in design units. */\n  readonly bbox: readonly [number, number, number, number];\n  readonly isFixedPitch: boolean;\n  readonly isSerif: boolean;\n  /** The glyph for a code point, or `0` (`.notdef`) when the font lacks it. */\n  glyphFor(codePoint: number): number;\n  /** Advance width in design units. */\n  advanceOf(glyph: number): number;\n  /** Left side bearing in design units. */\n  bearingOf(glyph: number): number;\n  /** The bytes, for the subsetter. */\n  readonly bytes: Uint8Array;\n  readonly tables: ReadonlyMap<string, TableRecord>;\n  readonly longLoca: boolean;\n}\n\nconst KEPT_TABLES = [\n  \"cvt \",\n  \"fpgm\",\n  \"glyf\",\n  \"head\",\n  \"hhea\",\n  \"hmtx\",\n  \"loca\",\n  \"maxp\",\n  \"prep\",\n] as const;\n\n/** Composite-glyph flags, from the `glyf` table's component records. */\nconst ARG_1_AND_2_ARE_WORDS = 0x0001;\nconst WE_HAVE_A_SCALE = 0x0008;\nconst MORE_COMPONENTS = 0x0020;\nconst WE_HAVE_AN_X_AND_Y_SCALE = 0x0040;\nconst WE_HAVE_A_TWO_BY_TWO = 0x0080;\n\nfunction bytesOf(source: Uint8Array | ArrayBuffer): Uint8Array {\n  return source instanceof Uint8Array ? source : new Uint8Array(source);\n}\n\nfunction viewOf(bytes: Uint8Array): DataView {\n  return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n}\n\nfunction tagAt(bytes: Uint8Array, at: number): string {\n  return String.fromCodePoint(\n    bytes[at] ?? 0,\n    bytes[at + 1] ?? 0,\n    bytes[at + 2] ?? 0,\n    bytes[at + 3] ?? 0\n  );\n}\n\nfunction readTables(\n  bytes: Uint8Array,\n  view: DataView\n): ReadonlyMap<string, TableRecord> {\n  const count = view.getUint16(4);\n  const tables = new Map<string, TableRecord>();\n  for (let i = 0; i < count; i++) {\n    const at = 12 + i * 16;\n    if (at + 16 > bytes.byteLength) break;\n    tables.set(tagAt(bytes, at), {\n      offset: view.getUint32(at + 8),\n      length: view.getUint32(at + 12),\n    });\n  }\n  return tables;\n}\n\n/**\n * One name record's text.\n *\n * Platform 3 (Windows) stores UTF-16BE and platform 1 (Mac) single bytes.\n * A PostScript name is ASCII either way, so anything outside it is\n * dropped rather than decoded — it cannot legally be there.\n */\nfunction readNameText(\n  view: DataView,\n  platform: number,\n  offset: number,\n  length: number\n): string {\n  const step = platform === 3 ? 2 : 1;\n  let name = \"\";\n  for (let at = 0; at < length; at += step) {\n    const code =\n      step === 2 ? view.getUint16(offset + at) : view.getUint8(offset + at);\n    if (code > 0x20 && code < 0x7f) name += String.fromCodePoint(code);\n  }\n  return name;\n}\n\n/** The one nameID that matters: 6, the PostScript name. */\nfunction readPostScriptName(\n  view: DataView,\n  table: TableRecord | undefined\n): string {\n  if (!table) return \"\";\n  const base = table.offset;\n  const count = view.getUint16(base + 2);\n  const stringsAt = base + view.getUint16(base + 4);\n  for (let i = 0; i < count; i++) {\n    const at = base + 6 + i * 12;\n    if (view.getUint16(at + 6) !== 6) continue;\n    const name = readNameText(\n      view,\n      view.getUint16(at),\n      stringsAt + view.getUint16(at + 10),\n      view.getUint16(at + 8)\n    );\n    if (name !== \"\") return name;\n  }\n  return \"\";\n}\n\n/** One segment of a format 4 subtable, as the glyph lookup needs it. */\ninterface Cmap4Segment {\n  delta: number;\n  rangeOffset: number;\n  rangeAt: number;\n  start: number;\n}\n\n/**\n * The glyph a format 4 segment gives a character.\n *\n * A segment either adds a constant to the character (`rangeOffset` of\n * zero) or points into a shared array of glyph indices; the second form\n * is how a font maps a range whose glyphs are not consecutive.\n */\nfunction cmap4Glyph(\n  view: DataView,\n  segment: Cmap4Segment,\n  code: number\n): number {\n  if (segment.rangeOffset === 0) return (code + segment.delta) & 0xffff;\n  const at = segment.rangeAt + segment.rangeOffset + (code - segment.start) * 2;\n  if (at + 1 >= view.byteLength) return 0;\n  const raw = view.getUint16(at);\n  return raw === 0 ? 0 : (raw + segment.delta) & 0xffff;\n}\n\n/** Format 4 — the segmented map every font has for the BMP. */\nfunction readCmap4(\n  view: DataView,\n  at: number,\n  into: Map<number, number>\n): void {\n  const segCount = view.getUint16(at + 6) / 2;\n  const endsAt = at + 14;\n  const startsAt = endsAt + segCount * 2 + 2;\n  const deltasAt = startsAt + segCount * 2;\n  const rangesAt = deltasAt + segCount * 2;\n  for (let seg = 0; seg < segCount; seg++) {\n    const end = view.getUint16(endsAt + seg * 2);\n    const start = view.getUint16(startsAt + seg * 2);\n    if (start > end) continue;\n    const segment = {\n      delta: view.getInt16(deltasAt + seg * 2),\n      // The offset is measured from the field itself, which is why the\n      // segment's own address has to travel with it.\n      rangeOffset: view.getUint16(rangesAt + seg * 2),\n      rangeAt: rangesAt + seg * 2,\n      start,\n    };\n    for (let code = start; code <= end && code !== 0xffff; code++) {\n      const glyph = cmap4Glyph(view, segment, code);\n      if (glyph !== 0) into.set(code, glyph);\n    }\n  }\n}\n\n/** Format 12 — the grouped map, for anything above the BMP. */\nfunction readCmap12(\n  view: DataView,\n  at: number,\n  into: Map<number, number>\n): void {\n  const groups = view.getUint32(at + 12);\n  for (let i = 0; i < groups; i++) {\n    const g = at + 16 + i * 12;\n    const start = view.getUint32(g);\n    const end = view.getUint32(g + 4);\n    const glyph = view.getUint32(g + 8);\n    // A single group can span a whole plane; cap the walk so a corrupt\n    // font cannot spin here forever.\n    const last = Math.min(end, start + 0xffff);\n    for (let code = start; code <= last; code++) {\n      into.set(code, glyph + (code - start));\n    }\n  }\n}\n\n/**\n * The best character map in the font.\n *\n * A (3,10) subtable covers every plane and wins outright; (3,1) covers the\n * BMP, which is every script this writer shapes; the Mac (0,x) tables are\n * the last resort for fonts that predate the Windows ones.\n */\nfunction readCmap(\n  view: DataView,\n  table: TableRecord | undefined\n): Map<number, number> {\n  const map = new Map<number, number>();\n  if (!table) return map;\n  const base = table.offset;\n  const count = view.getUint16(base + 2);\n  let best = -1;\n  let bestScore = -1;\n  for (let i = 0; i < count; i++) {\n    const at = base + 4 + i * 8;\n    const platform = view.getUint16(at);\n    const encoding = view.getUint16(at + 2);\n    const offset = view.getUint32(at + 4);\n    let score = -1;\n    if (platform === 3 && encoding === 10) score = 3;\n    else if (platform === 3 && encoding === 1) score = 2;\n    else if (platform === 0) score = 1;\n    if (score > bestScore) {\n      bestScore = score;\n      best = base + offset;\n    }\n  }\n  if (best < 0) return map;\n  const format = view.getUint16(best);\n  if (format === 4) readCmap4(view, best, map);\n  else if (format === 12) readCmap12(view, best, map);\n  return map;\n}\n\ninterface Metrics {\n  advances: number[];\n  lsbs: number[];\n}\n\n/**\n * Advance widths and left side bearings.\n *\n * `hmtx` stops repeating the advance once it stops changing — the last\n * long metric covers every glyph after it, which is how a monospaced font\n * stores one width for all of them — so the bearings that follow are read\n * from their own short array.\n */\nfunction readMetrics(\n  view: DataView,\n  hmtx: TableRecord | undefined,\n  numberOfHMetrics: number,\n  numGlyphs: number\n): Metrics {\n  const advances: number[] = [];\n  const lsbs: number[] = [];\n  if (!hmtx || numberOfHMetrics === 0) {\n    return {\n      advances: new Array<number>(numGlyphs).fill(0),\n      lsbs: new Array<number>(numGlyphs).fill(0),\n    };\n  }\n  const shortAt = hmtx.offset + numberOfHMetrics * 4;\n  for (let i = 0; i < numGlyphs; i++) {\n    const long = Math.min(i, numberOfHMetrics - 1);\n    const at = hmtx.offset + long * 4;\n    advances.push(at + 1 < view.byteLength ? view.getUint16(at) : 0);\n    const bearingAt =\n      i < numberOfHMetrics ? at + 2 : shortAt + (i - numberOfHMetrics) * 2;\n    lsbs.push(bearingAt + 1 < view.byteLength ? view.getInt16(bearingAt) : 0);\n  }\n  return { advances, lsbs };\n}\n\nfunction requiredTable(\n  tables: ReadonlyMap<string, TableRecord>,\n  tag: string\n): TableRecord {\n  const table = tables.get(tag);\n  if (!table) {\n    throw new Error(\n      `The font has no \\`${tag}\\` table, so it cannot be embedded.`\n    );\n  }\n  return table;\n}\n\n/**\n * Read a TrueType or OpenType font.\n *\n * @param source - The font file's bytes.\n * @returns The parsed font.\n * @throws If the bytes are not an sfnt font, or are CFF-flavoured — those\n *   store outlines as PostScript charstrings, which this does not subset.\n */\nexport function parseSfnt(source: Uint8Array | ArrayBuffer): Sfnt {\n  const bytes = bytesOf(source);\n  if (bytes.byteLength < 12) {\n    throw new Error(\"The font is too short to be a font file.\");\n  }\n  const view = viewOf(bytes);\n  const version = view.getUint32(0);\n  // 0x00010000 is TrueType, \"true\" is the Mac flavour, \"ttcf\" a collection.\n  const isTrueType = version === 0x00010000 || tagAt(bytes, 0) === \"true\";\n  if (!isTrueType && tagAt(bytes, 0) !== \"OTTO\") {\n    throw new Error(\n      \"The bytes are not a TrueType or OpenType font (no sfnt signature).\"\n    );\n  }\n  const tables = readTables(bytes, view);\n  if (!tables.has(\"glyf\") || !tables.has(\"loca\")) {\n    throw new Error(\n      \"This font stores its outlines as CFF, which the PDF writer does not \" +\n        \"subset. Use the TrueType (`.ttf`) build of the same family.\"\n    );\n  }\n  const head = requiredTable(tables, \"head\");\n  const hhea = requiredTable(tables, \"hhea\");\n  const maxp = requiredTable(tables, \"maxp\");\n  const os2 = tables.get(\"OS/2\");\n  const post = tables.get(\"post\");\n  const unitsPerEm = view.getUint16(head.offset + 18) || 1000;\n  const numGlyphs = view.getUint16(maxp.offset + 4);\n  const numberOfHMetrics = view.getUint16(hhea.offset + 34);\n  const metrics = readMetrics(\n    view,\n    tables.get(\"hmtx\"),\n    numberOfHMetrics,\n    numGlyphs\n  );\n  const cmap = readCmap(view, tables.get(\"cmap\"));\n  const familyClass = os2 ? view.getUint8(os2.offset + 30) : 0;\n  return {\n    unitsPerEm,\n    numGlyphs,\n    postScriptName:\n      readPostScriptName(view, tables.get(\"name\")) || \"EmbeddedFont\",\n    ascent: view.getInt16(hhea.offset + 4),\n    descent: view.getInt16(hhea.offset + 6),\n    // sCapHeight only exists from OS/2 version 2; 70% of the ascent is the\n    // usual stand-in and only feeds a hint the reader may ignore.\n    capHeight:\n      os2 && view.getUint16(os2.offset) >= 2\n        ? view.getInt16(os2.offset + 88)\n        : Math.round(view.getInt16(hhea.offset + 4) * 0.7),\n    italicAngle: post ? view.getInt32(post.offset + 4) / 65536 : 0,\n    bbox: [\n      view.getInt16(head.offset + 36),\n      view.getInt16(head.offset + 38),\n      view.getInt16(head.offset + 40),\n      view.getInt16(head.offset + 42),\n    ],\n    isFixedPitch: post ? view.getUint32(post.offset + 12) !== 0 : false,\n    // OS/2 family classes 1–7 are the serif designs; 8 is sans, 9+ are\n    // display and script faces the reader treats as neither.\n    isSerif: familyClass >= 1 && familyClass <= 7,\n    glyphFor: (codePoint) => cmap.get(codePoint) ?? 0,\n    advanceOf: (glyph) => metrics.advances[glyph] ?? 0,\n    bearingOf: (glyph) => metrics.lsbs[glyph] ?? 0,\n    bytes,\n    tables,\n    longLoca: view.getInt16(head.offset + 50) === 1,\n  };\n}\n\n/** Where glyph `index` starts and ends inside `glyf`. */\nfunction glyphRange(font: Sfnt, index: number): { at: number; end: number } {\n  const loca = font.tables.get(\"loca\");\n  const glyf = font.tables.get(\"glyf\");\n  if (!loca || !glyf || index < 0 || index >= font.numGlyphs) {\n    return { at: 0, end: 0 };\n  }\n  const view = viewOf(font.bytes);\n  const read = (i: number) =>\n    font.longLoca\n      ? view.getUint32(loca.offset + i * 4)\n      : view.getUint16(loca.offset + i * 2) * 2;\n  const at = read(index);\n  const end = read(index + 1);\n  return end > at\n    ? { at: glyf.offset + at, end: glyf.offset + end }\n    : { at: 0, end: 0 };\n}\n\n/** Every glyph a composite glyph draws, one level deep. */\nfunction componentsOf(font: Sfnt, index: number): number[] {\n  const { at, end } = glyphRange(font, index);\n  if (end - at < 10) return [];\n  const view = viewOf(font.bytes);\n  if (view.getInt16(at) >= 0) return [];\n  const out: number[] = [];\n  let cursor = at + 10;\n  let flags = MORE_COMPONENTS;\n  while ((flags & MORE_COMPONENTS) !== 0 && cursor + 4 <= end) {\n    flags = view.getUint16(cursor);\n    out.push(view.getUint16(cursor + 2));\n    cursor += 4;\n    cursor += (flags & ARG_1_AND_2_ARE_WORDS) !== 0 ? 4 : 2;\n    if ((flags & WE_HAVE_A_SCALE) !== 0) cursor += 2;\n    else if ((flags & WE_HAVE_AN_X_AND_Y_SCALE) !== 0) cursor += 4;\n    else if ((flags & WE_HAVE_A_TWO_BY_TWO) !== 0) cursor += 8;\n  }\n  return out;\n}\n\n/**\n * The glyphs a subset must carry, given the ones the document used.\n *\n * A composite glyph — an accented letter, most Arabic marks-on-letters —\n * is a reference to other glyphs, so keeping only what was typed would\n * write an outline that points at glyphs the file no longer has.\n */\nfunction withComponents(font: Sfnt, used: readonly number[]): number[] {\n  const order = [...used];\n  const seen = new Set(order);\n  // The loop appends to the array it walks, which is how a component that\n  // is itself composite gets its own components: an array iterator reads\n  // the length again at every step, so the additions are visited.\n  for (const glyph of order) {\n    for (const part of componentsOf(font, glyph)) {\n      if (seen.has(part)) continue;\n      seen.add(part);\n      order.push(part);\n    }\n  }\n  return order;\n}\n\n/** A composite glyph's component indices, rewritten to the new numbering. */\nfunction renumberComposite(\n  data: Uint8Array,\n  view: DataView,\n  newIndexOf: ReadonlyMap<number, number>\n): void {\n  let cursor = 10;\n  let flags = MORE_COMPONENTS;\n  while ((flags & MORE_COMPONENTS) !== 0 && cursor + 4 <= data.byteLength) {\n    flags = view.getUint16(cursor);\n    const original = view.getUint16(cursor + 2);\n    view.setUint16(cursor + 2, newIndexOf.get(original) ?? 0);\n    cursor += 4;\n    cursor += (flags & ARG_1_AND_2_ARE_WORDS) !== 0 ? 4 : 2;\n    if ((flags & WE_HAVE_A_SCALE) !== 0) cursor += 2;\n    else if ((flags & WE_HAVE_AN_X_AND_Y_SCALE) !== 0) cursor += 4;\n    else if ((flags & WE_HAVE_A_TWO_BY_TWO) !== 0) cursor += 8;\n  }\n}\n\ninterface GlyfResult {\n  glyf: Uint8Array;\n  loca: Uint8Array;\n  order: number[];\n  longLoca: boolean;\n}\n\n/** `glyf` and `loca` for the subset, in the caller's glyph order. */\nfunction buildGlyf(font: Sfnt, order: readonly number[]): GlyfResult {\n  const full = withComponents(font, order);\n  const newIndexOf = new Map(full.map((glyph, index) => [glyph, index]));\n  const pieces: Uint8Array[] = [];\n  const offsets: number[] = [0];\n  let total = 0;\n  for (const glyph of full) {\n    const { at, end } = glyphRange(font, glyph);\n    if (end > at) {\n      const data = font.bytes.slice(at, end);\n      const view = viewOf(data);\n      if (view.getInt16(0) < 0) renumberComposite(data, view, newIndexOf);\n      pieces.push(data);\n      total += data.byteLength;\n      // Every glyph must start on an even offset when `loca` is short.\n      if (total % 2 === 1) {\n        pieces.push(new Uint8Array(1));\n        total += 1;\n      }\n    }\n    offsets.push(total);\n  }\n  const glyf = new Uint8Array(total);\n  let at = 0;\n  for (const piece of pieces) {\n    glyf.set(piece, at);\n    at += piece.byteLength;\n  }\n  const long = total > 0x1fffe;\n  const loca = new Uint8Array(offsets.length * (long ? 4 : 2));\n  const locaView = viewOf(loca);\n  offsets.forEach((offset, index) => {\n    if (long) locaView.setUint32(index * 4, offset);\n    else locaView.setUint16(index * 2, offset / 2);\n  });\n  return { glyf, loca, order: full, longLoca: long };\n}\n\n/**\n * `hmtx` for the subset: one long metric per glyph.\n *\n * The table can end with a run of bearings that share the last advance,\n * and rebuilding that saves two bytes a glyph on a monospaced font. It is\n * not worth the arithmetic here — `numberOfHMetrics` equals the glyph\n * count, every entry is a full record, and `hhea` is patched to match.\n */\nfunction buildHmtx(font: Sfnt, order: readonly number[]): Uint8Array {\n  const out = new Uint8Array(order.length * 4);\n  const view = viewOf(out);\n  order.forEach((glyph, index) => {\n    view.setUint16(index * 4, font.advanceOf(glyph));\n    view.setInt16(index * 4 + 2, font.bearingOf(glyph));\n  });\n  return out;\n}\n\nfunction copyTable(font: Sfnt, tag: string): Uint8Array | undefined {\n  const table = font.tables.get(tag);\n  if (!table) return undefined;\n  return font.bytes.slice(table.offset, table.offset + table.length);\n}\n\nfunction patchedHead(font: Sfnt, longLoca: boolean): Uint8Array {\n  const head = copyTable(font, \"head\") ?? new Uint8Array(54);\n  const view = viewOf(head);\n  // The checksum is recomputed over the finished file, so blank it first.\n  view.setUint32(8, 0);\n  view.setInt16(50, longLoca ? 1 : 0);\n  return head;\n}\n\nfunction patchedHhea(font: Sfnt, glyphCount: number): Uint8Array {\n  const hhea = copyTable(font, \"hhea\") ?? new Uint8Array(36);\n  viewOf(hhea).setUint16(34, glyphCount);\n  return hhea;\n}\n\nfunction patchedMaxp(font: Sfnt, glyphCount: number): Uint8Array {\n  const maxp = copyTable(font, \"maxp\") ?? new Uint8Array(32);\n  viewOf(maxp).setUint16(4, glyphCount);\n  return maxp;\n}\n\n/** The sfnt checksum: the table's bytes as big-endian 32-bit words. */\nfunction checksum(bytes: Uint8Array): number {\n  let sum = 0;\n  const view = viewOf(bytes);\n  const words = Math.floor(bytes.byteLength / 4);\n  for (let i = 0; i < words; i++) sum = (sum + view.getUint32(i * 4)) >>> 0;\n  let tail = 0;\n  for (let i = words * 4; i < bytes.byteLength; i++) {\n    tail = (tail | ((bytes[i] ?? 0) << (24 - (i - words * 4) * 8))) >>> 0;\n  }\n  return (sum + tail) >>> 0;\n}\n\nfunction padded(length: number): number {\n  return (length + 3) & ~3;\n}\n\n/**\n * Write a font holding only the given glyphs.\n *\n * @param font - The parsed source font.\n * @param order - Original glyph indices, in the order the new font should\n *   number them. Index 0 of the result is always `.notdef`, so `order[0]`\n *   should be `0`; components the outlines reference are appended.\n * @returns The subset font's bytes.\n */\nexport function subsetSfnt(font: Sfnt, order: readonly number[]): Uint8Array {\n  const { glyf, loca, order: full, longLoca } = buildGlyf(font, order);\n  const built = new Map<string, Uint8Array>([\n    [\"glyf\", glyf],\n    [\"loca\", loca],\n    [\"hmtx\", buildHmtx(font, full)],\n    [\"head\", patchedHead(font, longLoca)],\n    [\"hhea\", patchedHhea(font, full.length)],\n    [\"maxp\", patchedMaxp(font, full.length)],\n  ]);\n  for (const tag of [\"cvt \", \"fpgm\", \"prep\"]) {\n    const copy = copyTable(font, tag);\n    if (copy) built.set(tag, copy);\n  }\n  // The directory is required to be in tag order.\n  const tags = KEPT_TABLES.filter((tag) => built.has(tag));\n  const count = tags.length;\n  // A power-of-two search range, as every sfnt header carries.\n  let entrySelector = 0;\n  while (1 << (entrySelector + 1) <= count) entrySelector += 1;\n  const searchRange = (1 << entrySelector) * 16;\n  const header = new Uint8Array(12 + count * 16);\n  const headerView = viewOf(header);\n  headerView.setUint32(0, 0x00010000);\n  headerView.setUint16(4, count);\n  headerView.setUint16(6, searchRange);\n  headerView.setUint16(8, entrySelector);\n  headerView.setUint16(10, count * 16 - searchRange);\n\n  let offset = header.byteLength;\n  const body: Uint8Array[] = [];\n  tags.forEach((tag, index) => {\n    const data = built.get(tag) ?? new Uint8Array(0);\n    const at = 12 + index * 16;\n    for (let i = 0; i < 4; i++) header[at + i] = tag.codePointAt(i) ?? 0;\n    headerView.setUint32(at + 4, checksum(data));\n    headerView.setUint32(at + 8, offset);\n    headerView.setUint32(at + 12, data.byteLength);\n    const block = new Uint8Array(padded(data.byteLength));\n    block.set(data);\n    body.push(block);\n    offset += block.byteLength;\n  });\n\n  const out = new Uint8Array(offset);\n  out.set(header);\n  let at = header.byteLength;\n  for (const block of body) {\n    out.set(block, at);\n    at += block.byteLength;\n  }\n  // `head.checkSumAdjustment` is the one field that describes the whole\n  // file, so it can only be filled in once the file exists.\n  const headTable = tags.indexOf(\"head\");\n  if (headTable >= 0) {\n    const headAt = headerView.getUint32(12 + headTable * 16 + 8);\n    viewOf(out).setUint32(headAt + 8, (0xb1b0afba - checksum(out)) >>> 0);\n  }\n  return out;\n}\n","/**\n * The two ways this writer can put text on a page.\n *\n * Without a font it uses Helvetica, one of the fourteen faces every PDF\n * reader is required to already have. Nothing is embedded, the file stays\n * tiny, and the alphabet stops at WinAnsi — Latin, and the punctuation\n * around it. That is the historic behaviour and still the default, because\n * most tables are Latin and most downloads should not carry a font.\n *\n * With a font it embeds one. The face is subset to the glyphs the document\n * used ({@link subsetSfnt}), wrapped as a composite Type0 font with\n * Identity-H encoding, and text is written as glyph indices rather than\n * characters. That is what makes Arabic and Chinese possible at all: the\n * simple encodings address 256 characters through a table of names, and\n * there is no name for 万. Identity-H addresses glyphs directly, two bytes\n * each, and a `/ToUnicode` map carries the characters back for copy-paste\n * and search.\n *\n * Both faces answer the same four questions — how wide is this text, what\n * order does it draw in, what operand shows it, which resource is it — so\n * the layout code never branches on which one it has.\n *\n * There is one thing an embedded font cannot do: be bold. A PDF font\n * resource is one face, and asking for a bold header would mean asking the\n * host for a second file. Instead the header row is stroked as well as\n * filled, which is what a word processor's \"faux bold\" does; it thickens\n * every stem by the same amount rather than using the type designer's\n * bold, and at nine points in a table header the difference is the point\n * of the row, not the shape of the letters.\n */\nimport { toDrawingOrder } from \"./arabicText\";\nimport { type Sfnt, subsetSfnt } from \"./sfnt\";\n\n/** A PDF object body: a dictionary as text, or bytes for a stream. */\nexport type PdfBody = string | Uint8Array;\n\n/** WinAnsi bytes for the characters Latin-1 does not share with CP1252. */\nconst WIN1252 = new Map<number, number>([\n  [0x20ac, 0x80],\n  [0x201a, 0x82],\n  [0x0192, 0x83],\n  [0x201e, 0x84],\n  [0x2026, 0x85],\n  [0x2020, 0x86],\n  [0x2021, 0x87],\n  [0x02c6, 0x88],\n  [0x2030, 0x89],\n  [0x0160, 0x8a],\n  [0x2039, 0x8b],\n  [0x0152, 0x8c],\n  [0x017d, 0x8e],\n  [0x2018, 0x91],\n  [0x2019, 0x92],\n  [0x201c, 0x93],\n  [0x201d, 0x94],\n  [0x2022, 0x95],\n  [0x2013, 0x96],\n  [0x2014, 0x97],\n  [0x02dc, 0x98],\n  [0x2122, 0x99],\n  [0x0161, 0x9a],\n  [0x203a, 0x9b],\n  [0x0153, 0x9c],\n  [0x017e, 0x9e],\n  [0x0178, 0x9f],\n]);\n\nexport function hex4(value: number): string {\n  return value.toString(16).toUpperCase().padStart(4, \"0\");\n}\n\nfunction winAnsiByte(code: number): number | undefined {\n  if (code >= 0x20 && code <= 0x7e) return code;\n  if (code >= 0xa0 && code <= 0xff) return code;\n  return WIN1252.get(code);\n}\n\n/**\n * Helvetica's advance widths, to the three buckets that matter.\n *\n * The real face has a width per glyph and the file does not carry them —\n * a reader looks them up in its own copy — so this is only ever used to\n * decide where a string ends and when to truncate it. Narrow letters,\n * wide letters, capitals and everything else is close enough that a\n * column's text lands inside its column.\n */\nfunction helveticaWidth(code: number): number {\n  const byte = winAnsiByte(code);\n  if (byte === undefined) return 556;\n  if (byte === 32 || byte === 105 || byte === 108 || byte === 116) {\n    return 278;\n  }\n  if (byte === 109 || byte === 119 || byte === 77 || byte === 87) {\n    return 833;\n  }\n  if (byte >= 65 && byte <= 90) return 667;\n  return 556;\n}\n\nfunction octalByte(code: number): string {\n  return `\\\\${code.toString(8).padStart(3, \"0\")}`;\n}\n\n/**\n * A PDF literal string. Non-ASCII WinAnsi bytes are octal so the content\n * stream stays ASCII and byte offsets equal character offsets.\n */\nexport function pdfLiteral(text: string): string {\n  let out = \"(\";\n  for (const ch of text) {\n    const code = winAnsiByte(ch.codePointAt(0) ?? 0);\n    if (code === undefined) {\n      out += \"?\";\n      continue;\n    }\n    if (code === 0x5c) out += \"\\\\\\\\\";\n    else if (code === 0x28) out += String.raw`\\(`;\n    else if (code === 0x29) out += String.raw`\\)`;\n    else if (code >= 32 && code <= 126) out += String.fromCodePoint(code);\n    else out += octalByte(code);\n  }\n  return `${out})`;\n}\n\n/** What the layout code needs from a face, whichever kind it is. */\nexport interface TextFace {\n  /** True when the document carries the font file itself. */\n  readonly embedded: boolean;\n  /** Width of already-ordered text at a font size, in points. */\n  measure(text: string, size: number): number;\n  /** Logical text turned into the sequence of characters to draw. */\n  order(text: string, rtl: boolean): string;\n  /** The operand for `Tj`: a literal string, or hex glyph indices. */\n  operand(text: string): string;\n  /** The resource name a `Tf` operator should use. */\n  fontRef(bold: boolean): string;\n  /** Operators that open and close a synthetically bold run. */\n  boldRun(bold: boolean): { open: string; close: string };\n  /** The `/Font` resource dictionary, given the id of the first extra object. */\n  fontResources(firstId: number): string;\n  /** Objects to append after the pages, in order from `firstId`. */\n  extraObjects(firstId: number): readonly PdfBody[];\n}\n\n/**\n * The built-in face: Helvetica and Helvetica-Bold, embedded nowhere.\n *\n * Objects 3 and 4 are the two font dictionaries; nothing is appended, so a\n * document with no font writes exactly the bytes it always has.\n */\nexport function standardFace(): TextFace {\n  return {\n    embedded: false,\n    measure: (text, size) => {\n      let units = 0;\n      for (const ch of text) units += helveticaWidth(ch.codePointAt(0) ?? 32);\n      return (units * size) / 1000;\n    },\n    // Helvetica has no Arabic glyphs to shape or reorder — every one of\n    // them draws as `?` — so the text is passed through untouched.\n    order: (text) => text,\n    operand: pdfLiteral,\n    fontRef: (bold) => (bold ? \"/F2\" : \"/F1\"),\n    boldRun: () => ({ open: \"\", close: \"\" }),\n    fontResources: () => \"<< /F1 3 0 R /F2 4 0 R >>\",\n    extraObjects: () => [],\n  };\n}\n\n/** What an embedded font draws for a character it does not cover. */\nconst FALLBACK = 0x3f;\n\n/** Six uppercase letters, the same ones for the same subset every time. */\nfunction subsetTag(name: string, glyphs: readonly number[]): string {\n  let hash = 0x811c9dc5;\n  const seed = `${name}:${glyphs.join(\",\")}`;\n  for (let i = 0; i < seed.length; i++) {\n    hash = Math.imul(hash ^ (seed.codePointAt(i) ?? 0), 0x01000193) >>> 0;\n  }\n  let tag = \"\";\n  for (let i = 0; i < 6; i++) {\n    tag += String.fromCodePoint(65 + (hash % 26));\n    hash = Math.floor(hash / 26) + 1;\n  }\n  return tag;\n}\n\n/** `/ToUnicode`, so the text is still text once it is glyph indices. */\nfunction toUnicodeCmap(\n  entries: readonly (readonly [number, number])[]\n): string {\n  const chunks: string[] = [];\n  for (let at = 0; at < entries.length; at += 100) {\n    const block = entries.slice(at, at + 100);\n    const lines = block\n      .map(([glyph, code]) => {\n        const value =\n          code > 0xffff\n            ? hex4(0xd800 + ((code - 0x10000) >> 10)) +\n              hex4(0xdc00 + ((code - 0x10000) & 0x3ff))\n            : hex4(code);\n        return `<${hex4(glyph)}> <${value}>`;\n      })\n      .join(\"\\n\");\n    chunks.push(`${String(block.length)} beginbfchar\\n${lines}\\nendbfchar`);\n  }\n  return [\n    \"/CIDInit /ProcSet findresource begin\",\n    \"12 dict begin\",\n    \"begincmap\",\n    \"/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\",\n    \"/CMapName /Adobe-Identity-UCS def\",\n    \"/CMapType 2 def\",\n    \"1 begincodespacerange\",\n    \"<0000> <FFFF>\",\n    \"endcodespacerange\",\n    ...chunks,\n    \"endcmap\",\n    \"CMapName currentdict /CMap defineresource pop\",\n    \"end\",\n    \"end\",\n  ].join(\"\\n\");\n}\n\nfunction streamBody(head: string, bytes: Uint8Array): PdfBody {\n  const prefix = new TextEncoder().encode(`${head}\\nstream\\n`);\n  const suffix = new TextEncoder().encode(\"\\nendstream\");\n  const out = new Uint8Array(\n    prefix.byteLength + bytes.byteLength + suffix.byteLength\n  );\n  out.set(prefix);\n  out.set(bytes, prefix.byteLength);\n  out.set(suffix, prefix.byteLength + bytes.byteLength);\n  return out;\n}\n\n/** The descriptor's `/Flags`, which is how a reader guesses at a face. */\nfunction descriptorFlags(font: Sfnt): number {\n  const SYMBOLIC = 4;\n  let flags = SYMBOLIC;\n  if (font.isFixedPitch) flags |= 1;\n  if (font.isSerif) flags |= 2;\n  if (font.italicAngle !== 0) flags |= 64;\n  return flags;\n}\n\n/**\n * A face backed by a host-supplied font file.\n *\n * Glyphs are numbered as they are first used, so the subset holds exactly\n * what the document drew and the content stream can name a glyph the\n * moment it needs one. Nothing is written until every page is laid out,\n * which is when the glyph list is finally known.\n *\n * @param font - The parsed source font.\n * @returns A face the PDF writer can draw with.\n */\nexport function embeddedFace(font: Sfnt): TextFace {\n  const scale = 1000 / font.unitsPerEm;\n  /** New glyph index by original glyph index; 0 is `.notdef`, always kept. */\n  const indexOf = new Map<number, number>([[0, 0]]);\n  const order: number[] = [0];\n  /** The character each new glyph came from, for `/ToUnicode`. */\n  const unicodeOf = new Map<number, number>();\n\n  /**\n   * The character actually drawn.\n   *\n   * A font covers the scripts its designer drew and no others, so an\n   * Arabic face handed an emoji — or a Latin word — has nothing for it.\n   * Drawing glyph zero there puts the reader's \"missing glyph\" box on the\n   * page, which reads as a broken file. `?` is what the built-in face\n   * does for the same gap and reads as what it is: a character this font\n   * does not have. The real character is still in `/ActualText` and\n   * `/ToUnicode`, so copy-paste and search are unaffected.\n   */\n  const substitute = (code: number): number =>\n    font.glyphFor(code) === 0 && code !== FALLBACK ? FALLBACK : code;\n\n  const glyphFor = (code: number): number => font.glyphFor(substitute(code));\n\n  const assign = (code: number): number => {\n    const glyph = glyphFor(code);\n    const existing = indexOf.get(glyph);\n    if (existing !== undefined) return existing;\n    const next = order.length;\n    indexOf.set(glyph, next);\n    order.push(glyph);\n    // The substituted character, not the one asked for: two different\n    // uncovered characters share the one `?` glyph, and a map claiming it\n    // is whichever came first would make copy-paste invent text.\n    unicodeOf.set(next, substitute(code));\n    return next;\n  };\n\n  const widthOf = (code: number): number =>\n    font.advanceOf(glyphFor(code)) * scale;\n\n  return {\n    embedded: true,\n    measure: (text, size) => {\n      let units = 0;\n      for (const ch of text) units += widthOf(ch.codePointAt(0) ?? 32);\n      return (units * size) / 1000;\n    },\n    // Shaping asks the font directly rather than through `substitute`:\n    // the question is whether this exact form exists, and a substituted\n    // `?` would answer yes to everything.\n    order: (text, rtl) =>\n      toDrawingOrder(text, {\n        rtl,\n        hasGlyph: (code) => font.glyphFor(code) !== 0,\n      }),\n    operand: (text) => {\n      let hex = \"\";\n      for (const ch of text) hex += hex4(assign(ch.codePointAt(0) ?? 32));\n      return `<${hex}>`;\n    },\n    fontRef: () => \"/F3\",\n    // Text render mode 2 fills and strokes, and the stroke is what\n    // thickens the stem. The stroke colour has to be set with it: the\n    // cell's own border left it light grey, and a header stroked in grey\n    // comes out paler than the rows under it rather than heavier.\n    boldRun: (bold) =>\n      bold\n        ? { open: \"0 G 0.3 w 2 Tr\\n\", close: \"0 Tr\\n\" }\n        : { open: \"\", close: \"\" },\n    fontResources: (firstId) => `<< /F3 ${String(firstId)} 0 R >>`,\n    extraObjects: (firstId) => {\n      const subset = subsetSfnt(font, order);\n      const tag = subsetTag(font.postScriptName, order);\n      const baseFont = `/${tag}+${font.postScriptName}`;\n      const descendantId = firstId + 1;\n      const descriptorId = firstId + 2;\n      const fileId = firstId + 3;\n      const unicodeId = firstId + 4;\n      const widths = order\n        .map((glyph) => String(Math.round(font.advanceOf(glyph) * scale)))\n        .join(\" \");\n      const bbox = font.bbox\n        .map((value) => String(Math.round(value * scale)))\n        .join(\" \");\n      const cmap = new TextEncoder().encode(\n        toUnicodeCmap([...unicodeOf.entries()])\n      );\n      return [\n        `<< /Type /Font /Subtype /Type0 /BaseFont ${baseFont} ` +\n          `/Encoding /Identity-H /DescendantFonts [${String(descendantId)} 0 R] ` +\n          `/ToUnicode ${String(unicodeId)} 0 R >>`,\n        `<< /Type /Font /Subtype /CIDFontType2 /BaseFont ${baseFont} ` +\n          \"/CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) \" +\n          \"/Supplement 0 >> \" +\n          `/FontDescriptor ${String(descriptorId)} 0 R /DW 1000 ` +\n          `/W [0 [${widths}]] /CIDToGIDMap /Identity >>`,\n        `<< /Type /FontDescriptor /FontName ${baseFont} ` +\n          `/Flags ${String(descriptorFlags(font))} /FontBBox [${bbox}] ` +\n          `/ItalicAngle ${String(Math.round(font.italicAngle))} ` +\n          `/Ascent ${String(Math.round(font.ascent * scale))} ` +\n          `/Descent ${String(Math.round(font.descent * scale))} ` +\n          `/CapHeight ${String(Math.round(font.capHeight * scale))} ` +\n          `/StemV 80 /FontFile2 ${String(fileId)} 0 R >>`,\n        streamBody(\n          `<< /Length ${String(subset.byteLength)} ` +\n            `/Length1 ${String(subset.byteLength)} >>`,\n          subset\n        ),\n        streamBody(`<< /Length ${String(cmap.byteLength)} >>`, cmap),\n      ];\n    },\n  };\n}\n","/**\n * What a printer (or \"Save as PDF\") should see: the current view, as HTML.\n *\n * A downloaded `.pdf` is a file. Print is a different verb — column widths,\n * group structure, page breaks, Unicode and RTL are all things the browser\n * already does well, and a hand-written PDF cannot match them without\n * embedding a font. This module is that path: a self-contained document the\n * host can hand to `window.print()`, or embed in its own page.\n *\n * Values resolve exactly as they do for CSV and XLSX — the caller passes an\n * {@link ExportTable} — so three formats of the same table cannot disagree\n * about what a cell contains.\n */\nimport type { ColumnDef } from \"../types\";\nimport { isBrowser } from \"../utils/env\";\nimport {\n  buildExportTable,\n  type ExportTable,\n  type ExportViewEntry,\n} from \"./exportWriter\";\n\n/** Paper the print stylesheet asks the browser for. */\nexport type PrintPageSize =\n  | \"a4\"\n  | \"a4-landscape\"\n  | \"letter\"\n  | \"letter-landscape\";\n\n/** How groups meet a page boundary. */\nexport type PrintPageBreak = \"auto\" | \"group\";\n\n/** Options for the printable document and the print dialog. */\nexport interface PrintLayoutOptions {\n  /** Document title and table caption. */\n  title?: string;\n  /** Visible caption when it should differ from {@link PrintLayoutOptions.title}. */\n  caption?: string;\n  /** `lang` on `<html>` when the host knows it. */\n  lang?: string;\n  /**\n   * Layout direction. Omit it and a browser document inherits\n   * `document.documentElement.dir`, so print matches what the reader sees.\n   */\n  direction?: \"ltr\" | \"rtl\";\n  /**\n   * Paper size. Defaults to A4 landscape — tables are wide, and a portrait\n   * page clips columns a landscape one still holds.\n   */\n  pageSize?: PrintPageSize;\n  /**\n   * `\"auto\"` (default) keeps a group together when it fits and never forces\n   * a page per group. `\"group\"` starts each top-level group on a new page.\n   */\n  pageBreak?: PrintPageBreak;\n  /**\n   * A font for the printed document, as the file's bytes.\n   *\n   * The browser already has fonts and shapes text with them, so print\n   * needs nothing here to render Arabic or Chinese correctly — unlike the\n   * PDF writer's `font` option, which is what makes those scripts\n   * possible at all in a downloaded file. Supply it when the printed page\n   * has to match the PDF exactly, or when the machine doing the printing\n   * cannot be assumed to have a face for the script.\n   *\n   * It is embedded whole, as an `@font-face` the document carries with\n   * it. Nothing is subset: the browser needs every glyph it might shape.\n   */\n  font?: Uint8Array | ArrayBuffer;\n}\n\n/**\n * The direction the print document should use.\n *\n * An explicit value wins. Otherwise a browser inherits the page's `dir`,\n * which is what the reader is looking at; outside a window the fallback is\n * `\"ltr\"` rather than guessing.\n */\nexport function resolvePrintDirection(\n  direction?: \"ltr\" | \"rtl\"\n): \"ltr\" | \"rtl\" {\n  if (direction === \"rtl\" || direction === \"ltr\") return direction;\n  if (!isBrowser()) return \"ltr\";\n  return document.documentElement.getAttribute(\"dir\") === \"rtl\" ? \"rtl\" : \"ltr\";\n}\n\n/** A date with no clock is a day; anything else is a day-and-time. */\nfunction isDateOnly(date: Date): boolean {\n  return (\n    (date.getUTCHours() === 0 &&\n      date.getUTCMinutes() === 0 &&\n      date.getUTCSeconds() === 0 &&\n      date.getUTCMilliseconds() === 0) ||\n    (date.getHours() === 0 &&\n      date.getMinutes() === 0 &&\n      date.getSeconds() === 0 &&\n      date.getMilliseconds() === 0)\n  );\n}\n\n/**\n * Strip what a table cell cannot carry: control characters. Tab, newline\n * and carriage return become a space so a cell stays one line.\n */\nfunction safeText(text: string): string {\n  let out = \"\";\n  for (const ch of text) {\n    if (ch === \"\\t\" || ch === \"\\n\" || ch === \"\\r\") out += \" \";\n    else if (ch >= \" \") out += ch;\n  }\n  return out;\n}\n\n/** A cell as the print document and the PDF both show it. */\nexport function exportCellText(value: unknown): string {\n  if (typeof value === \"string\") return safeText(value);\n  if (typeof value === \"number\" && Number.isFinite(value)) {\n    return String(value);\n  }\n  if (typeof value === \"boolean\") return value ? \"true\" : \"false\";\n  if (value instanceof Date && !Number.isNaN(value.getTime())) {\n    if (isDateOnly(value)) return value.toISOString().slice(0, 10);\n    return value.toISOString().slice(0, 16).replace(\"T\", \" \");\n  }\n  return \"\";\n}\n\n/** Escape the five characters HTML cannot carry literally. */\nfunction html(text: string): string {\n  return text\n    .replaceAll(\"&\", \"&amp;\")\n    .replaceAll(\"<\", \"&lt;\")\n    .replaceAll(\">\", \"&gt;\")\n    .replaceAll('\"', \"&quot;\")\n    .replaceAll(\"'\", \"&#39;\");\n}\n\nfunction pageSizeCss(size: PrintPageSize = \"a4-landscape\"): string {\n  if (size === \"letter\") return \"letter portrait\";\n  if (size === \"letter-landscape\") return \"letter landscape\";\n  if (size === \"a4\") return \"A4 portrait\";\n  return \"A4 landscape\";\n}\n\nfunction colPercents(table: ExportTable): number[] {\n  const count = table.headers.length;\n  if (count === 0) return [];\n  const weights = table.headers.map((_, index) => {\n    const stated = table.widths?.[index];\n    return stated !== undefined && stated > 0 ? stated : 12;\n  });\n  const sum = weights.reduce((total, weight) => total + weight, 0);\n  return weights.map((weight) => (100 * weight) / sum);\n}\n\nfunction colGroup(table: ExportTable): string {\n  const percents = colPercents(table);\n  const cols = percents.map((percent, index) => {\n    const stated = table.widths?.[index];\n    const ch = stated !== undefined ? ` data-ch=\"${String(stated)}\"` : \"\";\n    const width = (Math.round(percent * 100) / 100).toString();\n    return `<col${ch} style=\"width:${width}%\"/>`;\n  });\n  return cols.length > 0 ? `<colgroup>${cols.join(\"\")}</colgroup>` : \"\";\n}\n\nfunction firstCellTag(\n  role: string,\n  column: number\n): {\n  tag: \"th\" | \"td\";\n  scope: string;\n} {\n  if (column === 0 && role === \"group\") {\n    return { tag: \"th\", scope: ' scope=\"row\"' };\n  }\n  return { tag: \"td\", scope: \"\" };\n}\n\nfunction cellHtml(\n  value: unknown,\n  column: number,\n  role: string,\n  level: number\n): string {\n  const { tag, scope } = firstCellTag(role, column);\n  const indent =\n    column === 0 && level > 0\n      ? ` style=\"padding-inline-start:${String(6 + level * 16)}pt\"`\n      : \"\";\n  return `<${tag}${scope}${indent}>${html(exportCellText(value))}</${tag}>`;\n}\n\nfunction dataRow(\n  table: ExportTable,\n  row: readonly unknown[],\n  index: number\n): string {\n  const meta = table.rowMeta?.[index];\n  const role = meta?.role ?? \"data\";\n  const level = meta?.level ?? 0;\n  const cells = row\n    .map((value, column) => cellHtml(value, column, role, level))\n    .join(\"\");\n  return `<tr data-role=\"${role}\" data-level=\"${String(level)}\">${cells}</tr>`;\n}\n\nfunction flushGroup(\n  chunks: string[],\n  rows: string,\n  level: number,\n  open: boolean\n): boolean {\n  if (!open) return false;\n  chunks.push(\n    `<tbody class=\"print-group\" data-level=\"${String(level)}\">${rows}</tbody>`\n  );\n  return true;\n}\n\n/**\n * One `<tbody>` per group so `break-inside: avoid` can keep a header with\n * its leaves. A flat table is a single body. Tree rows (all `data`, with\n * a level) stay in one body and indent instead.\n */\nfunction tableBodies(table: ExportTable): string {\n  const meta = table.rowMeta;\n  if (!meta) {\n    const rows = table.rows\n      .map((row, index) => dataRow(table, row, index))\n      .join(\"\");\n    return `<tbody>${rows}</tbody>`;\n  }\n  const chunks: string[] = [];\n  let rows = \"\";\n  let level = 0;\n  let open = false;\n  table.rows.forEach((row, index) => {\n    const role = meta[index]?.role ?? \"data\";\n    const rowLevel = meta[index]?.level ?? 0;\n    if (role === \"group\") {\n      if (flushGroup(chunks, rows, level, open)) {\n        rows = \"\";\n        open = false;\n      }\n      level = rowLevel;\n    } else if (!open) {\n      level = rowLevel;\n    }\n    rows += dataRow(table, row, index);\n    open = true;\n  });\n  flushGroup(chunks, rows, level, open);\n  return chunks.join(\"\");\n}\n\nfunction headerRow(table: ExportTable): string {\n  const cells = table.headers\n    .map((text) => `<th scope=\"col\">${html(text)}</th>`)\n    .join(\"\");\n  return `<tr>${cells}</tr>`;\n}\n\n/**\n * A font file as a `data:` URL.\n *\n * The bytes are turned into a string in chunks: spreading a whole font\n * into `String.fromCodePoint` is hundreds of thousands of arguments in one\n * call, which overflows the stack on every engine.\n */\nfunction fontDataUrl(font: Uint8Array | ArrayBuffer): string {\n  const bytes = font instanceof Uint8Array ? font : new Uint8Array(font);\n  const CHUNK = 0x8000;\n  let binary = \"\";\n  for (let at = 0; at < bytes.byteLength; at += CHUNK) {\n    binary += String.fromCodePoint(...bytes.subarray(at, at + CHUNK));\n  }\n  return `data:font/ttf;base64,${btoa(binary)}`;\n}\n\n/**\n * The print stylesheet: repeating headers, row/group keep-together, and\n * column widths the table already decided.\n *\n * @param options - Paper size, page-break behaviour, and a font to embed.\n * @returns A CSS string, ready for a `<style>` element.\n */\nexport function printStyles(options?: PrintLayoutOptions): string {\n  const paper = pageSizeCss(options?.pageSize);\n  const face = options?.font\n    ? \"@font-face{font-family:AdaptTablePrint;font-display:block;\" +\n      `src:url(${fontDataUrl(options.font)}) format(\"truetype\")}`\n    : \"\";\n  const family = options?.font ? \"AdaptTablePrint,\" : \"\";\n  const groupBreak =\n    options?.pageBreak === \"group\"\n      ? 'table.adapttable-print-break-group tbody.print-group[data-level=\"0\"] + tbody.print-group[data-level=\"0\"]{break-before:page;page-break-before:always}'\n      : \"\";\n  return (\n    face +\n    `@page{size:${paper};margin:12mm}` +\n    \"html,body{margin:0;padding:0;background:#fff;color:#111;\" +\n    `font:11pt/1.35 ${family}` +\n    'system-ui,-apple-system,\"Segoe UI\",sans-serif}' +\n    \"table.adapttable-print{width:100%;border-collapse:collapse;\" +\n    \"table-layout:fixed}\" +\n    \"table.adapttable-print caption{caption-side:top;text-align:start;\" +\n    \"font-size:14pt;font-weight:650;margin:0 0 12pt}\" +\n    \"table.adapttable-print thead{display:table-header-group}\" +\n    \"table.adapttable-print th,table.adapttable-print td{\" +\n    \"border:0.4pt solid #bbb;padding:4pt 6pt;vertical-align:top;\" +\n    \"overflow:hidden;word-wrap:break-word;text-align:start}\" +\n    \"table.adapttable-print th{font-weight:650;background:#f0f0f0}\" +\n    \"table.adapttable-print tr{break-inside:avoid;page-break-inside:avoid}\" +\n    'table.adapttable-print tr[data-role=\"group\"]{break-after:avoid;' +\n    \"page-break-after:avoid;font-weight:650;background:#f7f7f7}\" +\n    'table.adapttable-print tr[data-role=\"aggregate\"]{break-before:avoid;' +\n    \"page-break-before:avoid;font-weight:650}\" +\n    \"table.adapttable-print tbody.print-group{break-inside:avoid;\" +\n    \"page-break-inside:avoid}\" +\n    groupBreak\n  );\n}\n\n/**\n * The table element alone — for a host that already has a page and a\n * stylesheet, and only needs the rows.\n */\nexport function buildPrintTableHtml(\n  table: ExportTable,\n  options?: PrintLayoutOptions\n): string {\n  const captionText = options?.caption ?? options?.title;\n  const caption = captionText ? `<caption>${html(captionText)}</caption>` : \"\";\n  const breakClass =\n    options?.pageBreak === \"group\" ? \" adapttable-print-break-group\" : \"\";\n  return (\n    `<table class=\"adapttable-print${breakClass}\">` +\n    caption +\n    colGroup(table) +\n    `<thead>${headerRow(table)}</thead>` +\n    tableBodies(table) +\n    \"</table>\"\n  );\n}\n\n/**\n * A complete HTML document: doctype, direction, the print stylesheet, and\n * the table. This is what {@link openPrintLayout} loads into the iframe.\n */\nexport function buildPrintDocument(\n  table: ExportTable,\n  options?: PrintLayoutOptions\n): string {\n  const direction = resolvePrintDirection(options?.direction);\n  const title = options?.title ?? \"Table\";\n  const lang = options?.lang ? ` lang=\"${html(options.lang)}\"` : \"\";\n  return (\n    \"<!DOCTYPE html>\" +\n    `<html${lang} dir=\"${direction}\">` +\n    '<head><meta charset=\"utf-8\"/>' +\n    `<title>${html(title)}</title>` +\n    `<style>${printStyles(options)}</style></head>` +\n    `<body>${buildPrintTableHtml(table, options)}</body></html>`\n  );\n}\n\n/**\n * Open the browser print dialog on the current view.\n *\n * A hidden iframe holds the document so the host page is not rewritten and\n * a popup blocker never sees a window. No-op outside a browser, so a\n * server render that reaches this does nothing rather than throwing.\n */\nexport function openPrintLayout(\n  table: ExportTable,\n  options?: PrintLayoutOptions\n): void {\n  if (!isBrowser()) return;\n  const iframe = document.createElement(\"iframe\");\n  iframe.setAttribute(\"title\", options?.title ?? \"Print\");\n  iframe.setAttribute(\"aria-hidden\", \"true\");\n  iframe.style.position = \"fixed\";\n  iframe.style.insetInlineEnd = \"0\";\n  iframe.style.insetBlockEnd = \"0\";\n  iframe.style.width = \"0\";\n  iframe.style.height = \"0\";\n  iframe.style.border = \"0\";\n  const cleanup = () => {\n    iframe.remove();\n  };\n  iframe.addEventListener(\"load\", () => {\n    const frameWindow = iframe.contentWindow;\n    if (!frameWindow) {\n      cleanup();\n      return;\n    }\n    frameWindow.addEventListener(\"afterprint\", cleanup);\n    frameWindow.focus();\n    frameWindow.print();\n  });\n  iframe.srcdoc = buildPrintDocument(table, options);\n  document.body.appendChild(iframe);\n}\n\n/**\n * Print rows and columns the same way the PDF builder writes a file:\n * resolve once, then open the dialog.\n */\nexport function printTable<TRow>(\n  options: {\n    rows: readonly TRow[];\n    columns: readonly ColumnDef<TRow>[];\n    view?: readonly ExportViewEntry<TRow>[];\n    summary?: Readonly<Partial<Record<string, unknown>>>;\n  } & PrintLayoutOptions\n): void {\n  openPrintLayout(\n    buildExportTable(options.rows, options.columns, {\n      view: options.view,\n      summary: options.summary,\n    }),\n    options\n  );\n}\n","/**\n * A PDF file, written by hand.\n *\n * PDF is a sequence of numbered objects, a cross-reference table and a\n * trailer — small enough to emit without a library, the same reason XLSX\n * is a ZIP we write ourselves. What it needs is a catalog, a page tree,\n * two standard fonts, and one content stream per page. Everything else\n * in the format is optional.\n *\n * Helvetica is one of the fourteen fonts every reader already has, so by\n * default the file embeds nothing and stays a few kilobytes. That is also\n * the limit: glyphs outside WinAnsi become `?` on the page.\n *\n * Hand it a font and that limit lifts. `font` takes a TrueType file as\n * bytes; the writer subsets it to the glyphs the table used, embeds it,\n * shapes Arabic into its presentation forms and reorders right-to-left\n * text for drawing. See `./pdfFont` and `./arabicText` for how. The\n * original characters still travel in `/ActualText`, so copy-paste and a\n * screen reader read the logical string either way.\n *\n * Values resolve exactly as they do for CSV and XLSX. What differs is\n * pagination: a column's width, a group's outline and a page break are\n * honoured here because a PDF that ignores them is a screenshot of the\n * wrong table.\n */\nimport type { ColumnDef } from \"../types\";\nimport {\n  buildExportTable,\n  type ExportTable,\n  type ExportViewEntry,\n  type ExportWriter,\n} from \"./exportWriter\";\nimport {\n  embeddedFace,\n  hex4,\n  type PdfBody,\n  pdfLiteral,\n  standardFace,\n  type TextFace,\n} from \"./pdfFont\";\nimport {\n  exportCellText,\n  type PrintPageBreak,\n  type PrintPageSize,\n  resolvePrintDirection,\n} from \"./printLayout\";\nimport { parseSfnt } from \"./sfnt\";\n\n/** Options the writer and {@link buildTablePdf} share. */\nexport interface PdfWriterOptions {\n  /** Document title. Defaults to the download name without its extension. */\n  title?: string;\n  /** Layout direction. Omit it and a browser inherits the page's `dir`. */\n  direction?: \"ltr\" | \"rtl\";\n  /**\n   * Paper size. Defaults to A4 landscape — the same default as the print\n   * stylesheet, so the two paths agree about how wide a table is.\n   */\n  pageSize?: PrintPageSize;\n  /**\n   * `\"auto\"` (default) starts a new page when the next row will not fit,\n   * and will not leave a group header alone at the bottom. `\"group\"`\n   * also starts a page before each top-level group after the first.\n   */\n  pageBreak?: PrintPageBreak;\n  /**\n   * A TrueType font to draw with, as the file's bytes.\n   *\n   * Omit it and the PDF uses Helvetica and embeds nothing, which is right\n   * for a Latin table. Supply one and the writer embeds a subset of it —\n   * only the glyphs this table used — which is what lets the file draw\n   * Arabic, Chinese, Cyrillic or anything else the font covers, instead of\n   * the `?` a built-in face has to fall back to.\n   *\n   * ```ts\n   * const font = await fetch(\"/fonts/NotoSansArabic-Regular.ttf\")\n   *   .then((res) => res.arrayBuffer());\n   *\n   * pdfWriter({ font, direction: \"rtl\" });\n   * ```\n   *\n   * The font must have TrueType outlines — a `.ttf`, or an `.otf` built\n   * from one. A CFF-flavoured OpenType file is rejected with a message\n   * saying so rather than embedded whole.\n   */\n  font?: Uint8Array | ArrayBuffer;\n}\n\ninterface PageBox {\n  width: number;\n  height: number;\n}\n\ninterface DrawContext {\n  box: PageBox;\n  colWidths: number[];\n  colXs: number[];\n  rtl: boolean;\n  face: TextFace;\n}\n\nconst MARGIN = 36;\nconst FONT_SIZE = 9;\nconst ROW_H = 16;\nconst HEADER_H = 18;\nconst TITLE_H = 22;\nconst FOOTER = 20;\nconst CELL_PAD = 4;\nconst INDENT = 12;\nconst HEADER_FILL = \"0.9 0.9 0.9\";\nconst GROUP_FILL = \"0.95 0.95 0.95\";\n\nfunction pageBox(size: PrintPageSize = \"a4-landscape\"): PageBox {\n  if (size === \"a4\") return { width: 595, height: 842 };\n  if (size === \"letter\") return { width: 612, height: 792 };\n  if (size === \"letter-landscape\") return { width: 792, height: 612 };\n  return { width: 842, height: 595 };\n}\n\nfunction num(value: number): string {\n  return String(Math.round(value * 100) / 100);\n}\n\nfunction ascii(text: string): Uint8Array<ArrayBuffer> {\n  return new TextEncoder().encode(text);\n}\n\nfunction concatBytes(chunks: readonly Uint8Array[]): Uint8Array<ArrayBuffer> {\n  let total = 0;\n  for (const chunk of chunks) total += chunk.byteLength;\n  const out = new Uint8Array(total);\n  let at = 0;\n  for (const chunk of chunks) {\n    out.set(chunk, at);\n    at += chunk.byteLength;\n  }\n  return out;\n}\n\n/** UTF-16BE with a BOM, as `/ActualText` hex strings require. */\nfunction utf16BeHex(text: string): string {\n  let hex = \"FEFF\";\n  for (const ch of text) {\n    const code = ch.codePointAt(0) ?? 0;\n    if (code > 0xffff) {\n      const u = code - 0x10000;\n      hex += hex4(0xd800 + (u >> 10));\n      hex += hex4(0xdc00 + (u & 0x3ff));\n    } else {\n      hex += hex4(code);\n    }\n  }\n  return `<${hex}>`;\n}\n\n/**\n * How wide the text is once drawn.\n *\n * Shaping happens first, because it changes the answer: an Arabic letter's\n * medial form is narrower than its isolated one, and measuring the letters\n * as typed would leave every joined word short of its column.\n */\nfunction drawnWidth(\n  text: string,\n  fontSize: number,\n  ctx: Pick<DrawContext, \"face\" | \"rtl\">\n): number {\n  return ctx.face.measure(ctx.face.order(text, ctx.rtl), fontSize);\n}\n\n/**\n * Trim text to a column, with an ellipsis.\n *\n * The cut is made on the logical string, not the drawn one, so a\n * right-to-left sentence loses its end rather than its beginning and the\n * ellipsis lands where the reader stopped reading.\n */\nfunction fitText(\n  text: string,\n  maxPt: number,\n  fontSize: number,\n  ctx: Pick<DrawContext, \"face\" | \"rtl\">\n): string {\n  if (drawnWidth(text, fontSize, ctx) <= maxPt) return text;\n  const ellipsis = \"…\";\n  if (drawnWidth(ellipsis, fontSize, ctx) > maxPt) return ellipsis;\n  let end = text.length;\n  while (\n    end > 0 &&\n    drawnWidth(text.slice(0, end) + ellipsis, fontSize, ctx) > maxPt\n  ) {\n    end -= 1;\n  }\n  return end === 0 ? ellipsis : text.slice(0, end) + ellipsis;\n}\n\nfunction contentTop(box: PageBox, titled: boolean): number {\n  return box.height - MARGIN - (titled ? TITLE_H : 0);\n}\n\nfunction columnWidths(table: ExportTable, usable: number): number[] {\n  const count = table.headers.length;\n  if (count === 0) return [];\n  const weights = table.headers.map((_, index) => {\n    const stated = table.widths?.[index];\n    return stated !== undefined && stated > 0 ? stated : 12;\n  });\n  const sum = weights.reduce((total, weight) => total + weight, 0);\n  return weights.map((weight) => (usable * weight) / sum);\n}\n\nfunction columnXs(\n  widths: readonly number[],\n  left: number,\n  rtl: boolean\n): number[] {\n  if (!rtl) {\n    let x = left;\n    return widths.map((width) => {\n      const at = x;\n      x += width;\n      return at;\n    });\n  }\n  let x = left + widths.reduce((total, width) => total + width, 0);\n  return widths.map((width) => {\n    x -= width;\n    return x;\n  });\n}\n\nfunction paginate(\n  rowCount: number,\n  roles: ExportTable[\"rowMeta\"],\n  box: PageBox,\n  pageBreak: PrintPageBreak | undefined,\n  titled: boolean\n): number[][] {\n  const pages: number[][] = [];\n  let current: number[] = [];\n  let y = contentTop(box, titled) - HEADER_H;\n  const bottom = MARGIN + FOOTER;\n  for (let index = 0; index < rowCount; index++) {\n    const role = roles?.[index]?.role ?? \"data\";\n    const level = roles?.[index]?.level ?? 0;\n    const force =\n      pageBreak === \"group\" &&\n      role === \"group\" &&\n      level === 0 &&\n      current.length > 0;\n    const overflow = y - ROW_H < bottom;\n    const orphan = role === \"group\" && y - ROW_H * 2 < bottom;\n    if ((force || overflow || orphan) && current.length > 0) {\n      pages.push(current);\n      current = [];\n      y = contentTop(box, false) - HEADER_H;\n    }\n    current.push(index);\n    y -= ROW_H;\n  }\n  pages.push(current);\n  return pages;\n}\n\nfunction fillRow(\n  ctx: DrawContext,\n  y: number,\n  height: number,\n  rgb: string\n): string {\n  const left = ctx.colXs.reduce(\n    (min, x) => Math.min(min, x),\n    ctx.colXs[0] ?? MARGIN\n  );\n  const width = ctx.colWidths.reduce((total, col) => total + col, 0);\n  return (\n    `${rgb} rg\\n${num(left)} ${num(y - height)} ${num(width)} ` +\n    `${num(height)} re f\\n0 g\\n`\n  );\n}\n\nfunction cellBox(x: number, y: number, w: number, h: number): string {\n  return (\n    `0.7 0.7 0.7 RG\\n0.4 w\\n${num(x)} ${num(y - h)} ${num(w)} ` +\n    `${num(h)} re S\\n0 g\\n`\n  );\n}\n\ninterface CellTextOptions {\n  text: string;\n  x: number;\n  y: number;\n  w: number;\n  height: number;\n  indent: number;\n  bold: boolean;\n  ctx: DrawContext;\n}\n\nfunction cellText({\n  text,\n  x,\n  y,\n  w,\n  height,\n  indent,\n  bold,\n  ctx,\n}: Readonly<CellTextOptions>): string {\n  const { face, rtl } = ctx;\n  const max = Math.max(8, w - CELL_PAD * 2 - indent);\n  const shown = fitText(text, max, FONT_SIZE, ctx);\n  const ordered = face.order(shown, rtl);\n  const drawn = face.measure(ordered, FONT_SIZE);\n  const tx = rtl ? x + w - CELL_PAD - indent - drawn : x + CELL_PAD + indent;\n  const ty = y - height + 5;\n  const weight = face.boldRun(bold);\n  return (\n    `q\\n${num(x)} ${num(y - height)} ${num(w)} ${num(height)} re W n\\n` +\n    `BT\\n${face.fontRef(bold)} ${String(FONT_SIZE)} Tf\\n` +\n    `1 0 0 1 ${num(Math.max(x, tx))} ${num(ty)} Tm\\n` +\n    `/Span << /ActualText ${utf16BeHex(text)} >> BDC\\n` +\n    `${weight.open}${face.operand(ordered)} Tj\\n${weight.close}EMC\\nET\\nQ\\n`\n  );\n}\n\nfunction drawCells(\n  count: number,\n  values: readonly unknown[],\n  ctx: DrawContext,\n  y: number,\n  height: number,\n  style: { bold: boolean; fill?: string; level: number }\n): string {\n  const parts: string[] = [];\n  if (style.fill) parts.push(fillRow(ctx, y, height, style.fill));\n  for (let i = 0; i < count; i++) {\n    const x = ctx.colXs[i] ?? 0;\n    const w = ctx.colWidths[i] ?? 0;\n    const indent = i === 0 ? style.level * INDENT : 0;\n    parts.push(cellBox(x, y, w, height));\n    const text = exportCellText(values[i]);\n    if (text !== \"\") {\n      parts.push(\n        cellText({\n          text,\n          x,\n          y,\n          w,\n          height,\n          indent,\n          bold: style.bold,\n          ctx,\n        })\n      );\n    }\n  }\n  return parts.join(\"\");\n}\n\nfunction drawTitle(title: string, ctx: DrawContext): string {\n  const y = ctx.box.height - MARGIN - 14;\n  const ordered = ctx.face.order(title, ctx.rtl);\n  const width = ctx.face.measure(ordered, 12);\n  const x = ctx.rtl ? ctx.box.width - MARGIN - width : MARGIN;\n  const weight = ctx.face.boldRun(true);\n  return (\n    `BT\\n${ctx.face.fontRef(true)} 12 Tf\\n` +\n    `1 0 0 1 ${num(Math.max(MARGIN, x))} ${num(y)} Tm\\n` +\n    `${weight.open}${ctx.face.operand(ordered)} Tj\\n${weight.close}ET\\n`\n  );\n}\n\nfunction drawFooter(page: number, pageCount: number, ctx: DrawContext): string {\n  // This label is written here, in one script, so it is laid out left to\n  // right whichever way the table runs.\n  const label = `Page ${String(page)} of ${String(pageCount)}`;\n  const x = (ctx.box.width - ctx.face.measure(label, 8)) / 2;\n  return (\n    `BT\\n${ctx.face.fontRef(false)} 8 Tf\\n` +\n    `1 0 0 1 ${num(x)} ${num(MARGIN - 4)} Tm\\n` +\n    `${ctx.face.operand(label)} Tj\\nET\\n`\n  );\n}\n\nfunction drawHeaderRow(\n  table: ExportTable,\n  ctx: DrawContext,\n  y: number\n): string {\n  return drawCells(table.headers.length, table.headers, ctx, y, HEADER_H, {\n    bold: true,\n    fill: HEADER_FILL,\n    level: 0,\n  });\n}\n\nfunction drawBodyRow(\n  table: ExportTable,\n  index: number,\n  ctx: DrawContext,\n  y: number\n): string {\n  const meta = table.rowMeta?.[index];\n  const role = meta?.role ?? \"data\";\n  const level = meta?.level ?? 0;\n  const chrome = role === \"group\" || role === \"aggregate\";\n  return drawCells(\n    table.headers.length,\n    table.rows[index] ?? [],\n    ctx,\n    y,\n    ROW_H,\n    {\n      bold: chrome,\n      fill: chrome ? GROUP_FILL : undefined,\n      level,\n    }\n  );\n}\n\nfunction pageStream(\n  table: ExportTable,\n  rowIndices: readonly number[],\n  ctx: DrawContext,\n  extras: { title?: string; page: number; pageCount: number }\n): string {\n  const parts: string[] = [];\n  if (extras.title) parts.push(drawTitle(extras.title, ctx));\n  let y = contentTop(ctx.box, Boolean(extras.title));\n  parts.push(drawHeaderRow(table, ctx, y));\n  y -= HEADER_H;\n  for (const index of rowIndices) {\n    parts.push(drawBodyRow(table, index, ctx, y));\n    y -= ROW_H;\n  }\n  parts.push(drawFooter(extras.page, extras.pageCount, ctx));\n  return parts.join(\"\");\n}\n\nfunction xrefLine(offset: number, gen: number, inUse: boolean): string {\n  const off = String(offset).padStart(10, \"0\");\n  const g = String(gen).padStart(5, \"0\");\n  const flag = inUse ? \"n\" : \"f\";\n  return `${off} ${g} ${flag} \\n`;\n}\n\nfunction streamObject(body: string): string {\n  const bytes = ascii(body);\n  return `<< /Length ${String(bytes.byteLength)} >>\\nstream\\n${body}\\nendstream`;\n}\n\nfunction pageObject(\n  contentId: number,\n  box: PageBox,\n  fontResources: string\n): string {\n  return (\n    \"<< /Type /Page /Parent 2 0 R \" +\n    `/MediaBox [0 0 ${String(box.width)} ${String(box.height)}] ` +\n    `/Contents ${String(contentId)} 0 R ` +\n    `/Resources << /Font ${fontResources} >> >>`\n  );\n}\n\n/**\n * The document title in the `/Info` dictionary.\n *\n * A literal string is WinAnsi, which is all a Latin title needs and is\n * what this has always written. A title the built-in face cannot spell\n * goes as UTF-16 instead, so a reader's window caption and a file\n * manager's preview show the words rather than question marks.\n */\nfunction infoTitle(title: string, face: TextFace): string {\n  return face.embedded ? utf16BeHex(title) : pdfLiteral(title);\n}\n\nfunction compilePdf(\n  title: string,\n  streams: readonly string[],\n  box: PageBox,\n  face: TextFace\n): Uint8Array<ArrayBuffer> {\n  const kids: string[] = [];\n  const pageBodies: PdfBody[] = [];\n  // Font objects go after the pages, so their ids are only known once the\n  // page count is.\n  const firstFontId = 6 + streams.length * 2;\n  const fontResources = face.fontResources(firstFontId);\n  streams.forEach((stream, index) => {\n    const pageId = 6 + index * 2;\n    const contentId = pageId + 1;\n    kids.push(`${String(pageId)} 0 R`);\n    pageBodies.push(\n      pageObject(contentId, box, fontResources),\n      streamObject(stream)\n    );\n  });\n  const extras = face.extraObjects(firstFontId);\n  const objects: PdfBody[] = [\n    \"<< /Type /Catalog /Pages 2 0 R >>\",\n    `<< /Type /Pages /Kids [${kids.join(\" \")}] /Count ${String(streams.length)} >>`,\n    \"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>\",\n    \"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>\",\n    `<< /Title ${infoTitle(title, face)} /Producer (AdaptTable) >>`,\n    ...pageBodies,\n    ...extras,\n  ];\n  const header = new Uint8Array([\n    0x25, 0x50, 0x44, 0x46, 0x2d, 0x31, 0x2e, 0x34, 0x0a, 0x25, 0xe2, 0xe3,\n    0xcf, 0xd3, 0x0a,\n  ]);\n  const chunks: Uint8Array[] = [header];\n  const offsets = [0];\n  let offset = header.byteLength;\n  objects.forEach((body, index) => {\n    const bytes = concatBytes([\n      ascii(`${String(index + 1)} 0 obj\\n`),\n      typeof body === \"string\" ? ascii(body) : body,\n      ascii(\"\\nendobj\\n\"),\n    ]);\n    offsets.push(offset);\n    chunks.push(bytes);\n    offset += bytes.byteLength;\n  });\n  let xref = `xref\\n0 ${String(objects.length + 1)}\\n`;\n  xref += xrefLine(0, 65535, false);\n  for (let i = 1; i < offsets.length; i++) {\n    xref += xrefLine(offsets[i] ?? 0, 0, true);\n  }\n  const trailer =\n    `trailer\\n<< /Size ${String(objects.length + 1)} /Root 1 0 R ` +\n    `/Info 5 0 R >>\\nstartxref\\n${String(offset)}\\n%%EOF\\n`;\n  chunks.push(ascii(xref), ascii(trailer));\n  return concatBytes(chunks);\n}\n\nfunction makeContext(\n  table: ExportTable,\n  box: PageBox,\n  rtl: boolean,\n  face: TextFace\n): DrawContext {\n  const usable = box.width - MARGIN * 2;\n  const widths = columnWidths(table, usable);\n  return {\n    box,\n    colWidths: widths,\n    colXs: columnXs(widths, MARGIN, rtl),\n    rtl,\n    face,\n  };\n}\n\nfunction faceFor(font: PdfWriterOptions[\"font\"]): TextFace {\n  return font === undefined ? standardFace() : embeddedFace(parseSfnt(font));\n}\n\nfunction pdfBytes(\n  table: ExportTable,\n  options: PdfWriterOptions\n): Uint8Array<ArrayBuffer> {\n  const box = pageBox(options.pageSize);\n  const rtl = resolvePrintDirection(options.direction) === \"rtl\";\n  const face = faceFor(options.font);\n  const ctx = makeContext(table, box, rtl, face);\n  const pages = paginate(\n    table.rows.length,\n    table.rowMeta,\n    box,\n    options.pageBreak,\n    Boolean(options.title)\n  );\n  const streams = pages.map((rows, index) =>\n    pageStream(table, rows, ctx, {\n      title: index === 0 ? options.title : undefined,\n      page: index + 1,\n      pageCount: pages.length,\n    })\n  );\n  return compilePdf(options.title ?? \"Table\", streams, box, face);\n}\n\nfunction titleFromFilename(filename: string): string {\n  const stem = filename.replace(/\\.[^.]+$/, \"\");\n  return stem === \"\" ? filename : stem;\n}\n\n/**\n * Build a PDF for the given rows and columns.\n *\n * Cell values resolve exactly as they do for CSV and XLSX — a column's\n * `exportValue` first, then its accessor — so the same table produces the\n * same data in every format. Page breaks, column widths and group\n * structure are taken from the resolved view.\n *\n * @typeParam TRow - The row type.\n * @param options - Rows, columns, and how the pages should look.\n * @returns The PDF bytes, ready to download.\n */\nexport function buildTablePdf<TRow>(\n  options: {\n    rows: readonly TRow[];\n    columns: readonly ColumnDef<TRow>[];\n    view?: readonly ExportViewEntry<TRow>[];\n    summary?: Readonly<Partial<Record<string, unknown>>>;\n  } & PdfWriterOptions\n): Uint8Array<ArrayBuffer> {\n  return pdfBytes(\n    buildExportTable(options.rows, options.columns, {\n      view: options.view,\n      summary: options.summary,\n    }),\n    options\n  );\n}\n\n/** The MIME type every reader registers for `.pdf`. */\nconst PDF_MIME = \"application/pdf\";\n\n/**\n * The PDF writer, for the `exportCsv` prop's `writer` option:\n *\n * ```tsx\n * import { pdfWriter } from \"@adapttable/core/pdf\";\n *\n * <DataTable exportCsv={{ writer: pdfWriter(), scope: \"selected\" }} … />\n * ```\n *\n * Every scope works unchanged — page, all, selected, range, and any\n * column subset — because the scope is resolved before a writer is asked\n * for anything. This is the production default for a downloaded PDF.\n * Print (Unicode, RTL chrome, the browser's own page breaks) is\n * {@link openPrintLayout}, not a writer: `downloadExportFile` cannot\n * open a dialog.\n *\n * @param options - Title, direction, paper and page-break behaviour.\n * @returns A writer to hand to `exportCsv`.\n */\nexport function pdfWriter(options?: PdfWriterOptions): ExportWriter {\n  return {\n    extension: \"pdf\",\n    build: ({ table, filename }) => ({\n      parts: [\n        pdfBytes(table, {\n          ...options,\n          title: options?.title ?? titleFromFilename(filename),\n          direction: options?.direction,\n        }),\n      ],\n      mimeType: PDF_MIME,\n      text: \"\",\n    }),\n  };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,MAAMA,eAAe,IAAIC,IAAqB;CAC5C,CAAC,MAAQ,CAAC,KAAM,CAAC;CACjB,CAAC,MAAQ,CAAC,OAAQ,KAAM,CAAC;CACzB,CAAC,MAAQ,CAAC,OAAQ,KAAM,CAAC;CACzB,CAAC,MAAQ,CAAC,OAAQ,KAAM,CAAC;CACzB,CAAC,MAAQ,CAAC,OAAQ,KAAM,CAAC;CACzB,CAAC,MAAQ;EAAC;EAAQ;EAAQ;EAAQ;CAAM,CAAC;CACzC,CAAC,MAAQ,CAAC,OAAQ,KAAM,CAAC;CACzB,CAAC,MAAQ;EAAC;EAAQ;EAAQ;EAAQ;CAAM,CAAC;CACzC,CAAC,MAAQ,CAAC,OAAQ,KAAM,CAAC;CACzB,CAAC,MAAQ;EAAC;EAAQ;EAAQ;EAAQ;CAAM,CAAC;CACzC,CAAC,MAAQ;EAAC;EAAQ;EAAQ;EAAQ;CAAM,CAAC;CAC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