在pdf.js android webview中打开本地文件(不支持“文件”错误)

时间:2018-11-13 02:35:34

标签: android webview pdfjs

我正在尝试遵循here所述的答案。根据评论,在android webview中使用pdf.js加载本地文件应该可以,但是出现以下错误:

I/chromium: [INFO:CONSOLE(18556)] "Fetch API cannot load file:///android_asset/www/pdfjs/web/tracemonkey.pdf. URL scheme "file" is not supported.", source: file:///android_asset/www/pdfjs/build/pdf.js (18556)
I/chromium: [INFO:CONSOLE(13127)] "Uncaught (in promise) DataCloneError: Failed to execute 'postMessage' on 'Worker': TypeError: Failed to fetch could not be cloned.", source: file:///android_asset/www/pdfjs/build/pdf.js (13127)
    [INFO:CONSOLE(985)] "Uncaught (in promise) Error: An error occurred while loading the PDF.", source: file:///android_asset/www/pdfjs/web/viewer.js (985)

这是我的代码:

class PDFViewerLocalActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.pdfviewer_layout)

        val webView = findViewById(R.id.pdfViewer) as WebView
        webView.settings.javaScriptEnabled = true
        webView.settings.allowFileAccessFromFileURLs = true
        webView.settings.allowUniversalAccessFromFileURLs = true
        webView.settings.builtInZoomControls = true
        webView.webChromeClient = WebChromeClient()

        webView.loadUrl("file:///android_asset/www/pdfjs/web/viewer.html?file=tracemonkey.pdf")

    }
}

enter image description here

1 个答案:

答案 0 :(得分:0)

好的,这是一个愚蠢的问题。我已经在清单中添加了以下权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

但是请注意,对于API 23及更高版本,您必须在运行时请求权限。因此,只需添加代码以请求权限即可。

@TargetApi(23)
fun askPermissions() {
    val permissions = arrayOf("android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE")
    val requestCode = 200
    requestPermissions(permissions, requestCode)
}