Jetpack Compose PDF Library

Since PSPDFKit for Android version 8.0, our SDK exposes Jetpack Compose-specific APIs out of the box. This makes dealing with PSPDFKit in a Jetpack Compose app easier, and it doesn’t require you to wrap PdfFragment yourself if you want to go the Compose route.

The main entry point is the DocumentView composable. DocumentView wraps the functionality of PdfUiFragment using the AndroidView composable.

Displaying a Document

To show a document, use the DocumentView composable function as part of your layout. You can load a document using the overload of DocumentView that expects a Uri:

setContent {
    Surface {
        val documentUri = remember { getDocumentUri() }
        DocumentView(
            documentUri = documentUri,
            modifier = Modifier
                .height(100.dp)
                .padding(16.dp)
        )
    }
}

Advanced Use

The DocumentView composable has the expected Modifier parameter, which allows you to control how it’ll be displayed inside your layout. On top of that, you can also provide a DocumentState. This object is a wrapper that allows you to modify the PdfActivityConfiguration used to display the document. It also exposes operations for verifying and updating the current page of the displayed document.

The correct way of instantiating a DocumentState is via the rememberDocumentState method. Here’s how to use the DocumentView composable after hoisting the DocumentState to control the UserInterfaceViewMode, and how to ensure the DocumentView only recomposes when another property changes:

setContent {
    Surface {
        var hideInterfaceElements by remember { mutableStateOf(false) }

        // Configuration to hide the interface.
        val pdfActivityConfiguration = remember(hideInterfaceElements) {

            val userInterfaceViewMode =
                if (hideInterfaceElements) UserInterfaceViewMode.USER_INTERFACE_VIEW_MODE_HIDDEN
                else UserInterfaceViewMode.USER_INTERFACE_VIEW_MODE_AUTOMATIC

            PdfActivityConfiguration
                .Builder(this)
                .setUserInterfaceViewMode(userInterfaceViewMode)
                .build()
        }

        val documentState = rememberDocumentState(documentUri, pdfActivityConfiguration)
        DocumentView(
            documentState = documentState,
            modifier = Modifier
                .height(100.dp)
                .padding(16.dp)
        )
    }
}

Exploring Further

For more details on how to integrate DocumentView, look at the Jetpack Compose example in the Catalog example project. You might also want to read our blog post on how to display documents in Compose, along with the reference documentation.