Cómo convertir imágenes a un PDF en C#

How to Convert Images to a PDF

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

Converting images to PDF is a useful process that combines multiple image files (such as JPG, PNG, or TIFF) into a single PDF document. This is often done to create digital portfolios, presentations, or reports, making it easier to share and store a collection of images in a more organized and universally readable format.

IronPDF allows you to convert a single or multiple images into a PDF with unique image placements and behaviors. These behaviors include fitting to the page, centering on the page, and cropping the page. Additionally, you can add text and HTML headers and footers using IronPDF, apply watermarks with IronPDF, set custom page sizes, and include background and foreground overlays.

Quickstart: Convert Images to PDF with IronPDF

Effortlessly convert images into a PDF document using IronPDF's ImageToPdfConverter class. This example demonstrates how to quickly transform an image file into a PDF, allowing developers to easily integrate image-to-PDF functionality into their .NET C# applications. With minimal code, you can convert images to PDF, ensuring a smooth and efficient workflow for creating digital portfolios or reports.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf

  2. Copy and run this code snippet.

    IronPdf.ImageToPdfConverter.ImageToPdf("path/to/image.png").SaveAs("imageToPdf.pdf");
  3. Deploy to test on your live environment

    Start using IronPDF in your project today with a free trial
    arrow pointer


Convert Image to PDF Example

Use the ImageToPdf static method within the ImageToPdfConverter class to convert an image to a PDF document. This method requires only the file path to the image, and it will convert it to a PDF document with default image placement and behavior. Supported image formats include .bmp, .jpeg, .jpg, .gif, .png, .svg, .tif, .tiff, .webp, .apng, .avif, .cur, .dib, .ico, .jfif, .jif, .jpe, .pjp, and .pjpeg.

Sample Image

Image Sample

Code

:path=/static-assets/pdf/content-code-examples/how-to/image-to-pdf-convert-one-image.cs
using IronPdf;

string imagePath = "meetOurTeam.jpg";

// Convert an image to a PDF
PdfDocument pdf = ImageToPdfConverter.ImageToPdf(imagePath);

// Export the PDF
pdf.SaveAs("imageToPdf.pdf");
Imports IronPdf

Private imagePath As String = "meetOurTeam.jpg"

' Convert an image to a PDF
Private pdf As PdfDocument = ImageToPdfConverter.ImageToPdf(imagePath)

' Export the PDF
pdf.SaveAs("imageToPdf.pdf")
$vbLabelText   $csharpLabel

Output PDF


Convert Images to PDF Example

To convert multiple images into a PDF document, you should provide an IEnumerable object that contains file paths instead of a single file path, as shown in our previous example. This will once again generate a PDF document with default image placement and behavior.

:path=/static-assets/pdf/content-code-examples/how-to/image-to-pdf-convert-multiple-images.cs
using IronPdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

// Retrieve all JPG and JPEG image paths in the 'images' folder.
IEnumerable<String> imagePaths = Directory.EnumerateFiles("images").Where(f => f.EndsWith(".jpg") || f.EndsWith(".jpeg"));

// Convert images to a PDF
PdfDocument pdf = ImageToPdfConverter.ImageToPdf(imagePaths);

// Export the PDF
pdf.SaveAs("imagesToPdf.pdf");
Imports IronPdf
Imports System
Imports System.Collections.Generic
Imports System.IO
Imports System.Linq

' Retrieve all JPG and JPEG image paths in the 'images' folder.
Private imagePaths As IEnumerable(Of String) = Directory.EnumerateFiles("images").Where(Function(f) f.EndsWith(".jpg") OrElse f.EndsWith(".jpeg"))

' Convert images to a PDF
Private pdf As PdfDocument = ImageToPdfConverter.ImageToPdf(imagePaths)

' Export the PDF
pdf.SaveAs("imagesToPdf.pdf")
$vbLabelText   $csharpLabel

Output PDF


Image Placements and Behaviors

