Skip to content

C# / .NET API-Referenz

Das NuGet-Paket PdfOxide umhüllt den Rust-Kern über LibraryImport-generiertes P/Invoke (alle 881 Deklarationen). NativeAOT-publish-ready und trim-safe. Ziel-Frameworks: net8.0, net10.0.

dotnet add package PdfOxide
using PdfOxide.Core;

Für andere Sprachen siehe Python, Node.js, Golang oder Rust.


Namespaces

using PdfOxide.Core;        // PdfDocument, Pdf, DocumentEditor, DocumentBuilder, ...
using PdfOxide.Geometry;    // Color, Point, Rect
using PdfOxide.Exceptions;  // PdfException and typed subclasses

Alle nativ gestützten Typen implementieren IDisposable — verwenden Sie using-Blöcke oder using-Deklarationen. Koordinaten werden in PDF-Punkten ab dem Ursprung links unten angegeben, sofern nicht anders vermerkt; als Floats übergebene Farbkanäle liegen im Bereich 0.01.0.


PdfDocument

Schreibgeschütztes Handle zur Extraktion. PdfDocument ist enumerierbar und indizierbar und liefert verzögert ausgewertete Page-Handles.

Open

static PdfDocument Open(string path)
static PdfDocument Open(Stream stream)
static PdfDocument Open(byte[] data)
static PdfDocument Open(ReadOnlySpan<byte> data)
static PdfDocument OpenWithPassword(string path, string password)
static PdfDocument OpenFromDocxBytes(byte[] data)
static PdfDocument OpenFromPptxBytes(byte[] data)
static PdfDocument OpenFromXlsxBytes(byte[] data)
  • Open(...) — öffnen aus einem Pfad, Stream, Byte-Array oder Span.
  • OpenWithPassword(path, password) — ein verschlüsseltes PDF in einem Schritt öffnen.
  • OpenFromDocxBytes / OpenFromPptxBytes / OpenFromXlsxBytes — Office-Bytes konvertieren und das Ergebnis als PDF öffnen (erfordert das Feature office).

Eigenschaften

(byte Major, byte Minor) Version { get; }   // PDF version, e.g. (1, 7)
int PageCount { get; }                       // number of pages
bool HasStructureTree { get; }               // Tagged PDF with a structure tree
bool IsEncrypted { get; }                    // document is encrypted
bool HasXfa { get; }                         // contains XFA forms
int SignatureCount { get; }                  // number of digital signatures
IReadOnlyList<Signature> Signatures { get; } // signature handles
IReadOnlyList<Page> Pages { get; }           // lazy per-page handles
Page this[int pageIndex] { get; }            // page at index

Authentifizierung

bool Authenticate(string password)

Authentifiziert ein verschlüsseltes Dokument nach dem Öffnen mit einem Benutzer- oder Eigentümer-Passwort. Gibt bei Erfolg true zurück.

Textextraktion

string ExtractText(int pageIndex)
string ExtractAllText()
Task<string> ExtractTextAsync(int pageIndex, CancellationToken cancellationToken = default)
string ExtractTextInRect(int pageIndex, float x, float y, float width, float height)

(string Text, float X, float Y, float W, float H)[] ExtractWords(int pageIndex)
(string Text, float X, float Y, float W, float H)[] ExtractWordsInRect(int pageIndex, float x, float y, float width, float height)
(string Text, float X, float Y, float W, float H)[] ExtractTextLines(int pageIndex)
(char Char, float X, float Y, float W, float H)[] ExtractChars(int pageIndex)
(float X, float Y, float W, float H, float StrokeWidth)[] ExtractPaths(int pageIndex)
Table[] ExtractTables(int pageIndex)
  • ExtractText / ExtractAllText — reiner Text aus einer Seite oder dem gesamten Dokument.
  • ExtractTextInRect — Text innerhalb eines rechteckigen Bereichs.
  • ExtractWords / ExtractWordsInRect — Wörter mit Begrenzungsrahmen (optional auf einen Bereich beschnitten).
  • ExtractTextLines — Zeilen mit Begrenzungsrahmen.
  • ExtractChars — Positionen pro Glyphe.
  • ExtractPaths — Vektorpfad-Segmente mit Strichbreiten.
  • ExtractTables — erkannte Tabellen (siehe Table).

Klassifizierung & Auto-Extraktion

