Referência da API Swift
O PDF Oxide oferece bindings idiomáticos de Swift sobre a C ABI nativa. Um módulo de biblioteca de sistema CPdfOxide expõe o header do cbindgen por meio de um module map, e PdfOxide é o wrapper em Swift. Os handles pertencem a classes (liberados no deinit), as strings e buffers de C retornados são copiados para String/[UInt8] do Swift, e os códigos de erro diferentes de sucesso são lançados como PdfOxideError.
// Package.swift
dependencies: [
.package(url: "https://github.com/yfedoseev/pdf_oxide", from: "0.3.69"),
],
targets: [
.target(name: "YourTarget", dependencies: [
.product(name: "PdfOxide", package: "pdf_oxide"),
]),
]
import PdfOxide
Para a API Rust, consulte a Referência da API Rust. Para a API Python, consulte a Referência da API Python. Para detalhes dos tipos, consulte Tipos e Enums.
Todos os índices de página começam em zero. A maioria dos métodos é throws e lança PdfOxideError em um código de erro da C-ABI diferente de sucesso.
Document
A classe principal para abrir, extrair, renderizar e inspecionar arquivos PDF. Obtenha instâncias por meio dos métodos de fábrica estáticos open*.
Abertura
static func open(_ path: String) throws -> Document
Abre um PDF a partir de um caminho de arquivo.
static func openFromBytes(_ bytes: [UInt8]) throws -> Document
Abre um PDF a partir de bytes em memória (por exemplo, baixados do S3 ou recebidos via HTTP).
static func openWithPassword(_ path: String, password: String) throws -> Document
Abre um PDF criptografado com uma senha de usuário ou de proprietário.
static func openFromDocxBytes(_ bytes: [UInt8]) throws -> Document
static func openFromPptxBytes(_ bytes: [UInt8]) throws -> Document
static func openFromXlsxBytes(_ bytes: [UInt8]) throws -> Document
Converte um documento do Office (DOCX, PPTX, XLSX) a partir de bytes em memória para um Document.
func authenticate(_ password: String) throws -> Bool
Autentica um documento criptografado já aberto. Retorna true em caso de sucesso.
func close()
Libera o handle nativo imediatamente (idempotente; também é executado no deinit).
Informações do Documento
func pageCount() throws -> Int
func version() throws -> PdfVersion
func isEncrypted() throws -> Bool
func hasStructureTree() throws -> Bool
func hasXfa() throws -> Bool
func page(_ index: Int) -> Page
Acessores gerais de metadados do documento. page(_:) retorna um handle leve Page para o índice informado.
Extração de Texto
func extractText(_ page: Int) throws -> String
Extrai texto puro de uma única página.
func extractChars(_ pageIndex: Int) throws -> [Char]
Extrai o posicionamento por caractere e os metadados de fonte.
func extractWords(_ pageIndex: Int) throws -> [Word]
Extrai palavras com bounding boxes, nome/tamanho da fonte e flag de negrito.
func extractTextLines(_ pageIndex: Int) throws -> [TextLine]
Extrai texto agrupado em linhas, com contagem de palavras e bounding boxes.
func extractTables(_ pageIndex: Int) throws -> [Table]
Detecta e extrai tabelas com linhas, colunas, cabeçalhos e texto das células.
func extractStructuredJson(_ page: Int) throws -> String
Extrai uma representação JSON estruturada do conteúdo de uma página.
Extração e Classificação Automáticas
func extractTextAuto(_ pageIndex: Int) throws -> String
Detecta automaticamente o melhor caminho de extração e retorna o texto de uma página.
func extractAllText() throws -> String
Extrai texto de todas as páginas do documento.
func extractPageAuto(_ pageIndex: Int, optionsJson: String = "{}") throws -> String
Extrai uma página automaticamente usando opções configuradas via JSON.
func classifyPage(_ pageIndex: Int) throws -> String
func classifyDocument() throws -> String
Classifica uma única página ou o documento inteiro (por exemplo, digitalizado vs. digital).
Extração por Região
func extractTextInRect(_ pageIndex: Int, x: Float, y: Float, w: Float, h: Float) throws -> String
func extractWordsInRect(_ pageIndex: Int, x: Float, y: Float, w: Float, h: Float) throws -> [Word]
func extractLinesInRect(_ pageIndex: Int, x: Float, y: Float, w: Float, h: Float) throws -> [TextLine]
func extractTablesInRect(_ pageIndex: Int, x: Float, y: Float, w: Float, h: Float) throws -> [Table]
func extractImagesInRect(_ pageIndex: Int, x: Float, y: Float, w: Float, h: Float) throws -> [Image]
Extrai conteúdo restrito a um retângulo (x, y, w, h) (pontos do espaço de usuário do PDF, com origem no canto inferior esquerdo).
Conversão
func toPlainText(_ page: Int) throws -> String
func toMarkdown(_ page: Int) throws -> String
func toHtml(_ page: Int) throws -> String
Converte uma única página para texto puro, Markdown ou HTML.
func toPlainTextAll() throws -> String
func toMarkdownAll() throws -> String
func toHtmlAll() throws -> String
Converte todas as páginas para texto puro, Markdown ou HTML.
Exportação para Office
func toDocx() throws -> [UInt8]
func toPptx() throws -> [UInt8]
func toXlsx() throws -> [UInt8]
Exporta o documento para bytes DOCX, PPTX ou XLSX.
Imagens, Fontes e Paths
func embeddedImages(_ pageIndex: Int) throws -> [Image]
Extrai imagens raster incorporadas (com os bytes brutos) de uma página.
func embeddedFonts(_ pageIndex: Int) throws -> [Font]
Lista as fontes incorporadas de uma página, com tipo, codificação e flags de subset.
func extractPaths(_ pageIndex: Int) throws -> [Path]
Extrai paths vetoriais (linhas, curvas, formas) de uma página.
func fontsToJson(_ pageIndex: Int) throws -> String
func fontSize(_ pageIndex: Int, fontIndex: Int) throws -> Float
Serializa as fontes da página para JSON ou lê o tamanho de uma única fonte.
Anotações
func pageAnnotations(_ pageIndex: Int) throws -> [Annotation]
Extrai anotações (tipo, subtipo, conteúdo, autor, rect) de uma página.
func annotationsToJson(_ pageIndex: Int) throws -> String
Serializa as anotações de uma página para JSON.
func annotationExtras(_ pageIndex: Int, index: Int) throws -> AnnotationExtras
Lê atributos estendidos de anotação (cor, datas, flags, URI, ícone, quad points).
Busca
func search(_ pageIndex: Int, _ term: String, _ caseSensitive: Bool) throws -> [SearchResult]
Busca texto em uma única página.
func searchAll(_ term: String, _ caseSensitive: Bool) throws -> [SearchResult]
Busca texto em todo o documento.
func searchResultsToJson(_ pageIndex: Int, _ term: String, caseSensitive: Bool) throws -> String
Busca em uma página e serializa as correspondências para JSON.
Geometria da Página
func pageWidth(_ pageIndex: Int) throws -> Float
func pageHeight(_ pageIndex: Int) throws -> Float
func pageRotation(_ pageIndex: Int) throws -> Int
func pageElements(_ pageIndex: Int) throws -> ElementList
Lê as dimensões da página, a rotação e uma lista genérica de elementos da página.
Renderização
func renderPage(_ pageIndex: Int, format: Int32 = 0) throws -> RenderedImage
Renderiza uma página para uma RenderedImage (PNG quando format é 0, JPEG quando 1).
func renderPageZoom(_ pageIndex: Int, zoom: Float, format: Int32 = 0) throws -> RenderedImage
Renderiza uma página com um fator de zoom.
func renderPageThumbnail(_ pageIndex: Int, size: Int, format: Int32 = 0) throws -> RenderedImage
Renderiza uma miniatura que cabe dentro de size pixels.
func renderPageWithOptions(
_ pageIndex: Int, dpi: Int32 = 150, format: Int32 = 0,
bgR: Float = 1, bgG: Float = 1, bgB: Float = 1, bgA: Float = 1,
transparentBackground: Bool = false, renderAnnotations: Bool = true, jpegQuality: Int32 = 90
) throws -> RenderedImage
Renderiza com o conjunto completo de opções de renderização (DPI, cor/alfa de fundo, anotações, qualidade JPEG).
func renderPageWithOptionsEx(
_ pageIndex: Int, dpi: Int32 = 150, format: Int32 = 0,
bgR: Float = 1, bgG: Float = 1, bgB: Float = 1, bgA: Float = 1,
transparentBackground: Bool = false, renderAnnotations: Bool = true,
jpegQuality: Int32 = 90, excludedLayers: [String] = []
) throws -> RenderedImage
Renderiza com as opções completas mais uma lista de nomes de camadas OCG a suprimir.
func renderPageRegion(
_ pageIndex: Int, cropX: Float, cropY: Float, cropWidth: Float, cropHeight: Float,
format: Int32 = 0
) throws -> RenderedImage
Renderiza uma região retangular de uma página.
func renderPageFit(_ pageIndex: Int, width: Int32, height: Int32, format: Int32 = 0) throws -> RenderedImage
Renderiza uma página para caber dentro de width×height pixels, preservando a proporção.
func renderPageRaw(_ pageIndex: Int, dpi: Int32 = 150) throws -> (image: RenderedImage, width: Int, height: Int)
Renderiza para um buffer RGBA8888 premultiplicado bruto, além das dimensões em pixels.
func estimateRenderTime(_ pageIndex: Int) throws -> Int32
Estima o custo de renderização de uma página (unidades definidas pela implementação).
OCR
func ocrPageNeedsOcr(_ pageIndex: Int) throws -> Bool
Decide heuristicamente se uma página precisa de OCR (por exemplo, uma página digitalizada).
func ocrExtractText(_ pageIndex: Int, engine: OcrEngine? = nil) throws -> String
Extrai texto via OCR. Passe um OcrEngine personalizado ou nil para o engine padrão.
Formulários
func formFields() throws -> [FormField]
Lista todos os campos de formulário com nome, valor, tipo e flags de somente leitura/obrigatório.
func exportFormData(formatType: Int32) throws -> [UInt8]
Exporta os dados do formulário como bytes FDF/XFDF.
func importFormData(_ dataPath: String) throws -> Int32
func importFormFromFile(_ filename: String) throws -> Bool
Importa dados de formulário a partir de um caminho de arquivo.
Estrutura do Documento
func outline() throws -> String
func pageLabels() throws -> String
func xmpMetadata() throws -> String
func sourceBytes() throws -> [UInt8]
func planSplitByBookmarks(optionsJson: String = "{}") throws -> String
Lê o outline do documento, os rótulos de página, os metadados XMP, os bytes brutos da origem ou um plano de divisão em JSON baseado em bookmarks.
Limpeza de Conteúdo
func eraseHeader(_ pageIndex: Int) throws -> Int32
func eraseFooter(_ pageIndex: Int) throws -> Int32
func eraseArtifacts(_ pageIndex: Int) throws -> Int32
func removeHeaders(threshold: Float) throws -> Int32
func removeFooters(threshold: Float) throws -> Int32
func removeArtifacts(threshold: Float) throws -> Int32
Apaga cabeçalhos/rodapés/artefatos de uma única página ou de todo o documento usando um limiar de frequência.
Validação
func validatePdfA(_ level: Int32) throws -> PdfAResults
func validatePdfUa(_ level: Int32) throws -> UaResults
func validatePdfX(_ level: Int32) throws -> PdfXResults
Valida o documento contra os níveis de conformidade PDF/A, PDF/UA ou PDF/X.
func convertToPdfA(_ level: Int32) throws -> Bool
Converte o documento para PDF/A no lugar. Retorna true em caso de sucesso.
Assinaturas
func sign(_ certificate: Certificate, reason: String, location: String) throws -> Int32
Assina o documento com um certificado, incorporando o motivo e o local.
func signatureCount() throws -> Int
func signature(_ index: Int) throws -> SignatureInfo?
func verifyAllSignatures() throws -> Int32
func hasTimestamp() throws -> Bool
func dss() throws -> Dss?
Inspeciona assinaturas existentes, verifica todas as assinaturas (1=válida, 0=inválida, -1=desconhecida), checa por um timestamp de documento e acessa o Document Security Store.
Códigos de Barras
func addBarcodeToPage(_ page: Int, _ barcode: BarcodeImage, x: Float, y: Float, width: Float, height: Float) throws
Desenha uma BarcodeImage gerada em uma página na posição e no tamanho indicados.
Page
Um handle leve por página, retornado por Document.page(_:). Todos os acessores delegam ao documento pai.
let index: Int
O índice da página, começando em zero.
func text() throws -> String
func markdown() throws -> String
func html() throws -> String
func plainText() throws -> String
Extrai a página como texto puro, Markdown ou HTML.
Uma classe para criar PDFs a partir de formatos de origem e salvá-los.
Métodos de Fábrica
static func fromMarkdown(_ md: String) throws -> Pdf
static func fromHtml(_ html: String) throws -> Pdf
static func fromText(_ text: String) throws -> Pdf
Cria um PDF a partir de Markdown, HTML ou texto puro.
static func fromImage(_ path: String) throws -> Pdf
static func fromImageBytes(_ bytes: [UInt8]) throws -> Pdf
Cria um PDF de página única a partir de um arquivo de imagem ou de bytes de imagem.
static func fromHtmlCss(html: String, css: String, fontBytes: [UInt8] = []) throws -> Pdf
Cria um PDF a partir de HTML + CSS com uma fonte incorporada opcional.
static func fromHtmlCssWithFonts(html: String, css: String, fonts: [(String, [UInt8])]) throws -> Pdf
Cria um PDF a partir de HTML + CSS com várias fontes nomeadas.
Métodos
func save(_ path: String) throws
func toBytes() throws -> [UInt8]
func pageCount() throws -> Int
func close()
Salva em um arquivo, obtém os bytes do PDF, conta as páginas ou libera o handle.
DocumentEditor
Um editor mutável para modificar PDFs existentes: páginas, rotação, geometria, redação, achatamento, formulários, merge e salvamento.
Abertura e Ciclo de Vida
static func openEditor(_ path: String) throws -> DocumentEditor
static func open(_ path: String) throws -> DocumentEditor
static func openFromBytes(_ bytes: [UInt8]) throws -> DocumentEditor
func close()
func free()
Abre um editor a partir de um caminho ou de bytes e libera o handle ao terminar.
Informações e Metadados
func pageCount() throws -> Int
func version() throws -> PdfVersion
func isModified() throws -> Bool
func getSourcePath() throws -> String
func getProducer() throws -> String
func setProducer(_ value: String) throws
func getCreationDate() throws -> String
func setCreationDate(_ date: String) throws
Lê as informações do documento e obtém/define o produtor e a data de criação.
Operações de Página
func deletePage(_ page: Int) throws
func movePage(_ from: Int, _ to: Int) throws
func rotatePageBy(_ page: Int, _ degrees: Int) throws
func rotateAllPages(_ degrees: Int) throws
func setPageRotation(_ page: Int, _ degrees: Int) throws
func getPageRotation(_ page: Int) throws -> Int
Exclui, move e rotaciona páginas.
Geometria da Página
func cropMargins(left: Float, right: Float, top: Float, bottom: Float) throws
func getPageCropBox(_ page: Int) throws -> Bbox
func setPageCropBox(_ page: Int, x: Double, y: Double, width: Double, height: Double) throws
func getPageMediaBox(_ page: Int) throws -> Bbox
func setPageMediaBox(_ page: Int, x: Double, y: Double, width: Double, height: Double) throws
Recorta margens e obtém/define a geometria de CropBox e MediaBox.
Apagamento e Redação
func eraseRegion(_ page: Int, x: Float, y: Float, width: Float, height: Float) throws
func eraseRegions(_ page: Int, _ rects: [(Double, Double, Double, Double)]) throws
func clearEraseRegions(_ page: Int) throws
Enfileira e limpa regiões retangulares de apagamento.
func applyAllRedactions() throws
func applyPageRedactions(_ page: Int) throws
func isPageMarkedForRedaction(_ page: Int) throws -> Bool
func unmarkPageForRedaction(_ page: Int) throws
Aplica as redações pendentes e gerencia as marcações de redação por página.
func redactionAdd(_ page: Int, x1: Double, y1: Double, x2: Double, y2: Double, r: Double, g: Double, b: Double) throws
func redactionCount(_ page: Int) throws -> Int
func redactionApply(scrubMetadata: Bool, r: Double, g: Double, b: Double) throws -> Int
func redactionScrubMetadata() throws -> Int
Enfileira regiões de redação, conta-as, aplica-as de forma destrutiva (retorna o número de glifos removidos) ou limpa apenas metadados/JavaScript/arquivos incorporados.
Achatamento
func flattenForms() throws
func flattenFormsOnPage(_ page: Int) throws
func flattenAnnotations(_ page: Int) throws
func flattenAllAnnotations() throws
func flattenWarningsCount() throws -> Int
func flattenWarning(_ index: Int) throws -> String
func isPageMarkedForFlatten(_ page: Int) throws -> Bool
func unmarkPageForFlatten(_ page: Int) throws
Achata formulários e anotações, lê os avisos de achatamento e gerencia as marcações de achatamento por página.
Formulários
func setFormFieldValue(_ name: String, _ value: String) throws
func importFdfBytes(_ data: [UInt8]) throws -> Int32
func importXfdfBytes(_ data: [UInt8]) throws -> Int32
Define o valor de um campo de formulário ou importa dados FDF/XFDF a partir de bytes.
Códigos de Barras
func addBarcodeToPage(_ page: Int, _ barcode: BarcodeImage, x: Float, y: Float, width: Float, height: Float) throws
Desenha um código de barras gerado em uma página.
Operações de Documento
func mergeFrom(_ sourcePath: String) throws
func mergeFromBytes(_ bytes: [UInt8]) throws
func convertToPdfA(_ level: Int) throws
func embedFile(_ name: String, _ data: [UInt8]) throws
func extractPagesToBytes(_ pages: [Int]) throws -> [UInt8]
Faz merge de outro PDF, converte para PDF/A, anexa um arquivo ou extrai um subconjunto de páginas para bytes.
Salvamento
func save(_ path: String) throws
func saveToBytes() throws -> [UInt8]
func saveToBytesWithOptions(compress: Bool, garbageCollect: Bool, linearize: Bool) throws -> [UInt8]
func saveEncrypted(_ path: String, userPassword: String, ownerPassword: String) throws
func saveEncryptedToBytes(userPassword: String, ownerPassword: String) throws -> [UInt8]
Salva em um arquivo ou em bytes, com compressão/GC/linearização opcionais ou criptografia AES por senha.
DocumentBuilder
Um builder fluente para criar PDFs marcados (tagged) e com múltiplas páginas do zero. A maioria dos métodos retorna self para encadeamento.
static func create() throws -> DocumentBuilder
Cria um novo document builder.
Metadados e Estrutura
func setTitle(_ title: String) throws -> DocumentBuilder
func setAuthor(_ author: String) throws -> DocumentBuilder
func setSubject(_ subject: String) throws -> DocumentBuilder
func setKeywords(_ keywords: String) throws -> DocumentBuilder
func setCreator(_ creator: String) throws -> DocumentBuilder
func onOpen(_ script: String) throws -> DocumentBuilder
func taggedPdfUa1() throws -> DocumentBuilder
func language(_ lang: String) throws -> DocumentBuilder
func roleMap(custom: String, standard: String) throws -> DocumentBuilder
func registerEmbeddedFont(_ name: String, _ font: EmbeddedFont) throws -> DocumentBuilder
Define os metadados do documento, um script de ação de abertura, a marcação PDF/UA, o idioma, o role map e registra fontes incorporadas.
Páginas
func a4Page() throws -> PageBuilder
func letterPage() throws -> PageBuilder
func page(_ width: Float, _ height: Float) throws -> PageBuilder
Inicia uma página A4, Letter ou de tamanho personalizado, retornando um PageBuilder.
Saída
func build() throws -> [UInt8]
func save(_ path: String) throws
func saveEncrypted(_ path: String, userPassword: String, ownerPassword: String) throws
func toBytesEncrypted(userPassword: String, ownerPassword: String) throws -> [UInt8]
func close()
Constrói para bytes, salva em um arquivo ou salva com criptografia AES.
PageBuilder
Um builder fluente para o conteúdo de uma página, retornado por DocumentBuilder.a4Page() / .letterPage() / .page(_:_:). A maioria dos métodos retorna self.
Texto e Layout
func font(_ name: String, _ size: Float) throws -> PageBuilder
func at(_ x: Float, _ y: Float) throws -> PageBuilder
func text(_ text: String) throws -> PageBuilder
func heading(_ level: Int, _ text: String) throws -> PageBuilder
func paragraph(_ text: String) throws -> PageBuilder
func space(_ points: Float) throws -> PageBuilder
func horizontalRule() throws -> PageBuilder
func columns(_ columnCount: UInt32, _ gapPt: Float, _ text: String) throws -> PageBuilder
func footnote(_ refMark: String, _ noteText: String) throws -> PageBuilder
func newPageSameSize() throws -> PageBuilder
Define a fonte e a posição ativas e, em seguida, escreve texto, títulos, parágrafos, espaçamento, réguas, fluxo multicoluna, notas de rodapé ou inicia uma página do mesmo tamanho.
Trechos Inline
func inline(_ text: String) throws -> PageBuilder
func inlineBold(_ text: String) throws -> PageBuilder
func inlineItalic(_ text: String) throws -> PageBuilder
func inlineColor(_ r: Float, _ g: Float, _ b: Float, _ text: String) throws -> PageBuilder
func newline() throws -> PageBuilder
Acrescenta trechos de texto inline estilizados e quebras de linha.
Links e Scripts
func linkUrl(_ url: String) throws -> PageBuilder
func linkPage(_ page: Int) throws -> PageBuilder
func linkNamed(_ destination: String) throws -> PageBuilder
func linkJavascript(_ script: String) throws -> PageBuilder
func onOpen(_ script: String) throws -> PageBuilder
func onClose(_ script: String) throws -> PageBuilder
func fieldKeystroke(_ script: String) throws -> PageBuilder
func fieldFormat(_ script: String) throws -> PageBuilder
func fieldValidate(_ script: String) throws -> PageBuilder
func fieldCalculate(_ script: String) throws -> PageBuilder
Adiciona anotações de link de URL/página/nomeado/JavaScript e anexa scripts de nível de página ou de campo.
Anotações de Marcação
func highlight(_ r: Float, _ g: Float, _ b: Float) throws -> PageBuilder
func underline(_ r: Float, _ g: Float, _ b: Float) throws -> PageBuilder
func strikeout(_ r: Float, _ g: Float, _ b: Float) throws -> PageBuilder
func squiggly(_ r: Float, _ g: Float, _ b: Float) throws -> PageBuilder
func stickyNote(_ text: String) throws -> PageBuilder
func stickyNoteAt(_ x: Float, _ y: Float, _ text: String) throws -> PageBuilder
func watermark(_ text: String) throws -> PageBuilder
func watermarkConfidential() throws -> PageBuilder
func watermarkDraft() throws -> PageBuilder
func stamp(_ typeName: String) throws -> PageBuilder
func freetext(_ x: Float, _ y: Float, _ w: Float, _ h: Float, _ text: String) throws -> PageBuilder
Adiciona marcações de destaque/sublinhado/tachado/ondulado, notas adesivas, marcas d’água, carimbos e anotações de texto livre.
Campos de Formulário
func textField(_ name: String, _ x: Float, _ y: Float, _ w: Float, _ h: Float, defaultValue: String? = nil) throws -> PageBuilder
func checkbox(_ name: String, _ x: Float, _ y: Float, _ w: Float, _ h: Float, checked: Bool) throws -> PageBuilder
func pushButton(_ name: String, _ x: Float, _ y: Float, _ w: Float, _ h: Float, _ caption: String) throws -> PageBuilder
func signatureField(_ name: String, _ x: Float, _ y: Float, _ w: Float, _ h: Float) throws -> PageBuilder
func comboBox(_ name: String, _ x: Float, _ y: Float, _ w: Float, _ h: Float, options: [String], selected: String? = nil) throws -> PageBuilder
func radioGroup(_ name: String, values: [String], xs: [Float], ys: [Float], ws: [Float], hs: [Float], selected: String? = nil) throws -> PageBuilder
Adiciona campos de texto AcroForm, caixas de seleção, botões de ação, campos de assinatura, combo boxes e grupos de botões de opção.
Códigos de Barras e Imagens
func barcode1d(_ barcodeType: Int32, _ data: String, _ x: Float, _ y: Float, _ w: Float, _ h: Float) throws -> PageBuilder
func barcodeQr(_ data: String, _ x: Float, _ y: Float, _ size: Float) throws -> PageBuilder
func image(_ bytes: [UInt8], _ x: Float, _ y: Float, _ w: Float, _ h: Float) throws -> PageBuilder
func imageWithAlt(_ bytes: [UInt8], _ x: Float, _ y: Float, _ w: Float, _ h: Float, altText: String) throws -> PageBuilder
func imageArtifact(_ bytes: [UInt8], _ x: Float, _ y: Float, _ w: Float, _ h: Float) throws -> PageBuilder
Desenha códigos de barras 1-D, QR codes e imagens (com texto alternativo ou marcação como artefato opcionais).
Gráficos Vetoriais
func rect(_ x: Float, _ y: Float, _ w: Float, _ h: Float) throws -> PageBuilder
func filledRect(_ x: Float, _ y: Float, _ w: Float, _ h: Float, _ r: Float, _ g: Float, _ b: Float) throws -> PageBuilder
func line(_ x1: Float, _ y1: Float, _ x2: Float, _ y2: Float) throws -> PageBuilder
func strokeRect(_ x: Float, _ y: Float, _ w: Float, _ h: Float, width: Float, _ r: Float, _ g: Float, _ b: Float) throws -> PageBuilder
func strokeLine(_ x1: Float, _ y1: Float, _ x2: Float, _ y2: Float, width: Float, _ r: Float, _ g: Float, _ b: Float) throws -> PageBuilder
func strokeRectDashed(_ x: Float, _ y: Float, _ w: Float, _ h: Float, width: Float, _ r: Float, _ g: Float, _ b: Float, dashArray: [Float], phase: Float) throws -> PageBuilder
func strokeLineDashed(_ x1: Float, _ y1: Float, _ x2: Float, _ y2: Float, width: Float, _ r: Float, _ g: Float, _ b: Float, dashArray: [Float], phase: Float) throws -> PageBuilder
func textInRect(_ x: Float, _ y: Float, _ w: Float, _ h: Float, _ text: String, align: Int32) throws -> PageBuilder
Desenha retângulos, linhas, formas com traço/tracejadas e texto restrito a um retângulo.
Tabelas
func table(nColumns: Int, widths: [Float], aligns: [Int32], nRows: Int, cellStrings: [String], hasHeader: Bool) throws -> PageBuilder
Bufferiza uma tabela estática; cellStrings é organizado por linha (row * nColumns + col).
func streamingTableBegin(nColumns: Int, headers: [String], widths: [Float], aligns: [Int32], repeatHeader: Bool) throws -> PageBuilder
func streamingTableBeginV2(nColumns: Int, headers: [String], widths: [Float], aligns: [Int32], repeatHeader: Bool, mode: Int32, sampleRows: Int, minColWidthPt: Float, maxColWidthPt: Float, maxRowspan: Int) throws -> PageBuilder
func streamingTableSetBatchSize(_ batchSize: Int) throws -> PageBuilder
func streamingTablePendingRowCount() throws -> Int
func streamingTableBatchCount() throws -> Int
func streamingTableFlush() throws -> PageBuilder
func streamingTablePushRow(_ cells: [String]) throws -> PageBuilder
func streamingTablePushRowV2(_ cells: [String], rowspans: [Int]?) throws -> PageBuilder
func streamingTableFinish() throws -> PageBuilder
Constrói tabelas grandes de forma incremental com linhas em streaming, rowspans opcionais, batching e modos de auto-ajuste.
Finalização
func done() throws
func close()
Finaliza a página e devolve o controle ao builder pai.
EmbeddedFont
Uma fonte registrada em um DocumentBuilder.
static func fromFile(_ path: String) throws -> EmbeddedFont
static func fromBytes(_ bytes: [UInt8], name: String? = nil) throws -> EmbeddedFont
func close()
Carrega uma fonte TrueType/OpenType a partir de um arquivo ou de bytes.
BarcodeImage
Gera e inspeciona códigos de barras 1-D/2-D.
static func generateQrCode(_ data: String, errorCorrection: Int32 = 1, sizePx: Int32 = 256) throws -> BarcodeImage
static func generateBarcode(_ data: String, format: Int32, sizePx: Int32 = 256) throws -> BarcodeImage
Gera um QR code ou um código de barras de um formato específico.
func data() throws -> String
func format() throws -> Int32
func confidence() throws -> Float
func imagePng(sizePx: Int32 = 256) throws -> [UInt8]
func svg(sizePx: Int32 = 256) throws -> String
func close()
Lê o payload decodificado, o formato e a confiança, ou renderiza o código de barras para bytes PNG ou uma string SVG.
RenderedImage
Uma imagem de página renderizada, retornada pelos métodos Document.renderPage*.
let width: Int
let height: Int
let data: [UInt8]
func save(_ path: String) throws
func close()
Dimensões em pixels, bytes da imagem codificada e um auxiliar para salvar a imagem em um arquivo.
Renderer
Um handle de configuração de renderizador autônomo.
static func create(dpi: Int32 = 150, format: Int32 = 0, quality: Int32 = 90, antiAlias: Bool = true) throws -> Renderer
func close()
Cria um renderizador reutilizável com configurações de DPI, formato (0=PNG, 1=JPEG), qualidade JPEG e anti-aliasing.
OcrEngine
Um engine de OCR apoiado por modelos de detecção/reconhecimento.
static func create(detModelPath: String, recModelPath: String, dictPath: String) throws -> OcrEngine
func close()
Cria um engine a partir dos caminhos do modelo de detecção, do modelo de reconhecimento e do dicionário. Passe-o para Document.ocrExtractText(_:engine:).
Certificate
Um certificado e chave de assinatura.
static func loadFromBytes(_ bytes: [UInt8], password: String) throws -> Certificate
static func loadFromPem(certPem: String, keyPem: String) throws -> Certificate
Carrega um certificado a partir de bytes PKCS#12 (com senha) ou de strings PEM.
func subject() throws -> String
func issuer() throws -> String
func serial() throws -> String
func validity() throws -> CertificateValidity
func isValid() throws -> Bool
func close()
Lê o subject, o issuer, o serial, a janela de validade e a validade atual.
SignatureInfo
Detalhes de uma assinatura existente, retornados por Document.signature(_:).
func signerName() throws -> String
func signingReason() throws -> String
func signingLocation() throws -> String
func signingTime() throws -> Int64
func certificate() throws -> Certificate?
func padesLevel() throws -> Int32
func hasTimestamp() throws -> Bool
func timestamp() throws -> Timestamp?
func addTimestamp(_ ts: Timestamp) throws -> Bool
func verify() throws -> Int32
func verifyDetached(_ pdf: [UInt8]) throws -> Int32
func close()
Lê os metadados do signatário, o certificado, o nível PAdES e o timestamp; verifica a assinatura (com uma checagem opcional de message-digest destacada).
Timestamp
Um token de timestamp RFC 3161.
static func parse(_ bytes: [UInt8]) throws -> Timestamp
func token() throws -> [UInt8]
func messageImprint() throws -> [UInt8]
func time() throws -> Int64
func serial() throws -> String
func tsaName() throws -> String
func policyOid() throws -> String
func hashAlgorithm() throws -> Int32
func verify() throws -> Bool
func close()
Faz o parse de um token de timestamp e lê seus campos, ou o verifica.
TsaClient
Um cliente de Autoridade de Carimbo do Tempo (atrás da feature tsa-client).
static func create(url: String, username: String? = nil, password: String? = nil,
timeout: Int32 = 30, hashAlgo: Int32 = 0, useNonce: Bool = true, certReq: Bool = true) throws -> TsaClient
func requestTimestamp(_ data: [UInt8]) throws -> Timestamp
func requestTimestampHash(_ hash: [UInt8], hashAlgo: Int32) throws -> Timestamp
func close()
Configura um endpoint de TSA e solicita timestamps sobre os dados ou sobre um hash pré-computado.
Dss
O Document Security Store, retornado por Document.dss().
func certCount() throws -> Int
func crlCount() throws -> Int
func ocspCount() throws -> Int
func vriCount() throws -> Int
func cert(_ index: Int) throws -> [UInt8]
func crl(_ index: Int) throws -> [UInt8]
func ocsp(_ index: Int) throws -> [UInt8]
func close()
Conta e lê os certificados, CRLs e respostas OCSP armazenados para validação de longo prazo.
PdfAResults / UaResults / PdfXResults
Handles de resultado de validação retornados por Document.validatePdfA/Ua/X(_:).
// PdfAResults
func isCompliant() throws -> Bool
func errors() throws -> [String]
func warningCount() throws -> Int
func close()
// UaResults
func isAccessible() throws -> Bool
func errors() throws -> [String]
func warnings() throws -> [String]
func stats() throws -> UaStats
func close()
// PdfXResults
func isCompliant() throws -> Bool
func errors() throws -> [String]
func close()
Inspeciona a conformidade/acessibilidade, as listas de erros e avisos e as estatísticas de PDF/UA.
ElementList
Uma lista genérica de elementos por página, retornada por Document.pageElements(_:).
func count() throws -> Int
func element(_ index: Int) throws -> Element
func all() throws -> [Element]
func toJson() throws -> String
func close()
Itera sobre os elementos da página (tipo, texto, rect) ou os serializa para JSON.
Funções de Nível Superior
Funções livres que operam sobre bytes brutos ou sobre o estado global.
func signBytes(_ pdf: [UInt8], certificate: Certificate, reason: String? = nil, location: String? = nil) throws -> [UInt8]
Assina bytes brutos de PDF e retorna o PDF assinado.
func signBytesPades(_ pdf: [UInt8], certificate: Certificate, level: Int32,
tsaUrl: String? = nil, reason: String? = nil, location: String? = nil,
certs: [[UInt8]] = [], crls: [[UInt8]] = [], ocsps: [[UInt8]] = []) throws -> [UInt8]
Assina em um nível baseline PAdES (0=B-B, 1=B-T, 2=B-LT) com URL de TSA e material de revogação opcionais.
func signBytesPadesOpts(_ pdf: [UInt8], certificate: Certificate, level: Int32,
tsaUrl: String? = nil, reason: String? = nil, location: String? = nil,
certs: [[UInt8]] = [], crls: [[UInt8]] = [], ocsps: [[UInt8]] = []) throws -> [UInt8]
Variante de signBytesPades com opções em struct.
func merge(_ paths: [String]) throws -> [UInt8]
Faz merge dos PDFs em paths (na ordem) em um único PDF em memória.
func addTimestamp(_ pdfData: [UInt8], sigIndex: Int32, tsaUrl: String) throws -> [UInt8]
Adiciona um timestamp RFC 3161 a uma assinatura e retorna os bytes do PDF re-salvo.
func setLogLevel(_ level: Int32)
func getLogLevel() -> Int32
Define ou lê o nível de log global da biblioteca (0=Off … 5=Trace).
PdfOxide (Configuração Global)
O enum PdfOxide agrupa, em namespace, a política criptográfica de todo o processo, o prefetch de modelos e a configuração do parser.
static func cryptoActiveProvider() -> String
static func cryptoCbom() -> String
static func cryptoFipsAvailable() -> Int32
static func cryptoInventory() -> String
static func cryptoPolicy() -> String
static func cryptoSetPolicy(_ spec: String) -> Int32
static func cryptoUseFips() -> Int32
Inspeciona e configura o provedor criptográfico, o CBOM/inventário, a política e o modo FIPS.
static func modelManifest() -> String
static func prefetchAvailable() -> Int32
static func prefetchModels(languagesCsv: String) throws -> String
Lê o manifesto de modelos de OCR e faz o prefetch dos modelos para uma lista de idiomas separados por vírgula.
static func setMaxOpsPerStream(_ limit: Int64) -> Int64
static func setPreserveUnmappedGlyphs(_ preserve: Int32) -> Int32
Ajusta os limites do parser e o comportamento de mapeamento de glifos.
Tipos de Valor
Structs simples retornados pelos métodos de extração.
PdfOxideError
struct PdfOxideError: Error, CustomStringConvertible {
let code: Int32
let op: String
}
Lançado em qualquer código de erro da C-ABI diferente de sucesso.
PdfVersion
struct PdfVersion { let major: Int; let minor: Int }
Versão do PDF (por exemplo, 1.7).
Bbox
struct Bbox { let x: Double; let y: Double; let width: Double; let height: Double }
Uma bounding box alinhada aos eixos, em unidades do espaço de usuário do PDF.
Char
struct Char { let character: UInt32; let bbox: Bbox; let fontName: String; let fontSize: Double }
Um único caractere extraído (valor escalar Unicode).
Word
struct Word { let text: String; let bbox: Bbox; let fontName: String; let fontSize: Double; let bold: Bool }
Uma única palavra extraída.
TextLine
struct TextLine { let text: String; let bbox: Bbox; let wordCount: Int }
Uma única linha de texto extraída.
Table
struct Table {
let rowCount: Int
let colCount: Int
let hasHeader: Bool
func cell(_ row: Int, _ col: Int) -> String
}
Uma única tabela extraída; as células são lidas sob demanda via cell(_:_:).
Font
struct Font { let name: String; let type: String; let encoding: String; let embedded: Bool; let subset: Bool }
Um descritor de fonte incorporada.
Image
struct Image {
let width: Int
let height: Int
let bitsPerComponent: Int
let format: String
let colorspace: String
let data: [UInt8]
}
Uma imagem raster extraída com seus bytes brutos.
Annotation
struct Annotation { let type: String; let subtype: String; let content: String; let author: String; let rect: Bbox; let borderWidth: Double }
Os atributos principais de uma anotação.
AnnotationExtras
struct AnnotationExtras {
let color: UInt32
let creationDate: Int64
let modificationDate: Int64
let hidden: Bool
let markedDeleted: Bool
let printable: Bool
let readOnly: Bool
let uri: String
let iconName: String
let quadPoints: [QuadPoint]
}
Atributos estendidos de anotação obtidos de annotationExtras(_:index:).
Path
struct Path { let bbox: Bbox; let strokeWidth: Double; let hasStroke: Bool; let hasFill: Bool; let operationCount: Int }
Um resumo da geometria de um path vetorial.
SearchResult
struct SearchResult { let text: String; let page: Int; let bbox: Bbox }
Uma correspondência de busca de texto.
FormField
struct FormField { let name: String; let value: String; let type: String; let readonly: Bool; let required: Bool }
Um descritor de campo de formulário.
QuadPoint
struct QuadPoint { let x1, y1, x2, y2, x3, y3, x4, y4: Double }
Um quadrilátero de anotação de marcação.
Element
struct Element { let type: String; let text: String; let rect: Bbox }
Um elemento genérico de página de um ElementList.
CertificateValidity
struct CertificateValidity { let notBefore: Int64; let notAfter: Int64 }
A janela de validade de um certificado (timestamps Unix).
UaStats
struct UaStats { let structElements: Int; let images: Int; let tables: Int; let forms: Int; let annotations: Int; let pages: Int }
Estatísticas de estrutura PDF/UA obtidas de UaResults.stats().
Exemplo Completo
import PdfOxide
// --- Extraction ---
let doc = try Document.open("input.pdf")
print("Pages: \(try doc.pageCount())")
for i in 0..<(try doc.pageCount()) {
let text = try doc.extractText(i)
print("Page \(i + 1): \(text.count) characters")
}
// Word-level geometry
let words = try doc.extractWords(0)
for w in words.prefix(5) {
print("'\(w.text)' at \(w.bbox) font=\(w.fontName) size=\(w.fontSize)")
}
// Render the first page to PNG
let image = try doc.renderPage(0, format: 0)
try image.save("page0.png")
// --- Creation (fluent) ---
let builder = try DocumentBuilder.create()
try builder.setTitle("Report")
let page = try builder.letterPage()
try page.at(72, 720).font("Helvetica", 18).heading(1, "Report")
try page.paragraph("Generated by PDF Oxide.")
try page.done()
try builder.save("report.pdf")
// --- Editing ---
let editor = try DocumentEditor.open("document.pdf")
try editor.rotateAllPages(90)
try editor.setFormFieldValue("name", "John Doe")
try editor.mergeFrom("appendix.pdf")
try editor.save("output.pdf")
// --- Signatures ---
let cert = try Certificate.loadFromBytes(p12Bytes, password: "secret")
let signed = try signBytesPades(pdfBytes, certificate: cert, level: 1,
tsaUrl: "https://freetsa.org/tsr")
Other Language Bindings
O PDF Oxide oferece bindings nativos para todos os principais ecossistemas: Rust, Python, Node.js, WASM, C#, Golang, Java, PHP, Ruby, C++, 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 Swift — tutorial