Cómo imprimir un documento PDF en C#

Print Document Tutorial

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronPrint is a powerful printing library designed to assist .NET C# developers in integrating printing capabilities into their applications. With a broad compatibility spectrum spanning across Windows, macOS, iOS, and Android platforms, IronPrint works consistently and reliably across diverse operating systems. Whether you are creating applications for desktop environments, Apple's macOS ecosystem, or mobile platforms like iOS and Android, IronPrint simplifies the implementation of printing features, providing a versatile and user-friendly solution for all your printing needs in the .NET C# environment.

Quickstart: Silently Print a Document with IronPrint

Just one line of code and you’re printing—no dialogs, no fuss. Use IronPrint.Printer.Print(...) to silently send PDFs or images straight to the printer using default or custom settings.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronPrint with NuGet Package Manager

    PM > Install-Package IronPrint

  2. Copy and run this code snippet.

    IronPrint.Printer.Print("path/to/your/document.pdf");
  3. Deploy to test on your live environment

    Start using IronPrint in your project today with a free trial
    arrow pointer

Table of Contents

Print Document

Print Silently

Print documents seamlessly without displaying the print dialog. The print settings can then be done directly within the code.

// Programmatically print a document without showing the print dialog.
// Define your print job and settings here as needed.

using System;
using IronPrint;

public class SilentPrint
{
    public static void Main()
    {
        // Create a print document instance
        var document = new PrintDocument("sample-document.pdf");

        // Initialize a silent print job
        var printJob = new PrintJob(document);

        // Apply specific settings as necessary
        // For example: set printer name, copies, etc.

        // Execute the print job
        printJob.PrintSilently();
    }
}
// Programmatically print a document without showing the print dialog.
// Define your print job and settings here as needed.

using System;
using IronPrint;

public class SilentPrint
{
    public static void Main()
    {
        // Create a print document instance
        var document = new PrintDocument("sample-document.pdf");

        // Initialize a silent print job
        var printJob = new PrintJob(document);

        // Apply specific settings as necessary
        // For example: set printer name, copies, etc.

        // Execute the print job
        printJob.PrintSilently();
    }
}
' Programmatically print a document without showing the print dialog.
' Define your print job and settings here as needed.

Imports System
Imports IronPrint

Public Class SilentPrint
	Public Shared Sub Main()
		' Create a print document instance
		Dim document = New PrintDocument("sample-document.pdf")

		' Initialize a silent print job
		Dim printJob As New PrintJob(document)

		' Apply specific settings as necessary
		' For example: set printer name, copies, etc.

		' Execute the print job
		printJob.PrintSilently()
	End Sub
End Class
$vbLabelText   $csharpLabel

Print With Dialog

Initiate the printing process with the print setting dialog displayed. This allows users to customize print options interactively.

// Start a print job with user interaction through the print dialog.

using System;
using IronPrint;

public class DialogPrint
{
    public static void Main()
    {
        // Create a print document instance
        var document = new PrintDocument("sample-document.pdf");

        // Initialize a print job with dialog
        var printJob = new PrintJob(document);

        // Execute the print job with display of print options dialog
        printJob.PrintWithDialog();
    }
}
// Start a print job with user interaction through the print dialog.

using System;
using IronPrint;

public class DialogPrint
{
    public static void Main()
    {
        // Create a print document instance
        var document = new PrintDocument("sample-document.pdf");

        // Initialize a print job with dialog
        var printJob = new PrintJob(document);

        // Execute the print job with display of print options dialog
        printJob.PrintWithDialog();
    }
}
' Start a print job with user interaction through the print dialog.

Imports System
Imports IronPrint

Public Class DialogPrint
	Public Shared Sub Main()
		' Create a print document instance
		Dim document = New PrintDocument("sample-document.pdf")

		' Initialize a print job with dialog
		Dim printJob As New PrintJob(document)

		' Execute the print job with display of print options dialog
		printJob.PrintWithDialog()
	End Sub
End Class
$vbLabelText   $csharpLabel

Apply Print Settings

Programmatically adjust print settings to meet specific requirements. This section provides the capability to fine-tune printing configurations through code.

// Example code to apply custom print settings programmatically.

using System;
using IronPrint;

public class PrintSettingsExample
{
    public static void Main()
    {
        // Create a print document instance
        var document = new PrintDocument("sample-document.pdf");

        // Create a print job
        var printJob = new PrintJob(document);

        // Set custom print settings like duplex, color mode, etc.
        var settings = new PrintSettings
        {
            ColorMode = ColorMode.Color,
            DuplexMode = DuplexMode.OneSided,
            Copies = 2
        };

        // Apply settings to print job
        printJob.ApplySettings(settings);

        // Print the document
        printJob.PrintSilently();
    }
}
// Example code to apply custom print settings programmatically.

using System;
using IronPrint;

