5

Does anyone know how to convert html code (with images within it) to image on Android? I know how to make it on Java using JLabel/JEditorPane and BufferedImage, but now should make the same with Android.

peter.tailor
  • 51
  • 1
  • 2
  • I think this is good solution: [http://stackoverflow.com/questions/8163202/convert-html-and-set-text-to-textview/12703962#12703962](http://stackoverflow.com/questions/8163202/convert-html-and-set-text-to-textview/12703962#12703962) – NrNazifi Oct 03 '12 at 07:37
  • Hi peter. Did you found any solution for this? I need exactly the same you asked.. – Eshack Nazir Nov 18 '16 at 11:20
  • Does this answer your question? [Generate bitmap from HTML in Android](https://stackoverflow.com/questions/4633988/generate-bitmap-from-html-in-android) – Ismail Iqbal Nov 23 '20 at 10:58

2 Answers2

6

The answer of @Neo1975 is worked for me, but to avoid using deprecated method WebView.capturePicture() you could use the following method to capture content of WebView.

/**
* WevView screenshot
*
* @param webView
* @return
*/
private static Bitmap screenshot(WebView webView) {
  webView.measure(View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
    webView.layout(0, 0, webView.getMeasuredWidth(), 
    webView.getMeasuredHeight());
    webView.setDrawingCacheEnabled(true);
    webView.buildDrawingCache();
    Bitmap bitmap = Bitmap.createBitmap(webView.getMeasuredWidth(), 
    webView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(bitmap);
    Paint paint = new Paint();
    int iHeight = bitmap.getHeight();
    canvas.drawBitmap(bitmap, 0, iHeight, paint);
    webView.draw(canvas);
    return bitmap;
}

The idea behind it is using WebView.draw(Canvas) method.

nhoxbypass
  • 9,695
  • 11
  • 48
  • 71
5

For this task I use the follow trick: I used a webview to parse HTML and call the method capturePicture on WevView object to extract a Picture of HTML, so I can suggest you the follow sniplet:

WebView wv = new WebView(this);
wv.loadData("<html><body><p>Hello World</p></body></html>");
Picture p = wv.capturePicture();

I hope this can help, but if you foun a different way to solve it please post it.

Neo1975
  • 124
  • 11