Introduction
This tip will give you a brief idea about how to find printers on the network on server/local and send the document to get printed within network. (Print Reports on installed Printer using IP Address and Name)
Background
This tutorial focuses on:
- How to find the network printer using printer IP address and Printer Name
- If printer is not configured, then show the message as "Printer is not configured with IP Address and Name"
- How to print report using network printer runtime
Using the Code
This tutorial is basically focused on how to print the report and not on how to create it.
To create report, check the link...
Pre-requisite: Need to configure the printer on server/local.
Let’s move on to the code.
Step 1: Create New console application.
Step 2: Add System.Printing
reference in your project.
Step 3: Use the below code to get the printer name:
using System.Printing;
namespace PrintApp
{
class Printer
{
public string CheckPrinterConfiguration(string printerIP, string printerName)
{
var server = new PrintServer();
var queues = server.GetPrintQueues(new[]
{ EnumeratedPrintQueueTypes.Local, EnumeratedPrintQueueTypes.Connections });
string fulllName = queues.Where(q => q.Name == printerName &&
q.QueuePort.Name == printerIP).Select(q => q.FullName).FirstOrDefault();
return fulllName;
}
}
}
- Get All Printers: If you want to take a list of available printers, use
EnumeratedPrintQueueTypes.Local
. It will get all the shared and local printers. Local printers are ("Send To OneNote 2016", "Microsoft XPS Document Writer"," Microsoft Print to PDF","Fax", etc.)
- Installed or Shared Printers: If you want to take installed or shared printers, use
EnumeratedPrintQueueTypes.Shared
.
To print report, use the below code:
public void PrintReport(string printerIP, string printerName)
{
string printerFullName = CheckPrinterConfiguration(printerIP, printerName);
if (!string.IsNullOrEmpty(printerFullName))
{
ReportDocument report = new ReportDocument();
string reportFilePath = Path.Combine(Environment.CurrentDirectory,
"Reports\\" + rptParam.ReportParameter.ReportName + ".rpt");
report.Load(reportFilePath);
report.SetDataSource(data);
report.PrintOptions.PrinterName = printerName;
System.Drawing.Printing.PageSettings page = new System.Drawing.Printing.PageSettings();
try
{
report.PrintToPrinter(1, true, 0, 0);
}
catch (Exception ex)
{
throw ex;
}
}
else
{
Console.WriteLine("Printer is not configured with IP: {0}
and Name: {1}", printerIP, printerName);
}
}