Saltar al pie de página
USANDO IRONPDF

Conversión de PDF en C# (Tutorial para Desarrolladores)

This article will discuss how the PDF Converter works using IronPDF, the PDF library for .NET and .NET Core.

IronPDF

IronPDF is a versatile and feature-rich software library designed to simplify the creation, manipulation, and management of PDF documents within the .NET ecosystem. Developed by Iron Software, this powerful toolset empowers developers with the ability to seamlessly integrate PDF functionality into their C#, VB.NET, and F# applications.

Whether you need to generate PDFs from scratch, convert your HTML pages, images, or existing documents into PDF format, or manipulate and edit existing PDFs, IronPDF offers a comprehensive suite of APIs and functionalities to streamline these tasks. This introduction provides a glimpse into the world of IronPDF, highlighting its capabilities and potential to enhance document processing and management in .NET applications. If you're interested in an itemization of these features, they're available on the IronPDF Features Overview website.

  1. PDF Generation: Easily create PDF documents programmatically in C# from various sources, including HTML, images, text, and existing files.
  2. HTML to PDF Conversion: Convert HTML content into PDFs, including web pages or HTML templates, into high-quality PDFs with full control over styling and formatting.
  3. Image to PDF Conversion: Convert image files (such as JPEG, PNG, or BMP) into PDF documents, allowing for easy integration of images into PDF reports and documents.
  4. PDF Manipulation: Comprehensive PDF editing capabilities, including text extraction from PDFs, merging and splitting PDFs, and rotation, as well as adding, modifying, or removing content and annotations.
  5. PDF Forms: Create, fill, and extract data from PDF forms, making it suitable for applications that require interactive forms and data collection.

Creating a New Visual Studio Project

Before writing the code, let's create a new Visual Studio C# Console Application project to run the project and examples.

  1. Open Visual Studio and create a new project by going to File > New > Project.

    PDF Conversion in C# (Developer Tutorial), Figure 1: The Project dropdown in Visual Studio The Project dropdown in Visual Studio

  2. A new window will appear; in the new window, select the project format. In this case, the Console Application will be selected and then click on the Next button located on the bottom left of the screen.

    PDF Conversion in C# (Developer Tutorial), Figure 2: The Create a new project dialogue with Console Application selected The "Create a new project" dialogue with "Console Application" selected

  3. In the newly opened window, write the Project name and select the project Location, then click on the Next button.

    PDF Conversion in C# (Developer Tutorial), Figure 3: The Configure your new project dialogue, with PDF Conversion as the name The "Configure your new project" dialogue, with PDF Conversion as the name

  4. Select the target framework and click on the Create button.

    PDF Conversion in C# (Developer Tutorial), Figure 4: An Additional Information dialogue, with .NET 5.0 selected An "Additional Information" dialogue, with .NET 5.0 selected

Now the project is created, let's install IronPDF.

Installing IronPDF

IronPDF offers many ways to download and install the PDF library. In this section, the first approach is to install IronPDF using NuGet Package Manager.

  1. In Visual Studio, go to the Tools menu and hover your pointer over NuGet Package Manager.
  2. In the new side menu, click on the Manage NuGet Packages for Solutions.

    PDF Conversion in C# (Developer Tutorial), Figure 5: The NuGet Package Manager dropdown from the Tools bar in Visual Studio The NuGet Package Manager dropdown from the Tools bar in Visual Studio

  3. A new window will appear. In this new window, go to the Browse menu and type "IronPDF" in the search bar.
  4. A list of IronPDF packages will appear; click on the latest package and click on "Install".
  5. You can also install IronPDF using the NuGet Package Manager Console; just open the NuGet console, type the following command, and press enter.

    Install-Package IronPdf

Or you can directly download the package from the IronPDF NuGet page.

PDF Conversion Using IronPDF

In this section, we will discuss how you can convert different documents and image formats into PDF files.

  1. HTML Files to PDF Documents
  2. Image to PDF Documents

HTML File to PDF Document

IronPDF offers this feature where you can convert HTML pages or HTML files to PDF content with just a few lines of code.

In the code snippet below, we will see the conversion of an HTML file into a PDF document.

using IronPdf;

// Create an instance of the ChromePdfRenderer class.
var renderer = new ChromePdfRenderer();

// Render the HTML file as a PDF document.
var pdf = renderer.RenderHtmlFileAsPdf("invoice.html");

// Save the PDF document as an output file.
pdf.SaveAs("output.pdf");
using IronPdf;

// Create an instance of the ChromePdfRenderer class.
var renderer = new ChromePdfRenderer();

// Render the HTML file as a PDF document.
var pdf = renderer.RenderHtmlFileAsPdf("invoice.html");

// Save the PDF document as an output file.
pdf.SaveAs("output.pdf");
Imports IronPdf

' Create an instance of the ChromePdfRenderer class.
Private renderer = New ChromePdfRenderer()

' Render the HTML file as a PDF document.
Private pdf = renderer.RenderHtmlFileAsPdf("invoice.html")

' Save the PDF document as an output file.
pdf.SaveAs("output.pdf")
$vbLabelText   $csharpLabel

This concise code snippet leverages the IronPDF library in C# to effortlessly transform an HTML file ("invoice.html") into a PDF document. By initializing a ChromePdfRenderer, it utilizes the Chromium-based rendering engine to ensure accurate conversion of HTML content to PDF, preserving the original appearance of the web page. The resulting PDF is then saved as "output.pdf" with a straightforward call to the SaveAs method. This streamlined process simplifies HTML-to-PDF conversion, making it an invaluable tool for generating PDFs from HTML content in C#.

