Stirling-Tools/Stirling-PDF · error · Error

PDFium: failed to create document

Error message

PDFium: failed to create document

What it means

Thrown when the PDFium WASM export `FPDF_CreateNewDocument()` returns a null/zero pointer. PDFium returns null on allocation failure inside the WASM heap — i.e. the module has exhausted its linear memory. The pointer is the root for every assembled page, so processing cannot continue.

Source

Thrown at frontend/editor/src/core/hooks/tools/adjustContrast/useAdjustContrastOperation.ts:45

  canvas.height = viewport.height;
  const ctx = canvas.getContext("2d");
  if (!ctx) throw new Error("Canvas 2D context unavailable");
  await page.render({ canvasContext: ctx, canvas, viewport }).promise;
  return canvas;
}

// Render, adjust, and assemble all pages of a single PDF into a new PDF using PDFium
async function buildAdjustedPdfForFile(
  file: File,
  params: AdjustContrastParameters,
): Promise<File> {
  const m = await getPdfiumModule();
  const arrayBuffer = await file.arrayBuffer();
  const pdf = await pdfWorkerManager.createDocument(arrayBuffer, {});
  const pageCount = pdf.numPages;

  const docPtr = m.FPDF_CreateNewDocument();
  if (!docPtr) throw new Error("PDFium: failed to create document");

  try {
    for (let p = 1; p <= pageCount; p++) {
      const srcCanvas = await renderPdfPageToCanvas(pdf, p, 2);
      const adjusted = applyAdjustmentsToCanvas(srcCanvas, params);
      const ctx = adjusted.getContext("2d");
      if (!ctx) {
        console.warn(
          `[adjustContrast] Skipping page ${p}: failed to get canvas context`,
        );
        continue;
      }

      const imageData = ctx.getImageData(0, 0, adjusted.width, adjusted.height);
      const imgWidth = imageData.width;
      const imgHeight = imageData.height;

      // Since we render at scale 2, the actual PDF page size is half

View on GitHub (pinned to 9ef20dcab8)

Solutions

  1. Stream pages — create, fill, save, and close the output document in batches rather than holding the full docPtr open for every page.
  2. Increase the PDFium WASM initial/maximum memory in the module loader config (e.g. allow memory growth).
  3. Lower the render scale (the main memory driver) so each page bitmap is smaller.
  4. Free per-page bitmaps and image objects promptly (already partly done) and verify no leaks across iterations.

Example fix

// before
const docPtr = m.FPDF_CreateNewDocument();
if (!docPtr) throw new Error("PDFium: failed to create document");

// after — surface size context and bail with a recoverable message
const docPtr = m.FPDF_CreateNewDocument();
if (!docPtr) {
  throw new Error(`PDFium: failed to create document (pages=${pageCount}, wasm heap likely exhausted)`);
}
Defensive patterns

Strategy: validation

Validate before calling

// Check WASM memory headroom before allocating the output document
const mem = m.pdfium.wasmExports as unknown as { memory?: { buffer: ArrayBuffer } };
const remaining = mem.memory ? mem.memory.buffer.byteLength : Infinity;
if (pageCount > 200) {
  // consider batching or lowering scale before calling FPDF_CreateNewDocument
}

Type guard

function isDocPtr(p: number): p is number { return typeof p === "number" && p !== 0; }

Try / catch

try {
  return await buildAdjustedPdfForFile(file, params);
} catch (e) {
  if (e instanceof Error && e.message.startsWith("PDFium: failed to create document")) {
    // retry once at scale 1, then surface a 'document too large' message
  }
  throw e;
}

Prevention

When it happens

Trigger: The adjust-contrast pipeline already decoded the source PDF and rendered pages to canvases at scale 2; for a large PDF the WASM heap is near its limit when a fresh output document is allocated. Also possible if the PDFium module failed to fully initialize (memory grew past the configured maximum).

Common situations: Adjusting contrast on a 100+ page or very high-resolution PDF; running in a tab where other PDFium-using tools already consumed WASM memory; browser memory limits lower than the document demands.

Related errors


AI-assisted analysis of Stirling-Tools/Stirling-PDF@9ef20dcab8 (2026-08-13). Data as JSON: /api/errors/ab49e9a7f23f4836. Report an issue: GitHub.