Przejdź do treści stopki
KORZYSTANIE Z IRONPRINT

Jak drukować za pomocą drukarki sieciowej w języku C#

Programmatic printing on network printers is a common task across various software applications. Whether you're building a desktop, mobile application, or a web service, the ability to send documents directly to a network printer can greatly enhance the usability and efficiency of your software. In this article, we'll explore how to print on a network printer using C# and IronPrint from Iron Software.

How to Print with Network Printer in C

  1. Create a New project for Printing Documents using IronPrint.
  2. Install IronPrint to a new project.
  3. List network printers available for printing documents.
  4. Print PDF documents using IronPrint.
  5. Print PDF documents using IronPrint with Dialog.
  6. Advanced Printing with Print settings.

Setting up the Environment

Before delving into the coding part, let's ensure that our environment is set up correctly. To print on a network printer in C#, you need to have the following:

  1. Ensure that a network printer is accessible from the machine where your C# application will run.
  2. The printer's network address (IP address or network printer name).
  3. Necessary printer driver/drivers installed on the machine.
  4. Administrative privileges to install printers or drivers if required.

IronPrint

Before diving into the implementation details, let's familiarize ourselves with how to get started with IronPrint:

  1. Installation: IronPrint can be easily installed via NuGet Package Manager. Simply visit the NuGet page and follow the installation instructions.
  2. Documentation: Refer to the official documentation for a quick start guide and comprehensive API reference.

Compatibility and Support: IronPrint offers extensive compatibility and support across various environments and project types:

  • .NET Version Support: IronPrint supports C#, VB.NET, and F#, including .NET 8,7,6,5, and Core 3.1+.
  • Operating Systems and Environments: IronPrint is compatible with Windows (7+), macOS (10+), iOS (11+), and Android API 21+ (v5 "Lollipop").
  • Project Types: Whether you're developing mobile (Xamarin, MAUI, Avalonia), desktop (WPF, MAUI, Windows Avalonia), or console applications, IronPrint has got you covered.

Now let's see how to print with IronPrint with the following example.

using IronPrint;

namespace IronPrintDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Configure printer setting
            PrintSettings printSettings = new PrintSettings();
            printSettings.Dpi = 220;
            printSettings.NumberOfCopies = 10;
            printSettings.PaperOrientation = PaperOrientation.Portrait;

            // Print the document
            Printer.Print("awesomeIronPrint.pdf", printSettings);
        }
    }
}
using IronPrint;

namespace IronPrintDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // Configure printer setting
            PrintSettings printSettings = new PrintSettings();
            printSettings.Dpi = 220;
            printSettings.NumberOfCopies = 10;
            printSettings.PaperOrientation = PaperOrientation.Portrait;

            // Print the document
            Printer.Print("awesomeIronPrint.pdf", printSettings);
        }
    }
}
Imports IronPrint

Namespace IronPrintDemo
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			' Configure printer setting
			Dim printSettings As New PrintSettings()
			printSettings.Dpi = 220
			printSettings.NumberOfCopies = 10
			printSettings.PaperOrientation = PaperOrientation.Portrait

			' Print the document
			Printer.Print("awesomeIronPrint.pdf", printSettings)
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

System.Printing

The System.Printing namespace in C# contains classes and interfaces that enable developers to interact with printers, print queues, print servers, and print jobs programmatically. Some key classes and interfaces within this namespace include:

  1. PrintQueue: Represents a printer or print device connected to the system.
  2. PrintServer: Represents a print server on the network.
  3. PrintSystemJobInfo: Provides information about a print job, such as its status and properties.
  4. PrintTicket: Represents the settings for a print job, including paper size, orientation, and print quality.

Getting Started with System.Printing: Before we dive into the code, let's ensure that we have a basic understanding of how printing works with System.Printing:

  1. PrintQueue Selection: You need to identify the PrintQueue object representing the printer you want to use for printing.
  2. PrintTicket Configuration: Optionally, you can configure the PrintTicket object to specify print settings such as paper size, orientation, and number of copies.
  3. Document Printing: Finally, you send the document to be printed to the selected PrintQueue.

Implementing Document Printing with System.Printing: Now, let's walk through the process of printing a document using System.Printing with the following example:

Here is the source code:

using System;
using System.IO;
using System.Printing;

