In my project I have a files:
"MyProject/assets/folder1/image1.jpg"
"MyProject/assets/folder1/index.html".
In webView I need to open index.html (with images).
I trying this code:
String baseUrl = "file:///android_asset/folder1/";
webView.loadDataWithBaseURL(baseUrl, readFileAsString("index.html") , mimeType, "UTF-8", null);
But images don't loading.
If I put images to "assets" directory (MyProject/assets/) and make baseUrl = "file:///android_asset" images are loaded correctly;
How load images not only from root assets directory, but and from assets/folder1?
try like this
WebView webview = (WebView)this.findViewById(R.id.webview);
String html = "<html><head><title>TITLE!!!</title></head>";
html += "<body><h1>Image?</h1><img src=\"icon.png\" /></body></html>";
webview.loadDataWithBaseURL("file:///android_res/drawable/", html, "text/html", "UTF-8", null);
For more information try this link
perfect LoadDataWithBaseurl
I think you have to set the base to assets and add the sub folders to your image src's like this:
webView.loadDataWithBaseURL("file:///android_asset/", readAssetFileAsString("folder1/index.html"), "text/html", "UTF-8", null);
Html:
<img src="folder1/image1.jpg">
This worked for me on Android 5.1
private String readAssetFileAsString(String sourceHtmlLocation)
{
InputStream is;
try
{
is = getContext().getAssets().open(sourceHtmlLocation);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer, "UTF-8");
}
catch(IOException e)
{
e.printStackTrace();
}
return "";
}
try to like this
try {
String filePath = null;
filePath = "Your File path";
Bitmap bitmap = null;
bitmap = BitmapFactory.decodeFile(filePath);
Log.v("Image data-->", "" + bitmap);
imageWidth = bitmap.getWidth();
imageHeight = bitmap.getHeight();
Log.e("Width", "" + imageWidth);
filePath = "file://" + filePath;
String html = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html\";charset=utf-8\"/><title></title></head><body style=\"width:"
+ imageWidth
+ "px; height:"
+ imageHeight
+ "px; background:url("
+ filePath
+ ") no-repeat; position:relative;\">"
+ getDivTag(mapList)
+ "</body></html>";
Log.v("MIS", "" + html);
webview.getSettings().setSupportZoom(true);
webview.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);
System.out.println(html);
} catch (Exception e) {
e.printStackTrace();
}
Have you give internet permission?
<uses-permission android:name="android.permission.INTERNET" />
Related
What is the best way to load a jpeg from an install-time asset pack and show it on a WebView?
I got it working in case the jpeg is a regular asset, however, I couldn't get it working optimally with install-time assets:
WebView webView = this.findViewById(R.id.webView);
String sHtmlTemplate = "<img src='file:///android_asset/files/"+file+".jpg' width='100%'/>";
webView.loadDataWithBaseURL("file:///android_asset/files/", sHtmlTemplate, "text/html", "utf-8", null);
UPDATE:
The solution below works, but it is slow. Is there a way to load images directly from InputStream or install-time assets?
AssetManager assetManager = getAssets();
InputStream is = assetManager.open(songNo + ".jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024000];
int count;
while(-1 != (count = is.read(buffer, 0, buffer.length))) {
baos.write(buffer, 0, count);
}
baos.flush();
byte[] imageRaw = baos.toByteArray();
baos.close();
is.close();
String image64 = Base64.encodeToString(imageRaw, Base64.DEFAULT);
String html = String.format("<img width='100%%25' src='data:image/jpeg;base64,%s' />", image64);
webView.loadData(html, "text/html; charset=UTF-8", null);
Thanks
Perhaps the WebView is not the most optimal way to show a jpg in this case. I ended up using another control:
com.ortiz.touchview.TouchImageView touchView = this.findViewById(R.id.touchImageView);
try {
AssetManager assetManager = getAssets();
InputStream is = assetManager.open(songNo + ".jpg");
Drawable d = Drawable.createFromStream(is,"src");
touchView.setImageDrawable(d);
}catch(Exception e){
Log.i("xxx", e.getMessage());
}
I have a very complex bug: in my application, I use in webview that display local images. until version '76.0.3809.111' of the webview, everything was work perfectly but from this version when I'm trying to display those images I get "Failed to load resource: net::ERR_UNKNOWN_URL_SCHEME". This error occurs only in the first run when I close the application and restart it everything is working fine.
Additionally when I set settings.setAppCacheEnabled(false) also everything is working perfectly.
When I debug my application I noticed that in the first time (that the images not loaded) the "shouldInterceptRequest" methods not calling.
this is my settings of the webview :
WebSettings settings = wv.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
wv.addJavascriptInterface(jsHandler, "cpjs");
settings.setDomStorageEnabled(true);
String PACKAGE_NAME = ctx.getPackageName();
settings.setDatabaseEnabled(true);
settings.setDatabasePath("/data/data/" + PACKAGE_NAME + "/databases/");
settings.setAppCacheMaxSize(1024 * 1024 * 16);
settings.setAppCachePath(ctx.getCacheDir().getAbsolutePath());
settings.setAllowFileAccess(true);
settings.setAppCacheEnabled(true);
settings.setLightTouchEnabled(false);
settings.setSupportZoom(false);
settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
//Allow to redirect https to http for downloading content
if (Build.VERSION.SDK_INT >= 21) {
settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
KsLog.i(TAG, "WebView settings, MIXED_CONTENT_ALWAYS_ALLOW set");
}
settings.setSavePassword(false);
settings.setLightTouchEnabled(false);
settings.setSupportZoom(false);
wv.setScrollContainer(false);
wv.setHorizontalScrollBarEnabled(false);
wv.setVerticalScrollBarEnabled(false);
wv.setLongClickable(false);
wv.cancelLongPress();
and this is the override of the "shouldInterceptRequest" method:
#Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
try {
if (url.startsWith(Constants.KS_LOCAL_PREFIX)) {
// In case url starts with our proprietary protocol handle the request.
// Images are located in the external files directory under "images" folder
String fileName = url.substring(url.lastIndexOf(Constants.URL_SLASH));
String filePath = FileUtils.getImagesLocalFolder(getAppContext()) + fileName;
File imagefile = new File(filePath);
FileInputStream fis = new FileInputStream(imagefile);
Bitmap bi = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (bi != null) {
bi.compress(Bitmap.CompressFormat.PNG, 100, baos);
}
byte[] data = baos.toByteArray();
InputStream is = new ByteArrayInputStream(data);
return new WebResourceResponse("text/html", "UTF-8", is);
}
} catch (FileNotFoundException e) {
KsLog.d(TAG, e.toString());
} catch (NullPointerException nullEx) {
KsLog.d(TAG, nullEx.toString());
}
return super.shouldInterceptRequest(view, url);
}
This is an example of bad image :
This is an example of good image :
Thanks to everyone and I hope I explained myself well.
I am working with iTextPdf (iTextG for Android)library to convert Html to PDF document for my android application. Everything is working fine for me except the logo on the receipt. My html contains <img> tag with the source http url for the image
<img src="http...."></img>
created pdf is not having the image. Same code and html running in my Java app is showing logo with created PDF (This shows there is no issue with accessing the image). I am wondering if this feature is only compatible with Java but not with the Android?
I am using using following dependencies:
compile 'com.itextpdf:itextg:5.5.10'
compile 'com.itextpdf.tool:xmlworker:5.5.10'
Html Code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="English">
<head>
<title>Title</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
</head>
<body>
<img src="https://image.flaticon.com/teams/slug/google.jpg"></img>
<h1>Fischerstube</h1>
</body>
</html>
Function in Main Activity:
private void htmlToPdf(String html) throws DocumentException, IOException {
try {
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "logo.pdf");
OutputStream fileOutputStream = new FileOutputStream(file);
Document document = new Document();
document.setPageSize(new Rectangle(201,720));
PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);
document.open();
InputStream is = new ByteArrayInputStream(html.getBytes());
XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
document.close();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Its only rendering <h1> tag and shows Fischerstube but no image on ANDROIRD DEVICE.
Can any one help me in this regard, will be grateful.
Looking at the documentation provided here solved for me.
make sure you have Internet permission in the manifest.
create Base64ImageProvider class
class Base64ImageProvider extends AbstractImageProvider {
#Override
public Image retrieve(String src) {
int pos = src.indexOf("base64,");
try {
if (src.startsWith("data") && pos > 0) {
byte[] img = Base64.decode(src.substring(pos + 7));
return Image.getInstance(img);
}
else {
return Image.getInstance(src);
}
} catch (BadElementException ex) {
return null;
} catch (IOException ex) {
return null;
}
}
#Override
public String getImageRootPath() {
return null;
}
}
Then call create pdf method to convert yout HTML to pdf
public void createPdf() throws IOException, DocumentException {
String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" +
"<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"English\">\n" +
"<head>\n" +
" <title>Title</title>\n" +
" <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"/>\n" +
"</head>\n" +
"\n" +
"<body>\n" +
"<img src=\"https://image.flaticon.com/teams/slug/google.jpg\"></img>\n" +
"<h1>Fischerstube</h1>\n" +
"</body>\n" +
"</html>";
// step 1
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "logo.pdf");
OutputStream fileOutputStream = new FileOutputStream(file);
Document document = new Document();
// step 2
PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream);
// step 3
document.open();
// step 4
// CSS
CSSResolver cssResolver =
XMLWorkerHelper.getInstance().getDefaultCssResolver(true);
// HTML
HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());
htmlContext.setImageProvider(new Base64ImageProvider());
// Pipelines
PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);
// XML Worker
XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker);
p.parse(new ByteArrayInputStream(str.getBytes()));
// step 5
document.close();
}
Make sure you execute createPdf method on background thread. since you will be performing network operation.
i am trying to change text color of webview with this code
String message ="<font color='white'>"+"<u>"+
"text in white"+ "<br>" +
"<font color='cyan'>"+"<font size='2'>"+
" text in blue color "+"</font>";
webview.loadData(message, "text/html", "utf8");
but i have some html pages. store in my sdcard then how can i change text color..
i use
webViewRead.loadUrl(url);
url is path of my file.
You have to give the path of that file like this.
String extStorageDirectory = Environment.getExternalStorageDirectory()
.toString() + "/folder_name";
File directory = new File(extStorageDirectory);
File fileInDirectory = new File(directory,file_name.html);
//Read text from file
StringBuilder html_text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(fileInDirectory));
String line;
while ((line = br.readLine()) != null) {
html_text.append(line);
html_text.append('\n');
}
}
catch (IOException e) {
//You'll need to add proper error handling here
}
then use this html code for edit
String message ="<font color='white'>"+"<u>"+"text in white"+ "<br>" +"<font color='cyan'>"+"<font size='2'>"+" text in blue color "+"</font>";
webview.loadData(message, "text/html", "utf8");
htmlDetail = dbValues.getContent(3);
tvDescription3.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
String finalHtml = "<html><head>"
+ "<style type=\"text/css\">li{color: #00f} span {color: #000}"
+ "</style></head>"
+ "<body>"
+ htmlDetail
+ "</body></html>";
tvDescription3.loadData(finalHtml, "text/html; charset=UTF-8", null);
put your file path as
String htmlPath = "file:///mnt/sdcard/test/11.html";
String baseUrl = "file:///mnt/sdcard/test/";
webView.loadDataWithBaseURL(baseUrl, message, "text/html", "utf-8", null);
webView.loadUrl(htmlPath);
In order to change a WebView’s background color there is a standard way:
mWebView.setBackgroundColor(Color.Black);
In order to change a WebView’s text font color there is no standard way:
Either you change the font through the html code, or you do this:
htmlData="<font color='black'>" + htmlData + "</font>";
mWebView.loadDataWithBaseURL(null, htmlData, "text/html", "UTF-8", null);
I've got the following
String urlStr = "http://example.com/my.jpg"
String mimeType = "image/jpeg";
String encoding = null;
String pageData = ""; // This is data read in from an HttpURLConnection
webview.loadDataWithBaseURL(urlStr, pageData, mimeType, encoding, urlStr);
but when I run this, all I see is a blue question mark instead of my image. What is the proper way to handle displaying an image in a WebView with loadData?
Edit:
Is there a way to do this without passing pageData as <img src="http://example.com/my.jpg/"> ? It seems silly that loadData takes a mime-type if it can only handle "text/html". Especially since the javadoc lists "image/jpeg" as an example mime-type that you might pass in.
It is possible to embedd the base64 encoded imagedata direct into the <img>-tag:
<img src="data:image/jpeg;base64,base64DataHere" />
Here an example for creating the <img>-tag (I use an byte-array instead the String for raw-data, because in my tests an String as source didn't work - I assume that String can't handle binary-data):
byte[] imageRaw = yourImage;
String image64 = Base64.encodeToString(imageRaw, Base64.DEFAULT);
String pageData = "<img src=\"data:image/jpeg;base64," + image64 + "\" />";
The Base64-class was introduced with API v.2.2 - for older API-versions you can copy the sourcefile from git and integrate it in your app. It should work with older API-versions.
Or you can use one of the alternative classes for base64-encoding like Base64Coder.
And here the complete working code for retrieving, converting and showing the image:
byte[] imageRaw = null;
try {
URL url = new URL("http://some.domain.tld/somePicture.jpg");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
out.flush();
imageRaw = out.toByteArray();
urlConnection.disconnect();
in.close();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String image64 = Base64.encodeToString(imageRaw, Base64.DEFAULT);
String urlStr = "http://example.com/my.jpg";
String mimeType = "text/html";
String encoding = null;
String pageData = "<img src=\"data:image/jpeg;base64," + image64 + "\" />";
WebView wv;
wv = (WebView) findViewById(R.id.webview);
wv.loadDataWithBaseURL(urlStr, pageData, mimeType, encoding, urlStr);
Use this.. solve the problem of images load in webview.
WebView webView = (WebView)findViewById(R.id.webView1);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setJavaScriptEnabled(true);
String url ="Path of image";
String imgSrcHtml = "<html><img src='" + url + "' /></html>";
webView.loadData(imgSrcHtml, "text/html", "UTF-8");