Cómo agregar imágenes a PDFs en C#

How to Add Images to PDFs

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

Embedding an image in a PDF means placing the image directly within the PDF file, ensuring it's self-contained and doesn't rely on external sources. This allows the PDF to display the image seamlessly, even without an internet connection or external files.

IronPDF is capable of rendering HTML strings, files, and web URLs to PDF. By using this method, images can be embedded in HTML and then converted into a PDF document.

Quickstart: Embed Images into PDFs with Ease

Get started with embedding images in your PDF files using IronPDF in .NET C#. By converting your image to a Base64 string and embedding it in an HTML <img> tag, you can generate a self-contained PDF that requires no external files. This method ensures your images display seamlessly without the need for internet access, making the process quick and straightforward.

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.

    new IronPdf.ChromePdfRenderer()
         .RenderHtmlAsPdf("<img src='data:image/png;base64," + Convert.ToBase64String(File.ReadAllBytes("logo.png")) + "'>")
         .SaveAs("image‑embedded.pdf");
  3. Deploy to test on your live environment

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


Embed Image in PDF Example

To embed an image in a PDF, you must first include the image in HTML using the <img> tag. Then, use the RenderHtmlAsPdf method to convert the HTML to PDF. If you have an existing PDF, you can stamp the image onto the PDF document using either an image stamper or HTML stamper tutorial.

:path=/static-assets/pdf/content-code-examples/how-to/add-images-to-pdfs-embed-image.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

string html = @"<img src='https://ironsoftware.com/img/products/ironpdf-logo-text-dotnet.svg'>";

// Render HTML to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf(html);

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

Private renderer As New ChromePdfRenderer()

Private html As String = "<img src='https://ironsoftware.com/img/products/ironpdf-logo-text-dotnet.svg'>"

' Render HTML to PDF
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)

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

Embed with Base64 Example

To use base64 for embedding an image in HTML, you must first obtain the binary data of the image either by reading the image file or receiving it through a network request. Use the Convert.ToBase64String method in Microsoft .NET to convert the binary data to base64. Construct the image tag in HTML using "data:image/svg+xml;base64," before the base64 data. You may have noticed that the image type is being specified before the base64 data. Visit the MDN Web Docs on Image Formats for more information on image format types.

:path=/static-assets/pdf/content-code-examples/how-to/add-images-to-pdfs-base64-image.cs
using IronPdf;
using System;
using System.IO;

ChromePdfRenderer renderer = new ChromePdfRenderer();

// Import image file binary data
byte[] binaryData = File.ReadAllBytes("ironpdf-logo-text-dotnet.svg");

// Convert the binary data to base 64
string imgDataUri = Convert.ToBase64String(binaryData);

// Embed in HTML
string html = $"<img src='data:image/svg+xml;base64,{imgDataUri}'>";

// Convert HTML to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf(html);

// Export the PDF
pdf.SaveAs("embedImageBase64.pdf");
Imports IronPdf
Imports System
Imports System.IO

Private renderer As New ChromePdfRenderer()

' Import image file binary data
Private binaryData() As Byte = File.ReadAllBytes("ironpdf-logo-text-dotnet.svg")

' Convert the binary data to base 64
Private imgDataUri As String = Convert.ToBase64String(binaryData)

' Embed in HTML
Private html As String = $"<img src='data:image/svg+xml;base64,{imgDataUri}'>"

' Convert HTML to PDF
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)

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

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

Preguntas Frecuentes

¿Cómo puedo agregar imágenes a PDFs usando C#?

Puedes agregar imágenes a PDFs en C# usando IronPDF. Primero, descarga la biblioteca de IronPDF C#. Luego, prepara el archivo de imagen e incrústalo en HTML usando la etiqueta <img>. Finalmente, usa el método RenderHtmlAsPdf para convertir el HTML a un PDF.

¿Cuál es la ventaja de usar la codificación Base64 para imágenes en PDFs?

La codificación Base64 te permite incrustar datos de imagen directamente en HTML. Esto significa que las imágenes pueden mostrarse en PDFs sin requerir archivos de imagen separados o solicitudes de red, asegurando que el PDF sea autónomo.

¿Puedo agregar imágenes a un documento PDF existente?

Sí, puedes agregar imágenes a un PDF existente estampándolas en el documento. IronPDF ofrece tutoriales para usar tanto un estampador de imagen como un estampador HTML para lograr esto.

¿Cuál es el proceso para convertir datos binarios de imagen a Base64?

Para convertir datos binarios de imagen a Base64, usa el método Convert.ToBase64String de Microsoft .NET. Una vez convertido, puedes incrustar la cadena Base64 en una etiqueta <img> en HTML y renderizarla a PDF usando IronPDF.

¿Las imágenes incrustadas en PDFs requieren conexión a Internet para mostrarse?

No, una vez que las imágenes están incrustadas en PDFs, no requieren conexión a Internet para mostrarse. Esto se debe a que las imágenes están contenidas dentro del propio archivo PDF.

¿Cómo puedo incrustar una imagen en un PDF usando HTML e IronPDF?

Para incrustar una imagen en un PDF usando HTML, incluye la imagen en un archivo HTML usando la etiqueta <img>. Luego, emplea el método RenderHtmlAsPdf de IronPDF para convertir ese HTML en un documento PDF.

¿Dónde puedo aprender más sobre formatos de imagen para usar en incrustación Base64?

Para más información sobre tipos de formato de imagen para incrustación Base64, puedes consultar los MDN Web Docs sobre formatos de imagen. Este recurso proporciona información detallada sobre diferentes tipos de imagen y su uso.

¿IronPDF es totalmente compatible con .NET 10 al trabajar con imágenes y renderizado HTML?

Sí. IronPDF es totalmente compatible con .NET 10, incluyendo sus funciones de incrustación de imágenes y renderizado de HTML a PDF. Admite recursos externos como imágenes, CSS y JavaScript, y funciona de inmediato en proyectos .NET 10.

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