class Program
{
    static void Main(string[] args)
    {
        // Specify the path to the document to be printed on the local printer
        string documentPath = "path/to/your/document.pdf";

        // Instantiate a Printer Server object representing the local print server
        using (PrintServer printServer = new PrintServer())
        {
            // Get the default PrintQueue from the PrintServer default 
            PrintQueue defaultPrintQueue = printServer.DefaultPrintQueue;

            // Create a PrintTicket object to specify print settings (optional)
            PrintTicket printTicket = new PrintTicket();

            // Configure print settings, e.g., number of copies
            printTicket.CopyCount = 1;

            // Print the document to the default PrintQueue with the specified PrintTicket
            defaultPrintQueue.AddJob("MyPrintJob", documentPath, false, printTicket);
        }

        Console.WriteLine("Document sent to print queue.");
    }
}
using System;
using System.IO;
using System.Printing;

class Program
{
    static void Main(string[] args)
    {
        // Specify the path to the document to be printed on the local printer
        string documentPath = "path/to/your/document.pdf";

        // Instantiate a Printer Server object representing the local print server
        using (PrintServer printServer = new PrintServer())
        {
            // Get the default PrintQueue from the PrintServer default 
            PrintQueue defaultPrintQueue = printServer.DefaultPrintQueue;

            // Create a PrintTicket object to specify print settings (optional)
            PrintTicket printTicket = new PrintTicket();

            // Configure print settings, e.g., number of copies
            printTicket.CopyCount = 1;

            // Print the document to the default PrintQueue with the specified PrintTicket
            defaultPrintQueue.AddJob("MyPrintJob", documentPath, false, printTicket);
        }

        Console.WriteLine("Document sent to print queue.");
    }
}
Imports System
Imports System.IO
Imports System.Printing

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Specify the path to the document to be printed on the local printer
		Dim documentPath As String = "path/to/your/document.pdf"

		' Instantiate a Printer Server object representing the local print server
		Using printServer As New PrintServer()
			' Get the default PrintQueue from the PrintServer default 
			Dim defaultPrintQueue As PrintQueue = printServer.DefaultPrintQueue

			' Create a PrintTicket object to specify print settings (optional)
			Dim printTicket As New PrintTicket()

			' Configure print settings, e.g., number of copies
			printTicket.CopyCount = 1

			' Print the document to the default PrintQueue with the specified PrintTicket
			defaultPrintQueue.AddJob("MyPrintJob", documentPath, False, printTicket)
		End Using

		Console.WriteLine("Document sent to print queue.")
	End Sub
End Class
$vbLabelText   $csharpLabel

IronPrint Vs System.Printing

How to Print with Network Printer in C#: Figure 1 - A quick comparison table between IronPrint vs System.Printing

This table provides a quick overview of the features and characteristics of IronPrint and System.Printing, helping developers make informed decisions based on their specific requirements and platform targets.

Step 1: Create a New project for Printing Documents using IronPrint

Create a console application in Visual Studio as shown below.

How to Print with Network Printer in C#: Figure 2 - Creating a console application

Provide a project name and location.

How to Print with Network Printer in C#: Figure 3 - Provide a project name

Wybierz wersję .NET.

How to Print with Network Printer in C#: Figure 4 - Select the appropriate .NET version

Now the project is created and ready for further coding.

Step 2: Install IronPrint on a new project

Install IronPrint from Visual Studio Package Manager as shown below.

How to Print with Network Printer in C#: Figure 5 - Search for IronPrint through Visual Studio Package Manager

IronPrint can also be installed using the command below:

Install-Package IronPrint

Step 3: List network printers available for printing documents

To list the printer names using IronPrint use the code below:

using System;
using System.Collections.Generic;
using IronPrint;

namespace IronPrintDemo
{
    public class Program
    {
        public static void Main()
        {
            // Get printer names using printer drivers
            List<string> printersName = Printer.GetPrinterNames();
            foreach (var printer in printersName)
            {
                Console.WriteLine(printer);
            }
        }
    }
}
using System;
using System.Collections.Generic;
using IronPrint;

namespace IronPrintDemo
{
    public class Program
    {
        public static void Main()
        {
            // Get printer names using printer drivers
            List<string> printersName = Printer.GetPrinterNames();
            foreach (var printer in printersName)
            {
                Console.WriteLine(printer);
            }
        }
    }
}
Imports System
Imports System.Collections.Generic
Imports IronPrint

Namespace IronPrintDemo
	Public Class Program
		Public Shared Sub Main()
			' Get printer names using printer drivers
			Dim printersName As List(Of String) = Printer.GetPrinterNames()
			For Each printer In printersName
				Console.WriteLine(printer)
			Next printer
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

Wyjaśnienie kodu

  1. Use Printer.GetPrinterNames to get all the available printer drivers.
  2. Print the names using Console.WriteLine.

Wynik

How to Print with Network Printer in C#: Figure 6 - Example output of available printers

Step 4: Print PDF document using IronPrint

