[Android] How to open PDF Viewer from my app?
Posted in Android Updated on .
Written by Robert Vojta
PDF Viewer implements Intents, which allows you to open PDF files programmatically.
To open a PDF file from your application, you can use this Kotlin snippet:
// Get your document URI.
val uri = Uri.fromFile(documentFile)
val mime = "application/pdf"
// Prepare an implicit intent.
val intent = Intent().apply {
action = Intent.ACTION_VIEW
setDataAndType(uri, mime)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
// Find PDF Viewer's document activity.
val viewerPackageName = "com.pspdfkit.viewer"
val viewerActivity = context.packageManager
.queryIntentActivities(intent, PackageManager.MATCH_ALL)
.map { it.activityInfo }
.firstOrNull { it.packageName == viewerPackageName }
// This check ensures that PDF Viewer was found on the device.
viewerActivity?.let {
// Update the intent making it explicitly use PDF Viewer.
val viewerComponent = ComponentName(it.packageName, it.name)
intent.setComponent(viewerComponent)
}
context.startActivity(intent)