Home > other >  How to convert bytearray to pdf and show it with ACTION_VIEW intent
How to convert bytearray to pdf and show it with ACTION_VIEW intent

Time:11-16

I am receveving a pdf as an encoded base64 String. I would like to show the PDF with ACTION_VIEW intent. How can I do that?

What I have so far is this

val byteArray = Base64.decode(base64String, Base64.DEFAULT)
val file = FileUtils.createFile(requireContext(), "application/pdf")

val fos = FileOutputStream(file)
fos.write(byteArray)
fos.close()

val uri = FileProvider.getUriForFile(requireContext(), requireActivity().getString(R.string.file_provider), file)

val intent = Intent(Intent.ACTION_VIEW)
intent.setDataAndType(uri, "application/pdf")
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
startActivity(intent)

createFile function looks like

fun createFile(context: Context, mimeType: String): File {
    val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
    val fileName = "TMP_"   timeStamp   "_"
    val suffix = "."   MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType) //.pdf
    return context.getExternalFilesDir("Documents")?.let {
        if (!it.exists()) {
            it.mkdir()
        }
        File.createTempFile(fileName, suffix, it)
    } ?: File.createTempFile(fileName, suffix, Environment.getExternalStorageDirectory())
}

The intent starts properly but when I try to open it with a pdf viewer it says the file is corrupted.

CodePudding user response:

I simple changed this

intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)

to

intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)

works fine now!

  • Related