Class PdfDocument
Represents a PDF document with full manipulation capabilities - merge, split, edit, secure, and save. This is your PDF after rendering - now you can modify it, add security, extract content, or save to disk.
Implements
Namespace: IronPdf
Assembly: IronPdf.dll
Syntax
public class PdfDocument : PdfClientAccessor, IDocumentId, IDisposable
Remarks
PdfDocument is the result of any PDF generation in IronPDF. Once you have a PdfDocument, you can manipulate it in countless ways: add pages, remove pages, merge with other PDFs, add passwords, sign digitally, redact content, extract text, and much more.
using IronPdf;
// Generate and manipulate
var pdf = ChromePdfRenderer.StaticRenderHtmlAsPdf("
Invoice
");
pdf.Password = "secret123";
pdf.SaveAs("secured-invoice.pdf");
pdf.Dispose(); // Or use 'using' statement
- Form filling and extraction
- Annotation management
- Page manipulation (rotate, crop, resize)
- Metadata editing
- OCR for scanned documents
- PDF/A conversion
- Compression and optimization
Examples
// Complete lifecycle example
using IronPdf;
// 1. Generate PDF
var renderer = new ChromePdfRenderer();
using (var pdf = renderer.RenderHtmlAsPdf("Report
"))
{
// 2. Manipulate
pdf.AddWatermark("CONFIDENTIAL
");
pdf.Password = "user123";
pdf.OwnerPassword = "owner456";
// 3. Extract if needed
string text = pdf.ExtractAllText();
// 4. Save
pdf.SaveAs("final-report.pdf");
} // Automatically disposed
// Merging example
var merged = PdfDocument.Merge(pdf1, pdf2, pdf3);
merged.SaveAs("combined.pdf");
merged.Dispose();
Constructors
PdfDocument(PdfDocument)
Creates an independent copy of an existing PDF document. Perfect for creating document versions, templates, or parallel processing without affecting the original.
// Create a working copy:
var original = new PdfDocument("template.pdf");
var copy = new PdfDocument(original);
copy.AddWatermark("DRAFT");
copy.SaveAs("draft-version.pdf");
// Original remains unchanged
// Create multiple versions from template:
var template = new PdfDocument("invoice-template.pdf");
foreach (var customer in customers)
{
var invoice = new PdfDocument(template);
invoice.ReplaceTextOnAllPages("[CUSTOMER]", customer.Name);
invoice.ReplaceTextOnAllPages("[AMOUNT]", customer.Amount.ToString());
invoice.SaveAs($"invoice-{customer.Id}.pdf");
}
// Safe parallel processing:
var source = new PdfDocument("source.pdf");
var tasks = Enumerable.Range(1, 5).Select(i => Task.Run(() =>
{
var clone = new PdfDocument(source);
clone.AddWatermark($"Version {i}");
clone.SaveAs($"version-{i}.pdf");
}));
await Task.WhenAll(tasks);Creates deep copy - changes don't affect original
Cloned document needs separate disposal
See: https://ironpdf.com/how-to/copy-pdf-pages/
Declaration
public PdfDocument(PdfDocument Document)
Parameters
| Type | Name | Description |
|---|---|---|
| PdfDocument | Document | Source PdfDocument to clone |
PdfDocument(in Byte[], String, String, ChangeTrackingModes)
Opens a PDF document from a byte array for fast in-memory processing.
Ideal for database BLOBs, encrypted data, or byte-based operations.
Adding a using declaration is not required. But can be used if you want to explicitly dispose. See: https://ironpdf.com/troubleshooting/ironpdf-using/
// Load from database BLOB:
byte[] pdfData = GetPdfBlobFromDatabase(documentId);
var pdf = new PdfDocument(pdfData);
pdf.SaveAs("from-database.pdf");
// Process encrypted PDF bytes:
byte[] encrypted = File.ReadAllBytes("encrypted.pdf");
byte[] decrypted = DecryptData(encrypted);
var pdf = new PdfDocument(decrypted);
// Convert base64 string to PDF:
string base64Pdf = GetBase64PdfFromApi();
byte[] pdfBytes = Convert.FromBase64String(base64Pdf);
var pdf = new PdfDocument(pdfBytes, "password");
// Process PDF from web service:
var client = new WebServiceClient();
byte[] pdfData = client.GetPdfDocument(invoiceId);
using (var pdf = new PdfDocument(pdfData))
{
pdf.AddWatermark("RECEIVED");
pdf.SaveAs($"invoice-{invoiceId}.pdf");
}
// Memory-efficient processing:
byte[] largePdfData = LoadLargePdf();
var pdf = new PdfDocument(in largePdfData); // 'in' keyword for efficiency
Use 'in' keyword for large byte arrays to avoid copying
Byte array must contain valid PDF data
Declaration
public PdfDocument(in byte[] PdfData, string Password = "", string OwnerPassword = "", ChangeTrackingModes TrackChanges)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Byte[] | PdfData | Byte array containing complete PDF document |
| System.String | Password | User password for encrypted PDFs (optional) |
| System.String | OwnerPassword | Owner password for restricted PDFs (optional) |
| ChangeTrackingModes | TrackChanges | Enable change tracking for incremental saves |
Exceptions
| Type | Condition |
|---|---|
| System.IO.IOException | Byte array is null or empty |
PdfDocument(List<IBoundedPdfDocumentObject>, List<RectangleF>)
Create a new PDF document from the specified low-level document objects and page bounds
Declaration
public PdfDocument(List<IBoundedPdfDocumentObject> objects, List<RectangleF> bounds)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.List<IronSoftware.Abstractions.Pdf.IBoundedPdfDocumentObject> | objects | Document objects |
| System.Collections.Generic.List<System.Drawing.RectangleF> | bounds | Page bounds |
PdfDocument(Double, Double)
Creates a new blank PDF document with custom dimensions. Perfect for generating custom forms, templates, or non-standard page sizes.
// Create A4 size document (210x297mm):
var a4Pdf = new PdfDocument(210, 297);
a4Pdf.SaveAs("blank-a4.pdf");
// Create US Letter (8.5x11 inches = 216x279mm):
var letterPdf = new PdfDocument(216, 279);
// Create business card size:
var cardPdf = new PdfDocument(85, 55);
// Create square document:
var squarePdf = new PdfDocument(200, 200);Dimensions are in millimeters for precise control
Creates completely blank document - add content with stampers
See: https://ironpdf.com/how-to/create-new-pdfs/
Declaration
public PdfDocument(double Width, double Height)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Double | Width | Document width in millimeters |
| System.Double | Height | Document height in millimeters |
PdfDocument(Stream, String, String, ChangeTrackingModes)
Opens a PDF document from a Stream for in-memory processing.
Perfect for processing uploaded files, database BLOBs, or API responses without disk I/O.
Adding a using declaration is not required. But can be used if you want to explicitly dispose. See: https://ironpdf.com/troubleshooting/ironpdf-using/
// Process uploaded file:
public async Task ProcessUpload(IFormFile file)
{
using (var stream = file.OpenReadStream())
{
var pdf = new PdfDocument(stream);
pdf.AddWatermark("UPLOADED");
pdf.SaveAs($"uploads/{file.FileName}");
}
}
// Load from database BLOB:
byte[] pdfBlob = GetPdfFromDatabase(documentId);
using (var stream = new MemoryStream(pdfBlob))
{
var pdf = new PdfDocument(stream, "password");
var text = pdf.ExtractAllText();
}
// Process API response stream:
using (var response = await httpClient.GetStreamAsync("api/getPdf"))
{
var pdf = new PdfDocument(response);
pdf.SaveAs("api-document.pdf");
}
// Read from embedded resource:
var assembly = Assembly.GetExecutingAssembly();
using (var resource = assembly.GetManifestResourceStream("template.pdf"))
{
var pdf = new PdfDocument(resource);
// Process template
}
Stream position is read from current position to end
Stream must be readable and contain valid PDF data
Declaration
public PdfDocument(Stream PdfDataStream, string Password = "", string OwnerPassword = "", ChangeTrackingModes TrackChanges)
Parameters
| Type | Name | Description |
|---|---|---|
| System.IO.Stream | PdfDataStream | Stream containing PDF data (MemoryStream, FileStream, etc.) |
| System.String | Password | User password for encrypted PDFs (optional) |
| System.String | OwnerPassword | Owner password for restricted PDFs (optional) |
| ChangeTrackingModes | TrackChanges | Enable change tracking for incremental saves |
Exceptions
| Type | Condition |
|---|---|
| System.IO.IOException | Stream is null or cannot be read |
PdfDocument(String, String, String, ChangeTrackingModes)
Opens an existing PDF document from file for editing, merging, or manipulation.
The primary way to load PDFs from disk for processing with IronPDF.
Adding a using declaration is not required. But can be used if you want to explicitly dispose. See: https://ironpdf.com/troubleshooting/ironpdf-using/
// Open existing PDF:
var pdf = new PdfDocument("invoice.pdf");
pdf.SaveAs("modified.pdf");
// Open password-protected PDF:
var securePdf = new PdfDocument("protected.pdf", "userpass123");
// Open with owner password for full permissions:
var ownedPdf = new PdfDocument("restricted.pdf", "", "ownerpass456");
// Open with change tracking for incremental saves:
var trackedPdf = new PdfDocument("document.pdf", "", "",
ChangeTrackingModes.EnableChangeTracking);
trackedPdf.SaveAsRevision("document-v2.pdf");
// Batch process PDFs:
foreach (var file in Directory.GetFiles("pdfs", "*.pdf"))
{
using (var pdf = new PdfDocument(file))
{
pdf.AddWatermark("PROCESSED");
pdf.SaveAs(Path.Combine("output", Path.GetFileName(file)));
}
}
Use 'using' statement for automatic disposal, or call Dispose() manually
File must exist and be a valid PDF or exception is thrown
Declaration
public PdfDocument(string PdfFilePath, string Password = "", string OwnerPassword = "", ChangeTrackingModes TrackChanges)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | PdfFilePath | Path to the PDF file (relative or absolute) |
| System.String | Password | User password for encrypted PDFs (optional) |
| System.String | OwnerPassword | Owner password for restricted PDFs (optional) |
| ChangeTrackingModes | TrackChanges | Enable change tracking for incremental saves |
Exceptions
| Type | Condition |
|---|---|
| System.IO.IOException | File cannot be opened or doesn't exist |
| System.ArgumentException | Path is null or empty |
PdfDocument(Uri, String, String, ChangeTrackingModes)
Opens a PDF document directly from a web URL or network location.
Downloads and loads PDFs from HTTP, HTTPS, FTP, or file:// URIs for processing.
Adding a using declaration is not required. But can be used if you want to explicitly dispose. See: https://ironpdf.com/troubleshooting/ironpdf-using/
// Load PDF from web URL:
var uri = new Uri("https://example.com/document.pdf");
var webPdf = new PdfDocument(uri);
webPdf.SaveAs("downloaded.pdf");
// Load from secure URL with authentication:
var secureUri = new Uri("https://secure.example.com/protected.pdf");
var securePdf = new PdfDocument(secureUri, "userpass");
// Process PDF from FTP server:
var ftpUri = new Uri("ftp://ftp.example.com/reports/monthly.pdf");
var ftpPdf = new PdfDocument(ftpUri);
ftpPdf.AddWatermark("Downloaded from FTP");
ftpPdf.SaveAs("ftp-report.pdf");
// Load from network share:
var networkUri = new Uri("file://server/share/document.pdf");
var networkPdf = new PdfDocument(networkUri);
// Download and process with error handling:
try
{
var uri = new Uri("https://api.example.com/getPdf?id=123");
using (var pdf = new PdfDocument(uri))
{
var text = pdf.ExtractAllText();
pdf.SaveAs("api-document.pdf");
}
}
catch (IronPdfProductException ex)
{
Console.WriteLine($"Failed to download PDF: {ex.Message}");
}
PDF is downloaded to memory before processing
Requires network access and valid URI
Declaration
public PdfDocument(Uri PdfUri, string Password = "", string OwnerPassword = "", ChangeTrackingModes TrackChanges)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Uri | PdfUri | URI pointing to the PDF (HTTP, HTTPS, FTP, or file://) |
| System.String | Password | User password if PDF is encrypted (optional) |
| System.String | OwnerPassword | Owner password for restricted PDFs (optional) |
| ChangeTrackingModes | TrackChanges | Enable change tracking for incremental saves |
Exceptions
| Type | Condition |
|---|---|
| IronPdfProductException | Cannot download from URI or incorrect password |
Properties
Annotations
Collection of PDF annotations (sticky notes, comments) for document markup. Annotations appear as interactive icons that expand to show comments when clicked.
// Quick add annotation:
var note = new TextAnnotation(0, "Review", "Check this section");
pdf.Annotations.Add(note);
note.X = 100; note.Y = 200; // Position from bottom-leftY-axis measured from BOTTOM upwards (not top-down!)
See: https://ironpdf.com/how-to/pdf-annotations/
Declaration
public PdfAnnotationCollection Annotations { get; }
Property Value
| Type | Description |
|---|---|
| PdfAnnotationCollection |
Remarks
Annotations are NOT the same as stamps/watermarks. They're interactive sticky-note style comments that users can view, edit, and respond to in PDF readers. Common for document review, feedback, and collaborative markup.
Attachments
Collection of file attachments embedded in the PDF document. Allows embedding any type of file for distribution as a single package.
// Attach file:
byte[] data = File.ReadAllBytes("report.xlsx");
pdf.Attachments.AddAttachment("Q4_Report.xlsx", data);
// Extract attachment:
var attachment = pdf.Attachments[0];
File.WriteAllBytes(attachment.Name, attachment.Data);Attachments are sorted alphabetically (case-sensitive)
See: https://ironpdf.com/how-to/pdf-attachments/
Declaration
public PdfAttachmentCollection Attachments { get; }
Property Value
| Type | Description |
|---|---|
| PdfAttachmentCollection |
Remarks
Attachments are complete files embedded in the PDF (not rendered content). Appear as paperclip icons in PDF readers. Perfect for invoices with receipts, reports with raw data, contracts with supporting documents. Note: Increases file size by size of attached files.
BinaryData
Gets the PDF as a byte array including all changes - perfect for databases, APIs, and streams. Returns the complete PDF binary data ready for storage or transmission without writing to disk.
// Get PDF as bytes for database storage:
byte[] pdfBytes = pdf.BinaryData;
SaveToDatabase(documentId, pdfBytes);
// Send PDF via web API:
var response = new HttpResponseMessage {
Content = new ByteArrayContent(pdf.BinaryData)
};
response.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/pdf");
// Convert to Base64 for JSON API:
string base64Pdf = Convert.ToBase64String(pdf.BinaryData);
// Create memory stream for processing:
using (var stream = new MemoryStream(pdf.BinaryData))
{
// Process stream...
}
// Save to Azure Blob Storage:
await blobClient.UploadAsync(
new MemoryStream(pdf.BinaryData),
overwrite: true);No disk I/O required - pure in-memory operation
Large PDFs consume significant memory
For incremental saves preserving history, use BinaryDataIncremental
See: https://ironpdf.com/how-to/binary-data-streams/
Declaration
public byte[] BinaryData { get; }
Property Value
| Type | Description |
|---|---|
| System.Byte[] | The complete PDF file as a byte array ready for storage or transmission. |
Remarks
BinaryData is essential for: • Storing PDFs in databases (BLOB fields) • Sending PDFs via web APIs • Cloud storage uploads (AWS S3, Azure Blob) • Email attachments • In-memory processing pipelines • Avoiding disk I/O for security or performance
The byte array includes all modifications made to the PDF. Each call regenerates the array, so cache it if using multiple times.
Examples
// Database storage pattern
public void SaveInvoiceToDatabase(int customerId, PdfDocument invoice)
{
using (var connection = new SqlConnection(connectionString))
{
var command = new SqlCommand(
"INSERT INTO Invoices (CustomerId, PdfData, CreatedDate) " +
"VALUES (@customerId, @pdfData, @date)", connection);
command.Parameters.AddWithValue("@customerId", customerId);
command.Parameters.AddWithValue("@pdfData", invoice.BinaryData);
command.Parameters.AddWithValue("@date", DateTime.Now);
connection.Open();
command.ExecuteNonQuery();
}
}
// Web API response pattern
[HttpGet("document/{id}")]
public IActionResult GetDocument(int id)
{
var pdf = GenerateDocument(id);
return File(pdf.BinaryData, "application/pdf", $"document_{id}.pdf");
}
BinaryDataIncremental
Saves the PDF as byte array with changes appended to the end of the file. For non-incremental saves, see BinaryData
For information on how to enable incremental saves see SaveAsRevision(String)
Declaration
public byte[] BinaryDataIncremental { get; }
Property Value
| Type | Description |
|---|---|
| System.Byte[] | The PDF file as a byte array. |
Bookmarks
Hierarchical navigation bookmarks (table of contents) for the PDF document. Bookmarks appear in PDF reader sidebars for quick document navigation.
// Add chapter bookmark:
pdf.Bookmarks.AddBookMarkAtEnd("Chapter 1", 10); // Links to page 11
// Add nested section:
var chapter = pdf.Bookmarks.FirstBookmark;
chapter.Children.AddBookMarkAtEnd("Section 1.1", 12);Page indexes are ZERO-BASED (page 1 = index 0)
See: https://ironpdf.com/how-to/pdf-bookmarks-contents/
Declaration
public PdfBookMarkCollection Bookmarks { get; }
Property Value
| Type | Description |
|---|---|
| PdfBookMarkCollection |
Remarks
Bookmarks (also called outlines) provide hierarchical navigation structure. NOT the same as annotations (which are sticky notes/comments). Perfect for creating table of contents, chapter navigation, and document structure.
Fonts
PDF Document's Font collection management. Access, analyze, and manipulate fonts embedded in the PDF document.
// List all fonts in document:
var pdf = PdfDocument.FromFile("report.pdf");
foreach (var font in pdf.Fonts) {
Console.WriteLine($"Font: {font.Name}, Embedded: {font.IsEmbedded}");
}
// Find specific font:
var arialFont = pdf.Fonts.Find("Arial");
if (arialFont != null) {
Console.WriteLine($"Arial font found, Type: {arialFont.Type}");
}
// Check font count:
Console.WriteLine($"Total fonts: {pdf.Fonts.Count}");
// Embed missing fonts for PDF/A compliance:
var zapfFont = pdf.Fonts.Find("ZapfDingbats");
if (zapfFont != null && !zapfFont.IsEmbedded) {
byte[] fontData = GetFontFile("ZapfDingbats.ttf");
zapfFont.Embed(fontData);
}
// Common standard PDF fonts:
// - Helvetica, Times-Roman, Courier (and variants)
// - Symbol, ZapfDingbatsFont embedding ensures consistent display across systems
Non-embedded fonts may display differently on other computers
See: https://ironpdf.com/how-to/fonts-management/
Declaration
public PdfFontCollection Fonts { get; }
Property Value
| Type | Description |
|---|---|
| PdfFontCollection |
Form
Gets an object returning any PDF editable form fields which can have their values both read and set programmatically. Provides complete access to text fields, checkboxes, radio buttons, dropdowns, and other interactive elements.
// Access form fields by name:
pdf.Form["firstName"].Value = "John";
pdf.Form["lastName"].Value = "Doe";
pdf.Form["subscribe"].Value = "Yes";
// Iterate all form fields:
foreach (var field in pdf.Form)
{
Console.WriteLine($"{field.Name}: {field.Value}");
}
// Check field types and properties:
var emailField = pdf.Form["email"];
if (emailField != null)
{
Console.WriteLine($"Type: {emailField.Type}");
Console.WriteLine($"Required: {emailField.Required}");
Console.WriteLine($"ReadOnly: {emailField.ReadOnly}");
}Access fields by name using indexer or iterate entire collection
Field names are case-sensitive
See: https://ironpdf.com/how-to/manage-pdf-forms/
Declaration
public FormFieldCollection Form { get; }
Property Value
| Type | Description |
|---|---|
| FormFieldCollection | The form field collection containing all interactive form fields in the document. |
Remarks
The Form collection provides: • Text fields (single and multi-line) • Checkboxes (boolean values) • Radio buttons (grouped selections) • Dropdown lists (combo boxes) • List boxes (multiple selections) • Push buttons (for actions) • Signature fields
Common operations: • Fill forms programmatically • Extract submitted data • Validate field values • Set field properties (readonly, required) • Export/import form data
Examples
// Complete form automation example
var pdf = PdfDocument.FromFile("application.pdf");
// Fill text fields
pdf.Form["fullName"].Value = "Jane Smith";
pdf.Form["email"].Value = "jane@example.com";
pdf.Form["phone"].Value = "555-0123";
// Set checkbox
pdf.Form["agreeTerms"].Value = "Yes";
// Select dropdown option
pdf.Form["country"].Value = "United States";
// Select radio button
pdf.Form["paymentMethod"].Value = "Credit Card";
// Save filled form
pdf.SaveAs("application-filled.pdf");
// Extract all form data
var formData = new Dictionary<string, string>();
foreach (var field in pdf.Form)
{
formData[field.Name] = field.Value;
}
MetaData
PDF document metadata (title, author, keywords, dates, etc.). Essential for document management, SEO, and searchability.
// Set document properties:
pdf.MetaData.Title = "Q4 Financial Report";
pdf.MetaData.Author = "Finance Team";
pdf.MetaData.Keywords = "finance, quarterly, 2025";
pdf.MetaData.Subject = "Quarterly financial results";
// Read creation date:
var created = pdf.MetaData.CreationDate;See: https://ironpdf.com/how-to/pdf-metadata/
Declaration
public PdfMetaData MetaData { get; }
Property Value
| Type | Description |
|---|---|
| PdfMetaData | MetaData settings for this PDF as an instance of PdfMetaData |
OwnerPassword
Sets the owner password and enables 128-bit encryption of PDF content. An owner password is one used to enable and disable all other security settings.
OwnerPassword must be set to a non empty string value forAllowUserCopyPasteContent,AllowUserAnnotations,AllowUserFormData,AllowUserPrinting andAllowUserEdits to be restricted.
Declaration
public string OwnerPassword { get; set; }
Property Value
| Type | Description |
|---|---|
| System.String |
PageCount
Declaration
public int PageCount { get; }
Property Value
| Type | Description |
|---|---|
| System.Int32 |
Pages
Gets the list of pages in the PDF document providing detailed page-level access. Each page object contains dimensions, rotation, and content information.
// Access specific page:
var firstPage = pdf.Pages[0];
Console.WriteLine($"Width: {firstPage.Width}mm");
Console.WriteLine($"Height: {firstPage.Height}mm");
// Iterate through all pages:
foreach (var page in pdf.Pages)
{
Console.WriteLine($"Page {page.PageIndex}: {page.Width}x{page.Height}mm");
Console.WriteLine($"Rotation: {page.Rotation} degrees");
}
// Get page dimensions:
var page = pdf.Pages[0];
var widthInches = page.Width / 25.4; // Convert mm to inches
var heightPixels = page.Height * 72 / 25.4; // Convert to pixels at 72 DPIProvides rich page metadata including size, rotation, and content info
Performance note: For large documents, avoid repeatedly accessing this property
See: https://ironpdf.com/how-to/manage-pdf-pages/
Declaration
public PdfPagesCollection Pages { get; }
Property Value
| Type | Description |
|---|---|
| PdfPagesCollection |
Remarks
The Pages collection provides: • Page dimensions (width, height) • Page rotation angle • Page content streams • Page resources (fonts, images) • Page annotations • Page crop/bleed boxes
Performance tip: For operations on many pages, cache the Pages collection rather than accessing it repeatedly in loops.
Examples
// Analyze document structure
var pdf = PdfDocument.FromFile("report.pdf");
var pages = pdf.Pages; // Cache for performance
// Find landscape pages
var landscapePages = pages
.Where(p => p.Width > p.Height)
.Select(p => p.PageIndex)
.ToList();
// Get page size statistics
var pageSizes = pages
.GroupBy(p => $"{p.Width:F0}x{p.Height:F0}")
.Select(g => new { Size = g.Key, Count = g.Count() })
.ToList();
foreach (var size in pageSizes)
{
Console.WriteLine($"Size {size.Size}mm: {size.Count} pages");
}
Password
Sets a Password used to protect and encrypt the PDF File. Setting a password will cause IronPDF to automatically protect the PDF file content using strong 128 bit encryption. Setting the password to null will remove any existing password.
Declaration
public string Password { get; set; }
Property Value
| Type | Description |
|---|---|
| System.String |
RevisionCount
Number of revisions available in the document. See SaveAsRevision(String)
Declaration
public int RevisionCount { get; }
Property Value
| Type | Description |
|---|---|
| System.Int32 |
SecuritySettings
Security settings for PDF encryption and access control. Control passwords, printing, copying, and editing permissions.
// Password protect PDF:
pdf.SecuritySettings.UserPassword = "read123";
pdf.SecuritySettings.OwnerPassword = "admin456";
// Restrict permissions:
pdf.SecuritySettings.AllowPrint = false;
pdf.SecuritySettings.AllowCopy = false;
pdf.SecuritySettings.AllowEditContent = false;Editing PDFs breaks digital signatures
See: https://ironpdf.com/how-to/pdf-security/
Declaration
public PdfSecuritySettings SecuritySettings { get; }
Property Value
| Type | Description |
|---|---|
| PdfSecuritySettings | Advanced security settings for this PDF as an instance of PdfSecuritySettings |
Stream
Gets the binary data for the full PDF file as a Stream.
This Stream is System.IDisposable and should be disposed with "using" or "Dispose()" methods.
Declaration
public MemoryStream Stream { get; }
Property Value
| Type | Description |
|---|---|
| System.IO.MemoryStream | The PDF file as a new MemoryStream which is System.IDisposable and should be disposed with "using" or "Dispose()" methods. |
Methods
AddBackgroundPdf(PdfDocument, Int32)
Adds a background from a PdfDocument object to all pages. Enables complex multi-layered document composition and watermarking.
// Add watermark from memory:
var watermark = PdfDocument.FromHtml("<h1 style='color:red;opacity:0.5'>DRAFT</h1>");
pdf.AddBackgroundPdf(watermark, 0);
// Add company letterhead:
var letterhead = PdfDocument.FromFile("letterhead.pdf");
report.AddBackgroundPdf(letterhead);
// Combine multiple documents:
var template = renderer.RenderHtmlAsPdf(templateHtml);
var content = PdfDocument.FromFile("content.pdf");
content.AddBackgroundPdf(template, 0);Background appears behind existing content
Background is stretched to fit each page
See: https://ironpdf.com/how-to/backgrounds-and-overlays/
Declaration
public PdfDocument AddBackgroundPdf(PdfDocument BackgroundPdf, int BackgroundPdfPageIndex = 0)
Parameters
| Type | Name | Description |
|---|---|---|
| PdfDocument | BackgroundPdf | The Background PDF as a PdfDocument. |
| System.Int32 | BackgroundPdfPageIndex | Index (zero-based page number) to copy from the BackgroundPdf. |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument object, allowing for a 'fluent' (LINQ like) chained in-line code style |
AddBackgroundPdf(String, Int32)
Adds a background to all pages of this PDF (appears behind content). Perfect for watermarks, letterheads, and document branding.
// Add watermark to all pages:
pdf.AddBackgroundPdf("watermark.pdf");
// Add letterhead:
pdf.AddBackgroundPdf("company_letterhead.pdf", 0);See: https://ironpdf.com/how-to/backgrounds-and-overlays/
Declaration
public PdfDocument AddBackgroundPdf(string BackgroundPdfPath, int BackgroundPdfPageIndex = 0)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | BackgroundPdfPath | Path to PDF file containing the background |
| System.Int32 | BackgroundPdfPageIndex | Zero-based page index from background PDF to use (default: 0) |
Returns
| Type | Description |
|---|---|
| PdfDocument | This PdfDocument for fluent chaining |
AddBackgroundPdfToPage(Int32, PdfDocument, Int32)
Declaration
public PdfDocument AddBackgroundPdfToPage(int ToPageIndex, PdfDocument BackgroundPdf, int BackgroundPdfPageIndex = 0)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | ToPageIndex | |
| PdfDocument | BackgroundPdf | |
| System.Int32 | BackgroundPdfPageIndex |
Returns
| Type | Description |
|---|---|
| PdfDocument |
AddBackgroundPdfToPage(Int32, String, Int32)
Adds a background to a single specific page from a file path. Perfect for page-specific watermarks or selective backgrounds.
// Add "CONFIDENTIAL" to first page only:
pdf.AddBackgroundPdfToPage(0, "confidential_watermark.pdf");
// Add signature background to last page:
int lastPage = pdf.PageCount - 1;
pdf.AddBackgroundPdfToPage(lastPage, "signature_template.pdf");
// Different backgrounds for different pages:
pdf.AddBackgroundPdfToPage(0, "cover_background.pdf")
.AddBackgroundPdfToPage(1, "content_background.pdf")
.AddBackgroundPdfToPage(pdf.PageCount - 1, "final_background.pdf");Use method chaining for multiple page-specific backgrounds
ToPageIndex must be valid (0 to PageCount-1)
See: https://ironpdf.com/how-to/backgrounds-and-overlays/
Declaration
public PdfDocument AddBackgroundPdfToPage(int ToPageIndex, string BackgroundPdfPath, int BackgroundPdfPageIndex = 0)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | ToPageIndex | Index (zero-based page number) of the page of this PDF to which the background will be applied to. |
| System.String | BackgroundPdfPath | The background PDF path. |
| System.Int32 | BackgroundPdfPageIndex | Index (zero-based page number) to copy from the BackgroundPdf. |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument object, allowing for a 'fluent' (LINQ like) chained in-line code style |
AddBackgroundPdfToPageRange(IEnumerable<Int32>, PdfDocument, Int32)
Adds backgrounds to specific pages using a PdfDocument. Core method for flexible background application with in-memory PDFs.
// Dynamic watermarks for different page types:
var draftMark = renderer.RenderHtmlAsPdf("<h1>DRAFT</h1>");
var confidentialMark = renderer.RenderHtmlAsPdf("<h1>CONFIDENTIAL</h1>");
var draftPages = GetDraftPageIndices();
var confidentialPages = GetConfidentialPageIndices();
pdf.AddBackgroundPdfToPageRange(draftPages, draftMark)
.AddBackgroundPdfToPageRange(confidentialPages, confidentialMark);
// Apply template to specific sections:
var sectionTemplate = CreateSectionTemplate();
var sectionPages = new[] { 5, 10, 15, 20 };
pdf.AddBackgroundPdfToPageRange(sectionPages, sectionTemplate);Pass null for ToPageIndexes to apply to all pages
Each call adds a new layer - multiple backgrounds stack
See: https://ironpdf.com/how-to/backgrounds-and-overlays/
Declaration
public PdfDocument AddBackgroundPdfToPageRange(IEnumerable<int> ToPageIndexes, PdfDocument BackgroundPdf, int BackgroundPdfPageIndex = 0)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<System.Int32> | ToPageIndexes | A list of Indexes (zero-based page numbers) of pages in this PDF to which the background will be applied to. |
| PdfDocument | BackgroundPdf | The Background PDF as a PdfDocument. |
| System.Int32 | BackgroundPdfPageIndex | Index (zero-based page number) to copy from the BackgroundPdf. |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument object, allowing for a 'fluent' (LINQ like) chained in-line code style |
AddBackgroundPdfToPageRange(IEnumerable<Int32>, String, Int32)
Adds backgrounds to specific pages from a file path. Ideal for selective watermarking or custom page backgrounds.
// Add watermark to odd pages only:
var oddPages = Enumerable.Range(0, pdf.PageCount)
.Where(i => i % 2 == 0);
pdf.AddBackgroundPdfToPageRange(oddPages, "watermark.pdf");
// Add to first and last pages:
pdf.AddBackgroundPdfToPageRange(
new[] { 0, pdf.PageCount - 1 },
"special_background.pdf");
// Skip cover page, watermark rest:
var contentPages = Enumerable.Range(1, pdf.PageCount - 1);
pdf.AddBackgroundPdfToPageRange(contentPages, "draft.pdf");Null or empty collection applies to all pages
Invalid page indices are silently ignored
See: https://ironpdf.com/how-to/backgrounds-and-overlays/
Declaration
public PdfDocument AddBackgroundPdfToPageRange(IEnumerable<int> ToPageIndexes, string BackgroundPdfPath, int BackgroundPdfPageIndex = 0)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<System.Int32> | ToPageIndexes | A list of Indexes (zero-based page numbers) of pages in this PDF to which the background will be applied to. |
| System.String | BackgroundPdfPath | The background PDF path. |
| System.Int32 | BackgroundPdfPageIndex | Index (zero-based page number) to copy from the BackgroundPdf. |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument object, allowing for a 'fluent' (LINQ like) chained in-line code style |
AddBackgroundPdfToPageRange(Int32, Int32, PdfDocument, Int32)
Declaration
public PdfDocument AddBackgroundPdfToPageRange(int StartPageIndex, int EndPageIndex, PdfDocument BackgroundPdf, int BackgroundPdfPageIndex = 0)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | StartPageIndex | |
| System.Int32 | EndPageIndex | |
| PdfDocument | BackgroundPdf | |
| System.Int32 | BackgroundPdfPageIndex |
Returns
| Type | Description |
|---|---|
| PdfDocument |
AddBackgroundPdfToPageRange(Int32, Int32, String, Int32)
Adds backgrounds to a consecutive page range from a file. Efficient method for applying backgrounds to sequential pages.
// Add watermark to pages 2-10:
pdf.AddBackgroundPdfToPageRange(1, 9, "watermark.pdf");
// Add background to middle section:
int startChapter = 5;
int endChapter = 25;
pdf.AddBackgroundPdfToPageRange(startChapter, endChapter,
"chapter_background.pdf");
// Skip first and last page:
pdf.AddBackgroundPdfToPageRange(
1, // Skip cover
pdf.PageCount - 2, // Skip back cover
"content_bg.pdf");Both StartPageIndex and EndPageIndex are inclusive
EndPageIndex must be >= StartPageIndex
See: https://ironpdf.com/how-to/backgrounds-and-overlays/
Declaration
public PdfDocument AddBackgroundPdfToPageRange(int StartPageIndex, int EndPageIndex, string BackgroundPdfPath, int BackgroundPdfPageIndex = 0)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | StartPageIndex | First index (zero-based page number) to start adding backgrounds to . |
| System.Int32 | EndPageIndex | Last index (zero-based page number) to end adding backgrounds to. |
| System.String | BackgroundPdfPath | The background PDF path. |
| System.Int32 | BackgroundPdfPageIndex | Index (zero-based page number) to copy from the BackgroundPdf. |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument object, allowing for a 'fluent' (LINQ like) chained in-line code style |
AddForegroundOverlayPdf(PdfDocument, Int32)
Adds a foreground overlay to all pages using a PdfDocument. Enables dynamic overlays and complex document composition.
// Add dynamic timestamp overlay:
var timestamp = renderer.RenderHtmlAsPdf(
$"<div>Processed: {DateTime.Now}</div>");
pdf.AddForegroundOverlayPdf(timestamp);
// Add semi-transparent overlay:
var overlay = renderer.RenderHtmlAsPdf(@"
<div style='opacity:0.3; color:red; font-size:72px;
transform:rotate(-45deg)'>
CONFIDENTIAL
</div>");
pdf.AddForegroundOverlayPdf(overlay);
// Layer multiple overlays:
pdf.AddForegroundOverlayPdf(headerOverlay)
.AddForegroundOverlayPdf(footerOverlay)
.AddForegroundOverlayPdf(watermarkOverlay);Multiple overlays stack in order applied
Overlays can make text unselectable if opaque
See: https://ironpdf.com/how-to/backgrounds-and-overlays/
Declaration
public PdfDocument AddForegroundOverlayPdf(PdfDocument OverlayPdf, int OverlayPdfPageIndex = 0)
Parameters
| Type | Name | Description |
|---|---|---|
| PdfDocument | OverlayPdf | The overlay PDF as a PdfDocument. |
| System.Int32 | OverlayPdfPageIndex | Index (zero-based page number) to copy from the Overlay PDF. |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument object, allowing for a 'fluent' (LINQ like) chained in-line code style |
AddForegroundOverlayPdf(String, Int32)
Adds a foreground overlay to all pages from a file path. Perfect for stamps, headers, annotations that appear above content.
// Add "APPROVED" stamp to all pages:
pdf.AddForegroundOverlayPdf("approved_stamp.pdf");
// Add header overlay:
pdf.AddForegroundOverlayPdf("header_template.pdf", 0);
// Add signature overlay to contract:
contract.AddForegroundOverlayPdf("signature_overlay.pdf");
contract.SaveAs("signed_contract.pdf");Overlay appears above existing content
Transparent areas in overlay show underlying content
See: https://ironpdf.com/how-to/backgrounds-and-overlays/
Declaration
public PdfDocument AddForegroundOverlayPdf(string OverlayPdfPath, int OverlayPdfPageIndex = 0)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | OverlayPdfPath | The background PDF's file path. |
| System.Int32 | OverlayPdfPageIndex | Index (zero-based page number) to copy from the Overlay PDF. |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument object, allowing for a 'fluent' (LINQ like) chained in-line code style |
AddForegroundOverlayPdfToPage(Int32, PdfDocument, Int32)
Adds a foreground overlay to a single page using a PdfDocument. Enables dynamic, page-specific overlays with in-memory PDFs.
// Add dynamic approval stamp:
var approvalStamp = renderer.RenderHtmlAsPdf(
$"<div>Approved by {userName} on {DateTime.Now}</div>");
pdf.AddForegroundOverlayPdfToPage(0, approvalStamp);
// Different overlays from template document:
var overlays = PdfDocument.FromFile("overlays.pdf");
pdf.AddForegroundOverlayPdfToPage(0, overlays, 0) // Header overlay
.AddForegroundOverlayPdfToPage(1, overlays, 1) // Body overlay
.AddForegroundOverlayPdfToPage(2, overlays, 2); // Footer overlay
// Conditional page stamping:
if(needsReview) {
var reviewStamp = CreateReviewStamp();
pdf.AddForegroundOverlayPdfToPage(pageIndex, reviewStamp);
}OverlayPdf can be dynamically generated
Ensure ToPageIndex is valid before applying
See: https://ironpdf.com/how-to/backgrounds-and-overlays/
Declaration
public PdfDocument AddForegroundOverlayPdfToPage(int ToPageIndex, PdfDocument OverlayPdf, int OverlayPdfPageIndex = 0)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | ToPageIndex | Index (zero-based page number) of the page of this PDF to which the foreground will be applied to. |
| PdfDocument | OverlayPdf | The overlay PDF as a PdfDocument. |
| System.Int32 | OverlayPdfPageIndex | Index (zero-based page number) to copy from the Overlay PDF. |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument object, allowing for a 'fluent' (LINQ like) chained in-line code style |
AddForegroundOverlayPdfToPage(Int32, String, Int32)
Adds a foreground overlay to a single page from a file. Ideal for page-specific stamps, signatures, or annotations.
// Add signature to last page:
int lastPage = pdf.PageCount - 1;
pdf.AddForegroundOverlayPdfToPage(lastPage, "signature.pdf");
// Add "VOID" stamp to specific page:
pdf.AddForegroundOverlayPdfToPage(3, "void_stamp.pdf");
// Chain multiple page-specific overlays:
pdf.AddForegroundOverlayPdfToPage(0, "page1_overlay.pdf")
.AddForegroundOverlayPdfToPage(5, "page6_overlay.pdf")
.AddForegroundOverlayPdfToPage(10, "page11_overlay.pdf");Perfect for adding stamps to specific pages
Overlay scales to fit target page dimensions
See: https://ironpdf.com/how-to/backgrounds-and-overlays/
Declaration
public PdfDocument AddForegroundOverlayPdfToPage(int ToPageIndex, string OverlayPdfPath, int OverlayPdfPageIndex = 0)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | ToPageIndex | Index (zero-based page number) of the page of this PDF to which the foreground will be applied to. |
| System.String | OverlayPdfPath | The overlay PDF path. |
| System.Int32 | OverlayPdfPageIndex | Index (zero-based page number) to copy from the Overlay PDF. |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument object, allowing for a 'fluent' (LINQ like) chained in-line code style |
AddForegroundOverlayPdfToPageRange(IEnumerable<Int32>, PdfDocument, Int32)
Declaration
public PdfDocument AddForegroundOverlayPdfToPageRange(IEnumerable<int> ToPageIndexes, PdfDocument OverlayPdf, int OverlayPdfPageIndex = 0)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<System.Int32> | ToPageIndexes | |
| PdfDocument | OverlayPdf | |
| System.Int32 | OverlayPdfPageIndex |
Returns
| Type | Description |
|---|---|
| PdfDocument |
AddForegroundOverlayPdfToPageRange(IEnumerable<Int32>, String, Int32)
Adds foreground overlays to specific pages from a file. Perfect for selective stamping, watermarking, or annotations.
// Add "DRAFT" to even pages only:
var evenPages = Enumerable.Range(0, pdf.PageCount)
.Where(i => i % 2 == 1);
pdf.AddForegroundOverlayPdfToPageRange(evenPages, "draft_overlay.pdf");
// Stamp specific pages with "CONFIDENTIAL":
var confidentialPages = new[] { 2, 5, 8, 11 };
pdf.AddForegroundOverlayPdfToPageRange(
confidentialPages, "confidential.pdf");
// Apply overlays to content pages (skip cover/appendix):
var contentPages = Enumerable.Range(1, pdf.PageCount - 2);
pdf.AddForegroundOverlayPdfToPageRange(
contentPages, "content_overlay.pdf");Null collection applies overlay to all pages
Overlays appear above existing content
See: https://ironpdf.com/how-to/backgrounds-and-overlays/
Declaration
public PdfDocument AddForegroundOverlayPdfToPageRange(IEnumerable<int> ToPageIndexes, string OverlayPdfPath, int OverlayPdfPageIndex = 0)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<System.Int32> | ToPageIndexes | A list of Indexes (zero-based page numbers) of pages in this PDF to which the overlay will be applied to. |
| System.String | OverlayPdfPath | The overlay PDF path. |
| System.Int32 | OverlayPdfPageIndex | Index (zero-based page number) to copy from the Overlay PDF. |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument object, allowing for a 'fluent' (LINQ like) chained in-line code style |
AddForegroundOverlayPdfToPageRange(Int32, Int32, PdfDocument, Int32)
Adds foreground overlays to a page range using a PdfDocument. Optimal for applying dynamic overlays to sequential pages.
// Add timestamp overlay to all content pages:
var timestamp = renderer.RenderHtmlAsPdf(
$"<footer>Generated: {DateTime.Now}</footer>");
pdf.AddForegroundOverlayPdfToPageRange(
0, pdf.PageCount - 1, timestamp);
// Progressive page numbering:
var pageNumbers = GeneratePageNumberOverlay();
pdf.AddForegroundOverlayPdfToPageRange(
5, 50, pageNumbers);
// Apply security classification overlay:
var classification = renderer.RenderHtmlAsPdf(@"
<div style='color:red; position:absolute; top:0'>
CLASSIFIED - INTERNAL USE ONLY
</div>");
pdf.AddForegroundOverlayPdfToPageRange(
0, pdf.PageCount - 1, classification);
// Chapter-specific overlays:
foreach(var chapter in chapters) {
var chapterOverlay = CreateChapterOverlay(chapter.Title);
pdf.AddForegroundOverlayPdfToPageRange(
chapter.StartPage, chapter.EndPage, chapterOverlay);
}Method chains for multiple overlays
Verify page indices are within document bounds
See: https://ironpdf.com/how-to/backgrounds-and-overlays/
Declaration
public PdfDocument AddForegroundOverlayPdfToPageRange(int StartPageIndex, int EndPageIndex, PdfDocument OverlayPdf, int OverlayPdfPageIndex = 0)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | StartPageIndex | First index (zero-based page number) to start adding overlays to . |
| System.Int32 | EndPageIndex | Last index (zero-based page number) to end adding overlays to. |
| PdfDocument | OverlayPdf | The overlay PDF as a PdfDocument. |
| System.Int32 | OverlayPdfPageIndex | Index (zero-based page number) to copy from the Overlay PDF. |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument object, allowing for a 'fluent' (LINQ like) chained in-line code style |
AddForegroundOverlayPdfToPageRange(Int32, Int32, String, Int32)
Declaration
public PdfDocument AddForegroundOverlayPdfToPageRange(int StartPageIndex, int EndPageIndex, string OverlayPdfPath, int OverlayPdfPageIndex = 0)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | StartPageIndex | |
| System.Int32 | EndPageIndex | |
| System.String | OverlayPdfPath | |
| System.Int32 | OverlayPdfPageIndex |
Returns
| Type | Description |
|---|---|
| PdfDocument |
AddHtmlFooters(HtmlHeaderFooter, Double, Double, Double, Int32, IEnumerable<Int32>)
Adds HTML footers with precise margin control for professional layouts. Essential for exact footer positioning and spacing requirements.
// Footer with custom margins for binding:
var footer = new HtmlHeaderFooter {
HtmlFragment = @"
<footer style='background:#f0f0f0; padding:10px'>
<p>Document ID: DOC-2024-001</p>
<p>Page {page} of {total-pages}</p>
</footer>",
Height = 40
};
// Extra left margin for binding
pdf.AddHtmlFooters(footer, 30, 20, 25);
// Responsive footer with margins:
var responsiveFooter = new HtmlHeaderFooter {
HtmlFragment = @"
<div style='display:grid; grid-template-columns:1fr 1fr 1fr'>
<div>{date}</div>
<div style='text-align:center'>Confidential</div>
<div style='text-align:right'>{time}</div>
</div>",
Height = 35
};
pdf.AddHtmlFooters(responsiveFooter, 25, 25, 20, 1);Larger bottom margin prevents content overlap
Total footer height = Height + MarginBottom
See: https://ironpdf.com/how-to/headers-and-footers/
Declaration
public PdfDocument AddHtmlFooters(HtmlHeaderFooter Footer, double MarginLeft, double MarginRight, double MarginBottom, int FirstPageNumber = 1, IEnumerable<int> PageIndexesToAddFootersTo = null)
Parameters
| Type | Name | Description |
|---|---|---|
| HtmlHeaderFooter | Footer | A new instance of IronPdf.HtmlHeaderFooter that defines the footer content and layout. |
| System.Double | MarginLeft | The left margin of the footer on the page in mm. |
| System.Double | MarginRight | The right margin of the footer on the page in mm. |
| System.Double | MarginBottom | The bottom margin of the footer on the page in mm. |
| System.Int32 | FirstPageNumber | Optional. The number of first page for {page} mail-merge. |
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexesToAddFootersTo | Optional. The PageIndexes (zero-based page numbers) to which the footer will be added. |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument object, allowing for a 'fluent' (LINQ like) chained in-line code style |
AddHtmlFooters(HtmlHeaderFooter, Int32, IEnumerable<Int32>)
Adds HTML footers to existing PDF with rich content support. Perfect for complex footer layouts with images, links, and styling.
// Simple HTML footer with page numbers:
var footer = new HtmlHeaderFooter {
HtmlFragment = @"
<div style='text-align:center; font-size:10px'>
Page {page} | © 2024 Company Name
</div>",
Height = 25
};
pdf.AddHtmlFooters(footer);
// Footer with links and social icons:
var richFooter = new HtmlHeaderFooter {
HtmlFragment = @"
<div style='display:flex; justify-content:space-between'>
<a href='https://example.com'>Visit Website</a>
<span>Follow us:
<img src='twitter.png' height='15'/>
<img src='linkedin.png' height='15'/>
</span>
</div>",
Height = 30
};
pdf.AddHtmlFooters(richFooter, 1);
// Add to specific pages only:
var lastPages = Enumerable.Range(pdf.PageCount - 5, 5);
pdf.AddHtmlFooters(footer, 1, lastPages);Use Height property to reserve space for footer
Images must be accessible via file path or URL
See: https://ironpdf.com/how-to/headers-and-footers/
Declaration
public PdfDocument AddHtmlFooters(HtmlHeaderFooter Footer, int FirstPageNumber = 1, IEnumerable<int> PageIndexesToAddFootersTo = null)
Parameters
| Type | Name | Description |
|---|---|---|
| HtmlHeaderFooter | Footer | A new instance of IronPdf.HtmlHeaderFooter that defines the footer content and layout. |
| System.Int32 | FirstPageNumber | Optional. The number of first page for {page} mail-merge. |
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexesToAddFootersTo | Optional. The PageIndexes (zero-based page numbers) to which the footer will be added. |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument object, allowing for a 'fluent' (LINQ like) chained in-line code style |
AddHtmlHeaders(HtmlHeaderFooter, Double, Double, Double, Int32, IEnumerable<Int32>)
Adds HTML headers with custom margins for precise layout control. Perfect for professional documents with strict formatting requirements.
// Elegant header with custom margins:
var header = new HtmlHeaderFooter {
HtmlFragment = @"
<div style='background:linear-gradient(to right,#667eea,#764ba2);
color:white; padding:20px; border-radius:5px'>
<h1>Premium Report</h1>
<p>Quarterly Analysis Q4 2024</p>
</div>",
Height = 80
};
// Wide margins for premium look
pdf.AddHtmlHeaders(header, 30, 30, 35);
// Technical document header:
var techHeader = new HtmlHeaderFooter {
HtmlFragment = @"
<table style='width:100%; font-size:10px'>
<tr>
<td>Doc: API-REF-2024</td>
<td style='text-align:center'>Version 3.2</td>
<td style='text-align:right'>{page}/{total-pages}</td>
</tr>
</table>",
Height = 30
};
// Tight margins for technical docs
pdf.AddHtmlHeaders(techHeader, 15, 15, 10, 1);
// Different margins for landscape orientation:
var landscapeHeader = new HtmlHeaderFooter {
HtmlFragment = "<h3>Wide Format Report</h3>",
Height = 35
};
pdf.AddHtmlHeaders(landscapeHeader, 50, 50, 25, 1, landscapePages);Adjust margins based on page orientation and size
Large top margins may push content down significantly
See: https://ironpdf.com/how-to/headers-and-footers/
Declaration
public PdfDocument AddHtmlHeaders(HtmlHeaderFooter Header, double MarginLeft, double MarginRight, double MarginTop, int FirstPageNumber = 1, IEnumerable<int> PageIndexesToAddHeadersTo = null)
Parameters
| Type | Name | Description |
|---|---|---|
| HtmlHeaderFooter | Header | A new instance of IronPdf.HtmlHeaderFooter that defines the header content and layout. |
| System.Double | MarginLeft | The left margin of the header on the page in mm. |
| System.Double | MarginRight | The right margin of the header on the page in mm. |
| System.Double | MarginTop | The top margin of the header on the page in mm. |
| System.Int32 | FirstPageNumber | Optional. The number of first page for {page} mail-merge. |
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexesToAddHeadersTo | Optional. The PageIndexes (zero-based page numbers) to which the header will be added. |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument object, allowing for a 'fluent' (LINQ like) chained in-line code style |
AddHtmlHeaders(HtmlHeaderFooter, Int32, IEnumerable<Int32>)
Adds HTML headers to PDF pages with full web content capabilities. Supports complex layouts, images, CSS, and dynamic content.
// Corporate header with logo:
var header = new HtmlHeaderFooter {
HtmlFragment = @"
<header style='border-bottom:2px solid #007bff'>
<img src='logo.png' height='40' style='float:left'/>
<h1 style='text-align:center'>Annual Report 2024</h1>
</header>",
Height = 60
};
pdf.AddHtmlHeaders(header);
// Dynamic header with JavaScript:
var dynamicHeader = new HtmlHeaderFooter {
HtmlFragment = @"
<div id='header'></div>
<script>
document.getElementById('header').innerHTML =
'Generated: ' + new Date().toLocaleDateString();
</script>",
Height = 30
};
pdf.AddHtmlHeaders(dynamicHeader, 1);
// Chapter-specific headers:
var chapterHeader = new HtmlHeaderFooter {
HtmlFragment = "<h2 style='color:#333'>Chapter 1: Introduction</h2>",
Height = 40
};
var chapterPages = Enumerable.Range(5, 15);
pdf.AddHtmlHeaders(chapterHeader, 1, chapterPages);JavaScript executes during header rendering
External resources must be accessible
See: https://ironpdf.com/how-to/headers-and-footers/
Declaration
public PdfDocument AddHtmlHeaders(HtmlHeaderFooter Header, int FirstPageNumber = 1, IEnumerable<int> PageIndexesToAddHeadersTo = null)
Parameters
| Type | Name | Description |
|---|---|---|
| HtmlHeaderFooter | Header | A new instance of IronPdf.HtmlHeaderFooter that defines the header content and layout. |
| System.Int32 | FirstPageNumber | Optional. The number of first page for {page} mail-merge. |
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexesToAddHeadersTo | Optional. The PageIndexes (zero-based page numbers) to which the header will be added. |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument object, allowing for a 'fluent' (LINQ like) chained in-line code style |
AddHtmlHeadersAndFooters(ChromePdfRenderOptions, IEnumerable<Int32>)
Adds rich HTML headers and footers to existing PDF pages. Enables complex layouts, styling, images, and JavaScript in headers/footers.
// HTML header with logo and styling:
var options = new ChromePdfRenderOptions {
HtmlHeader = new HtmlHeaderFooter {
HtmlFragment = @"
<div style='text-align:center'>
<img src='logo.png' height='30'/>
<h2>Company Report</h2>
</div>",
Height = 50
},
HtmlFooter = new HtmlHeaderFooter {
HtmlFragment = @"
<div style='border-top:1px solid #ccc; padding:5px'>
<span>Page {page}</span>
<span style='float:right'>© 2024</span>
</div>",
Height = 30
}
};
pdf.AddHtmlHeadersAndFooters(options);
// Add to specific sections:
var sectionOptions = new ChromePdfRenderOptions {
HtmlHeader = new HtmlHeaderFooter {
HtmlFragment = "<h3 style='color:blue'>Section A</h3>",
Height = 25
}
};
var sectionPages = new[] { 10, 11, 12, 13, 14 };
pdf.AddHtmlHeadersAndFooters(sectionOptions, sectionPages);Supports full HTML/CSS including images and JavaScript
Complex HTML may impact performance
See: https://ironpdf.com/how-to/headers-and-footers/
Declaration
public PdfDocument AddHtmlHeadersAndFooters(ChromePdfRenderOptions Options, IEnumerable<int> PageIndexes = null)
Parameters
| Type | Name | Description |
|---|---|---|
| ChromePdfRenderOptions | Options | Render options for the HTML headers and footers |
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexes | Optional list of page indices to apply headers and footers to. Defaults to all pages |
Returns
| Type | Description |
|---|---|
| PdfDocument | Pdf document |
AddTextFooters(TextHeaderFooter, Double, Double, Double, Int32, IEnumerable<Int32>)
Adds text footers to existing PDF with custom margins. Perfect for precise footer positioning and page numbering control.
// Add centered page numbers with margins:
var footer = new TextHeaderFooter {
CenterText = "Page {page} of {total-pages}",
Font = FontTypes.Helvetica,
FontSize = 10
};
pdf.AddTextFooters(footer, 20, 20, 15);
// Add footer with document info:
var infoFooter = new TextHeaderFooter {
LeftText = "{date}",
CenterText = "Confidential",
RightText = "{time}"
};
pdf.AddTextFooters(infoFooter, 25, 25, 20, 1);
// Add to specific pages only:
var pageNumbers = new[] { 0, 2, 4, 6 };
pdf.AddTextFooters(footer, 15, 15, 10, 1, pageNumbers);Margins in millimeters for precise control
Performance: Consider using render-time headers for better speed
See: https://ironpdf.com/how-to/headers-and-footers/
Declaration
public PdfDocument AddTextFooters(TextHeaderFooter Footer, double MarginLeft, double MarginRight, double MarginBottom, int FirstPageNumber = 1, IEnumerable<int> PageIndexesToAddFootersTo = null)
Parameters
| Type | Name | Description |
|---|---|---|
| TextHeaderFooter | Footer | A new instance of IronPdf.SimpleHeaderFooter that defines the footer content and layout. |
| System.Double | MarginLeft | The left margin of the footer on the page in mm. |
| System.Double | MarginRight | The right margin of the footer on the page in mm. |
| System.Double | MarginBottom | The bottom margin of the footer on the page in mm. |
| System.Int32 | FirstPageNumber | Optional. The number of first page for {page} mail-merge. |
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexesToAddFootersTo | Optional. The PageIndexes (zero-based page numbers) to which the footer will be added. |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument object, allowing for a 'fluent' (LINQ like) chained in-line code style |
AddTextFooters(TextHeaderFooter, Int32, IEnumerable<Int32>)
Adds text footers to existing PDF pages (POST-RENDER method). For FASTER performance, use ChromePdfRenderOptions.TextFooter at render-time!
// Add page numbers after merging:
var footer = new TextHeaderFooter {
CenterText = "Page {page} of {total-pages}"
};
pdf.AddTextFooters(footer);TIP: Use ReplaceText() for custom page numbering after merging!
See: https://ironpdf.com/how-to/headers-and-footers/
Declaration
public PdfDocument AddTextFooters(TextHeaderFooter Footer, int FirstPageNumber = 1, IEnumerable<int> PageIndexesToAddFootersTo = null)
Parameters
| Type | Name | Description |
|---|---|---|
| TextHeaderFooter | Footer | Footer content and formatting |
| System.Int32 | FirstPageNumber | Starting page number for {page} merge (default: 1) |
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexesToAddFootersTo | Specific pages to add footer (null = all pages) |
Returns
| Type | Description |
|---|---|
| PdfDocument | This PdfDocument for fluent chaining |
AddTextHeaders(TextHeaderFooter, Double, Double, Double, Int32, IEnumerable<Int32>)
Adds text headers with custom margin control in millimeters. Ideal for precise header positioning and professional document formatting.
// Corporate header with margins:
var header = new TextHeaderFooter {
CenterText = "ACME Corporation",
Font = FontTypes.TimesRoman,
FontSize = 16
};
pdf.AddTextHeaders(header, 25, 25, 20);
// Header with document metadata:
var metaHeader = new TextHeaderFooter {
LeftText = "Rev: 2.1",
CenterText = "{title}",
RightText = "{date}"
};
pdf.AddTextHeaders(metaHeader, 20, 20, 15);
// Different margins for landscape pages:
var wideHeader = new TextHeaderFooter {
CenterText = "Landscape Report"
};
var landscapePages = GetLandscapePageIndices();
pdf.AddTextHeaders(wideHeader, 40, 40, 25, 1, landscapePages);Use larger top margin to avoid overlapping content
Margins are in millimeters (25.4mm = 1 inch)
See: https://ironpdf.com/how-to/headers-and-footers/
Declaration
public PdfDocument AddTextHeaders(TextHeaderFooter Header, double MarginLeft, double MarginRight, double MarginTop, int FirstPageNumber = 1, IEnumerable<int> PageIndexesToAddHeadersTo = null)
Parameters
| Type | Name | Description |
|---|---|---|
| TextHeaderFooter | Header | A new instance of IronPdf.SimpleHeaderFooter that defines the header content and layout. |
| System.Double | MarginLeft | The left margin of the header on the page in mm. |
| System.Double | MarginRight | The right margin of the header on the page in mm. |
| System.Double | MarginTop | The top margin of the header on the page in mm. |
| System.Int32 | FirstPageNumber | Optional. The number of first page for {page} mail-merge. |
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexesToAddHeadersTo | Optional. The PageIndexes (zero-based page numbers) to which the header will be added. |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument object, allowing for a 'fluent' (LINQ like) chained in-line code style |
AddTextHeaders(TextHeaderFooter, Int32, IEnumerable<Int32>)
Adds text headers to existing PDF pages (POST-RENDER method). Essential for adding document titles, dates, and page information after PDF creation.
// Add simple header with title:
var header = new TextHeaderFooter {
CenterText = "Annual Report 2024",
Font = FontTypes.Arial,
FontSize = 14
};
pdf.AddTextHeaders(header);
// Add header with merge fields:
var dynamicHeader = new TextHeaderFooter {
LeftText = "{date}",
CenterText = "{title}",
RightText = "Page {page}"
};
pdf.AddTextHeaders(dynamicHeader, 1);
// Add headers to specific pages:
var contentPages = Enumerable.Range(1, pdf.PageCount - 1);
pdf.AddTextHeaders(header, 1, contentPages);Supports merge fields: {page}, {total-pages}, {date}, {time}, {title}
For better performance, set headers at render-time with ChromePdfRenderOptions
See: https://ironpdf.com/how-to/headers-and-footers/
Declaration
public PdfDocument AddTextHeaders(TextHeaderFooter Header, int FirstPageNumber = 1, IEnumerable<int> PageIndexesToAddHeadersTo = null)
Parameters
| Type | Name | Description |
|---|---|---|
| TextHeaderFooter | Header | A new instance of IronPdf.TextHeaderFooter that defines the header content and layout. |
| System.Int32 | FirstPageNumber | Optional. The number of first page for {page} mail-merge. |
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexesToAddHeadersTo | Optional. The PageIndexes (zero-based page numbers) to which the header will be added. |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument object, allowing for a 'fluent' (LINQ like) chained in-line code style |
AddTextHeadersAndFooters(ChromePdfRenderOptions, IEnumerable<Int32>)
Adds both text headers and footers using comprehensive render options. Advanced method for complete header/footer customization with full control.
// Complete header and footer setup:
var options = new ChromePdfRenderOptions {
TextHeader = new TextHeaderFooter {
CenterText = "Document Title",
Font = FontTypes.Arial,
FontSize = 14
},
TextFooter = new TextHeaderFooter {
CenterText = "Page {page} of {total-pages}",
FontSize = 10
},
MarginTop = 30,
MarginBottom = 25,
FirstPageNumber = 1
};
pdf.AddTextHeadersAndFooters(options);
// Add to specific pages with custom settings:
var customOptions = new ChromePdfRenderOptions {
TextHeader = new TextHeaderFooter {
LeftText = "Chapter 1",
RightText = "{date}"
},
CssMediaType = PdfCssMediaType.Print
};
var chapterPages = Enumerable.Range(5, 20);
pdf.AddTextHeadersAndFooters(customOptions, chapterPages);Combine with ChromePdfRenderOptions for maximum control
Headers/footers added post-render are slower than render-time
See: https://ironpdf.com/how-to/headers-and-footers/
Declaration
public PdfDocument AddTextHeadersAndFooters(ChromePdfRenderOptions Options, IEnumerable<int> PageIndexes = null)
Parameters
| Type | Name | Description |
|---|---|---|
| ChromePdfRenderOptions | Options | Render options for the text headers and footers |
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexes | Optional list of page indices to apply headers and footers to. Defaults to all pages |
Returns
| Type | Description |
|---|---|
| PdfDocument | Pdf document |
AppendPdf(PdfDocument)
Appends another PDF to the end of the current PdfDocument. Perfect for adding attachments, appendices, or combining documents sequentially. If AnotherPdfFile contains form fields, those fields will be appended with '' in the resulting PDF. e.g. 'Name' will be 'Name'
// Add appendix to report:
var report = PdfDocument.FromFile("annual_report.pdf");
var appendix = PdfDocument.FromFile("appendix.pdf");
report.AppendPdf(appendix);
report.SaveAs("complete_report.pdf");
// Chain multiple appends:
var main = PdfDocument.FromFile("main.pdf");
main.AppendPdf(PdfDocument.FromFile("section1.pdf"))
.AppendPdf(PdfDocument.FromFile("section2.pdf"))
.AppendPdf(PdfDocument.FromFile("section3.pdf"))
.SaveAs("complete_document.pdf");
// Add cover letter to invoice:
var invoice = renderer.RenderHtmlAsPdf(invoiceHtml);
var coverLetter = PdfDocument.FromFile("cover_letter.pdf");
invoice.AppendPdf(coverLetter);Returns this for method chaining
Form fields renamed to avoid conflicts (Name→Name_)
Declaration
public PdfDocument AppendPdf(PdfDocument AnotherPdfFile)
Parameters
| Type | Name | Description |
|---|---|---|
| PdfDocument | AnotherPdfFile | PdfDocument to append. |
Returns
| Type | Description |
|---|---|
| PdfDocument | A new PdfDocument |
ApplyMultipleStamps(IEnumerable<Stamper>, IEnumerable<Int32>)
Declaration
public PdfDocument ApplyMultipleStamps(IEnumerable<Stamper> Stampers, IEnumerable<int> PageIndexesToStamp = null)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<Stamper> | Stampers | A list of Stamper objects, each with their own HTML stamp, to all be stamped onto the PDF. |
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexesToStamp | The page indexes (zero-based page number) to apply the stamps to. |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument, allowing for a 'fluent' (LINQ like) chained in-line code style |
Remarks
Note: This method combines all the provided Stamper objects into a single composite stamp before applying it to each page. As a result, the final stamp appearance may differ slightly from the ApplyStamp(Stamper) method, which applies a single stamp at a time per page. Additionally, this method is generally faster than applying stamps one by one using ApplyStamp(Stamper) as it reduces multiple renderings and page processing operations.
If the stamp appears to be behind some elements in your PDF such as another stamp created by a third party tool, please try Flatten(IEnumerable<Int32>) before applying the stamp.
ApplyMultipleStamps(IEnumerable<Stamper>, Int32)
Declaration
public PdfDocument ApplyMultipleStamps(IEnumerable<Stamper> Stampers, int PageIndexToStamp)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<Stamper> | Stampers | A list of Stamper objects, each with their own HTML stamp, to all be stamped onto the PDF. |
| System.Int32 | PageIndexToStamp | The page index (zero-based page number) to apply the stamps to. |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument, allowing for a 'fluent' (LINQ like) chained in-line code style |
Remarks
Note: This method combines all the provided Stamper objects into a single composite stamp before applying it to each page. As a result, the final stamp appearance may differ slightly from the ApplyStamp(Stamper) method, which applies a single stamp at a time per page. Additionally, this method is generally faster than applying stamps one by one using ApplyStamp(Stamper) as it reduces multiple renderings and page processing operations.
If the stamp appears to be behind some elements in your PDF such as another stamp created by a third party tool, please try Flatten(IEnumerable<Int32>) before applying the stamp.
ApplyMultipleStampsAsync(IEnumerable<Stamper>)
Declaration
public Task<PdfDocument> ApplyMultipleStampsAsync(IEnumerable<Stamper> Stampers)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<Stamper> | Stampers | A list of Stamper objects, each with their own HTML stamp, to all be stamped onto the PDF. |
Returns
| Type | Description |
|---|---|
| System.Threading.Tasks.Task<PdfDocument> | Returns this PdfDocument, allowing for a 'fluent' (LINQ like) chained in-line code style |
Remarks
Note: This method combines all the provided Stamper objects into a single composite stamp before applying it to each page. As a result, the final stamp appearance may differ slightly from the ApplyStamp(Stamper) method, which applies a single stamp at a time per page. Additionally, this method is generally faster than applying stamps one by one using ApplyStamp(Stamper) as it reduces multiple renderings and page processing operations.
If the stamp appears to be behind some elements in your PDF such as another stamp created by a third party tool, please try Flatten(IEnumerable<Int32>) before applying the stamp.
ApplyMultipleStampsAsync(IEnumerable<Stamper>, IEnumerable<Int32>)
Declaration
public Task<PdfDocument> ApplyMultipleStampsAsync(IEnumerable<Stamper> Stampers, IEnumerable<int> PageIndexesToStamp)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<Stamper> | Stampers | A list of Stamper objects, each with their own HTML stamp, to all be stamped onto the PDF. |
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexesToStamp | The page indexes (zero-based page number) to apply the stamps to. |
Returns
| Type | Description |
|---|---|
| System.Threading.Tasks.Task<PdfDocument> | Returns this PdfDocument, allowing for a 'fluent' (LINQ like) chained in-line code style |
Remarks
Note: This method combines all the provided Stamper objects into a single composite stamp before applying it to each page. As a result, the final stamp appearance may differ slightly from the ApplyStamp(Stamper) method, which applies a single stamp at a time per page. Additionally, this method is generally faster than applying stamps one by one using ApplyStamp(Stamper) as it reduces multiple renderings and page processing operations.
If the stamp appears to be behind some elements in your PDF such as another stamp created by a third party tool, please try Flatten(IEnumerable<Int32>) before applying the stamp.
ApplyMultipleStampsAsync(IEnumerable<Stamper>, Int32)
Declaration
public Task<PdfDocument> ApplyMultipleStampsAsync(IEnumerable<Stamper> Stampers, int PageIndexToStamp)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<Stamper> | Stampers | A list of Stamper objects, each with their own HTML stamp, to all be stamped onto the PDF. |
| System.Int32 | PageIndexToStamp | The page index (zero-based page number) to apply the stamps to. |
Returns
| Type | Description |
|---|---|
| System.Threading.Tasks.Task<PdfDocument> | Returns this PdfDocument, allowing for a 'fluent' (LINQ like) chained in-line code style |
Remarks
Note: This method combines all the provided Stamper objects into a single composite stamp before applying it to each page. As a result, the final stamp appearance may differ slightly from the ApplyStamp(Stamper) method, which applies a single stamp at a time per page. Additionally, this method is generally faster than applying stamps one by one using ApplyStamp(Stamper) as it reduces multiple renderings and page processing operations.
If the stamp appears to be behind some elements in your PDF such as another stamp created by a third party tool, please try Flatten(IEnumerable<Int32>) before applying the stamp.
ApplyStamp(Stamper)
Edits the PDF by applying the Stamper's rendered Html to every page. Add headers, footers, watermarks, page numbers, or any HTML content to existing PDFs.
// Add page numbers to every page:
var pdf = PdfDocument.FromFile("report.pdf");
var footer = new HtmlStamper("<div>Page {page} of {total}</div>") {
VerticalAlignment = VerticalAlignment.Bottom,
HorizontalAlignment = HorizontalAlignment.Center,
FontFamily = "Arial",
FontSize = 10
};
pdf.ApplyStamp(footer);
// Add watermark to all pages:
var watermark = new TextStamper("CONFIDENTIAL") {
Opacity = 30,
Rotation = 45,
FontSize = 60,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Middle
};
pdf.ApplyStamp(watermark);
// Add company logo header:
var header = new HtmlStamper(@"
<img src='logo.png' width='100'/>
<h3>Company Report 2025</h3>") {
VerticalAlignment = VerticalAlignment.Top,
HorizontalOffset = new Length(20, MeasurementUnit.Millimeter)
};
pdf.ApplyStamp(header).SaveAs("branded_report.pdf");Supports HTML/CSS for rich formatting
{page} and {total} placeholders auto-replaced
Declaration
public PdfDocument ApplyStamp(Stamper Stamper)
Parameters
| Type | Name | Description |
|---|---|---|
| Stamper | Stamper | The Stamper object that has the HTML to be stamped onto the PDF. |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument, allowing for a 'fluent' (LINQ like) chained in-line code style |
Remarks
If the stamp appears to be behind some elements in your PDF such as another stamp created by a third party tool, please try Flatten(IEnumerable<Int32>) before applying the stamp.
ApplyStamp(Stamper, IEnumerable<Int32>)
Applies a stamp to multiple specific pages of the PDF. Ideal for selective watermarking, batch annotations, or conditional stamping.
// Add "DRAFT" to odd pages only:
var oddPages = Enumerable.Range(0, pdf.PageCount)
.Where(i => i % 2 == 0);
var draft = new TextStamper("DRAFT") {
Opacity = 25,
Rotation = -45,
FontSize = 100,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Middle
};
pdf.ApplyStamp(draft, oddPages);
// Add page numbers to specific section:
var contentPages = Enumerable.Range(5, 20); // Pages 6-25
var pageNumbers = new HtmlStamper(
"<div style='text-align:center'>{page}</div>") {
VerticalAlignment = VerticalAlignment.Bottom
};
pdf.ApplyStamp(pageNumbers, contentPages);
// Apply different stamps to different page sets:
var confidentialPages = new[] { 0, 1, 2 };
var publicPages = new[] { 3, 4, 5, 6 };
var confidential = new TextStamper("CONFIDENTIAL") {
FontColor = Color.Red
};
var publicStamp = new TextStamper("PUBLIC") {
FontColor = Color.Green
};
pdf.ApplyStamp(confidential, confidentialPages)
.ApplyStamp(publicStamp, publicPages);Efficient batch stamping for large documents
Same stamp instance applied to all specified pages
See: https://ironpdf.com/how-to/stamping/
Declaration
public PdfDocument ApplyStamp(Stamper Stamper, IEnumerable<int> PageIndexesToStamp)
Parameters
| Type | Name | Description |
|---|---|---|
| Stamper | Stamper | The Stamper object that has the HTML to be stamped onto the PDF. |
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexesToStamp | The list of page indexes (zero-based page number) to apply the stamp to. |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument, allowing for a 'fluent' (LINQ like) chained in-line code style |
ApplyStamp(Stamper, Int32)
Applies a stamp to a single specific page of the PDF. Perfect for page-specific annotations, signatures, or unique identifiers.
// Add "APPROVED" stamp to first page only:
var approved = new TextStamper("APPROVED") {
FontSize = 48,
FontColor = Color.Green,
Opacity = 50,
VerticalAlignment = VerticalAlignment.Top,
HorizontalAlignment = HorizontalAlignment.Right
};
pdf.ApplyStamp(approved, 0); // First page only
// Add signature to last page:
int lastPage = pdf.PageCount - 1;
var signature = new ImageStamper("signature.png") {
Width = new Length(150, MeasurementUnit.Pixel),
Height = new Length(50, MeasurementUnit.Pixel),
VerticalAlignment = VerticalAlignment.Bottom,
VerticalOffset = new Length(100, MeasurementUnit.Pixel)
};
pdf.ApplyStamp(signature, lastPage);
// Add page-specific QR code:
var qrCode = new BarcodeStamper("Page5-ID-12345", BarcodeEncoding.QRCode) {
Width = 100,
Height = 100,
HorizontalAlignment = HorizontalAlignment.Left
};
pdf.ApplyStamp(qrCode, 4); // Page 5 (index 4)Use for unique page identifiers or signatures
Remember: Page 1 = Index 0
See: https://ironpdf.com/how-to/stamping/
Declaration
public PdfDocument ApplyStamp(Stamper Stamper, int PageIndexToStamp)
Parameters
| Type | Name | Description |
|---|---|---|
| Stamper | Stamper | The Stamper object that has the HTML to be stamped onto the PDF. |
| System.Int32 | PageIndexToStamp | The page index (zero-based page number) to apply the stamp to. |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument, allowing for a 'fluent' (LINQ like) chained in-line code style |
Remarks
If the stamp appears to be behind some elements in your PDF such as another stamp created by a third party tool, please try Flatten(IEnumerable<Int32>) before applying the stamp.
ApplyStampAsync(Stamper)
Declaration
public Task<PdfDocument> ApplyStampAsync(Stamper Stamper)
Parameters
| Type | Name | Description |
|---|---|---|
| Stamper | Stamper | The Stamper object that has the HTML to be stamped onto the PDF. |
Returns
| Type | Description |
|---|---|
| System.Threading.Tasks.Task<PdfDocument> | Returns this PdfDocument, allowing for a 'fluent' (LINQ like) chained in-line code style |
Remarks
Please wait for the task to be completed before saving to file!
If the stamp appears to be behind some elements in your PDF such as another stamp created by a third party tool, please try Flatten(IEnumerable<Int32>) before applying the stamp.
ApplyStampAsync(Stamper, IEnumerable<Int32>)
Declaration
public Task<PdfDocument> ApplyStampAsync(Stamper Stamper, IEnumerable<int> PageIndexesToStamp)
Parameters
| Type | Name | Description |
|---|---|---|
| Stamper | Stamper | The Stamper object that has the HTML to be stamped onto the PDF. |
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexesToStamp | The page indexes (zero-based page number) to apply the stamps to. |
Returns
| Type | Description |
|---|---|
| System.Threading.Tasks.Task<PdfDocument> | Returns this PdfDocument, allowing for a 'fluent' (LINQ like) chained in-line code style |
Remarks
Please wait for the task to be completed before saving to file!
If the stamp appears to be behind some elements in your PDF such as another stamp created by a third party tool, please try Flatten(IEnumerable<Int32>) before applying the stamp.
ApplyStampAsync(Stamper, Int32)
Declaration
public Task<PdfDocument> ApplyStampAsync(Stamper Stamper, int PageIndexToStamp)
Parameters
| Type | Name | Description |
|---|---|---|
| Stamper | Stamper | The Stamper object that has the HTML to be stamped onto the PDF. |
| System.Int32 | PageIndexToStamp | The page index (zero-based page number) to apply the stamp to. |
Returns
| Type | Description |
|---|---|
| System.Threading.Tasks.Task<PdfDocument> | Returns this PdfDocument, allowing for a 'fluent' (LINQ like) chained in-line code style |
Remarks
Please wait for the task to be completed before saving to file!
If the stamp appears to be behind some elements in your PDF such as another stamp created by a third party tool, please try Flatten(IEnumerable<Int32>) before applying the stamp.
ApplyWatermark(String, Int32, VerticalAlignment, HorizontalAlignment)
Adds Watermark to PDF, Please use ApplyStamp(Stamper) for more control. Quick method to add transparent text or HTML watermarks across all pages.
// Simple text watermark:
var pdf = PdfDocument.FromFile("document.pdf");
pdf.ApplyWatermark("DRAFT", 30);
// HTML watermark with styling:
pdf.ApplyWatermark(@"
<div style='color: red; font-size: 72px;'>
CONFIDENTIAL
</div>",
opacity: 25);
// Company watermark bottom-right:
pdf.ApplyWatermark(
"© 2025 Company Name",
opacity: 40,
verticalAlignment: VerticalAlignment.Bottom,
horizontalAlignment: HorizontalAlignment.Right);
// Centered logo watermark:
pdf.ApplyWatermark(
"<img src='watermark.png' width='300'/>",
opacity: 15);Use low opacity (15-30) for subtle watermarks
For rotated watermarks, use overload with rotation parameter
For more information and a code example please visit: https://ironpdf.com/tutorials/csharp-edit-pdf-complete-tutorial/#add-a-watermark-to-a-pdf
Declaration
public PdfDocument ApplyWatermark(string html, int opacity = 50, VerticalAlignment verticalAlignment, HorizontalAlignment horizontalAlignment)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | html | The HTML fragment which will be stamped onto your PDF. |
| System.Int32 | opacity | Watermark transparent value. 0 is invisible, 100 if fully opaque. |
| VerticalAlignment | verticalAlignment | The vertical alignment of the watermark relative to the page. |
| HorizontalAlignment | horizontalAlignment | The horizontal alignment of the watermark relative to the page. |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument, allowing for a 'fluent' (LINQ like) chained in-line code style |
ApplyWatermark(String, Int32, Int32, VerticalAlignment, HorizontalAlignment)
Adds Watermark to PDF, Please use ApplyStamp(Stamper) for more control.
For more information and a code example please visit: https://ironpdf.com/tutorials/csharp-edit-pdf-complete-tutorial/#add-a-watermark-to-a-pdf
Declaration
public PdfDocument ApplyWatermark(string html, int rotation, int opacity = 50, VerticalAlignment verticalAlignment, HorizontalAlignment horizontalAlignment)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | html | The HTML fragment which will be stamped onto your PDF. |
| System.Int32 | rotation | Rotates the watermark clockwise from 0 to 360 degrees as specified. |
| System.Int32 | opacity | Watermark transparent value. 0 is invisible, 100 if fully opaque. |
| VerticalAlignment | verticalAlignment | The vertical alignment of the watermark relative to the page. |
| HorizontalAlignment | horizontalAlignment | The horizontal alignment of the watermark relative to the page. |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument, allowing for a 'fluent' (LINQ like) chained in-line code style |
CombinePages(Double, Double, Int32, Int32, Boolean)
Combine all pages of this document into a NEW document with the pages organized into a grid of columns and rows. Create thumbnail sheets, contact sheets, or n-up printing layouts (2-up, 4-up, etc).
// Create 2x2 thumbnail sheet (4 pages per sheet):
var pdf = PdfDocument.FromFile("presentation.pdf");
var thumbnails = pdf.CombinePages(
NewWidth: 210, // A4 width in mm
NewHeight: 297, // A4 height in mm
Columns: 2,
Rows: 2,
DrawBorders: true);
thumbnails.SaveAs("thumbnail_sheet.pdf");
// Create contact sheet (3x3 grid):
var photos = PdfDocument.FromFile("photo_album.pdf");
var contactSheet = photos.CombinePages(297, 420, 3, 3, true); // A3 size
// Create handout with 2 slides per page:
var slides = PdfDocument.FromFile("slides.pdf");
var handout = slides.CombinePages(210, 297, 1, 2, false);
// Create poster from pages (2x3 grid on large format):
var poster = pdf.CombinePages(600, 900, 2, 3, false);Perfect for creating handouts, proofs, or overview sheets
Dimensions in millimeters (A4 = 210x297mm)
Pages are scaled to fit grid cells
Declaration
public PdfDocument CombinePages(double NewWidth, double NewHeight, int Columns, int Rows, bool DrawBorders = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Double | NewWidth | Width of the new document, in millimeters |
| System.Double | NewHeight | Height of the new document, in millimeters |
| System.Int32 | Columns | Number of columns-per-page in the new document |
| System.Int32 | Rows | Number of rows-per-page in the new document |
| System.Boolean | DrawBorders | Draw borders around each individual page |
Returns
| Type | Description |
|---|---|
| PdfDocument | New document with the specified number of columns and rows per page |
Compress(CompressionOptions)
Compresses PDF document to reduce file size while maintaining readability. Combines multiple optimization techniques for maximum size reduction.
// Basic compression with defaults:
pdf.Compress();
var sizeBefore = new FileInfo("original.pdf").Length;
pdf.SaveAs("compressed.pdf");
var sizeAfter = new FileInfo("compressed.pdf").Length;
Console.WriteLine($"Reduced by {(1 - sizeAfter/sizeBefore)*100:F1}%");
// Aggressive compression for email/storage:
pdf.Compress(new CompressionOptions {
CompressImages = true,
JpegQuality = 60,
ShrinkImages = true,
RemoveStructureTree = true,
HighQualityImageSubsampling = false
});
// Balanced compression preserving quality:
pdf.Compress(new CompressionOptions {
CompressImages = true,
JpegQuality = 85,
ShrinkImages = false,
RemoveStructureTree = false
});Can reduce file size by 50-90% depending on content
RemoveStructureTree may affect text selection in complex documents
See: https://ironpdf.com/how-to/compress-pdf/
Declaration
public void Compress(CompressionOptions Options = null)
Parameters
| Type | Name | Description |
|---|---|---|
| CompressionOptions | Options | Compression options. See CompressionOptions |
Remarks
This method is deprecated and will be removed in a future version.
Please migrate to
Compression can drastically reduce the size of a document by removing unused features or by reducing quality.
CompressAndSaveAs(Byte[], String, Nullable<Int32>, String, Boolean)
Create a compressed file from pdf byte array.
------------------------------------------------
Usage:
PdfDocument.CompressAndSaveAs(pdfBytes, "my-pdf-file-compressed.pdf", 90, "");
------------------------------------------------
Declaration
public static void CompressAndSaveAs(byte[] PdfBytes, string OutputPath, Nullable<int> JpegQuality = null, string Password = "", bool CompressStructTree = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Byte[] | PdfBytes | byte arrray of the Pdf file |
| System.String | OutputPath | Path of the file where it will be saved in file system |
| System.Nullable<System.Int32> | JpegQuality | Optional JPEG compression quality (0-100). If null, uses default compression. |
| System.String | Password | password to open the file |
| System.Boolean | CompressStructTree | If true, removes the document structure tree to reduce file size. Default is false. |
Remarks
Important Notes:
Performance: This method is highly performant.
Security: Always validate file paths to prevent directory traversal vulnerabilities.
Related Documentation:
How-To Guide: Getting Started with PDF Compression
API Reference: Full API Documentation
Exceptions
| Type | Condition |
|---|---|
| System.ArgumentException | Thrown when the PdfBytes array is null or empty. |
| System.ArgumentException | Thrown when the OutputPath is null, empty, or whitespace. |
CompressAndSaveAs(Stream, String, Nullable<Int32>, String, Boolean)
Create a compressed file from pdf stream.
------------------------------------------------
Usage:
PdfDocument.CompressAndSaveAs(pdfStream, "my-pdf-file-compressed.pdf", 90, "mypassword");
------------------------------------------------
Declaration
public static void CompressAndSaveAs(Stream Stream, string OutputPath, Nullable<int> JpegQuality = null, string Password = "", bool CompressStructTree = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.IO.Stream | Stream | Stream of the PDF file |
| System.String | OutputPath | Path of the file where it will be saved in file system |
| System.Nullable<System.Int32> | JpegQuality | Optional JPEG compression quality (0-100). If null, uses default compression. |
| System.String | Password | password to open the file |
| System.Boolean | CompressStructTree | If true, removes the document structure tree to reduce file size. Default is false. |
Remarks
Important Notes:
Performance: This method is highly performant.
Security: Always validate file paths to prevent directory traversal vulnerabilities.
Related Documentation:
How-To Guide: Getting Started with PDF Compression
API Reference: Full API Documentation
Exceptions
| Type | Condition |
|---|---|
| System.ArgumentNullException | Thrown when the input Stream is null. |
| System.ArgumentException | Thrown when the input Stream is not readable. |
| System.ArgumentException | Thrown when the OutputPath is null, empty, or whitespace. |
CompressAndSaveAs(String, Nullable<Int32>, Boolean)
Create a compressed file from the current pdf document.
------------------------------------------------
Usage:
pdf.CompressAndSaveAs("my-pdf-file-compressed.pdf", 90);
------------------------------------------------
Declaration
public void CompressAndSaveAs(string OutputPath, Nullable<int> JpegQuality = null, bool CompressStructTree = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | OutputPath | Path of the file where it will be saved in file system. |
| System.Nullable<System.Int32> | JpegQuality | Optional JPEG compression quality (0-100). If null, uses default compression. |
| System.Boolean | CompressStructTree | If true, removes the document structure tree to reduce file size. Default is false. |
Remarks
Important Notes:
Performance: This method is highly performant.
Security: Always validate file paths to prevent directory traversal vulnerabilities.
Related Documentation:
How-To Guide: Getting Started with PDF Compression
API Reference: Full API Documentation
Exceptions
| Type | Condition |
|---|---|
| System.ArgumentException | Thrown when the OutputPath is null, empty, or whitespace. |
CompressImages(Int32, Boolean, Boolean)
Compresses existing images in PDF using JPEG encoding with fine-tuned control. Ideal for optimizing PDFs with many or large images while controlling quality.
// High quality for print (minimal compression):
pdf.CompressImages(95, false, true);
pdf.SaveAs("print-quality.pdf");
// Balanced for web viewing:
pdf.CompressImages(75, true, true);
pdf.SaveAs("web-optimized.pdf");
// Maximum compression for email:
pdf.CompressImages(50, true, false);
pdf.SaveAs("email-size.pdf");
// Archive storage (good quality, smaller size):
pdf.CompressImages(80, true, false);
// Photo-heavy PDF optimization:
var photoAlbum = PdfDocument.FromFile("vacation-photos.pdf");
photoAlbum.CompressImages(70, true, true);
photoAlbum.SaveAs("vacation-compressed.pdf");Quality 60-80 offers best size/quality balance
ShrinkImage=true can dramatically reduce file size but may blur text in images
See: https://ironpdf.com/how-to/compress-pdf/
Declaration
public void CompressImages(int Quality, bool ShrinkImage = true, bool HighQualitySubsampling = true)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | Quality | Quality (1 - 100) to use during compression |
| System.Boolean | ShrinkImage | Scale down the image resolution according to its visible size in the PDF document. This will drastically reduce the size and quality of the images. |
| System.Boolean | HighQualitySubsampling | True to use 444 chroma subsampling for a higher quality image. False to use 411 chrome subsampling to further reduce the image size. |
Remarks
This method is deprecated and will be removed in a future version.
Please migrate to
Exceptions
| Type | Condition |
|---|---|
| System.ArgumentOutOfRangeException | Argument out of range |
CompressPdfToBytes(Byte[], Nullable<Int32>, String, Boolean, CompressionMode)
Compresses a PDF byte array and returns the result as a byte array.
Static method for compressing PDFs without creating a PdfDocument instance.
------------------------------------------------
Usage:byte[] compressed = PdfDocument.CompressPdfToBytes(pdfBytes, jpegQuality: 85);
------------------------------------------------
Declaration
public static byte[] CompressPdfToBytes(byte[] PdfBytes, Nullable<int> JpegQuality = null, string Password = "", bool CompressStructTree = false, CompressionMode mode)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Byte[] | PdfBytes | Byte array containing the PDF data. |
| System.Nullable<System.Int32> | JpegQuality | Optional JPEG compression quality (1-100). Only applies if mode supports image optimization. |
| System.String | Password | Password to decrypt the PDF if encrypted. |
| System.Boolean | CompressStructTree | If true, removes the document structure tree to reduce file size. Default is false. |
| CompressionMode | mode | Compression strategy. Defaults to Automatic. |
Returns
| Type | Description |
|---|---|
| System.Byte[] | Compressed PDF as byte array. |
Remarks
When to Use:
Use this static method when you have PDF data as bytes and don't need a full PdfDocument object.
Related Documentation:
How-To Guide: Getting Started with PDF Compression
Exceptions
| Type | Condition |
|---|---|
| System.ArgumentException | Thrown when the PdfBytes array is null or empty. |
CompressPdfToBytes(Stream, Nullable<Int32>, String, Boolean, CompressionMode)
Compresses a PDF stream and returns the result as a byte array.
Static method for compressing PDFs from stream input.
------------------------------------------------
Usage:byte[] compressed = PdfDocument.CompressPdfToBytes(pdfStream, jpegQuality: 85);
------------------------------------------------
Declaration
public static byte[] CompressPdfToBytes(Stream PdfStream, Nullable<int> JpegQuality = null, string Password = "", bool CompressStructTree = false, CompressionMode mode)
Parameters
| Type | Name | Description |
|---|---|---|
| System.IO.Stream | PdfStream | Stream containing the PDF data. |
| System.Nullable<System.Int32> | JpegQuality | Optional JPEG compression quality (1-100). Only applies if mode supports image optimization. |
| System.String | Password | Password to decrypt the PDF if encrypted. Default is empty string. |
| System.Boolean | CompressStructTree | If true, removes the document structure tree to reduce file size. Default is false. |
| CompressionMode | mode | Compression strategy. Defaults to Automatic. |
Returns
| Type | Description |
|---|---|
| System.Byte[] | Compressed PDF as byte array. |
Remarks
Important Notes:
Memory: Stream is copied to memory before compression.
Exceptions
| Type | Condition |
|---|---|
| System.ArgumentNullException | Thrown when the input PdfStream is null. |
| System.ArgumentException | Thrown when the input PdfStream is not readable. |
CompressPdfToBytes(Nullable<Int32>, Boolean, CompressionMode)
Compresses the current PDF document and returns the result as a byte array.
Reduces file size while keeping data in memory (no disk I/O).
------------------------------------------------
Usage:byte[] compressed = pdf.CompressPdfToBytes(jpegQuality: 85, mode: CompressionMode.HighQuality);
------------------------------------------------
Declaration
public byte[] CompressPdfToBytes(Nullable<int> JpegQuality = null, bool CompressStructTree = false, CompressionMode mode)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Nullable<System.Int32> | JpegQuality | Optional JPEG compression quality (1-100). Only applies if mode supports image optimization. Lower values = smaller file, lower quality. |
| System.Boolean | CompressStructTree | If true, removes the document structure tree (accessibility metadata) to further reduce file size. Default is false. |
| CompressionMode | mode | Compression strategy. Defaults to Automatic. |
Returns
| Type | Description |
|---|---|
| System.Byte[] | Compressed PDF as byte array. |
Remarks
Compression Modes:
Automatic: Tries HighQuality first, falls back to FastMemory if disk access is restricted.
FastMemory: In-memory compression only (no JPEG optimization, no disk I/O).
HighQuality: Maximum compression with JPEG optimization (requires temporary disk access).
Important Notes:
Memory Usage: Entire PDF is kept in memory. Consider SaveAs methods for very large files.
JPEG Quality: Ignored in FastMemory mode (no image resampling).
Related Documentation:
How-To Guide: Getting Started with PDF Compression
API Reference: Full API Documentation
CompressPdfToStream(Byte[], Nullable<Int32>, String, Boolean, CompressionMode)
Compresses a PDF byte array and returns the result as a Stream.
Static method for compressing PDFs without creating a PdfDocument instance.
------------------------------------------------
Usage:Stream compressed = PdfDocument.CompressPdfToStream(pdfBytes, jpegQuality: 85);
------------------------------------------------
Declaration
public static Stream CompressPdfToStream(byte[] PdfBytes, Nullable<int> JpegQuality = null, string Password = "", bool CompressStructTree = false, CompressionMode mode)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Byte[] | PdfBytes | Byte array containing the PDF data. |
| System.Nullable<System.Int32> | JpegQuality | Optional JPEG compression quality (1-100). Only applies if mode supports image optimization. |
| System.String | Password | Password to decrypt the PDF if encrypted. |
| System.Boolean | CompressStructTree | If true, removes the document structure tree to reduce file size. Default is false. |
| CompressionMode | mode | Compression strategy. Defaults to Automatic. |
Returns
| Type | Description |
|---|---|
| System.IO.Stream | Compressed PDF as MemoryStream. |
Exceptions
| Type | Condition |
|---|---|
| System.ArgumentException | Thrown when the PdfBytes array is null or empty. |
CompressPdfToStream(Stream, Nullable<Int32>, String, Boolean, CompressionMode)
Compresses a PDF stream and returns the result as a Stream.
Static method for compressing PDFs from stream input.
------------------------------------------------
Usage:Stream compressed = PdfDocument.CompressPdfToStream(pdfStream, jpegQuality: 85);
------------------------------------------------
Declaration
public static Stream CompressPdfToStream(Stream PdfStream, Nullable<int> JpegQuality = null, string Password = "", bool CompressStructTree = false, CompressionMode mode)
Parameters
| Type | Name | Description |
|---|---|---|
| System.IO.Stream | PdfStream | Stream containing the PDF data. |
| System.Nullable<System.Int32> | JpegQuality | Optional JPEG compression quality (1-100). Only applies if mode supports image optimization. |
| System.String | Password | Password to decrypt the PDF if encrypted. Default is empty string. |
| System.Boolean | CompressStructTree | If true, removes the document structure tree to reduce file size. Default is false. |
| CompressionMode | mode | Compression strategy. Defaults to Automatic. |
Returns
| Type | Description |
|---|---|
| System.IO.Stream | Compressed PDF as MemoryStream. |
Exceptions
| Type | Condition |
|---|---|
| System.ArgumentNullException | Thrown when the input PdfStream is null. |
| System.ArgumentException | Thrown when the input PdfStream is not readable. |
CompressPdfToStream(Nullable<Int32>, Boolean, CompressionMode)
Compresses the current PDF document and returns the result as a Stream.
Reduces file size while keeping data in memory (no disk I/O).
------------------------------------------------
Usage:Stream compressed = pdf.CompressPdfToStream(jpegQuality: 85);
------------------------------------------------
Declaration
public Stream CompressPdfToStream(Nullable<int> JpegQuality = null, bool CompressStructTree = false, CompressionMode mode)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Nullable<System.Int32> | JpegQuality | Optional JPEG compression quality (1-100). Only applies if mode supports image optimization. |
| System.Boolean | CompressStructTree | If true, removes the document structure tree to reduce file size. Default is false. |
| CompressionMode | mode | Compression strategy. Defaults to Automatic. |
Returns
| Type | Description |
|---|---|
| System.IO.Stream | Compressed PDF as MemoryStream. |
Remarks
Important Notes:
Memory: Returns MemoryStream backed by byte array. Dispose when done.
Usage: Useful for piping to other stream-based APIs without file I/O.
Related Documentation:
How-To Guide: Getting Started with PDF Compression
CompressStructTree()
Removes document structure tree to significantly reduce file size. Useful for PDFs where accessibility features are not required.
// Remove structure tree from large report:
var report = PdfDocument.FromFile("annual-report.pdf");
var sizeBefore = report.BinaryData.Length;
report.CompressStructTree();
var sizeAfter = report.BinaryData.Length;
Console.WriteLine($"Saved {(sizeBefore - sizeAfter) / 1024}KB");
// Optimize scanned documents (structure tree not needed):
var scanned = PdfDocument.FromFile("scanned-docs.pdf");
scanned.CompressStructTree();
scanned.CompressImages(70);
scanned.SaveAs("optimized-scan.pdf");
// Batch optimize for storage:
foreach(var file in Directory.GetFiles("pdfs", "*.pdf")) {
var pdf = PdfDocument.FromFile(file);
pdf.CompressStructTree();
pdf.SaveAs(file.Replace(".pdf", "_compressed.pdf"));
}Can reduce file size by 10-40% in complex documents
Removes accessibility features and may affect text selection
Not recommended for documents requiring screen reader support
Declaration
public void CompressStructTree()
Remarks
This method is deprecated and will be removed in a future version.
Please migrate to
ConvertToPdfA(PdfAVersions, String)
Converts PDF to PDF/A format for long-term archival compliance. PDF/A ensures documents remain viewable and accessible for decades.
// Convert to PDF/A-3B (most common):
pdf.ConvertToPdfA(PdfAVersions.PdfA3b);
// With custom color profile:
pdf.ConvertToPdfA(PdfAVersions.PdfA2b, "sRGB.icc");PDF/A-3 supports attachments, PDF/A-1 and PDF/A-2 do NOT
See: https://ironpdf.com/how-to/pdfa/
Declaration
public PdfDocument ConvertToPdfA(PdfAVersions PdfAVersion, string CustomICC = null)
Parameters
| Type | Name | Description |
|---|---|---|
| PdfAVersions | PdfAVersion | PDF/A compliance level (default: PdfA3b for attachments support) |
| System.String | CustomICC | Optional custom ICC color profile path |
Returns
| Type | Description |
|---|---|
| PdfDocument | This PdfDocument converted to PDF/A format |
ConvertToPdfA(IEnumerable<EmbedFileByte>, PdfAVersions, String)
Convert the current document into the specified PDF/A standard format with embedded files and selected icc file
Declaration
public PdfDocument ConvertToPdfA(IEnumerable<EmbedFileByte> EmbedFileBytes, PdfAVersions PdfAVersion, string CustomICC = null)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<EmbedFileByte> | EmbedFileBytes | Collection of byte[] and their file type of embedding file with type of that file to the PDF/A document |
| PdfAVersions | PdfAVersion | (Optional) PDF/A compliant version, default is PDF/A-3B (ISO 19005-3) |
| System.String | CustomICC | (Optional) Custom color profile file path |
Returns
| Type | Description |
|---|---|
| PdfDocument | A PDF/A compliant reference to this document with embedded files |
ConvertToPdfA(IEnumerable<EmbedFilePath>, PdfAVersions, String)
Convert the current document into the specified PDF/A standard format with embedded files and selected icc file
Declaration
public PdfDocument ConvertToPdfA(IEnumerable<EmbedFilePath> EmbedFilePaths, PdfAVersions PdfAVersion, string CustomICC = null)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<EmbedFilePath> | EmbedFilePaths | Collection of path to embedding file to the PDF/A document |
| PdfAVersions | PdfAVersion | (Optional) PDF/A compliant version, default is PDF/A-3B (ISO 19005-3) |
| System.String | CustomICC | (Optional) Custom color profile file path |
Returns
| Type | Description |
|---|---|
| PdfDocument | A PDF/A compliant reference to this document with embedded files |
ConvertToPdfA(IEnumerable<EmbedFileStream>, PdfAVersions, String)
Convert the current document into the specified PDF/A standard format with embedded files and selected icc file
Declaration
public PdfDocument ConvertToPdfA(IEnumerable<EmbedFileStream> EmbedFileStreams, PdfAVersions PdfAVersion, string CustomICC = null)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<EmbedFileStream> | EmbedFileStreams | Collection of Stream and their file type of embedding file with type of that file to the PDF/A document |
| PdfAVersions | PdfAVersion | (Optional) PDF/A compliant version, default is PDF/A-3B (ISO 19005-3) |
| System.String | CustomICC | (Optional) Custom color profile file path |
Returns
| Type | Description |
|---|---|
| PdfDocument | A PDF/A compliant reference to this document with embedded files |
ConvertToPdfA(IEnumerable<String>, PdfAVersions, String)
Declaration
public PdfDocument ConvertToPdfA(IEnumerable<string> EmbedFilePaths, PdfAVersions PdfAVersion, string CustomICC = null)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<System.String> | EmbedFilePaths | |
| PdfAVersions | PdfAVersion | |
| System.String | CustomICC |
Returns
| Type | Description |
|---|---|
| PdfDocument |
ConvertToPdfUA(PdfUAVersions, NaturalLanguages)
Converts PDF to PDF/UA format for accessibility compliance (Section 508, W3C WCAG). Ensures documents are accessible to users with disabilities and screen readers.
// Convert to PDF/UA-1:
pdf.ConvertToPdfUA(PdfUAVersions.PdfUA1, NaturalLanguages.English);
// For other languages:
pdf.ConvertToPdfUA(PdfUAVersions.PdfUA1, NaturalLanguages.Spanish);W3C standards compliant for full accessibility
See: https://ironpdf.com/how-to/pdfua/
Declaration
public PdfDocument ConvertToPdfUA(PdfUAVersions PdfUAVersion, NaturalLanguages NaturalLanguage)
Parameters
| Type | Name | Description |
|---|---|---|
| PdfUAVersions | PdfUAVersion | PDF/UA compliance level (default: PdfUA1) |
| NaturalLanguages | NaturalLanguage | Document language for screen readers (default: English) |
Returns
| Type | Description |
|---|---|
| PdfDocument | This PdfDocument converted to accessible PDF/UA format |
Remarks
PDF/UA-2 Limitation: PDF/UA-2 conversion may not work correctly with encrypted PDFs.
CopyPage(Int32, Boolean)
Creates a new PDF document by copying a single page from the current PdfDocument.
------------------------------------------------
Usage:
var newDoc = pdf.CopyPage(0);
------------------------------------------------
Declaration
public PdfDocument CopyPage(int pageIndex, bool copyBookmarks = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | pageIndex | The zero-based index of the page to copy. Note: Page 1 has index 0. |
| System.Boolean | copyBookmarks | A flag indicating whether bookmarks should be preserved in the new PDF. |
Returns
| Type | Description |
|---|---|
| PdfDocument | A new PdfDocument instance containing only the specified page. |
Remarks
Exceptions
| Type | Condition |
|---|---|
| System.ArgumentException | Thrown when |
CopyPages(IEnumerable<Int32>, Boolean)
Creates a new PDF document by copying a specified set of pages from the current PdfDocument.
------------------------------------------------
Usage:
var newDoc = pdf.CopyPages(new[] { 0, 3, 5 });
------------------------------------------------
Declaration
public PdfDocument CopyPages(IEnumerable<int> pageIndexes, bool copyBookmarks = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<System.Int32> | pageIndexes | A sequence of zero-based page indexes identifying which pages to copy into the new PDF. |
| System.Boolean | copyBookmarks | A flag indicating whether bookmarks should be included in the new PDF. |
Returns
| Type | Description |
|---|---|
| PdfDocument | A new PdfDocument containing the copied pages. |
Remarks
Exceptions
| Type | Condition |
|---|---|
| System.ArgumentException | Thrown when |
CopyPages(Int32, Int32, Boolean)
Creates a new PDF document by copying a continuous range of pages from the current PdfDocument.
------------------------------------------------
Usage:
var newDoc = pdf.CopyPages(0, 4);
------------------------------------------------
Declaration
public PdfDocument CopyPages(int startIndex, int endIndex, bool copyBookmarks = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | startIndex | The zero-based index of the first page to copy. Note: Page 1 has index 0. |
| System.Int32 | endIndex | The zero-based index of the last page to copy. Must be greater than or equal to |
| System.Boolean | copyBookmarks | Indicates whether bookmarks should be preserved. |
Returns
| Type | Description |
|---|---|
| PdfDocument | A new PdfDocument containing the specified page range. |
Remarks
Exceptions
| Type | Condition |
|---|---|
| System.ArgumentException | Thrown if |
Dispose()
Releases used resources.
Declaration
public void Dispose()
DrawBitmap(AnyBitmap, IEnumerable<Int32>, IEnumerable<Double>, IEnumerable<Double>, IEnumerable<Double>, IEnumerable<Double>, PixelFormat, Boolean)
Efficiently draws the same image multiple times across different pages or positions. Shares a single data stream for all instances, saving memory and file size.
// Add logo to all pages at same position:
var logo = new AnyBitmap("logo.png");
var pages = Enumerable.Range(0, pdf.PageCount);
var xPos = Enumerable.Repeat(500.0, pdf.PageCount);
var yPos = Enumerable.Repeat(750.0, pdf.PageCount);
var widths = Enumerable.Repeat(80.0, pdf.PageCount);
var heights = Enumerable.Repeat(40.0, pdf.PageCount);
pdf.DrawBitmap(logo, pages, xPos, yPos, widths, heights);
logo.Dispose();
// Add watermark at different positions:
var watermark = new AnyBitmap("draft.png");
pdf.DrawBitmap(watermark,
new[] { 0, 1, 2 }, // Pages 1-3
new[] { 100.0, 200.0, 300.0 }, // Different X positions
new[] { 400.0, 400.0, 400.0 }, // Same Y position
new[] { 200.0, 200.0, 200.0 }, // Same width
new[] { 100.0, 100.0, 100.0 }); // Same height
watermark.Dispose();
// Add thumbnails grid on single page:
var thumb = new AnyBitmap("thumbnail.jpg");
pdf.DrawBitmap(thumb,
new[] { 0, 0, 0, 0 }, // All on page 1
new[] { 50.0, 200.0, 350.0, 500.0 }, // X positions
new[] { 100.0, 100.0, 100.0, 100.0 }, // Y positions
new[] { 100.0, 100.0, 100.0, 100.0 }, // Widths
new[] { 100.0, 100.0, 100.0, 100.0 }); // Heights
thumb.Dispose();More efficient than calling DrawBitmap multiple times
All arrays must have the same length
See: https://ironpdf.com/how-to/add-image-to-pdf/
Declaration
public void DrawBitmap(AnyBitmap Bitmap, IEnumerable<int> PageIndices, IEnumerable<double> XCoordinates, IEnumerable<double> YCoordinates, IEnumerable<double> DesiredWidths, IEnumerable<double> DesiredHeights, PixelFormat PixelFormat, bool IgnorePageRotation = false)
Parameters
| Type | Name | Description |
|---|---|---|
| IronSoftware.Drawing.AnyBitmap | Bitmap | Image to draw (shared across all positions) |
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndices | Page indices for each image instance |
| System.Collections.Generic.IEnumerable<System.Double> | XCoordinates | X positions for each instance |
| System.Collections.Generic.IEnumerable<System.Double> | YCoordinates | Y positions for each instance |
| System.Collections.Generic.IEnumerable<System.Double> | DesiredWidths | Widths for each instance |
| System.Collections.Generic.IEnumerable<System.Double> | DesiredHeights | Heights for each instance |
| PixelFormat | PixelFormat | Pixel format for transparency |
| System.Boolean | IgnorePageRotation | True to ignore page rotation |
DrawBitmap(AnyBitmap, Int32, Double, Double, Double, Double, PixelFormat, Boolean)
Draws an image onto a PDF page at specified coordinates and size. Perfect for adding logos, stamps, signatures, or dynamic images.
// Add company logo:
var logo = new AnyBitmap("logo.png");
pdf.DrawBitmap(logo, 0, 50, 50, 100, 50); // Page 1, position (50,50), size 100x50
// Add signature image:
var signature = AnyBitmap.FromFile("signature.jpg");
pdf.DrawBitmap(signature, lastPage, 400, 100, 150, 75);
logo.Dispose(); signature.Dispose(); // Always disposeRemember to Dispose() bitmaps after use
Coordinates are from bottom-left corner
Declaration
public void DrawBitmap(AnyBitmap Bitmap, int PageIndex, double X, double Y, double DesiredWidth, double DesiredHeight, PixelFormat PixelFormat, bool IgnorePageRotation = false)
Parameters
| Type | Name | Description |
|---|---|---|
| IronSoftware.Drawing.AnyBitmap | Bitmap | Image to draw (PNG, JPG, BMP supported) |
| System.Int32 | PageIndex | Zero-based page index |
| System.Double | X | X coordinate from left edge |
| System.Double | Y | Y coordinate from bottom edge |
| System.Double | DesiredWidth | Target width in PDF units |
| System.Double | DesiredHeight | Target height in PDF units |
| PixelFormat | PixelFormat | Pixel format for transparency support |
| System.Boolean | IgnorePageRotation | True to always use bottom-left origin regardless of page rotation |
DrawLine(Int32, PointF, PointF, Double, Color)
Draws a line on a PDF page between two points. Perfect for creating dividers, underlines, borders, or custom graphics.
// Draw horizontal separator:
pdf.DrawLine(0,
new PointF(50, 300), // Start point
new PointF(550, 300), // End point
2, // Line width
Color.Black);
// Draw diagonal watermark line:
pdf.DrawLine(0,
new PointF(0, 0),
new PointF(612, 792),
5,
Color.Red);
// Draw vertical margin line:
pdf.DrawLine(pageIndex,
new PointF(72, 72), // 1 inch from left
new PointF(72, 720), // Full height
0.5,
Color.Gray);
// Create signature line:
pdf.DrawLine(lastPage,
new PointF(350, 100),
new PointF(550, 100),
1,
Color.Black);
pdf.DrawText("Signature", "Arial", 10, lastPage, 350, 85, Color.Black, 0);Coordinates are from bottom-left corner (0,0)
Line width is in PDF units (points)
See: https://ironpdf.com/how-to/add-annotations-to-pdfs/
Declaration
public void DrawLine(int PageIndex, PointF Start, PointF End, double Width, Color Color)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | PageIndex | Zero-based page index to draw on |
| IronSoftware.Drawing.PointF | Start | Starting point coordinates (X,Y from bottom-left) |
| IronSoftware.Drawing.PointF | End | Ending point coordinates (X,Y from bottom-left) |
| System.Double | Width | Line thickness in points |
| IronSoftware.Drawing.Color | Color | Line color |
DrawRectangle(Int32, RectangleF, Color, Color, Double)
Draws a rectangle on a PDF page with optional fill and border. Essential for creating boxes, highlights, frames, or custom form fields.
// Draw filled box:
pdf.DrawRectangle(0,
new RectangleF(100, 100, 200, 50),
Color.Black, // Border color
Color.LightGray, // Fill color
2); // Border width
// Draw border only (no fill):
pdf.DrawRectangle(0,
new RectangleF(50, 50, 300, 200),
Color.Red,
Color.Transparent, // No fill
3);
// Highlight area with semi-transparent yellow:
pdf.DrawRectangle(pageIndex,
new RectangleF(100, 400, 400, 30),
Color.Transparent,
Color.FromArgb(128, 255, 255, 0), // 50% yellow
0);
// Create form field box:
var fieldBox = new RectangleF(150, 500, 200, 25);
pdf.DrawRectangle(0, fieldBox, Color.Black, Color.White, 1);
pdf.DrawText("Name: ___________", "Arial", 10, 0, 155, 505, Color.Black, 0);Use Color.Transparent for no fill or no border
Rectangle coordinates: (X, Y, Width, Height) from bottom-left
See: https://ironpdf.com/how-to/add-annotations-to-pdfs/
Declaration
public void DrawRectangle(int PageIndex, RectangleF Rect, Color LineColor, Color FillColor, double Width)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | PageIndex | Zero-based page index |
| IronSoftware.Drawing.RectangleF | Rect | Rectangle bounds (X, Y, Width, Height) |
| IronSoftware.Drawing.Color | LineColor | Border color (Transparent for no border) |
| IronSoftware.Drawing.Color | FillColor | Fill color (Transparent for no fill) |
| System.Double | Width | Border line thickness in points |
DrawText(String, PdfFont, Double, Int32, Double, Double, Color, Double)
Draws text with a PdfFont object for enhanced font control and Unicode support. Use for custom fonts, embedded fonts, or when precise font management is needed.
// Using embedded font:
var font = pdf.Fonts.Add("CustomFont.ttf");
pdf.DrawText("Special Text", font, 14, 0, 100, 200, Color.Blue, 0);
// Using standard font:
var helvetica = PdfFont.Helvetica;
pdf.DrawText("Standard Text", helvetica, 12, 0, 100, 300, Color.Black, 0);
// Rotated text with custom font:
var customFont = pdf.Fonts.Last;
pdf.DrawText("© 2024", customFont, 10, 0, 400, 50, Color.Gray, 90);Use this overload when working with PdfFont objects
Font must be added to document first via Fonts.Add()
Declaration
public void DrawText(string Text, PdfFont Font, double FontSize, int PageIndex, double X, double Y, Color Color, double Rotation)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | Text | Text to draw |
| PdfFont | Font | Font (must be a system font or already added to the document using Fonts.Add()) |
| System.Double | FontSize | Font size |
| System.Int32 | PageIndex | Page index |
| System.Double | X | X coordinate |
| System.Double | Y | Y coordinate |
| IronSoftware.Drawing.Color | Color | Desired font color |
| System.Double | Rotation | Text rotation (degrees, clockwise) |
DrawText(String, String, Double, Int32, Double, Double, Color, Double)
Draws text directly onto a PDF page at precise coordinates. Essential for adding dynamic text, watermarks, headers, or annotations.
// Add page number:
pdf.DrawText("Page 1", "Arial", 12, 0, 100, 50, Color.Black, 0);
// Add rotated watermark:
pdf.DrawText("DRAFT", "Helvetica", 48, 0, 300, 400, Color.Red, 45);
// Unicode text with custom font:
pdf.Fonts.Add(fontBytes);
pdf.DrawText("ä½ å¥½", "CustomFont", 14, 0, 200, 300, Color.Black, 0);For Unicode text, add font using Fonts.Add() first
Coordinates are from bottom-left corner
Declaration
public void DrawText(string Text, string FontName, double FontSize, int PageIndex, double X, double Y, Color Color, double Rotation)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | Text | Text to draw |
| System.String | FontName | Font name (must be system font or added via Fonts.Add()) |
| System.Double | FontSize | Font size in points |
| System.Int32 | PageIndex | Zero-based page index |
| System.Double | X | X coordinate from left edge |
| System.Double | Y | Y coordinate from bottom edge |
| IronSoftware.Drawing.Color | Color | Text color |
| System.Double | Rotation | Rotation in degrees (clockwise) |
Equals(Object)
Declaration
public override bool Equals(object obj)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Object | obj |
Returns
| Type | Description |
|---|---|
| System.Boolean |
ExtendPage(Int32, Double, Double, Double, Double, MeasurementUnit)
Declaration
public void ExtendPage(int PageIndex, double ExtendLeft, double ExtendRight, double ExtendTop, double ExtendBottom, MeasurementUnit Units)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | PageIndex | |
| System.Double | ExtendLeft | |
| System.Double | ExtendRight | |
| System.Double | ExtendTop | |
| System.Double | ExtendBottom | |
| MeasurementUnit | Units |
ExtractAllBitmaps()
Declaration
public List<AnyBitmap> ExtractAllBitmaps()
Returns
| Type | Description |
|---|---|
| System.Collections.Generic.List<IronSoftware.Drawing.AnyBitmap> |
ExtractAllImages()
Declaration
public List<AnyBitmap> ExtractAllImages()
Returns
| Type | Description |
|---|---|
| System.Collections.Generic.List<IronSoftware.Drawing.AnyBitmap> |
ExtractAllRawImages()
Extracts all images from PDF as raw byte arrays for maximum performance. Best for streaming, API responses, or direct database storage without processing.
// Save to database:
var rawImages = pdf.ExtractAllRawImages();
foreach(var imageData in rawImages) {
db.SaveImage(new ImageRecord {
Data = imageData,
Size = imageData.Length
});
}
// Stream to API response:
var images = pdf.ExtractAllRawImages();
return File(images.First(), "image/jpeg");
// Process without creating bitmap objects:
var rawData = pdf.ExtractAllRawImages();
foreach(var data in rawData) {
var hash = ComputeHash(data);
if(IsDuplicate(hash)) continue;
SaveToStorage(data);
}
// Check image sizes:
var totalSize = pdf.ExtractAllRawImages()
.Sum(img => img.Length);
Console.WriteLine($"Total image data: {totalSize / 1024}KB");Most memory-efficient extraction method
Returns raw bytes - format depends on PDF encoding
See: https://ironpdf.com/how-to/extract-images-from-pdf/
Declaration
public List<byte[]> ExtractAllRawImages()
Returns
| Type | Description |
|---|---|
| System.Collections.Generic.List<System.Byte[]> | An Enumerable of Byte Arrays. Each Byte Array represents one image. |
ExtractAllText(TextExtractionOrder)
Extracts all text content from the PDF for searching, indexing, or analysis. Critical feature for content extraction, search functionality, and data mining.
// Extract all text:
string text = pdf.ExtractAllText();
// Extract with visual order (top to bottom):
string visualText = pdf.ExtractAllText(TextExtractionOrder.VisualOrder);Pages separated by 4 newlines for easy splitting
See: https://ironpdf.com/how-to/extract-text/
Declaration
public string ExtractAllText(TextExtractionOrder Order)
Parameters
| Type | Name | Description |
|---|---|---|
| TextExtractionOrder | Order | LogicalOrder preserves columns, VisualOrder reads top-to-bottom |
Returns
| Type | Description |
|---|---|
| System.String | All text in the PDF as a string. |
ExtractBitmapsFromPage(Int32)
Declaration
public List<AnyBitmap> ExtractBitmapsFromPage(int PageIndex)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | PageIndex |
Returns
| Type | Description |
|---|---|
| System.Collections.Generic.List<IronSoftware.Drawing.AnyBitmap> |
ExtractBitmapsFromPages(IEnumerable<Int32>)
Declaration
public List<AnyBitmap> ExtractBitmapsFromPages(IEnumerable<int> PageIndexes)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexes |
Returns
| Type | Description |
|---|---|
| System.Collections.Generic.List<IronSoftware.Drawing.AnyBitmap> |
ExtractBitmapsFromPages(Int32, Int32)
Declaration
public List<AnyBitmap> ExtractBitmapsFromPages(int StartIndex, int EndIndex)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | StartIndex | |
| System.Int32 | EndIndex |
Returns
| Type | Description |
|---|---|
| System.Collections.Generic.List<IronSoftware.Drawing.AnyBitmap> |
ExtractImagesFromPage(Int32)
Declaration
public List<AnyBitmap> ExtractImagesFromPage(int PageIndex)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | PageIndex |
Returns
| Type | Description |
|---|---|
| System.Collections.Generic.List<IronSoftware.Drawing.AnyBitmap> |
ExtractImagesFromPages(IEnumerable<Int32>)
Extracts images from specified PDF pages with full control over page selection. Core method for flexible multi-page image extraction.
// Extract from odd pages:
var oddPages = Enumerable.Range(0, pdf.PageCount)
.Where(i => i % 2 == 0);
var oddImages = pdf.ExtractImagesFromPages(oddPages);
Console.WriteLine($"Odd pages: {oddImages.Count} images");
// Extract from pages with forms:
var formPages = new[] { 3, 7, 12, 18 };
var formImages = pdf.ExtractImagesFromPages(formPages);
foreach(var img in formImages) {
ProcessFormImage(img);
img.Dispose();
}
// Extract based on metadata:
var importantPages = GetPagesWithTag("important");
var criticalImages = pdf.ExtractImagesFromPages(importantPages);
ArchiveImages(criticalImages);Most flexible extraction method for custom page sets
Large page sets may use significant memory
See: https://ironpdf.com/how-to/extract-images-from-pdf/
Declaration
public List<AnyBitmap> ExtractImagesFromPages(IEnumerable<int> PageIndexes)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexes | An IEnumerable list of page indexes. |
Returns
| Type | Description |
|---|---|
| System.Collections.Generic.List<IronSoftware.Drawing.AnyBitmap> | The extracted images as IronSoftware.Drawing.AnyBitmap Objects |
ExtractImagesFromPages(Int32, Int32)
Declaration
public List<AnyBitmap> ExtractImagesFromPages(int StartIndex, int EndIndex)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | StartIndex | |
| System.Int32 | EndIndex |
Returns
| Type | Description |
|---|---|
| System.Collections.Generic.List<IronSoftware.Drawing.AnyBitmap> |
ExtractRawImagesFromPage(Int32)
Declaration
public List<byte[]> ExtractRawImagesFromPage(int PageIndex)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | PageIndex |
Returns
| Type | Description |
|---|---|
| System.Collections.Generic.List<System.Byte[]> |
ExtractRawImagesFromPages(IEnumerable<Int32>)
Extracts images from specified pages as raw byte arrays. Optimal for selective extraction without bitmap overhead.
// Extract from specific pages for upload:
var pages = new[] { 0, 5, 10 };
var rawImages = pdf.ExtractRawImagesFromPages(pages);
foreach(var imgBytes in rawImages) {
await UploadToCloud(imgBytes);
}
// Extract even pages for compression:
var evenPages = Enumerable.Range(0, pdf.PageCount)
.Where(i => i % 2 == 0);
var images = pdf.ExtractRawImagesFromPages(evenPages);
CompressAndStore(images);
// Batch process selected pages:
var selectedPages = GetUserSelection();
var extractedImages = pdf.ExtractRawImagesFromPages(selectedPages);
var totalSize = extractedImages.Sum(img => img.Length);
Console.WriteLine($"Extracted {totalSize / 1048576}MB of images");
// Hash images for duplicate detection:
var criticalPages = new[] { 1, 3, 5, 7 };
var rawData = pdf.ExtractRawImagesFromPages(criticalPages);
var hashes = rawData.Select(ComputeSHA256).ToList();No bitmap objects created - pure byte arrays
Order matches occurrence in PDF, not page order
See: https://ironpdf.com/how-to/extract-images-from-pdf/
Declaration
public List<byte[]> ExtractRawImagesFromPages(IEnumerable<int> PageIndexes)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexes | An IEnumerable list of page indexes. |
Returns
| Type | Description |
|---|---|
| System.Collections.Generic.List<System.Byte[]> | List of raw image byte array. |
ExtractRawImagesFromPages(Int32, Int32)
Declaration
public List<byte[]> ExtractRawImagesFromPages(int StartIndex, int EndIndex)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | StartIndex | |
| System.Int32 | EndIndex |
Returns
| Type | Description |
|---|---|
| System.Collections.Generic.List<System.Byte[]> |
ExtractTextFromPage(Int32)
Declaration
public string ExtractTextFromPage(int PageIndex)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | PageIndex |
Returns
| Type | Description |
|---|---|
| System.String |
ExtractTextFromPage(Int32, TextExtractionOrder)
Extracts the text content from one page of the PDF and returns it as a string.
Declaration
public string ExtractTextFromPage(int PageIndex, TextExtractionOrder Order)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | PageIndex | Index of the page. Note: Page 1 has index 0... |
| TextExtractionOrder | Order | Determines order of how text is extracted from each page (see TextExtractionOrder |
Returns
| Type | Description |
|---|---|
| System.String | The text extracted from the PDF page as a string. |
ExtractTextFromPages(IEnumerable<Int32>)
Extracts text from specific pages in the PDF for selective content extraction. Perfect for extracting data from specific sections or forms.
// Extract from specific pages:
var pageList = new List<int> { 0, 2, 4 }; // Pages 1, 3, 5
string text = pdf.ExtractTextFromPages(pageList);
// Extract table of contents (typically pages 2-3):
var tocPages = new[] { 1, 2 };
string toc = pdf.ExtractTextFromPages(tocPages);
// Extract appendices (last 5 pages):
var lastPages = Enumerable.Range(pdf.PageCount - 5, 5);
string appendix = pdf.ExtractTextFromPages(lastPages);Pages separated by 4 newlines for easy splitting
Zero-based indexing: Page 1 = index 0
See: https://ironpdf.com/how-to/extract-text/
Declaration
public string ExtractTextFromPages(IEnumerable<int> PageIndices)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndices | Collection of zero-based page indexes to extract |
Returns
| Type | Description |
|---|---|
| System.String | Extracted text with pages separated by 4 newlines |
ExtractTextFromPages(IEnumerable<Int32>, TextExtractionOrder)
Extracts text from specific pages with control over extraction order. Essential for handling complex layouts like columns or modified documents.
// Extract with visual order for heavily edited PDFs:
var pages = new[] { 0, 1, 2 };
string text = pdf.ExtractTextFromPages(pages,
TextExtractionOrder.VisualOrder);
// Extract with logical order for column layouts:
var multiColumnPages = new List<int> { 3, 4, 5 };
string columns = pdf.ExtractTextFromPages(multiColumnPages,
TextExtractionOrder.LogicalOrder);
// Extract forms preserving field order:
var formPages = Enumerable.Range(0, 3);
string formData = pdf.ExtractTextFromPages(formPages,
TextExtractionOrder.LogicalOrder);LogicalOrder preserves original document structure
VisualOrder reads top-to-bottom, left-to-right
See: https://ironpdf.com/how-to/extract-text/
Declaration
public string ExtractTextFromPages(IEnumerable<int> PageIndices, TextExtractionOrder Order)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndices | Collection of zero-based page indexes |
| TextExtractionOrder | Order | Text extraction strategy (Logical or Visual) |
Returns
| Type | Description |
|---|---|
| System.String | Extracted text with pages separated by 4 newlines |
ExtractTextFromPages(Int32, Int32, TextExtractionOrder)
Extracts text from a continuous range of pages efficiently. Perfect for extracting chapters, sections, or sequential content.
// Extract first chapter (pages 1-10):
string chapter1 = pdf.ExtractTextFromPages(0, 9);
// Extract middle section:
string middle = pdf.ExtractTextFromPages(
pdf.PageCount / 2 - 5,
pdf.PageCount / 2 + 5);
// Extract everything except cover and back:
string content = pdf.ExtractTextFromPages(1, pdf.PageCount - 2);
// Extract with column preservation:
string columns = pdf.ExtractTextFromPages(5, 15,
TextExtractionOrder.LogicalOrder);Range is inclusive - both start and end pages are extracted
Zero-based: First page = 0, Last = PageCount-1
See: https://ironpdf.com/how-to/extract-text/
Declaration
public string ExtractTextFromPages(int StartIndex, int EndIndex, TextExtractionOrder Order)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | StartIndex | First page to extract (0-based) |
| System.Int32 | EndIndex | Last page to extract (inclusive) |
| TextExtractionOrder | Order | Text extraction strategy (default: LogicalOrder) |
Returns
| Type | Description |
|---|---|
| System.String | Extracted text with pages separated by 4 newlines |
Finalize()
Finalizer
Declaration
protected override void Finalize()
Flatten(IEnumerable<Int32>)
Flattens a document making form fields non-editable and merges them into the page content. Converts interactive elements into static content for final distribution.
// Flatten entire document:
pdf.Flatten();
// Flatten only first page:
pdf.Flatten(new[] { 0 });
// Flatten specific pages (0, 2, 4):
pdf.Flatten(new[] { 0, 2, 4 });Use before final distribution to prevent form modification
This operation cannot be reversed - keep original if editing needed
See: https://ironpdf.com/how-to/manage-pdf-forms/
Declaration
public void Flatten(IEnumerable<int> Pages = null)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<System.Int32> | Pages | Optional page indices to flatten (defaults to all pages if null) |
Remarks
Flattening is essential for: • Finalizing filled forms for archival • Preventing tampering with form data • Ensuring consistent display across PDF viewers • Reducing file size by removing interactive elements • Preparing documents for print production
Note: After flattening, form fields cannot be filled or modified programmatically. Always save a copy before flattening if you need to preserve the editable version.
Examples
// Complete form processing workflow
var pdf = PdfDocument.FromFile("application-form.pdf");
// Fill the form
pdf.Form["name"].Value = "John Doe";
pdf.Form["email"].Value = "john@example.com";
pdf.Form["agree"].Value = "Yes";
// Save editable version
pdf.SaveAs("filled-form-editable.pdf");
// Flatten for final distribution
pdf.Flatten();
pdf.SaveAs("filled-form-final.pdf");
FromFile(String, String, String, ChangeTrackingModes)
Opens an existing PDF document for editing. Your gateway to manipulating existing PDFs - merge, split, watermark, extract, and more.
// Open simple PDF:
var pdf = PdfDocument.FromFile("invoice.pdf");
string text = pdf.ExtractAllText();
pdf.SaveAs("copy.pdf");
// Open password-protected PDF:
var secured = PdfDocument.FromFile("protected.pdf", "user123");
// Open with owner password for full access:
var restricted = PdfDocument.FromFile(
"restricted.pdf",
Password: "user123",
OwnerPassword: "owner456");
// Track changes for incremental save (preserves signatures):
var signed = PdfDocument.FromFile(
"signed_contract.pdf",
TrackChanges: ChangeTrackingModes.EnableChangeTracking);
signed.AddWatermark("PROCESSED");
signed.SaveAsRevision(); // Preserves original signature
// Batch processing:
foreach (var file in Directory.GetFiles("invoices", "*.pdf")) {
using var pdf = PdfDocument.FromFile(file);
pdf.Password = "secure123";
pdf.SaveAs(file); // Overwrite with security
}Use 'using' for automatic disposal
Password = user password, OwnerPassword = admin password
TrackChanges preserves digital signatures
Adding a using declaration is not required. But can be used if you want to explicitly dispose. See: https://ironpdf.com/troubleshooting/ironpdf-using/
Declaration
public static PdfDocument FromFile(string PdfFilePath, string Password = "", string OwnerPassword = "", ChangeTrackingModes TrackChanges)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | PdfFilePath | The PDF file path. |
| System.String | Password | Optional user password if the PDF document is encrypted. |
| System.String | OwnerPassword | Optional password if the PDF document is protected by owner (printing, modifying restrictions etc..). |
| ChangeTrackingModes | TrackChanges | Optionally track changes (for use with incremental saving) |
Returns
| Type | Description |
|---|---|
| PdfDocument | An IronPdf.PdfDocument object as loaded from the file path. |
Exceptions
| Type | Condition |
|---|---|
| System.IO.IOException | Exception thrown if can not be opened. |
| System.ArgumentException |
|
FromJson(String)
Creates a PDF document from JSON data following the IRON document schema. Enables programmatic PDF generation from structured data or API responses.
// Create PDF from JSON string:
string json = @"{
'pageWidth': 210,
'pageHeight': 297,
'objects': [
{'type': 'text', 'content': 'Hello World', 'x': 50, 'y': 50}
]
}";
var pdf = PdfDocument.FromJson(json);
pdf.SaveAs("from-json.pdf");
// Generate from API response:
var apiResponse = await httpClient.GetStringAsync("api/document");
var pdfFromApi = PdfDocument.FromJson(apiResponse);
// Create from serialized model:
var model = new { title = "Report", content = "Data..." };
string jsonModel = JsonConvert.SerializeObject(model);
var pdfFromModel = PdfDocument.FromJson(jsonModel);Useful for dynamic PDF generation from databases or APIs
JSON must follow IRON document schema format
See: https://ironpdf.com/how-to/json-to-pdf/
Declaration
public static PdfDocument FromJson(string Json)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | Json | JSON string in IRON document format |
Returns
| Type | Description |
|---|---|
| PdfDocument | New PDF document created from JSON data |
FromJsonFile(String)
Creates a PDF document from a JSON file following the IRON document schema. Perfect for template-based generation and batch processing from JSON files.
// Load PDF from JSON file:
var pdf = PdfDocument.FromJsonFile("template.json");
pdf.SaveAs("output.pdf");
// Batch process JSON files:
foreach (var jsonFile in Directory.GetFiles("templates", "*.json"))
{
var pdf = PdfDocument.FromJsonFile(jsonFile);
var pdfName = Path.ChangeExtension(jsonFile, ".pdf");
pdf.SaveAs(pdfName);
}
// Load from resources:
var resourcePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
"Resources", "document-template.json");
var templatePdf = PdfDocument.FromJsonFile(resourcePath);
// Process with error handling:
try
{
var pdf = PdfDocument.FromJsonFile("data/report.json");
pdf.SaveAs("report.pdf");
}
catch (Exception ex)
{
Console.WriteLine($"Invalid JSON schema: {ex.Message}");
}Ideal for separating PDF structure from application logic
File must contain valid IRON document schema JSON
See: https://ironpdf.com/how-to/json-to-pdf/
Declaration
public static PdfDocument FromJsonFile(string Path)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | Path | Path to JSON file in IRON document format |
Returns
| Type | Description |
|---|---|
| PdfDocument | New PDF document created from JSON file |
FromUrl(Uri, String, String)
Opens a PDF stored on a URL for editing. Downloads and opens remote PDFs from HTTP/HTTPS URLs for manipulation.
// Open PDF from URL:
var pdf = PdfDocument.FromUrl(
new Uri("https://example.com/report.pdf"));
string text = pdf.ExtractAllText();
pdf.SaveAs("downloaded-report.pdf");
// Open password-protected PDF from URL:
var secured = PdfDocument.FromUrl(
new Uri("https://secure.example.com/invoice.pdf"),
Password: "user123");
// Open with both user and owner passwords:
var restricted = PdfDocument.FromUrl(
new Uri("https://example.com/restricted.pdf"),
Password: "user123",
OwnerPassword: "owner456");
// Download and process multiple PDFs:
var urls = new[] {
"https://example.com/pdf1.pdf",
"https://example.com/pdf2.pdf"
};
var pdfs = urls.Select(url =>
PdfDocument.FromUrl(new Uri(url))).ToList();Supports HTTP and HTTPS protocols with automatic redirect handling
Large files are downloaded entirely before processing
Use HTTPS for secure transmission of passwords
See: https://ironpdf.com/how-to/open-existing-pdf/
Declaration
public static PdfDocument FromUrl(Uri Uri, string Password = "", string OwnerPassword = "")
Parameters
| Type | Name | Description |
|---|---|---|
| System.Uri | Uri | The URI to the PDF document (HTTP or HTTPS). |
| System.String | Password | Optional user password if the PDF document is encrypted. |
| System.String | OwnerPassword | Optional owner password for full access to restricted PDFs. |
Returns
| Type | Description |
|---|---|
| PdfDocument | A PdfDocument object loaded from the URL, ready for manipulation. |
Remarks
FromUrl is perfect for: • Processing PDFs from web services or APIs • Downloading and archiving online documents • Integrating with cloud storage services • Processing email attachments via URLs • Batch downloading and processing
The PDF is downloaded completely before processing. For very large files, consider downloading to disk first, then using FromFile for better memory management.
Examples
// Download and merge PDFs from multiple URLs
public async Task MergeOnlinePdfs()
{
var urls = new[] {
"https://example.com/report1.pdf",
"https://example.com/report2.pdf",
"https://example.com/report3.pdf"
};
var pdfs = new List<PdfDocument>();
foreach (var url in urls)
{
try
{
var pdf = PdfDocument.FromUrl(new Uri(url));
pdfs.Add(pdf);
}
catch (Exception ex)
{
Console.WriteLine($"Failed to download {url}: {ex.Message}");
}
}
if (pdfs.Any())
{
var merged = PdfDocument.Merge(pdfs.ToArray());
merged.SaveAs("combined-reports.pdf");
// Dispose all PDFs
pdfs.ForEach(p => p.Dispose());
merged.Dispose();
}
}
Exceptions
| Type | Condition |
|---|---|
| IronPdfProductException | Thrown if cannot read the PDF due to incorrect URL, network issues, or wrong password. |
GetAnnotations(Int32)
Retrieves all annotations from a specific page for review or processing. Essential for reading comments, extracting feedback, or auditing markup.
// Get all annotations from first page:
var firstPageNotes = pdf.GetAnnotations(0);
foreach (var note in firstPageNotes) {
Console.WriteLine($"Title: {note.Title}");
Console.WriteLine($"Content: {note.Contents}");
Console.WriteLine($"Author: {note.Author}");
Console.WriteLine($"Position: ({note.X}, {note.Y})");
}
// Extract all review comments from document:
var allComments = new List<string>();
for (int i = 0; i < pdf.PageCount; i++) {
var annotations = pdf.GetAnnotations(i);
allComments.AddRange(annotations
.Where(a => !string.IsNullOrEmpty(a.Contents))
.Select(a => $"Page {i+1}: {a.Contents}"));
}
// Find annotations by specific reviewer:
var page5Annotations = pdf.GetAnnotations(4);
var johnReview = page5Annotations
.Where(a => a.Author == "John Smith")
.ToList();Returns empty list if page has no annotations
Y coordinates are from bottom of page upward
See: https://ironpdf.com/how-to/pdf-annotations/
Declaration
public List<PdfAnnotation> GetAnnotations(int pageIndex)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | pageIndex | Index of the page for which to retrieve annotations. The index of the first page is 0. |
Returns
| Type | Description |
|---|---|
| System.Collections.Generic.List<PdfAnnotation> | A list of annotations. |
GetHashCode()
Declaration
public override int GetHashCode()
Returns
| Type | Description |
|---|---|
| System.Int32 |
GetPageRotation(Int32)
Gets the rotation of a PDF page in degrees. Detects current page orientation for display or processing decisions.
// Check if first page is landscape:
var rotation = pdf.GetPageRotation(0);
bool isLandscape = (rotation == PdfPageRotation.Clockwise90 ||
rotation == PdfPageRotation.Clockwise270);
// Audit all rotated pages:
for (int i = 0; i < pdf.PageCount; i++) {
var rot = pdf.GetPageRotation(i);
if (rot != PdfPageRotation.None)
Console.WriteLine($"Page {i+1} is rotated {rot}");
}Useful for orientation-dependent processing
Values: None (0°), Clockwise90, Clockwise180, Clockwise270
Declaration
public PdfPageRotation GetPageRotation(int PageIndex)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | PageIndex | Index of the page to inspect. PageIndex is a 'Zero based' page number, the first page being 0. |
Returns
| Type | Description |
|---|---|
| PdfPageRotation | Degrees of rotation |
GetPrintDocument(PrinterSettings, PrintController, Boolean)
Returns a PrintDocument for advanced printing control - custom settings, preview, and events. Provides full access to .NET printing capabilities for complex requirements.
// Get PrintDocument with custom settings:
var printerSettings = new PrinterSettings {
PrinterName = "HP LaserJet",
Copies = 2,
Collate = true
};
printerSettings.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
var printDoc = pdf.GetPrintDocument(printerSettings);
printDoc.Print();
// Print preview dialog:
var printPreview = new PrintPreviewDialog();
printPreview.Document = pdf.GetPrintDocument(
printController: new PreviewPrintController());
printPreview.ShowDialog();
// Handle printing events:
var doc = pdf.GetPrintDocument();
doc.PrintPage += (s, e) => Console.WriteLine($"Printing page {e.PageSettings.PrinterSettings.FromPage}");
doc.EndPrint += (s, e) => Console.WriteLine("Print complete!");
doc.Print();
// Print filled form (flatten to show values):
var formDoc = pdf.GetPrintDocument(Flatten: true);Windows only - requires System.Drawing reference
Set margins to (0,0,0,0) for full-page printing
See: https://ironpdf.com/how-to/printing/
Declaration
public PrintDocument GetPrintDocument(PrinterSettings printerSettings = null, PrintController printController = null, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Drawing.Printing.PrinterSettings | printerSettings | Custom printer settings. If creating new PrinterSettings(), set margins to (0,0,0,0) |
| System.Drawing.Printing.PrintController | printController | Custom print controller (e.g., PreviewPrintController for GUI preview) |
| System.Boolean | Flatten | True to flatten form fields before printing (shows filled values) |
Returns
| Type | Description |
|---|---|
| System.Drawing.Printing.PrintDocument | A System.Drawing.Printing.PrintDocument for advanced printing control |
Remarks
GetPrintDocument is essential for: • Custom printer selection and settings • Print preview dialogs • Handling print events • Batch printing with progress tracking • Integration with existing print workflows • Advanced paper handling (duplex, trays)
The returned PrintDocument integrates with standard .NET printing, allowing full control over the print process.
Exceptions
| Type | Condition |
|---|---|
| System.Exception | IronPDF must be licensed to use this feature |
GetRevision(Int32)
Creates a copy of this document at the specified revision number. See SaveAsRevision(String)
Declaration
public PdfDocument GetRevision(int index)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | index | Revision number. Revision 0 represents the original document, revision 1 is the first revision, etc. |
Returns
| Type | Description |
|---|---|
| PdfDocument | A copy of the specified revision of this document |
GetVerifiedSignatures(Boolean)
Gets detailed information about all digital signatures in the PDF. Returns signature details including validity, signer info, and timestamps.
// Check all signatures in a PDF:
var signatures = pdf.GetVerifiedSignatures();
foreach (var sig in signatures)
{
Console.WriteLine($"Signer: {sig.SignerName}");
Console.WriteLine($"Valid: {sig.Valid}");
Console.WriteLine($"Date: {sig.SigningDate}");
}
// Enable incremental tampering detection for multi-signature documents:
var signatures = pdf.GetVerifiedSignatures(detectIncrementalTampering: true);
foreach (var sig in signatures)
{
Console.WriteLine($"Signer: {sig.SignerName}");
Console.WriteLine($"Status: {sig.Status}");
}
// Verify signatures before processing:
var sigs = pdf.GetVerifiedSignatures();
if (sigs.All(s => s.Valid))
{
// All signatures valid, proceed
ProcessDocument(pdf);
}
else
{
// Invalid signature detected
var invalid = sigs.First(s => !s.Valid);
Console.WriteLine($"Invalid: {invalid.Reason}");
}Includes certificate details and validation status
Signature validity can change if document is modified
See: https://ironpdf.com/troubleshooting/digital-signatures/
Declaration
public List<VerifiedSignature> GetVerifiedSignatures(bool detectIncrementalTampering = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Boolean | detectIncrementalTampering | When May add noticeable processing time for large or heavily revised documents. Recommended for multi-signature workflows in legal or government contexts. Default isfalse.
|
Returns
| Type | Description |
|---|---|
| System.Collections.Generic.List<VerifiedSignature> | List of VerifiedSignature objects with signature details |
IncrementReference()
Declaration
public void IncrementReference()
InsertPdf(PdfDocument, Int32)
Inserts another PDF into the current PdfDocument, starting at a given Page Index. Ideal for inserting pages, chapters, or sections at specific locations. If AnotherPdfFile contains form fields, those fields will be appended with '' in the resulting PDF. e.g. 'Name' will be 'Name'
// Insert cover page at beginning:
var document = PdfDocument.FromFile("report.pdf");
var coverPage = PdfDocument.FromFile("cover.pdf");
document.InsertPdf(coverPage, 0); // Insert at start
// Insert chapter at page 10:
var book = PdfDocument.FromFile("book.pdf");
var newChapter = PdfDocument.FromFile("chapter5.pdf");
book.InsertPdf(newChapter, 9); // Insert at page 10 (index 9)
// Insert disclaimer before last page:
var contract = PdfDocument.FromFile("contract.pdf");
var disclaimer = PdfDocument.FromFile("disclaimer.pdf");
contract.InsertPdf(disclaimer, contract.PageCount - 1);
// Build document from parts:
var final = new PdfDocument();
final.InsertPdf(intro, 0)
.InsertPdf(mainContent, intro.PageCount)
.InsertPdf(conclusion, final.PageCount);AtIndex=0 inserts at beginning, PageCount inserts at end
Indexes shift after insertion
Declaration
public PdfDocument InsertPdf(PdfDocument AnotherPdfFile, int AtIndex = 0)
Parameters
| Type | Name | Description |
|---|---|---|
| PdfDocument | AnotherPdfFile | Another PdfDocument. |
| System.Int32 | AtIndex | Index at which to insert the new content. Note: Page 1 has index 0... |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument object, allowing for a 'fluent' (LINQ like) chained in-line code style |
IsLinearized(String, String)
Loads a PDF document from a specified file path and check if the file is linearized or not.
------------------------------------------------
Usage:
PdfDocument.IsLinearized("my-pdf-file.pdf");
------------------------------------------------
Declaration
public static bool IsLinearized(string FilePath, string Password = "")
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FilePath | The full path to the PDF file to load. |
| System.String | Password | The password for the PDF file if it is encrypted. Default is empty string. |
Returns
| Type | Description |
|---|---|
| System.Boolean | True if the file is linearized or False if the file is not linearized |
Remarks
Important Notes:
Performance: This method is highly performant.
Security: Always validate file paths to prevent directory traversal vulnerabilities.
Related Documentation:
How-To Guide: Getting Started with PDF Linearization
API Reference: Full API Documentation
Exceptions
| Type | Condition |
|---|---|
| System.ArgumentException | Thrown when the FilePath is null, empty, or whitespace. |
| System.IO.FileNotFoundException | Thrown when the file at the specified FilePath does not exist. |
Merge(PdfDocument, PdfDocument)
Joins two PDFs into one: PdfDocument.Merge(pdf1, pdf2).SaveAs("merged.pdf") Quick method for combining exactly two documents.
// Merge two reports:
var report1 = PdfDocument.FromFile("q1_report.pdf");
var report2 = PdfDocument.FromFile("q2_report.pdf");
var combined = PdfDocument.Merge(report1, report2);
combined.SaveAs("half_year_report.pdf");
// Add cover page to document:
var cover = renderer.RenderHtmlAsPdf("<h1>Report 2024</h1>");
var content = PdfDocument.FromFile("report_content.pdf");
var final = PdfDocument.Merge(cover, content);
// Chain merges for multiple documents:
var part1 = PdfDocument.Merge(doc1, doc2);
var part2 = PdfDocument.Merge(doc3, doc4);
var complete = PdfDocument.Merge(part1, part2);For more than 2 PDFs, use Merge(IEnumerable<PdfDocument>)
Form fields renamed to avoid conflicts (Name→Name_0)
See: https://ironpdf.com/examples/merge-pdfs/
Declaration
public static PdfDocument Merge(PdfDocument A, PdfDocument B)
Parameters
| Type | Name | Description |
|---|---|---|
| PdfDocument | A | First PDF document |
| PdfDocument | B | Second PDF document |
Returns
| Type | Description |
|---|---|
| PdfDocument | A new merged PdfDocument containing all pages from A followed by all pages from B |
Merge(IEnumerable<PdfDocument>)
Combines PDFs into one: PdfDocument.Merge(pdf1, pdf2, pdf3).SaveAs("combined.pdf") Essential for batch processing - merge invoices, reports, or any documents. Form fields are renamed (Name→Name_0) to prevent conflicts.
Declaration
public static PdfDocument Merge(IEnumerable<PdfDocument> Documents)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<PdfDocument> | Documents | Collection of PDFs to merge. Use PdfDocument.FromFile() to load existing PDFs. |
Returns
| Type | Description |
|---|---|
| PdfDocument | A new PdfDocument containing all pages from input documents in order. |
Remarks
Merge is the primary method for combining PDFs - invoices into batches, chapters into books, reports into compilations. Pages are concatenated in the order provided.
using IronPdf;
// Merge multiple invoices
var invoice1 = PdfDocument.FromFile("invoice1.pdf");
var invoice2 = PdfDocument.FromFile("invoice2.pdf");
var invoice3 = PdfDocument.FromFile("invoice3.pdf");
var batch = PdfDocument.Merge(invoice1, invoice2, invoice3);
batch.SaveAs("invoice-batch.pdf");
// Merge from collection
var pdfs = Directory.GetFiles(@"C:\PDFs", "*.pdf")
.Select(f => PdfDocument.FromFile(f));
var combined = PdfDocument.Merge(pdfs);
combined.SaveAs("all-documents.pdf");
// Don't forget to dispose
foreach(var pdf in pdfs) pdf.Dispose();
combined.Dispose();
Exceptions
| Type | Condition |
|---|---|
| System.ArgumentNullException | Documents collection is null or empty. |
See Also
PageToBitmap(Int32, Int32, Boolean)
Renders a single page of the PDF to a (JPEG) IronSoftware.Drawing.AnyBitmap object.
Please add an assembly reference to IronSoftware.Drawing.AnyBitmap to use this "PDF To Image" method
Declaration
public AnyBitmap PageToBitmap(int pageIndex, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | pageIndex | The zero based page number to be converted to an image. E.g. Page 1 has a pageIndex of 0 |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| IronSoftware.Drawing.AnyBitmap | A IronSoftware.Drawing.AnyBitmap of the rendered PDF page. |
PageToBitmap(Int32, Nullable<Int32>, Nullable<Int32>, Int32, Boolean)
Renders a single page of the PDF to a (JPEG) IronSoftware.Drawing.AnyBitmap object.
Please add an assembly reference to IronSoftware.Drawing.AnyBitmap to use this "PDF To Image" method
Declaration
public AnyBitmap PageToBitmap(int pageIndex, Nullable<int> imageMaxWidth, Nullable<int> imageMaxHeight, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | pageIndex | The zero based page number to be converted to an image. E.g. Page 1 has a pageIndex of 0 |
| System.Nullable<System.Int32> | imageMaxWidth | The target maximum width of the output images. |
| System.Nullable<System.Int32> | imageMaxHeight | The target maximum height of the output images. |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| IronSoftware.Drawing.AnyBitmap | A IronSoftware.Drawing.AnyBitmap of the rendered PDF page. |
PageToBitmapHighQuality(Int32, Int32, Boolean)
Renders a single page of the PDF to a (BMP) IronSoftware.Drawing.AnyBitmap object.
Please add an assembly reference to IronSoftware.Drawing.AnyBitmap to use this "PDF To Image" method
Declaration
public AnyBitmap PageToBitmapHighQuality(int pageIndex, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | pageIndex | The zero based page number to be converted to an image. E.g. Page 1 has a pageIndex of 0 |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| IronSoftware.Drawing.AnyBitmap | A IronSoftware.Drawing.AnyBitmap of the rendered PDF page. The resulting images have significantly larger file sizes compared to PageToBitmap(Int32, Int32, Boolean) |
Remarks
The DPI will be ignored under Linux and macOS.
PageToBitmapHighQuality(Int32, Nullable<Int32>, Nullable<Int32>, Int32, Boolean)
Renders a single page of the PDF to a (BMP) IronSoftware.Drawing.AnyBitmap object.
Please add an assembly reference to IronSoftware.Drawing.AnyBitmap to use this "PDF To Image" method
Declaration
public AnyBitmap PageToBitmapHighQuality(int pageIndex, Nullable<int> imageMaxWidth, Nullable<int> imageMaxHeight, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | pageIndex | The zero based page number to be converted to an image. E.g. Page 1 has a pageIndex of 0 |
| System.Nullable<System.Int32> | imageMaxWidth | The target maximum width of the output images. |
| System.Nullable<System.Int32> | imageMaxHeight | The target maximum height of the output images. |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| IronSoftware.Drawing.AnyBitmap | A IronSoftware.Drawing.AnyBitmap of the rendered PDF page. The resulting images have significantly larger file sizes compared to PageToBitmap(Int32, Nullable<Int32>, Nullable<Int32>, Int32, Boolean) |
Remarks
The DPI will be ignored under Linux and macOS.
PerformOcr()
Perform Optical Character Recognition on this document. Requires IronOcr NuGet package installed. Extracts text from scanned PDFs, images, and non-searchable documents using AI-powered OCR.
// Basic OCR on scanned PDF:
var pdf = PdfDocument.FromFile("scanned_invoice.pdf");
var ocrResult = pdf.PerformOcr();
string extractedText = ocrResult.Text;
double confidence = ocrResult.Confidence;
Console.WriteLine($"OCR confidence: {confidence:P}");
// Process each page's OCR results:
foreach (var page in ocrResult.Pages) {
Console.WriteLine($"Page {page.PageNumber}: {page.Text}");
foreach (var word in page.Words) {
Console.WriteLine($" '{word.Text}' at ({word.X},{word.Y})");
}
}
// Make scanned PDF searchable:
var searchablePdf = ocrResult.SaveAsSearchablePdf();
searchablePdf.SaveAs("searchable_invoice.pdf");
// Extract structured data:
var invoiceNumber = ocrResult.Text
.Split('\n')
.FirstOrDefault(line => line.Contains("Invoice #"))
?.Replace("Invoice #", "").Trim();OCR works best with 300+ DPI scanned images
Requires: Install-Package IronOcr
Supports 125+ languages with language packs
See: https://ironpdf.com/how-to/ocr-pdf-text-extraction/
Declaration
public IOcrResult PerformOcr()
Returns
| Type | Description |
|---|---|
| IronSoftware.Abstractions.Ocr.IOcrResult | OCR result. |
PrependPdf(PdfDocument)
Adds another PDF to the beginning of the current PdfDocument. Perfect for adding cover pages, disclaimers, or table of contents. If AnotherPdfFile contains form fields, those fields will be appended with '' in the resulting PDF. e.g. 'Name' will be 'Name'
// Add cover page to report:
var report = PdfDocument.FromFile("annual_report.pdf");
var cover = renderer.RenderHtmlAsPdf("<h1>Annual Report 2025</h1>");
report.PrependPdf(cover);
report.SaveAs("report_with_cover.pdf");
// Add legal disclaimer to contract:
var contract = PdfDocument.FromFile("contract.pdf");
var disclaimer = PdfDocument.FromFile("legal_disclaimer.pdf");
contract.PrependPdf(disclaimer);
// Add table of contents:
var book = PdfDocument.FromFile("book_content.pdf");
var toc = GenerateTableOfContents(book);
book.PrependPdf(toc);
// Chain multiple prepends (reverse order!):
document.PrependPdf(page3) // Will be page 3
.PrependPdf(page2) // Will be page 2
.PrependPdf(page1); // Will be page 1Equivalent to InsertPdf(pdf, 0)
Multiple prepends work in reverse order
Declaration
public PdfDocument PrependPdf(PdfDocument AnotherPdfFile)
Parameters
| Type | Name | Description |
|---|---|---|
| PdfDocument | AnotherPdfFile | PdfDocument to prepend. |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument object, allowing for a 'fluent' (LINQ like) chained in-line code style |
Print(Boolean)
Prints PDF to default printer at 300 DPI quality. Simple one-line printing for documents, reports, and forms.
// Print to default printer:
await pdf.Print();
// Print filled form (flatten to show values):
await pdf.Print(Flatten: true);
// Print and check page count:
int printed = await pdf.Print();
Console.WriteLine($"Printed {printed} pages");Windows only - use GetPrintDocument for cross-platform
300 DPI provides excellent print quality
See: https://ironpdf.com/how-to/printing/
Declaration
public Task<int> Print(bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Boolean | Flatten | True to flatten form fields before printing (shows filled values) |
Returns
| Type | Description |
|---|---|
| System.Threading.Tasks.Task<System.Int32> | Number of pages successfully printed |
See Also
Print(Int32, Int32, String, String, PrintController, Boolean)
Prints this PDF by sending it to the computer's printer.
For even more advanced real-world printing options please see overloads of this method and also GetPrintDocument(PrinterSettings, PrintController, Boolean).
Note: 'Print(Int32, Int32, String, String, PrintController, Boolean)' is only supported on: 'Windows'.
the horizontal PDF resolution, in dots per inch.the vertical PDF resolution, in dots per inch.the name of a printer, setnull or an empty string ("") to use default print. Default value is null.the file path, when printing to a file, setfilePath. The default value is null. custom printController such as PreviewPrintController for a GUI print previewFlatten the PDF before printing - useful for displaying form field values
Declaration
public Task<int> Print(int dpiX, int dpiY, string printerName = null, string filePath = null, PrintController customPrintController = null, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | dpiX | |
| System.Int32 | dpiY | |
| System.String | printerName | |
| System.String | filePath | |
| System.Drawing.Printing.PrintController | customPrintController | |
| System.Boolean | Flatten |
Returns
| Type | Description |
|---|---|
| System.Threading.Tasks.Task<System.Int32> | The number of printed pages. |
See Also
Print(Int32, String, String, Boolean)
Prints this PDF by sending it to the computer's printer.
For even more advanced real-world printing options please see overloads of this method and also GetPrintDocument(PrinterSettings, PrintController, Boolean).
Note: 'Print(Int32, String, String, Boolean)' is only supported on: 'Windows'.
the horizontal and vertical PDF resolutions, in dots per inch. if-1 print with default
printer resolution. Default value is 300.the name of a printer, setnull or an empty string ("") to use default print. Default value is null.the file path, when printing to a file, set FilePath. The default value is null.Flatten the PDF before printing - useful for displaying form field values
Declaration
public Task<int> Print(int dpi, string PrinterName = null, string FilePath = null, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | dpi | |
| System.String | PrinterName | |
| System.String | FilePath | |
| System.Boolean | Flatten |
Returns
| Type | Description |
|---|---|
| System.Threading.Tasks.Task<System.Int32> | The number of printed pages. |
See Also
Print(String, Boolean)
Prints PDF to specified printer at 300 DPI quality. Direct printing to any installed printer by name.
// Print to specific printer:
await pdf.Print("HP LaserJet Pro");
// Print to default printer (pass null or ""):
await pdf.Print(null);
// Print filled form to printer:
pdf.Form["name"].Value = "John Doe";
await pdf.Print("Canon Printer", Flatten: true);
// Get available printer names:
foreach (string printer in PrinterSettings.InstalledPrinters)
{
Console.WriteLine(printer);
}
await pdf.Print("Microsoft Print to PDF");Windows only - 300 DPI default quality
Use PrinterSettings.InstalledPrinters to list available printers
See: https://ironpdf.com/how-to/printing/
Declaration
public Task<int> Print(string PrinterName, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | PrinterName | Printer name (null or "" for default printer) |
| System.Boolean | Flatten | True to flatten form fields before printing |
Returns
| Type | Description |
|---|---|
| System.Threading.Tasks.Task<System.Int32> | Number of pages successfully printed |
See Also
PrintToFile(Int32, String, Boolean)
Prints this PDF by sending it to the computer's printer. (300 DPI)
For advanced real-world printing options please see overloads of this method and also GetPrintDocument(PrinterSettings, PrintController, Boolean).
Note: 'PrintToFile(Int32, String, Boolean)' is only supported on: 'Windows'.
the horizontal and vertical PDF resolutions, in dots per inch. if-1 print with default printer
resolution. Default value is 300.output file path, if set to null or an empty string ("") default filePath will be random GUID.Flatten the PDF before printing - useful for displaying form field values
Declaration
public Task<int> PrintToFile(int dpi = 300, string filePath = null, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | dpi | |
| System.String | filePath | |
| System.Boolean | Flatten |
Returns
| Type | Description |
|---|---|
| System.Threading.Tasks.Task<System.Int32> | The number of printed pages. |
See Also
PrintToFile(String, Boolean)
Prints this PDF by sending it to the computer's printer. (300 DPI)
For advanced real-world printing options please see overloads GetPrintDocument(PrinterSettings, PrintController, Boolean).
Note: 'PrintToFile(String, Boolean)' is only supported on: 'Windows'.
output file path, if set to null or an empty string ("") default filePath will be random GUID.Flatten the PDF before printing - useful for displaying form field valuesDeclaration
public Task<int> PrintToFile(string filePath, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | filePath | |
| System.Boolean | Flatten |
Returns
| Type | Description |
|---|---|
| System.Threading.Tasks.Task<System.Int32> | The number of printed pages. |
See Also
RasterizeToImageFiles(String, ImageType, Int32, Boolean)
Batch converts PDF pages directly to image files: pdf.RasterizeToImageFiles(@"C:\Output\page_.png", 150) Essential for SharePoint uploads, web galleries, document management systems, and batch processing. The asterisk () in the pattern is replaced with page numbers automatically.
Declaration
public string[] RasterizeToImageFiles(string FileNamePattern, ImageType ImageFileType, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileNamePattern | File path with asterisk for page numbers: @"C:\images\doc_*.png" creates doc_1.png, doc_2.png, etc. |
| ImageType | ImageFileType | Output format (PNG, JPEG, TIFF, etc). Auto-detected from file extension if not specified. |
| System.Int32 | DPI | Resolution: 96=web display, 150=documents, 300=print quality. Higher DPI = larger files. |
| System.Boolean | Flatten | Flatten form fields before rendering - essential for displaying filled forms accurately |
Returns
| Type | Description |
|---|---|
| System.String[] | Array of created file paths for verification or further processing. |
Remarks
This method is optimized for batch processing - directly writes to disk without loading all images into memory. Perfect for converting large PDFs or processing multiple documents.
using IronPdf;
// SharePoint gallery - convert entire PDF to PNG images
var pdf = PdfDocument.FromFile("annual-report.pdf");
var imagePaths = pdf.RasterizeToImageFiles(
@"C:\SharePoint\Gallery\report_page_*.png",
DPI: 150 // Good balance of quality and size
);
Console.WriteLine($"Created {imagePaths.Length} images for SharePoint");
// Generate thumbnails for document management system
var catalog = PdfDocument.FromFile("product-catalog.pdf");
catalog.RasterizeToImageFiles(
@"thumbnails\catalog_*.jpg",
new[] { 0, 1, 2 }, // First 3 pages only
ImageType.Jpeg,
DPI: 96 // Web thumbnail size
);
// Batch process multiple PDFs to images
foreach (var pdfFile in Directory.GetFiles(@"C:\PDFs", ".pdf"))
{
var doc = PdfDocument.FromFile(pdfFile);
var baseName = Path.GetFileNameWithoutExtension(pdfFile);
doc.RasterizeToImageFiles(
$@"C:\Images{baseName}page.png",
DPI: 200
);
doc.Dispose();
}
// Archive to TIFF for compliance
var legal = PdfDocument.FromFile("contract.pdf");
legal.RasterizeToImageFiles(
@"\Archive\2024\Contracts\contract_*.tiff",
ImageType.Tiff,
DPI: 300, // High quality for legal archives
Flatten: true // Ensure all signatures visible
);
See Also
RasterizeToImageFiles(String, IEnumerable<Int32>, ImageType, Int32, Boolean)
Renders the PDF and exports image Files in convenient formats. Page Numbers may be specified. 1 image file is created for each page.
FileNamePattern should normally contain an asterisk (*) character which will be substituted for the page numbers
Declaration
public string[] RasterizeToImageFiles(string FileNamePattern, IEnumerable<int> PageIndexes, ImageType ImageFileType, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileNamePattern | A full or partial file path for the output files containing an asterisk. E.g. C:\images\pdf_page_*.png |
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexes | A list of the specific zero based page numbe to render as images. |
| ImageType | ImageFileType | Type of the image file. If not specified, a best guess will be taken from the FileNamePattern file extension |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| System.String[] | An array of the file paths of the image files created. |
RasterizeToImageFiles(String, IEnumerable<Int32>, Nullable<Int32>, Nullable<Int32>, ImageType, Int32, Boolean)
Renders the PDF and exports image Files in convenient formats. Page Numbers may be specified. 1 image file is created for each page.
FileNamePattern should normally contain an asterisk (*) character which will be substituted for the page numbers
Declaration
public string[] RasterizeToImageFiles(string FileNamePattern, IEnumerable<int> PageIndexes, Nullable<int> ImageMaxWidth, Nullable<int> ImageMaxHeight, ImageType ImageFileType, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileNamePattern | A full or partial file path for the output files containing an asterisk. E.g. C:\images\pdf_page_*.png |
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexes | A list of the specific zero based page numbe to render as images. |
| System.Nullable<System.Int32> | ImageMaxWidth | The target maximum width(in pixel) of the output images. |
| System.Nullable<System.Int32> | ImageMaxHeight | The target maximum height(in pixel) of the output images. |
| ImageType | ImageFileType | Type of the image file. If not specified, a best guess will be taken from the FileNamePattern file extension |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| System.String[] | An array of the file paths of the image files created. |
RasterizeToImageFiles(String, Nullable<Int32>, Nullable<Int32>, ImageType, Int32, Boolean)
Renders the PDF and exports image Files in convenient formats. Image dimensions may be specified. 1 image file is created for each page.
FileNamePattern should normally contain an asterisk (*) character which will be substituted for the page numbers
Declaration
public string[] RasterizeToImageFiles(string FileNamePattern, Nullable<int> ImageMaxWidth, Nullable<int> ImageMaxHeight, ImageType ImageFileType, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileNamePattern | A full or partial file path for the output files containing an asterisk. E.g. C:\images\pdf_page_*.png |
| System.Nullable<System.Int32> | ImageMaxWidth | The target maximum width(in pixel) of the output images. |
| System.Nullable<System.Int32> | ImageMaxHeight | The target maximum height(in pixel) of the output images. |
| ImageType | ImageFileType | Type of the image file. If not specified, a best guess will be taken from the FileNamePattern file extension |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| System.String[] | An array of the file paths of the image files created. |
RedactRegionOnPage(Int32, RectangleF)
Permanently redacts a rectangular region on a page with a black box. Perfect for removing signatures, stamps, headers, or fixed-position sensitive data.
// Redact signature area at bottom of page:
var signatureArea = new RectangleF(100, 700, 300, 50);
pdf.RedactRegionOnPage(0, signatureArea);
// Remove header region from first page:
var headerRegion = new RectangleF(0, 0, 612, 72); // Full width, 1 inch
pdf.RedactRegionOnPage(0, headerRegion);
// Redact ID photo location:
var photoBox = new RectangleF(450, 100, 100, 120);
pdf.RedactRegionOnPage(1, photoBox);
// Remove address block:
var addressArea = new RectangleF(50, 200, 250, 100);
pdf.RedactRegionOnPage(2, addressArea);Coordinates: X=0,Y=0 is bottom-left, measured in points (72 per inch)
Region is permanently blacked out - cannot be reversed
See: https://ironpdf.com/how-to/redact-pdf-text/
Declaration
public void RedactRegionOnPage(int PageIndex, RectangleF Region)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | PageIndex | Zero-based page index to redact |
| IronSoftware.Drawing.RectangleF | Region | Rectangle defining area to black out (X, Y, Width, Height) |
RedactRegionOnPages(Int32[], RectangleF)
Permanently redacts the same region across multiple pages. Essential for removing consistent headers, footers, or watermarks from specific pages.
// Remove footer from selected pages:
var footerRegion = new RectangleF(0, 750, 612, 42);
var pages = new[] { 0, 2, 4, 6, 8 };
pdf.RedactRegionOnPages(pages, footerRegion);
// Redact watermark from all odd pages:
var watermark = new RectangleF(200, 400, 200, 100);
var oddPages = Enumerable.Range(0, pdf.PageCount)
.Where(i => i % 2 == 1).ToArray();
pdf.RedactRegionOnPages(oddPages, watermark);
// Remove logo from first 5 pages:
var logoArea = new RectangleF(500, 20, 80, 80);
var firstPages = Enumerable.Range(0, 5).ToArray();
pdf.RedactRegionOnPages(firstPages, logoArea);
// Redact page numbers from specific pages:
var pageNumArea = new RectangleF(280, 760, 50, 20);
pdf.RedactRegionOnPages(new[] { 0, 1, 10, 11 }, pageNumArea);Same region coordinates applied to each specified page
Ensure region exists at same position on all pages
See: https://ironpdf.com/how-to/redact-pdf-text/
Declaration
public void RedactRegionOnPages(int[] PageIndices, RectangleF Region)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32[] | PageIndices | Array of zero-based page indexes |
| IronSoftware.Drawing.RectangleF | Region | Rectangle to black out on each page |
RedactRegionsOnAllPages(RectangleF)
Permanently redacts the same region on every page of the document. Perfect for removing headers, footers, watermarks, or page numbers throughout.
// Remove header from all pages:
var headerRegion = new RectangleF(0, 0, 612, 72);
pdf.RedactRegionsOnAllPages(headerRegion);
// Remove watermark throughout document:
var watermark = new RectangleF(150, 350, 300, 150);
pdf.RedactRegionsOnAllPages(watermark);
// Redact footer containing confidential info:
var footer = new RectangleF(0, 750, 612, 42);
pdf.RedactRegionsOnAllPages(footer);
// Remove page numbers from entire document:
var pageNumberArea = new RectangleF(280, 20, 50, 20);
pdf.RedactRegionsOnAllPages(pageNumberArea);
// Redact company logo from all pages:
var logo = new RectangleF(500, 700, 100, 50);
pdf.RedactRegionsOnAllPages(logo);Most efficient way to redact same area on all pages
Applied to EVERY page - verify region position first
See: https://ironpdf.com/how-to/redact-pdf-text/
Declaration
public void RedactRegionsOnAllPages(RectangleF Region)
Parameters
| Type | Name | Description |
|---|---|---|
| IronSoftware.Drawing.RectangleF | Region | Rectangle to black out on every page |
RedactRegionsOnPage(Int32, IEnumerable<RectangleF>)
Permanently redacts multiple rectangular regions on a single page. Efficient for removing multiple sensitive areas like form fields, tables, or images.
// Redact multiple form fields on page:
var regions = new List<RectangleF>
{
new RectangleF(100, 200, 200, 30), // Name field
new RectangleF(100, 250, 200, 30), // SSN field
new RectangleF(100, 300, 200, 30), // Phone field
new RectangleF(100, 350, 200, 30) // Email field
};
pdf.RedactRegionsOnPage(0, regions);
// Remove all images from a catalog page:
var imageAreas = new[]
{
new RectangleF(50, 50, 150, 150),
new RectangleF(250, 50, 150, 150),
new RectangleF(50, 250, 150, 150),
new RectangleF(250, 250, 150, 150)
};
pdf.RedactRegionsOnPage(3, imageAreas);
// Redact table columns with sensitive data:
var columnRegions = Enumerable.Range(0, 10)
.Select(i => new RectangleF(400, 100 + i * 20, 100, 20));
pdf.RedactRegionsOnPage(5, columnRegions);More efficient than multiple single-region calls
All regions are permanently blacked out
See: https://ironpdf.com/how-to/redact-pdf-text/
Declaration
public void RedactRegionsOnPage(int PageIndex, IEnumerable<RectangleF> Regions)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | PageIndex | Zero-based page index to redact |
| System.Collections.Generic.IEnumerable<IronSoftware.Drawing.RectangleF> | Regions | Collection of rectangles to black out |
RedactTextOnAllPages(String, Boolean, Boolean, Boolean, String)
Permanently redacts sensitive text throughout document: pdf.RedactTextOnAllPages("SSN: 123-45-6789", DrawRectangles: true) CRITICAL for GDPR/HIPAA compliance - removes text completely, not just visually. Cannot be undone. Unlike ReplaceText which leaves traces, redaction is forensically secure.
Declaration
public void RedactTextOnAllPages(string ReplaceText, bool CaseSensitive = false, bool OnlyMatchWholeWords = true, bool DrawRectangles = true, string ReplacementText = "*")
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | ReplaceText | The text string to be redacted |
| System.Boolean | CaseSensitive | Match capital or lower-case letters |
| System.Boolean | OnlyMatchWholeWords | Only match whole words |
| System.Boolean | DrawRectangles | Draw black rectangles around redacted area(s) |
| System.String | ReplacementText | Text to be written in place of redacted items |
Remarks
using IronPdf;
// GDPR compliance - remove all personal data
var pdf = PdfDocument.FromFile("customer-records.pdf");
// Redact Social Security Numbers
pdf.RedactTextOnAllPages(@"\d{3}-\d{2}-\d{4}", // SSN pattern
CaseSensitive: false,
OnlyMatchWholeWords: false,
DrawRectangles: true,
ReplacementText: "[REDACTED]");
// Redact email addresses
pdf.RedactTextOnAllPages(@"[\w.-]+@[\w.-]+.\w+", // Email pattern
DrawRectangles: true,
ReplacementText: "[EMAIL REMOVED]");
// Redact specific names from legal document
string[] namesToRedact = { "John Doe", "Jane Smith", "Robert Johnson" };
foreach (var name in namesToRedact)
{
pdf.RedactTextOnAllPages(name,
CaseSensitive: false,
OnlyMatchWholeWords: true,
DrawRectangles: true,
ReplacementText: "[NAME REDACTED]");
}
// Save the sanitized document
pdf.SaveAs("customer-records-redacted.pdf");
// Medical records HIPAA compliance
var medical = PdfDocument.FromFile("patient-record.pdf");
medical.RedactTextOnAllPages("Patient ID:",
OnlyMatchWholeWords: false,
DrawRectangles: true);
medical.RedactTextOnAllPages("DOB:",
OnlyMatchWholeWords: false,
DrawRectangles: true);
medical.SaveAs("patient-record-deidentified.pdf");
See Also
RedactTextOnPage(Int32, String, Boolean, Boolean, Boolean, String)
Permanently redacts sensitive text on a specific page with security-compliant black boxes. Critical for GDPR compliance, privacy protection, and secure document sharing.
// Redact SSN on first page:
pdf.RedactTextOnPage(0, "123-45-6789",
CaseSensitive: false,
DrawRectangles: true,
ReplacementText: "[REDACTED]");
// Remove all email addresses on page 2:
pdf.RedactTextOnPage(1, "john.doe@email.com",
OnlyMatchWholeWords: false,
DrawRectangles: true,
ReplacementText: "***");
// Redact case-insensitive personal names:
pdf.RedactTextOnPage(0, "John Smith",
CaseSensitive: false,
OnlyMatchWholeWords: true,
DrawRectangles: true);
// Hide confidential data with custom text:
pdf.RedactTextOnPage(3, "salary: $",
CaseSensitive: true,
OnlyMatchWholeWords: false,
ReplacementText: "[CONFIDENTIAL]");Redaction is permanent - save a backup first!
Black rectangles cannot be removed once applied
See: https://ironpdf.com/how-to/redact-pdf-text/
Declaration
public void RedactTextOnPage(int PageIndex, string ReplaceText, bool CaseSensitive = false, bool OnlyMatchWholeWords = true, bool DrawRectangles = true, string ReplacementText = "*")
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | PageIndex | Zero-based page index to redact |
| System.String | ReplaceText | Sensitive text to permanently redact |
| System.Boolean | CaseSensitive | Match exact case (default: false) |
| System.Boolean | OnlyMatchWholeWords | Match complete words only (default: true) |
| System.Boolean | DrawRectangles | Draw black boxes over text (default: true) |
| System.String | ReplacementText | Text shown instead of redacted content (default: "*") |
RedactTextOnPages(Int32[], String, Boolean, Boolean, Boolean, String)
Permanently redacts sensitive text across multiple pages for batch privacy protection. Essential for removing PII, financial data, or confidential information from documents.
// Redact credit cards on billing pages:
var billingPages = new[] { 2, 3, 4 };
pdf.RedactTextOnPages(billingPages, "4111-1111-1111-1111",
DrawRectangles: true,
ReplacementText: "[CARD REMOVED]");
// Remove phone numbers from contact pages:
var contactPages = new[] { 0, 1, 10, 11 };
pdf.RedactTextOnPages(contactPages, "(555)",
CaseSensitive: false,
OnlyMatchWholeWords: false,
ReplacementText: "[PHONE]");
// Redact names from all odd pages:
var oddPages = Enumerable.Range(0, pdf.PageCount)
.Where(i => i % 2 == 0).ToArray();
pdf.RedactTextOnPages(oddPages, "Jane Doe",
CaseSensitive: false,
DrawRectangles: true);
// GDPR compliance - remove all personal data:
var allPages = Enumerable.Range(0, pdf.PageCount).ToArray();
pdf.RedactTextOnPages(allPages, "@example.com",
OnlyMatchWholeWords: false,
ReplacementText: "[EMAIL]");Process multiple pages efficiently in one operation
Redaction is irreversible - always keep originals
See: https://ironpdf.com/how-to/redact-pdf-text/
Declaration
public void RedactTextOnPages(int[] PageIndices, string ReplaceText, bool CaseSensitive = false, bool OnlyMatchWholeWords = true, bool DrawRectangles = true, string ReplacementText = "*")
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32[] | PageIndices | Array of zero-based page indexes to redact |
| System.String | ReplaceText | Sensitive text to permanently remove |
| System.Boolean | CaseSensitive | Match exact case (default: false) |
| System.Boolean | OnlyMatchWholeWords | Match complete words only (default: true) |
| System.Boolean | DrawRectangles | Draw black boxes over text (default: true) |
| System.String | ReplacementText | Text shown instead (default: "*") |
RemovePage(Int32)
Removes a page from the PDF at the given index. Perfect for deleting unwanted pages like blank pages or advertisements.
// Remove the first page (cover):
var pdf = PdfDocument.FromFile("document.pdf");
pdf.RemovePage(0);
pdf.SaveAs("no_cover.pdf");
// Remove last page (often blank):
pdf.RemovePage(pdf.PageCount - 1);
// Chain operations fluently:
pdf.RemovePage(0)
.RemovePage(0) // Now removes what was page 2
.SaveAs("trimmed.pdf");
// Remove page 5 (index 4):
pdf.RemovePage(4);
// Check page count after removal:
Console.WriteLine($"Pages remaining: {pdf.PageCount}");Returns this for method chaining
Page indexes shift after each removal
Remember: Page 1 = Index 0
Declaration
public PdfDocument RemovePage(int PageIndex)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | PageIndex | Index of the page. Note: Page 1 has index 0... |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument object, allowing for a 'fluent' (LINQ like) chained in-line code style |
RemovePages(IEnumerable<Int32>)
Removes a range of pages from the PDF. Efficiently delete multiple specific pages in one operation.
// Remove multiple specific pages:
var pdf = PdfDocument.FromFile("report.pdf");
pdf.RemovePages(new[] { 0, 5, 10, 15 }); // Remove pages 1, 6, 11, 16
// Remove all even pages (keep odd only):
var evenPages = Enumerable.Range(0, pdf.PageCount)
.Where(x => x % 2 == 1)
.Reverse(); // Remove from end to avoid shifting
pdf.RemovePages(evenPages);
// Remove all pages except first and last:
var middlePages = Enumerable.Range(1, pdf.PageCount - 2);
pdf.RemovePages(middlePages);
// Remove blank pages (detected earlier):
List<int> blankPages = DetectBlankPages(pdf);
if (blankPages.Any()) {
pdf.RemovePages(blankPages.OrderByDescending(x => x));
Console.WriteLine($"Removed {blankPages.Count} blank pages");
}Remove in descending order to avoid index shifting issues
All indexes removed in single operation
Declaration
public PdfDocument RemovePages(IEnumerable<int> PageIndexes)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexes | A list of pages indexes to remove. |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument object, allowing for a 'fluent' (LINQ like) chained in-line code style |
RemovePages(Int32, Int32)
Removes a range of pages from the PDF. Delete consecutive pages efficiently, perfect for removing chapters or sections.
// Remove pages 2-5 (indexes 1-4):
var pdf = PdfDocument.FromFile("book.pdf");
pdf.RemovePages(1, 4);
pdf.SaveAs("chapter_removed.pdf");
// Remove first 10 pages:
pdf.RemovePages(0, 9);
// Remove last 5 pages:
int lastIndex = pdf.PageCount - 1;
pdf.RemovePages(lastIndex - 4, lastIndex);
// Keep only middle section (remove beginning and end):
var copy1 = PdfDocument.FromFile("doc.pdf");
copy1.RemovePages(0, 4); // Remove first 5 pages
var copy2 = PdfDocument.FromFile("doc.pdf");
copy2.RemovePages(copy2.PageCount - 5, copy2.PageCount - 1); // Last 5
// Extract chapter by removing everything else:
var chapter3Start = 20; // Page 21
var chapter3End = 35; // Page 36
pdf.RemovePages(chapter3End + 1, pdf.PageCount - 1); // Remove after
pdf.RemovePages(0, chapter3Start - 1); // Remove beforeInclusive range: both start and end indexes are removed
Ensure EndIndex >= StartIndex
Declaration
public PdfDocument RemovePages(int StartIndex, int EndIndex)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | StartIndex | The start index. Note: Page 1 has index 0 |
| System.Int32 | EndIndex | The end index. Note: The last page has index |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument object, allowing for a 'fluent' (LINQ like) chained in-line code style |
RemoveSignatures()
Removes all digital signatures from the PDF document, making it unsigned. Use this before re-signing or when signatures are no longer needed.
// Remove all signatures from a signed PDF:
var pdf = PdfDocument.FromFile("signed-contract.pdf");
pdf.RemoveSignatures();
pdf.SaveAs("unsigned-contract.pdf");
// Remove and re-sign with new certificate:
pdf.RemoveSignatures();
pdf.SignWithFile("new-cert.pfx", "password");
pdf.SaveAs("re-signed-contract.pdf");Useful for updating expired signatures or changing signers
This permanently removes all signatures - save a copy first if needed
See: https://ironpdf.com/how-to/digital-signatures/
Declaration
public void RemoveSignatures()
ReplaceTextOnAllPages(String, String, PdfFont, Nullable<Single>)
Replaces text throughout the entire PDF using a PdfFont object for precise control. Ideal for maintaining font consistency in global document updates.
// Replace with specific font from PDF:
var font = pdf.Fonts.First(f => f.Name == "Arial");
pdf.ReplaceTextOnAllPages("old", "new", font, 12);
// Global update preserving original formatting:
pdf.ReplaceTextOnAllPages("2023", "2024");
// Use embedded custom font throughout:
var customFont = pdf.Fonts.Add("corporate.ttf");
pdf.ReplaceTextOnAllPages("Generic Corp", "Specific Inc",
customFont, 14);
// Replace with existing document font:
var titleFont = pdf.Fonts.First(f => f.IsEmbedded);
pdf.ReplaceTextOnAllPages("DRAFT", "FINAL", titleFont, 24);Null parameters preserve original text formatting
Affects every occurrence on every page
See: https://ironpdf.com/how-to/find-replace-text/
Declaration
public void ReplaceTextOnAllPages(string OldText, string NewText, PdfFont CustomFont = null, Nullable<float> CustomFontSize = null)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | OldText | Text to find throughout document |
| System.String | NewText | Replacement text |
| PdfFont | CustomFont | PdfFont object (null keeps original) |
| System.Nullable<System.Single> | CustomFontSize | Font size (null keeps original) |
ReplaceTextOnAllPages(String, String, String, Nullable<Single>)
Globally replaces text across all pages: pdf.ReplaceTextOnAllPages("2024", "2025", "Arial", 12) Essential for updating dates, versions, prices, or any repeating text throughout documents. Font must be a system font (Arial, Times New Roman) or previously embedded in the PDF.
Declaration
public void ReplaceTextOnAllPages(string OldText, string NewText, string CustomFontName, Nullable<float> CustomFontSize = null)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | OldText | The old text to be replaced. |
| System.String | NewText | The new text to replace the old text with. |
| System.String | CustomFontName | The name of the custom font for the new text. Must be a system font or added to the document using Fonts.Add(). |
| System.Nullable<System.Single> | CustomFontSize | The font size of the new text (optional). |
Remarks
Text replacement is case-sensitive and exact match. For template systems, consider using unique markers like {{customer_name}} or %INVOICE_DATE% to avoid unintended replacements.
using IronPdf;
// Update year in financial reports
var pdf = PdfDocument.FromFile("annual-report-2024.pdf");
pdf.ReplaceTextOnAllPages("2024", "2025", "Arial", 12);
pdf.ReplaceTextOnAllPages("FY2024", "FY2025", "Arial Bold", 14);
pdf.SaveAs("annual-report-2025.pdf");
// Template personalization
var template = PdfDocument.FromFile("invoice-template.pdf");
template.ReplaceTextOnAllPages("{{customer_name}}", "Acme Corp", "Helvetica", 11);
template.ReplaceTextOnAllPages("{{invoice_date}}", DateTime.Today.ToString("MM/dd/yyyy"), "Helvetica", 10);
template.ReplaceTextOnAllPages("{{amount_due}}", "$1,234.56", "Helvetica-Bold", 12);
template.SaveAs($"invoice-{DateTime.Now:yyyyMMdd}.pdf");
// Batch update footer text
foreach (var file in Directory.GetFiles(@"C:\Reports", "*.pdf"))
{
var doc = PdfDocument.FromFile(file);
doc.ReplaceTextOnAllPages("© 2024 OldCompany", "© 2025 NewCompany LLC", "Arial", 8);
doc.SaveAs(file); // Overwrite original
doc.Dispose();
}
See Also
ReplaceTextOnPage(Int32, String, String, PdfFont, Nullable<Single>)
Replaces text on a specific page using a PdfFont object for precise font control. Ideal for using embedded fonts or maintaining font consistency across replacements.
// Replace with existing PDF font:
var font = pdf.Fonts[0];
pdf.ReplaceTextOnPage(0, "old", "new", font, 12);
// Replace keeping original font and size:
pdf.ReplaceTextOnPage(0, "DRAFT", "FINAL");
// Use custom embedded font:
var customFont = pdf.Fonts.Add("CustomFont.ttf");
pdf.ReplaceTextOnPage(1, "[SIGNATURE]", "Jane Doe",
customFont, 14);
// Replace with specific font from collection:
var helvetica = pdf.Fonts.First(f => f.Name.Contains("Helvetica"));
pdf.ReplaceTextOnPage(2, "Lorem", "Ipsum", helvetica, 10);Null font/size preserves original formatting
Font must exist in PDF or be added first
See: https://ironpdf.com/how-to/find-replace-text/
Declaration
public void ReplaceTextOnPage(int PageIndex, string OldText, string NewText, PdfFont CustomFont = null, Nullable<float> CustomFontSize = null)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | PageIndex | Zero-based page index to search |
| System.String | OldText | Exact text to find and replace |
| System.String | NewText | Replacement text |
| PdfFont | CustomFont | PdfFont object (null keeps original) |
| System.Nullable<System.Single> | CustomFontSize | Font size (null keeps original) |
ReplaceTextOnPage(Int32, String, String, String, Nullable<Single>)
Replaces text on a specific page with custom font styling by font name. Perfect for updating templates, correcting errors, or personalizing documents.
// Replace placeholder with actual name:
pdf.ReplaceTextOnPage(0, "[NAME]", "John Smith", "Arial", 12);
// Update date with custom font:
pdf.ReplaceTextOnPage(0, "[DATE]", DateTime.Now.ToString(),
"Times New Roman", 10);
// Replace with system font, keeping original size:
pdf.ReplaceTextOnPage(2, "DRAFT", "FINAL", "Helvetica");
// Use custom embedded font:
pdf.Fonts.Add("CustomFont.ttf");
pdf.ReplaceTextOnPage(0, "old", "new", "CustomFont", 14);Font must be system font or added via Fonts.Add()
Case-sensitive replacement - exact match required
See: https://ironpdf.com/how-to/find-replace-text/
Declaration
public void ReplaceTextOnPage(int PageIndex, string OldText, string NewText, string CustomFontName, Nullable<float> CustomFontSize = null)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | PageIndex | Zero-based page index to search |
| System.String | OldText | Exact text to find and replace |
| System.String | NewText | Replacement text |
| System.String | CustomFontName | Font name (system or embedded) |
| System.Nullable<System.Single> | CustomFontSize | Optional font size (null keeps original) |
ReplaceTextOnPages(Int32[], String, String, PdfFont, Nullable<Single>)
Replaces text across multiple pages using a PdfFont object. Provides precise font control for batch replacements and document updates.
// Replace with embedded font on selected pages:
var font = pdf.Fonts.Add("corporate-font.ttf");
var pages = new[] { 0, 1, 5, 10 };
pdf.ReplaceTextOnPages(pages, "old brand", "new brand",
font, 12);
// Update prices on product pages:
var productPages = new[] { 3, 4, 5, 6, 7 };
var priceFont = pdf.Fonts.First(f => f.Name == "Arial");
pdf.ReplaceTextOnPages(productPages, "$99", "$89",
priceFont, 14);
// Replace preserving original formatting:
var allPages = Enumerable.Range(0, pdf.PageCount).ToArray();
pdf.ReplaceTextOnPages(allPages, "2023", "2024");Null font/size preserves original formatting
Processes pages sequentially for consistency
See: https://ironpdf.com/how-to/find-replace-text/
Declaration
public void ReplaceTextOnPages(int[] PageIndices, string OldText, string NewText, PdfFont CustomFont = null, Nullable<float> CustomFontSize = null)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32[] | PageIndices | Array of zero-based page indexes |
| System.String | OldText | Text to find and replace |
| System.String | NewText | Replacement text |
| PdfFont | CustomFont | PdfFont object (null keeps original) |
| System.Nullable<System.Single> | CustomFontSize | Font size (null keeps original) |
ReplaceTextOnPages(Int32[], String, String, String, Nullable<Single>)
Replaces text across multiple pages using a font specified by name. Essential for batch updates, template processing, and document personalization.
// Replace on specific pages:
var pages = new[] { 0, 2, 4, 6 };
pdf.ReplaceTextOnPages(pages, "[COMPANY]", "Acme Corp",
"Arial", 14);
// Update footer on all even pages:
var evenPages = Enumerable.Range(0, pdf.PageCount)
.Where(i => i % 2 == 0).ToArray();
pdf.ReplaceTextOnPages(evenPages, "2023", "2024",
"Helvetica", 8);
// Replace headers on first 5 pages:
var headerPages = Enumerable.Range(0, 5).ToArray();
pdf.ReplaceTextOnPages(headerPages, "Draft", "Final",
"Times New Roman", 16);Efficient for batch replacements across pages
All occurrences on specified pages are replaced
See: https://ironpdf.com/how-to/find-replace-text/
Declaration
public void ReplaceTextOnPages(int[] PageIndices, string OldText, string NewText, string CustomFontName, Nullable<float> CustomFontSize = null)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32[] | PageIndices | Array of zero-based page indexes |
| System.String | OldText | Text to find and replace |
| System.String | NewText | Replacement text |
| System.String | CustomFontName | Font name (system or embedded) |
| System.Nullable<System.Single> | CustomFontSize | Optional font size |
Resize(Length, Length, IEnumerable<Int32>)
Resizes the PdfDocument to the specified width, height, and desired measurement unit. This will scale existing page contents to fit the new page dimensions, this may cause distortion in cases where Width-to-height ratio is different.
// Using Length objects for precise control:
var width = new Length { Value = 210, Unit = MeasurementUnit.Millimeter };
var height = new Length { Value = 297, Unit = MeasurementUnit.Millimeter };
pdf.Resize(width, height); // A4 size
// Mix units for complex requirements:
var widthInches = new Length { Value = 8.5, Unit = MeasurementUnit.Inch };
var heightMm = new Length { Value = 297, Unit = MeasurementUnit.Millimeter };
pdf.Resize(widthInches, heightMm);
// Scale by percentage:
var scale75 = new Length { Value = 75, Unit = MeasurementUnit.Percentage };
pdf.Resize(scale75, scale75); // Reduce to 75% of original
// Resize selected pages only:
var posterWidth = new Length { Value = 24, Unit = MeasurementUnit.Inch };
var posterHeight = new Length { Value = 36, Unit = MeasurementUnit.Inch };
pdf.Resize(posterWidth, posterHeight, new[] { 0 }); // First page onlyLength objects allow mixing different units
Percentage units scale relative to original size
Declaration
public void Resize(Length PageWidth, Length PageHeight, IEnumerable<int> Pages = null)
Parameters
| Type | Name | Description |
|---|---|---|
| Length | PageWidth | The width of the resized PdfDocument. |
| Length | PageHeight | The height of the resized PdfDocument. |
| System.Collections.Generic.IEnumerable<System.Int32> | Pages | The page(s) to resize, if not specified all pages will be resized |
Resize(PdfPaperSize, IEnumerable<Int32>)
Resizes the PDF document to the specified paper size. Scales content to fit standard paper formats like Letter, A4, Legal, etc.
// Resize entire document to A4:
var pdf = PdfDocument.FromFile("report.pdf");
pdf.Resize(PdfPaperSize.A4);
pdf.SaveAs("report_a4.pdf");
// Resize for US Letter printing:
pdf.Resize(PdfPaperSize.Letter);
// Resize only specific pages to Legal:
pdf.Resize(PdfPaperSize.Legal, new[] { 5, 10, 15 });
// Common paper sizes:
pdf.Resize(PdfPaperSize.A3); // 297 × 420 mm
pdf.Resize(PdfPaperSize.A4); // 210 × 297 mm
pdf.Resize(PdfPaperSize.Letter); // 8.5 × 11 inches
pdf.Resize(PdfPaperSize.Legal); // 8.5 × 14 inches
pdf.Resize(PdfPaperSize.Tabloid); // 11 × 17 inchesContent is scaled to fit - may distort if aspect ratio changes
Text remains selectable after resize
Declaration
public void Resize(PdfPaperSize PdfPaperSize, IEnumerable<int> Pages = null)
Parameters
| Type | Name | Description |
|---|---|---|
| PdfPaperSize | PdfPaperSize | The size to resize the PDF document to. |
| System.Collections.Generic.IEnumerable<System.Int32> | Pages | The page(s) to resize, if not specified all pages will be resized |
Remarks
The available paper sizes are defined in the PdfPaperSize enumeration.
Resize(Double, Double, MeasurementUnit, IEnumerable<Int32>)
Resizes the PdfDocument to the specified width, height, and desired measurement unit. This will scale existing page contents to fit the new page dimensions, this may cause distortion in cases where Width-to-height ratio is different.
// Resize to custom dimensions in inches:
pdf.Resize(8.5, 11, MeasurementUnit.Inch); // US Letter
// Resize to square format in millimeters:
pdf.Resize(200, 200, MeasurementUnit.Millimeter);
// Resize to poster size in centimeters:
pdf.Resize(60, 90, MeasurementUnit.Centimeter);
// Resize specific pages by percentage:
pdf.Resize(50, 50, MeasurementUnit.Percentage, new[] { 0, 1, 2 });
// Preserve aspect ratio (calculate proportionally):
var page = pdf.GetPage(0);
double ratio = page.Width / page.Height;
double newHeight = 297; // A4 height in mm
double newWidth = newHeight * ratio;
pdf.Resize(newWidth, newHeight, MeasurementUnit.Millimeter);Use Percentage to scale relative to current size
May distort if aspect ratio changes
Declaration
public void Resize(double PageWidth, double PageHeight, MeasurementUnit MeasurementUnit, IEnumerable<int> Pages = null)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Double | PageWidth | The width of the resized PdfDocument. |
| System.Double | PageHeight | The height of the resized PdfDocument. |
| MeasurementUnit | MeasurementUnit | The measurement unit for the width and height values. |
| System.Collections.Generic.IEnumerable<System.Int32> | Pages | The page(s) to resize, if not specified all pages will be resized |
ResizePage(Int32, Double, Double, MeasurementUnit)
Declaration
public void ResizePage(int PageIndex, double PageWidth, double PageHeight, MeasurementUnit Units)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | PageIndex | |
| System.Double | PageWidth | |
| System.Double | PageHeight | |
| MeasurementUnit | Units |
SaveAs(String, Boolean)
Saves the PDF document to disk: pdf.SaveAs("invoice.pdf") The final step in most PDF workflows. Overwrites existing files by default. Set SaveAsRevision=true for incremental saves that preserve document history.
Declaration
public PdfDocument SaveAs(string FileName, bool SaveAsRevision = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileName | Full path where the PDF will be saved (e.g., C:\Documents\invoice.pdf) |
| System.Boolean | SaveAsRevision | False: Standard save (default). True: Incremental save preserving document history |
Returns
| Type | Description |
|---|---|
| PdfDocument | The PdfDocument instance for method chaining. If SaveAsRevision=true, returns a new revision. |
Remarks
SaveAs is the most common way to persist your PDF to disk after generation and manipulation. The file is written atomically - either fully succeeds or fails with no partial writes.
using IronPdf;
// Simple save
var pdf = renderer.RenderHtmlAsPdf("
Invoice
");
pdf.SaveAs(@"C:\Invoices\invoice.pdf");
// Save with error handling
try
{
pdf.SaveAs(@"C:\Reports\report.pdf");
}
catch (IOException ex)
{
Console.WriteLine($"File may be open: {ex.Message}");
}
// Incremental save (preserves history)
pdf.SaveAs("document.pdf", SaveAsRevision: true);
Exceptions
| Type | Condition |
|---|---|
| System.IO.IOException | File is locked or inaccessible. Common when PDF is open in viewer. |
| System.UnauthorizedAccessException | Insufficient permissions to write to the specified path. |
See Also
SaveAsHtml(String, Boolean, String, IEnumerable<Int32>, HtmlFormatOptions)
Converts the PDF document to an HTML document and saves it to the provided file path with optional custom formatting. Enables PDF content to be displayed in web browsers with full text selection and searchability.
// Basic conversion to HTML:
pdf.SaveAsHtml("output.html");
// Full-width responsive HTML:
pdf.SaveAsHtml("responsive.html", fullContentWidth: true);
// Convert specific pages with custom title:
pdf.SaveAsHtml("summary.html",
title: "Executive Summary",
pageIndexes: new[] { 0, 1, 2 });
// With custom formatting options:
var formatOptions = new HtmlFormatOptions {
BackgroundColor = "#f0f0f0",
TextColor = "#333333",
FontFamily = "Arial, sans-serif"
};
pdf.SaveAsHtml("styled.html",
htmlFormatOptions: formatOptions);Preserves text selection and searchability in browsers
Complex layouts may require adjustment for optimal display
See: https://ironpdf.com/how-to/pdf-to-html-conversion/
Declaration
public void SaveAsHtml(string filePath, bool fullContentWidth = false, string title = "", IEnumerable<int> pageIndexes = null, HtmlFormatOptions htmlFormatOptions = null)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | filePath | The file path where the HTML output will be saved. |
| System.Boolean | fullContentWidth | If set to true, the PDF content in the HTML will be set to full width for responsive display. |
| System.String | title | Optional title to be used in the HTML output. If not provided, the title from PDF metadata will be used. |
| System.Collections.Generic.IEnumerable<System.Int32> | pageIndexes | Optional set of page indexes to include in the HTML output (0-based). If not provided, all pages will be included. |
| HtmlFormatOptions | htmlFormatOptions | Optional HTML formatting options for styling. If not provided, default formatting will be used. |
Remarks
HTML conversion features: • Maintains text as selectable HTML elements • Preserves document structure and formatting • Supports responsive full-width layout • Enables browser-based text search (Ctrl+F) • Compatible with all modern browsers • Can be styled with custom CSS
The generated HTML uses embedded SVG for graphics and positioned text elements to maintain layout fidelity.
Examples
// Create web-viewable version of PDF report
var pdf = PdfDocument.FromFile("annual-report.pdf");
// Convert to responsive HTML with custom styling
var options = new HtmlFormatOptions {
BackgroundColor = "white",
PageMargin = "20px",
FontSize = "16px"
};
// Save full document
pdf.SaveAsHtml("report-full.html",
fullContentWidth: true,
title: "2024 Annual Report",
htmlFormatOptions: options);
// Save executive summary (first 5 pages)
pdf.SaveAsHtml("report-summary.html",
title: "Executive Summary",
pageIndexes: Enumerable.Range(0, 5));
SaveAsJson(Byte[], String, String)
Saves a PDF byte array as a JSON file.
------------------------------------------------
Usage:
PdfDocument.SaveAsJson(pdfBytes, "output.json");
------------------------------------------------
Declaration
public static void SaveAsJson(byte[] PdfBytes, string OutputPath, string Password = "")
Parameters
| Type | Name | Description |
|---|---|---|
| System.Byte[] | PdfBytes | byte array of the PDF file |
| System.String | OutputPath | Path where the JSON file will be saved in the file system |
| System.String | Password | password to open the file |
Remarks
Important Notes:
Performance: This method is optimized for large PDFs and streams output to file.
Security: Always validate file paths to prevent directory traversal vulnerabilities.
Related Documentation:
How-To Guide: Converting PDF to JSON
API Reference: Full API Documentation
Exceptions
| Type | Condition |
|---|---|
| System.ArgumentException | Thrown when the PdfBytes array is null or empty. |
| System.ArgumentException | Thrown when the OutputPath is null, empty, or whitespace. |
SaveAsJson(Stream, String, String)
Saves a PDF stream as a JSON file.
------------------------------------------------
Usage:
PdfDocument.SaveAsJson(pdfStream, "output.json");
------------------------------------------------
Declaration
public static void SaveAsJson(Stream Stream, string OutputPath, string Password = "")
Parameters
| Type | Name | Description |
|---|---|---|
| System.IO.Stream | Stream | Stream of the PDF file |
| System.String | OutputPath | Path where the JSON file will be saved in the file system |
| System.String | Password | password to open the file |
Remarks
Important Notes:
Performance: This method is optimized for large PDFs and streams output to file.
Security: Always validate file paths to prevent directory traversal vulnerabilities.
Related Documentation:
How-To Guide: Converting PDF to JSON
API Reference: Full API Documentation
Exceptions
| Type | Condition |
|---|---|
| System.ArgumentNullException | Thrown when the input Stream is null. |
| System.ArgumentException | Thrown when the input Stream is not readable. |
| System.ArgumentException | Thrown when the OutputPath is null, empty, or whitespace. |
SaveAsJson(String)
Saves the current PDF document as a JSON file.
------------------------------------------------
Usage:
pdf.SaveAsJson("output.json");
------------------------------------------------
Declaration
public void SaveAsJson(string OutputPath)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | OutputPath | Path where the JSON file will be saved in the file system. |
Remarks
Important Notes:
Performance: This method is optimized for large PDFs and streams output to file.
Security: Always validate file paths to prevent directory traversal vulnerabilities.
Related Documentation:
How-To Guide: Converting PDF to JSON
API Reference: Full API Documentation
Exceptions
| Type | Condition |
|---|---|
| System.ArgumentException | Thrown when the OutputPath is null, empty, or whitespace. |
SaveAsJsonAsync(String)
Asynchronously saves the current PDF document as a JSON file.
Declaration
public Task SaveAsJsonAsync(string OutputPath)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | OutputPath | Path where the JSON file will be saved. |
Returns
| Type | Description |
|---|---|
| System.Threading.Tasks.Task |
SaveAsLinearized(Byte[], String, String)
Create a linearized file from pdf byte array.
------------------------------------------------
Usage:
PdfDocument.SaveAsLinearized(pdfBytes, "my-pdf-file-linearized.pdf", "");
------------------------------------------------
Declaration
public static void SaveAsLinearized(byte[] PdfBytes, string OutputPath, string Password = "")
Parameters
| Type | Name | Description |
|---|---|---|
| System.Byte[] | PdfBytes | byte arrray of the Pdf file |
| System.String | OutputPath | Path of the file where it will be saved in file system |
| System.String | Password | password to open the file |
Remarks
Important Notes:
Performance: This method is highly performant.
Security: Always validate file paths to prevent directory traversal vulnerabilities.
Related Documentation:
How-To Guide: Getting Started with PDF Linearization
API Reference: Full API Documentation
Exceptions
| Type | Condition |
|---|---|
| System.ArgumentException | Thrown when the PdfBytes array is null or empty. |
| System.ArgumentException | Thrown when the OutputPath is null, empty, or whitespace. |
SaveAsLinearized(Stream, String, String)
Create a linearized file from pdf stream.
------------------------------------------------
Usage:
PdfDocument.SaveAsLinearized(pdfStream, "my-pdf-file-linearized.pdf", "mypassword");
------------------------------------------------
Declaration
public static void SaveAsLinearized(Stream Stream, string OutputPath, string Password = "")
Parameters
| Type | Name | Description |
|---|---|---|
| System.IO.Stream | Stream | Stream of the PDF file |
| System.String | OutputPath | Path of the file where it will be saved in file system |
| System.String | Password | password to open the file |
Remarks
Important Notes:
Performance: This method is highly performant.
Security: Always validate file paths to prevent directory traversal vulnerabilities.
Related Documentation:
How-To Guide: Getting Started with PDF Linearization
API Reference: Full API Documentation
Exceptions
| Type | Condition |
|---|---|
| System.ArgumentNullException | Thrown when the input Stream is null. |
| System.ArgumentException | Thrown when the input Stream is not readable. |
| System.ArgumentException | Thrown when the OutputPath is null, empty, or whitespace. |
SaveAsLinearized(String)
Create a linearized file from the current pdf document.
------------------------------------------------
Usage:
pdf.SaveAsLinearized("my-pdf-file-linearized.pdf");
------------------------------------------------
Declaration
public void SaveAsLinearized(string OutputPath)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | OutputPath | Path of the file where it will be saved in file system. |
Remarks
Important Notes:
Performance: This method is highly performant.
Security: Always validate file paths to prevent directory traversal vulnerabilities.
Related Documentation:
How-To Guide: Getting Started with PDF Linearization
API Reference: Full API Documentation
Exceptions
| Type | Condition |
|---|---|
| System.ArgumentException | Thrown when the OutputPath is null, empty, or whitespace. |
SaveAsPdfA(String, PdfAVersions, String)
Saves PDF as PDF/A compliant file for archival purposes. Converts and saves in one operation for convenience.
// Save as PDF/A-3B (supports attachments):
pdf.SaveAsPdfA("archive.pdf", PdfAVersions.PdfA3b);
// Save as PDF/A-1B (basic archival):
pdf.SaveAsPdfA("legacy.pdf", PdfAVersions.PdfA1b);Non-embedded fonts converted to Helvetica for compliance
See: https://ironpdf.com/how-to/pdfa/
Declaration
public PdfDocument SaveAsPdfA(string FileName, PdfAVersions PdfAVersion, string CustomICC = null)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileName | Output file path for PDF/A document |
| PdfAVersions | PdfAVersion | PDF/A compliance level (default: PdfA3b) |
| System.String | CustomICC | Optional ICC color profile path |
Returns
| Type | Description |
|---|---|
| PdfDocument | This PdfDocument after saving |
Remarks
Supports embedding .xml, .pdf, and .png files in PDF/A-3
SaveAsPdfA(String, IEnumerable<EmbedFileByte>, PdfAVersions, String)
Saves the PdfDocument as a PDF/A Compliant PDF File with embedded files
For more information see the: IronPDF PDFA How-To Guide
Note: All of non-embedded fonts are embedded as Helvetica Font which is one of 14 standard fonts provided by Adobe.
Declaration
public PdfDocument SaveAsPdfA(string FileName, IEnumerable<EmbedFileByte> EmbedFileBytes, PdfAVersions PdfAVersion, string CustomICC = null)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileName | Target file path |
| System.Collections.Generic.IEnumerable<EmbedFileByte> | EmbedFileBytes | Collection of byte[] and their file type of embedding file with type of that file to the PDF/A document |
| PdfAVersions | PdfAVersion | (Optional) PDF/A compliant version, default is PDF/A-3B (ISO 19005-3) |
| System.String | CustomICC | (Optional) Custom color profile file path |
Returns
| Type | Description |
|---|---|
| PdfDocument |
Remarks
currently only support embedding 3 types of file; .xml, .pdf, and .png
SaveAsPdfA(String, IEnumerable<EmbedFilePath>, PdfAVersions, String)
Saves the PdfDocument as a PDF/A Compliant PDF File with embedded files
For more information see the: IronPDF PDFA How-To Guide
Note: All of non-embedded fonts are embedded as Helvetica Font which is one of 14 standard fonts provided by Adobe.
Declaration
public PdfDocument SaveAsPdfA(string FileName, IEnumerable<EmbedFilePath> EmbedFilePaths, PdfAVersions PdfAVersion, string CustomICC = null)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileName | Target file path |
| System.Collections.Generic.IEnumerable<EmbedFilePath> | EmbedFilePaths | Collection of path to embedding file to the PDF/A document |
| PdfAVersions | PdfAVersion | (Optional) PDF/A compliant version, default is PDF/A-3B (ISO 19005-3) |
| System.String | CustomICC | (Optional) Custom color profile file path |
Returns
| Type | Description |
|---|---|
| PdfDocument |
Remarks
currently only support embedding 3 types of file; .xml, .pdf, and .png
Exceptions
| Type | Condition |
|---|---|
| System.Exception |
SaveAsPdfA(String, IEnumerable<EmbedFileStream>, PdfAVersions, String)
Saves the PdfDocument as a PDF/A Compliant PDF File with embedded files
For more information see the: IronPDF PDFA How-To Guide
Note: All of non-embedded fonts are embedded as Helvetica Font which is one of 14 standard fonts provided by Adobe.
Declaration
public PdfDocument SaveAsPdfA(string FileName, IEnumerable<EmbedFileStream> EmbedFileStreams, PdfAVersions PdfAVersion, string CustomICC = null)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileName | Target file path |
| System.Collections.Generic.IEnumerable<EmbedFileStream> | EmbedFileStreams | Collection of Stream and their file type of embedding file with type of that file to the PDF/A document |
| PdfAVersions | PdfAVersion | (Optional) PDF/A compliant version, default is PDF/A-3B (ISO 19005-3) |
| System.String | CustomICC | (Optional) Custom color profile file path |
Returns
| Type | Description |
|---|---|
| PdfDocument |
Remarks
currently only support embedding 3 types of file; .xml, .pdf, and .png
SaveAsPdfA(String, IEnumerable<String>, PdfAVersions, String)
Saves the PdfDocument as a PDF/A Compliant PDF File with embedded files using the default EmbedFileConfiguration
For more information see the: IronPDF PDFA How-To Guide
Note: All of non-embedded fonts are embedded as Helvetica Font which is one of 14 standard fonts provided by Adobe.
Declaration
public PdfDocument SaveAsPdfA(string FileName, IEnumerable<string> EmbedFilePaths, PdfAVersions PdfAVersion, string CustomICC = null)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileName | Target file path |
| System.Collections.Generic.IEnumerable<System.String> | EmbedFilePaths | Collection of string path to embedding file to the PDF/A document |
| PdfAVersions | PdfAVersion | (Optional) PDF/A compliant version, default is PDF/A-3B (ISO 19005-3) |
| System.String | CustomICC | (Optional) Custom color profile file path |
Returns
| Type | Description |
|---|---|
| PdfDocument |
Remarks
currently only support embedding 3 types of file; .xml, .pdf, and .png
To use custom EmbedFileConfiguration, using a collection of EmbedFilePath, EmbedFileByte, or EmbedFileStream instead a collection of string path
Exceptions
| Type | Condition |
|---|---|
| System.Exception |
SaveAsPdfUA(String, PdfUAVersions, NaturalLanguages)
Saves PDF as PDF/UA compliant file for Section 508 accessibility. Converts and saves in one operation for convenience.
// Save as accessible PDF:
pdf.SaveAsPdfUA("accessible.pdf");
// With language specification:
pdf.SaveAsPdfUA("accessible_es.pdf", NaturalLanguage: NaturalLanguages.Spanish);W3C WCAG compliant - fully standards compliant
Non-embedded fonts converted to Helvetica for compliance
See: https://ironpdf.com/how-to/pdfua/
Declaration
public PdfDocument SaveAsPdfUA(string FileName, PdfUAVersions PdfUAVersion, NaturalLanguages NaturalLanguage)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileName | Output file path for accessible PDF |
| PdfUAVersions | PdfUAVersion | PDF/UA compliance level (default: PdfUA1) |
| NaturalLanguages | NaturalLanguage | Document language for screen readers |
Returns
| Type | Description |
|---|---|
| PdfDocument | This PdfDocument after saving as accessible format |
Remarks
PDF/UA-2 Limitation: PDF/UA-2 conversion may not work correctly with encrypted PDFs.
SaveAsRevision(String)
Saves changes by APPENDING to PDF file instead of overwriting: pdf.SaveAsRevision("doc.pdf") Revisions preserve document history like git commits - original PDF remains intact inside file. Required for: digital signatures (keeps valid), audit trails, legal compliance. File grows with each revision: [Original][Changes1][Changes2] all preserved.
Declaration
public PdfDocument SaveAsRevision(string FileName = null)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileName | Optional file path |
Returns
| Type | Description |
|---|---|
| PdfDocument | The revised PdfDocument, ready for a new set of changes |
SaveAsSvg(String)
Converts the PDF document to SVG format and saves it to the provided file path. Creates one SVG file per page, perfect for web display and vector graphics editing.
// Convert all pages to SVG files:
pdf.SaveAsSvg("output_page_*.svg");
// Creates: output_page_1.svg, output_page_2.svg, etc.
// Save to specific directory:
pdf.SaveAsSvg(@"C:\images\pdf_page_*.svg");
// With custom naming pattern:
pdf.SaveAsSvg("invoice_2024_page_*.svg");
// Creates: invoice_2024_page_001.svg, etc.SVG preserves vector graphics for infinite scalability
The asterisk (*) is replaced with page numbers
See: https://ironpdf.com/how-to/pdf-to-svg-conversion/
Declaration
public void SaveAsSvg(string fileNamePattern)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | fileNamePattern | A full or partial file path for the output files containing an asterisk (). E.g. C:\images\pdf_page_.svg |
Remarks
SVG conversion benefits: • Maintains vector quality at any size • Perfect for web display (scales with CSS) • Editable in vector graphics programs • Smaller file size than raster images for simple graphics • Preserves text as selectable elements
The asterisk in the pattern is automatically replaced with page numbers, zero-padded based on total page count (e.g., 001, 002 for 100+ pages).
Examples
// Convert PDF to SVG for web display
var pdf = PdfDocument.FromFile("presentation.pdf");
// Save all pages as SVG
pdf.SaveAsSvg("slides/slide_*.svg");
// Use in HTML:
// <img src="slides/slide_001.svg" alt="Slide 1" />
// <object data="slides/slide_002.svg" type="image/svg+xml"></object>
SetAllPageRotations(PdfPageRotation)
Set rotation degree to all pages of the PdfDocument by a specified degree. Perfect for correcting scanned documents or changing orientation for printing.
// Fix sideways scanned documents:
var pdf = PdfDocument.FromFile("scanned_sideways.pdf");
pdf.SetAllPageRotations(PdfPageRotation.Clockwise90);
pdf.SaveAs("corrected.pdf");
// Convert to landscape for wide tables:
pdf.SetAllPageRotations(PdfPageRotation.Clockwise270);
// Reset all pages to normal:
pdf.SetAllPageRotations(PdfPageRotation.None);
// Flip upside down (180°):
pdf.SetAllPageRotations(PdfPageRotation.Clockwise180);Rotation is visual only - doesn't affect text extraction
Some PDF viewers may not respect rotation metadata
Declaration
public void SetAllPageRotations(PdfPageRotation Rotation)
Parameters
| Type | Name | Description |
|---|---|---|
| PdfPageRotation | Rotation | Degrees of rotation |
SetPageRotation(Int32, PdfPageRotation)
Set rotation degree to one page of the PdfDocument by a specified degree. Ideal for fixing individual pages without affecting the entire document.
// Rotate only the cover page:
pdf.SetPageRotation(0, PdfPageRotation.Clockwise90);
// Fix upside-down signature page:
int lastPage = pdf.PageCount - 1;
pdf.SetPageRotation(lastPage, PdfPageRotation.Clockwise180);
// Landscape chart on page 5:
pdf.SetPageRotation(4, PdfPageRotation.Clockwise270);
// Reset page 3 to normal:
pdf.SetPageRotation(2, PdfPageRotation.None);Remember: Page 1 = Index 0
Common: Clockwise90 for landscape view
Declaration
public void SetPageRotation(int PageIndex, PdfPageRotation Rotation)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | PageIndex | Index of the page to rotate. PageIndex is a 'Zero based' page number, the first page being 0. |
| PdfPageRotation | Rotation | Degrees of rotation |
SetPageRotations(IEnumerable<Int32>, PdfPageRotation)
Set rotation degree to selected pages of the PdfDocument by a specified degree. Efficiently rotate multiple specific pages in one operation.
// Rotate odd pages only (for duplex printing issues):
var oddPages = Enumerable.Range(0, pdf.PageCount)
.Where(x => x % 2 == 0); // Even indexes = odd pages
pdf.SetPageRotations(oddPages, PdfPageRotation.Clockwise180);
// Rotate specific chapter pages:
pdf.SetPageRotations(new[] { 5, 6, 7, 8, 9 }, PdfPageRotation.Clockwise90);
// Fix scanned pages 10-15:
var pagesToFix = Enumerable.Range(9, 6); // Pages 10-15
pdf.SetPageRotations(pagesToFix, PdfPageRotation.Clockwise270);
// Rotate all charts and graphs:
List<int> chartPages = new List<int> { 3, 7, 12, 18, 24 };
pdf.SetPageRotations(chartPages, PdfPageRotation.Clockwise90);Batch operations are more efficient than individual rotations
Page indexes are zero-based (Page 1 = Index 0)
Declaration
public void SetPageRotations(IEnumerable<int> PageIndexes, PdfPageRotation Rotation)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexes | Indexes of the pages to rotate in an IEnumerable, list or array. PageIndex is a 'Zero based' page number, the first page being 0. |
| PdfPageRotation | Rotation | Degrees of rotation |
Sign(PdfSignature, SignaturePermissions)
Signs PDF with advanced PdfSignature object for full control over signature appearance and behavior. Perfect for custom signature fields, visible signatures, and complex signing scenarios.
// Create signature with custom appearance:
var signature = new PdfSignature("cert.pfx", "password");
signature.SignatureImage = new SignatureImage("signature.png", 0, 100, 100);
pdf.Sign(signature);
pdf.SaveAs("signed.pdf");
// Sign with form filling still allowed:
var sig = new PdfSignature("cert.pfx", "pass");
pdf.Sign(sig, SignaturePermissions.FormFillingAllowed);
// Multiple signatures with different permissions:
var authorSig = new PdfSignature("author.pfx", "pass1");
var approverSig = new PdfSignature("approver.pfx", "pass2");
pdf.Sign(authorSig, SignaturePermissions.NoChangesAllowed)
.Sign(approverSig, SignaturePermissions.NoChangesAllowed)
.SaveAs("multi-approved.pdf");Use PdfSignature for visible signatures and custom positioning
Remember to call SaveAs() to finalize the signature
See: https://ironpdf.com/examples/pdf-digital-signature/
Declaration
public PdfDocument Sign(PdfSignature Signature, SignaturePermissions Permissions)
Parameters
| Type | Name | Description |
|---|---|---|
| PdfSignature | Signature | PdfSignature object with certificate and options |
| SignaturePermissions | Permissions | Document modification permissions after signing |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument for method chaining |
SignAndSave(String, IHsmSigner, PdfSignatureImage, SignaturePermissions)
Saves a PDF document after signing it using an HSM (PKCS#11) signer.
------------------------------------------------
Usage:
doc.SignAndSave(destinationPath, hsmSigner, signatureImage, signaturePermission);
------------------------------------------------
Declaration
public void SignAndSave(string destinationPath, IHsmSigner hsmSigner, PdfSignatureImage signatureImage = null, SignaturePermissions signaturePermission)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | destinationPath | The file path where the signed PDF will be saved. |
| IHsmSigner | hsmSigner | The HSM-based signer used to sign the PDF. |
| PdfSignatureImage | signatureImage | An optional image to include in the signature. |
| SignaturePermissions | signaturePermission | The signaturePermission applied to the signed PDF. Defaults to |
Remarks
Important Notes:
Performance: This method writes the entire PDF file binary format for intermediate use, loads it into memory to modify the document bytes, and finally saves the signed version to the destination path.
Security: Always create a new temporary path and clean it up after execution.
Note: The optional signaturePermission parameter defaults to NoChangesAllowed.
How-To Guide: Guide to Digitally Signing PDFs
API Reference: Full API Documentation
SignWithFile(String, String, String, SignaturePermissions)
Signs the PDF with a digital certificate file (.pfx or .p12) for legal validity and authenticity. Signature is applied when the document is saved.
// Basic signing with certificate:
pdf.SignWithFile("certificate.pfx", "password");
pdf.SaveAs("signed-document.pdf");
// Sign with timestamp server for long-term validation:
pdf.SignWithFile("certificate.pfx", "password",
TimeStampUrl: "http://timestamp.digicert.com");
// Sign with restricted permissions:
pdf.SignWithFile("certificate.pfx", "password",
Permissions: SignaturePermissions.FormFillingAllowed);
// Chain multiple signatures:
pdf.SignWithFile("signer1.pfx", "pass1")
.SignWithFile("signer2.pfx", "pass2")
.SaveAs("multi-signed.pdf");Must call SaveAs() to apply the signature
Any document changes after signing will invalidate the signature
See: https://ironpdf.com/how-to/digital-signatures/
Declaration
public PdfDocument SignWithFile(string CertificateFilePath, string Password, string TimeStampUrl = null, SignaturePermissions Permissions)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | CertificateFilePath | Path to .pfx or .p12 certificate file |
| System.String | Password | Certificate password |
| System.String | TimeStampUrl | Optional timestamp server URL for long-term validation |
| SignaturePermissions | Permissions | Document modification permissions after signing |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument for method chaining |
See Also
SignWithStore(String, StoreLocation, SignaturePermissions)
Signs PDF using certificate from Windows Certificate Store by thumbprint. No password needed - perfect for enterprise certificates and smart cards.
// Sign with certificate from local machine store:
pdf.SignWithStore("2E98F3...thumbprint...7A3B");
pdf.SaveAs("signed.pdf");
// Sign with certificate from current user store:
pdf.SignWithStore("ABC123...thumbprint",
StoreLocation.CurrentUser);
// Get certificate thumbprint from store:
// 1. Run: certmgr.msc
// 2. Find certificate → Details → Thumbprint
// 3. Copy without spaces
pdf.SignWithStore("1A2B3C4D5E6F...");
// Sign with permissions for form filling:
pdf.SignWithStore("thumbprint",
StoreLocation.LocalMachine,
SignaturePermissions.FormFillingAllowed);Perfect for enterprise PKI and smart card certificates
Certificate must have private key accessible
See: https://ironpdf.com/how-to/certificate-store-signing/
Declaration
public PdfDocument SignWithStore(string Thumbprint, StoreLocation StoreLocation, SignaturePermissions Permissions)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | Thumbprint | Certificate thumbprint (40 hex characters, spaces ignored) |
| System.Security.Cryptography.X509Certificates.StoreLocation | StoreLocation | LocalMachine or CurrentUser certificate store |
| SignaturePermissions | Permissions | Document modification permissions after signing |
Returns
| Type | Description |
|---|---|
| PdfDocument | Returns this PdfDocument for method chaining |
ToBitmap(IEnumerable<Int32>, Int32, Boolean)
Rasterizes (renders) the PDF into (JPEG) IronSoftware.Drawing.AnyBitmap objects.
Specific pages may be selected using the PageIndexes parameter.
Please add an assembly reference to IronSoftware.Drawing.AnyBitmap to use this "PDF To Image" method
Declaration
public AnyBitmap[] ToBitmap(IEnumerable<int> pageIndexes, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<System.Int32> | pageIndexes | Specific zero based page index may be given to only convert part of the PDF document to images |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| IronSoftware.Drawing.AnyBitmap[] | An array of IronSoftware.Drawing.AnyBitmap image objects which can be saved, manipulated, displayed or edited programmatically. |
ToBitmap(Int32, Boolean)
Declaration
public AnyBitmap[] ToBitmap(int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | DPI | |
| System.Boolean | Flatten |
Returns
| Type | Description |
|---|---|
| IronSoftware.Drawing.AnyBitmap[] |
ToBitmap(Nullable<Int32>, Nullable<Int32>, IEnumerable<Int32>, Int32, Boolean)
Rasterizes (renders) the PDF into (JPEG) IronSoftware.Drawing.AnyBitmap objects.
Specific pages may be selected using the PageIndexes parameter. The Widths and Height of the output images may be specified.
Please add an assembly reference to IronSoftware.Drawing.AnyBitmap to use this "PDF To Image" method
Declaration
public AnyBitmap[] ToBitmap(Nullable<int> imageMaxWidth, Nullable<int> imageMaxHeight, IEnumerable<int> pageIndexes = null, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Nullable<System.Int32> | imageMaxWidth | The target maximum width(in pixel) of the output images. |
| System.Nullable<System.Int32> | imageMaxHeight | The target maximum height(in pixel) of the output images. |
| System.Collections.Generic.IEnumerable<System.Int32> | pageIndexes | Specific zero based page index may be given to only convert part of the PDF document to images |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| IronSoftware.Drawing.AnyBitmap[] | An array of IronSoftware.Drawing.AnyBitmap image objects which can be saved, manipulated, displayed or edited programmatically. |
ToBitmapHighQuality(IEnumerable<Int32>, Int32, Boolean)
Rasterizes (renders) the PDF into (BMP) IronSoftware.Drawing.AnyBitmap objects.
Specific pages may be selected using the PageIndexes parameter.
Please add an assembly reference to IronSoftware.Drawing.AnyBitmap to use this "PDF To Image" method
Declaration
public AnyBitmap[] ToBitmapHighQuality(IEnumerable<int> pageIndexes, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<System.Int32> | pageIndexes | Specific zero based page index may be given to only convert part of the PDF document to images |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| IronSoftware.Drawing.AnyBitmap[] | An array of IronSoftware.Drawing.AnyBitmap image objects which can be saved, manipulated, displayed or edited programmatically. The resulting images have significantly larger file sizes compared to ToBitmap(IEnumerable<Int32>, Int32, Boolean) |
Remarks
The DPI will be ignored under Linux and macOS.
ToBitmapHighQuality(Int32, Boolean)
Rasterizes (renders) the PDF into (BMP) IronSoftware.Drawing.AnyBitmap objects. 1 Bitmap for each page.
Please add an assembly reference to IronSoftware.Drawing.AnyBitmap to use this "PDF To Image" method.
Please Dispose() each Bitmap object after use.
Declaration
public AnyBitmap[] ToBitmapHighQuality(int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | DPI | The resolution of the output Bitmap in 'Dots Per Inch'. Higher DPI creates larger bitmap files of higher image quality. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| IronSoftware.Drawing.AnyBitmap[] | An array of IronSoftware.Drawing.AnyBitmap image objects which can be saved, manipulated, displayed or edited programmatically. The resulting images have significantly larger file sizes compared to ToBitmap(IEnumerable<Int32>, Int32, Boolean) |
Remarks
The DPI may be ignored on some Linux distros.
ToBitmapHighQuality(Nullable<Int32>, Nullable<Int32>, IEnumerable<Int32>, Int32, Boolean)
Rasterizes (renders) the PDF into (BMP) IronSoftware.Drawing.AnyBitmap objects.
Specific pages may be selected using the PageIndexes parameter. The Widths and Height of the output images may be specified.
Please add an assembly reference to IronSoftware.Drawing.AnyBitmap to use this "PDF To Image" method
Declaration
public AnyBitmap[] ToBitmapHighQuality(Nullable<int> imageMaxWidth, Nullable<int> imageMaxHeight, IEnumerable<int> pageIndexes = null, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Nullable<System.Int32> | imageMaxWidth | The target maximum width(in pixel) of the output images. |
| System.Nullable<System.Int32> | imageMaxHeight | The target maximum height(in pixel) of the output images. |
| System.Collections.Generic.IEnumerable<System.Int32> | pageIndexes | Specific zero based page index may be given to only convert part of the PDF document to images |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| IronSoftware.Drawing.AnyBitmap[] | An array of IronSoftware.Drawing.AnyBitmap image objects which can be saved, manipulated, displayed or edited programmatically. The resulting images have significantly larger file sizes compared to ToBitmap(Nullable<Int32>, Nullable<Int32>, IEnumerable<Int32>, Int32, Boolean) |
Remarks
The DPI will be ignored under Linux and macOS.
ToHtmlString(Boolean, String, IEnumerable<Int32>, HtmlFormatOptions)
Converts the PDF document to an HTML string with optional custom formatting. Returns complete HTML document as a string for dynamic web applications.
// Get HTML string for dynamic rendering:
string htmlContent = pdf.ToHtmlString();
// Full-width responsive HTML string:
string responsiveHtml = pdf.ToHtmlString(fullContentWidth: true);
// Convert specific pages to HTML:
string summaryHtml = pdf.ToHtmlString(
title: "Executive Summary",
pageIndexes: new[] { 0, 1, 2 });
// Styled HTML with custom formatting:
var formatOptions = new HtmlFormatOptions {
BackgroundColor = "#f8f9fa",
FontSize = "14px"
};
string styledHtml = pdf.ToHtmlString(
htmlFormatOptions: formatOptions);
// Use in web application:
Response.ContentType = "text/html";
Response.Write(pdf.ToHtmlString(fullContentWidth: true));Returns complete HTML document including <html>, <head>, and <body> tags
Large PDFs may generate substantial HTML strings
See: https://ironpdf.com/how-to/pdf-to-html-conversion/
Declaration
public string ToHtmlString(bool fullContentWidth = false, string title = "", IEnumerable<int> pageIndexes = null, HtmlFormatOptions htmlFormatOptions = null)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Boolean | fullContentWidth | If set to true, the PDF content in the HTML will be set to full width for responsive display. |
| System.String | title | Optional title to be used in the HTML <title> tag. If not provided, the title from PDF metadata will be used. |
| System.Collections.Generic.IEnumerable<System.Int32> | pageIndexes | Optional set of page indexes to include in the HTML output (0-based). If not provided, all pages will be included. |
| HtmlFormatOptions | htmlFormatOptions | Optional HTML formatting options for styling. If not provided, default formatting will be used. |
Returns
| Type | Description |
|---|---|
| System.String | A complete HTML document string representing the specified pages of the PDF document. |
Remarks
Use cases for HTML strings: • Dynamic web page generation • Email content creation • Content management systems • AJAX responses in web applications • Server-side rendering • API responses for web services
The returned HTML is self-contained with inline styles and can be directly rendered in browsers or embedded in other HTML documents.
Examples
// Web API endpoint returning PDF as HTML
[HttpGet("document/{id}/html")]
public IActionResult GetDocumentAsHtml(int id)
{
var pdfPath = GetPdfPath(id);
var pdf = PdfDocument.FromFile(pdfPath);
// Convert to responsive HTML
string htmlContent = pdf.ToHtmlString(
fullContentWidth: true,
title: $"Document {id}"
);
return Content(htmlContent, "text/html");
}
// Email PDF content as HTML
public void SendPdfAsEmail(string recipient, string pdfPath)
{
var pdf = PdfDocument.FromFile(pdfPath);
var htmlBody = pdf.ToHtmlString(
title: "Invoice",
pageIndexes: new[] { 0 } // First page only
);
var mail = new MailMessage {
Body = htmlBody,
IsBodyHtml = true,
Subject = "Your Invoice"
};
// Send email...
}
ToJpegImages(String, IEnumerable<Int32>, Int32, Boolean)
Renders the pages of the PDF as JPEG files and saves them to disk.
Specific image dimensions and page numbers may be given as optional parameters
FileNamePattern should normally contain an asterisk (*) character which will be substituted for the page numbers
Declaration
public string[] ToJpegImages(string FileNamePattern, IEnumerable<int> PageIndexes, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileNamePattern | A full or partial file path for the output files containing an asterisk. E.g. C:\images\pdf_page_*.jpg |
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexes | A list of the specific zero based page numbe to render as images. |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| System.String[] | An array of the file paths of the image files created. |
ToJpegImages(String, IEnumerable<Int32>, Nullable<Int32>, Nullable<Int32>, Int32, Boolean)
Renders the pages of the PDF as JPEG files and saves them to disk.
Specific image dimensions and page numbers may be given as optional parameters
FileNamePattern should normally contain an asterisk (*) character which will be substituted for the page numbers
Declaration
public string[] ToJpegImages(string FileNamePattern, IEnumerable<int> PageIndexes, Nullable<int> ImageMaxWidth, Nullable<int> ImageMaxHeight, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileNamePattern | A full or partial file path for the output files containing an asterisk. E.g. C:\images\pdf_page_*.jpg |
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexes | A list of the specific zero based page numbe to render as images. |
| System.Nullable<System.Int32> | ImageMaxWidth | The target maximum width(in pixel) of the output images. |
| System.Nullable<System.Int32> | ImageMaxHeight | The target maximum height(in pixel) of the output images. |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| System.String[] | An array of the file paths of the image files created. |
ToJpegImages(String, Int32, Boolean)
Renders the pages of the PDF as JPEG files and saves them to disk.
Specific image dimensions and page numbers may be given as optional parameters
FileNamePattern should normally contain an asterisk (*) character which will be substituted for the page numbers
Declaration
public string[] ToJpegImages(string FileNamePattern, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileNamePattern | A full or partial file path for the output files containing an asterisk. E.g. C:\images\pdf_page_*.jpg |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| System.String[] | An array of the file paths of the image files created. |
ToJpegImages(String, Nullable<Int32>, Nullable<Int32>, Int32, Boolean)
Renders the pages of the PDF as JPEG files and saves them to disk.
Specific image dimensions and page numbers may be given as optional parameters
FileNamePattern should normally contain an asterisk (*) character which will be substituted for the page numbers
Declaration
public string[] ToJpegImages(string FileNamePattern, Nullable<int> ImageMaxWidth, Nullable<int> ImageMaxHeight, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileNamePattern | A full or partial file path for the output files containing an asterisk. E.g. C:\images\pdf_page_*.jpg |
| System.Nullable<System.Int32> | ImageMaxWidth | The target maximum width(in pixel) of the output images. |
| System.Nullable<System.Int32> | ImageMaxHeight | The target maximum height(in pixel) of the output images. |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| System.String[] | An array of the file paths of the image files created. |
ToJson()
Converts the current PDF document to JSON format for testing and comparison purposes.
This feature is specifically designed for unit testing, regression testing, and PDF validation scenarios.
------------------------------------------------
Usage:
string json = pdf.ToJson();
------------------------------------------------
Declaration
public string ToJson()
Returns
| Type | Description |
|---|---|
| System.String | JSON string representation of the PDF document in structured JSON format |
Remarks
Important Notes:
Testing Focus: Optimized for unit testing and CI/CD validation pipelines.
Performance: For large PDFs, consider using SaveAsJson to write directly to file or ToJson with StringBuilder.
Comparison: Compare JSON outputs using standard JSON comparison libraries or text diff tools.
Format: Outputs normalized JSON format with stream data represented as SHA256 hashes by default.
Related Documentation:
How-To Guide: Converting PDF to JSON for Testing
API Reference: Full API Documentation
Examples
// Basic usage for PDF comparison in unit tests
var pdf = PdfDocument.FromFile("invoice.pdf");
string json = pdf.ToJson();
// Compare two PDFs by converting to JSON
var expectedJson = expectedPdf.ToJson();
var actualJson = actualPdf.ToJson();
Assert.AreEqual(expectedJson, actualJson);
ToJson(Byte[], String)
Converts a PDF byte array to JSON format.
------------------------------------------------
Usage:
string json = PdfDocument.ToJson(pdfBytes);
------------------------------------------------
Declaration
public static string ToJson(byte[] PdfBytes, string Password = "")
Parameters
| Type | Name | Description |
|---|---|---|
| System.Byte[] | PdfBytes | byte array of the PDF file |
| System.String | Password | password to open the file |
Returns
| Type | Description |
|---|---|
| System.String | JSON string representation of the PDF document |
Remarks
Important Notes:
Performance: For large PDFs, consider using SaveAsJson to write directly to file.
Security: The JSON output may contain sensitive PDF content.
Related Documentation:
How-To Guide: Converting PDF to JSON
API Reference: Full API Documentation
Exceptions
| Type | Condition |
|---|---|
| System.ArgumentException | Thrown when the PdfBytes array is null or empty. |
ToJson(Stream, String)
Converts a PDF stream to JSON format.
------------------------------------------------
Usage:
string json = PdfDocument.ToJson(pdfStream);
------------------------------------------------
Declaration
public static string ToJson(Stream Stream, string Password = "")
Parameters
| Type | Name | Description |
|---|---|---|
| System.IO.Stream | Stream | Stream of the PDF file |
| System.String | Password | password to open the file |
Returns
| Type | Description |
|---|---|
| System.String | JSON string representation of the PDF document |
Remarks
Important Notes:
Performance: For large PDFs, consider using SaveAsJson to write directly to file.
Security: The JSON output may contain sensitive PDF content.
Related Documentation:
How-To Guide: Converting PDF to JSON
API Reference: Full API Documentation
Exceptions
| Type | Condition |
|---|---|
| System.ArgumentNullException | Thrown when the input Stream is null. |
| System.ArgumentException | Thrown when the input Stream is not readable. |
ToJson(TextWriter)
Converts the current PDF document to JSON format using a TextWriter for flexible output.
Supports streaming to files, network streams, or any TextWriter implementation.
------------------------------------------------
Usage:
using (var writer = new StreamWriter("output.json")) { pdf.ToJson(writer); }
------------------------------------------------
Declaration
public void ToJson(TextWriter writer)
Parameters
| Type | Name | Description |
|---|---|---|
| System.IO.TextWriter | writer | TextWriter to write the JSON output to |
Examples
// Write JSON directly to file
using (var writer = new StreamWriter("pdf-analysis.json"))
{
pdf.ToJson(writer);
}
// Write to StringWriter for in-memory processing
using (var stringWriter = new StringWriter())
{
pdf.ToJson(stringWriter);
string json = stringWriter.ToString();
}
Exceptions
| Type | Condition |
|---|---|
| System.ArgumentNullException | Thrown when writer is null. |
ToJson(String)
Converts the current PDF document to JSON and saves it to a file.
Convenience method that combines ToJson with file writing.
------------------------------------------------
Usage:
pdf.ToJson("output.json");
------------------------------------------------
Declaration
public void ToJson(string filePath)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | filePath | Path where the JSON file will be saved. |
Examples
// Save JSON to file
pdf.ToJson("analysis.json");
Exceptions
| Type | Condition |
|---|---|
| System.ArgumentException | Thrown when the filePath is null, empty, or whitespace. |
ToJson(StringBuilder)
Converts the current PDF document to JSON format using a StringBuilder for memory efficiency.
Ideal for processing large PDFs or when building composite JSON output.
------------------------------------------------
Usage:
var sb = new StringBuilder(); pdf.ToJson(sb);
------------------------------------------------
Declaration
public void ToJson(StringBuilder builder)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Text.StringBuilder | builder | StringBuilder to append the JSON output to |
Examples
// Build composite JSON from multiple PDFs
var sb = new StringBuilder();
sb.AppendLine("[");
pdf1.ToJson(sb);
sb.AppendLine(",");
pdf2.ToJson(sb);
sb.AppendLine("]");
string combinedJson = sb.ToString();
Exceptions
| Type | Condition |
|---|---|
| System.ArgumentNullException | Thrown when builder is null. |
ToJsonAsync()
Asynchronously converts the current PDF document to JSON format.
Declaration
public Task<string> ToJsonAsync()
Returns
| Type | Description |
|---|---|
| System.Threading.Tasks.Task<System.String> | Task that returns JSON string representation of the PDF document |
ToJsonAsync(TextWriter)
Asynchronously converts PDF to JSON using TextWriter.
Declaration
public Task ToJsonAsync(TextWriter writer)
Parameters
| Type | Name | Description |
|---|---|---|
| System.IO.TextWriter | writer | TextWriter to write the JSON output to. |
Returns
| Type | Description |
|---|---|
| System.Threading.Tasks.Task |
ToJsonAsync(String)
Asynchronously converts the current PDF to JSON and saves to file.
Declaration
public Task ToJsonAsync(string filePath)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | filePath | Path where the JSON file will be saved. |
Returns
| Type | Description |
|---|---|
| System.Threading.Tasks.Task |
ToJsonAsync(StringBuilder)
Asynchronously converts PDF to JSON using StringBuilder.
Declaration
public Task ToJsonAsync(StringBuilder builder)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Text.StringBuilder | builder | StringBuilder to append the JSON output to. |
Returns
| Type | Description |
|---|---|
| System.Threading.Tasks.Task |
ToMultiPageTiffBytes(IEnumerable<Int32>, Int32, Boolean)
Renders the pages of the PDF as a TIFF (Tagged Image File Format / Tif) file and returns it as a byte array.
This method bypasses the need to save the TIFF to disk first.
Declaration
public byte[] ToMultiPageTiffBytes(IEnumerable<int> PageIndexes = null, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexes | A list of the specific zero based page numbers to render. If null, all pages will be rendered. |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| System.Byte[] | A byte array containing the TIFF image data. |
ToMultiPageTiffBytes(IEnumerable<Int32>, Nullable<Int32>, Nullable<Int32>, Int32, Boolean)
Renders the pages of the PDF as a TIFF (Tagged Image File Format / Tif) file and returns it as a byte array.
This method bypasses the need to save the TIFF to disk first.
Specific image dimensions and page numbers can be provided as optional parameters.
Declaration
public byte[] ToMultiPageTiffBytes(IEnumerable<int> PageIndexes, Nullable<int> ImageMaxWidth, Nullable<int> ImageMaxHeight, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexes | A list of the specific zero based page numbers to render. If null, all pages will be rendered. |
| System.Nullable<System.Int32> | ImageMaxWidth | The target maximum width(in pixel) of the output images. |
| System.Nullable<System.Int32> | ImageMaxHeight | The target maximum height(in pixel) of the output images. |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| System.Byte[] | A byte array containing the TIFF image data. |
ToMultiPageTiffImage(String, IEnumerable<Int32>, Int32, Boolean)
Renders the pages of the PDF as TIFF (Tagged Image File Format / Tif) file and saves it to disk.
Specific image dimensions and page numbers may be given as optional parameters
FileNamePattern should normally contain an asterisk (*) character which will be substituted for the page numbers
Declaration
public string ToMultiPageTiffImage(string FileName, IEnumerable<int> PageIndexes = null, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileName | A full file path for the output file. E.g. C:\images\pdf_pages.tiff |
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexes | A list of the specific zero based page number to render |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| System.String | A file path of the image file created. |
ToMultiPageTiffImage(String, IEnumerable<Int32>, Nullable<Int32>, Nullable<Int32>, Int32, Boolean)
Renders the pages of the PDF as TIFF (Tagged Image File Format / Tif) file and saves it to disk.
Specific image dimensions and page numbers may be given as optional parameters
FileNamePattern should normally contain an asterisk (*) character which will be substituted for the page numbers
Declaration
public string[] ToMultiPageTiffImage(string FileName, IEnumerable<int> PageIndexes, Nullable<int> ImageMaxWidth, Nullable<int> ImageMaxHeight, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileName | A full file path for the output file. E.g. C:\images\pdf_pages.tiff |
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexes | A list of the specific zero based page numbe to number to render |
| System.Nullable<System.Int32> | ImageMaxWidth | The target maximum width(in pixel) of the output images. |
| System.Nullable<System.Int32> | ImageMaxHeight | The target maximum height(in pixel) of the output images. |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| System.String[] | An array of the file paths of the image files created. |
ToMultiPageTiffImage(String, Nullable<Int32>, Nullable<Int32>, Int32, Boolean)
Renders the pages of the PDF as TIFF (Tagged Image File Format / Tif) file and saves it to disk.
Specific image dimensions and page numbers may be given as optional parameters
FileNamePattern should normally contain an asterisk (*) character which will be substituted for the page numbers
Declaration
public string[] ToMultiPageTiffImage(string FileName, Nullable<int> ImageMaxWidth, Nullable<int> ImageMaxHeight, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileName | A full file path for the output file. E.g. C:\images\pdf_pages.tiff |
| System.Nullable<System.Int32> | ImageMaxWidth | The target maximum width(in pixel) of the output images. |
| System.Nullable<System.Int32> | ImageMaxHeight | The target maximum height(in pixel) of the output images. |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| System.String[] | An array of the file paths of the image files created. |
ToMultiPageTiffStream(IEnumerable<Int32>, Int32, Boolean)
Renders the pages of the PDF as a TIFF (Tagged Image File Format / Tif) file and returns it as a Stream.
This method bypasses the need to save the TIFF to disk first.
Declaration
public Stream ToMultiPageTiffStream(IEnumerable<int> PageIndexes = null, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexes | A list of the specific zero based page numbers to render. If null, all pages will be rendered. |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| System.IO.Stream | A Stream containing the TIFF image data. |
ToMultiPageTiffStream(IEnumerable<Int32>, Nullable<Int32>, Nullable<Int32>, Int32, Boolean)
Renders the pages of the PDF as a TIFF (Tagged Image File Format / Tif) file and returns it as a Stream.
This method bypasses the need to save the TIFF to disk first.
Specific image dimensions and page numbers can be provided as optional parameters.
Declaration
public Stream ToMultiPageTiffStream(IEnumerable<int> PageIndexes, Nullable<int> ImageMaxWidth, Nullable<int> ImageMaxHeight, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexes | A list of the specific zero based page numbers to render. If null, all pages will be rendered. |
| System.Nullable<System.Int32> | ImageMaxWidth | The target maximum width(in pixel) of the output images. |
| System.Nullable<System.Int32> | ImageMaxHeight | The target maximum height(in pixel) of the output images. |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| System.IO.Stream | A Stream containing the TIFF image data. |
ToPngImages(String, IEnumerable<Int32>, Int32, Boolean)
Renders the pages of the PDF as PNG (Portable Network Graphic) files and saves them to disk.
Specific image dimensions and page numbers may be given as optional parameters
FileNamePattern should normally contain an asterisk (*) character which will be substituted for the page numbers
Declaration
public string[] ToPngImages(string FileNamePattern, IEnumerable<int> PageIndexes, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileNamePattern | A full or partial file path for the output files containing an asterisk. E.g. C:\images\pdf_pages_*.png |
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexes | A list of the specific zero based page numbe to render as images. |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| System.String[] | An array of the file paths of the image files created. |
ToPngImages(String, IEnumerable<Int32>, Nullable<Int32>, Nullable<Int32>, Int32, Boolean)
Renders the pages of the PDF as PNG (Portable Network Graphic) files and saves them to disk.
Specific image dimensions and page numbers may be given as optional parameters
FileNamePattern should normally contain an asterisk (*) character which will be substituted for the page numbers
Declaration
public string[] ToPngImages(string FileNamePattern, IEnumerable<int> PageIndexes, Nullable<int> ImageMaxWidth, Nullable<int> ImageMaxHeight, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileNamePattern | A full or partial file path for the output files containing an asterisk. E.g. C:\images\pdf_pages_*.png |
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexes | A list of the specific zero based page numbe to render |
| System.Nullable<System.Int32> | ImageMaxWidth | The target maximum width(in pixel) of the output images. |
| System.Nullable<System.Int32> | ImageMaxHeight | The target maximum height(in pixel) of the output images. |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten |
Returns
| Type | Description |
|---|---|
| System.String[] | An array of the file paths of the image files created. |
ToPngImages(String, Int32, Boolean)
Renders the pages of the PDF as PNG (Portable Network Graphic) files and saves them to disk.
Specific image dimensions and page numbers may be given as optional parameters
FileNamePattern should normally contain an asterisk (*) character which will be substituted for the page numbers
Declaration
public string[] ToPngImages(string FileNamePattern, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileNamePattern | A full or partial file path for the output files containing an asterisk. E.g. C:\images\pdf_pages_*.png |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| System.String[] | An array of the file paths of the image files created. |
ToPngImages(String, Nullable<Int32>, Nullable<Int32>, Int32, Boolean)
Renders the pages of the PDF as PNG (Portable Network Graphic) files and saves them to disk.
Specific image dimensions and page numbers may be given as optional parameters
FileNamePattern should normally contain an asterisk (*) character which will be substituted for the page numbers
Declaration
public string[] ToPngImages(string FileNamePattern, Nullable<int> ImageMaxWidth, Nullable<int> ImageMaxHeight, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileNamePattern | A full or partial file path for the output files containing an asterisk. E.g. C:\images\pdf_pages_*.png |
| System.Nullable<System.Int32> | ImageMaxWidth | The target maximum width(in pixel) of the output images. |
| System.Nullable<System.Int32> | ImageMaxHeight | The target maximum height(in pixel) of the output images. |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| System.String[] | An array of the file paths of the image files created. |
ToString()
Represent PDF document as a document id string
Declaration
public override string ToString()
Returns
| Type | Description |
|---|---|
| System.String |
ToSvgString(Int32)
Converts a specific page of the PDF document to SVG format and returns it as a string. Perfect for dynamic web rendering and inline SVG display.
// Convert first page to SVG string:
string svgContent = pdf.ToSvgString(0);
// Convert specific page:
string page3Svg = pdf.ToSvgString(2); // Third page (0-indexed)
// Embed directly in HTML:
string html = $@"
<div class='svg-container'>
{pdf.ToSvgString(0)}
</div>";
// Process SVG content:
var svgDoc = XDocument.Parse(pdf.ToSvgString());
var width = svgDoc.Root.Attribute("width")?.Value;Returns complete SVG XML ready for inline HTML embedding
Page parameter is 0-based (0 = first page)
See: https://ironpdf.com/how-to/pdf-to-svg-conversion/
Declaration
public string ToSvgString(int page = 0)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Int32 | page | The page number to be converted to SVG (0-based index). Default is 0 (first page). |
Returns
| Type | Description |
|---|---|
| System.String | The SVG representation of the specified page as a complete XML string. |
Remarks
Use cases for SVG strings: • Dynamic web page generation • Inline SVG in HTML documents • SVG manipulation before display • Creating responsive graphics • Server-side rendering scenarios
The returned SVG includes all styling and can be embedded directly in HTML or processed with XML/SVG libraries.
Examples
// Generate dynamic web page with PDF content
var pdf = PdfDocument.FromFile("report.pdf");
// Create HTML with embedded SVG
var htmlBuilder = new StringBuilder();
htmlBuilder.AppendLine("<html><body>");
for (int i = 0; i < Math.Min(3, pdf.PageCount); i++)
{
string svgContent = pdf.ToSvgString(i);
htmlBuilder.AppendLine($"<div class='page'>{svgContent}</div>");
}
htmlBuilder.AppendLine("</body></html>");
File.WriteAllText("preview.html", htmlBuilder.ToString());
ToTiffImages(String, IEnumerable<Int32>, Int32, Boolean)
Renders the pages of the PDF as TIFF (Tagged Image File Format / Tif) files and saves them to disk.
Specific image dimensions and page numbers may be given as optional parameters
FileNamePattern should normally contain an asterisk (*) character which will be substituted for the page numbers
Declaration
public string[] ToTiffImages(string FileNamePattern, IEnumerable<int> PageIndexes, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileNamePattern | A full or partial file path for the output files containing an asterisk. E.g. C:\images\pdf_pages_*.tiff |
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexes | A list of the specific zero based page number to render |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| System.String[] | An array of the file paths of the image files created. |
ToTiffImages(String, IEnumerable<Int32>, Nullable<Int32>, Nullable<Int32>, Int32, Boolean)
Renders the pages of the PDF as TIFF (Tagged Image File Format / Tif) files and saves them to disk.
Specific image dimensions and page numbers may be given as optional parameters
FileNamePattern should normally contain an asterisk (*) character which will be substituted for the page numbers
Declaration
public string[] ToTiffImages(string FileNamePattern, IEnumerable<int> PageIndexes, Nullable<int> ImageMaxWidth, Nullable<int> ImageMaxHeight, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileNamePattern | A full or partial file path for the output files containing an asterisk. E.g. C:\images\pdf_pages_*.tiff |
| System.Collections.Generic.IEnumerable<System.Int32> | PageIndexes | A list of the specific zero based page number to render |
| System.Nullable<System.Int32> | ImageMaxWidth | The target maximum width(in pixel) of the output images. |
| System.Nullable<System.Int32> | ImageMaxHeight | The target maximum height(in pixel) of the output images. |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| System.String[] | An array of the file paths of the image files created. |
ToTiffImages(String, Int32, Boolean)
Renders the pages of the PDF as TIFF (Tagged Image File Format / Tif) files and saves them to disk.
Specific image dimensions and page numbers may be given as optional parameters
FileNamePattern should normally contain an asterisk (*) character which will be substituted for the page numbers
Declaration
public string[] ToTiffImages(string FileNamePattern, int DPI, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileNamePattern | A full or partial file path for the output files containing an asterisk. E.g. C:\images\pdf_pages_*.tiff |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| System.String[] | An array of the file paths of the image files created. |
ToTiffImages(String, Nullable<Int32>, Nullable<Int32>, Int32, Boolean)
Renders the pages of the PDF as TIFF (Tagged Image File Format / Tif) files and saves them to disk.
Specific image dimensions and page numbers may be given as optional parameters
FileNamePattern should normally contain an asterisk (*) character which will be substituted for the page numbers
Declaration
public string[] ToTiffImages(string FileNamePattern, Nullable<int> ImageMaxWidth, Nullable<int> ImageMaxHeight, int DPI = 96, bool Flatten = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileNamePattern | A full or partial file path for the output files containing an asterisk. E.g. C:\images\pdf_pages_*.tiff |
| System.Nullable<System.Int32> | ImageMaxWidth | The target maximum width(in pixel) of the output images. |
| System.Nullable<System.Int32> | ImageMaxHeight | The target maximum height(in pixel) of the output images. |
| System.Int32 | DPI | The desired resolution of the output Images. |
| System.Boolean | Flatten | Flatten the PDF before rendering the images - useful for displaying form field values |
Returns
| Type | Description |
|---|---|
| System.String[] | An array of the file paths of the image files created. |
TrySaveAs(String)
Attempt to save the PdfDocument to a file.
Declaration
public bool TrySaveAs(string FileName)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | FileName | File Path |
Returns
| Type | Description |
|---|---|
| System.Boolean | } |
VerifyPdfSignatures(Boolean)
Quickly verifies if all digital signatures in the PDF are valid. Returns true only if every signature is authentic and unmodified.
// Simple signature validation:
if (pdf.VerifyPdfSignatures())
{
Console.WriteLine(" All signatures valid");
ProcessSecureDocument(pdf);
}
else
{
Console.WriteLine(" Invalid signature detected");
RejectDocument();
}
// Strict validation with incremental tampering detection:
var contract = PdfDocument.FromFile("signed-contract.pdf");
if (!contract.VerifyPdfSignatures(detectIncrementalTampering: true))
{
throw new SecurityException("Invalid signature");
}Fast check for document integrity and authenticity
Any edit after signing invalidates signatures
See: https://ironpdf.com/how-to/signing/
Declaration
public bool VerifyPdfSignatures(bool detectIncrementalTampering = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.Boolean | detectIncrementalTampering | When May add noticeable processing time for large or heavily revised documents. Recommended for multi-signature workflows in legal or government contexts. Default isfalse.
|
Returns
| Type | Description |
|---|---|
| System.Boolean | True if all signatures are valid, false if any are invalid or missing |
VerifyPdfSignaturesInFile(String, Boolean)
Verifies digital signatures in a PDF file without loading the entire document. Efficient for batch validation or pre-screening files before processing.
// Quick file signature check:
if (PdfDocument.VerifyPdfSignaturesInFile("contract.pdf"))
{
Console.WriteLine(" Signatures valid");
// Safe to process the file
}
// Batch validate multiple files:
var files = Directory.GetFiles("contracts/", "*.pdf");
var validFiles = files.Where(f =>
PdfDocument.VerifyPdfSignaturesInFile(f)
).ToList();
Console.WriteLine($"{validFiles.Count} valid signed PDFs");
// Strict validation with incremental tampering detection:
string largePdf = "large-signed-document.pdf";
if (!PdfDocument.VerifyPdfSignaturesInFile(largePdf, detectIncrementalTampering: true))
{
throw new Exception("Invalid signature - processing aborted");
}
// Now safe to load and process
var pdf = PdfDocument.FromFile(largePdf);Static method - no need to load full PDF into memory
Returns false for unsigned PDFs or any invalid signature
See: https://ironpdf.com/examples/digitally-sign-a-pdf/
Declaration
public static bool VerifyPdfSignaturesInFile(string PdfFilePath, bool detectIncrementalTampering = false)
Parameters
| Type | Name | Description |
|---|---|---|
| System.String | PdfFilePath | Full or relative path to the PDF file |
| System.Boolean | detectIncrementalTampering | When May add noticeable processing time for large or heavily revised documents. Recommended for multi-signature workflows in legal or government contexts. Default isfalse.
|
Returns
| Type | Description |
|---|---|
| System.Boolean | True if all signatures in the file are valid, false otherwise |
Operators
Implicit(DocumentId to PdfDocument)
Implicit conversion from DocumentId to PdfDocument
Declaration
public static implicit operator PdfDocument(DocumentId id)
Parameters
| Type | Name | Description |
|---|---|---|
| IronSoftware.Abstractions.Pdf.DocumentId | id | DocumentId to convert |
Returns
| Type | Description |
|---|---|
| PdfDocument |