1

I'm trying to write a byteArray received from a server. This is my code

private fun writePdf(content: ByteArray) {

        val storageDir = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
        val file = File("${storageDir?.path}/", "${Date().time}Download.pdf")

        try {
//           file.writeBytes(archivo)
            val os = FileOutputStream(file, false)
            os.write(content)
            os.flush()
            os.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        val intent = Intent(Intent.ACTION_VIEW)
        val uri = FileProvider
            .getUriForFile(
                this,
                this.packageName + ".fileprovider",
                file)
        intent.setDataAndType(uri, "application/pdf")
        intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP

        try{
            startActivity(intent)
        }catch (e: Exception){
            e.printStackTrace()
            Toast.makeText(this, "Error", Toast.LENGTH_LONG)
                .show()
        }
    }

The problem is that when the pdf opens it is blank, like nothing has been written.

  • I've tried writing with FileOutputStream and File.writeBytes.
  • I've checked the byteArray (in case is corrupted or something) and it has no problems.
  • I've checked the length() of the file before and after writing, and it's length increases accordingly.

Thanks, any kind of help is appreciated.

navi95
  • 23
  • 5
  • Have you copied the PDF off of the device and compared it with the original? Note that this approach (putting the PDF content in a `ByteArray`) will only work for small PDFs. It would be better if you wrote the data to the file as you downloaded it, such as by using OkHttp and Okio -- see https://stackoverflow.com/a/29012988/115145 and various Kotlin ports in that same question. – CommonsWare Apr 06 '22 at 21:21
  • @CommonsWare Hi, yes i tried that approach but got the same result. I think the problem lies on this method because I tested writing the content of a pdf directly (a pdf in the emulator device) on a new file using my code above and got the same result (the new file is blank). – navi95 Apr 07 '22 at 14:16

1 Answers1

1

I finally found the problem, and solution. Everything with the code above was okay; the problem was that the flags for the intent to visualize the PDF were wrong. Instead of:

intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP

It should be:

intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
navi95
  • 23
  • 5