{"record":{"id":"8f8877bb4b8ce52a","repo":"Stirling-Tools/Stirling-PDF","slug":"failed-to-convert-image-to-pdf-error-instanceof","errorCode":null,"errorMessage":"Failed to convert image to PDF: ${error instanceof Error ? error.message : \"Unknown error\"}","messagePattern":"Failed to convert image to PDF: (.+?)","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"frontend/editor/src/core/utils/imageToPdfUtils.ts","lineNumber":172,"sourceCode":"\n      // Insert image into page\n      m.FPDFPage_InsertObject(pagePtr, imageObjPtr);\n\n      // Generate page content stream\n      m.FPDFPage_GenerateContent(pagePtr);\n      m.FPDF_ClosePage(pagePtr);\n\n      // Save document\n      const pdfBytes = await saveRawDocument(docPtr);\n      const pdfFilename = imageFile.name.replace(/\\.[^.]+$/, \".pdf\");\n\n      return new File([pdfBytes], pdfFilename, { type: \"application/pdf\" });\n    } finally {\n      m.FPDF_CloseDocument(docPtr);\n    }\n  } catch (error) {\n    console.error(\"Error converting image to PDF:\", error);\n    throw new Error(\n      `Failed to convert image to PDF: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n      {\n        cause: error,\n      },\n    );\n  }\n}\n\n/**\n * Decode an image Blob to RGBA pixel data via canvas.\n */\nfunction decodeImageToRgba(\n  imageBlob: Blob,\n): Promise<{ rgba: Uint8Array; width: number; height: number } | null> {\n  return new Promise((resolve) => {\n    const img = new Image();\n    const url = URL.createObjectURL(imageBlob);\n","sourceCodeStart":154,"sourceCodeEnd":190,"githubUrl":"https://github.com/Stirling-Tools/Stirling-PDF/blob/9ef20dcab80b85041912f045e17a6aea1d08f969/frontend/editor/src/core/utils/imageToPdfUtils.ts#L154-L190","documentation":"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.","triggerScenarios":"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').","commonSituations":"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.","solutions":["Inspect error.cause for the specific inner error (decode failure, PDFium allocation, etc.) to identify the real root cause.","Check the browser console — the original error is logged via console.error before re-throw.","Based on the inner cause, apply the corresponding fix (reduce resolution, validate format, free prior documents).","Wrap the call and show the inner cause's message to the user for actionable feedback."],"exampleFix":"// before — caller shows only the generic wrapper\ntry { await convertImageToPdf(file); }\ncatch (e) { alert(e.message); }\n// after — surface the real cause\ntry { await convertImageToPdf(file); }\ncatch (e) {\n  const reason = e.cause?.message ?? e.message;\n  alert(`Could not convert: ${reason}`);\n}","handlingStrategy":"try-catch","validationCode":"const CANVAS_DECODABLE = ['image/png', 'image/jpeg', 'image/gif', 'image/bmp', 'image/webp'];\nconst MAX_PIXELS = 25_000_000;\n\nfunction canConvertInBrowser(file: File): string | null {\n  if (!CANVAS_DECODABLE.includes(file.type)) return 'Unsupported image format.';\n  if (file.size === 0) return 'File is empty.';\n  return null;\n}\nconst issue = canConvertInBrowser(file);\nif (issue) { showUser(issue); return; }","typeGuard":"function isLikelyConvertible(file: File): boolean {\n  return CANVAS_DECODABLE.includes(file.type) && file.size > 0;\n}","tryCatchPattern":"try {\n  const pdf = await convertImageToPdf(file, { imageResolution: 'reduced' });\n} catch (e) {\n  const cause = (e as Error & { cause?: Error }).cause;\n  const reason = cause?.message ?? e.message;\n  if (reason.includes('decode')) showUser('Cannot decode this image. Use PNG or JPEG.');\n  else if (reason.includes('PDFium') || reason.includes('document') || reason.includes('bitmap'))\n    showUser('Image too large for in-browser conversion. Reduce its size or use server-side conversion.');\n  else showUser(`Conversion failed: ${reason}`);\n}","preventionTips":["Always inspect error.cause for the specific inner failure.","Validate image format and size before calling convertImageToPdf.","Default to imageResolution: 'reduced' for large images.","Offer server-side conversion as a fallback for unsupported or oversized images."],"tags":["image-to-pdf","pdfium","wrapper","error-handling"],"backgroundTag":null,"analyzedSha":"9ef20dcab80b85041912f045e17a6aea1d08f969","analyzedAt":"2026-08-13T22:11:39.827Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}