Skip to content

Conversation

@CorleoneYu
Copy link

Add configurable onImageError callback for image loading failures

This PR adds an optional onImageError callback to Svg2PdfOptions that allows consumers to decide how to handle image loading failures, addressing the feedback from #338.

Changes

  • Add onImageError callback option to Svg2PdfOptions interface
  • Implement error handling in ImageNode for both image data loading and dimension retrieval failures
  • Callback receives imageUrl, error, and element parameters
  • Callback returns boolean: true to interrupt rendering (throw error), false to silently skip the image

Implementation Details

The callback is invoked in two places:

  1. When imageLoadingPromise fails (image data loading)
  2. When getImageDimensions fails (image dimension retrieval)

If the callback returns true, the error is re-thrown to interrupt the rendering process. If it returns false or is not provided, the error is silently ignored and the image is skipped (maintaining backward compatibility).

Usage Example

doc.svg(element, {
  onImageError: (imageUrl, error, element) => {
    console.error('Image load failed:', imageUrl, error)
    return true  // Throw error to interrupt rendering
    // or return false to skip the image
  }
})

Testing

  • Code formatted with prettier
  • Code passes eslint checks
  • Build successful
  • Maintains backward compatibility (no callback = current behavior)

@yGuy
Copy link
Member

yGuy commented Nov 18, 2025

Nice!

How about returning the image data or a promise for it? The implementation can then choose to can handle the image request and return a fallback image.
No need for a true/false as you can just as well decide to throw right in the listener?

  • If nothing/undefined/null is returned the image is silently skipped.
  • I image data or a promise thereof is returned, that image is used instead.
  • And if you throw, it just propagates?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants