简体   繁体   中英

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?

我得到的图像

我期望的图像

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM