Displaying docx, excel, pdf files within my app - android

I have an Android app where I want to display files in pdf, excel, docx, txt formats from their respective Urls. I am able to display these files using external apps, but for this, the file is first downloaded and stored on the device and then displayed. I do not want the downloading, I tried using Google document viewer to display the files in a WebView, but since the documents are private, they wont display. I have tried something like below :-
mDocumentUrl = mIntent.getStringExtra(Constant.DOCUMENT_URL);
wvDocumentReader.getSettings().setJavaScriptEnabled(true);
wvDocumentReader.setWebViewClient(new WebViewClient(){
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
super.onPageStarted(view, url, favicon);
wvProgressBar.setVisibility(View.VISIBLE);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)
{
view.loadUrl(request.getUrl().toString());
return true;
}
#Override
public void onPageFinished(WebView view, String url)
{
super.onPageFinished(view, url);
wvProgressBar.setVisibility(View.GONE);
}
});
wvDocumentReader.loadUrl("http://docs.google.com/gview?embedded=true&url="+ mDocumentUrl);
Can anyone suggest a library or a workaround to achieve this? Any help is appreciated.

I think you should use custom library for getting that done .
See : https://github.com/googlesamples/android-PdfRendererBasic
There is also another way for displaying PDF without calling another application
This is a way for showing PDF in android app that is embed PDF document to android webview using support from http://docs.google.com/viewer
pseudo
String doc="<iframe src='http://docs.google.com/viewer?url=+location to your PDF File+'
width='100%' height='100%'
style='border: none;'></iframe>";
a sample is is shown below
String doc="<iframe src='http://docs.google.com/viewer?url=http://www.iasted.org/conferences/formatting/presentations-tips.ppt&embedded=true'
width='100%' height='100%'
style='border: none;'></iframe>";
Code
WebView wv = (WebView)findViewById(R.id.webView);
wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setPluginsEnabled(true);
wv.getSettings().setAllowFileAccess(true);
wv.loadUrl(doc);
//wv.loadData( doc, "text/html", "UTF-8");
and in manifest provide
<uses-permission android:name="android.permission.INTERNET"/>
OR
See this :https://stackoverflow.com/a/43292083/9976418

Related

Webview webcontent not loading

I am trying to load some HTML content (it is a hyperlink) in WebView. But when I click that link nothing is opening. But the same link is working in browser or iOS WebView perfectly.
The code I try:
htmlContent.getSettings().setJavaScriptEnabled(true);
htmlContent.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
htmlContent.loadDataWithBaseURL(null, Html.fromHtml(categoryItemsBean.getContent()).toString(), "text/html", "utf-8", null);
Value of categoryItemsBean.getContent().
<p><a title="كتاب مساعدة الأصدقاء"
href="https://www.manhal.com/platform/stories/demo/index.php?storyid=31"
target="_blank">كتاب مساعدة الأصدقاء </a></p>
Using loadData() method for loading html content on webview
Sample
String unencodedHtml ="<html><body>'%23' is the percent code for ‘#‘ </body></html>";
String encodedHtml = Base64.encodeToString(unencodedHtml.getBytes(),Base64.NO_PADDING);
htmlContent.loadData(encodedHtml, "text/html", "base64");
Convert your html content into base64

loading only a specific element properly in webview

i am trying to load only a specific element in my webview webpage ('contentbody').
but i dont know how to modify my code to load that only. i can block elements in my webview by using this simple javascript.
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
// Removes element which id = 'mastHead'
view.loadUrl("javascript:(function() { "
+ "(elem = document.getElementById('smsform')).parentNode.removeChild(elem); "
+ "})()");
}
An option might be to use Jsoup, to load the HTML page from the website, extract the desired portion of the HTML, and then load just that into your WebView. A small example of how it could be done:
Document doc = Jsoup.connect("http://example.com/").get();
myWebView.loadDataWithBaseURL("http://example.com/", doc.select(".contentbody").first().outerHtml(), "text/html", "UTF-8", null);
With this, you use Jsoup to extract the first item with contentbody class from the HTML, and then directly load it into your WebView.

WebView shows source html with loadDataWithBaseURL, not rendered view

I'm developing an application witch uses WebView to render custom html.
But when I call
loadDAtaWithBaseURL(URL, "<html><h1>TEST</h1></html>", "text/html; charset=utf-8;", "utf-8", null);
it shows html itself (not rendered one) on Genymotion emulator.
On my HTC-one, it works fine with rendered html.
Each result is showed as attached.
Does anyone have a same problem or solution?
Thanks.
Don't enter mimeType below KitKat.
fun getMimeType(): String? {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
"text/html; charset=utf-8"
} else {
null
}
}
loadDAtaWithBaseURL(URL, "<html><h1>TEST</h1></html>", getMimeType(), "utf-8", null);
Java:
if(Build.VERSION.SDK_INT < 21)
webView.loadDataWithBaseURL("about:blank","<html><h1>TEST</h1></html>","text/html", "UTF-8",null);
else
webView.loadDataWithBaseURL("about:blank","<html><h1>TEST</h1></html>","text/html; charset=utf-8", "UTF-8",null);
Regarding the info you have given, i can not have a clear debug for the issue, but this is how it should be done, just to check if you missed something
First, add this line to your activity in the manifest file
Load your data using
public void loadDataWithBaseURL (String baseUrl, String data, String mimeType, String encoding, String historyUrl);
And this is done this way
loadDataWithBaseURL(Url, data, "text/html", "UTF-8", historyUrl)
Note that
If the base URL uses the data scheme, this method is equivalent to calling loadData() and the historyUrl is ignored, and the data will be treated as part of a data: URL. If the base URL uses any other scheme, then the data will be loaded into the WebView as a plain string (i.e. not part of a data URL) and any URL-encoded entities in the string will not be decoded.

