Printing a Control in WPF using C#

Print a Control, User Control, or Window in WPF

In WPF, a Visual is an object that is parent class of all user interfaces including UIElement, Containers, Controls, UserControls, and even Viewport3DVisual. If you notice all control or user controls classes, they are inherited from a UIElement class.

The PrintVisual print a Visual object. That means, by using the PrintVisual method, we can print any control, container, Window or user control.

The following code snippet in creates a PrintDialog object and calls its PrintVisual method by passing a UserControl to print the UserControl. Using this method, we can print any controls in WPF including a Window, page, or a ListBox.

  1. PrintDialog printDlg = new PrintDialog();  
  2. UserControl1 uc = new UserControl1();  
  3. printDlg.PrintVisual(uc, "User Control Printing.");   

What if you want to print a Grid control or any other control?

As said above, printing any control in WPF is same process. Just pass the Grid or other control in the PrintVisual method of PrintDialog.

  1. PrintDialog printDlg = new PrintDialog();  
  2. printDlg.PrintVisual(grid1, "Grid Printing.");  

How about printing the entire Window?

For entire window, you can either pass the window object or this keyword. This time, you pass "this" that is the object of current Window where you are writing this code.

  1. PrintDialog printDlg = new PrintDialog();  
  2. printDlg.PrintVisual(this"Window Printing.");  


Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.