Search code examples
c#wpfprintdialog

Migrating PrintDialog and PrinterSettings from winforms to wpf


I have the following code which works very well in winforms and C#:

printDialog = new PrintDialog();
if (DialogResult.OK == printDialog.ShowDialog())
{
  try
  {
    PrintDocument pd = new PrintDocument();
    PrinterSettings ps = new PrinterSettings();
    pd.PrintPage += new PrintPageEventHandler(PrintImage);
    pd.PrinterSettings = printDialog.PrinterSettings;
    pd.Print();
  }
  catch
  {
  
  }
}

Now in wpf it is indicated that there is an error in the line:

pd.PrinterSettings = printDialog.PrinterSettings;

So to test if the rest of the code works I commented it and it works very well, but obviously it always prints on the printer that the PC has configured by default.

I tried to investigate in other threads how to solve this problem and the solution is supposedly the following:

printDialog.PrintQueue = new PrintQueue(new PrintServer(), "The exact name of my printer");

But performing this action generates an error:

Severity Code Description Project File Line Status deleted Error CS0012 Type 'PrintQueue' is defined in an assembly that is not referenced. You must add a reference to the assembly 'System.Printing, Version = 4.0.0.0, Culture = neutral,

Any comments or suggestions are welcome.


Solution

  • The solution for wpf is add add reference to System.Printing.dll (Thanks @Sinatr ) and the code is like this:

    PrintDocument pd = new PrintDocument();
    PrinterSettings ps = new PrinterSettings();
    pd.PrintPage += new PrintPageEventHandler(PrintImage);
    
    pd.PrinterSettings.PrinterName = printDialog.PrintQueue.Name; 
    
    pd.Print();