C# Imprimir Documentos PDF

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

Puede imprimir fácilmente un PDF en aplicaciones .NET con la ayuda de código Visual Basic o C#. Este tutorial le mostrará cómo utilizar las funciones de impresión de PDF de C# para imprimir mediante programación.



Biblioteca NuGet C# para PDF

Instalar con NuGet

Install-Package IronPdf
o
Java PDF JAR

Descargar DLL

Descargar DLL

Instalar manualmente en su proyecto

Crear un PDF e imprimir

Puede enviar un documento PDF directamente a una impresora de forma silenciosa o crear un System.Drawing.Printing.PrintDocument con el que se puede trabajar y enviar a diálogos de impresión GUI.

El siguiente código puede utilizarse para ambas opciones:

:path=/static-assets/pdf/content-code-examples/how-to/csharp-print-pdf-create-and-print-pdf.cs
using IronPdf;
using System.Threading.Tasks;

// Create a new PDF and print it
ChromePdfRenderer renderer = new ChromePdfRenderer();

PdfDocument pdf = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf");

// Print PDF from default printer
await pdf.Print();

// For advanced silent real-world printing options, use PdfDocument.GetPrintDocument
// Remember to add an assembly reference to System.Drawing.dll
System.Drawing.Printing.PrintDocument PrintDocYouCanWorkWith = pdf.GetPrintDocument();
Imports IronPdf
Imports System.Threading.Tasks

' Create a new PDF and print it
Private renderer As New ChromePdfRenderer()

Private pdf As PdfDocument = renderer.RenderUrlAsPdf("https://www.nuget.org/packages/IronPdf")

' Print PDF from default printer
Await pdf.Print()

' For advanced silent real-world printing options, use PdfDocument.GetPrintDocument
' Remember to add an assembly reference to System.Drawing.dll
Dim PrintDocYouCanWorkWith As System.Drawing.Printing.PrintDocument = pdf.GetPrintDocument()
VB   C#

Impresión avanzada

IronPDF es bastante capaz de lidiar con características avanzadas de Impresión como encontrar el nombre de la impresora o configurarlo y establecer la resolución de la Impresora.

Especifique el nombre de la impresora

Para especificar el nombre de la impresora, basta con obtener el objeto de documento de impresión actual (con el uso del GetPrintDocument método del documento PDF)utilice la propiedad PrinterSettings.PrinterName de la siguiente manera:

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

PdfDocument pdf = PdfDocument.FromFile("sample.pdf");

// Get PrintDocument object
var printDocument = pdf.GetPrintDocument();

// Assign the printer name
printDocument.PrinterSettings.PrinterName = "Microsoft Print to PDF";

// Print document
printDocument.Print();
Imports IronPdf

Private pdf As PdfDocument = PdfDocument.FromFile("sample.pdf")

' Get PrintDocument object
Private printDocument = pdf.GetPrintDocument()

' Assign the printer name
printDocument.PrinterSettings.PrinterName = "Microsoft Print to PDF"

' Print document
printDocument.Print()
VB   C#

Configurar la resolución de la impresora

La resolución se refiere al número de píxeles que se imprimen, o se muestran, dependiendo de la salida. Puede establecer la resolución de su impresión a través de IronPDF haciendo uso de la opción DefaultPageSettings.PrinterResolution del documento PDF. He aquí una demostración muy rápida:

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

PdfDocument pdf = PdfDocument.FromFile("sample.pdf");

// Get PrintDocument object
var printDocument = pdf.GetPrintDocument();

// Set printer resolution
printDocument.DefaultPageSettings.PrinterResolution = new PrinterResolution
{
    Kind = PrinterResolutionKind.Custom,
    X = 1200,
    Y = 1200
};

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

Private pdf As PdfDocument = PdfDocument.FromFile("sample.pdf")

' Get PrintDocument object
Private printDocument = pdf.GetPrintDocument()

' Set printer resolution
printDocument.DefaultPageSettings.PrinterResolution = New PrinterResolution With {
	.Kind = PrinterResolutionKind.Custom,
	.X = 1200,
	.Y = 1200
}

' Print document
printDocument.Print()
VB   C#

Como puedes ver, he ajustado la resolución a un nivel personalizado: 1200 vertical y 1200 horizontal.

Método PrintToFile

El método PdfDocument.PrintToFile permite imprimir el PDF en un archivo. Sólo tiene que indicar la ruta del archivo de salida y especificar si desea ver una vista previa. El código siguiente imprimirá en el archivo especificado sin incluir una vista previa:

:path=/static-assets/pdf/content-code-examples/how-to/csharp-print-pdf-printtofile.cs
using IronPdf;
using System.Threading.Tasks;

PdfDocument pdf = PdfDocument.FromFile("sample.pdf");

await pdf.PrintToFile("PathToFile", false);
Imports IronPdf
Imports System.Threading.Tasks

Private pdf As PdfDocument = PdfDocument.FromFile("sample.pdf")

Await pdf.PrintToFile("PathToFile", False)
VB   C#

Seguimiento de los procesos de impresión con C#

La belleza de C# en conjunción con IronPDF es que cuando se trata de realizar un seguimiento de las páginas impresas, o cualquier cosa relacionada con la impresión, en realidad es bastante simple. En el siguiente ejemplo demostraré cómo cambiar el nombre de la impresora, la resolución, así como la forma de obtener un recuento de las páginas que se imprimieron.

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

PdfDocument pdf = PdfDocument.FromFile("sample.pdf");

// Get PrintDocument object
var printDocument = pdf.GetPrintDocument();

// Subscribe to the PrintPage event
var printedPages = 0;
printDocument.PrintPage += (sender, args) => printedPages++;

// Print document
printDocument.Print();
Imports IronPdf

Private pdf As PdfDocument = PdfDocument.FromFile("sample.pdf")

' Get PrintDocument object
Private printDocument = pdf.GetPrintDocument()

' Subscribe to the PrintPage event
Private printedPages = 0
Private printDocument.PrintPage += Sub(sender, args) printedPages++

' Print document
printDocument.Print()
VB   C#