Referencia de la API de C# / .NET
El paquete NuGet PdfOxide envuelve el núcleo Rust mediante P/Invoke generado con LibraryImport (las 881 declaraciones). Listo para publicación con NativeAOT y trim-safe. Target frameworks: net8.0, net10.0.
dotnet add package PdfOxide
using PdfOxide.Core;
Para otros lenguajes consulta Python, Node.js, Golang o Rust.
Namespaces
using PdfOxide.Core; // PdfDocument, Pdf, DocumentEditor, DocumentBuilder, ...
using PdfOxide.Geometry; // Color, Point, Rect
using PdfOxide.Exceptions; // PdfException and typed subclasses
Todos los tipos respaldados por código nativo implementan IDisposable — usa bloques using o declaraciones using. Las coordenadas están en puntos PDF desde el origen inferior izquierdo salvo que se indique lo contrario; los canales de color pasados como floats van de 0.0 a 1.0.
PdfDocument
Handle de solo lectura / extracción. PdfDocument es enumerable e indexable, y produce handles Page perezosos.
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(...)— abre desde una ruta, un stream, un arreglo de bytes o un span.OpenWithPassword(path, password)— abre un PDF cifrado en un solo paso.OpenFromDocxBytes/OpenFromPptxBytes/OpenFromXlsxBytes— convierte bytes de Office y abre el resultado como un PDF (requiere la featureoffice).
Propiedades
(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
Autenticación
bool Authenticate(string password)
Autentica un documento cifrado tras abrirlo, con una contraseña de usuario o de propietario. Devuelve true si tiene éxito.
Extracción de texto
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— texto plano de una página o de todo el documento.ExtractTextInRect— texto dentro de una región rectangular.ExtractWords/ExtractWordsInRect— palabras con sus bounding boxes (opcionalmente recortadas a una región).ExtractTextLines— líneas con sus bounding boxes.ExtractChars— posiciones por glifo.ExtractPaths— segmentos de trazo vectorial con sus anchos de línea.ExtractTables— tablas detectadas (consultaTable).
Clasificación y extracción automática
string ExtractStructured(int page)
string ClassifyPage(int pageIndex)
string ClassifyDocument()
string ExtractTextAuto(int pageIndex)
string ExtractPageAuto(int pageIndex, string? optionsJson = null)
ExtractStructured— JSON estructurado del contenido de la página.ClassifyPage/ClassifyDocument— clasifica una página o el documento completo (p. ej. escaneado vs. digital).ExtractTextAuto— enruta automáticamente una página a la mejor vía de texto (digital u OCR).ExtractPageAuto— extracción automática con un blob de opciones JSON opcional.
Conversión
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) — convierte una página o el documento completo.ToDocxBytes/ToPptxBytes/ToXlsxBytes— exporta a formatos Office (requiere la featureoffice).
Limpieza de contenido
int RemoveHeaders(float threshold = 0.8f)
int RemoveFooters(float threshold = 0.8f)
int RemoveArtifacts(float threshold = 0.8f)
Detecta y elimina encabezados, pies de página o artefactos de página recurrentes. Devuelve la cantidad de elementos eliminados. threshold es el ratio de recurrencia entre páginas.
Búsqueda
(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)
Busca en todo el documento o en una sola página; devuelve las coincidencias con el índice de página y el bounding box.
Estructura y metadatos
string GetPageLabels()
string GetXmpMetadata()
string GetOutline()
string PlanSplitByBookmarks(int level, string? namePattern = null)
string[] GetFonts(int pageIndex)
GetPageLabels— rangos de etiquetas de página (JSON).GetXmpMetadata— metadatos XMP (JSON / paquete XML).GetOutline— árbol de marcadores / tabla de contenidos (JSON).PlanSplitByBookmarks— calcula un plan de división en un nivel de marcador.GetFonts— nombres de las fuentes usadas en una página.
Imágenes
ExtractedImage[] ExtractImages(int pageIndex)
Extrae imágenes incrustadas con sus metadatos y bytes en bruto (consulta ExtractedImage).
Formularios
FormField[] GetFormFields()
Enumera los campos de AcroForm (consulta FormField).
Renderizado
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— renderiza con el DPI predeterminado (format:0= PNG,1= JPEG) o conRenderOptionscompleto.RenderPageZoom— renderiza con un factor de zoom.RenderPageFit— renderiza escalado para ajustarse a un recuadro de píxeles.RenderThumbnail— renderiza una miniatura pequeña.RenderToRgba— renderiza a un pixmap RGBA en bruto (consultaRgbaPixmap).SaveRenderedImage— renderiza y escribe directamente a un archivo.
Firmas
unsafe DocumentSecurityStore? GetDss()
bool HasDocumentTimestamp()
GetDss— lee el Document Security Store (DSS), si está presente.HasDocumentTimestamp— indica si existe un timestamp a nivel de documento.
Consulta Signature para la verificación por firma.
Configuración estática
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— controlan el nivel de detalle del log nativo.PrefetchModels/ModelManifest/PrefetchAvailable— gestionan la descarga de los modelos de OCR.GetActiveCryptoProvider/IsFipsCryptoAvailable/UseFipsCryptoProvider— selección del proveedor criptográfico (FIPS).SetCryptoPolicy/CryptoPolicy— obtienen/establecen la política criptográfica activa.CryptoInventory/CryptoCbom— enumeran el uso de criptografía / emiten un CBOM.
Dispose
void Dispose()
Page
Handle perezoso por página obtenido con doc[i] o por iteración. Todos los miembros delegan en el documento padre.
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 — creación
Crea un PDF a partir de un formato de origen y luego guárdalo.
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— crea a partir de formatos de texto.FromHtmlCss/FromHtmlCssWithFonts— pipeline HTML + CSS con fuentes incrustadas.FromImage/FromImageBytes— PDF de una sola página a partir de una imagen.Save/SaveToBytes/SaveToStream(+ async) — persiste el resultado.
DocumentEditor
Editor mutable para PDFs existentes: metadatos, páginas, formularios, redacción y cifrado.
Abrir y guardar
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()
Propiedades
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; }
Operaciones de página
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— añade páginas de otro PDF (MergeFromBytesdevuelve el número de páginas combinadas).DeletePage/MovePage— elimina o reordena páginas.GetPageRotation/SetPageRotation/RotateAllPages/RotatePageBy— control de rotación (absoluta vs. relativa).CropMargins— recorta todos los márgenes de la página.Get/SetPageMediaBoxyGet/SetPageCropBox— recuadros de geometría de la página.
Borrado / whiteout
void EraseRegion(int pageIndex, float x, float y, float width, float height)
void EraseRegions(int pageIndex, double[][] rects)
void ClearEraseRegions(int pageIndex)
Anotaciones y formularios
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)
Redacción
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— encola un rectángulo de redacción con un color de relleno.ApplyPageRedactions/ApplyAllRedactions/ApplyRedactions— aplica de forma permanente las redacciones pendientes (ApplyRedactionsopcionalmente depura los metadatos/el texto oculto).SanitizeDocument— elimina datos ocultos/no referenciados; devuelve la cantidad depurada.
Otros
void EmbedFile(string name, byte[] data)
void ConvertToPdfA(PdfALevel level = PdfALevel.A2b)
EmbedFile— adjunta un archivo al PDF.ConvertToPdfA— convierte a un nivel de conformidad PDF/A.
Las firmas exactas de
AddRedaction/ApplyRedactionsusan internamente argumentos nativos en snake-case; la superficie de C# mostrada aquí es el binding público.
DocumentBuilder
Builder fluido para documentos nuevos. DocumentBuilder.Create() → metadatos → página(s) → 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
Superficie fluida por página devuelta por A4Page() / LetterPage() / Page(w, h). Cada método devuelve el builder para encadenar; Done() confirma la página de vuelta al padre.
Texto y maquetación
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()
Runs en línea
PageBuilder Inline(string text)
PageBuilder InlineBold(string text)
PageBuilder InlineItalic(string text)
PageBuilder InlineColor(float r, float g, float b, string text)
Enlaces y JavaScript
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)
Anotaciones
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)
Widgets de formulario
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)
Gráficos
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)
Imágenes y códigos de barras
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)
Tablas
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— renderiza una tabla totalmente materializada a partir de unTableSpec.StreamingTable— abre una tabla en streaming para datos grandes o fila a fila (consultaStreamingTable).Done— confirma la página y devuelve elDocumentBuilderpadre.
EmbeddedFont
static EmbeddedFont FromFile(string path)
static EmbeddedFont FromBytes(byte[] data, string? name = null)
void Dispose()
Carga una fuente TTF/OTF para incrustarla con DocumentBuilder.RegisterEmbeddedFont.
StreamingTable
Builder de tablas fila a fila para grandes conjuntos de datos, devuelto por PageBuilder.StreamingTable(...).
unsafe StreamingTable AddRow(params string[] cells)
unsafe StreamingTable AddRowSpan(params (string? Text, int Rowspan)[] cells)
void Flush()
PageBuilder Build()
void Dispose()
AddRow— añade una fila de celdas.AddRowSpan— añade una fila con rowspans por celda (requieremaxRowspan >= 2).Flush— vuelca las filas en búfer a la capa nativa.Build— finaliza y devuelve elPageBuilderpadre.
OcrEngine
OCR sobre PDFs escaneados (requiere la feature ocr). Los modelos se cargan desde las rutas de detección / reconocimiento / diccionario.
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— carga un motor a partir de archivos de modelo.PageNeedsOcr— comprobación heurística de si una página carece de capa de texto digital.ExtractText— ejecuta OCR sobre una página.
Consulta también PdfDocument.PrefetchModels, ModelManifest y PrefetchAvailable.
Firmas digitales
Signature
Handle por firma obtenido de PdfDocument.Signatures.
string? SignerName { get; }
string? Reason { get; }
string? Location { get; }
Certificate GetCertificate()
bool Verify()
bool VerifyDetached(ReadOnlySpan<byte> pdfData)
void Dispose()
Verify— valida la integridad criptográfica de la firma.VerifyDetached— además valida elmessageDigestfrente a los bytes del PDF suministrado.GetCertificate— el certificado del firmante.
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— carga un certificado de firma (par PEM, o bytes PKCS#12 con contraseña opcional).SignPdfBytes— firma con una firma CMS básica.SignPdfBytesPades— firma con un perfil PAdES (consultaPadesSignOptions).
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 (solo init): Url (obligatorio), Username, Password, TimeoutSeconds (= 30), HashAlgorithm (= Sha256), UseNonce (= true), CertReq (= true). Detrás de la 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
Comprobaciones de conformidad estáticas. Cada una devuelve un PdfValidationResult.
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)
Tipos de datos
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 }
Tipos PAdES / DSS
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 }
Tipos de validación
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 }
Geometría (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);
}
Excepciones
Todos los fallos nativos lanzan PdfException (en 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);
}
Las subclases tipadas cubren categorías específicas — por ejemplo: 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 y 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}");
}
Las excepciones estándar de .NET se siguen lanzando para E/S (FileNotFoundException, etc.) y validación de argumentos (ArgumentOutOfRangeException, ArgumentNullException).
Seguridad entre hilos
- Los métodos de solo lectura de
PdfDocumentson thread-safe — comparte un único documento entre hilos. DocumentEditory los builders no son thread-safe para escrituras. Serializa las escrituras en un solo hilo o protégelas con un lock.
Consulta la guía de concurrencia.
Patrón async
Los métodos ligados a E/S exponen variantes *Async que aceptan CancellationToken (ExtractTextAsync, SaveAsync, SaveToStreamAsync y la familia Page.*Async). Consulta la guía async.
NativeAOT
Publica con -p:PublishAot=true. Sin configuración adicional — todo el P/Invoke se genera por fuente, sin reflexión y sin código dinámico.
Ejemplo completo
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 ofrece bindings nativos para todos los ecosistemas principales: Rust, Python, Node.js, WASM, Golang, Java, PHP, Ruby, C++, Swift, Kotlin, Dart, R, Julia, Zig, Scala, Clojure, Objective-C y Elixir.
Próximos pasos
- Tipos y enums — todos los tipos y enums compartidos
- Referencia de la API Page — iteración de página consistente entre bindings
- Primeros pasos con C# — tutorial