Search code examples
androidkotlinandroid-jetpack-composeandroid-jetpack

How to use Android PdfViewer in jetpack compose


I want to open pdf in my app after some research i found about "Android PdfViewer" but i don't know how to use it jetpack compose using the interoperability as it is java library.

This is how i using Android PdfViewer but it is not rendering the pdf.

@Composable

fun PdfViewer(
modifier: Modifier = Modifier,
dashboardViewModel: DashboardViewModel
) {
AndroidView(
    modifier = modifier
        .fillMaxSize()
        .padding(top = 4.dp, bottom = 24.dp),
    factory = { context ->
        PDFView(context = context, set = null).apply {
            Timber.i(File(dashboardViewModel.pdfUri.value).toUri().toString())
            fromUri(File(dashboardViewModel.pdfUri.value).toUri())
                .load()
        }
    })
}

Solution

  • It was not working so i made an new activity in which i use xml instead of composables.

    To render pdf i am using Android PdfViewer library.

    PdfActivity.kt

    class PdfActivity : AppCompatActivity() {
    
    private lateinit var fileName: String
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_pdf)
    
        val pdfLayout = findViewById<PDFView>(R.id.pdfViewLayout)
        val intent = intent
    
        if (intent.extras != null) {
            fileName = intent.extras?.getString("fileName").toString()
        }
    
        try {
            pdfLayout.fromUri(File("${applicationContext.getExternalFilesDir(null)}/$fileName.pdf").toUri())
                .autoSpacing(true)
                .fitEachPage(true)
                .load()
        } catch (e: Exception) {
            Timber.d(e.message)
        }
    }
    }
    

    activity_pdf.xml

    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".PdfActivity">
    
    <com.github.barteksc.pdfviewer.PDFView
        android:id="@+id/pdfViewLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    
    </androidx.constraintlayout.widget.ConstraintLayout>