Android webview not generating pdf report on button click - android

I have created a web app in Android studio using WebView. I have loaded a WordPress site in android WebView. The WordPress site exports a pdf report on a button click When i load it on chrome browser.
The website loaded in chrome
When i click on PDF button shows the window
and
and finally it starts downloading the pdf file
and the generated pdf report looks like:
But the problem occurs when i use the Android App created in WebView. When i click on PDF button it does nothing and i get a Debug log
D/cr_Ime: [InputMethodManagerWrapper.java:59] isActive: true
[InputMethodManagerWrapper.java:68] hideSoftInputFromWindow
I have manifest permission set to
uses-permission android:name="android.permission.INTERNET"
Code here
private static final String WEB_URL = "http://workmanager.midzonetechnologies.com/";
webView = findViewById(R.id.webView);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setAllowContentAccess(true);
webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setAllowFileAccessFromFileURLs(true);
webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
webView.getSettings().setBlockNetworkLoads(false);
webView.getSettings().setAppCacheMaxSize( 10 * 1024 * 1024 ); // 10MB
webView.getSettings().setAppCachePath(getApplicationContext().getCacheDir().getAbsolutePath() );
webView.getSettings().setAllowFileAccess( true );
webView.getSettings().setAppCacheEnabled( true );
webView.getSettings().setJavaScriptEnabled( true );
webView.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT );
webView.setWebViewClient(new WebViewClient());
webView.setWebChromeClient(new WebChromeClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(WEB_URL);
Please tell is the problem related to manifest file permission or run time permission, Please give a solution.
The Android app that i created in WebView.

What you are seeing happening in Chrome is:
noticing the downloadable file based on path: mywebsite.com/randomPath/randomFile**.pdf**
request download permissions
download the file to it's local storage
open the PDF file using Google Drive
If you want that behaviour you have to code all those steps in your app.
A fast solution to this is to intercept the url, check if it is a pdf file and then use a browser to open it.
webView.webviewClient = object : WebViewClient() {
#TargetApi(Build.VERSION_CODES.N)
fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest): Boolean {
val url = request.url.toString()
if (url.takeLast(4) == ".pdf") {
startActivity(
Intent(
Intent.ACTION_VIEW,
"https://docs.google.com/gview?embedded=true&url=${request.url}"
)
)
return true
}
return false
}
}

You would probably have to have different steps in here. As #Florin T. stated, you would first have to get the Permission required for your App:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
In the next step you would be detect wether the system can be downloading anything.
This coud be done like so:
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}});
Source here
If you then click on the PDF-Button in your WebView, the system should be handling the download on your phone. This means that you can then be opening your download as if it would have been downloaded via chrome.
In the last step, you would have to get the saved loaction from the download and start an Intent to open it with a local PDF-App. This could be done via android intents.

Related

How to open pdf from url online in Android without download option?

In my app I want the user to read the pdf files inside my app without any option to download them. How can I do this? I am using the following code but not working-
WebView webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginsEnabled(true);
webView.loadUrl("https://docs.google.com/viewer?"+pdf_url);
Is there any other way to do this? If you can do it?
You can open pdf from URL online in Android without a download option.
Kotlin
val path="https://github.github.com/training-kit/downloads/github-git-cheat-sheet.pdf"
activityWebViewBinding.webview.settings.loadWithOverviewMode = true
activityWebViewBinding.webview.settings.javaScriptEnabled = true
val url = "https://docs.google.com/gview?embedded=true&url=$path"
activityWebViewBinding.webview.loadUrl(url)
Java
String path="https://github.github.com/training-kit/downloads/github-git-cheat-sheet.pdf";
webview.settings.setLoadWithOverviewMode(true);
webview.settings.setJavaScriptEnabled(true);
String url = "https://docs.google.com/gview?embedded=true&url="+path;
webview.loadUrl(url);
You can simply launch intent as below
val pdfUrl = "ENTER_PDF_URL_HERE"
val intent: Intent = Intent(Intent.ACTION_VIEW, Uri.parse(pdfUrl))
.addCategory(Intent.CATEGORY_BROWSABLE)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(intent)
This would simply open it up device's pdf viewer app which comes in almost all android devices com.google.android.apps.docs
You can also safeguard this code by querying packages beforehand and adding fallbacks

Xamarin Android WebView download file does nothing

I have a webview that shows a website which i did not make so i dont know the details of how it works.
On this site there are several buttons which download various files which are generated on the fly. Here is an example of the url request used on one of these buttons: test.example.com/Test/Export/Stuff?format=Pdf
This causes a file to be downloaded on my desktop browser and on my phones chrome but nothing happens on my app.
I have scoured the internet searching for a solution but i am unable to find one that works.
I have tried setting DownloadListener as discribed here: https://forums.xamarin.com/discussion/4605/download-file-by-webview but the OnDownloadStart never triggers.
I have also tried intercepting the url request using ShouldOverrideUrlLoading in my custom WebViewClient as descibed in other posts with no luck.
Here is the html code for the button:
<input id="exportPdfButton" class="secondary hover" format="Pdf" value="Download (PDF)" name="exportPdfButton" type="submit">
<script id="dxss_848651839" type="text/javascript">
<!--
var dxo = new MVCxClientButton('exportPdfButton');
dxo.InitGlobalVariable('exportPdfButton');
dxo.SetProperties({'autoPostBack':true,'isNative':true});
dxo.SetEvents({'Click':ExportButtonOnClick});
dxo.AfterCreate();
//-->
</script>
I have set permissions for ACCESS_DOWNLOAD_MANAGER, WRITE_EXTERNAL_STORAGE etc.
Can anyone help me figure out how i can download these files in the app? Otherwise is there any other information i can provide to help?
Can anyone help me figure out how i can download these files in the app?
Firstly, please make sure your WebView has enabled javascript and the WebViewClient is set correctly:
mWebview = FindViewById<WebView>(Resource.Id.mWebview);
mWebview.Download += MWebview_Download;
var client = new WebViewClient();
mWebview.Settings.JavaScriptEnabled = true;
mWebview.SetWebViewClient(client);
mWebview.LoadUrl("your url");
Then in the WebView.Download event use DownloadManager to download the file:
private void MWebview_Download(object sender, DownloadEventArgs e)
{
var url = e.Url;
DownloadManager.Request request = new DownloadManager.Request(Uri.Parse(url));
request.AllowScanningByMediaScanner();
request.SetNotificationVisibility(DownloadManager.Request.VisibilityVisibleNotifyCompleted); //Notify client once download is completed!
request.SetDestinationInExternalPublicDir(Environment.DirectoryDownloads, "CPPPrimer");
DownloadManager dm = (DownloadManager)GetSystemService("download");
dm.Enqueue(request);
Toast.MakeText(ApplicationContext, "Downloading File",ToastLength.Long//To notify the Client that the file is being downloaded
).Show();
}

