如何在 Jetpack Compose 中使用 Android PdfViewer

How to use Android PdfViewer in jetpack compose

经过一些研究发现“Android PdfViewer”后,我想在我的应用程序中打开 pdf,但我不知道如何使用 Jetpack Compose 使用互操作性 java图书馆。

这就是我使用 Android PdfViewer 的方式,但它没有呈现 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()
        }
    })
}

它不起作用,所以我制作了一个新的 activity,其中我使用 xml 而不是可组合项。

为了呈现 pdf,我正在使用 Android PdfViewer 库。

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>