Cómo imprimir un documento PDF en C# | IronPRINT

How to Print PDF Files in C#

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

Sending a PDF to a printer from .NET C# code automates the printing process, allowing you to integrate printing functionality into your applications, reducing manual efforts, and ensuring consistency in PDF file production. It provides precise control over the printing process.

IronPDF offers the option to quickly print programmatically to a physical printer in one method call, allowing you to print multiple PDF files. The printer resolution can also be specified with configurable horizontal and vertical DPI. Use the method that accepts both Microsoft PrinterSettings and PrintController for further control over the PDF printing process.

Quickstart: Print PDFs in .NET with IronPDF

Easily print your PDF documents using IronPDF with just a few lines of code. This guide shows you how to quickly integrate PDF printing into your .NET applications. With IronPDF, you can send files directly to printers with minimal setup, all while enjoying flexible settings and high-quality output. Get started now and simplify your document workflow.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf

  2. Copy and run this code snippet.

    IronPdf.PdfDocument.FromFile("example.pdf").Print();
  3. Deploy to test on your live environment

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


Print PDF File Example

The Print method is available through the PdfDocument object, allowing you to print both newly created and existing PDF files. By default, the method uses the system's default printer, but you can specify a different printer by passing its name as a string to the Print method.

Por favor notaAll printing features are only supported on Windows.

:path=/static-assets/pdf/content-code-examples/how-to/print-pdf-print.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Test printing</h1>");

// Send the document to "Microsoft Print to PDF" printer
pdf.Print("Microsoft Print to PDF");
Imports IronPdf

Private renderer As New ChromePdfRenderer()

Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Test printing</h1>")

' Send the document to "Microsoft Print to PDF" printer
pdf.Print("Microsoft Print to PDF")
$vbLabelText   $csharpLabel
Print queue

Printer Resolution

You can specify the resolution of the printed PDF by providing the desired DPI value to the Print method, which will apply the same DPI for both horizontal and vertical dimensions. To use different DPI values, pass two parameters to the method: the first for horizontal (x) DPI and the second for vertical (y) DPI.

:path=/static-assets/pdf/content-code-examples/how-to/print-pdf-dpi.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Test printing</h1>");

// Set custom DPI
pdf.Print(300);

// Specify printing resolution
pdf.Print(10, 10, "Microsoft Print to PDF");
Imports IronPdf

Private renderer As New ChromePdfRenderer()

Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Test printing</h1>")

' Set custom DPI
pdf.Print(300)

' Specify printing resolution
pdf.Print(10, 10, "Microsoft Print to PDF")
$vbLabelText   $csharpLabel

Let's see how to rasterize and print a PDF file in the next example.


Print to File

The PrintToFile method efficiently rasterizes PDF documents by converting them into bitmap (pixel-based) images and saving them as a PDF file. This process is handled by the Windows built-in printer, such as "Microsoft Print to PDF." Notably, this method saves the PDF to disk without sending it to a physical printer.

:path=/static-assets/pdf/content-code-examples/how-to/print-pdf-print-to-file.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Test printing</h1>");

// Print to file
pdf.PrintToFile("");
Imports IronPdf

Private renderer As New ChromePdfRenderer()

Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Test printing</h1>")

' Print to file
pdf.PrintToFile("")
$vbLabelText   $csharpLabel

Explore Print PDF Document Settings

To customize printing options, use the GetPrintDocument method, which accepts Microsoft PrinterSettings and PrintController objects. This method returns the current print document object. The PrinterSettings allows you to configure options such as page range and printer selection, while PrintController enables control over the printing process, including handling exceptions, progress reporting, print dialogs, print previews, and other related tasks. Detailed descriptions of PrinterSettings options are provided below the code example.

:path=/static-assets/pdf/content-code-examples/how-to/print-pdf-printer-setting.cs
using IronPdf;
using System.Drawing.Printing;

ChromePdfRenderer renderer = new ChromePdfRenderer();

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Testing</h1>");

