{"record":{"id":"7a0480f5332e6c83","repo":"Stirling-Tools/Stirling-PDF","slug":"pdfium-failed-to-create-page","errorCode":null,"errorMessage":"PDFium: failed to create page","messagePattern":"PDFium: failed to create page","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"frontend/editor/src/core/services/pdfiumDocBuilder.ts","lineNumber":364,"sourceCode":"  /** Create a new empty PDF document. Drop-in replacement for `PDFDocument.create()`. */\n  static async create(): Promise<PdfiumDocument> {\n    const m = await getPdfiumModule();\n    const docPtr = m.FPDF_CreateNewDocument();\n    if (!docPtr) throw new Error(\"PDFium: failed to create document\");\n    return new PdfiumDocument(m, docPtr);\n  }\n\n  /** Add a new page to the document. */\n  addPage(dimensions: [number, number]): PdfiumPage {\n    const [width, height] = dimensions;\n    const insertIdx = this._pages.length;\n    const pagePtr = this._m.FPDFPage_New(\n      this._docPtr,\n      insertIdx,\n      width,\n      height,\n    );\n    if (!pagePtr) throw new Error(\"PDFium: failed to create page\");\n    const page = new PdfiumPage(this._m, this._docPtr, pagePtr, width, height);\n    this._pages.push(page);\n    return page;\n  }\n\n  /** Embed a standard PDF font. Returns a PdfiumFont for text measurement and drawing. */\n  async embedFont(fontName: string): Promise<PdfiumFont> {\n    if (this._fonts.has(fontName)) return this._fonts.get(fontName)!;\n    const font = new PdfiumFont(fontName);\n    this._fonts.set(fontName, font);\n    return font;\n  }\n\n  /** Embed a PNG image from raw bytes. */\n  async embedPng(bytes: Uint8Array | ArrayBuffer): Promise<PdfiumImage> {\n    return this._decodeImage(\n      bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes),\n      \"image/png\",","sourceCodeStart":346,"sourceCodeEnd":382,"githubUrl":"https://github.com/Stirling-Tools/Stirling-PDF/blob/9ef20dcab80b85041912f045e17a6aea1d08f969/frontend/editor/src/core/services/pdfiumDocBuilder.ts#L346-L382","documentation":"`PdfiumDocument.addPage(dimensions)` calls `FPDFPage_New(docPtr, index, width, height)`. A null return means page creation failed. Unlike document creation, page creation has a concrete precondition: `width`/`height` must be positive finite numbers within PDFium's coordinate range. Zero, negative, NaN, Infinity, or astronomically large values make PDFium refuse the page.","triggerScenarios":"Passing `[0, 0]`, negative dimensions, `NaN` (e.g. from a failed `parseFloat`), `Infinity`, or values outside PDFium's expected point range; calling `addPage` after the document pointer was closed/corrupted; WASM heap exhaustion at page allocation.","commonSituations":"Page dimensions sourced from a malformed PDF page object (e.g. a corrupt `getViewport` returning 0); a calculation that divided by zero; using a closed `PdfiumDocument` whose `_docPtr` was already freed.","solutions":["Validate dimensions before calling `addPage`: `Number.isFinite(width) && Number.isFinite(height) && width > 0 && height > 0`, clamping to sane bounds (e.g. 1–14400 pt).","Guard against using a disposed document: track a `_disposed` flag and throw a clearer error if `addPage` is called after `dispose()`.","On null pagePtr, call `FPDF_GetLastError()` to capture the reason (this code currently does not).","Audit upstream callers for unguarded `parseFloat`/division that could yield NaN."],"exampleFix":"// before\naddPage(dimensions: [number, number]): PdfiumPage {\n  const [width, height] = dimensions;\n  const insertIdx = this._pages.length;\n  const pagePtr = this._m.FPDFPage_New(this._docPtr, insertIdx, width, height);\n  if (!pagePtr) throw new Error(\"PDFium: failed to create page\");\n  ...\n}\n\n// after\naddPage(dimensions: [number, number]): PdfiumPage {\n  const [width, height] = dimensions;\n  if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {\n    throw new Error(`PdfiumDocument.addPage: invalid dimensions [${width}, ${height}]`);\n  }\n  const insertIdx = this._pages.length;\n  const pagePtr = this._m.FPDFPage_New(this._docPtr, insertIdx, width, height);\n  if (!pagePtr) {\n    const err = this._m.FPDF_GetLastError?.() ?? \"unknown\";\n    throw new Error(`PDFium: failed to create page (error ${err})`);\n  }\n  ...\n}","handlingStrategy":"validation","validationCode":"// Validate dimensions before addPage\nfunction validDims(w: number, h: number): boolean {\n  return Number.isFinite(w) && Number.isFinite(h) && w > 0 && h > 0 && w <= 14400 && h <= 14400;\n}","typeGuard":"function isFinitePositiveDimensions(d: [number, number]): boolean {\n  return Array.isArray(d) && d.length === 2 && d.every(n => Number.isFinite(n) && n > 0);\n}","tryCatchPattern":"try {\n  doc.addPage([w, h]);\n} catch (e) {\n  if (e instanceof Error && /invalid dimensions/.test(e.message)) {\n    doc.addPage([595.276, 841.89]); // fall back to A4\n  } else throw e;\n}","preventionTips":["Validate width/height are finite and positive before calling addPage.","Clamp absurd values to a sane page-size range (e.g. 1–14400 pt).","Guard against calling addPage on a disposed PdfiumDocument (track a _disposed flag).","Capture FPDF_GetLastError() on failure for a real cause."],"tags":["pdfium","wasm","page","validation","doc-builder"],"backgroundTag":null,"analyzedSha":"9ef20dcab80b85041912f045e17a6aea1d08f969","analyzedAt":"2026-08-13T22:11:39.827Z","schemaVersion":2},"datasetVersion":"2026-08-14T05:17:29.042Z"}