string ExtractStructured(int page)
string ClassifyPage(int pageIndex)
string ClassifyDocument()
string ExtractTextAuto(int pageIndex)
string ExtractPageAuto(int pageIndex, string? optionsJson = null)
  • ExtractStructured — strukturiertes JSON des Seiteninhalts.
  • ClassifyPage / ClassifyDocument — eine Seite oder das gesamte Dokument klassifizieren (z. B. gescannt vs. digital).
  • ExtractTextAuto — eine Seite automatisch auf den besten Textpfad leiten (digital oder OCR).
  • ExtractPageAuto — Auto-Extraktion mit einem optionalen JSON-Options-Blob.

Konvertierung

string ToMarkdown(int pageIndex)
string ToMarkdownAll()
string ToHtml(int pageIndex)
string ToHtmlAll()
string ToPlainText(int pageIndex)
string ToPlainTextAll()

byte[] ToDocxBytes()
byte[] ToPptxBytes()
byte[] ToXlsxBytes()
  • ToMarkdown / ToHtml / ToPlainText (+ *All) — eine Seite oder das gesamte Dokument konvertieren.
  • ToDocxBytes / ToPptxBytes / ToXlsxBytes — in Office-Formate exportieren (erfordert das Feature office).

Inhaltsbereinigung

int RemoveHeaders(float threshold = 0.8f)
int RemoveFooters(float threshold = 0.8f)
int RemoveArtifacts(float threshold = 0.8f)

Erkennt und entfernt wiederkehrende Kopf-, Fußzeilen oder Seitenartefakte. Gibt die Anzahl der entfernten Elemente zurück. threshold ist das seitenübergreifende Wiederholungsverhältnis.

Suche

(int Page, string Text, float X, float Y, float W, float H)[] SearchAll(string text, bool caseSensitive = false)
(int Page, string Text, float X, float Y, float W, float H)[] SearchPage(int pageIndex, string text, bool caseSensitive = false)

Sucht im gesamten Dokument oder auf einer einzelnen Seite; gibt Treffer mit Seitenindex und Begrenzungsrahmen zurück.

Struktur & Metadaten

string GetPageLabels()
string GetXmpMetadata()
string GetOutline()
string PlanSplitByBookmarks(int level, string? namePattern = null)
string[] GetFonts(int pageIndex)
  • GetPageLabels — Seitenbezeichnungs-Bereiche (JSON).
  • GetXmpMetadata — XMP-Metadaten (JSON / XML-Paket).
  • GetOutline — Lesezeichenbaum / Inhaltsverzeichnis (JSON).
  • PlanSplitByBookmarks — einen Teilungsplan auf einer Lesezeichenebene berechnen.
  • GetFonts — auf einer Seite verwendete Schriftnamen.

Bilder

ExtractedImage[] ExtractImages(int pageIndex)

Extrahiert eingebettete Bilder mit Metadaten und Roh-Bytes (siehe ExtractedImage).

Formulare

FormField[] GetFormFields()

Listet AcroForm-Felder auf (siehe FormField).

Rendering

byte[] RenderPage(int pageIndex, int format = 0)
byte[] RenderPage(int pageIndex, RenderOptions options)
byte[] RenderPageZoom(int pageIndex, float zoom, int format = 0)
byte[] RenderPageFit(int pageIndex, int fitWidth, int fitHeight, int format = 0)
byte[] RenderThumbnail(int pageIndex, int format = 0)
RgbaPixmap RenderToRgba(int pageIndex, int dpi = 150)
void SaveRenderedImage(int pageIndex, string filePath, int format = 0)
  • RenderPage — bei Standard-DPI rendern (format: 0 = PNG, 1 = JPEG) oder mit vollständigen RenderOptions.
  • RenderPageZoom — mit einem Zoomfaktor rendern.
  • RenderPageFit — skaliert rendern, um in ein Pixelfeld zu passen.
  • RenderThumbnail — ein kleines Vorschaubild rendern.
  • RenderToRgba — in eine rohe RGBA-Pixmap rendern (siehe RgbaPixmap).
  • SaveRenderedImage — rendern und direkt in eine Datei schreiben.

Signaturen

unsafe DocumentSecurityStore? GetDss()
bool HasDocumentTimestamp()
  • GetDss — den Document Security Store (DSS) lesen, sofern vorhanden.
  • HasDocumentTimestamp — ob ein dokumentweiter Zeitstempel vorhanden ist.

Siehe Signature für die Verifizierung einzelner Signaturen.

Statische Konfiguration

