【问题标题】:Converting a byte array to a pdf file then saving it将字节数组转换为pdf文件然后保存
【发布时间】:2020-09-04 21:15:16
【问题描述】:

我正在使用 Kotlin Android 应用程序访问 API 端点。在这个 API 调用中,我返回一个字节数组。我希望看到的是一种将字节数组转换为pdf文件并保存在手机下载文件夹中的方法。

    private suspend fun getIDCard(sessionID: String?, carriermemid: String?): ByteArray? {
        var results: String = ""

        val postData = "{\"sessionid\": \" $sessionID\"}"
        val outputStreamWriter: OutputStreamWriter

        var byteArray: ByteArray? = null
        val url: URL = URL(idURL + carriermemid)
        val conn: HttpURLConnection = url.openConnection() as HttpURLConnection

        try {
            conn.setRequestProperty(apiConfig.typeKey, apiConfig.typeValueJSON)
            conn.setRequestProperty("Accept", "application/json")
            conn.setRequestProperty("sessionid", sessionID)
            conn.requestMethod = apiConfig.methodGet


            val responseCode: Int = conn.responseCode
            println("Response Code :: $responseCode")
            //returning 404
            return if (responseCode == HttpURLConnection.HTTP_OK) {// connection ok
                var out: ByteArrayOutputStream? = ByteArrayOutputStream()
                val `in`: InputStream = conn.inputStream
                var bytesRead: Int
                val buffer = ByteArray(1024)
                while (`in`.read(buffer).also { bytesRead = it } > 0) {
                    out!!.write(buffer, 0, bytesRead)
                }
                out!!.close()
                byteArray = out.toByteArray()
                return byteArray

            } else {
                return byteArray
            }

        } catch (ex: Exception) {
            ex.printStackTrace()
        } finally {
            conn.disconnect()
        }
        return byteArray
    }

【问题讨论】:

  • convert the byte array to a pdf file and save it in the phones download folder. 字节数组中有什么可以转成pdf的?我认为字节数组将包含pdf,您所要做的就是将数组中的字节保存到文件中,您就完成了。
  • @blackapps 字节数组确实包含 pdf。至于我如何寻找例子。 :facepalm:
  • 所以基本上你的问题是:如何将文件存储在全局下载文件夹中?
  • @tynn 将字节数组转换为文件以存储在全局下载中。

标签: android arrays pdf kotlin pdf-generation


【解决方案1】:

这将获取Android下载目录并将字节数组写入PDF文件(假设字节数组包含PDF)。将 File.createTempFile 更改为您喜欢的任何文件(您不需要创建临时文件):

fun writeBytesAsPdf(bytes : ByteArray) {
   val path = requireContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
    var file = File.createTempFile("my_file",".pdf", path)
    var os = FileOutputStream(file);
    os.write(bytes);
    os.close();
}

您还必须将 android.permission.WRITE_EXTERNAL_STORAGE 添加到清单中。

【讨论】:

  • 为了避免在 viewModel 中需要上下文,您可以在片段/活动中获取路径并将其保存在 viewModel 中,对于特定用户,它应该是常量。
  • 您也不需要使用 createTemporaryFile,它在“下载”文件夹中可能有效,也可能无效。您可以只使用(或类似的): File(path, "my_file.pdf")
  • 是的,清单已更新,让我尝试摆脱创建临时文件
  • 那也没用。也许是由于权限或字节数组,我会稍微看看
  • 这根本不是解决问题的原因。查看接受的答案。
【解决方案2】:

查看How to download PDF file with Retrofit and Kotlin coroutines?,可以使用:

private const val BUFFER_SIZE = 4 * 1024

private fun copyStreamToFile(inputStream: InputStream, outputFile: File) {
    inputStream.use { input ->
        val outputStream = FileOutputStream(outputFile)
        outputStream.use { output ->
            val buffer = ByteArray(BUFFER_SIZE)
            while (true) {
                val byteCount = input.read(buffer)
                if (byteCount < 0) break
                output.write(buffer, 0, byteCount)
            }
            output.flush()
        }
    }
}

private fun InputStream.saveToFile(file: String) = use { input ->
    File(file).outputStream().use { output ->
        input.copyTo(output)
    }
}

您还应该创建文件。

private fun createFile(context: Context, name: String): File? {
    val storageDir = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.path
    var file = File("$storageDir/$name.pdf")
    return storageDir?.let { file }
}

【讨论】:

    【解决方案3】:

    所以这最终解决了这个问题。差点忘记发这个了。是 resolveinfo 列表和我授予权限的方式让我通过了,但这里是

                        try {
                            val pdfbyte = viewModel.getPDFImage()
                            val path =
                                requireContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
                                    .toString() + File.separator
                            val fileName = "my_idcard.pdf"
                            val storageDir =
                                requireContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.path
                            var file = File("$storageDir/$fileName")
                            var os = FileOutputStream(file);
                            os.write(pdfbyte);
                            os.close();
                            val intent = Intent(Intent.ACTION_VIEW)
                            val uri: Uri = FileProvider.getUriForFile(
                                requireContext(),
                                BuildConfig.APPLICATION_ID + ".provider",
                                file
                            )
                            intent.setDataAndType(uri, "application/pdf")
                            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                            intent.flags = Intent.FLAG_ACTIVITY_NO_HISTORY
                            val resInfoList: List<ResolveInfo> = requireActivity().getPackageManager()
                                .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
    
                            for (resolveInfo in resInfoList) {
                                val packageName = resolveInfo.activityInfo.packageName
                                requireActivity().grantUriPermission(
                                    packageName,
                                    uri,
                                    Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION
                                )
                            }
                            startActivity(intent)
                        } catch (e: ActivityNotFoundException) {
                            println("*************************NO PDF**************************")
                        }
    

    【讨论】:

      猜你喜欢
      • 2017-04-14
      • 2015-09-16
      • 1970-01-01
      • 2016-04-14
      • 1970-01-01
      • 1970-01-01
      • 2012-06-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多