Saltar al pie de página
USANDO IRONPRINT

Imprimir PDF a una Impresora Específica en C# (Tutorial con Ejemplo de Código)

There are many instances where developers may need to print PDF documents directly from their application. This task can sometimes seem complicated when the user either wants to print multiple PDF files or use a specific printer name other than the default printer. Multiple methods can assist us with printing PDF files. Some of these need to be paid for, some perform erratically, and some are difficult to implement.

IronPDF is a .NET library that provides a set of classes for creating PDF files programmatically. These classes are located in the IronPDF.Core assembly and are designed to be easy to use with any .NET language, including C#, VB.NET, F#, etc. The library offers many functions for creating PDF documents, manipulating existing PDFs, reading PDFs, printing PDFs, and programmatically creating PDF Forms.

Let's take a look at some example code snippets for printing a PDF file.

Install IronPDF

First of all, install the IronPDF library. For that, go to the Package Manager Console and write the following command.

Install-Package IronPrint

C# Print PDF to Specific Printer (Code Example Tutorial), Figure 1: Install the package via the Package Manager Console Install the package via the Package Manager Console

The next step is to create a PDF document. You can also simply load an existing PDF document if you don't want to create a new one. Let's create a PDF document.

Create a PDF Document using a URL

IronPDF provides two functions for creating a PDF document using a URL: RenderUrlAsPdf and RenderUrlAsPdfAsync. The RenderUrlAsPdfAsync provides asynchronous functionality.

The following code snippet will create a PDF file from the URL.

var renderer = new IronPdf.ChromePdfRenderer();
PdfDocument doc = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/PDF");
var renderer = new IronPdf.ChromePdfRenderer();
PdfDocument doc = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/PDF");
Dim renderer = New IronPdf.ChromePdfRenderer()
Dim doc As PdfDocument = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/PDF")
$vbLabelText   $csharpLabel

Create a PDF Document using HTML String

It is possible to create a PDF document using an HTML string. IronPDF provides two methods for this purpose: RenderHtmlAsPdf and RenderHtmlAsPdfAsync. The RenderHtmlAsPdfAsync method is for asynchronous operations.

The following code snippet will create a PDF file from the HTML string.

IronPdf.ChromePdfRenderer renderer = new IronPdf.ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf(@"<h1>My PDF File</h1> <p>This is a sample PDF document created to demonstrate the PDF file generation using HTML string</p>");
IronPdf.ChromePdfRenderer renderer = new IronPdf.ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf(@"<h1>My PDF File</h1> <p>This is a sample PDF document created to demonstrate the PDF file generation using HTML string</p>");
Dim renderer As New IronPdf.ChromePdfRenderer()
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>My PDF File</h1> <p>This is a sample PDF document created to demonstrate the PDF file generation using HTML string</p>")
$vbLabelText   $csharpLabel

Print PDF Files to a Specific Printer

Printing PDF files to a specific printer can be done easily by using the PrinterName property of PrinterSettings. Here's a demonstration of how to print PDF documents to a specific printer in C#.

var printDoc = pdf.GetPrintDocument();
printDoc.PrinterSettings.PrinterName = "myPrinter";
var printDoc = pdf.GetPrintDocument();
printDoc.PrinterSettings.PrinterName = "myPrinter";
Dim printDoc = pdf.GetPrintDocument()
printDoc.PrinterSettings.PrinterName = "myPrinter"
$vbLabelText   $csharpLabel

The pdf variable refers to the PDF document that was created. The GetPrintDocument method returns a PrintDocument instance, allowing granular control over sending the PDF to a printer.

Print Dialogue

If the user needs to select all the printer settings using a UI dialogue similar to that appearing in a Word document or Adobe Acrobat, IronPDF can show the print GUI dialogue by passing a single parameter to the Print function.

pdf.Print(true);
pdf.Print(true);
pdf.Print(True)
$vbLabelText   $csharpLabel

Passing true to the Print function's argument displays the GUI print dialogue. By default, the Print function prints to the default printer.

Specify the Number of Copies

Printing multiple copies of a single document can be achieved by setting the Copies property of PrinterSettings. The following sample code shows this:

var printDoc = pdf.GetPrintDocument();
printDoc.PrinterSettings.Copies = 5;
var printDoc = pdf.GetPrintDocument();
printDoc.PrinterSettings.Copies = 5;
Dim printDoc = pdf.GetPrintDocument()
printDoc.PrinterSettings.Copies = 5
$vbLabelText   $csharpLabel

Here, the pdf is the current print document object.

Select Page Range to Print PDF file

If you do not wish to print a complete document, you can specify the FromPage and ToPage properties of PrinterSettings.

