Jak wydrukować plik na drukarce w języku C#
Printing PDF files directly from a C# application can be a valuable feature, especially when developing applications that require seamless integration with physical PDF documents. Whether you're working on a PDF document management system, a point-of-sale application, or any other software that deals with printing, C# provides a robust set of libraries to facilitate this PDF print method functionality.
For this purpose, Microsoft C# provides a print method to print PDF files to a default printer. In this article, we'll explore the steps to print a PDF file to a printer using C#.
How to Print a File to a Printer in C
- Create a C# Windows Forms Application
- Import System.Drawing.Printing by using keyword
- Design the Form with a button and other necessary controls
- Handling the PrintDocument Event using PrintPage Event
- Initiate Print job
- Run the application and click the Print button to print
Wymagania wstępne
Przed rozpoczęciem upewnij się, że spełniasz następujące wymagania wstępne:
- A C# development environment (e.g., Visual Studio).
- Adequate permissions to interact with printers.
- Basic understanding of C# programming.
Step 1: Setting Up Your Project
Create a new C# project or open an existing one in your preferred development environment. Ensure that your project is configured correctly, and you have the necessary permissions for printer interactions. The following process allows you to complete this process:
Install Visual Studio
If you don't have Visual Studio installed, download and install it from the official website: Visual Studio.
Utwórz nowy projekt
- Otwórz program Visual Studio.
- Click on "Create a new project".

Choose Project Template
- In the "Create a new project" dialog, select "Windows Forms App (.NET Framework)" or "Windows Forms App (.NET Core)" based on your preference.

- Provide a name and location for your project.

- Click Next and from the additional information screen, select the .NET Framework and click "Create."
Design the Form
- Once the project is created, the main form will be displayed in the designer.
- Use the toolbox to add controls such as buttons, textboxes, labels, etc., to your form as required.
- Customize the properties of each control using the Properties window.

- Adjust the form's appearance and layout.

Step 2: Importing Required Libraries
In your C# code file, import the necessary namespaces to access the classes and methods related to printing.
using System.Drawing.Printing;
using System.Drawing.Printing;
Imports System.Drawing.Printing
These namespaces provide essential classes such as PrintDocument, PrintPageEventArgs, and PrintController for handling print operations.
Step 3: Handling the PrintDocument Event
The PrintDocument class is a cornerstone for printing in C#. Handle its PrintPage event to define what content to print and how it should be formatted. Let's start with a simple example of printing the contents of a text file:
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
// Specify the file path
string filePath = "C:\\path\\to\\your\\file.txt";
// Read the content of the file
string line = System.IO.File.ReadAllText(filePath);
// Create a Font object (adjust as needed)
Font font = new Font("Arial", 12);
// Create a RectangleF to define the printing area
RectangleF area = new RectangleF(e.MarginBounds.Left, e.MarginBounds.Top, e.MarginBounds.Width, e.MarginBounds.Height);
// Draw the content to the printing area
e.Graphics.DrawString(line, font, Brushes.Black, area);
// Set HasMorePages to false to indicate that there are no more pages to print
e.HasMorePages = false;
}
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
// Specify the file path
string filePath = "C:\\path\\to\\your\\file.txt";
// Read the content of the file
string line = System.IO.File.ReadAllText(filePath);
// Create a Font object (adjust as needed)
Font font = new Font("Arial", 12);
// Create a RectangleF to define the printing area
RectangleF area = new RectangleF(e.MarginBounds.Left, e.MarginBounds.Top, e.MarginBounds.Width, e.MarginBounds.Height);
// Draw the content to the printing area
e.Graphics.DrawString(line, font, Brushes.Black, area);
// Set HasMorePages to false to indicate that there are no more pages to print
e.HasMorePages = false;
}
Private Sub printDocument1_PrintPage(ByVal sender As Object, ByVal e As PrintPageEventArgs)
' Specify the file path
Dim filePath As String = "C:\path\to\your\file.txt"
' Read the content of the file
Dim line As String = System.IO.File.ReadAllText(filePath)
' Create a Font object (adjust as needed)
Dim font As New Font("Arial", 12)
' Create a RectangleF to define the printing area
Dim area As New RectangleF(e.MarginBounds.Left, e.MarginBounds.Top, e.MarginBounds.Width, e.MarginBounds.Height)
' Draw the content to the printing area
e.Graphics.DrawString(line, font, Brushes.Black, area)
' Set HasMorePages to false to indicate that there are no more pages to print
e.HasMorePages = False
End Sub
This example reads the content of a text file and prints it using the specified font and formatting.
Step 4: Initiating the Print Job
Initiate the print job by creating an instance of the PrintDocument class, attaching the PrintPage event handler, and then triggering the print process. Optionally, you can display a print dialog for user configuration:
private void btnPrint_Click(object sender, EventArgs e)
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
// Optionally, display a print dialog for user configuration
PrintDialog printDialog = new PrintDialog();
if (printDialog.ShowDialog() == DialogResult.OK)
{
pd.PrinterSettings = printDialog.PrinterSettings;
pd.Print();
}
}
private void btnPrint_Click(object sender, EventArgs e)
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
// Optionally, display a print dialog for user configuration
PrintDialog printDialog = new PrintDialog();
if (printDialog.ShowDialog() == DialogResult.OK)
{
pd.PrinterSettings = printDialog.PrinterSettings;
pd.Print();
}
}
Private Sub btnPrint_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim pd As New PrintDocument()
AddHandler pd.PrintPage, AddressOf printDocument1_PrintPage
' Optionally, display a print dialog for user configuration
Dim printDialog As New PrintDialog()
If printDialog.ShowDialog() = DialogResult.OK Then
pd.PrinterSettings = printDialog.PrinterSettings
pd.Print()
End If
End Sub
This code creates a PrintDocument instance, attaches the PrintPage event handler, and then prints the document. The optional print dialog allows users to configure printing settings before initiating the print job. This prints the text document to a locally connected printer. If it is not present then the file is printed to the default printer name (Microsoft Print to PDF) in the Print dialog as shown below:

