Cómo agregar y eliminar adjuntos en PDF C#

How to Add and Remove PDF Attachments

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

Attachments in a PDF document refer to files or additional data embedded within the PDF file itself. This is distinct from the regular content of the PDF, which includes visible text, images, and formatting when you view the PDF. These attachments can take the form of various file types, including images, documents, spreadsheets, or other formats. Typically, attachments are used to provide additional reference materials or supplementary data that users can access when they open the PDF.

Quickstart: Adding Attachments to PDF

Easily add attachments to your PDF documents using IronPDF's powerful library. This quick example demonstrates how to embed a file as an attachment into a PDF. Simply load your existing PDF, use the AddAttachment method, and save the updated document. This process ensures your supplementary materials are seamlessly included with your PDF, making them accessible directly from any PDF viewer.

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.

    var pdf = IronPdf.PdfDocument.FromFile("example.pdf");
    pdf.Attachments.AddAttachment("file.txt", System.IO.File.ReadAllBytes("file.txt"));
    pdf.SaveAs("updated.pdf");
  3. Deploy to test on your live environment

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


Add Attachment Example

To add a file as an attachment, first load it in your program as a byte[]. The easiest way to do this is to use the File.ReadAllBytes method. With the file loaded in as a byte[], you can then use the AddAttachment method to add the object into a PDF as an attachment like so:

:path=/static-assets/pdf/content-code-examples/how-to/add-remove-attachments-add-attachment.cs
using IronPdf;
using System.IO;

// Import attachment file
byte[] fileData = File.ReadAllBytes(@"path/to/file");

// Open existing PDF
PdfDocument pdf = PdfDocument.FromFile("sample.pdf");

// Add attachment to the PDF
pdf.Attachments.AddAttachment("Example", fileData);

pdf.SaveAs("addAttachment.pdf");
Imports IronPdf
Imports System.IO

' Import attachment file
Private fileData() As Byte = File.ReadAllBytes("path/to/file")

' Open existing PDF
Private pdf As PdfDocument = PdfDocument.FromFile("sample.pdf")

' Add attachment to the PDF
pdf.Attachments.AddAttachment("Example", fileData)

pdf.SaveAs("addAttachment.pdf")
$vbLabelText   $csharpLabel

The AddAttachment function outputs a PdfAttachment object that we can keep for future reference or remove it later if needed.

After saving the PDF, you can open the attachment from the toolbar of a PDF viewer. We demonstrate where to find this feature in Google Chrome's PDF Viewer in the image below:

Attachment Preview

From there, you can click on it and save the attachment to your own storage.

Retrieve Attachment Example

The attachments in a PDF could be retrieved as binary data by accessing the Attachments property of the PdfDocument object. With the binary data, you can export the attachments from the PDF as their respective file formats.

:path=/static-assets/pdf/content-code-examples/how-to/add-remove-attachments-retrieve-attachment.cs
using IronPdf;
using System.IO;

// Open existing PDF
PdfDocument pdf = PdfDocument.FromFile("addAttachment.pdf");

// Iterate through all attachments
foreach (var attachment in pdf.Attachments)
{
    if (attachment.Name.Contains("Example"))
    {
        // Save byte to file
        File.WriteAllBytes($"{attachment.Name}.doc", attachment.Data);
    }
}
Imports IronPdf
Imports System.IO

' Open existing PDF
Private pdf As PdfDocument = PdfDocument.FromFile("addAttachment.pdf")

' Iterate through all attachments
For Each attachment In pdf.Attachments
	If attachment.Name.Contains("Example") Then
		' Save byte to file
		File.WriteAllBytes($"{attachment.Name}.doc", attachment.Data)
	End If
Next attachment
$vbLabelText   $csharpLabel

Remove Attachment Example

To remove an attachment, simply use the RemoveAttachment function. This method requires a reference to the attachment, which can be retrieved from the Attachments property. We demonstrate how to do this using the saved file from above.

:path=/static-assets/pdf/content-code-examples/how-to/add-remove-attachments-remove-attachment.cs
using IronPdf;
using System.Linq;

// Open existing PDF
PdfDocument pdf = PdfDocument.FromFile("addAttachment.pdf");

// Add attachment to the PDF
PdfAttachmentCollection retrieveAttachments = pdf.Attachments;

// Remove attachment from PDF
pdf.Attachments.RemoveAttachment(retrieveAttachments.First());

pdf.SaveAs("removeAttachment.pdf");
Imports IronPdf
Imports System.Linq

' Open existing PDF
Private pdf As PdfDocument = PdfDocument.FromFile("addAttachment.pdf")

' Add attachment to the PDF
Private retrieveAttachments As PdfAttachmentCollection = pdf.Attachments

' Remove attachment from PDF
pdf.Attachments.RemoveAttachment(retrieveAttachments.First())

pdf.SaveAs("removeAttachment.pdf")
$vbLabelText   $csharpLabel

After removing the attachment and opening the resulting file in a PDF viewer, you will see that the attachment no longer appears:

Attachment Preview

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

Preguntas Frecuentes

¿Cómo puedo agregar adjuntos a un documento PDF usando C#?

Puedes agregar adjuntos a un documento PDF usando IronPDF cargando el archivo como un arreglo de bytes con el método File.ReadAllBytes y luego utilizando el método AddAttachment para incrustarlo en el PDF.

¿Cuál es el proceso para eliminar adjuntos de un PDF?

Para eliminar adjuntos de un PDF usando IronPDF, emplea el método RemoveAttachment. Primero debes obtener una referencia al adjunto desde la propiedad Attachments del objeto PdfDocument.

¿Qué formatos de archivo se pueden agregar como adjuntos en un PDF?

Se puede adjuntar una amplia gama de formatos de archivo a un PDF, incluyendo imágenes, documentos, hojas de cálculo y otros tipos de archivo.

¿Cómo recupero y exporto adjuntos de un PDF?

Para recuperar adjuntos de un PDF usando IronPDF, accede a la propiedad Attachments del objeto PdfDocument para obtenerlos como datos binarios, que luego pueden ser exportados al disco.

¿Qué pasos son necesarios para comenzar a gestionar adjuntos de PDF en C#?

Para empezar a gestionar adjuntos de PDF, descarga la biblioteca IronPDF C# desde NuGet, carga o crea un documento PDF y usa los métodos relevantes para agregar o eliminar adjuntos.

¿Pueden los usuarios acceder y guardar los adjuntos en un PDF?

Sí, una vez que los adjuntos se añaden a un PDF usando IronPDF, se pueden acceder a través de la barra de herramientas del visor de PDF, permitiendo a los usuarios guardarlos en su almacenamiento.

¿Cómo aseguro que los cambios en los adjuntos PDF se guarden?

Después de modificar adjuntos en un PDF usando IronPDF, utiliza el método SaveAs para guardar el documento PDF actualizado en la ubicación deseada.

¿Cuál es la diferencia entre el contenido visible del PDF y los adjuntos?

El contenido visible del PDF incluye texto, imágenes y formato, mientras que los adjuntos son archivos o datos adicionales incrustados dentro del PDF que proporcionan información suplementaria.

Jordi Bardia
Ingeniero de Software
Jordi es más competente en Python, C# y C++. Cuando no está aprovechando sus habilidades en Iron Software, está programando juegos. Compartiendo responsabilidades para pruebas de productos, desarrollo de productos e investigación, Jordi agrega un valor inmenso a la mejora continua del producto. La experiencia variada lo mantiene ...
Leer más
¿Listo para empezar?
Nuget Descargas 16,154,058 | Versión: 2025.11 recién lanzado