Saltar al pie de página
USANDO IRONPDF

Cómo Convertir Imagen a PDF en C# [Tutorial de Ejemplo de Código]

Numerous libraries allow C# developers to convert images to PDFs. Finding a free, user-friendly library with good performance can be challenging, as some are paid, complex, or limited in functionality. Among these libraries, IronPDF stands out as a free, efficient, and easy-to-implement C# library. It comes with comprehensive documentation and a professional, responsive support team.

IronPDF is a .NET library for generating, reading, editing, and saving PDF files in .NET projects. IronPDF features HTML-to-PDF for .NET 5, Core, Standard & Framework with full HTML-to-PDF support, including CSS3 and JS.

Let's take a look at how to create a sample project to learn about converting images to PDF.

Create a Visual Studio Project

To create a new project, open Microsoft Visual Studio. It is recommended to use the latest version of Visual Studio. The steps for creating a new project may differ between versions, but the remainder should be the same for every version.

  1. Click on Create New Project.
  2. Select Project Template, then select the Console Application template for this demonstration. You can use any as per your requirement.
  3. Click on Next. Name the Project.
  4. Click Next and select the .NET Framework version.
  5. Click the Create button.

The new project will be created as shown below.

How to Convert Image to PDF in C# [Code Example Tutorial], Figure 1: Create a new Console Application in Visual Studio Create a new Console Application in Visual Studio

Next, install the IronPDF NuGet Package in this project to use its features. The interesting thing about IronPDF is that it takes the frustration out of generating PDF documents by not relying on proprietary APIs. HTML to PDF rendering example renders pixel-perfect PDFs from open standard document types: HTML, JS, CSS, JPG, PNG, GIF, and SVG. In short, it uses the skills that developers already possess.

Install the IronPDF NuGet Package

To install the NuGet Package, go to Tools > NuGet Package Manager > Package Manager Console. The following window will appear:

How to Convert Image to PDF in C# [Code Example Tutorial], Figure 2: Package Manager Console UI Package Manager Console UI

Next, write the following command in the Package Manager Console:

Install-Package IronPdf

Press Enter.

How to Convert Image to PDF in C# [Code Example Tutorial], Figure 3: Install the IronPdf package in the Package Manager Console Install the IronPdf package in the Package Manager Console

Convert Image File to PDF Document

The next step will show how to convert the following image to PDF.

Example Image

How to Convert Image to PDF in C# [Code Example Tutorial], Figure 4: The sample image The sample image

To use the library, reference the IronPDF library in the program.cs file. Write the following code snippet at the top of the file.

using IronPdf;
using IronPdf;
Imports IronPdf
$vbLabelText   $csharpLabel

Next, write the following code inside the main function. This will convert a JPG file to a PDF file.

public static void Main(string[] args)
{
    // Convert a single image to the PDF document
    PdfDocument doc = ImageToPdfConverter.ImageToPdf(@"D:\Iron Software\ImageToPDF\bird.jpg", IronPdf.Imaging.ImageBehavior.CropPage);
    // Save the resulting PDF to the specified path
    doc.SaveAs(@"D:\Iron Software\ImageToPDF\bird.pdf");
}
public static void Main(string[] args)
{
    // Convert a single image to the PDF document
    PdfDocument doc = ImageToPdfConverter.ImageToPdf(@"D:\Iron Software\ImageToPDF\bird.jpg", IronPdf.Imaging.ImageBehavior.CropPage);
    // Save the resulting PDF to the specified path
    doc.SaveAs(@"D:\Iron Software\ImageToPDF\bird.pdf");
}
Public Shared Sub Main(ByVal args() As String)
	' Convert a single image to the PDF document
	Dim doc As PdfDocument = ImageToPdfConverter.ImageToPdf("D:\Iron Software\ImageToPDF\bird.jpg", IronPdf.Imaging.ImageBehavior.CropPage)
	' Save the resulting PDF to the specified path
	doc.SaveAs("D:\Iron Software\ImageToPDF\bird.pdf")
End Sub
$vbLabelText   $csharpLabel

In the above code example, the ImageToPdfConverter class provided by IronPDF is used for image conversion. The ImageToPdf method can be used to create PDF documents from images. It accepts both image files and a System.Drawing object as input.

The static method ImageToPdf converts a single image file to an identical PDF document of matching dimensions. It takes two arguments: Image Path and Image Behavior (how the image will display on paper). Imaging.ImageBehavior.CropPage will set the paper size equal to the image size. The default page size is A4. You can set it via the following line of code:

ImageToPdfConverter.PaperSize = IronPdf.Rendering.PdfPaperSize.Letter;
ImageToPdfConverter.PaperSize = IronPdf.Rendering.PdfPaperSize.Letter;
ImageToPdfConverter.PaperSize = IronPdf.Rendering.PdfPaperSize.Letter
$vbLabelText   $csharpLabel

There are multiple page-size options provided, and you can set them as per your requirements.

Convert Multiple Images to a PDF File

The following example will convert JPG images into a new document.

