How to Load and Manage PDF Documents in .NET
Overview
This guide covers opening, creating, and saving PDF documents using the
core Document class.
Prerequisites
| Requirement | Detail |
|---|---|
| Runtime | .NET 8.0 or later |
| Package | Install via dotnet add package |
Open a PDF from bytes
Load an existing PDF into a Document instance by passing a byte array to
Document.Open. This approach avoids file locks and works well for in-memory
workflows such as web request handlers.
using var doc = Document.Open(File.ReadAllBytes("input.pdf"));
Console.WriteLine($"Pages: {doc.Pages.Count}");Create a new document
Instantiate an empty Document, add at least one page, and call Save to
produce a valid PDF file on disk.
using var doc = new Document();
doc.Pages.Add();
doc.Save("new.pdf");Modify page geometry
Access a page by its 1-based index and set the media box, crop box, or rotation.
The Rectangle constructor takes coordinates in the order left, bottom, right, top.
var page = doc.Pages[1];
page.SetMediaBox(new Rectangle(0, 0, 612, 792));
page.SetRotation(90);Add a file attachment
Embed a file into the PDF using FileSpecification. The embedded file appears in
the viewer’s attachment panel and can be extracted by recipients.
var spec = new FileSpecification("data.csv", "Embedded data");
doc.EmbeddedFiles.Add(spec);
doc.Save("with-attachment.pdf");Key Classes
| Class | Purpose |
|---|---|
Document | Root PDF object |
Document.Open | Open from byte array |
Page | Single page with content and geometry |
PageCollection | Manage document pages |
FileSpecification | File attachment descriptor |