static void SetLogLevel(int level)
static int GetLogLevel()
static string PrefetchModels(params string[] languages)
static string ModelManifest()
static bool PrefetchAvailable()
static string GetActiveCryptoProvider()
static bool IsFipsCryptoAvailable()
static void UseFipsCryptoProvider()
static void SetCryptoPolicy(string spec)
static string CryptoPolicy()
static string[] CryptoInventory()
static string CryptoCbom()
  • SetLogLevel / GetLogLevel — die native Log-Ausführlichkeit steuern.
  • PrefetchModels / ModelManifest / PrefetchAvailable — OCR-Modell-Downloads verwalten.
  • GetActiveCryptoProvider / IsFipsCryptoAvailable / UseFipsCryptoProvider — Auswahl des Krypto-Providers (FIPS).
  • SetCryptoPolicy / CryptoPolicy — die aktive Krypto-Richtlinie abrufen/setzen.
  • CryptoInventory / CryptoCbom — Krypto-Nutzung auflisten / eine CBOM ausgeben.

Dispose

void Dispose()

Page

Verzögert ausgewertetes Seiten-Handle aus doc[i] oder Iteration. Alle Member delegieren an das übergeordnete Dokument.

int Index { get; }

string ExtractText();
Task<string> ExtractTextAsync(CancellationToken ct = default);
string ToMarkdown();
Task<string> ToMarkdownAsync(CancellationToken ct = default);
string ToHtml();
Task<string> ToHtmlAsync(CancellationToken ct = default);
string ToPlainText();
Task<string> ToPlainTextAsync(CancellationToken ct = default);

(string Text, float X, float Y, float W, float H)[] ExtractWords();
(string Text, float X, float Y, float W, float H)[] ExtractLines();
(char Char, float X, float Y, float W, float H)[] ExtractChars();
(float X, float Y, float W, float H, float StrokeWidth)[] ExtractPaths();
Table[] ExtractTables();
ExtractedImage[] ExtractImages();
string[] GetFonts();
(int Page, string Text, float X, float Y, float W, float H)[] Search(string text, bool caseSensitive = false);

byte[] Render(int format = 0);
byte[] RenderThumbnail(int format = 0);

Pdf — Erstellung

Ein PDF aus einem Quellformat erstellen und dann speichern.

static Pdf FromMarkdown(string markdown)
static Pdf FromHtml(string html)
static Pdf FromHtmlCss(string html, string css, byte[] fontBytes)
static unsafe Pdf FromHtmlCssWithFonts(string html, string css, (string Name, byte[] Bytes)[] fonts)
static Pdf FromText(string text)
static Pdf FromImage(string path)
static Pdf FromImageBytes(byte[] data)
int PageCount { get; }

void Save(string path)
byte[] SaveToBytes()
void SaveToStream(Stream stream)
Task SaveAsync(string path, CancellationToken cancellationToken = default)
Task SaveToStreamAsync(Stream stream, CancellationToken cancellationToken = default)
void Dispose()
  • FromMarkdown / FromHtml / FromText — aus Textformaten erstellen.
  • FromHtmlCss / FromHtmlCssWithFonts — HTML-±CSS-Pipeline mit eingebetteten Schriften.
  • FromImage / FromImageBytes — einseitiges PDF aus einem Bild.
  • Save / SaveToBytes / SaveToStream (+ async) — das Ergebnis persistieren.

DocumentEditor

Veränderbarer Editor für bestehende PDFs: Metadaten, Seiten, Formulare, Schwärzung, Verschlüsselung.

Öffnen & speichern

static DocumentEditor Open(string path)
static DocumentEditor OpenFromBytes(byte[] data)

void Save(string path)
Task SaveAsync(string path, CancellationToken cancellationToken = default)
byte[] SaveToBytes()
byte[] SaveToBytesWithOptions(bool compress, bool garbageCollect, bool linearize)
void SaveEncrypted(string path, string userPassword, string ownerPassword)
byte[] SaveEncryptedToBytes(string userPassword, string ownerPassword)
unsafe byte[] ExtractPages(int[] pageIndices)
void Dispose()

Eigenschaften

bool IsModified { get; }
string SourcePath { get; }
(byte Major, byte Minor) Version { get; }
int PageCount { get; }
string? Title { get; set; }
string? Author { get; set; }
string? Subject { get; set; }
string? Keywords { get; set; }
string? Producer { get; set; }
string? CreationDate { get; set; }
string[] FlattenWarnings { get; }

