如何从 base64 字符串显示 PDF

How to show PDF from base64 String

我收到一个 PDF 文件的编码 base64 字符串,我想在带有浮动操作按钮的片段中显示它,该按钮可用于保存或打印 pdf。

我已经尝试了 this solution,但对我来说没有成功,因为它在抱怨 exposed beyond app through Intent.getData()。它可能与写访问有关。我的清单中确实有 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>,但我也收到警告 write_external_storage no longer provides write access when targeting android 10+.

无论如何,在该解决方案中,它会先尝试保存 pdf,然后再打开它。有什么办法吗?只是简单地显示 pdf,然后提供一个按钮来保存它?

我要实现的截图:

我使用 this library

解决了我的问题

将以下内容添加到您的 build.gradle

implementation 'com.github.mhiew:android-pdf-viewer:3.2.0-beta.1'

将以下内容添加到您的布局中

<com.github.barteksc.pdfviewer.PDFView
        android:id="@+id/pdfView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@id/app_bar" />

然后简单地解码base64字符串并将其传递给pdfView,如下所示

private fun renderPdf(base64EncodedString: String) = try {
    val decodedString = Base64.decode(base64EncodedString, Base64.DEFAULT)
    binding.pdfView.fromBytes(decodedString).load()
} catch (e: Exception) {
    // handle error
}