USING IRONPRINT

How to Print a File to a Printer in C#

Published April 29, 2024
Share:

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#

  1. Create a C# Windows Forms Application
  2. Import System.Drawing.Printing by using keyword
  3. Design the Form with a button and other necessary controls
  4. Handling the PrintDocument Event using PrintPage Event
  5. Initiate Print job
  6. Run the application and click the Print button to print

Prerequisites

Before getting started, make sure you have the following prerequisites in place:

  1. A C# development environment (e.g., Visual Studio).
  2. Adequate permissions to interact with printers.
  3. 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.

Create a New Project

  1. Open Visual Studio.
    1. Click on "Create a new project".

How to Print a File to a Printer in C#: Figure 1 - New Project

Choose Project Template

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

How to Print a File to a Printer in C#: Figure 2 - Windows Forms App

  1. Provide a name and location for your project.

How to Print a File to a Printer in C#: Figure 3 - Project Configuration

  1. Click Next and from the additional information screen, select the .NET Framework and click "Create."

Design the Form

  1. Once the project is created, the main form will be displayed in the designer.
  2. Use the toolbox to add controls such as buttons, textboxes, labels, etc., to your form as required.
    1. Customize the properties of each control using the Properties window.

How to Print a File to a Printer in C#: Figure 4 - Form Design

  1. Adjust the form's appearance and layout.

How to Print a File to a Printer in C#: Figure 5 - Print Form

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
VB   C#

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
VB   C#

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
VB   C#

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:

How to Print a File to a Printer in C#: Figure 6 - Microsoft Print Dialog

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.

How to Print a File to a Printer in C#: Figure 7 - IronPrint

Key Features

  1. Format Support: IronPrint supports a variety of document formats, including PDF, PNG, HTML, TIFF, GIF, JPEG, and BITMAP. This versatility ensures that developers can work with different types of content for printing.
  2. Customizable Settings: Developers have the flexibility to customize print settings according to their application's requirements. This includes options to set DPI (dots per inch), specify paper orientation (portrait or landscape), and control the number of copies.
  3. 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 need to interact with the printing process and select specific options.
  4. 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).
  5. Broad .NET Version Support: Whether you're using the latest .NET 8, 7, 6, or Core 3.1+, IronPrint has you covered. It also extends its support to the .NET Framework (4.6.2+), ensuring compatibility across various development environments.

Installing 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
VB   C#

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
{
// static void main
    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
{
// static void main
    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
' static void main
	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
VB   C#

This example demonstrates printing a PDF file, but IronPrint supports a variety of file formats, including PDF, PNG, HTML, 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
VB   C#

Here is what the output looks like:

How to Print a File to a Printer in C#: Figure 8 - Customized Print Output

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 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
VB   C#

For more detailed information, please visit the documentation page.

Conclusion

Printing files in C# is a manageable task with the capabilities provided by the System.Drawing.Printing namespace. By handling the PrintPage event and utilizing the PrintDocument class, you can tailor the printing process to your specific requirements. This comprehensive guide has covered the fundamental steps involved in printing files from a C# application, offering you a solid foundation to integrate this functionality into your projects. As we explored further, we looked at IronPrint for additional customization options, such as handling different file types, incorporating images, and enhancing formatting based on the application's needs.

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.

IronPrint offers a free trial page for more information. Download the library from here and give it a try.

< PREVIOUS
How to Print a QR Code in C#
NEXT >
How to Print a QR code in C#

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 10,762 View Licenses >