Seitenoperationen

void MergeFrom(string sourcePath)
int MergeFromBytes(byte[] data)
void DeletePage(int pageIndex)
void MovePage(int fromIndex, int toIndex)
int GetPageRotation(int pageIndex)
void SetPageRotation(int pageIndex, int degrees)
void RotateAllPages(int degrees)
void RotatePageBy(int pageIndex, int degrees)
void CropMargins(float left, float right, float top, float bottom)
(double X, double Y, double Width, double Height) GetPageMediaBox(int pageIndex)
void SetPageMediaBox(int pageIndex, double x, double y, double width, double height)
(double X, double Y, double Width, double Height) GetPageCropBox(int pageIndex)
void SetPageCropBox(int pageIndex, double x, double y, double width, double height)
  • MergeFrom / MergeFromBytes — Seiten aus einem anderen PDF anhängen (MergeFromBytes gibt die zusammengeführte Seitenzahl zurück).
  • DeletePage / MovePage — Seiten entfernen oder neu anordnen.
  • GetPageRotation / SetPageRotation / RotateAllPages / RotatePageBy — Rotationssteuerung (absolut vs. relativ).
  • CropMargins — alle Seitenränder beschneiden.
  • Get/SetPageMediaBox und Get/SetPageCropBox — Seitengeometrie-Boxen.

Löschen / Übermalen

void EraseRegion(int pageIndex, float x, float y, float width, float height)
void EraseRegions(int pageIndex, double[][] rects)
void ClearEraseRegions(int pageIndex)

Anmerkungen & Formulare

void SetFormFieldValue(string name, string value)
void FlattenForms()
void FlattenFormsOnPage(int pageIndex)
void FlattenAnnotations(int pageIndex)
void FlattenAllAnnotations()
bool IsPageMarkedForFlatten(int pageIndex)
void UnmarkPageForFlatten(int pageIndex)

Schwärzung

void AddRedaction(int pageIndex, double x1, double y1, double x2, double y2, byte r, byte g, byte b)
int RedactionCount(int pageIndex)
void ApplyPageRedactions(int pageIndex)
void ApplyAllRedactions()
int ApplyRedactions(bool scrubMetadata = true, bool scrubText = true)
bool IsPageMarkedForRedaction(int pageIndex)
void UnmarkPageForRedaction(int pageIndex)
int SanitizeDocument()
  • AddRedaction — ein Schwärzungsrechteck mit einer Füllfarbe in die Warteschlange stellen.
  • ApplyPageRedactions / ApplyAllRedactions / ApplyRedactions — ausstehende Schwärzungen einbrennen (ApplyRedactions bereinigt optional Metadaten/verborgenen Text).
  • SanitizeDocument — verborgene/nicht referenzierte Daten entfernen; gibt die Anzahl der bereinigten Elemente zurück.

Sonstiges

void EmbedFile(string name, byte[] data)
void ConvertToPdfA(PdfALevel level = PdfALevel.A2b)
  • EmbedFile — eine Datei an das PDF anhängen.
  • ConvertToPdfA — in eine PDF/A-Konformitätsstufe konvertieren.

Die genauen Signaturen von AddRedaction / ApplyRedactions verwenden intern native Argumente in snake_case; die hier gezeigte C#-Oberfläche ist die öffentliche Bindung.


DocumentBuilder

Fluent-Builder für neue Dokumente. DocumentBuilder.Create() → Metadaten → Seite(n) → Build() / Save().

static DocumentBuilder Create()

DocumentBuilder Title(string title)
DocumentBuilder Author(string author)
DocumentBuilder Subject(string subject)
DocumentBuilder Keywords(string keywords)
DocumentBuilder Creator(string creator)
DocumentBuilder OnOpen(string script)            // document-open JavaScript
DocumentBuilder TaggedPdfUa1()                    // emit a Tagged PDF/UA-1
DocumentBuilder Language(string lang)
DocumentBuilder RoleMap(string custom, string standard)
DocumentBuilder RegisterEmbeddedFont(string name, EmbeddedFont font)

PageBuilder A4Page()
PageBuilder LetterPage()
PageBuilder Page(float width, float height)

byte[] Build()
void Save(string path)
void SaveEncrypted(string path, string userPassword, string ownerPassword)
byte[] ToBytesEncrypted(string userPassword, string ownerPassword)
void Dispose()

PageBuilder