public static void Main(string[] args)
{
    // Enumerate and filter JPG files from the specified directory
    var imageFiles = System.IO.Directory.EnumerateFiles(@"D:\Iron Software\ImageToPDF\")
                                        .Where(f => f.EndsWith(".jpg") || f.EndsWith(".jpeg"));
    // Convert the images to a PDF document and save it
    PdfDocument doc = ImageToPdfConverter.ImageToPdf(imageFiles);
    doc.SaveAs(@"D:\Iron Software\ImageToPDF\JpgToPDF.pdf");
}
public static void Main(string[] args)
{
    // Enumerate and filter JPG files from the specified directory
    var imageFiles = System.IO.Directory.EnumerateFiles(@"D:\Iron Software\ImageToPDF\")
                                        .Where(f => f.EndsWith(".jpg") || f.EndsWith(".jpeg"));
    // Convert the images to a PDF document and save it
    PdfDocument doc = ImageToPdfConverter.ImageToPdf(imageFiles);
    doc.SaveAs(@"D:\Iron Software\ImageToPDF\JpgToPDF.pdf");
}
Public Shared Sub Main(ByVal args() As String)
	' Enumerate and filter JPG files from the specified directory
	Dim imageFiles = System.IO.Directory.EnumerateFiles("D:\Iron Software\ImageToPDF\").Where(Function(f) f.EndsWith(".jpg") OrElse f.EndsWith(".jpeg"))
	' Convert the images to a PDF document and save it
	Dim doc As PdfDocument = ImageToPdfConverter.ImageToPdf(imageFiles)
	doc.SaveAs("D:\Iron Software\ImageToPDF\JpgToPDF.pdf")
End Sub
$vbLabelText   $csharpLabel

In the above code, System.IO.Directory.EnumerateFiles retrieves all files available in the specified folder. The Where clause filters all the JPG images from that folder and stores them in the imageFiles collection. If you have PNG or any other image format, you can just add that to the Where query.

The next line will take all the images and combine them into a single PDF document.

Print PDF File

The following code snippet will print the document:

doc.Print();
doc.Print();
doc.Print()
$vbLabelText   $csharpLabel

The Print method provided by the PdfDocument class will print the document using the default printer. It also provides an option to change the printer name and other settings. For more details about printing documents, please visit this PDF printing example.

Summary

This tutorial showed a very easy way to convert images into a PDF file with code examples, either converting a single image into a PDF or combining multiple images into a single PDF file. Moreover, it also explained how to print documents with a single line of code.

Additionally, some of the important features of IronPDF include:

There are multiple useful and interesting features provided by IronPDF, please visit this IronPDF homepage for more details.

IronPDF is a part of the Iron Software suite. The Iron Suite includes additional interesting products such as IronXL, IronBarcode, IronOCR, and IronWebscraper, and all of these products are extremely useful. You can save up to 250% by purchasing the complete Iron Suite, as you can currently get all five products for the price of just two. Please visit the licensing details page for more details.

Preguntas Frecuentes

¿Cómo puedo convertir una imagen a un PDF en C#?

Puedes convertir una imagen a un PDF en C# usando el método ImageToPdf de IronPDF. Este método te permite especificar la ruta de la imagen y los ajustes deseados de salida en PDF.

¿Se pueden convertir múltiples imágenes en un solo archivo PDF?

Sí, IronPDF te permite convertir múltiples imágenes en un solo archivo PDF utilizando el método ImageToPdf, donde proporcionas una colección de archivos de imagen.

¿Qué formatos de imagen son compatibles con la conversión a PDF?

IronPDF soporta la conversión de varios formatos de imagen como JPG, PNG, GIF y SVG en documentos PDF.

¿Cómo establezco el tamaño de página al convertir una imagen a un PDF?

Para establecer el tamaño de página durante la conversión, usa la propiedad PaperSize dentro de la clase ImageToPdfConverter para seleccionar un tamaño estándar como Carta o A4.

¿Es posible imprimir un documento PDF creado con IronPDF?

Sí, IronPDF incluye un método Print dentro de la clase PdfDocument que te permite imprimir documentos PDF utilizando configuraciones de impresora predeterminadas o especificadas.

¿Qué características adicionales ofrece IronPDF?

IronPDF proporciona características adicionales como generar PDFs desde URLs, encriptar y desencriptar PDFs, fusionar archivos PDF y crear y editar formularios PDF.

¿Cómo instalo IronPDF en un proyecto de Visual Studio?

Para instalar IronPDF en un proyecto de Visual Studio, abre la Consola de Administrador de Paquetes y ejecuta el comando Install-Package IronPdf.

¿Cuáles son las ventajas de usar IronPDF para la generación de PDFs?

IronPDF ofrece una API simple, eficiente y bien documentada para la generación de PDFs sin depender de APIs propietarias. También proporciona soporte profesional y maneja varias tareas de PDF de manera efectiva.

¿IronPDF es compatible con .NET 10 y cómo lo uso para la conversión de imágenes a PDF en un proyecto .NET 10?

Sí. IronPDF es totalmente compatible con .NET 10 y permite convertir imágenes a PDF en proyectos .NET 10 de forma predeterminada. Para usarlo, instale el paquete NuGet IronPdf en su proyecto .NET 10 y, a continuación, invoque métodos como ImageToPdfConverter.ImageToPdf("path/to/image.png") para convertir una sola imagen, o pase un IEnumerable de rutas de imagen para convertir varias imágenes. También puede especificar opciones como ImageBehavior o de renderizado mediante ChromePdfRenderOptions para personalizarlo. Esto funciona igual que en versiones anteriores de .NET.

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