WebView can easily be used for displaying PDF file from a web url but if you have local PDF file, then it becomes a pain.
In my case i first stored a reference of my local file:-
File file = new File(getExternalFilesDir(null),"your_pdf_file.pdf");
Then i obtained file path URI of my local PDF file using FileProvider and started an intent for opening it using existing applications that can open PDF documents:-
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(); }
Also to use FileProvider API, you need to declare it in manifest as:-
<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>
And declare file_paths.xml under XML resource folder as:-
<paths> <external-path name="external_files" path="."/> </paths>