Advanced Printing in C# via IronPrint Library
When it comes to handling printing functionality in C# console applications efficiently and effectively, the IronPrint library provides a powerful solution.
Introduction to IronPrint
IronPrint is a comprehensive print library developed by Iron Software, designed to seamlessly integrate with .NET applications. Whether you're working on a desktop, web, or mobile project, IronPrint offers versatile printing PDF documents capabilities, supporting various file formats and providing customizable print settings.

Najważniejsze cechy
- Format Support:IronPrint supports various document formats, including PDF, PNG, TIFF, GIF, JPEG, and BITMAP. This versatility ensures that developers can work with different types of content for printing.
- Customizable Settings:Developers can customize print settings according to their application's requirements. Obejmuje to opcje ustawiania DPI (punktów na cal), określania orientacji papieru (pionowej lub poziomej) oraz kontrolowania liczby kopii.
- Print Dialog:IronPrint facilitates a seamless user experience by allowing developers to show a print dialog before printing. This can be useful in scenarios where users must interact with the printing process and select specific options.
- Print Silently: IronPrint offers a silent printing feature that is particularly beneficial for automation and enhancing workflow efficiency. This allows developers to print invoices without user interaction, eliminating the need for manual intervention and streamlining the overall process.
- Cross-Platform Compatibility:IronPrint goes beyond platform limitations, offering compatibility with a diverse range of environments, including Windows (7+), macOS (10+), iOS (11+), and Android API 21+ (v5 "Lollipop"). It seamlessly integrates with different project types such as Mobile (Xamarin, MAUI & Avalonia), Desktop (WPF, MAUI & Windows Avalonia), and Console (App & Library).
- Broad .NET Version Support:Whether you're using the latest .NET 8, 7, 6, or Core 3.1+, IronPrint has you covered. It also supports the .NET Framework (4.6.2+), ensuring compatibility across various development environments.
Instalacja IronPrint
Before diving into file printing, you need to install the IronPrint library. You can easily do this using the NuGet Package Manager Console:
Install-Package IronPrint
This command line will download and install the IronPrint library into your C# project.
Initializing IronPrint
Once IronPrint is installed, you need to initialize it in your C# code. Import the IronPrint namespace, and set the license key to ensure proper functionality:
using IronPrint;
class Program
{
public static void Main()
{
License.LicenseKey = "YOUR_IRONPRINT_LICENSE_KEY";
}
}
using IronPrint;
class Program
{
public static void Main()
{
License.LicenseKey = "YOUR_IRONPRINT_LICENSE_KEY";
}
}
Imports IronPrint
Friend Class Program
Public Shared Sub Main()
License.LicenseKey = "YOUR_IRONPRINT_LICENSE_KEY"
End Sub
End Class
Printing a File with IronPrint
Printing a file using IronPrint is straightforward. You can use the Printer class, specifying the file path to the Print method to print PDF silently:
using IronPrint;
class Program
{
public static void Main()
{
License.LicenseKey = "YOUR_IRONPRINT_LICENSE_KEY";
// Specify the file path
var document = "C:\\path\\to\\your\\file.pdf";
// Print PDFs
Printer.Print(document);
}
}
using IronPrint;
class Program
{
public static void Main()
{
License.LicenseKey = "YOUR_IRONPRINT_LICENSE_KEY";
// Specify the file path
var document = "C:\\path\\to\\your\\file.pdf";
// Print PDFs
Printer.Print(document);
}
}
Imports IronPrint
Friend Class Program
Public Shared Sub Main()
License.LicenseKey = "YOUR_IRONPRINT_LICENSE_KEY"
' Specify the file path
Dim document = "C:\path\to\your\file.pdf"
' Print PDFs
Printer.Print(document)
End Sub
End Class
Printing silently comes with the benefit of not needing any user interaction to print the PDF, which is helpful for situations where automation is required to streamline the workflow. For situations that require user interaction, such as a dialog box before printing, you can use ShowPrintDialog, which achieves the same result but with a dialog as an additional step.
Although this example only demonstrates printing a PDF file, IronPrint also supports various file formats, including PDF, PNG, TIFF, GIF, JPEG, IMAGE, and BITMAP.
Customizing Print Settings
IronPrint allows you to customize print settings according to your application's requirements. You can configure settings like DPI, number of copies, paper orientation, and more using the PrintSettings class. The following code example helps you set the page settings and print PDF documents:
using IronPrint;
class Program
{
public static void Main()
{
IronPrint.License.LicenseKey = "YOUR_IRONPRINT_LICENSE_KEY";
Console.WriteLine("Printing Started...");
// Specify the file path
string filePath = "C:\\path\\to\\your\\file.pdf";
// Configure print settings
PrintSettings printSettings = new PrintSettings();
printSettings.Dpi = 300;
printSettings.NumberOfCopies = 2;
printSettings.PaperOrientation = PaperOrientation.Landscape;
// Print the document with custom settings
Printer.Print(filePath, printSettings);
// Print using the Print dialog
Printer.ShowPrintDialog(filePath, printSettings);
}
}
using IronPrint;
class Program
{
public static void Main()
{
IronPrint.License.LicenseKey = "YOUR_IRONPRINT_LICENSE_KEY";
Console.WriteLine("Printing Started...");
// Specify the file path
string filePath = "C:\\path\\to\\your\\file.pdf";
// Configure print settings
PrintSettings printSettings = new PrintSettings();
printSettings.Dpi = 300;
printSettings.NumberOfCopies = 2;
printSettings.PaperOrientation = PaperOrientation.Landscape;
// Print the document with custom settings
Printer.Print(filePath, printSettings);
// Print using the Print dialog
Printer.ShowPrintDialog(filePath, printSettings);
}
}
Imports IronPrint
Friend Class Program
Public Shared Sub Main()
IronPrint.License.LicenseKey = "YOUR_IRONPRINT_LICENSE_KEY"
Console.WriteLine("Printing Started...")
' Specify the file path
Dim filePath As String = "C:\path\to\your\file.pdf"
' Configure print settings
Dim printSettings As New PrintSettings()
printSettings.Dpi = 300
printSettings.NumberOfCopies = 2
printSettings.PaperOrientation = PaperOrientation.Landscape
' Print the document with custom settings
Printer.Print(filePath, printSettings)
' Print using the Print dialog
Printer.ShowPrintDialog(filePath, printSettings)
End Sub
End Class
Here is what the output looks like:

