I\'ve been having troubles getting PDF printing work on Android. What I\'m trying to do is render some HTML in WebView, then draw the WebView contents on a PDF canvas and fi
Summary: Don't modify the density, (it should be set on your device, probably to medium 160 dpi) instead, use scale. If you Just need Bitmaps of your HTML page in your PDF (No hyper-link function), this works. This is what your code is generating, with the following code:
//Create PDF document
PdfDocument doc = new PdfDocument();
//Create A4 sized PDF page
int my_width = 595;
int my_height = 842;
PageInfo pageInfo = new PageInfo.Builder(my_width,my_height,1).create();
// PageInfo pageInfo = new PageInfo.Builder(650,850,1).create();
Page page = doc.startPage(pageInfo);
WebView wv = (WebView) this.findViewById(R.id.webView1);
Canvas canvas = page.getCanvas();
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
final DisplayMetrics displayMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;
float density = displayMetrics.density;
int wvWidth = wv.getWidth();
int wvHeight= wv.getHeight();
float wvScaleX= wv.getScaleX();
float wvScaleY= wv.getScaleY();
// canvas.setDensity(100);//200 Bitmap.DENSITY_NONE
int cdensity = canvas.getDensity();
float scaleWidth = (float)width/(float)my_width;
float scaleHeight = (float)height/(float)my_height;
canvas.scale(scaleWidth, scaleHeight);
Log.e("button1onClick","canvas width:" + canvas.getHeight() + " canvas height:" + canvas.getWidth());
Log.e("button1onClick","metrics width:" + width + " metrics height:" + height + "metrics density:" + density);
Log.e("button1onClick"," wvWidth:" + wvWidth + " wvHeight:" + wvHeight);
Log.e("button1onClick"," scaleWidth: " + scaleWidth +
" scaleHeight:" + scaleHeight +" cdensity:" + cdensity);
Paint paint = new Paint();
// paint.setStyle(Style.FILL);
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(1);
//Draw the webview to the canvas
wv.draw(canvas);
canvas.scale(1f, 1f);
canvas.drawRect(0, 0, canvas.getWidth()-1, canvas.getHeight()-1, paint);
canvas.drawText("Direct drawn Red Rectangle to fill page canvas 0, 0," +
canvas.getWidth() + "," + canvas.getHeight(), 100, 100, paint);
doc.finishPage(page);
This works well (Hyper-links cannot work of course). More complex example: