Skip to content

About

A Kotlin Multiplatform / Compose Multiplatform PDF viewer for Android and iOS, with page swiping, pinch-to-zoom, fullscreen mode, and a simple Compose-first API.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Compose PDF Viewer

A Compose Multiplatform PDF viewer for Android and iOS.

  • Local file, in-memory bytes, or remote URL sources
  • Horizontal or vertical page swiping, or continuous vertical scrolling, with the current page observable and controllable
  • Pinch zoom, pan while zoomed, and double-tap zoom/reset
  • Loading and error states (with retry) that you can replace with your own
  • Right-to-left layouts, localizable page descriptions for accessibility
  • Bounded memory use

Pages are rendered natively (PdfRenderer on Android; PDFKit or Core Graphics on iOS) and everything else (pager, zoom, gestures, states) is shared Compose code. The library depends only on Compose Foundation/UI and kotlinx-coroutines.

Demo

The sample app demonstrates PDF page navigation and vertical paging on both platforms.

Android iOS
Android PDF viewer demo iOS PDF viewer demo

Installation

// build.gradle.kts of your shared module
kotlin {
    sourceSets {
        commonMain.dependencies {
            implementation("io.github.amrelmekawy:pdfviewer:0.1.0")
        }
    }
}

Requirements: Android minSdk 24, iOS (iosArm64, iosSimulatorArm64).

Usage

Load a PDF

Choose a PdfSource for a local file, in-memory bytes, or a remote URL:

PdfSource.File("/absolute/path/to/document.pdf")  // local file on the device
PdfSource.Bytes(bytes)                            // PDF already in memory
PdfSource.Remote("https://example.com/doc.pdf")   // load a remote PDF

PdfSource.Bytes is compared by identity. In a composable, remember the instance so the document stays open across recompositions:

val bytes = remember(data) { PdfSource.Bytes(data) }

For a remote PDF that requires headers:

PdfSource.Remote(
    url = "https://example.com/report.pdf",
    headers = mapOf("Authorization" to "Bearer $token"),
)

On iOS and Android 26+, remote documents are read progressively when the server supports HTTP byte ranges and supplies a strong ETag. Requested blocks are kept in a bounded in-memory cache; this does not create a complete persistent disk copy. Opening a document reads page sizes eagerly, so requests may include metadata for pages that are not yet visible.

Android 24–25, and servers without suitable range responses or a strong ETag, use a full download stored in the app's cache directory. Cached downloads are keyed by URL and every header, so different credentials do not share a file. state.reload() bypasses any existing disk copy and reopens the remote source. Cancelling an open or closing the document cancels active network access; cancelling an individual offscreen render may wait for the read timeout.

On Android, add the internet permission to your app to use PdfSource.Remote:

<uses-permission android:name="android.permission.INTERNET" />

Display the document

Pass the source to rememberPdfViewerState, then display it with PdfViewer:

@Composable
fun DocumentScreen(path: String) {
    val state = rememberPdfViewerState(PdfSource.File(path))
    PdfViewer(state, Modifier.fillMaxSize())
}

State and errors

PdfViewerState is hoisted, so you can observe and control the viewer:

val state = rememberPdfViewerState(source, initialPage = 0)
val scope = rememberCoroutineScope()

when (val load = state.loadState) {
    PdfLoadState.Loading -> Unit
    is PdfLoadState.Ready -> Text("${state.currentPage + 1} / ${load.pageCount}")
    is PdfLoadState.Failed -> Text("Failed: ${load.error}")
}

Button(onClick = { scope.launch { state.scrollToPage(state.currentPage + 1) } }) { Text("Next") }

currentPage survives configuration changes. When the source changes, the old document is closed and the new one opened. The document is closed when the state leaves the composition.

Errors are a small sealed type and never contain platform messages (which can leak paths or URLs): NotFound, Network(httpCode), InvalidDocument, PasswordProtected, TooLarge, and Unknown.

Replace the default loading and error UI with slots:

PdfViewer(
    state = state,
    loading = { CircularProgressIndicator() },
    error = { error, retry ->
        Column {
            Text(stringResource(messageFor(error)))
            Button(onClick = retry) { Text("Retry") }
        }
    },
)

Vertical paging

Pages swipe horizontally by default. Pass Orientation.Vertical to swipe up for the next page (still one page at a time):

PdfViewer(state, Modifier.fillMaxSize(), orientation = Orientation.Vertical)

reverseLayout = true puts the next page above instead. The layout direction does not affect vertical paging.

Continuous vertical scrolling

Pass continuousScroll = true to display pages in a continuous vertical list. Each page is sized to the available width and retains its own aspect ratio. currentPage reports the first visible page, and scrollToPage navigates in the list. Page spacing and reverseLayout also apply. In this mode orientation is ignored.

PdfViewer(state, Modifier.fillMaxSize(), continuousScroll = true, pageSpacing = 8.dp)

Right-to-left and accessibility

Horizontal pages follow LocalLayoutDirection: in a right-to-left layout the next page is on the left. Use reverseLayout = true to flip that. Page content is never mirrored.

Each page has the accessibility description "Page X of Y". Pass your own to localize it:

PdfViewer(
    state = state,
    pageContentDescription = { page, count -> "صفحة ${page + 1} من $count" },
)

Fullscreen

The library has no fullscreen mode; because the state is hoisted, you can show the same state in a fullscreen screen and keep the document and current page:

val state = rememberPdfViewerState(source)
var fullscreen by rememberSaveable { mutableStateOf(false) }

if (fullscreen) {
    Box(Modifier.fillMaxSize().background(Color.Black)) {
        PdfViewer(state, Modifier.fillMaxSize())
        Button(onClick = { fullscreen = false }, Modifier.align(Alignment.TopEnd)) { Text("Close") }
    }
} else {
    Column {
        PdfViewer(state, Modifier.weight(1f))
        Button(onClick = { fullscreen = true }) { Text("Fullscreen") }
    }
}

Platform notes

  • Android: uses the framework PdfRenderer (no dependency). In-memory documents are written to a temporary file in the app's cache directory, deleted when closed.
  • iOS: uses PDFKit for local and fully downloaded documents and Core Graphics for progressive documents. Rendered pixels are copied into Skia-owned memory. NSURLSession uses a 30-second request idle timeout.
  • Limits: remote PDFs are capped at 100 MiB. Full-page preview bitmaps are limited to 4096 px per side and 8 megapixels; the preview cache has a 64 MiB budget and, in paged mode, a five-page limit. High-resolution tiles have a separate limit of up to 32 MiB for the active zoomed page; progressive source blocks have a separate limit of up to 4 MiB.

Limitations

Not supported in 0.1.0: password-protected documents (reported as PasswordProtected), text selection and search, annotations, forms, thumbnails, outlines, and desktop or web targets.

Sample

sample/ contains an app for both platforms that shows every source and error:

  • Android: ./gradlew :sample:androidApp:installDebug
  • iOS: open sample/iosApp/iosApp.xcodeproj in Xcode and run.

Development

./gradlew check                                 # tests, iOS simulator tests, lint, ktlint, ABI
./gradlew :pdfviewer:connectedAndroidDeviceTest # real PdfRenderer tests (device/emulator)
./gradlew :pdfviewer:updateKotlinAbi            # after an intended public API change
./gradlew :pdfviewer:dokkaGenerate              # API docs

License

Copyright 2026 Amr Elmekawy

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

About

A Kotlin Multiplatform / Compose Multiplatform PDF viewer for Android and iOS, with page swiping, pinch-to-zoom, fullscreen mode, and a simple Compose-first API.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages