在安卓设备上显示PDF

3
我写了一个返回pdf字节流的C# Web服务。一旦我从我的Android应用程序调用Web服务,我将把响应存储在字节数组中,直到这里我可以做到这一点。但是之后,我需要将该字节数组转换为PDF,然后才能显示它。我有一个菜单页面,一旦按下按钮,就会使用文件名调用Web服务,然后点击按钮后,我应该能够打开PDF。这可行吗?还是有其他更好的解决方案?我在网上查找更好的理解,但是我找不到可以帮助我更好地理解的方法。
谢谢您的建议,但我手头没有PDF,我只有从Web服务获取的字节数组。因此,我现在需要从这个字节数组重新生成PDF并显示它,但我不知道如何做到这一点。

可能是在Android应用程序中显示PDF?的重复问题。 - user180100
请参考以下链接:https://dev59.com/5mkw5IYBdhLWcg3wwdQS 和 https://dev59.com/q2Uq5IYBdhLWcg3wV_Ai。 - user180100
请发布代码。 - karan
https://dev59.com/T3rZa4cB1Zd3GeqP0kqz - karan
如何将字节数组写入文件 https://dev59.com/CGw15IYBdhLWcg3wGn9c - karan
1个回答

0

请尝试按照以下步骤操作

  1. 将字节数组转换为输入流
val inputStream = ByteArrayInputStream(byteArray) 
  • 将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
    }
    

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接