Fluent-Oberfläche pro Seite, zurückgegeben von A4Page() / LetterPage() / Page(w, h). Jede Methode gibt den Builder zur Verkettung zurück; Done() übergibt die Seite zurück an das übergeordnete Element.

Text & Layout

PageBuilder Font(string name, float size)
PageBuilder At(float x, float y)
PageBuilder Text(string text)
PageBuilder Heading(byte level, string text)
PageBuilder Paragraph(string text)
PageBuilder Space(float points)
PageBuilder HorizontalRule()
PageBuilder Newline()
PageBuilder Columns(uint columnCount, float gapPt, string text)
PageBuilder Footnote(string refMark, string noteText)
PageBuilder TextInRect(float x, float y, float w, float h, string text, Alignment align = Alignment.Left)
PageBuilder NewPageSameSize()
float Measure(string text)
float RemainingSpace()

Inline-Läufe

PageBuilder Inline(string text)
PageBuilder InlineBold(string text)
PageBuilder InlineItalic(string text)
PageBuilder InlineColor(float r, float g, float b, string text)
PageBuilder LinkUrl(string url)
PageBuilder LinkPage(int pageIndex)
PageBuilder LinkNamed(string destination)
PageBuilder LinkJavascript(string script)
PageBuilder OnOpen(string script)
PageBuilder OnClose(string script)
PageBuilder FieldKeystroke(string script)
PageBuilder FieldFormat(string script)
PageBuilder FieldValidate(string script)
PageBuilder FieldCalculate(string script)

Anmerkungen

PageBuilder Highlight(float r, float g, float b)
PageBuilder Underline(float r, float g, float b)
PageBuilder Strikeout(float r, float g, float b)
PageBuilder Squiggly(float r, float g, float b)
PageBuilder StickyNote(string text)
PageBuilder StickyNoteAt(float x, float y, string text)
PageBuilder Watermark(string text)
PageBuilder WatermarkConfidential()
PageBuilder WatermarkDraft()
PageBuilder Stamp(string typeName)
PageBuilder FreeText(float x, float y, float w, float h, string text)

Formular-Widgets

PageBuilder TextField(string name, float x, float y, float w, float h, string? defaultValue = null)
PageBuilder Checkbox(string name, float x, float y, float w, float h, bool @checked = false)
unsafe PageBuilder ComboBox(string name, float x, float y, float w, float h, string[] options, string? selected = null)
unsafe PageBuilder RadioGroup(string name, (string Value, float X, float Y, float W, float H)[] buttons, string? selected = null)
PageBuilder PushButton(string name, float x, float y, float w, float h, string caption)
PageBuilder SignatureField(string name, float x, float y, float w, float h)

Grafik

PageBuilder Rect(float x, float y, float w, float h)
PageBuilder FilledRect(float x, float y, float w, float h, float r, float g, float b)
PageBuilder Line(float x1, float y1, float x2, float y2)
PageBuilder StrokeRect(float x, float y, float w, float h, float width = 1f, float r = 0f, float g = 0f, float b = 0f)
PageBuilder StrokeLine(float x1, float y1, float x2, float y2, float width = 1f, float r = 0f, float g = 0f, float b = 0f)
unsafe PageBuilder StrokeRectDashed(float x, float y, float w, float h, float[] dash, float phase = 0f, float width = 1f, float r = 0f, float g = 0f, float b = 0f)
unsafe PageBuilder StrokeLineDashed(float x1, float y1, float x2, float y2, float[] dash, float phase = 0f, float width = 1f, float r = 0f, float g = 0f, float b = 0f)

Bilder & Barcodes

unsafe PageBuilder Image(byte[] imageBytes, float x, float y, float w, float h)
unsafe PageBuilder ImageWithAlt(byte[] imageBytes, float x, float y, float w, float h, string altText)
unsafe PageBuilder ImageArtifact(byte[] imageBytes, float x, float y, float w, float h)
PageBuilder Barcode1d(int barcodeType, string data, float x, float y, float w, float h)
PageBuilder BarcodeQr(string data, float x, float y, float size)

Tabellen

unsafe PageBuilder Table(TableSpec spec)
StreamingTable StreamingTable(IReadOnlyList<Column> columns, bool repeatHeader = true,
                              TableMode? mode = null, int maxRowspan = 1, int batchSize = 256)
DocumentBuilder Done()
void Dispose()
  • Table — eine vollständig materialisierte Tabelle aus einer TableSpec rendern.
  • StreamingTable — eine Streaming-Tabelle für große/zeilenweise Daten öffnen (siehe StreamingTable).
  • Done — die Seite übergeben und den übergeordneten DocumentBuilder zurückgeben.

EmbeddedFont

static EmbeddedFont FromFile(string path)
static EmbeddedFont FromBytes(byte[] data, string? name = null)
void Dispose()

Lädt eine TTF/OTF-Schrift zum Einbetten über DocumentBuilder.RegisterEmbeddedFont.


StreamingTable

Zeilenweiser Tabellen-Builder für große Datensätze, zurückgegeben von PageBuilder.StreamingTable(...).

unsafe StreamingTable AddRow(params string[] cells)
unsafe StreamingTable AddRowSpan(params (string? Text, int Rowspan)[] cells)
void Flush()
PageBuilder Build()
void Dispose()
  • AddRow — eine Zeile mit Zellen anhängen.
  • AddRowSpan — eine Zeile mit Rowspans pro Zelle anhängen (erfordert maxRowspan >= 2).
  • Flush — gepufferte Zeilen an die native Schicht leeren.
  • Build — abschließen und den übergeordneten PageBuilder zurückgeben.

OcrEngine

OCR über gescannte PDFs (erfordert das Feature ocr). Modelle werden aus Erkennungs-, Erfassungs- und Wörterbuchpfaden geladen.

static OcrEngine Load(string detectionModelPath, string recognitionModelPath, string dictionaryPath)
static bool PageNeedsOcr(PdfDocument document, int pageIndex)
string ExtractText(PdfDocument document, int pageIndex)
void Dispose()
  • Load — eine Engine aus Modelldateien laden.
  • PageNeedsOcr — heuristische Prüfung, ob einer Seite eine digitale Textebene fehlt.
  • ExtractText — OCR auf einer Seite ausführen.

Siehe auch PdfDocument.PrefetchModels, ModelManifest und PrefetchAvailable.


Digitale Signaturen

Signature

Handle pro Signatur aus PdfDocument.Signatures.

string? SignerName { get; }
string? Reason { get; }
string? Location { get; }
Certificate GetCertificate()
bool Verify()
bool VerifyDetached(ReadOnlySpan<byte> pdfData)
void Dispose()
  • Verify — die kryptografische Integrität der Signatur validieren.
  • VerifyDetached — zusätzlich den messageDigest gegen die übergebenen PDF-Bytes validieren.
  • GetCertificate — das Zertifikat des Unterzeichners.

Certificate