For ease of use, we offer a range of helpful image placement and behavior options. For instance, you can center the image on the page or fit it to the page size while maintaining its aspect ratio. All available image placements and behaviors are as follows:

  • TopLeftCornerOfPage: Image is placed at the top-left corner of the page.
  • TopRightCornerOfPage: Image is placed at the top-right corner of the page.
  • CenteredOnPage: Image is centered on the page.
  • FitToPageAndMaintainAspectRatio: Image fits the page while keeping its original aspect ratio.
  • BottomLeftCornerOfPage: Image is placed at the bottom-left corner of the page.
  • BottomRightCornerOfPage: Image is placed at the bottom-right corner of the page.
  • FitToPage: Image fits the page.
  • CropPage: Page is adjusted to fit the image.
:path=/static-assets/pdf/content-code-examples/how-to/image-to-pdf-convert-one-image-image-behavior.cs
using IronPdf;
using IronPdf.Imaging;

string imagePath = "meetOurTeam.jpg";

// Convert an image to a PDF with image behavior of centered on page
PdfDocument pdf = ImageToPdfConverter.ImageToPdf(imagePath, ImageBehavior.CenteredOnPage);

// Export the PDF
pdf.SaveAs("imageToPdf.pdf");
Imports IronPdf
Imports IronPdf.Imaging

Private imagePath As String = "meetOurTeam.jpg"

' Convert an image to a PDF with image behavior of centered on page
Private pdf As PdfDocument = ImageToPdfConverter.ImageToPdf(imagePath, ImageBehavior.CenteredOnPage)

' Export the PDF
pdf.SaveAs("imageToPdf.pdf")
$vbLabelText   $csharpLabel

Image Behaviors Comparison

Place the image at the top-left of the page
Place the image at the top-right of the page
Place the image at the center of the page
Fit the image to the page while maintaining the aspect ratio
Place the image at the bottom-left of the page
Place the image at the bottom-right of the page
Stretch the image to fit the page
Crop the page to fit the image

Apply Rendering Options

The key to converting various types of images into a PDF document under the hood of the ImageToPdf static method is to import the image as an HTML <img> tag and then convert the HTML to PDF. This is also the reason we can pass the ChromePdfRenderOptions object as a third parameter of the ImageToPdf method to customize the rendering process directly.

:path=/static-assets/pdf/content-code-examples/how-to/image-to-pdf-convert-one-image-rendering-options.cs
using IronPdf;

string imagePath = "meetOurTeam.jpg";

ChromePdfRenderOptions options = new ChromePdfRenderOptions()
{
    HtmlHeader = new HtmlHeaderFooter()
    {
        HtmlFragment = "<h1 style='color: #2a95d5;'>Content Header</h1>",
        DrawDividerLine = true,
    },
};

// Convert an image to a PDF with custom header
PdfDocument pdf = ImageToPdfConverter.ImageToPdf(imagePath, options: options);

// Export the PDF
pdf.SaveAs("imageToPdfWithHeader.pdf");
Imports IronPdf

Private imagePath As String = "meetOurTeam.jpg"

Private options As New ChromePdfRenderOptions() With {
	.HtmlHeader = New HtmlHeaderFooter() With {
		.HtmlFragment = "<h1 style='color: #2a95d5;'>Content Header</h1>",
		.DrawDividerLine = True
	}
}

' Convert an image to a PDF with custom header
Private pdf As PdfDocument = ImageToPdfConverter.ImageToPdf(imagePath, options:= options)

' Export the PDF
pdf.SaveAs("imageToPdfWithHeader.pdf")
$vbLabelText   $csharpLabel

Output PDF

If you'd like to convert or rasterize a PDF document into images, please refer to our guide on how to rasterize PDFs to images.

Ready to see what else you can do? Check out our tutorial page here: Convert PDFs

Preguntas Frecuentes

¿Cómo convertir imágenes a PDF en .NET C#?

Puedes convertir imágenes a PDF en .NET C# utilizando la clase ImageToPdfConverter de la biblioteca de IronPDF. Esta clase ofrece un método sencillo para convertir archivos de imagen a un documento PDF especificando la ruta de la imagen.

¿Qué formatos de imagen se pueden convertir a PDF utilizando .NET C#?

