使用自定义视图从Web打开PDF

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用自定义视图从Web打开PDF相关的知识,希望对你有一定的参考价值。

我需要在自定义视图中从Web打开PDF。我只需要PDF信息和后退按钮。

我见过以下库:https://github.com/barteksc/AndroidPdfViewer

我已经实现了这样,但不起作用。

我该怎么办?

布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ReaderActivity">

    <com.github.barteksc.pdfviewer.PDFView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/pdfView"/>

</LinearLayout>

活动

class ReaderActivity : BaseAppCompatActivity()
{
    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_reader)

        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        pdfView.fromUri(Uri.parse("https://si.ua.es/es/documentos/documentacion/pdf-s/mozilla12-pdf.pdf"))
            .pageSnap(true)
            .load()
    }
}
答案

fromUri()Uri可以使用的ContentResolver,例如content计划。

如果您知道PDF非常小,您可以尝试使用fromStream()而不是fromUri()。否则,您将需要首先下载PDF(例如,到getCacheDir()),然后使用fromFile(),因为如果您尝试使用fromStream(),可能会耗尽内存。

另一答案

这是对我有用的解决方案:

val client = OkHttpClient()
val request = Request.Builder().url("URL TO PDF").build()

client.newCall(request).enqueue(object : Callback
{
    @Throws(IOException::class)
    override fun onResponse(call: Call, response: Response)
    {
        if (!response.isSuccessful)
        {
            throw IOException("Failed to download file: $response")
        }

        val stream = ByteArrayInputStream(response.body()?.bytes())
        pdfView.fromStream(stream).load()
    }

    override fun onFailure(call: Call, e: IOException)
    {
        e.printStackTrace()
    }
})

其中pdfView是从该库导入的元素:https://github.com/barteksc/AndroidPdfViewer

以上是关于使用自定义视图从Web打开PDF的主要内容,如果未能解决你的问题,请参考以下文章

如何让自定义视图观察包含片段的生命周期事件而不是活动?

Android:在自定义 Web 视图中检测并打开外部链接

片段中的按钮自定义视图

如何从 iCloud 打开 PDF

在片段中创建自定义列表视图时出错。必需的活动,找到的片段

在片段中创建自定义列表视图时出错所需活动,找到片段