static Certificate LoadFromPem(string certPem, string keyPem)
static Certificate Load(byte[] data, string? password = null)
unsafe byte[] SignPdfBytes(byte[] pdfData, string? reason = null, string? location = null)
unsafe byte[] SignPdfBytesPades(byte[] pdfData, PadesSignOptions options)
void Dispose()
  • LoadFromPem / Load — ein Signaturzertifikat laden (PEM-Paar oder PKCS#12-Bytes mit optionalem Passwort).
  • SignPdfBytes — mit einer einfachen CMS-Signatur signieren.
  • SignPdfBytesPades — mit einem PAdES-Profil signieren (siehe PadesSignOptions).

Timestamp

static Timestamp Parse(byte[] data)
string Serial { get; }
string PolicyOid { get; }
string TsaName { get; }
bool Verify()
void Dispose()

TsaClient

static TsaClient Create(TsaClientOptions options)
Timestamp RequestTimestamp(byte[] data)
Timestamp RequestTimestampHash(byte[] hash, TimestampHashAlgorithm hashAlgorithm)
void Dispose()

TsaClientOptions (init-only): Url (erforderlich), Username, Password, TimeoutSeconds (= 30), HashAlgorithm (= Sha256), UseNonce (= true), CertReq (= true). Hinter dem Feature tsa-client.


Barcode

static Barcode GenerateQrCode(string data, int errorCorrection = 1, int sizePx = 300)
static Barcode Generate(string data, BarcodeFormat format = BarcodeFormat.Code128, int sizePx = 300)
byte[] ToPng(int sizePx = 300)
string ToSvg()
void Dispose()

BarcodeFormat: Code128, Code39, Ean13, Ean8, UpcA, Itf.


PdfValidator

Statische Konformitätsprüfungen. Jede gibt ein PdfValidationResult zurück.

static PdfValidationResult ValidatePdfA(PdfDocument document, PdfALevel level = PdfALevel.A2b)
static PdfValidationResult ValidatePdfX(PdfDocument document, PdfXLevel level = PdfXLevel.X4)
static PdfValidationResult ValidatePdfUA(PdfDocument document, PdfUaLevel level = PdfUaLevel.Ua1)

Datentypen

RgbaPixmap

public sealed record RgbaPixmap(ReadOnlyMemory<byte> Data, int Width, int Height);

Table

public sealed class Table
{
    public int RowCount { get; }
    public int ColCount { get; }
    public bool HasHeader { get; }
}

ExtractedImage

public sealed class ExtractedImage
{
    public int Width { get; }
    public int Height { get; }
    public string Format { get; }
    public string Colorspace { get; }
    public int BitsPerComponent { get; }
    public byte[] Data { get; }
}

FormField

public sealed class FormField
{
    public string Name { get; }
    public string FieldType { get; }
    public string Value { get; }
}

TableSpec

public sealed class TableSpec
{
    public List<Column> Columns { get; set; }
    public IList<IList<string>> Rows { get; set; }
    public bool HasHeader { get; set; }
}

public sealed class Column
{
    public string Header { get; set; }
    public float Width { get; set; }
    public Alignment Align { get; set; }
    public Column(string header, float width, Alignment align = Alignment.Left);
}

public abstract class TableMode
{
    public sealed class Fixed : TableMode { }
    public sealed class Sample : TableMode
    {
        public int SampleRows { get; init; }      // = 20
        public float MinColWidthPt { get; init; } // = 0
        public float MaxColWidthPt { get; init; } // = 9999
    }
}

public enum Alignment { Left = 0, Center = 1, Right = 2 }

RenderOptions

public sealed class RenderOptions
{
    public int Dpi { get; set; }                   // = 150
    public RenderImageFormat Format { get; set; }  // = Png
    public bool TransparentBackground { get; set; }
    public bool RenderAnnotations { get; set; }    // = true
    public int JpegQuality { get; set; }           // = 85
}

public enum RenderImageFormat { Png = 0, Jpeg = 1 }

PAdES- / DSS-Typen

public enum PadesLevel { BB = 0, BT = 1, BLt = 2, BLta = 3 }

public sealed class PadesSignOptions
{
    public PadesLevel Level { get; set; }            // = BB
    public string? TsaUrl { get; set; }
    public string? Reason { get; set; }
    public string? Location { get; set; }
    public RevocationMaterial? Revocation { get; set; }
}

public sealed class RevocationMaterial
{
    public IList<byte[]> Certificates { get; }
    public IList<byte[]> Crls { get; }
    public IList<byte[]> OcspResponses { get; }
}

public sealed class DocumentSecurityStore
{
    public IReadOnlyList<byte[]> Certificates { get; }
    public IReadOnlyList<byte[]> Crls { get; }
    public IReadOnlyList<byte[]> OcspResponses { get; }
    public int VriCount { get; }
}

public enum TimestampHashAlgorithm { Unknown = 0, Sha1 = 1, Sha256 = 2, Sha384 = 3, Sha512 = 4 }

Validierungstypen

public sealed class PdfValidationResult
{
    public bool IsCompliant { get; }
    public IReadOnlyList<string> Errors { get; }
    public IReadOnlyList<string> Warnings { get; }
}

public enum PdfALevel { A1b = 0, A1a = 1, A2b = 2, A2a = 3, A2u = 4, A3b = 5, A3a = 6, A3u = 7 }
public enum PdfXLevel { X1a = 0, X3 = 1, X4 = 2 }
public enum PdfUaLevel { Ua1 = 1, Ua2 = 2 }

Geometrie (PdfOxide.Geometry)

public struct Color : IEquatable<Color>
{
    public Color(byte red, byte green, byte blue);
    public Color(byte red, byte green, byte blue, byte alpha);
    public byte Red { get; }
    public byte Green { get; }
    public byte Blue { get; }
    public byte Alpha { get; }
    public static Color FromArgb(uint argb);
    public uint ToArgb();
    public string ToHex();
    public static Color Black { get; }
    public static Color White { get; }
    public static Color Yellow { get; }
    public static Color Cyan { get; }
    public static Color Magenta { get; }
}

public struct Point : IEquatable<Point>
{
    public Point(float x, float y);
    public float X { get; }
    public float Y { get; }
    public float Magnitude { get; }
    public float Distance(Point other);
    // operators: + - * / == !=
}

public struct Rect : IEquatable<Rect>
{
    public Rect(float x, float y, float width, float height);
    public float X { get; }
    public float Y { get; }
    public float Width { get; }
    public float Height { get; }
    public bool Contains(Point point);
    public bool Intersects(Rect other);
}

Exceptions

Alle nativen Fehler lösen PdfException aus (in PdfOxide.Exceptions):

public class PdfException : Exception
{
    public string Code { get; }
    public static string GetErrorMessage(int errorCode);
    public PdfException WithContext(string operation, params (string key, object? value)[] context);
}

Typisierte Unterklassen decken bestimmte Kategorien ab — zum Beispiel: ParseException, InvalidStructure, CorruptedData, UnsupportedVersion, EncryptionException, InvalidPassword, DecryptionFailed, UnsupportedAlgorithm, DocumentClosed, OperationNotAllowed, UnsupportedFeatureException, FeatureNotImplemented, FormatNotSupported, ValidationException, InvalidParameter, MissingRequired, RenderingException, RenderFailed, UnsupportedRenderFormat, SearchException, InvalidPattern, SignatureException, RedactionException, AccessibilityException, OptimizationException, ComplianceException, ComplianceFailed, OcrException, RecognitionFailed, LanguageNotSupported, ImageProcessingFailed, InternalError und XfaException.

try
{
    using var doc = PdfDocument.Open("file.pdf");
    var text = doc.ExtractText(0);
}
catch (InvalidPassword)
{
    // wrong / missing password
}
catch (UnsupportedFeatureException)
{
    // feature not compiled into this build (e.g. ocr, office)
}
catch (PdfException e)
{
    Console.Error.WriteLine($"{e.Code}: {e.Message}");
}

Für E/A (FileNotFoundException usw.) und Argumentvalidierung (ArgumentOutOfRangeException, ArgumentNullException) werden weiterhin die Standard-.NET-Exceptions ausgelöst.


Thread-Sicherheit

  • Die schreibgeschützten Methoden von PdfDocument sind thread-sicher — teilen Sie ein einzelnes Dokument über mehrere Threads hinweg.
  • DocumentEditor und die Builder sind für Schreibvorgänge nicht thread-sicher. Serialisieren Sie Schreibvorgänge auf einen Thread oder schützen Sie sie mit einem Lock.

Siehe den Nebenläufigkeits-Leitfaden.

Async-Muster

E/A-gebundene Methoden stellen *Async-Varianten bereit, die einen CancellationToken entgegennehmen (ExtractTextAsync, SaveAsync, SaveToStreamAsync sowie die Page.*Async-Familie). Siehe den Async-Leitfaden.

NativeAOT

Veröffentlichen mit -p:PublishAot=true. Keine zusätzliche Konfiguration — das gesamte P/Invoke ist source-generated, ohne Reflection, ohne dynamischen Code.


Vollständiges Beispiel

using PdfOxide.Core;

// --- Creation ---
using (var builder = DocumentBuilder.Create()
    .Title("Report").Author("PDF Oxide"))
{
    builder.LetterPage()
        .Heading(1, "Quarterly Report")
        .Paragraph("Generated by PDF Oxide.")
        .LinkUrl("https://oxide.fyi")
        .Done();
    builder.Save("report.pdf");
}

// --- Extraction ---
using var doc = PdfDocument.Open("report.pdf");
Console.WriteLine($"Pages: {doc.PageCount}");
foreach (var page in doc)
    Console.WriteLine($"Page {page.Index}: {page.ExtractText().Length} chars");

// Search with LINQ
var hits = doc.SearchAll("Report", caseSensitive: false)
    .GroupBy(r => r.Page);

// --- Editing ---
using (var editor = DocumentEditor.Open("report.pdf"))
{
    editor.Title = "Updated Title";
    editor.RotateAllPages(90);
    editor.SetFormFieldValue("name", "Jane Doe");
    editor.Save("report-updated.pdf");
}

// --- Rendering ---
byte[] png = doc.RenderPage(0, new RenderOptions { Dpi = 200, Format = RenderImageFormat.Png });
File.WriteAllBytes("page0.png", png);

Other Language Bindings

PDF Oxide bietet native Bindings für jedes wichtige Ökosystem: Rust, Python, Node.js, WASM, Golang, Java, PHP, Ruby, C++, Swift, Kotlin, Dart, R, Julia, Zig, Scala, Clojure, Objective-C und Elixir.

Nächste Schritte