0

I am receiving an encoded base64 string for a PDF file and I would to show it inside a fragment with a Floating Action button that can be used for saving or printing the pdf.

I have tried this solution but it didn't work out for me because it was complaining about exposed beyond app through Intent.getData(). It probably has something to do with the write access. I do have <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> in my Manifest but I also have a warning that write_external_storage no longer provides write access when targeting android 10+.

Anyhow, in that solution, it tries to save the pdf first then open it. Is there any way around it? To just simply show the pdf and then provide a button to save it?

Screenshot of what I want to achieve: enter image description here

Mehdi Satei
  • 1,225
  • 9
  • 26
  • If you want in-app PDF rendering, there is `PdfRenderer` in the Android SDK, but it cannot handle arbitrary PDFs. There are also PDF rendering libraries, like [this one](https://github.com/barteksc/AndroidPdfViewer). – CommonsWare Nov 10 '21 at 14:31
  • Thanks @CommonsWare. Can I use base64 String with that lib? – Mehdi Satei Nov 10 '21 at 14:34
  • You would need to decode the base-64 encoded data. This is not significantly different than with any other data that for whatever bizarre reason is base-64 encoded. – CommonsWare Nov 10 '21 at 14:42

1 Answers1

4

I was able to solve my issue by using this library

Add following to your build.gradle

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

Add the following to your layout

<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" />

Then simply decode the base64 string and pass it to the pdfView as follow

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