PrinterSettings settings = new PrinterSettings() {
    PrinterName = "Microsoft Print to PDF",

    // Number of Copy
    Copies = 2,

    // Page range to print
    FromPage = 2,
    ToPage = 4,
};

PrintDocument document = pdf.GetPrintDocument(settings);

// Print
document.Print();
Imports IronPdf
Imports System.Drawing.Printing

Private renderer As New ChromePdfRenderer()

Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Testing</h1>")

Private settings As New PrinterSettings() With {
	.PrinterName = "Microsoft Print to PDF",
	.Copies = 2,
	.FromPage = 2,
	.ToPage = 4
}

Private document As PrintDocument = pdf.GetPrintDocument(settings)

' Print
document.Print()
$vbLabelText   $csharpLabel
  • CanDuplex: Indicates whether the printer supports duplex (double-sided) printing. If true, printing on both sides of the paper is possible; otherwise, it cannot.
  • Collate: Specifies whether multiple PDF files or copies of a PDF document should be collated (organized in order) when printed. When true, the printer collates the copies; when false, it does not.
  • Copies: Sets the number of copies of the PDF document to print. It determines how many identical copies of the document will be printed.
  • DefaultPageSettings: Represents the default page settings for the printer, including paper size, margins, and orientation.
  • Duplex: Specifies the duplex (double-sided) printing mode to use. Options include Duplex.Default, Duplex.Simplex (single-sided), Duplex.Horizontal, and Duplex.Vertical.
  • InstalledPrinters: Provides a collection of installed printer names on the system. You can iterate through this collection to get the names of available printers.
  • IsDefaultPrinter: Indicates whether the printer specified in PrinterName is set as the default printer on the system.
  • IsPlotter: Determines whether the printer is a plotter. Plotter printers are often used for large-format printing, such as for architectural or engineering drawings.
  • IsValid: Indicates whether the printer settings are valid and can be used for printing PDF files.
  • LandscapeAngle: Specifies the angle (rotation) of landscape orientation for the printer, usually 90 degrees for portrait.
  • MaximumCopies: Represents the maximum number of copies that can be specified for printing PDF.
  • MaximumPage: Specifies the maximum page number that can be set for printing or conversion.
  • MinimumPage: Specifies the minimum page number that can be set for printing or conversion.
  • PaperSizes: Provides a collection of supported paper sizes for the printer. You can query this collection to determine available paper sizes.
  • PaperSources: Offers a collection of paper sources or trays available for the printer. This can be useful when selecting the paper source for printing PDF files.
  • PrinterName: Specifies the name of the printer to use for printing or conversion.
  • PrinterResolutions: Provides a collection of available printer resolutions, allowing you to choose the print quality.
  • PrintFileName: Gets or sets the file name when printing to a file using PrintToFile.
  • PrintRange: Specifies the range of PDF pages to print, such as all pages, a specific range, or a selection. Use this to print specific pages.
  • FromPage: Specifies the starting page number for printing or conversion. Printing will begin from this page.
  • ToPage: Specifies the ending page number for printing or conversion. Printing will stop after reaching this page.
  • PrintToFile: Indicates whether to print to a file instead of a physical printer. When true, you can specify the file path using PrintFileName.
  • SupportsColor: Indicates whether the printer supports color printing. If true, print in color is supported; otherwise, it is limited to black and white (monochrome) printing.

Lastly, to configure the default printer to print PDFs, you may go to the "Printers & Scanners" section of the machine settings.

Preguntas Frecuentes

¿Cuál es la mejor manera de imprimir documentos PDF usando .NET C#?

La mejor manera de imprimir documentos PDF usando .NET C# es utilizando la biblioteca IronPDF. Proporciona un método `Print` simple que permite enviar archivos PDF directamente a una impresora física.

¿Cómo puedo instalar la biblioteca IronPDF en mi proyecto .NET?

