Android Webview: Display Website With Pdf
In my Xamarin.Android App I am using a WebView to display a website: AXML:
Solution 1:
You can use google docs like this
WebViewwebview= (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
Stringpdf="url_to_your_pdf" ;
webview.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf);
Please refer to the question here.
Now you will also have contents other than pdf and probably a link to pdf somewhere in your site. in that case you can put this method inside shouldOverrideLoadingUrl() method.
Edited based on Comment
- Download html
- change the line containing reference to pdf with iframe - load google docs inside an iframe
- instead of webview.loadUrl() try loadDataWithBaseURL(). - please refer to this answer if you want more information about how to use loadDataWithBaseUrl().
Solution 2:
Put your URL like,
url = "https://drive.google.com/viewerng/viewer?embedded=true&url=" + GetString(Resource.String.your_pdf_url);
Solution 3:
Use this code to open web view and then i have made a Floating Action Button and on the click of it, you can download the pdf view...Make Sure you enter correct URL's
BUT FIRST..MAKE ANOTHER CLASS NAMED PDFVIEW AND WE WILL USE THIS CLASS METHOD'S IN OUR CODE...
CLASS PDFVIEW CODE...
publicclassPdfView {
privatestaticfinalint REQUEST_CODE=101;
/**
* convert webview content into to pdf file
* @param activity pass the current activity context
* @param webView webview
* @param directory directory path where pdf file will be saved
* @param fileName name of the pdf file.
* */publicstaticvoidcreateWebPrintJob(Activity activity, WebView webView, File directory, String fileName, final Callback callback) {
//check the marshmallow permissionif (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
activity.requestPermissions(newString[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
callback.failure();
return;
}
}
StringjobName= activity.getString(R.string.app_name) + " Document";
PrintAttributesattributes=null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
attributes = newPrintAttributes.Builder()
.setMediaSize(PrintAttributes.MediaSize.ISO_A3)
.setResolution(newPrintAttributes.Resolution("pdf", "pdf", 600, 600))
.setMinMargins(PrintAttributes.Margins.NO_MARGINS).build();
}
PdfPrintpdfPrint=newPdfPrint(attributes);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
pdfPrint.print(webView.createPrintDocumentAdapter(jobName), directory, fileName, newPdfPrint.CallbackPrint() {
@Overridepublicvoidsuccess(String path) {
callback.success(path);
}
@OverridepublicvoidonFailure() {
callback.failure();
}
});
}else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
pdfPrint.print(webView.createPrintDocumentAdapter(), directory, fileName, newPdfPrint.CallbackPrint() {
@Overridepublicvoidsuccess(String path) {
callback.success(path);
}
@OverridepublicvoidonFailure() {
callback.failure();
}
});
}
}
}
/**
* create alert dialog to open the pdf file
* @param activity pass the current activity context
* @param title to show the heading of the alert dialog
* @param message to show on the message area.
* @param path file path create on storage directory
*/publicstaticvoidopenPdfFile(final Activity activity, String title, String message, final String path){
//check the marshmallow permissionif (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
activity.requestPermissions(newString[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
return;
}
}
AlertDialog.Builder builder=newAlertDialog.Builder(activity);
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton("Open", newDialogInterface.OnClickListener() {
@OverridepublicvoidonClick(DialogInterface dialog, int which) {
dialog.dismiss();
fileChooser(activity,path);
}
});
builder.setNegativeButton("Dismiss", newDialogInterface.OnClickListener() {
@OverridepublicvoidonClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialogalert= builder.create();
alert.show();
}
/** callback interface to get the result back after created pdf file*/publicinterfaceCallback{
voidsuccess(String path);
voidfailure();
}
/**
* @param activity pass the current activity context
* @param path storage full path
*/privatestaticvoidfileChooser(Activity activity, String path) {
Filefile=newFile(path);
Intenttarget=newIntent("android.intent.action.VIEW");
//Uri uri = FileProvider.getUriForFile(activity, "${applicationId}.com.package.name.fileprovider", file);Uriuri= FileProvider.getUriForFile(activity, activity.getApplicationContext().getPackageName()+ ".fileprovider", file);
target.setDataAndType(uri, "application/pdf");
target.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Intentintent= Intent.createChooser(target, "Open File");
try {
activity.startActivity(intent);
} catch (ActivityNotFoundException var6) {
var6.printStackTrace();
}
}
}
//NOW MAIN CLASS CODE..
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_orders);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
WebView wb = (WebView) findViewById(R.id.webview);
wb.getSettings().setBuiltInZoomControls(true);
Pbar = (ProgressBar) findViewById(R.id.pB1);
WebSettings ws = wb.getSettings();
ws.setJavaScriptEnabled(true);
ws.setDomStorageEnabled(true);
ws.setAllowFileAccess(true);
wb.getSettings().setBuiltInZoomControls(true);
// wb.getSettings().setDisplayZoomControls(false);
wb.clearCache(true);
wb.setWebChromeClient(newWebChromeClient() {
publicvoidonProgressChanged(WebView view, int progress) {
if (progress < 100 && Pbar.getVisibility() == ProgressBar.GONE) {
Pbar.setVisibility(ProgressBar.VISIBLE);
}
Pbar.setProgress(progress);
if (progress == 100) {
Pbar.setVisibility(ProgressBar.GONE);
pdfdownload.setVisibility(View.VISIBLE);
}
}
});
pdfdownload = (FloatingActionButton) findViewById(R.id.pdf);
pdfdownload = (FloatingActionButton) findViewById(R.id.pdf);
pdfdownload.setOnClickListener(newView.OnClickListener() {
@OverridepublicvoidonClick(View view) {
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM + "/ANY_DIRECTORY/");
final ProgressDialog progressDialog = newProgressDialog(context);
progressDialog.setMessage("Please wait");
progressDialog.show();
//PDFView Class MethodPdfView.createWebPrintJob(context, wb, path, fileName, newPdfView.Callback() {
@Overridepublicvoidsuccess(String path) {
progressDialog.dismiss();
PdfView.openPdfFile(context.this, getString(R.string.app_name), "Do you want to open the pdf file?" + fileName, path);
}
@Overridepublicvoidfailure() {
progressDialog.dismiss();
}
});
}
});
wb.setWebViewClient(newWebViewClient() {
publicbooleanshouldOverrideUrlLoading(WebView view, String url) {
// do your handling codes here, which url is the requested url// probably you need to open that url rather than redirect:Log.e("redirectUrl", "" + url);
//CHECK YOUR URL CONDITIONS TO OPEN RIGHT URL FOR PDF, IF ANY..OTHERWISE LOAD DIRECTLYif (url.contains("/guest/home")) {
view.loadUrl(postUrl);
} else {
view.loadUrl(url);
}
returnfalse; // then it is not handled by default action
}
@OverridepublicvoidonPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Log.e("url finished", url);
}
});
wb.setDownloadListener(newDownloadListener() {
publicvoidonDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
Log.e("DOWNLOAD", url + " , " + userAgent + " , " + contentDisposition + " , " + mimetype + " , " + contentLength);
try {
DownloadManager.Request request = newDownloadManager.Request(Uri.parse(newURL[1].trim()));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, file_name);
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Log.e("download", "download fail" + e.toString());
}
}
});
}
Post a Comment for "Android Webview: Display Website With Pdf"