【问题标题】:Display pdf in android在android中显示pdf
【发布时间】:2015-11-22 16:51:03
【问题描述】:

我编写了一个 C# Web 服务,它以字节流的形式返回一个 pdf 作为响应。一旦我从我的 android 应用程序调用 web 服务,我会将响应存储在一个数组字节中,直到我能够做到这一点。但在那之后我需要将该字节数组转换为pdf,我应该能够显示它。我有一个菜单页面,其中一旦按下按钮,就会使用文件名调用 Web 服务,单击按钮我应该能够打开 pdf。这可能吗?还是有其他更好的解决方案?为了更好地理解,我在网上查了一下,但我找不到可以帮助我更好地理解的。

感谢您的建议,但我手头没有 pdf,我只有从 Web 服务获得的数组字节。所以我现在需要从这个字节数组中重新生成 pdf 并显示它,但我不知道该怎么做。

【问题讨论】:

标签: android


【解决方案1】:

尝试按照以下步骤操作

  1. 将字节数组转换为 InputStream
val inputStream = ByteArrayInputStream(byteArray) 
  1. 将 InputStream 保存为 PDF 文件:
    suspend fun saveInputStreamAsPdfFile(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
    }
  1. PdfRenderer显示PDF
var totalPdfPages: Int

fun showPdf(pdfFile: File) {
    val input = ParcelFileDescriptor.open(pdfFile, MODE_READ_ONLY)
    val renderer = PdfRenderer(input)
    val wrapper = PdfRendererWrapper(renderer)
    totalPdfPages = wrapper.getTotalPages()
    showPdfPage(0)
}

fun showPdfPage(currentPageIndex: Int) {
    val pageBitmap = wrapper.getBitmap(currentPageIndex)
    imageView.setImageBitmap(pageBitmap) // Show current page
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-04
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2012-04-11
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    相关资源
    最近更新 更多