var printDoc = pdf.GetPrintDocument();
printDoc.PrinterSettings.FromPage = 3;
printDoc.PrinterSettings.ToPage = 3;
var printDoc = pdf.GetPrintDocument();
printDoc.PrinterSettings.FromPage = 3;
printDoc.PrinterSettings.ToPage = 3;
Dim printDoc = pdf.GetPrintDocument()
printDoc.PrinterSettings.FromPage = 3
printDoc.PrinterSettings.ToPage = 3
$vbLabelText   $csharpLabel

This code sets both the starting and ending pages for printing, so only a specific range of the document prints.

Collate Property

The Collate feature in printing means if you're printing more than one copy of a multi-page document, the copies will print all pages of each copy before printing the second copy. You can set this property as needed.

var printDoc = pdf.GetPrintDocument();
printDoc.PrinterSettings.Collate = false;
var printDoc = pdf.GetPrintDocument();
printDoc.PrinterSettings.Collate = false;
Dim printDoc = pdf.GetPrintDocument()
printDoc.PrinterSettings.Collate = False
$vbLabelText   $csharpLabel

With Collate set to false, the printer will print all required copies of each page before printing the next page.

Get Paper Sources

To retrieve available paper sources for the printer, use the following code:

var paperSources = pdf.GetPrintDocument().PrinterSettings.PaperSources;
var paperSources = pdf.GetPrintDocument().PrinterSettings.PaperSources;
Dim paperSources = pdf.GetPrintDocument().PrinterSettings.PaperSources
$vbLabelText   $csharpLabel

Conclusion

IronPDF provides all the necessary features for developing .NET applications that require printing functionalities. Multiple options are available for printing PDF files, allowing you to choose the best fit for your needs and print multiple PDF files.

Summary

This tutorial demonstrated how to print PDFs straightforwardly to a specific printer using the IronPDF library — it is free for development and provides high-performance levels. For more print PDF capabilities with IronPDF, explore this sample page.

Furthermore, IronPDF is capable of rendering charts, adding barcodes, enhancing security with passwords, and watermarking in just a few lines of code.

Additionally, there are other useful libraries such as IronXL for working with Excel documents, IronBarcode for working with barcodes, and IronOCR for working with OCR. You can get all five libraries for the price of just two by purchasing the complete Iron Suite. Please visit the licensing page for more details.

Preguntas Frecuentes

¿Cómo imprimo un PDF en una impresora específica en C#?

Para imprimir un PDF en una impresora específica en C#, use IronPDF para establecer la propiedad PrinterName de PrinterSettings con el nombre de la impresora deseada y ejecute el método Print.

¿Puedo personalizar la configuración de DPI al imprimir un PDF?

Sí, IronPDF te permite personalizar la configuración de DPI al imprimir un PDF. Puedes especificar el DPI en la clase PrintDoc para satisfacer tus necesidades de calidad de impresión.

¿Cómo puedo mostrar un diálogo de impresión al imprimir un PDF con IronPDF?

Para mostrar un diálogo de impresión, pasa 'true' al argumento de la función Print en IronPDF. Esto activará el diálogo de impresión GUI para ajustar las configuraciones de la impresora antes de imprimir.

¿Es posible imprimir solo un rango específico de páginas de un PDF?

Sí, con IronPDF, puedes imprimir un rango específico de páginas estableciendo las propiedades FromPage y ToPage de PrinterSettings antes de ejecutar el comando de impresión.

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

Para imprimir múltiples copias, establece la propiedad Copies de PrinterSettings en IronPDF al número deseado de copias antes de ejecutar el método Print.

¿Qué hace la opción Collate al imprimir PDFs?

La opción Collate en IronPDF asegura que todas las páginas de cada copia se impriman secuencialmente antes de comenzar a imprimir la siguiente copia, lo cual es útil al imprimir múltiples copias de un documento.

¿Cómo puedo recuperar las fuentes de papel disponibles para una impresora?

En IronPDF, puedes usar la propiedad PaperSources de PrinterSettings para recuperar y seleccionar entre las fuentes de papel disponibles para una impresora específica.

¿Qué características adicionales ofrece IronPDF para la manipulación de PDF?

IronPDF ofrece características como renderizar HTML y URLs como PDFs, agregar códigos de barras, mejorar la seguridad del documento con contraseñas, marca de agua y más, convirtiéndolo en una herramienta completa para desarrolladores.

¿Cómo instalo la biblioteca IronPDF para manipulación de PDF?

Para instalar IronPDF, usa el comando Install-Package IronPdf en la Consola del Administrador de Paquetes para agregar la biblioteca a tu proyecto .NET.

¿Puede IronPDF renderizar documentos PDF existentes para impresión?

Sí, IronPDF puede renderizar tanto documentos PDF nuevos como existentes para impresión, permitiéndote especificar configuraciones de impresora y ejecutar el comando de impresión con facilidad.

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