Use the code below to print the document silently:

using IronPrint;

namespace IronPrintDemo
{
    public class Program
    {
        public static void Main()
        {
            // Print the document silently
            Printer.Print("sample.pdf");
        }
    }
}
using IronPrint;

namespace IronPrintDemo
{
    public class Program
    {
        public static void Main()
        {
            // Print the document silently
            Printer.Print("sample.pdf");
        }
    }
}
Imports IronPrint

Namespace IronPrintDemo
	Public Class Program
		Public Shared Sub Main()
			' Print the document silently
			Printer.Print("sample.pdf")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

After the execution, the document is added to the print queue as shown in the output.

Wynik

How to Print with Network Printer in C#: Figure 7 - Example output showcasing the document being added to print queue

Step 5: Print PDF document using IronPrint with Dialog

Use the code below to print the document with the dialog:

using IronPrint;

namespace IronPrintDemo
{
    public class Program
    {
        public static void Main()
        {
            // Print with Dialog
            Printer.ShowPrintDialog("sample.pdf");
        }
    }
}
using IronPrint;

namespace IronPrintDemo
{
    public class Program
    {
        public static void Main()
        {
            // Print with Dialog
            Printer.ShowPrintDialog("sample.pdf");
        }
    }
}
Imports IronPrint

Namespace IronPrintDemo
	Public Class Program
		Public Shared Sub Main()
			' Print with Dialog
			Printer.ShowPrintDialog("sample.pdf")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

Wyjaśnienie kodu

  1. Using ShowPrintDialog from IronPrint we can print with Dialog.
  2. Once the dialog is open, select the required printer to print the document.

Wynik

How to Print with Network Printer in C#: Figure 8 - Select the correct printer

Step 6: Advanced Printing with Print settings

Printing documents with advanced settings is supported in IronPrint. It supports the following Properties:

  1. PaperSize: Specifies the paper dimensions utilized by the printer.
  2. PaperOrientation: Defines the orientation of the paper, such as Automatic, Portrait, or Landscape.
  3. DPI: Sets the desired print resolution in dots per inch. The default value is 300, commonly employed in commercial printing. The actual DPI may be constrained by the printer's capabilities.
  4. NumberOfCopies: Indicates the number of identical copies to print for a document.
  5. PrinterName: Specifies the name of the printer designated for printing tasks.
  6. PaperMargins: Determines the margins for printing, measured in millimeters.
  7. Grayscałe: A boolean value determining whether to print in grayscałe. Domyślną wartością jest false.

Now let's look at a code example:

using IronPrint;

namespace IronPrintDemo
{
    public class Program
    {
        public static void Main()
        {
            // Configure custom print settings
            PrintSettings printSettings = new PrintSettings();
            printSettings.Dpi = 150;
            printSettings.NumberOfCopies = 2;
            printSettings.PaperOrientation = PaperOrientation.Portrait;

            // Print the required document
            Printer.Print("sample.pdf", printSettings);
        }
    }
}
using IronPrint;

namespace IronPrintDemo
{
    public class Program
    {
        public static void Main()
        {
            // Configure custom print settings
            PrintSettings printSettings = new PrintSettings();
            printSettings.Dpi = 150;
            printSettings.NumberOfCopies = 2;
            printSettings.PaperOrientation = PaperOrientation.Portrait;

            // Print the required document
            Printer.Print("sample.pdf", printSettings);
        }
    }
}
Imports IronPrint

Namespace IronPrintDemo
	Public Class Program
		Public Shared Sub Main()
			' Configure custom print settings
			Dim printSettings As New PrintSettings()
			printSettings.Dpi = 150
			printSettings.NumberOfCopies = 2
			printSettings.PaperOrientation = PaperOrientation.Portrait

			' Print the required document
			Printer.Print("sample.pdf", printSettings)
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

Wyjaśnienie kodu

  1. The code begins by importing the necessary namespace IronPrint, which contains the required classes and methods for printing.
  2. Inside the IronPrintDemo namespace, there's a class named Program declared as public.
  3. The Main method serves as the entry point of the program.
  4. Within the Main method:
    • A PrintSettings object named printSettings is instantiated to configure custom print settings.
    • The Dpi property of printSettings is set to 150, indicating a print resolution of 150 dots per inch.
    • The NumberOfCopies property of printSettings is set to 2, specifying that two identical copies of the document will be printed.
    • The PaperOrientation property of printSettings is set to PaperOrientation.Portrait, indicating that the document will be printed in portrait orientation.
  5. Finally, the Printer.Print method is invoked with parameters "sample.pdf" (the name of the document to print) and printSettings (the custom print settings). This method handles the printing process using the specified settings.

