Search code examples
androidpdfwebview

Can not open PDF file using WebView


I was trying to show pdf file using a url in webview. Although the WebView is loading webpage like google.com, it does not load anything or throw any exception when I try to load the url of the pdf.

The url loads pdf in google chrome desktop browser, so I guess the problem is not with the url itself.

Here's what I've coded so far:

onCreateView() of Fragment that loads the pdf

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_brochure, container, false);
        webView = view.findViewById(R.id.webView);
//        webView.loadUrl("https://google.com");
        webView.loadUrl("https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf");
//        webView.loadUrl(brochureUrl);
        // Enable Javascript
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(true);

        // Force links and redirects to open in the WebView instead of in a browser
        webView.setWebViewClient(new WebViewClient());
        return view;
    }

Layout (xml file):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/purple_500"
    tools:context=".ui.project_details.project_details_pages.BrochureFragment">

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="28dp"/>

</LinearLayout>

Manifest file (only the portion that I think to be relavant)

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

    <application
        android:allowBackup="true"
        ...
        ...
        ...
        android:supportsRtl="true"
        android:usesCleartextTraffic="true">

What am I missing here?


Solution

  • There some issue while loading pdf with webView. You can use the following code to solve your problem. This method takes the help of drive to view pdf in webView.

    webview.getSettings().setJavaScriptEnabled(true);
    String pdf = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";
    webview.loadUrl("https://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf);