Stirling-Tools/Stirling-PDF · error · Error

Failed to convert image to PDF: ${error instanceof Error ? e

Error message

Failed to convert image to PDF: ${error instanceof Error ? error.message : "Unknown error"}

What it means

The top-level catch in convertImageToPdf that wraps any error thrown inside the function (PDFium allocation failures, decode failure, matrix errors, or saveRawDocument failures) into a single 'Failed to convert image to PDF' message while preserving the original via { cause: error }. Callers of convertImageToPdf only ever see this wrapper, not the inner PDFium-specific messages.

Source

Thrown at frontend/editor/src/core/utils/imageToPdfUtils.ts:172

      // Insert image into page
      m.FPDFPage_InsertObject(pagePtr, imageObjPtr);

      // Generate page content stream
      m.FPDFPage_GenerateContent(pagePtr);
      m.FPDF_ClosePage(pagePtr);

      // Save document
      const pdfBytes = await saveRawDocument(docPtr);
      const pdfFilename = imageFile.name.replace(/\.[^.]+$/, ".pdf");

      return new File([pdfBytes], pdfFilename, { type: "application/pdf" });
    } finally {
      m.FPDF_CloseDocument(docPtr);
    }
  } catch (error) {
    console.error("Error converting image to PDF:", error);
    throw new Error(
      `Failed to convert image to PDF: ${error instanceof Error ? error.message : "Unknown error"}`,
      {
        cause: error,
      },
    );
  }
}

/**
 * Decode an image Blob to RGBA pixel data via canvas.
 */
function decodeImageToRgba(
  imageBlob: Blob,
): Promise<{ rgba: Uint8Array; width: number; height: number } | null> {
  return new Promise((resolve) => {
    const img = new Image();
    const url = URL.createObjectURL(imageBlob);

View on GitHub (pinned to 9ef20dcab8)

Solutions

  1. Inspect error.cause for the specific inner error (decode failure, PDFium allocation, etc.) to identify the real root cause.
  2. Check the browser console — the original error is logged via console.error before re-throw.
  3. Based on the inner cause, apply the corresponding fix (reduce resolution, validate format, free prior documents).
  4. Wrap the call and show the inner cause's message to the user for actionable feedback.

Example fix

// before — caller shows only the generic wrapper
try { await convertImageToPdf(file); }
catch (e) { alert(e.message); }
// after — surface the real cause
try { await convertImageToPdf(file); }
catch (e) {
  const reason = e.cause?.message ?? e.message;
  alert(`Could not convert: ${reason}`);
}
Defensive patterns

Strategy: try-catch

Validate before calling

const CANVAS_DECODABLE = ['image/png', 'image/jpeg', 'image/gif', 'image/bmp', 'image/webp'];
const MAX_PIXELS = 25_000_000;

function canConvertInBrowser(file: File): string | null {
  if (!CANVAS_DECODABLE.includes(file.type)) return 'Unsupported image format.';
  if (file.size === 0) return 'File is empty.';
  return null;
}
const issue = canConvertInBrowser(file);
if (issue) { showUser(issue); return; }

Type guard

function isLikelyConvertible(file: File): boolean {
  return CANVAS_DECODABLE.includes(file.type) && file.size > 0;
}

Try / catch

try {
  const pdf = await convertImageToPdf(file, { imageResolution: 'reduced' });
} catch (e) {
  const cause = (e as Error & { cause?: Error }).cause;
  const reason = cause?.message ?? e.message;
  if (reason.includes('decode')) showUser('Cannot decode this image. Use PNG or JPEG.');
  else if (reason.includes('PDFium') || reason.includes('document') || reason.includes('bitmap'))
    showUser('Image too large for in-browser conversion. Reduce its size or use server-side conversion.');
  else showUser(`Conversion failed: ${reason}`);
}

Prevention

When it happens

Trigger: Any uncaught error inside the try block of convertImageToPdf: errors 72-78 (decode or PDFium failures), a saveRawDocument failure, or any unexpected throw. The catch logs the original to console.error and re-throws a normalized message containing the inner error's message (or 'Unknown error').

Common situations: The user tried to convert an unsupported/corrupt image or an image too large for in-browser PDFium. The PDFium WASM module failed to load. A transient browser memory issue. Any of the inner conditions (72-78) occurred.

Related errors


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