Wynik

How to Print with Network Printer in C#: Figure 9 - Example output showcasing the PDF document added to the print queue for printing

License

IronPrint from Iron Software is an enterprise library and requires a license to run. Adding an IronPrint license key makes the project live without restrictions or watermarks. Buy a license here or sign up for a free 30-day trial key here.

Once the License key is obtained, the key needs to be placed in the appSettings.json file in the application

{
  "IronPrint.License.LicenseKey": "IRONPRINT.KEY"
}

This will print documents without restrictions and watermarks.

Wnioski

In summary, IronPrint and System.Printing each have their strengths and are suitable for different scenarios. IronPrint provides a streamlined and cross-platform solution with a focus on simplicity and versatility, while System.Printing offers native integration and fine-grained control, particularly for Windows-based applications. Developers should consider their specific requirements and platform targets when choosing between these printing libraries for their C# projects.

IronPrint simplifies document printing within .NET applications by providing a user-friendly API and extensive compatibility across various platforms and project types. By following the steps outlined in this article, you can seamlessly integrate printing functionality into your .NET projects, enhancing their usability and productivity. Explore the possibilities with IronPrint and unlock a world of efficient document printing within your applications.

Często Zadawane Pytania

Jak mogę drukować na drukarce sieciowej za pomocą języka C#?

Za pomocą IronPrint można drukować dokumenty na drukarce sieciowej w języku C#. Pozwala to na wysyłanie dokumentów bezpośrednio do drukarki sieciowej za pomocą metod obsługujących zadania drukowania programowo.

Jakie kroki należy wykonać, aby skonfigurować drukowanie na drukarce sieciowej w języku C#?

Najpierw upewnij się, że masz dostęp do drukarki sieciowej i znasz jej adres. Zainstaluj niezbędne sterowniki oraz IronPrint za pomocą menedżera pakietów NuGet. Następnie użyj metod IronPrint do zarządzania i wysyłania zadań drukowania.

Jak zainstalować IronPrint w moim projekcie C#?

Możesz zainstalować IronPrint za pomocą menedżera pakietów NuGet w Visual Studio lub uruchamiając polecenie Install-Package IronPrint w konsoli menedżera pakietów.

Które wersje .NET są kompatybilne z IronPrint?

IronPrint obsługuje języki C#, VB.NET i F# oraz jest kompatybilny z platformami .NET 8, 7, 6, 5 i Core 3.1+.

Czy IronPrint może być używany na różnych systemach operacyjnych?

Tak, IronPrint jest kompatybilny z systemami Windows (7+), macOS (10+), iOS (11+) oraz Android API 21+ (v5 „Lollipop”).

Czym różni się IronPrint od System.Printing w języku C#?

IronPrint oferuje rozwiązanie wieloplatformowe, w którym nacisk kładziony jest na prostotę, podczas gdy System.Printing zapewnia natywną integrację i kontrolę dla aplikacji opartych na systemie Windows.

Jak mogę wyświetlić listę dostępnych drukarek sieciowych za pomocą IronPrint?

W bibliotece IronPrint można użyć metody Printer.GetPrinterNames(), która zwraca listę dostępnych sterowników drukarek.

Jakie zaawansowane opcje drukowania są dostępne w IronPrint?

IronPrint obsługuje zaawansowane ustawienia, w tym PaperSize, PaperOrientation, DPI, NumberOfCopies, PrinterName, PaperMargins i Grayscale.

Jakie opcje licencyjne są dostępne dla IronPrint?

Licencje IronPrint można kupić lub zarejestrować się na 30-dniowy okres próbny na stronie internetowej Iron Software. Klucz licencyjny umieszcza się w pliku appSettings.json aplikacji.

Jakiego polecenia używa się do zainstalowania IronPrint z poziomu wiersza poleceń?

Aby zainstalować IronPrint za pomocą wiersza poleceń, należy użyć polecenia Install-Package IronPrint.

Curtis Chau
Autor tekstów technicznych

Curtis Chau posiada tytuł licencjata z informatyki (Uniwersytet Carleton) i specjalizuje się w front-endowym rozwoju, z ekspertką w Node.js, TypeScript, JavaScript i React. Pasjonuje się tworzeniem intuicyjnych i estetycznie przyjemnych interfejsów użytkownika, Curtis cieszy się pracą z nowoczesnymi frameworkami i tworzeniem dobrze zorganizowanych, atrakcyjnych wizualnie podrę...

Czytaj więcej

Zespol wsparcia Iron

Jestesmy online 24 godziny, 5 dni w tygodniu.
Czat
Email
Zadzwon do mnie