Output

PDF Conversion in C# (Developer Tutorial), Figure 6: An invoice PDF with Invoice as the title, and various invoice related fields displayed An invoice PDF with "Invoice" as the title, and various invoice-related fields displayed

Image to PDF files

Now, let's discuss how you can convert an image to a PDF document using IronPDF. You will need a demo image for this, and with just a few lines of code, you can easily convert an image to a PDF.

Input Image

PDF Conversion in C# (Developer Tutorial), Figure 7: A screenshot of the IronPDF website, with a variety of text A screenshot of the IronPDF website, with a variety of text

using IronPdf;
using System.IO;
using System.Linq;

// Enumerate all PNG files from the specified directory.
var imageFiles = Directory.EnumerateFiles("assets").Where(f => f.EndsWith(".png"));

// Convert the images to a PDF document.
ImageToPdfConverter.ImageToPdf(imageFiles).SaveAs("composite.pdf");
using IronPdf;
using System.IO;
using System.Linq;

// Enumerate all PNG files from the specified directory.
var imageFiles = Directory.EnumerateFiles("assets").Where(f => f.EndsWith(".png"));

// Convert the images to a PDF document.
ImageToPdfConverter.ImageToPdf(imageFiles).SaveAs("composite.pdf");
Imports IronPdf
Imports System.IO
Imports System.Linq

' Enumerate all PNG files from the specified directory.
Private imageFiles = Directory.EnumerateFiles("assets").Where(Function(f) f.EndsWith(".png"))

' Convert the images to a PDF document.
ImageToPdfConverter.ImageToPdf(imageFiles).SaveAs("composite.pdf")
$vbLabelText   $csharpLabel

The above code snippet uses IronPDF and system input and output files. Then, the code opens any files in the assets folder of this project that end with the .png file format and converts these image files into a PDF using the ImageToPdfConverter.ImageToPdf method. Finally, it saves the PDF using the SaveAs method.

Output

PDF Conversion in C# (Developer Tutorial), Figure 8: The previous image as a PDF, opened in Google Chrome The previous image as a PDF, opened in Google Chrome

Conclusion

In conclusion, this article sheds light on the significance of PDF conversion in C# for document management and sharing. With C#, it simplifies the entire process, enabling developers to seamlessly integrate PDF functionality into their applications. From generating PDFs to converting HTML, images, and existing documents, IronPDF offers a wide array of capabilities. The code examples provided showcase how to effortlessly convert both HTML documents and images to PDFs, highlighting the library's ease of use and effectiveness. As demonstrated, IronPDF greatly simplifies complex tasks, making it a valuable asset for developers seeking to enhance document processing and management in their .NET applications.

To download the PDF conversion library, visit the NuGet package for IronPDF. Also, make sure to check out the HTML-to-PDF conversion tutorial with IronPDF. IronPDF developers can choose from a variety of licenses to suit their requirements. There is also a free trial available. For complete pricing and licensing information about IronPDF, kindly refer to the IronPDF Licensing Information page.

Preguntas Frecuentes

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

Puedes usar el método RenderHtmlAsPdf de IronPDF para convertir cadenas de HTML en PDFs. También puedes convertir archivos HTML a PDFs usando RenderHtmlFileAsPdf.

¿Qué pasos están involucrados en la configuración de IronPDF en un proyecto de Visual Studio?

Para configurar IronPDF en un proyecto de Visual Studio, use el Administrador de Paquetes NuGet para buscar 'IronPDF' e instalar el paquete más reciente. Este proceso integra IronPDF en su proyecto, permitiéndole acceder a sus funcionalidades PDF.

¿Cuáles son las capacidades de IronPDF para la manipulación de PDF?

IronPDF ofrece capacidades completas de manipulación de PDF, incluyendo extracción de texto, fusión y división de PDFs, rotación de páginas y modificación de contenido y anotaciones.

¿Puedo convertir imágenes a PDF usando IronPDF?

Sí, puedes convertir imágenes a PDF usando el método ImageToPdfConverter de IronPDF, que soporta formatos de imagen como JPEG, PNG y BMP.

¿Cómo mantiene IronPDF el formato durante la conversión de PDF?

IronPDF garantiza que el formato original del documento se preserve durante la conversión al renderizar con precisión el contenido HTML e imágenes en formato PDF, gracias a su robusto motor de renderizado.

¿Hay una versión de prueba disponible para IronPDF?

Sí, una prueba gratuita de IronPDF está disponible. Para obtener información detallada sobre precios y licencias, puede consultar la página de Información de Licencias de IronPDF.

¿Qué lenguajes de programación son compatibles con IronPDF?

IronPDF admite la integración con aplicaciones C#, VB.NET y F#, proporcionando una amplia gama de posibilidades para desarrolladores que trabajan dentro del ecosistema .NET.

¿Dónde puedo encontrar más tutoriales o soporte para usar IronPDF?

Tutoriales adicionales y soporte para usar IronPDF están disponibles en el sitio web de IronPDF y en las páginas de documentación, incluidos guías sobre la conversión de HTML a PDF y otras funcionalidades.

¿IronPDF es totalmente compatible con .NET 10?

Sí, IronPDF es totalmente compatible con .NET 10 y funciona a la perfección sin necesidad de ninguna configuración especial. Admite las últimas funciones de entorno de ejecución y lenguaje de .NET 10, incluyendo la implementación multiplataforma y API modernas compatibles con la función asíncrona.

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