user3908652
user3908652

Reputation: 131

How to convert HTML files (stored in assets) to image in android?

I'm trying to convert html files stored as assets to image so that I can share them. I tried the following code:

Picture picture = webView.capturePicture();
Bitmap b = Bitmap.createBitmap(
        picture.getWidth(), picture.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
picture.draw(c);

FileOutputStream fos = null;
try {
    fos = new FileOutputStream( Environment.getExternalStorageDirectory().toString() +"/temp.jpg");
    if ( fos != null ) {
        b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        Toast.makeText(SyllabusPage_NW.this, "created", Toast.LENGTH_SHORT).show();
        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        Uri screenshotUri = Uri.parse(Environment.getExternalStorageDirectory().toString() + "/temp.jpg");

        sharingIntent.setType("image/jpeg");
        sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
        startActivity(Intent.createChooser(sharingIntent, "Share image using"));
        fos.close();

    }
}
catch( Exception e ) {

    Toast.makeText(SyllabusPage_NW.this, "Error", Toast.LENGTH_SHORT).show();
}

The result of this is attached and the expected result is also attached. The webview captures only the first part of the html page. I wanna know how I can capture the entire html page instead of just the first bit?

Image that I'm getting

The Image I'm expecting

Upvotes: 1

Views: 1161

Answers (1)

Mohammad
Mohammad

Reputation: 69

for API Lollipop and higher should enable slow draw:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    WebView.enableSlowWholeDocumentDraw();
}

then check the height of picture is correct by debugging.
if not measre webview first then layout.

webView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
webView.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
webView.buildDrawingCache(true);

Bitmap b = Bitmap.createBitmap(webView.getDrawingCache());
webView.setDrawingCacheEnabled(false);

Upvotes: 1

Related Questions