How to Load and Manage PDF Documents in .NET

How to Load and Manage PDF Documents in .NET

How to Load and Manage PDF Documents in .NET

This guide covers opening, creating, and saving PDF documents using the core Document class.


Prerequisites

RequirementDetail
Runtime.NET 8.0 or later
Packagedotnet add package Aspose.Pdf.Foss

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

ClassPurpose
DocumentRoot PDF object
Document.OpenOpen from byte array
PageSingle page with content and geometry
PageCollectionManage document pages
FileSpecificationFile attachment descriptor

See Also