If the physical printer is not installed then the default printer is used to print PDF documents. To get all the available printers, you can also use the GetPrinterNames method.
// Retrieve printers' name
List<string> printersName = Printer.GetPrinterNames();
foreach (string printer in printersName)
{
Console.WriteLine(printer);
}
// Retrieve printers' name
List<string> printersName = Printer.GetPrinterNames();
foreach (string printer in printersName)
{
Console.WriteLine(printer);
}
' Retrieve printers' name
Dim printersName As List(Of String) = Printer.GetPrinterNames()
For Each printer As String In printersName
Console.WriteLine(printer)
Next printer
For more detailed information, please visit the documentation page.
Wnioski
Printing files in C# is a manageable task using the capabilities provided by theSystem.Drawing.Printingnamespace. By handling thePrintPageevent and utilizing thePrintDocumentclass, you can tailor the printing process to your specific requirements. This comprehensive guide has covered the fundamental steps in printing files from a C# application, offering a solid foundation to integrate this functionality into your projects.
For developers seeking advanced capabilities, scałability, and automation, IronPrint stands out as an ideal solution. Its intuitive API and additional features surpass the basic packages offered by Microsoft. As we delved deeper into IronPrint, we discovered a range of customization options, including support for various file types, the ability to incorporate images, and enhancements in formatting to better align with the specific needs of an application.
Integrating IronPrint into your C# application simplifies the process of printing files to a printer. With support for various file formats and customizable print settings, IronPrint provides a robust solution for developers looking to enhance their printing capabilities. Whether you're working on a desktop, web, or mobile project, IronPrint streamlines the printing process, making it a valuable addition to your .NET toolkit. Discover the benefits of IronPrint by exploring our free trial page. Download the library from this here and experience its features firsthand!
IronPrint offers a free trial page for more information. Pobierz bibliotekę stąd i wypróbuj ją.
Często Zadawane Pytania
Jak wydrukować plik PDF na drukarce za pomocą języka C#?
Możesz wydrukować plik PDF na drukarce za pomocą języka C#, tworząc aplikację Windows Forms, importując przestrzeń nazw System.Drawing.Printing i obsługując zdarzenie PrintDocument. Aby uzyskać bardziej zaawansowane funkcje, takie jak obsługa różnych formatów plików i konfigurowalne ustawienia drukowania, możesz skorzystać z biblioteki IronPrint firmy Iron Software.
Jakie kroki należy wykonać, aby skonfigurować projekt C# do drukowania?
Aby skonfigurować projekt C# do drukowania, należy najpierw utworzyć nową aplikację Windows Forms w Visual Studio, zaprojektować interfejs formularza i zaimportować przestrzeń nazw System.Drawing.Printing. IronPrint można zintegrować w celu uzyskania rozszerzonych funkcji drukowania, takich jak obsługa wielu formatów i ustawień.
Czy IronPrint obsługuje różne formaty plików do drukowania?
Tak, IronPrint obsługuje szeroki zakres formatów plików, w tym PDF, PNG, HTML, TIFF, GIF, JPEG, IMAGE i BITMAP, co czyni go wszechstronnym wyborem dla programistów potrzebujących drukować różnego rodzaju treści.
Co sprawia, że IronPrint jest solidnym rozwiązaniem do drukowania w aplikacjach C#?
IronPrint oferuje solidne rozwiązania dzięki obsłudze wielu formatów, konfigurowalnym ustawieniom, takim jak DPI i orientacja papieru, oraz kompatybilności międzyplatformowej. Łatwo integruje się również z aplikacjami .NET, zapewniając rozszerzone możliwości drukowania.
Jak dostosować ustawienia drukowania za pomocą IronPrint?
IronPrint pozwala dostosować ustawienia drukowania za pomocą klasy PrintSettings. Można dostosować takie ustawienia, jak rozdzielczość (DPI), liczba kopii i orientacja papieru, aby spełnić konkretne wymagania dotyczące drukowania.
Czy IronPrint jest kompatybilny z różnymi platformami?
Tak, IronPrint jest kompatybilny z wieloma platformami, obsługując środowiska takie jak Windows, macOS, iOS i Android, co pozwala programistom na korzystanie z biblioteki IronPrint w różnych aplikacjach na różnych systemach operacyjnych.
W jaki sposób IronPrint może ulepszyć funkcjonalność drukowania w aplikacji napisanej w języku C#?
IronPrint rozszerza funkcjonalność drukowania, oferując zaawansowane funkcje, takie jak obsługa wielu formatów dokumentów, konfigurowalne ustawienia drukowania oraz płynną integrację z aplikacjami .NET, co usprawnia cały proces drukowania w aplikacjach napisanych w języku C#.
Jak zainicjować zadanie drukowania w języku C# przy użyciu IronPrint?
Aby zainicjować zadanie drukowania w języku C# przy użyciu IronPrint, należy utworzyć instancję klasy PrintDocument, dołączyć procedurę obsługi zdarzenia PrintPage, a następnie użyć metod IronPrint do wykonania zadania drukowania z dowolnymi wymaganymi dostosowaniami.
Co jest potrzebne, aby rozpocząć drukowanie plików w języku C#?
Aby rozpocząć drukowanie plików w języku C#, potrzebne jest środowisko programistyczne, takie jak Visual Studio, uprawnienia dostępu do drukarek oraz podstawowa znajomość programowania w języku C#. Bibliotekę IronPrint można dodać do projektu, aby zapewnić rozszerzone możliwości drukowania.



