在Android上从字节流创建pdf文件

时间:2017-09-23 17:27:13

标签: java android pdf bytestream

如何在Android上正确保存来自http响应的pdf文件?通过rest API接收字节流。我试过这个:

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();
}

并且文件和数据被写入,但是当打开pdf时,只有空白页,出了什么问题?

2 个答案:

答案 0 :(得分: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()
}

答案 1 :(得分:0)

试试这个用例:

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
    }
}