Saltar al pie de página
COMPARACIONES DE PRODUCTOS

PdfiumViewer Imprimir PDF en C# (Tutorial Alternativo)

PDF documents play a crucial role in various software applications, including generating invoices, displaying reports, and sharing information. When it comes to working with PDFs in C#, developers have multiple options. This article explores two popular libraries for printing PDFs using Microsoft Print in C#:

  • IronPDF
  • PDFiumViewer

Let's delve into their features and ease of use and compare their printing capabilities to help you make an informed decision for your next C# project.

IronPDF

Overview of IronPDF

IronPDF is a robust C# library designed for creating, manipulating, and processing PDFs effortlessly. It offers a wide range of features, making it a preferred choice among developers. IronPDF stands out for its ability to:

  • Convert HTML, CSS, and images to PDF files.
  • Generate PDF documents from scratch.
  • Edit existing PDFs.
  • Support various PDF document elements like images, text, tables, and forms.
  • Provide advanced functionalities such as digital signatures, watermarks, and encryption.
  • Enable silent printing without any third-party tools or libraries.
  • Offer a user-friendly interface and comprehensive documentation.

PDFiumViewer

Overview of PDFiumViewer

PDFiumViewer is another popular option for working with PDFs in C#. Built on top of the open-source PDFium project, it provides a .NET wrapper for its functionality. PDFiumViewer offers:

  • The ability to render PDFs and display them in Windows Forms applications.
  • Support for navigation, zooming, and text selection within PDF documents.
  • A straightforward integration process for Windows Forms projects.

Installing IronPDF

To start using IronPDF, follow these steps to install it using the NuGet Package Manager in Visual Studio:

  1. Open Visual Studio and create a new Console Application or open an existing one.

    PdfiumViewer Print PDF in C# (Alternative Tutorial) Figure 1 - New Project- PDFiumViewer Print PDF C#

  2. Right-click on the project in the Solution Explorer and select "Manage NuGet Packages."
  3. Switch to the "Browse" tab, search for "IronPDF," and click "Install."

    PdfiumViewer Print PDF in C# (Alternative Tutorial) Figure 2 - IronPDF Installation

With IronPDF successfully installed, we can begin using it for printing PDFs and other PDF document-related tasks. Before that, let's also install PDFiumViewer in our system.

Installing PDFiumViewer

You can install PDFiumViewer via the NuGet Package Manager as well. Here's how:

  1. Open your Visual Studio project and create a Windows Forms application.

    PdfiumViewer Print PDF in C# (Alternative Tutorial) Figure 3 - New Project

  2. Drag a button to the Form and name it "Print PDF".

    PdfiumViewer Print PDF in C# (Alternative Tutorial) Figure 4 - Print Button

  3. Right-click on the project in the Solution Explorer and choose "Manage NuGet Packages."
  4. In the "NuGet Package Manager" window, switch to the "Browse" tab, search for "PDFiumViewer" and click "Install."

    PdfiumViewer Print PDF in C# (Alternative Tutorial) Figure 5 - PDFiumViewer Installation

  5. Alternatively, to install the PDFium DLL, you can search for "PDFiumViewer.Native" 32-bit or 64-bit, depending on your OS requirements. This DLL is necessary to load PDF files or pages using PDFiumViewer in a Windows Forms application.

    PdfiumViewer Print PDF in C# (Alternative Tutorial) Figure 6 - PDFiumViewer.Native

Once the installation is complete, you can start using PDFiumViewer for printing PDF files and other PDF-related tasks.

Printing PDFs with IronPDF

Printing PDFs using IronPDF is straightforward. Here's the source code example demonstrating how to print a PDF file without a printer name:

using IronPdf;

class Program
{
    static void Main()
    {
        // Create a new PDF renderer
        var renderer = new ChromePdfRenderer();

        // Render a PDF from a URL
        PdfDocument pdf = renderer.RenderUrlAsPdf("https://ironpdf.com");

        // Print the PDF document, 300 dpi, without printer name
        pdf.Print(300, true);
    }
}
using IronPdf;

