---
title: "Extract embedded files from a PDF in C#"
url: https://recursiveai.org/onepdf/cookbook/extract-pdf-attachments/
description: "Extract embedded files from a PDF in C#. Find document and page attachments, decode their bytes, and save them without trusting PDF filenames."
version: "1.25.1"
---

# Extract embedded files from a PDF in C#

**OnePDF** is a free, open-source PDF library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OnePdf) · [GitHub](https://github.com/recursive-ai-oss/onepdf-csharp) · [Docs](https://recursiveai.org/onepdf/docs/) · [Download example (.zip)](https://recursiveai.org/onepdf/cookbook/extract-pdf-attachments/extract-pdf-attachments.zip)

Call `GetAllEmbeddedFiles()` to find document and page attachments. Try it on `attachments.pdf` from the zip.

```shell
dotnet add package RecursiveAI.OnePdf
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using System;
using System.IO;
using OnePdf;

using var pdf =
    PdfDocument.Open("attachments.pdf");
int number = 0;
foreach (var file in pdf.GetAllEmbeddedFiles())
{
    if (!file.HasContent) continue;
    var bytes = file.ReadContent();
    var path = $"attachment-{++number}.bin";
    using var output =
        File.Open(path, FileMode.CreateNew);
    output.Write(bytes.Span);
    Console.WriteLine(path);
}
```

[The example](https://recursiveai.org/onepdf/cookbook/extract-pdf-attachments/extract-pdf-attachments.zip) is the full program below: unzip it and `dotnet run`. To run only the code above, paste it into Program.cs of a new `dotnet new console` project and `dotnet run`.

Writes the two decoded files to the current directory and prints:

```text
attachment-1.bin
attachment-2.bin
```

The files are numbered because `Name` is a label, not a trusted path; to keep it, take only the basename, validate it as a local filename, and use a numbered fallback for invalid or duplicate names.

## The full program

The sample PDF contains `notes.txt` (“Invoice notes”) and a page 1 attachment `page-note.txt` (“Page note”), each ending with a newline. The download prints where it found each attachment and how many bytes it wrote. Run `dotnet run -- your.pdf` for your own file. Run in an empty output directory or remove your previous extracted files first: `FileMode.CreateNew` throws `IOException` instead of replacing a file that already exists.

```csharp
using System;
using System.IO;
using OnePdf;

using var pdf = PdfDocument.Open(
    args.Length > 0 ? args[0] : "attachments.pdf");
var files = args is [_, "--document-only"]
    ? pdf.EmbeddedFiles : pdf.GetAllEmbeddedFiles();
int number = 0;
foreach (var file in files)
{
    if (!file.HasContent)
        continue;

    var bytes = file.ReadContent();
    var path = $"attachment-{++number}.bin";
    using var output = File.Open(path, FileMode.CreateNew);
    output.Write(bytes.Span);
    var source = file.PageIndex < 0
        ? "document" : $"page {file.PageIndex + 1}";
    Console.WriteLine($"{source}: {path} ({bytes.Length} bytes)");
}
```

```text
document: attachment-1.bin (14 bytes)
page 1: attachment-2.bin (10 bytes)
```

## Variations

**Extract only document-level attachments.** Replace `pdf.GetAllEmbeddedFiles()` with `pdf.EmbeddedFiles` in the loop:

```csharp
foreach (var file in pdf.EmbeddedFiles)
{
    // Keep the same loop body.
}
```

Run this mode in the download with `dotnet run -- attachments.pdf --document-only`:

```text
document: attachment-1.bin (14 bytes)
```

## Related recipes

- [Parse a PDF’s object structure](https://recursiveai.org/onepdf/cookbook/parse-pdf-structure/)
- [Extract hyperlinks from a PDF](https://recursiveai.org/onepdf/cookbook/extract-hyperlinks-from-pdf/)
- [Extract embedded images from a PDF](https://recursiveai.org/onepdf/cookbook/extract-images/)

## The short answer

Use `GetAllEmbeddedFiles()` to find both document-level and page attachments. Skip entries where `HasContent` is false. For the rest, `ReadContent()` decodes the embedded stream and returns the file’s bytes. Choose output filenames locally rather than writing to paths supplied by the PDF.

## How do I extract embedded files from a PDF?

A document can list files in its `EmbeddedFiles` name tree, a catalog index that associates names with file specifications. A page can also carry file attachment annotations. These are different from hyperlinks, which can point outside the PDF, and from images used to draw a page.

`GetAllEmbeddedFiles()` starts with the indexed files and then scans each page’s annotations. If all you need is the document list, `EmbeddedFiles` skips the page scan. `PageIndex` is `-1` for the indexed files and zero-based for annotations. The full program adds one only to page indices so the first page is printed as “page 1.”

## How do I save embedded files without trusting their names?

Treat `Name` as a label, not a path. Two specifications can supply the same name, and a specification can name an external file without including any bytes. OnePDF does not open that external file. `HasContent` distinguishes that case from a genuinely embedded zero-byte file. Here, numbered filenames avoid using the PDF’s labels, and `FileMode.CreateNew` prevents overwrites on repeat runs.

Listing attachments does not decode their contents. `ReadContent()` does, and it can throw `PdfLimitException` if the declared or decoded size exceeds the configured stream limit. The `Size` property is just what the PDF declares, so the program reports `bytes.Length` after decoding instead.