Webview InputText not supported in 2.1 and 2.2

In Android we have an url
"http://offers.bartizan.com/we-want-ileads-at-our-shows"
which contains lot of data.
We load this url in webview, In android 2.3 and onwards its working fine means diplay all content of url data but in android 2.1 and 2.2 not display Input Text form.
Here is my code which i used to load url in webview.
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
webView.getSettings().setPluginsEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setRenderPriority(RenderPriority.HIGH);
webView.enablePlatformNotifications();
webView.getSettings().setCacheMode(android.webkit.WebSettings.LOAD_DEFAULT);
webView.loadUrl("http://offers.bartizan.com/we-want-ileads-at-our-shows");
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//if(url.contains("http://www.youtube.com/embed/")){
Log.d("WBC", "This is a YouTube link: " + url);
Log.e("url---Video->", url);
view.loadUrl(url);
return true;
} });
class MyJavaScriptInterface {
public void showHTML(String html) {
String htmlString = html;
Log.e("<---MyJavaScriptInterface---showHTML----->", htmlString);
}
}
Below form not display in android OS. 2.1 and 2.2
First name *
Last name
Email address *
List the names of your shows here. Please include the show manager name, email and phone. *
1) Showing blank area above image
2) Textbox we require

How to pass parameter into HTML file from android

I can show up HTML file content in android webview well.Now how could i pass parameter into HTML file.For ex.my HTML content has an video player
i need to pass dynamic values(URL) into HTML file for playing dynamic video.My HTML file is located on asset folder.How could i do this?
Thanks.
I came upon this problem today, however I needed this to work with UTF-8 encoding, so this was my approach, hopefully it will help someone and clarify some of the previous answers to this question.
HTML:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<h1>%ERR_TITLE%</h1>
<h2>%ERR_DESC%</h2>
</body>
</html>
Java:
String content = IOUtils.toString(getAssets().open("error.html"))
.replaceAll("%ERR_TITLE%", getString(R.string.error_title))
.replaceAll("%ERR_DESC%", getString(R.string.error_desc))
mWebView.loadDataWithBaseURL("file:///android_asset/error.html", content, "text/html", "UTF-8", null);
As for IOUtils:
http://commons.apache.org/proper/commons-io/download_io.cgi
Instead of passing directly the video URL (following you example), i would have used tokens in the Html file. For example:
<embed src="$VIDEO_URL$" autostart="false" />
where the $VIDEO_URL$ will be the token wich will be replaced during the runtime with a real video URL.
Also, since you cannot change the contents of your asset folder during runtime you should load the html file contents into a String variable and use the replace method to replace the token with a real URL and, finally, pass that string to your webview. Something like this:
//The html variable has the html contents of the file stored in the assets folder
//and real_video_url string variable has the correct video url
html = html.replace("$VIDEO_URL$", real_video_url);
webview.loadData(html, "text/html", "utf-8");
If i would like to have something dynamic in my HTML i would have an html with dynamic parts written like this:
<B>%NAME%</B>
Then i would load my HTML:
String template = Utils.inputStreamToString(assets.open("html/template.html"));
then
Then i would replace all dynamics parts with what i want like this:
String data = template.replaceAll("%NAME%", "Alice McGee");
then i would pass it to my webView!
WebView webView = new WebView(this);
webView.loadDataWithBaseURL("file:///android_asset/html/", data, "text/html", "utf-8", null);
I managed to pass variables in a different way.
My problem was that everytime I switched to another app, when coming to the webapp, the webview kept reloading. I guess that's because of the following line in my onCreate() method: myWebView.loadUrl(url); I had the idea to pass these state variables in the url, but as you know it is not possible yet.
What I did was to save the state of some variables using onSaveInstanceState(Bundle outState) {...} and restore them with onRestoreInstanceState(Bundle savedInstanceState){...}.
In onCreate method after setting up myWebView I did the following:
myWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String urlString)
{
Log.i("onPageFinished", "loadVariables("+newURL+")");
if(newURL!="")
myWebView.loadUrl("javascript:loadVariables("+"\""+newURL+"\")");
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
jsInterface = new JSInterface(this,myWebView);
myWebView.addJavascriptInterface(jsInterface, "Android");
if (savedInstanceState != null)
{
// retrieve saved variables and build a new URL
newURL = "www.yoururl.com";
newURL +="?var1=" + savedInstanceState.getInt("key1");
newURL +="?var2=" + savedInstanceState.getInt("key2");
Log.i("myWebApp","NEW URL = " + newURL);
}
myWebView.loadUrl("www.yoururl.com");
So, what it happens is that first I load the page with the default URL (www.yoururl.com) and onPageFinished I call a new javascript method where I pass the variables.
In javascript loadVariables function looks like this:
function loadVariables(urlString){
// if it is not the default URL
if(urlString!="www.yoururl.com")
{
console.log("loadVariables: " + urlString);
// parse the URL using a javascript url parser (here I use purl.js)
var source = $.url(urlString).attr('source');
var query = $.url(urlString).attr('query');
console.log("URL SOURCE = "+source + " URL QUERY = "+query);
//do something with the variables
}
}
here assets means what?
String template = Utils.inputStreamToString(assets.open("html/template.html"));

Categories

Resources