Tuesday, April 01, 2008

Total Number of Pages in PrintPreviewControl

This is strange but, it seems like the Print Preview Control doesn't exposes a property/method that would give total number of pages. Then how do you get it ?? Well , there exist a private property inside the PrintPreviewControl and you need to use reflection to get it. Here is the code for it.

private int NumberOfPages()
Type ObjectType = typeof(PrintPreviewControl);
MethodInfo CalculatePageInfo = ObjectType.GetMethod("CalculatePageInfo", BindingFlags.Instance | BindingFlags.NonPublic);

FieldInfo PageInfo = ObjectType.GetField("pageInfo", BindingFlags.Instance | BindingFlags.NonPublic);
PreviewPageInfo[] infos = (PreviewPageInfo[]) PageInfo.GetValue(this.printPreviewControl1);
return infos.Length;