如何在Webview中显示pdf文档?

时间:2022-09-04 08:19:05

I want to display pdf contents on webview. Here is my code:

我想在webview上显示pdf内容。这是我的代码:

WebView webview = new WebView(this); 
setContentView(webview);
webview.getSettings().setJavaScriptEnabled(true); 
webview.loadUrl("http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf");

I am getting a blank screen. I have set internet permission also.

我得到一个空白的屏幕。我也设置了互联网许可。

7 个解决方案

#1


140  

You can use Google Docs Viewer to read your pdf online:

您可以使用Google文档查看器在线阅读您的pdf:

WebView webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true); 
String pdf = "http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf";
webview.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf);

#2


28  

If you use the view only url the user is not propted to login to there google account.

如果您使用仅查看网址,则不建议用户登录Google帐户。

https://docs.google.com/viewer?url=http://my.domain.com/yourPdfUrlHere.pdf

#3


6  

Opening a pdf using google docs is a bad idea in terms of user experience. It is really slow and unresponsive.

在用户体验方面,使用谷歌文档打开PDF是一个坏主意。它真的很慢而且没有反应。

Solution after API 21

Since api 21, we have PdfRenderer which helps converting a pdf to Bitmap. I've never used it but is seems easy enough.

从api 21开始,我们有了PdfRenderer,它有助于将pdf转换为Bitmap。我从来没用过它,但看起来很容易。

Solution for any api level

Other solution is to download the PDF and pass it via Intent to a dedicated PDF app which will do a banger job displaying it. Fast and nice user experience, especially if this feature is not central in your app.

其他解决方案是下载PDF并通过Intent将其传递给专用的PDF应用程序,该应用程序将执行显示它的banger工作。快速和良好的用户体验,特别是如果此功能不是您的应用程序的核心。

Use this code to download and open the PDF

使用此代码下载并打开PDF

public class PdfOpenHelper {

public static void openPdfFromUrl(final String pdfUrl, final Activity activity){
    Observable.fromCallable(new Callable<File>() {
        @Override
        public File call() throws Exception {
            try{
                URL url = new URL(pdfUrl);
                URLConnection connection = url.openConnection();
                connection.connect();

                // download the file
                InputStream input = new BufferedInputStream(connection.getInputStream());
                File dir = new File(activity.getFilesDir(), "/shared_pdf");
                dir.mkdir();
                File file = new File(dir, "temp.pdf");
                OutputStream output = new FileOutputStream(file);

                byte data[] = new byte[1024];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();
                return file;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<File>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onNext(File file) {
                    String authority = activity.getApplicationContext().getPackageName() + ".fileprovider";
                    Uri uriToFile = FileProvider.getUriForFile(activity, authority, file);

                    Intent shareIntent = new Intent(Intent.ACTION_VIEW);
                    shareIntent.setDataAndType(uriToFile, "application/pdf");
                    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    if (shareIntent.resolveActivity(activity.getPackageManager()) != null) {
                        activity.startActivity(shareIntent);
                    }
                }
            });
}

}

}

For the Intent to work, you need to create a FileProvider to grant permission to the receiving app to open the file.

要使Intent起作用,您需要创建一个FileProvider来授予接收应用程序打开文件的权限。

Here is how you implement it: In your Manifest:

以下是您如何实现它:在您的清单中:

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">

        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />

    </provider>

Finally create a file_paths.xml file in the resources foler

最后在资源foler中创建一个file_paths.xml文件

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <files-path name="shared_pdf" path="shared_pdf"/>
</paths>

Hope this helps =)

希望这有助于=)

#4


3  

You can use the Mozilla pdf.js project. Basically it will show you the PDF. Take a look at their example.

您可以使用Mozilla pdf.js项目。基本上它会显示PDF。看看他们的例子。

I only use it on the browser (desktop and mobile) and it's working fine.

我只在浏览器(桌面和移动设备)上使用它,它工作正常。

#5


2  

Here load with progressDialog. Need to give WebClient otherwise it force to open in browser:

这里使用progressDialog加载。需要提供WebClient,否则它强制在浏览器中打开:

final ProgressDialog pDialog = new ProgressDialog(context);
    pDialog.setTitle(context.getString(R.string.app_name));
    pDialog.setMessage("Loading...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(false);
    WebView webView = (WebView) rootView.findViewById(R.id.web_view);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            pDialog.show();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            pDialog.dismiss();
        }
    });
    String pdf = "http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf";
    webView.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf);

#6


0  

This is the actual usage limit that google allows before you get the error mentioned in the comments, if it's a once in a lifetime pdf that the user will open in app then i feel its completely safe. Although it is advised to to follow the the native approach using the built in framework in Android from Android 5.0 / Lollipop, it's called PDFRenderer.

这是谷歌在你收到评论中提到的错误之前允许的实际使用限制,如果这是用户将在应用程序中打开的一生一次的pdf,那么我觉得它完全安全。虽然建议在Android 5.0 / Lollipop中使用Android内置框架来遵循原生方法,但它被称为PDFRenderer。

#7


0  

Download source code from here (Open pdf in webview android)

从这里下载源代码(在webview android中打开pdf)

activity_main.xml

activity_main.xml中

<RelativeLayout android:layout_width="match_parent"
                android:layout_height="match_parent"
                xmlns:android="http://schemas.android.com/apk/res/android">

    <WebView
        android:layout_width="match_parent"
        android:background="#ffffff"
        android:layout_height="match_parent"
        android:id="@+id/webview"></WebView>
</RelativeLayout>

MainActivity.java

MainActivity.java

package com.pdfwebview;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

    WebView webview;
    ProgressDialog pDialog;

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

    init();
    listener();
    }

    private void init() {

        webview = (WebView) findViewById(R.id.webview);
        webview.getSettings().setJavaScriptEnabled(true);

        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setTitle("PDF");
        pDialog.setMessage("Loading...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        webview.loadUrl("https://drive.google.com/file/d/0B534aayZ5j7Yc3RhcnRlcl9maWxl/view");

    }

    private void listener() {
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                pDialog.show();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                pDialog.dismiss();
            }
        });
    }
}

#1


140  

You can use Google Docs Viewer to read your pdf online:

您可以使用Google文档查看器在线阅读您的pdf:

WebView webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true); 
String pdf = "http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf";
webview.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf);

#2


28  

If you use the view only url the user is not propted to login to there google account.

如果您使用仅查看网址,则不建议用户登录Google帐户。

https://docs.google.com/viewer?url=http://my.domain.com/yourPdfUrlHere.pdf

#3


6  

Opening a pdf using google docs is a bad idea in terms of user experience. It is really slow and unresponsive.

在用户体验方面,使用谷歌文档打开PDF是一个坏主意。它真的很慢而且没有反应。

Solution after API 21

Since api 21, we have PdfRenderer which helps converting a pdf to Bitmap. I've never used it but is seems easy enough.

从api 21开始,我们有了PdfRenderer,它有助于将pdf转换为Bitmap。我从来没用过它,但看起来很容易。

Solution for any api level

Other solution is to download the PDF and pass it via Intent to a dedicated PDF app which will do a banger job displaying it. Fast and nice user experience, especially if this feature is not central in your app.

其他解决方案是下载PDF并通过Intent将其传递给专用的PDF应用程序,该应用程序将执行显示它的banger工作。快速和良好的用户体验,特别是如果此功能不是您的应用程序的核心。

Use this code to download and open the PDF

使用此代码下载并打开PDF

public class PdfOpenHelper {

public static void openPdfFromUrl(final String pdfUrl, final Activity activity){
    Observable.fromCallable(new Callable<File>() {
        @Override
        public File call() throws Exception {
            try{
                URL url = new URL(pdfUrl);
                URLConnection connection = url.openConnection();
                connection.connect();

                // download the file
                InputStream input = new BufferedInputStream(connection.getInputStream());
                File dir = new File(activity.getFilesDir(), "/shared_pdf");
                dir.mkdir();
                File file = new File(dir, "temp.pdf");
                OutputStream output = new FileOutputStream(file);

                byte data[] = new byte[1024];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();
                return file;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<File>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onNext(File file) {
                    String authority = activity.getApplicationContext().getPackageName() + ".fileprovider";
                    Uri uriToFile = FileProvider.getUriForFile(activity, authority, file);

                    Intent shareIntent = new Intent(Intent.ACTION_VIEW);
                    shareIntent.setDataAndType(uriToFile, "application/pdf");
                    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    if (shareIntent.resolveActivity(activity.getPackageManager()) != null) {
                        activity.startActivity(shareIntent);
                    }
                }
            });
}

}

}

For the Intent to work, you need to create a FileProvider to grant permission to the receiving app to open the file.

要使Intent起作用,您需要创建一个FileProvider来授予接收应用程序打开文件的权限。

Here is how you implement it: In your Manifest:

以下是您如何实现它:在您的清单中:

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">

        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />

    </provider>

Finally create a file_paths.xml file in the resources foler

最后在资源foler中创建一个file_paths.xml文件

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <files-path name="shared_pdf" path="shared_pdf"/>
</paths>

Hope this helps =)

希望这有助于=)

#4


3  

You can use the Mozilla pdf.js project. Basically it will show you the PDF. Take a look at their example.

您可以使用Mozilla pdf.js项目。基本上它会显示PDF。看看他们的例子。

I only use it on the browser (desktop and mobile) and it's working fine.

我只在浏览器(桌面和移动设备)上使用它,它工作正常。

#5


2  

Here load with progressDialog. Need to give WebClient otherwise it force to open in browser:

这里使用progressDialog加载。需要提供WebClient,否则它强制在浏览器中打开:

final ProgressDialog pDialog = new ProgressDialog(context);
    pDialog.setTitle(context.getString(R.string.app_name));
    pDialog.setMessage("Loading...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(false);
    WebView webView = (WebView) rootView.findViewById(R.id.web_view);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            pDialog.show();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            pDialog.dismiss();
        }
    });
    String pdf = "http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf";
    webView.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf);

#6


0  

This is the actual usage limit that google allows before you get the error mentioned in the comments, if it's a once in a lifetime pdf that the user will open in app then i feel its completely safe. Although it is advised to to follow the the native approach using the built in framework in Android from Android 5.0 / Lollipop, it's called PDFRenderer.

这是谷歌在你收到评论中提到的错误之前允许的实际使用限制,如果这是用户将在应用程序中打开的一生一次的pdf,那么我觉得它完全安全。虽然建议在Android 5.0 / Lollipop中使用Android内置框架来遵循原生方法,但它被称为PDFRenderer。

#7


0  

Download source code from here (Open pdf in webview android)

从这里下载源代码(在webview android中打开pdf)

activity_main.xml

activity_main.xml中

<RelativeLayout android:layout_width="match_parent"
                android:layout_height="match_parent"
                xmlns:android="http://schemas.android.com/apk/res/android">

    <WebView
        android:layout_width="match_parent"
        android:background="#ffffff"
        android:layout_height="match_parent"
        android:id="@+id/webview"></WebView>
</RelativeLayout>

MainActivity.java

MainActivity.java

package com.pdfwebview;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

    WebView webview;
    ProgressDialog pDialog;

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

    init();
    listener();
    }

    private void init() {

        webview = (WebView) findViewById(R.id.webview);
        webview.getSettings().setJavaScriptEnabled(true);

        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setTitle("PDF");
        pDialog.setMessage("Loading...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        webview.loadUrl("https://drive.google.com/file/d/0B534aayZ5j7Yc3RhcnRlcl9maWxl/view");

    }

    private void listener() {
        webview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                pDialog.show();
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                pDialog.dismiss();
            }
        });
    }
}