如何在Android中的WebView中打开本地PDF文件?

时间:2012-07-23 13:28:36

标签: android pdf webview

我想在WebView中打开本地(SD卡)PDF文件。

我已经尝试过了:

webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setPluginsEnabled(true);
webview.getSettings().setAllowFileAccess(true);
File file = new File(Environment.getExternalStorageDirectory() + "/test.pdf");

final Uri uri = Uri.fromFile(file);

webview.loadUrl(uri.toString());

但它还没有打开它,那么让我知道如何在WebView中打开PDF?

8 个答案:

答案 0 :(得分:23)

我知道,这个问题已经过时了。

但我真的很喜欢Xamarin使用Mozilla的pdf.js的方法。它适用于较旧的Android版本,您不需要特殊的PDF Viewer应用程序,您可以轻松地在应用程序视图层次结构中显示PDF

Git for this: https://mozilla.github.io/pdf.js/

其他默认选项(如标准缩放): https://github.com/mozilla/pdf.js/wiki/Viewer-options

只需将pdfjs文件添加到Assets目录:

enter image description here

并按以下方式调用:

array_push($orderBy, "companyname asc");

if(count($orderBy) > 0) {
   $query = $query." order by ".implode(",", $orderBy);
}

很酷的事情:如果你想减少功能/控制的数量。转到Assets / pdfjs / web / viewer.html文件并将某些控件标记为隐藏。 与

// Assuming you got your pdf file:
File file = new File(Environment.getExternalStorageDirectory() + "/test.pdf");

webview = (WebView) findViewById(R.id.webview);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
settings.setAllowFileAccessFromFileURLs(true);
settings.setAllowUniversalAccessFromFileURLs(true);
settings.setBuiltInZoomControls(true);
webview.setWebChromeClient(new WebChromeClient());
webview.loadUrl("file:///android_asset/pdfjs/web/viewer.html?file=" + file.getAbsolutePath() + "#zoom=page-width");

E.g。如果您不喜欢正确的工具栏:

style="display: none;"

答案 1 :(得分:4)

正如@Sameer在上面的评论中回复的那样,在webview中查看PDF的唯一解决方案是通过Google Docs的在线查看器,该查看器将呈现并向您的应用程序发回可读版本。

此前讨论过

答案 2 :(得分:2)

你做不到。使用Intent,您可以在Acrobat Reader等外部查看器应用程序中打开PDF:

try
{
 Intent intentUrl = new Intent(Intent.ACTION_VIEW);
 intentUrl.setDataAndType(uri, "application/pdf");
 intentUrl.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 mActivity.startActivity(intentUrl);
}
catch (ActivityNotFoundException e)
{
 Toast.makeText(mActivity, "No PDF Viewer Installed", Toast.LENGTH_LONG).show();
}

答案 3 :(得分:1)

经过几个帖子后,我在Quora上遇到了this简单的答案。以下是步骤: -

在gradle文件中添加此依赖项:

compile 'com.github.barteksc:android-pdf-viewer:2.0.3'

<强> activity_main.xml中

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

<强> MainActivity.java

package pdfviewer.pdfviewer;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.shockwave.pdfium.PdfDocument;

import java.util.List;

public class MainActivity extends Activity implements OnPageChangeListener,OnLoadCompleteListener{
    private static final String TAG = MainActivity.class.getSimpleName();
    public static final String SAMPLE_FILE = "sample_pdf.pdf";
    PDFView pdfView;
    Integer pageNumber = 0;
    String pdfFileName;

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


        pdfView= (PDFView)findViewById(R.id.pdfView);
        displayFromAsset(SAMPLE_FILE);
    }

    private void displayFromAsset(String assetFileName) {
        pdfFileName = assetFileName;

        pdfView.fromAsset(SAMPLE_FILE)
                .defaultPage(pageNumber)
                .enableSwipe(true)

                .swipeHorizontal(false)
                .onPageChange(this)
                .enableAnnotationRendering(true)
                .onLoad(this)
                .scrollHandle(new DefaultScrollHandle(this))
                .load();
    }


    @Override    public void onPageChanged(int page, int pageCount) {
        pageNumber = page;
        setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
    }


    @Override    public void loadComplete(int nbPages) {
        PdfDocument.Meta meta = pdfView.getDocumentMeta();
        printBookmarksTree(pdfView.getTableOfContents(), "-");

    }

    public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
        for (PdfDocument.Bookmark b : tree) {

            Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));

            if (b.hasChildren()) {
                printBookmarksTree(b.getChildren(), sep + "-");
            }
        }
    }

}

您必须确保您的资产文件夹包含sample_pdf.pdf(图书馆也支持从Uri和SDCard打开pdf)

enter image description here

快乐编码:)

答案 4 :(得分:0)

从Android OS 5.0(棒棒糖)on-wards ,您可以使用 PdfRenderer instead of webview/library. 您可以使用此类在应用中显示pdf。

如果你想支持低于你的操作系统,你可以使用其他答案中提到的库/其他方法,因为没有原生支持。

docs了解详情,您也可以参考此example

答案 5 :(得分:0)

您可以使用SkewPdfView库从远程或本地URL加载pdf。

首先,在root build.gradle中添加以下内容:

allprojects {
    repositories {
        ...
        maven { url 'https://jitpack.io' }
    }
}

并将SkewPdfView库添加为:

dependencies {
    implementation 'com.github.naya-aastra:SkewPdfView:1.1'
}

现在在您的布局中包括SkewPdfView:

<com.nayaastra.skewpdfview.SkewPdfView
    android:id="@+id/skewPdfView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

将所有本地文件保存在资产文件夹中,然后按以下方式使用SkewPdfView。 以编程方式以以下方式加载PDF文件:

SkewPdfView skewPdfView;
skewPdfView = findViewById(R.id.skewPdfView);
String pdfLink = "LINK TO ASSET FILE";
skewPdfView.loadPdf(pdfLink);

P.S。 SkewPdfView库的链接

SkewPdfView Github Page

答案 6 :(得分:0)

WebView 可以很容易地用于显示来自 Web url 的 PDF 文件,但如果您有本地 PDF 文件,那就很麻烦了。

就我而言,我首先存储了本地文件的引用:-

File file = new File(getExternalFilesDir(null),"your_pdf_file.pdf");

然后我使用 FileProvider 获取了本地 PDF 文件的文件路径 URI,并开始使用可以打开 PDF 文档的现有应用程序打开它:-

try{
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(FileProvider.getUriForFile(BaseActivity.this,BuildConfig.APPLICATION_ID +".provider",file), "application/pdf");
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    startActivity(intent);
    } catch (ActivityNotFoundException e) {
    Toast.makeText(BaseActivity.this,"No Application Available to View PDF",Toast.LENGTH_SHORT).show();
    }

还要使用 FileProvider API,您需要在清单中将其声明为:-

        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>

并将 XML 资源文件夹下的 file_paths.xml 声明为:-

<paths>
    <external-path name="external_files" path="."/>
</paths>

答案 7 :(得分:-1)

WebView无法打开.pdf文件。最流行的解决方案(谷歌文档&#39; url +你在WebView中的网址)只是显示你转换为谷歌文档图片。 但是仍然没有简单的方法从url打开.pdf。