4

How can I save correctly a pdf file from http response on Android? byte stream is received through rest API. I tried this:

try
{
File outputFile = new File("/storage/emulated/0/Android/data/package/files/", "cot.pdf");
FileOutpuStream fos = new FileOutputStream(outputFile);
byte [] bytes = data.getBytes();//byte stream response
fos.write(bytes);
fos.flush();
fos.close();
}
catch(Exception e)
{
e.printStackTrace();
}

and file and data is written, but when pdf is opened, there's only blank pages, what's wrong?

dgama
  • 41
  • 1
  • 2

2 Answers2

0
  fun download_pdf(data : ByteArray){
     val fileOutputStream =     FileOutputStream("/storage/emulated/0/dndinfoways.pdf")
    val inputStream: InputStream = ByteArrayInputStream(data)
    var data: Int
    while (inputStream.read().also { data = it } >= 0) {
        fileOutputStream.write(data)
    }
    inputStream.close()
}
Softlabsindia
  • 791
  • 6
  • 11
0

Try with this use case:

class SaveInputStreamAsPdfFileUseCase {

    suspend operator fun invoke(inputStream: InputStream, applicationContext: Context): File? {
        var outputFile: File? = null
        withContext(Dispatchers.IO) {
            try {
                val directory = ContextCompat.getExternalFilesDirs(applicationContext, "documents").first()
                val outputDir = File(directory, "outputPath")
                outputFile = File(outputDir, UUID.randomUUID().toString() + ".pdf")
                 if (!outputDir.exists()) {
                     outputDir.mkdirs()
                }
                val outputStream = FileOutputStream(outputFile, false)
                inputStream.use { fileOut -> fileOut.copyTo(outputStream) }
                outputStream.close()
            } catch (e: Exception) {
                // Something went wrong
            }
        }
        return outputFile
    }
}
Juan Fraga
  • 434
  • 3
  • 9