public class PrintSettingsExample
{
    public static void Main()
    {
        // Create a print document instance
        var document = new PrintDocument("sample-document.pdf");

        // Create a print job
        var printJob = new PrintJob(document);

        // Set custom print settings like duplex, color mode, etc.
        var settings = new PrintSettings
        {
            ColorMode = ColorMode.Color,
            DuplexMode = DuplexMode.OneSided,
            Copies = 2
        };

        // Apply settings to print job
        printJob.ApplySettings(settings);

        // Print the document
        printJob.PrintSilently();
    }
}
' Example code to apply custom print settings programmatically.

Imports System
Imports IronPrint

Public Class PrintSettingsExample
	Public Shared Sub Main()
		' Create a print document instance
		Dim document = New PrintDocument("sample-document.pdf")

		' Create a print job
		Dim printJob As New PrintJob(document)

		' Set custom print settings like duplex, color mode, etc.
		Dim settings = New PrintSettings With {
			.ColorMode = ColorMode.Color,
			.DuplexMode = DuplexMode.OneSided,
			.Copies = 2
		}

		' Apply settings to print job
		printJob.ApplySettings(settings)

		' Print the document
		printJob.PrintSilently()
	End Sub
End Class
$vbLabelText   $csharpLabel

Get Printer Information

Get Printer Names

Access a list of all available printers. Retrieve the names of printers installed on the system for informative purposes or dynamic printer selection in your application.

// Retrieve and display a list of printer names available on the system.

using System;
using IronPrint;

public class PrinterInfo
{
    public static void Main()
    {
        // Get an enumerable list of printer names
        var printerNames = PrinterSettings.GetAvailablePrinters();

        // Print each printer name to the console
        Console.WriteLine("Available Printers:");
        foreach (var name in printerNames)
        {
            Console.WriteLine(name);
        }
    }
}
// Retrieve and display a list of printer names available on the system.

using System;
using IronPrint;

public class PrinterInfo
{
    public static void Main()
    {
        // Get an enumerable list of printer names
        var printerNames = PrinterSettings.GetAvailablePrinters();

        // Print each printer name to the console
        Console.WriteLine("Available Printers:");
        foreach (var name in printerNames)
        {
            Console.WriteLine(name);
        }
    }
}
' Retrieve and display a list of printer names available on the system.

Imports System
Imports IronPrint

Public Class PrinterInfo
	Public Shared Sub Main()
		' Get an enumerable list of printer names
		Dim printerNames = PrinterSettings.GetAvailablePrinters()

		' Print each printer name to the console
		Console.WriteLine("Available Printers:")
		For Each name In printerNames
			Console.WriteLine(name)
		Next name
	End Sub
End Class
$vbLabelText   $csharpLabel

Preguntas Frecuentes

¿Cómo puedo imprimir documentos en silencio en .NET C#?

Puede usar el método PrintSilently() de una instancia de PrintJob para ejecutar trabajos de impresión sin interacción del usuario. Esto permite que el documento se imprima programáticamente sin mostrar el cuadro de diálogo de impresión.

¿Cuál es el proceso para imprimir un documento con un cuadro de diálogo de impresión en .NET C#?

Puede iniciar un trabajo de impresión con interacción del usuario usando el método PrintWithDialog() en una instancia de PrintJob. Esto muestra el cuadro de diálogo de configuración de impresión, permitiendo a los usuarios personalizar las opciones antes de imprimir.

¿Es posible aplicar ajustes de impresión personalizados programáticamente en .NET C#?

Sí, puede aplicar ajustes de impresión personalizados programáticamente creando un objeto PrintSettings y configurando propiedades como el modo de color, el modo dúplex y el número de copias. Estos ajustes se pueden aplicar a una instancia de PrintJob.

¿Cómo puedo recuperar los nombres de impresoras disponibles en una aplicación .NET C#?

Puede recuperar los nombres de impresoras disponibles usando el método PrinterSettings.GetAvailablePrinters(). Esto proporciona una lista enumerable de nombres de impresoras instaladas en el sistema para selección o propósitos informativos.

¿Puedo imprimir diferentes formatos de documentos usando una biblioteca .NET C#?

Sí, la biblioteca admite la impresión de varios formatos de documentos, incluidos PDF, PNG, HTML, TIFF, GIF, JPEG, IMAGE y BITMAP, permitiendo opciones versátiles de impresión de documentos.

¿Qué plataformas son compatibles para imprimir documentos usando la biblioteca .NET C#?

La biblioteca admite múltiples plataformas, como Windows, macOS, iOS y Android, asegurando capacidades de impresión consistentes y confiables a través de estos sistemas operativos.

¿Cómo difiere la impresión silenciosa de la impresión basada en diálogo en .NET C#?

La impresión silenciosa permite imprimir documentos programáticamente sin la interacción del usuario, usando el método PrintSilently(). La impresión basada en diálogo implica mostrar un cuadro de diálogo de impresión para personalización del usuario, logrado a través del método PrintWithDialog().

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más
¿Listo para empezar?
Nuget Descargas 34,016 | Versión: 2025.11 recién lanzado