在App中显示PDF文件

Lai*_*ire 6 pdf android

我发现这两种可能性来显示pdf文件.

  1. 使用以下命令打开webView:

    webView.loadUrl("https://docs.google.com/gview?embedded=true&url="+uri);

  2. 使用extern App打开pdf文件:

    Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(不过outFile), "应用/ PDF"); intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); startActivity(意向);

他们都工作.但我的问题是pdf仅供内部使用,在两个示例中,用户可以下载或将其保存在另一个文件夹中.

我知道iOS开发中的框架,我正在寻找适用于Android的解决方案.

GvS*_*rma 10

Android现在提供PDF API,很容易在应用程序中呈现pdf内容.

你可以在这里找到细节

下面是要从assets文件夹中的pdf文件呈现的示例代码段.

    private void openRenderer(Context context) throws IOException {
    // In this sample, we read a PDF from the assets directory.
    File file = new File(context.getCacheDir(), FILENAME);
    if (!file.exists()) {
        // Since PdfRenderer cannot handle the compressed asset file directly, we copy it into
        // the cache directory.
        InputStream asset = context.getAssets().open(FILENAME);
        FileOutputStream output = new FileOutputStream(file);
        final byte[] buffer = new byte[1024];
        int size;
        while ((size = asset.read(buffer)) != -1) {
            output.write(buffer, 0, size);
        }
        asset.close();
        output.close();
    }
    mFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
    // This is the PdfRenderer we use to render the PDF.
    if (mFileDescriptor != null) {
        mPdfRenderer = new PdfRenderer(mFileDescriptor);
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:此片段是来自谷歌开发者提供的样本.


Jay*_*dev 5

许多库可用于在您自己的应用程序中显示 pdf。

有关使用的工作示例android-pdfView,请参阅此博客文章。它演示了库的基本用法,通过垂直和水平滑动将 pdf 显示到视图上。

pdfView = (PDFView) findViewById(R.id.pdfView);
pdfView.fromFile(new File("/storage/sdcard0/Download/pdf.pdf")).defaultPage(1).enableSwipe(true).onPageChange(this).load();
Run Code Online (Sandbox Code Playgroud)

  • Android API 19 现在提供了在应用程序内呈现 pdf 内容的可行性,因此不需要第 3 方 SDK。 (2认同)