Referência da API C# / .NET
O pacote NuGet PdfOxide encapsula o núcleo Rust via P/Invoke gerado por LibraryImport (todas as 881 declarações). Pronto para publicação com NativeAOT e trim-safe. Target frameworks: net8.0, net10.0.
dotnet add package PdfOxide
using PdfOxide.Core;
Para outras linguagens, veja Python, Node.js, Golang ou Rust.
Namespaces
using PdfOxide.Core; // PdfDocument, Pdf, DocumentEditor, DocumentBuilder, ...
using PdfOxide.Geometry; // Color, Point, Rect
using PdfOxide.Exceptions; // PdfException and typed subclasses
Todos os tipos com suporte nativo implementam IDisposable — use blocos using ou declarações using. As coordenadas estão em pontos PDF a partir da origem inferior esquerda, salvo indicação em contrário; canais de cor passados como floats vão de 0.0 a 1.0.
PdfDocument
Handle somente leitura / de extração. PdfDocument é enumerável e indexável, produzindo handles Page preguiçosos (lazy).
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 a partir de um caminho, stream, array de bytes ou span.OpenWithPassword(path, password)— abre um PDF criptografado em uma única etapa.OpenFromDocxBytes/OpenFromPptxBytes/OpenFromXlsxBytes— converte bytes de Office e abre o resultado como um PDF (requer a featureoffice).
Propriedades
(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
Autenticação
bool Authenticate(string password)
Autentica um documento criptografado depois de aberto, usando uma senha de usuário ou de proprietário. Retorna true em caso de sucesso.
Extração 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 puro de uma página ou do documento inteiro.ExtractTextInRect— texto dentro de uma região retangular.ExtractWords/ExtractWordsInRect— palavras com bounding boxes (opcionalmente recortadas por região).ExtractTextLines— linhas com bounding boxes.ExtractChars— posições por glifo.ExtractPaths— segmentos de caminhos vetoriais com larguras de traço.ExtractTables— tabelas detectadas (vejaTable).
Classificação e extração 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 estruturado com o conteúdo da página.ClassifyPage/ClassifyDocument— classifica uma página ou o documento inteiro (por exemplo, digitalizado vs. digital).ExtractTextAuto— roteia automaticamente uma página pelo melhor caminho de texto (digital ou OCR).ExtractPageAuto— extração automática com um blob opcional de opções JSON.
Conversão
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) — converte uma página ou o documento inteiro.ToDocxBytes/ToPptxBytes/ToXlsxBytes— exporta para formatos Office (requer a featureoffice).
Limpeza de conteúdo
int RemoveHeaders(float threshold = 0.8f)
int RemoveFooters(float threshold = 0.8f)
int RemoveArtifacts(float threshold = 0.8f)
Detecta e remove cabeçalhos, rodapés ou artefatos de página recorrentes. Retorna o número de elementos removidos. threshold é a razão de recorrência entre páginas.
Busca
(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 em todo o documento ou em uma única página; retorna as ocorrências com índice de página e bounding box.
Estrutura e metadados
string GetPageLabels()
string GetXmpMetadata()
string GetOutline()
string PlanSplitByBookmarks(int level, string? namePattern = null)
string[] GetFonts(int pageIndex)
GetPageLabels— intervalos de rótulos de página (JSON).GetXmpMetadata— metadados XMP (pacote JSON / XML).GetOutline— árvore de marcadores / sumário (JSON).PlanSplitByBookmarks— calcula um plano de divisão em um nível de marcador.GetFonts— nomes de fontes usadas em uma página.
Imagens
ExtractedImage[] ExtractImages(int pageIndex)
Extrai imagens incorporadas com metadados e bytes brutos (veja ExtractedImage).
Formulários
FormField[] GetFormFields()
Enumera os campos de AcroForm (veja FormField).
Renderização
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 no DPI padrão (format:0= PNG,1= JPEG) ou comRenderOptionscompletas.RenderPageZoom— renderiza com um fator de zoom.RenderPageFit— renderiza dimensionado para caber em uma caixa de pixels.RenderThumbnail— renderiza uma miniatura pequena.RenderToRgba— renderiza para um pixmap RGBA bruto (vejaRgbaPixmap).SaveRenderedImage— renderiza e grava diretamente em um arquivo.
Assinaturas
unsafe DocumentSecurityStore? GetDss()
bool HasDocumentTimestamp()
GetDss— lê o Document Security Store (DSS), se presente.HasDocumentTimestamp— indica se há um timestamp em nível de documento.
Veja Signature para verificação por assinatura.
Configuração 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— controlam a verbosidade do log nativo.PrefetchModels/ModelManifest/PrefetchAvailable— gerenciam os downloads de modelos de OCR.GetActiveCryptoProvider/IsFipsCryptoAvailable/UseFipsCryptoProvider— seleção do provedor de criptografia (FIPS).SetCryptoPolicy/CryptoPolicy— obtêm/definem a política de criptografia ativa.CryptoInventory/CryptoCbom— enumeram o uso de criptografia / emitem um CBOM.
Dispose
void Dispose()
Page
Handle preguiçoso (lazy) por página, obtido a partir de doc[i] ou de iteração. Todos os membros despacham para o documento pai.
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 — criação
Cria um PDF a partir de um formato de origem e, em seguida, salva.
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— cria a partir de formatos de texto.FromHtmlCss/FromHtmlCssWithFonts— pipeline HTML + CSS com fontes incorporadas.FromImage/FromImageBytes— PDF de página única a partir de uma imagem.Save/SaveToBytes/SaveToStream(+ async) — persiste o resultado.
DocumentEditor
Editor mutável para PDFs existentes: metadados, páginas, formulários, redação e criptografia.
Abrir e salvar
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()
Propriedades
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; }
Operações 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— anexa páginas de outro PDF (MergeFromBytesretorna a contagem de páginas mescladas).DeletePage/MovePage— remove ou reordena páginas.GetPageRotation/SetPageRotation/RotateAllPages/RotatePageBy— controle de rotação (absoluta vs. relativa).CropMargins— recorta todas as margens da página.Get/SetPageMediaBoxeGet/SetPageCropBox— caixas de geometria da página.
Apagar / whiteout
void EraseRegion(int pageIndex, float x, float y, float width, float height)
void EraseRegions(int pageIndex, double[][] rects)
void ClearEraseRegions(int pageIndex)
Anotações e formulários
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)
Redação
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— enfileira um retângulo de redação com uma cor de preenchimento.ApplyPageRedactions/ApplyAllRedactions/ApplyRedactions— aplica as redações pendentes de forma permanente (ApplyRedactionsopcionalmente limpa metadados/texto oculto).SanitizeDocument— remove dados ocultos/não referenciados; retorna a quantidade removida.
Outros
void EmbedFile(string name, byte[] data)
void ConvertToPdfA(PdfALevel level = PdfALevel.A2b)
EmbedFile— anexa um arquivo ao PDF.ConvertToPdfA— converte para um nível de conformidade PDF/A.
As assinaturas exatas de
AddRedaction/ApplyRedactionsusam argumentos nativos em snake-case nos bastidores; a superfície C# mostrada aqui é o binding público.
DocumentBuilder
Builder fluente para novos documentos. DocumentBuilder.Create() → metadados → 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
Superfície fluente por página retornada por A4Page() / LetterPage() / Page(w, h). Cada método retorna o builder para encadeamento; Done() confirma a página de volta ao pai.
Texto e 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()
Trechos inline
PageBuilder Inline(string text)
PageBuilder InlineBold(string text)
PageBuilder InlineItalic(string text)
PageBuilder InlineColor(float r, float g, float b, string text)
Links e 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)
Anotações
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 formulário
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)
Imagens e 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)
Tabelas
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 uma tabela totalmente materializada a partir de umTableSpec.StreamingTable— abre uma tabela em streaming para dados grandes / linha por linha (vejaStreamingTable).Done— confirma a página e retorna oDocumentBuilderpai.
EmbeddedFont
static EmbeddedFont FromFile(string path)
static EmbeddedFont FromBytes(byte[] data, string? name = null)
void Dispose()
Carrega uma fonte TTF/OTF para incorporação via DocumentBuilder.RegisterEmbeddedFont.
StreamingTable
Builder de tabela linha por linha para grandes volumes de dados, retornado 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— anexa uma linha de células.AddRowSpan— anexa uma linha com rowspans por célula (requermaxRowspan >= 2).Flush— descarrega as linhas em buffer para a camada nativa.Build— finaliza e retorna oPageBuilderpai.
OcrEngine
OCR sobre PDFs digitalizados (requer a feature ocr). Os modelos são carregados a partir dos caminhos de detecção / reconhecimento / dicionário.
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— carrega um engine a partir de arquivos de modelo.PageNeedsOcr— verificação heurística sobre se uma página não tem uma camada de texto digital.ExtractText— executa o OCR em uma página.
Veja também PdfDocument.PrefetchModels, ModelManifest e PrefetchAvailable.
Assinaturas digitais
Signature
Handle por assinatura, obtido 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 a integridade criptográfica da assinatura.VerifyDetached— valida adicionalmente omessageDigestem relação aos bytes do PDF fornecidos.GetCertificate— o certificado do signatário.
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— carrega um certificado de assinatura (par PEM, ou bytes PKCS#12 com senha opcional).SignPdfBytes— assina com uma assinatura CMS básica.SignPdfBytesPades— assina com um perfil PAdES (vejaPadesSignOptions).
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 (somente init): Url (obrigatório), Username, Password, TimeoutSeconds (= 30), HashAlgorithm (= Sha256), UseNonce (= true), CertReq (= true). Sob a 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
Verificações estáticas de conformidade. Cada uma retorna um 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 dados
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 validação
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 }
Geometria (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);
}
Exceções
Todas as falhas nativas lançam PdfException (em 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);
}
Subclasses tipadas cobrem categorias específicas — por exemplo: 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 e 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}");
}
Exceções padrão do .NET continuam sendo lançadas para I/O (FileNotFoundException, etc.) e validação de argumentos (ArgumentOutOfRangeException, ArgumentNullException).
Thread safety
- Os métodos somente leitura de
PdfDocumentsão thread-safe — compartilhe um único documento entre threads. DocumentEditore os builders não são thread-safe para escrita. Serialize as escritas em uma única thread ou proteja com um lock.
Veja o guia de concorrência.
Padrão assíncrono
Os métodos limitados por I/O expõem variantes *Async que aceitam CancellationToken (ExtractTextAsync, SaveAsync, SaveToStreamAsync e a família Page.*Async). Veja o guia assíncrono.
NativeAOT
Publique com -p:PublishAot=true. Sem configuração extra — todo o P/Invoke é gerado pelo compilador, sem reflection e sem código dinâmico.
Exemplo 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
O PDF Oxide oferece bindings nativos para todos os principais ecossistemas: Rust, Python, Node.js, WASM, Golang, Java, PHP, Ruby, C++, Swift, Kotlin, Dart, R, Julia, Zig, Scala, Clojure, Objective-C e Elixir.
Próximos passos
- Tipos e Enums — todos os tipos e enums compartilhados
- Referência da API Page — iteração consistente por página entre os bindings
- Primeiros Passos com C# — tutorial