Con IronPDF, puedes convertir una variedad de formatos de imagen a PDF, incluyendo BMP, JPEG, GIF, PNG, SVG, TIFF, WEBP, y más. Esta flexibilidad garantiza la compatibilidad con la mayoría de los archivos de imagen.

¿Cómo puedo convertir múltiples imágenes en un solo documento PDF en C#?

Para convertir múltiples imágenes en un solo documento PDF usando IronPDF, puedes proporcionar un objeto IEnumerable que contenga las rutas de los archivos de las imágenes. Esto te permitirá compilar todas las imágenes en un único archivo PDF cohesionado.

¿Qué opciones están disponibles para colocar imágenes en un PDF?

IronPDF ofrece varias opciones de colocación para imágenes en un PDF, como TopLeftCornerOfPage, CenteredOnPage, FitToPageAndMaintainAspectRatio, y otras. Estas opciones te permiten personalizar cómo aparece la imagen en la página del PDF.

¿Puedo añadir encabezados y pies de página a un PDF al convertir imágenes?

Sí, puedes añadir texto y encabezados y pies de página HTML personalizados a un PDF al convertir imágenes usando IronPDF. Esta función es útil para añadir información adicional o branding a tus documentos PDF.

¿Es posible incluir marcas de agua en un PDF durante la conversión de imágenes?

Sí, IronPDF te permite aplicar marcas de agua a PDFs durante el proceso de conversión. Esto se puede hacer siguiendo las guías en los tutoriales de IronPDF para añadir marcas de agua.

¿Cómo puedo personalizar el proceso de conversión de imagen a PDF?

Puedes personalizar el proceso de conversión de imagen a PDF en IronPDF utilizando el objeto ChromePdfRenderOptions. Esto te permitirá ajustar las configuraciones de renderizado para adecuarlas a tus necesidades específicas.

¿Cuál es el método que IronPDF usa para convertir imágenes a PDFs?

IronPDF convierte imágenes a PDFs importando la imagen como una etiqueta HTML <img> y luego renderizándola en formato PDF. Este enfoque proporciona flexibilidad en la personalización del archivo resultante.

¿Dónde puedo encontrar más recursos sobre convertir imágenes a PDF usando IronPDF?

Recursos adicionales y tutoriales sobre la conversión de imágenes a PDF usando IronPDF pueden encontrarse en el sitio web oficial de IronPDF y dentro de su documentacion integral.

¿Cómo beneficia a los proyectos digitales la conversión de imágenes a PDF?

La conversión de imágenes a PDF beneficia a los proyectos digitales al organizar múltiples imágenes en un solo documento compartible. Esto es ideal para crear portafolios digitales, presentaciones o informes que necesiten ser distribuidos en un formato universalmente legible.

¿IronPDF es totalmente compatible con .NET 10 al convertir imágenes a PDF?

Sí, IronPDF es totalmente compatible con .NET 10. La biblioteca es oficialmente compatible con .NET 10 (junto con las versiones .NET 9, 8, 7, 6 y Core), lo que permite la conversión de imágenes a PDF, la representación HTML y todas las funciones clave sin necesidad de configuración ni alternativas. ([ironpdf.com](https://ironpdf.com/?utm_source=openai))

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
Revisado por
Jeff Fritz
Jeffrey T. Fritz
Gerente Principal de Programas - Equipo de la Comunidad .NET
Jeff también es Gerente Principal de Programas para los equipos de .NET y Visual Studio. Es el productor ejecutivo de la serie de conferencias virtuales .NET Conf y anfitrión de 'Fritz and Friends', una transmisión en vivo para desarrolladores que se emite dos veces a la semana donde habla sobre tecnología y escribe código junto con la audiencia. Jeff escribe talleres, presentaciones, y planifica contenido para los eventos de desarrolladores más importantes de Microsoft, incluyendo Microsoft Build, Microsoft Ignite, .NET Conf y la Cumbre de Microsoft MVP.
¿Listo para empezar?
Nuget Descargas 16,154,058 | Versión: 2025.11 recién lanzado