Printing WPF Window to Printer and Fit on a Page

1. Normal Printing

Printing in WPF is easy as compare to other window printing. Here in this we have to show the PrintDialog and call the PrintVisual method of the PrintDialog. This example has been shown in the btnPrint_OnClick event handler.

PrintDialog printDlg = new System.Windows.Controls.PrintDialog();

if (printDlg.ShowDialog() == true)

{

      printDlg.PrintVisual(this"WPF Print");

}

2. Print to Fit Window

Now if you want to fit your visual to fit into the print page then you have to do little more coding.

  • Add Reference the ReachFramework.dll.
  • Add reference of the System.Printing.dll.
  • Get the capabilities of the selected printer.
  • Calculate the scaling of the printer with w.r.t. to visual to be printed.
  • Transform the visual to be printed to the calculated scale.
  • Get the printable area of the paper size.
  • Update the layout of the visual to the printable area.
  • Print the visual.

Code: This code in the sample is called in the btnPrintFit_OnClick handler.

PrintDialog printDlg = new System.Windows.Controls.PrintDialog();

if (printDlg.ShowDialog() == true)

   {

      //get selected printer capabilities

      System.Printing.PrintCapabilities capabilities = printDlg.PrintQueue.GetPrintCapabilities(printDlg.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 sz = new Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight);

 

     //update the layout of the visual to the printer page size.

     this.Measure(sz);

     this.Arrange(new Rect(new Point(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight), sz));

 

      //now print the visual to printer to fit on the one page.

      printDlg.PrintVisual(this"First Fit to Page WPF Print");

}


Summary

Using WPF you can print any visual element in the normal way or to fit on the page easily.

Next Recommended Reading Print Using Flow Document In WPF