我正在为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);
但是,它仅打印页面的可见部分。
答案 0 :(得分:0)
如果要使用位图,请使用以下课程获得一个位图
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()));
这对我有用
答案 1 :(得分:0)
只需让Webview完全加载,然后调用createWebPagePrint
函数即可,而不是立即调用createWebPagePrint
函数。
public void createWebPagePrint(WebView webView) {
PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter(System.currentTimeMillis() + ".pdf");
String jobName = "Job_Name";
PrintAttributes.Builder builder = new PrintAttributes.Builder();
builder.setMediaSize(PrintAttributes.MediaSize.ISO_A4);
builder.setMinMargins(PrintAttributes.Margins.NO_MARGINS);
printManager.print(jobName, printAdapter, builder.build());
}