Webview to display pdf file in offline mode

1.3k Views Asked by At

Using webview the following code will execute fine on online and it will display the PDF file. After that if i goes to offline it will not display the cached pdf file.

mWebview.getSettings().setJavaScriptEnabled(true);
String pdfStr="https://www.sample.structure.first.pdf";
mWebview.loadUrl("https://docs.google.com/gview?embedded=true&url=" + pdfStr);

But i need to cache the pdf and display it on offline mode also. Anybody have any idea about this?

1

There are 1 best solutions below

1
On

You can save your work in cache of Web view using following:

WebView webView = new WebView( context );
webView.getSettings().setAppCacheMaxSize( 10 * 1024 * 1024 );
webView.getSettings().setAppCachePath( getApplicationContext().getCacheDir().getAbsolutePath() );
webView.getSettings().setAllowFileAccess( true );
webView.getSettings().setAppCacheEnabled( true );
webView.getSettings().setJavaScriptEnabled( true );
webView.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT );

if ( !isNetworkAvailable() ) { 
    webView.getSettings().setCacheMode( WebSettings.LOAD_CACHE_ELSE_NETWORK );
}

webView.loadUrl( "your_url" );

Add this method to check if network is available:

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService( CONNECTIVITY_SERVICE );
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

Add these permissions in your manifest :

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