Skip to content

Fix IllegalStateException: Already closed in PDF viewer#142

Merged
binary-koan merged 2 commits intomainfrom
fix/pdf-already-closed-exception
Apr 3, 2026
Merged

Fix IllegalStateException: Already closed in PDF viewer#142
binary-koan merged 2 commits intomainfrom
fix/pdf-already-closed-exception

Conversation

@gumclaw
Copy link
Copy Markdown
Contributor

@gumclaw gumclaw commented Apr 1, 2026

Problem

Sentry reported an IllegalStateException: Already closed crash in the PDF viewer on Android (Sentry issue).

The crash originates from io.legere.pdfiumandroid.util.ConfigKt.handleAlreadyClosed when the native PdfiumAndroid rendering thread tries to render a page bitmap after the PDF document has already been closed.

Root cause: When switching between single-page and continuous view modes, the Pdf component uses key={viewMode} which causes React to unmount the old instance and mount a new one synchronously. During unmount, the native PDF document is closed, but the background RenderingHandler thread may still be mid-render, leading to the Already closed exception.

Fix

  • Added a pdfMounted state that explicitly unmounts the Pdf component before changing the view mode
  • The component is remounted on the next animation frame via requestAnimationFrame, giving the native rendering thread time to finish before document resources are released
  • The key={viewMode} is preserved so React still creates a fresh instance with the new configuration

Stack trace

IllegalStateException: Already closed
  RenderingHandler.handleMessage → RenderingHandler.proceed → PdfFile.renderPageBitmap
  → PdfiumCore.renderPageBitmap → PdfPage.renderPageBitmap → PdfPage.close
  → ConfigKt.handleAlreadyClosed

When switching view modes (single/continuous), the Pdf component was
unmounted and remounted via key={viewMode}. This caused a race condition
where the native PdfiumAndroid rendering thread was still rendering a
page bitmap when the document was closed during unmount.

Fix: explicitly unmount the Pdf component before changing the view mode,
then remount on the next animation frame. This gives the native rendering
thread time to complete before the document resources are released.
@binary-koan
Copy link
Copy Markdown
Contributor

Seems worth a try

@binary-koan binary-koan merged commit 9961188 into main Apr 3, 2026
2 checks passed
@binary-koan binary-koan deleted the fix/pdf-already-closed-exception branch April 3, 2026 10:03
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.

3 participants