AndroidPDFViewer - 我的应用程序无法打开pdf文档

4

我正在使用这个库。我试图加载位于assets中的PDF文件,但无法加载。以下是我的加载代码:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.github.barteksc.pdfviewer.PDFView;

public class MainActivity extends AppCompatActivity {

    private PDFView pdfView;
    private String nameOfPDF = "" + R.string.name_of_pdf;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        pdfView = (PDFView) findViewById(R.id.pdfView);

        pdfView.fromAsset(nameOfPDF).load();
    }
}

以下是相关的XML代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="ru.webant.projects.mypdfviewer.MainActivity">

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

应用程序已运行,但没有任何反应。为什么会发生这种情况?
2个回答

2
因为您没有设置正确的文件名。请看这里:
private String nameOfPDF = "" + R.string.name_of_pdf;

这将导致:nameOfPDF = SomeIdAsString。你想要调用的是getString(),像这样:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    pdfView = (PDFView) findViewById(R.id.pdfView);

    pdfView.fromAsset(getString(R.string.name_of_pdf)).load();
}

如何从URL加载PDF?我使用了pdfView.fromUri(Uri.parse(value)).load();,但在调试时出现了以下错误 PDFView: load pdf error java.io.FileNotFoundException: No content provider: http://example.com/pdf/sample1.pdf - abhilash kaveriappa

1
private String nameOfPDF = "" + R.string.name_of_pdf;

除非您将资产命名为某个较大的、半随机的数字,否则这是不正确的。

如果R.string.name_of_pdf应该是一个字符串资源的标识符,其中包含您的PDF文件的名称,请使用:

private String nameOfPDF = getString(R.string.name_of_pdf);

这个示例项目演示了如何使用AndroidPdfViewer在资产中以及其他位置显示PDF。


如何从URL中显示内容? - abhilash kaveriappa
@abhilashkaveriappa:使用OkHttp下载PDF文件到本地文件(例如在getCacheDir()中),然后显示已下载的PDF。 - CommonsWare

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