Can not open PDF file using WebView
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.Finally let me know if your problem solved or not
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);
How to open pdf files in webview in pdfactivity?
BINGO!! My issue resolved can open pdf directly using BufferedInputStream
I created two activity, First Activity to load all pdfs in webview. When user clicks the link of pdf, the pdfurl
fetches the url as strings, passes strings to next activity.
PdfActivity.java
final String pdfurl = view.getHitTestResult().getExtra();
Intent intent = new Intent(PdfActivity.this,PdfViewer.class);
intent.putExtra("PDFURL",pdfurl);
startActivity(intent);
Second Activity is PdfViewer, bateksc pdfviewer to load pdf from url, edited as above
PdfViewer.java
package ak.wp.meto.activity;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.TextView;
import android.widget.Toast;
import com.github.barteksc.pdfviewer.PDFView;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import ak.wp.meto.R;
public class PdfViewer extends Activity {
private TextView txt; // You can remove if you don't want this
private PDFView pdf;
String value = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_pdf);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
value = bundle.getString("PDFURL");
}
System.out.println("PRINT PDFVIEWER DATA" +value);
pdf = (PDFView) findViewById(R.id.pdfView); //github.barteksc
txt = findViewById(R.id.txtPdf);
String pdfUrl = value;
try{
new RetrievePdfStream().execute(pdfUrl);
}
catch (Exception e){
Toast.makeText(this, "Failed to load Url :" + e.toString(), Toast.LENGTH_SHORT).show();
}
}
class RetrievePdfStream extends AsyncTask<String, Void, InputStream> {
@Override
protected InputStream doInBackground(String... strings) {
InputStream inputStream = null;
try {
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
if (urlConnection.getResponseCode() == 200) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
}
} catch (IOException e) {
return null;
}
return inputStream;
}
@Override
protected void onPostExecute(InputStream inputStream) {
pdf.fromStream(inputStream).load();
}
}
}
i want to show pdf file in Android Activity with WebView but after run project nothing show up
As the user @CommonsWare say, you can't open a PDF in the webview.
The best solution would be download it and send it across an intent to a PDF dedicated reader app the user should have, or implement a special class to open it inside your own app.
Android - Load PDF inside webview
This could be as simple as:
try
{
Intent intentUrl = new Intent(Intent.ACTION_VIEW);
intentUrl.setDataAndType(url, "application/pdf");
intentUrl.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
myActivity.startActivity(intentUrl);
}
catch (ActivityNotFoundException e)
{
Toast.makeText(myActivity, "No PDF Viewer Installed", Toast.LENGTH_LONG).show();
}
though I've not tried this.
In our apps, we DOWNLOAD the PDF to the apps file system, make it world readable, then pass the path in an Intent to open a PDF viewing app (e.g. Acrobat Reader). Please note that you'd also need to also be concerned with cleaning up these downloaded PDF's!
in your try block put
new DownloadPDFTask().execute(url);
DownloadPDFTask class:
public class DownloadPDFTask extends AsyncTask<String, Void, Integer>
{
protected ProgressDialog mWorkingDialog; // progress dialog
protected String mFileName; // downloaded file
protected String mError; // for errors
@Override
protected Integer doInBackground(String... urls)
{
try
{
byte[] dataBuffer = new byte[4096];
int nRead = 0;
// set local filename to last part of URL
String[] strURLParts = urls[0].split("/");
if (strURLParts.length > 0)
mFileName = strURLParts[strURLParts.length - 1];
else
mFileName = "REPORT.pdf";
// download URL and store to strFileName
// connection to url
java.net.URL urlReport = new java.net.URL(urls[0]);
URLConnection urlConn = urlReport.openConnection();
InputStream streamInput = urlConn.getInputStream();
BufferedInputStream bufferedStreamInput = new BufferedInputStream(streamInput);
FileOutputStream outputStream = myActivity.openFileOutput(mFileName,Context.MODE_WORLD_READABLE); // must be world readable so external Intent can open!
while ((nRead = bufferedStreamInput.read(dataBuffer)) > 0)
outputStream.write(dataBuffer, 0, nRead);
streamInput.close();
outputStream.close();
}
catch (Exception e)
{
Log.e("myApp", e.getMessage());
mError = e.getMessage();
return (1);
}
return (0);
}
//-------------------------------------------------------------------------
// PreExecute - UI thread setup
//-------------------------------------------------------------------------
@Override
protected void onPreExecute()
{
// show "Downloading, Please Wait" dialog
mWorkingDialog = ProgressDialog.show(myActivity, "", "Downloading PDF Document, Please Wait...", true);
return;
}
//-------------------------------------------------------------------------
// PostExecute - UI thread finish
//-------------------------------------------------------------------------
@Override
protected void onPostExecute (Integer result)
{
if (mWorkingDialog != null)
{
mWorkingDialog.dismiss();
mWorkingDialog = null;
}
switch (result)
{
case 0: // a URL
// Intent to view download PDF
Uri uri = Uri.fromFile(myActivity.getFileStreamPath(mFileName));
try
{
Intent intentUrl = new Intent(Intent.ACTION_VIEW);
intentUrl.setDataAndType(uri, "application/pdf");
intentUrl.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
myActivity.startActivity(intentUrl);
}
catch (ActivityNotFoundException e)
{
Toast.makeText(myActivity, "No PDF Viewer Installed", Toast.LENGTH_LONG).show();
}
break;
case 1: // Error
Toast.makeText(myActivity, mError, Toast.LENGTH_LONG).show();
break;
}
}
}
any reference to "myActivity" must be replaced with a reference to your Activity class
Related Topics
How to Store a String Longer Than 4000 Characters in an Oracle Database Using Java/Jdbc
How to Convert a One-Dimensional Array to Two-Dimensional Array in Java
How to Update Only the Incoming Fields in a Model Using Spring Data Jpa
Shifting Characters Within a String
Wrong Answer in Task - Mistake in Algorithm
Arraylist: How Does the Size Increase
How to Check Whether a Field Exists or Not in Mongodb
How to Map Json Field Names to Different Object Field Names
How to Return a HTML Page from a Restful Controller in Spring Boot
Returning Json Object as Response in Spring Boot
Spring Data JPA and Parameters That Can Be Null
Field Required a Bean Which Could Not Be Found in Springboot
How to Get All Members of Ad Group Via Ldap in Java
Jpa:How to Convert a Native Query Result Set to Pojo Class Collection