Printing in WPF with fit to printing page.
Posted by Viral Sarvaiya on May 17, 2011
Hi,
Here is the code for the print in WPF.
It is very simple to print a page in comparison with normal window application. Just make a object of the PrintDialog Class and just call function PrintVisual as below
PrintDialog printDlg = new System.Windows.Controls.PrintDialog();
if (printDlg.ShowDialog() == true)
{
printDlg.PrintVisual(this, "First WPF Print");
}
This code will print the page. That will take automatically margin to the printing page
What if you want to print page with fit to the printing page?
Here are the steps to print page with fit to printing page.
Step 1: Add the reference of the ReachFramework.dll
Step 2: Add the reference of the System.Printing.dll
Step 3: Get selected Printer’s capability
Step 4: calculate scale of the printer
Step 5: Get printable area of Paper.
Step 6: Update visual layout
Step 7: Print Visual
Here is the code for the above procedure
private void btnPrint_Click(object sender, RoutedEventArgs e)
{
PrintDialog Objprint = new System.Windows.Controls.PrintDialog();
if (Objprint.ShowDialog() == true)
{
//get selected printer capabilities
System.Printing.PrintCapabilities capabilities = Objprint.PrintQueue.GetPrintCapabilities(Objprint.PrintTicket);
//get scale of the print wrt to screen of WPF visual
double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth / this.ActualWidth, capabilities.PageImageableArea.ExtentHeight / this.ActualHeight);
//Transform the Visual to scale
this.LayoutTransform = new ScaleTransform(scale, scale);
//get the size of the printer page
Size size = new Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight);
//update the layout of the visual to the printer page size.
this.Measure(size);
this.Arrange(new Rect(new Point(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight), size));
//now print the visual to printer to fit on the one page.
Objprint.PrintVisual(this, "Print in WPF with fit to printing page");
}
}
thanks
Enjoy….



Print dynamically generated controls in WPF « Web Developer Friend – Viral Sarvaiya said
[...] Printing in WPF with fit to printing page. [...]
business cards said
prince edward island…
Printing in WPF with fit to printing page. « Web Developer Friend – Viral Sarvaiya…