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
Here is where it gets interesting. What about those hard coded values for the canvas ?:-
PageInfo pageInfo = new PageInfo.Builder(595,842,1).create();
You need the width and height of the WebView CONTENTS, after you loaded your HTML. YES you do, but there is no getContentWidth method (only a view port value), AND the getContentHeight() is inaccurate !
Answer: sub-class WebView:
/*
Jon Goodwin
*/
package com.example.html2pdf;//your package
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.webkit.WebView;
class CustomWebView extends WebView
{
public int rawContentWidth = 0; //unneeded
public int rawContentHeight = 0; //unneeded
Context mContext = null; //unneeded
public CustomWebView(Context context) //unused constructor
{
super(context);
mContext = this.getContext();
}
public CustomWebView(Context context, AttributeSet attrs) //inflate constructor
{
super(context,attrs);
mContext = context;
}
public int getContentWidth()
{
int ret = super.computeHorizontalScrollRange();//working after load of page
rawContentWidth = ret;
return ret;
}
public int getContentHeight()
{
int ret = super.computeVerticalScrollRange(); //working after load of page
rawContentHeight = ret;
return ret;
}
public void onPageFinished(WebView page, String url)
{
//never gets called, don't know why, but getContentHeight & getContentWidth function after load of page
rawContentWidth = ((CustomWebView) page).getContentWidth();
rawContentHeight = ((CustomWebView) page).getContentHeight();
Log.e("CustomWebView:onPageFinished","ContentWidth: " + ((CustomWebView) page).getContentWidth());
Log.e("CustomWebView:onPageFinished","ContentHeight: " + ((CustomWebView) page).getContentHeight());
}
//=========
}//class
//=========
In my modified code (in the other answer) change:
private CustomWebView wv;
wv = (CustomWebView) this.findViewById(R.id.webView1);
int my_width = wv.getContentWidth();
int my_height = wv.getContentHeight();
and change your layout class entry from WebView to com.example.html2pdf.CustomWebView.
then you good to go !