class Program
{
    static void Main()
    {
        // Create a new PDF renderer
        var renderer = new ChromePdfRenderer();

        // Render a PDF from a URL
        PdfDocument pdf = renderer.RenderUrlAsPdf("https://ironpdf.com");

        // Print the PDF document, 300 dpi, without printer name
        pdf.Print(300, true);
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main()
		' Create a new PDF renderer
		Dim renderer = New ChromePdfRenderer()

		' Render a PDF from a URL
		Dim pdf As PdfDocument = renderer.RenderUrlAsPdf("https://ironpdf.com")

		' Print the PDF document, 300 dpi, without printer name
		pdf.Print(300, True)
	End Sub
End Class
$vbLabelText   $csharpLabel

In this code example, IronPDF efficiently renders a PDF from a URL and sends it to the default printer for printing. The method Print is configured for a resolution of 300 DPI, allowing silent printing without prompting the user. For more advanced printing options, please visit the C# Print PDF Documents.

Output

Upon executing the project, the Print method displays a print dialog to save the file as a PDF. If the default printer is set to a physical printer, the document will be printed directly.

PdfiumViewer Print PDF in C# (Alternative Tutorial) Figure 7 - Print Dialog

The output saved is a pixel-perfect PDF document:

PdfiumViewer Print PDF in C# (Alternative Tutorial) Figure 8 - PDF Output

Printing PDFs with PDFiumViewer

While PDFiumViewer excels in rendering and displaying PDFs, it doesn't provide native PDF printing capabilities. To print a PDF document using PDFiumViewer, you'll need to utilize additional third-party drawing tools or libraries. To print directly using PDFiumViewer, we need to use Microsoft's System.Drawing.Printing assembly along with the PDFiumViewer library.

In the following code, first, we load the PDF using the PdfDocument.Load method. Then, we create a printing object called printDocument using the CreatePrintDocument method, which comes from the System.Drawing.Printing namespace. Finally, we use the Print method to send the loaded PDF to the printer for printing.

using System;
using System.Drawing.Printing;
using PdfiumViewer;

class Program
{
    static void Main()
    {
        string pathToFile = @"C:\assets\input.pdf"; // Absolute path with filename

        // Load the PDF document
        using (var pdf = PdfDocument.Load(pathToFile))
        {
            // Create a print document for the loaded PDF
            var printDocument = pdf.CreatePrintDocument();

            // Print the document
            printDocument.Print();
        }
    }
}
using System;
using System.Drawing.Printing;
using PdfiumViewer;

class Program
{
    static void Main()
    {
        string pathToFile = @"C:\assets\input.pdf"; // Absolute path with filename

        // Load the PDF document
        using (var pdf = PdfDocument.Load(pathToFile))
        {
            // Create a print document for the loaded PDF
            var printDocument = pdf.CreatePrintDocument();

            // Print the document
            printDocument.Print();
        }
    }
}
Imports System
Imports System.Drawing.Printing
Imports PdfiumViewer

Friend Class Program
	Shared Sub Main()
		Dim pathToFile As String = "C:\assets\input.pdf" ' Absolute path with filename

		' Load the PDF document
		Using pdf = PdfDocument.Load(pathToFile)
			' Create a print document for the loaded PDF
			Dim printDocument = pdf.CreatePrintDocument()

			' Print the document
			printDocument.Print()
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel

Note: PDFiumViewer requires a System.Windows.Forms assembly to work; otherwise, it will throw an exception. This is because the PDFiumViewer library is designed to be used with Windows Forms applications. Ensure this task is performed in a valid Windows Forms application.

On executing the app, the Windows form is displayed with a "Print PDF" button. Upon clicking, the print dialog is displayed. Save the document as a PDF file.

PdfiumViewer Print PDF in C# (Alternative Tutorial) Figure 9 - Save as PDF

The output is the same as the input PDF file. If the printer settings had the physical printer name, then it would have been printed out on paper perfectly.

PdfiumViewer Print PDF in C# (Alternative Tutorial) Figure 10 - Output

Conclusion

IronPDF and PDFiumViewer both serve distinct purposes when it comes to working with PDFs. IronPDF offers a comprehensive set of features for creating, manipulating, and printing PDFs. Its ease of use and rich functionality make it a popular choice for .NET developers.

On the other hand, PDFiumViewer shines in rendering and displaying PDFs within Windows Forms applications. However, it lacks native PDF printing capabilities, and additional solutions for printing, as shown in the above example, may be required.

The choice between IronPDF and PDFiumViewer depends on your specific project requirements. If you need access to a versatile library with robust PDF manipulation features, IronPDF is an excellent choice. On the other hand, if your focus is on displaying PDFs in a Windows Forms application, PDFiumViewer can fulfill that role.

IronPDF is a powerful PDF library for C# developers. It is free for development purposes, and commercial licenses start at $799 for a single developer. There is also a free trial with full features and support, so you can try it out before buying. You can download the software from here.

Por favor notaPDFiumViewer is a registered trademark of its respective owner. This site is not affiliated with, endorsed by, or sponsored by PDFiumViewer. All product names, logos, and brands are property of their respective owners. Comparisons are for informational purposes only and reflect publicly available information at the time of writing.

Preguntas Frecuentes

¿Cómo puedo convertir HTML a PDF usando C#?

Puedes usar el método RenderHtmlAsPdf de IronPDF para convertir cadenas de HTML en PDFs. Además, el método RenderHtmlFileAsPdf permite convertir archivos HTML directamente en documentos PDF.

¿Cuál es la mejor manera de imprimir PDFs en una aplicación C#?

IronPDF proporciona funcionalidades integradas para la impresión silenciosa de PDFs desde aplicaciones C#, permitiéndote imprimir documentos directamente sin utilizar herramientas de terceros.

¿Cómo puedo mostrar PDFs dentro de una aplicación Windows Forms?

PDFiumViewer es una biblioteca adecuada para renderizar y mostrar PDFs dentro de aplicaciones Windows Forms. Soporta navegación, zoom y selección de texto, aunque carece de capacidades nativas de impresión.

¿Cuáles son los pasos de instalación para bibliotecas PDF usando NuGet en Visual Studio?

Para instalar IronPDF, abre Visual Studio, navega a 'Administrar paquetes NuGet' en tu proyecto, busca 'IronPDF' y haz clic en 'Instalar'. Para PDFiumViewer, sigue los mismos pasos y busca 'PDFiumViewer'.

¿Qué características ofrece IronPDF para la manipulación de PDFs en C#?

IronPDF ofrece características integrales para crear y editar PDFs, incluyendo conversión de HTML a PDF, agregar firmas digitales, marcas de agua, cifrado, y la capacidad de imprimir PDFs de manera silenciosa.

¿Es PDFiumViewer adecuado para imprimir PDFs directamente desde aplicaciones C#?

PDFiumViewer no soporta la impresión directa de PDFs. Se requieren bibliotecas o herramientas adicionales, como System.Drawing.Printing, para manejar tareas de impresión.

¿Por qué elegir IronPDF para manejar PDFs en C#?

IronPDF es ideal para desarrolladores que necesitan una solución robusta para la creación, manipulación e impresión de PDFs. Soporta características avanzadas y proporciona documentación completa e integración fácil de usar.

¿Puedo usar IronPDF de forma gratuita durante el desarrollo?

Sí, IronPDF está disponible para uso de desarrollo gratuito. Para aplicaciones comerciales, hay licencias disponibles a partir de un costo especificado.

¿Qué biblioteca es mejor para mi proyecto C#, IronPDF o PDFiumViewer?

La elección depende de tus necesidades. IronPDF es más adecuado para la creación e impresión completa de PDFs, mientras que PDFiumViewer está optimizado para mostrar PDFs en aplicaciones Windows Forms.

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