Puedes instalar la biblioteca IronPDF en tu proyecto .NET usando el Administrador de Paquetes NuGet en Visual Studio. Busca 'IronPDF' en el administrador de paquetes NuGet y agrégalo a tu proyecto.

¿Puedo personalizar las configuraciones de impresión para un documento PDF?

Sí, con IronPDF, puedes personalizar las configuraciones de impresión usando el método `GetPrintDocument`, que te permite especificar opciones como la selección de impresora, rango de páginas e impresión a doble cara.

¿Es posible imprimir páginas específicas de un archivo PDF?

Sí, puedes imprimir páginas específicas de un archivo PDF configurando las propiedades `PrintRange`, `FromPage` y `ToPage` dentro del objeto `PrinterSettings` en IronPDF.

¿Cómo imprimo un PDF con configuraciones de alta calidad?

Para imprimir un PDF con configuraciones de alta calidad usando IronPDF, puedes configurar el DPI (puntos por pulgada) especificando los valores deseados en el método `Print` para asegurar una salida de alta resolución.

¿Puedo imprimir archivos PDF en plataformas no Windows?

Actualmente, las características de impresión de IronPDF son soportadas principalmente en plataformas Windows. Sin embargo, la biblioteca es versátil y puede ser utilizada para otras funcionalidades en macOS, Android e iOS.

¿Cómo guardo un documento PDF como un archivo de imagen?

Puedes guardar un documento PDF como un archivo de imagen usando el método `PrintToFile` en IronPDF, que convierte el PDF en imágenes de mapa de bits y las guarda en el disco.

¿IronPDF soporta la impresión a doble cara para documentos PDF?

Sí, IronPDF soporta la impresión a doble cara o dúplex si tu impresora tiene esta capacidad. Esto se puede configurar mediante el objeto `PrinterSettings`.

¿Cómo puedo imprimir múltiples copias de un PDF usando IronPDF?

Puedes imprimir múltiples copias de un PDF configurando la propiedad `Copies` en el objeto `PrinterSettings` en IronPDF al número deseado de copias.

¿Qué debo hacer si mi PDF no se imprime correctamente?

Si tu PDF no se imprime correctamente, asegúrate de tener instalada la última versión de IronPDF y verifica las configuraciones de la impresora en tu aplicación. Asegúrate de que la impresora correcta esté seleccionada y revisa los mensajes de error para más resolución de problemas.

¿IronPDF es totalmente compatible con .NET 10 al imprimir archivos PDF?

Sí. IronPDF es totalmente compatible con .NET 10, al igual que con versiones anteriores de .NET. Admite la impresión mediante métodos como `Print()`, `PrintToFile()` y `GetPrintDocument()` en proyectos .NET 10 sin necesidad de soluciones alternativas ni cambios de configuración. Esto aplica tanto para aplicaciones de escritorio, web, de microservicios como para .NET MAUI.

Chaknith Bin
Ingeniero de Software
Chaknith trabaja en IronXL e IronBarcode. Tiene un profundo conocimiento en C# y .NET, ayudando a mejorar el software y apoyar a los clientes. Sus conocimientos derivados de las interacciones con los usuarios contribuyen a mejores productos, documentación y experiencia en general.
Revisado por
Jeff Fritz
Jeffrey T. Fritz
Gerente Principal de Programas - Equipo de la Comunidad .NET
Jeff también es Gerente Principal de Programas para los equipos de .NET y Visual Studio. Es el productor ejecutivo de la serie de conferencias virtuales .NET Conf y anfitrión de 'Fritz and Friends', una transmisión en vivo para desarrolladores que se emite dos veces a la semana donde habla sobre tecnología y escribe código junto con la audiencia. Jeff escribe talleres, presentaciones, y planifica contenido para los eventos de desarrolladores más importantes de Microsoft, incluyendo Microsoft Build, Microsoft Ignite, .NET Conf y la Cumbre de Microsoft MVP.
¿Listo para empezar?
Nuget Descargas 16,154,058 | Versión: 2025.11 recién lanzado