代码之家  ›  专栏  ›  技术社区  ›  Entretoize

打印整个WebView网页

  •  1
  • Entretoize  · 技术社区  · 6 年前

    我正在为Android构建一个WebView基础应用程序,我需要一个打印功能。 我试过了:

    var printMgr = (PrintManager)activity.GetSystemService(Context.PrintService);
    
    if (((int)Android.OS.Build.VERSION.SdkInt) >= 21)
        printMgr.Print("my page", webview.CreatePrintDocumentAdapter("my page"), null);
    else
        printMgr.Print("my page", webview.CreatePrintDocumentAdapter(), null);
    

    但是它只打印页面的可见部分。

    1 回复  |  直到 6 年前
        1
  •  0
  •   Asfar Ali    6 年前

    如果需要位图,请使用以下类获取位图

    public class Screenshot {
    
        public static Bitmap get(Context context,WebView view){
            float width=getWindowWidth(context);
            float height=view.getContentHeight() * getDensity(context);
            return capture(view,width,height);
        }
        private static Bitmap capture(View view, float width, float height) {
            if (!view.isDrawingCacheEnabled()) {
                view.setDrawingCacheEnabled(true);
            }
            view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
            Bitmap bitmap = Bitmap.createBitmap((int) width, (int) height, Bitmap.Config.ARGB_8888);
            bitmap.eraseColor(Color.WHITE);
            Canvas canvas = new Canvas(bitmap);
            int left = view.getLeft();
            int top = view.getTop();
            int status = canvas.save();
            canvas.translate(-left, -top);
            float scale = width / view.getWidth();
            canvas.scale(scale, scale, left, top);
            view.draw(canvas);
            canvas.restoreToCount(status);
            Paint alphaPaint = new Paint();
            alphaPaint.setColor(Color.TRANSPARENT);
            canvas.drawRect(0f, 0f, 1f, height, alphaPaint);
            canvas.drawRect(width - 1f, 0f, width, height, alphaPaint);
            canvas.drawRect(0f, 0f, width, 1f, alphaPaint);
            canvas.drawRect(0f, height - 1f, width, height, alphaPaint);
            canvas.setBitmap(null);
            return bitmap;
        }
        private static int getWindowWidth(Context context) {
            return context.getResources().getDisplayMetrics().widthPixels;
        }
        private static float getDensity(Context context) {
            return context.getResources().getDisplayMetrics().density;
        }
    }
    

    如果要打印,请尝试替换

        printMgr.Print("my page", webview.CreatePrintDocumentAdapter(), null);
    

    具有

    printMgr.Print("my page", webview.CreatePrintDocumentAdapter(), new PrintAttributes.Builder().build()));
    

    这对我有用