DEV Community

IronSoftware
IronSoftware

Posted on

How to Add Attachments to PDF in C# (.NET Guide)

Last year, our accounting team requested a feature where invoices could carry supporting documents—receipts, contracts, delivery confirmations—embedded directly in the PDF. Email attachments were getting lost, and manually zipping files was error-prone.

That's when I learned PDFs support embedded attachments, accessible through the toolbar in any PDF reader. Here's how I implemented it in C#.

What Are PDF Attachments?

PDF attachments are files embedded inside a PDF document. They don't appear as part of the visible content but are stored in the PDF file structure and accessible through the "Attachments" panel in PDF viewers like Adobe Acrobat or Chrome's built-in reader.

using [IronPdf](https://ironpdf.com/);
// Install via NuGet: Install-Package IronPdf

var pdf = PdfDocument.FromFile("invoice.pdf");
var receipt = File.ReadAllBytes("receipt.jpg");
pdf.Attachments.AddAttachment("Receipt", receipt);
pdf.SaveAs("invoice-with-attachments.pdf");
Enter fullscreen mode Exit fullscreen mode

This code embeds receipt.jpg into the PDF. Users open the PDF, click the attachment icon in the toolbar, and view or save the file.

Why Embed Files Instead of Zipping or Emailing Separately?

Before implementing PDF attachments, our invoice workflow looked like this:

  1. Generate invoice PDF
  2. Create a ZIP file with invoice + supporting docs
  3. Email the ZIP
  4. Users extract ZIP, open invoice, reference supporting docs in separate windows

This caused problems:

  • Clients misplaced supporting documents
  • Email filters blocked ZIPs (security concerns)
  • No visibility into whether clients reviewed supporting materials

Embedding attachments solved this. One PDF contains everything. Clients can't "lose" the receipt because it's inside the invoice they're already viewing.

How Do I Add Attachments to PDFs in C#?

The workflow is straightforward: load the file as a byte array, then call AddAttachment on the PDF document.

using IronPdf;
using System.IO;

byte[] contract = File.ReadAllBytes("contract.pdf");
byte[] photo = File.ReadAllBytes("photo.jpg");

var pdf = PdfDocument.FromFile("main-document.pdf");
pdf.Attachments.AddAttachment("Contract", contract);
pdf.Attachments.AddAttachment("Photo", photo);
pdf.SaveAs("output.pdf");
Enter fullscreen mode Exit fullscreen mode

You can attach any file type: PDFs, images, Word docs, Excel spreadsheets, even ZIP files (though that defeats the purpose). The attachment name is what users see in the PDF reader's attachment panel.

What File Types Can Be Attached?

Any. I've embedded:

  • Images (JPG, PNG, TIFF)
  • Office documents (DOCX, XLSX, PPTX)
  • PDFs (yes, PDFs inside PDFs)
  • Text files
  • Compressed archives (ZIP, RAR)
  • Code files (CS, JSON, XML)

The PDF specification doesn't restrict attachment types. However, be mindful of file size. Large attachments bloat your PDF, making it slow to open and email.

How Do I Retrieve Attachments from PDFs?

The Attachments property exposes all embedded files. Each attachment includes its name and binary data.

using IronPdf;
using System.IO;

var pdf = PdfDocument.FromFile("document-with-attachments.pdf");

foreach (var attachment in pdf.Attachments)
{
    Console.WriteLine($"Found: {attachment.Name}");
    File.WriteAllBytes($"extracted-{attachment.Name}", attachment.Data);
}
Enter fullscreen mode Exit fullscreen mode

This extracts all attachments from the PDF and saves them to disk. I built a batch processor using this pattern to pull supporting documents from thousands of archived invoices.

Can I Filter or Search Attachments by Name?

Yes, since Attachments is an enumerable collection. I use LINQ to find specific attachments:

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

var pdf = PdfDocument.FromFile("invoice.pdf");

var receipt = pdf.Attachments.FirstOrDefault(a => a.Name.Contains("Receipt"));
if (receipt != null)
{
    File.WriteAllBytes("receipt.jpg", receipt.Data);
}
Enter fullscreen mode Exit fullscreen mode

This is useful when PDFs have multiple attachments and you only need to extract one. For example, pulling receipts from invoices while ignoring other supporting docs.

How Do I Remove Attachments from PDFs?

Use RemoveAttachment with a reference to the attachment object:

using IronPdf;

var pdf = PdfDocument.FromFile("document.pdf");

foreach (var attachment in pdf.Attachments.ToList())
{
    if (attachment.Name.Contains("Draft"))
    {
        pdf.Attachments.RemoveAttachment(attachment);
    }
}

pdf.SaveAs("cleaned.pdf");
Enter fullscreen mode Exit fullscreen mode

Important: Call .ToList() before iterating if you're modifying the collection during enumeration. Otherwise, you'll hit a collection modification exception.

I used this pattern to remove draft documents from PDFs before sending them to clients. The PDFs were initially created with internal notes attached, which needed stripping before external distribution.

What Are Common Use Cases for PDF Attachments?

1. Invoicing with Supporting Documents

Embed receipts, delivery confirmations, and contracts directly in invoices. This ensures clients have complete context without managing separate files.

2. Compliance and Audit Trails

Attach signed approval forms, timestamps, or verification documents to reports. When auditors request documentation, one PDF contains everything.

3. Technical Documentation with Code Samples

Embed sample code files in tutorial PDFs. Readers don't need to visit GitHub or download separate ZIPs—the code is right there in the PDF.

4. Legal Documents with Exhibits

Attach evidence, correspondence, or referenced documents to contracts or legal filings. Each exhibit is embedded at the document level.

5. Engineering Drawings with Specifications

Embed detailed spec sheets or CAD files alongside PDF renderings. Engineers view the drawing and access the full specifications without leaving the PDF.

How Do Attachments Compare to Portfolios?

PDF portfolios (also called PDF packages) are a different feature where multiple PDFs are bundled together with a custom navigation interface. Attachments are simpler: files embedded in an existing PDF without changing its structure.

Portfolios require Adobe Acrobat to create and often don't render properly in browser-based PDF viewers. Attachments work everywhere.

For most business use cases, attachments are the better choice. Portfolios are overkill unless you're building a document management system with custom navigation.

What About Alternatives to IronPDF?

Aspose.PDF requires creating FileSpecification objects and calling EmbeddedFiles.Add(). It works but involves more boilerplate than IronPDF's AddAttachment method.

Syncfusion PDF Library has a similar API to IronPDF. It's a good alternative if you're already using Syncfusion components.

iTextSharp (now iText 7) can add attachments via the PdfFileSpec class. However, iText's licensing can be complex for commercial projects, and the API is more verbose.

I chose IronPDF because it fit naturally into our existing document generation workflow, and the licensing was straightforward for commercial use.

How Do I Handle Attachment Errors?

Not all PDFs support attachments. Encrypted or corrupted PDFs might throw exceptions when you attempt to add attachments.

using IronPdf;
using System.IO;

try
{
    var pdf = PdfDocument.FromFile("input.pdf");
    var file = File.ReadAllBytes("attachment.txt");
    pdf.Attachments.AddAttachment("Document", file);
    pdf.SaveAs("output.pdf");
}
catch (Exception ex)
{
    Console.WriteLine($"Failed to attach file: {ex.Message}");
    // Log error or fallback to ZIP archive
}
Enter fullscreen mode Exit fullscreen mode

I log these failures and send alerts if the failure rate exceeds a threshold. Most errors are corrupted input PDFs, not library issues.

Do Attachments Affect PDF File Size?

Yes. Attachments are embedded in the PDF, increasing file size by the size of the attached files. A 500KB PDF with a 2MB attachment becomes a 2.5MB PDF.

For email delivery, keep total size under 10MB. If attachments push you over that limit, consider:

  • Compressing attachments before embedding
  • Using lower-resolution images
  • Linking to cloud storage instead of embedding

I built a validator that checks PDF size before emailing. If it exceeds 8MB, the system uploads it to Azure Blob Storage and emails a download link instead.

Can I Add Attachments to Newly Created PDFs?

Yes. Attachments work on both existing PDFs and newly rendered ones:

using IronPdf;
using System.IO;

var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf("<h1>Report</h1><p>See attached data.</p>");

var data = File.ReadAllBytes("data.xlsx");
pdf.Attachments.AddAttachment("RawData", data);

pdf.SaveAs("report.pdf");
Enter fullscreen mode Exit fullscreen mode

This generates a PDF from HTML and embeds an Excel file in one workflow. I use this pattern for monthly reports where the PDF visualizes data and the raw dataset is attached for further analysis.

How Do I Verify Attachments Were Added?

Open the PDF in a viewer and check the attachments panel. In Chrome's PDF viewer, click the three-dot menu, then "Attachments." You'll see a list of embedded files.

Programmatically, you can verify by reading the Attachments property after saving:

var pdf = PdfDocument.FromFile("output.pdf");
Console.WriteLine($"Attachment count: {pdf.Attachments.Count()}");

foreach (var attachment in pdf.Attachments)
{
    Console.WriteLine($"- {attachment.Name} ({attachment.Data.Length} bytes)");
}
Enter fullscreen mode Exit fullscreen mode

This confirms the attachment was written correctly and retrieves its size.

What About Security Concerns with Embedded Files?

Embedded files can carry malware, just like email attachments. If your application accepts user-uploaded PDFs and extracts attachments, scan the attachments with antivirus software before processing.

var pdf = PdfDocument.FromFile("user-upload.pdf");

foreach (var attachment in pdf.Attachments)
{
    if (IsFileSafe(attachment.Data)) // Integrate virus scanner here
    {
        File.WriteAllBytes(attachment.Name, attachment.Data);
    }
    else
    {
        Console.WriteLine($"Malicious file detected: {attachment.Name}");
    }
}
Enter fullscreen mode Exit fullscreen mode

Never blindly trust attachments from untrusted sources. Treat them like email attachments: scan first, execute only if verified.

Can I Set Descriptions or Metadata for Attachments?

The AddAttachment method accepts a name, but additional metadata (like descriptions) depends on the PDF specification version. Most implementations support only filename and binary data.

If you need richer metadata, consider adding it to the PDF's own metadata fields or embedding a manifest file that describes all attachments:

var manifest = "Receipt: Photo of signed delivery confirmation\nContract: Original signed agreement";
var manifestBytes = System.Text.Encoding.UTF8.GetBytes(manifest);

pdf.Attachments.AddAttachment("README", manifestBytes);
Enter fullscreen mode Exit fullscreen mode

Users open README to see descriptions of other attachments.


Written by Jacob Mellor, CTO at Iron Software. Jacob created IronPDF and leads a team of 50+ engineers building .NET document processing libraries._

Top comments (0)