How do I open another app in my WebView app?

I have an Android app with that displays a mobile website (WebView), in the mobile website there are links redirecting to a PDF, Excel and video files.
When try to open it in my regular browser my phone asks to open it with another app or it start a download, so I can open it afterwards.
But in my WebView app it either doesn't work, no response or it displays a "Page unavailable" error.
Is it even possible?
To handle links in WebView, you can use the shouldOverrideUrlLoading method of WebViewClient class. Consider the following example;
WebView webView = (WebView) findViewById(R.id.infoView);
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// Assuming you are giving link to some PDF file.
if (url.contains(".pdf")) {
// Now do what you want to with the url here
}
return true;
}
}
This way, you can intercept any link tapped in WebView and then do whatever you want.

How to open a PDF file from server in android

I have a requirement where there is a URL = "http://www.example/Open.pdf"
Now from my android application I want to open this PDF file directly in the default PDF viewer.
The moment I click on this link on the webpage, user should be presented with a default PDF viewer opened with this document.
Note: This file should not be stored on the SD card.
How do I proceed for this implementation?
We can open PDF file in the webview without caching it. Write below code in "onCreate" method .
Working code :
String url = "http://www.example.com/abc.pdf";
final String googleDocsUrl = "http://docs.google.com/viewer?url=";
WebView mWebView=new WebView(this);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginsEnabled(true);
mWebView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url){
view.loadUrl(url);
return false; // then it is not handled by default action
}
});
mWebView.loadUrl((googleDocsUrl + url));
setContentView(mWebView);
What happens here is you open the PDF using Google Docs. Best Advantage of using above method is the lazy loading of PDF. Does not matter how heavy the PDF is. Google Docs takes care of it.
You can view the pdf in the WebView using googleDocs.
WebView webView = (WebView) findViewById(R.id.my_webview);
webView.setWebViewClient(new MyWebViewClient());
webView.addView(webView.getZoomControls());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://docs.google.com/gview?embedded=true&url=http://myurl.com/demo.pdf");
There is no way you can open a default PDF view from your application.
If your file is on the server and you want to open it without downloading then this might also pose a greater security concern. If external applications like default adobe reader can access the content on your server, then this is breaking the security framework altogether.
So, best option would be to launch a new instance of browser or webview and show the PDF document in google docs to the user.
This way user can read the document and get back to the recent state of the application as well.
You can view the pdf in the WebView using googleDocs.
WebView webView = (WebView) findViewById(R.id.my_webview);
webView.setWebViewClient(new MyWebViewClient());
webView.addView(webView.getZoomControls());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://docs.google.com/gview?embedded=true&url=http://myurl.com/demo.pdf");
do you have the others solution besides view pdf file using http://docs.google.com/gview?embedded=true&url=http://myurl.com/demo.pdf

How can I make webview use the HTML5 cache manifest?

On Android devices up to and including 4.4.2, the default Browser and Chrome support the HTML5 cache manifest. However, on those same devices, the WebView component does not seem to support the HTML5 cache manifest. Does anybody know how I can make the WebView component support the HTML5 manifest?
webView.getSettings().setDomStorageEnabled(true);
// Set cache size to 8 mb by default. should be more than enough
webView.getSettings().setAppCacheMaxSize(1024*1024*8);
// This next one is crazy. It's the DEFAULT location for your app's cache
// But it didn't work for me without this line
webView.getSettings().setAppCachePath("/data/data/"+ getPackageName() +"/cache");
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
Try this code:
private void enableHTML5AppCache() {
webView.getSettings().setDomStorageEnabled(true);
// Set cache size to 8 mb by default. should be more than enough
webView.getSettings().setAppCacheMaxSize(1024*1024*8);
// This next one is crazy. It's the DEFAULT location for your app's cache
// But it didn't work for me without this line
webView.getSettings().setAppCachePath("/data/data/"+ getPackageName() +"/cache");
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
}
Here the link.
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl)
{
// The magic redirect
if( "http://HTML5app.com/app/".equals(failingUrl) ) {
// main.html is the place we are redirected to by the server if we are online
mWebView.loadUrl("http://HTML5app.com/app/main.html");
return;
}
else if( "http://HTML5app.com/app/main.html".equals(failingUrl) ) {
// The cache failed - We don't have an offline version to show
// This code removes the ugly android's "can't open page"
// and simply shows a dialog stating we have no network
view.loadData("", "text/html", "UTF-8");
showDialog(DIALOG_NONETWORK);
}
}
Above method will be used to handle redirection in offline scenario. [For implementing appcache and path refer previous comment.
Reference Link : HTML5 Cache mechanism in android

Categories

Resources