Skip to content

Referencia de la API de Swift

PDF Oxide ofrece bindings idiomáticos de Swift sobre la C ABI nativa. Un módulo de librería del sistema CPdfOxide expone la cabecera de cbindgen mediante un module map, y PdfOxide es el wrapper de Swift. Las clases son propietarias de los handles (que se liberan en deinit), las cadenas y buffers de C devueltos se copian a String/[UInt8] de Swift, y los códigos de error distintos de éxito se lanzan 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 la API de Rust, consulta la Referencia de la API de Rust. Para la API de Python, consulta la Referencia de la API de Python. Para detalles sobre los tipos, consulta Tipos y enumeraciones.

Todos los índices de página empiezan en cero. La mayoría de los métodos son throws y lanzan PdfOxideError ante un código de error de la C ABI distinto de éxito.


Document

La clase principal para abrir, extraer, renderizar e inspeccionar archivos PDF. Obtén instancias mediante los métodos de fábrica estáticos open*.

Apertura

static func open(_ path: String) throws -> Document

Abre un PDF a partir de una ruta de archivo.

static func openFromBytes(_ bytes: [UInt8]) throws -> Document

Abre un PDF a partir de bytes en memoria (por ejemplo, descargado desde S3 o recibido por HTTP).

static func openWithPassword(_ path: String, password: String) throws -> Document

Abre un PDF cifrado con una contraseña de usuario o de propietario.

static func openFromDocxBytes(_ bytes: [UInt8]) throws -> Document
static func openFromPptxBytes(_ bytes: [UInt8]) throws -> Document
static func openFromXlsxBytes(_ bytes: [UInt8]) throws -> Document

Convierte un documento de Office (DOCX, PPTX, XLSX) a partir de bytes en memoria en un Document.

func authenticate(_ password: String) throws -> Bool

Autentica un documento cifrado ya abierto. Devuelve true si tiene éxito.

func close()

Libera el handle nativo de inmediato (idempotente; también se ejecuta en deinit).

Información del 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

Accesores generales a los metadatos del documento. page(_:) devuelve un handle Page ligero para el índice dado.

Extracción de texto

func extractText(_ page: Int) throws -> String

Extrae texto plano de una sola página.

func extractChars(_ pageIndex: Int) throws -> [Char]

Extrae la posición de cada carácter y los metadatos de fuente.

func extractWords(_ pageIndex: Int) throws -> [Word]

Extrae palabras con cuadros delimitadores, nombre/tamaño de fuente y flag de negrita.

func extractTextLines(_ pageIndex: Int) throws -> [TextLine]

Extrae el texto agrupado en líneas con recuentos de palabras y cuadros delimitadores.

func extractTables(_ pageIndex: Int) throws -> [Table]

Detecta y extrae tablas con filas, columnas, cabeceras y texto de celda.

func extractStructuredJson(_ page: Int) throws -> String

Extrae una representación JSON estructurada del contenido de una página.

Extracción y clasificación automáticas

func extractTextAuto(_ pageIndex: Int) throws -> String

Detecta automáticamente la mejor ruta de extracción y devuelve el texto de una página.

func extractAllText() throws -> String

Extrae el texto de todas las páginas del documento.

func extractPageAuto(_ pageIndex: Int, optionsJson: String = "{}") throws -> String

Extrae automáticamente una página usando opciones configuradas en JSON.

func classifyPage(_ pageIndex: Int) throws -> String
func classifyDocument() throws -> String

Clasifica una sola página o el documento completo (por ejemplo, escaneado frente a digital).

Extracción por región

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]

Extrae contenido restringido a un rectángulo (x, y, w, h) (puntos del espacio de usuario del PDF, origen abajo a la izquierda).

Conversión

func toPlainText(_ page: Int) throws -> String
func toMarkdown(_ page: Int) throws -> String
func toHtml(_ page: Int) throws -> String

Convierte una sola página a texto plano, Markdown o HTML.

func toPlainTextAll() throws -> String
func toMarkdownAll() throws -> String
func toHtmlAll() throws -> String

Convierte todas las páginas a texto plano, Markdown o HTML.

Exportación a Office

func toDocx() throws -> [UInt8]
func toPptx() throws -> [UInt8]
func toXlsx() throws -> [UInt8]

Exporta el documento a bytes DOCX, PPTX o XLSX.

Imágenes, fuentes y trazados

func embeddedImages(_ pageIndex: Int) throws -> [Image]

Extrae las imágenes ráster incrustadas (con sus bytes en bruto) de una página.

func embeddedFonts(_ pageIndex: Int) throws -> [Font]

Lista las fuentes incrustadas de una página con su tipo, codificación y flags de subconjunto.

func extractPaths(_ pageIndex: Int) throws -> [Path]

Extrae trazados vectoriales (líneas, curvas, formas) de una página.

func fontsToJson(_ pageIndex: Int) throws -> String
func fontSize(_ pageIndex: Int, fontIndex: Int) throws -> Float

Serializa las fuentes de una página a JSON, o lee el tamaño de una sola fuente.

Anotaciones

func pageAnnotations(_ pageIndex: Int) throws -> [Annotation]

Extrae las anotaciones (tipo, subtipo, contenido, autor, rect) de una página.

func annotationsToJson(_ pageIndex: Int) throws -> String

Serializa las anotaciones de una página a JSON.

func annotationExtras(_ pageIndex: Int, index: Int) throws -> AnnotationExtras

Lee los atributos extendidos de una anotación (color, fechas, flags, URI, icono, quad points).

Búsqueda

func search(_ pageIndex: Int, _ term: String, _ caseSensitive: Bool) throws -> [SearchResult]

Busca texto en una sola página.

func searchAll(_ term: String, _ caseSensitive: Bool) throws -> [SearchResult]

Busca texto en todo el documento.

func searchResultsToJson(_ pageIndex: Int, _ term: String, caseSensitive: Bool) throws -> String

Busca en una página y serializa las coincidencias a JSON.

Geometría de la 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

Lee las dimensiones, la rotación y una lista genérica de elementos de la página.

Renderizado

func renderPage(_ pageIndex: Int, format: Int32 = 0) throws -> RenderedImage

Renderiza una página a un RenderedImage (PNG cuando format es 0, JPEG cuando es 1).

func renderPageZoom(_ pageIndex: Int, zoom: Float, format: Int32 = 0) throws -> RenderedImage

Renderiza una página con un factor de zoom.

func renderPageThumbnail(_ pageIndex: Int, size: Int, format: Int32 = 0) throws -> RenderedImage

Renderiza una miniatura que cabe dentro de size píxeles.

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 con todas las opciones de renderizado (DPI, color/alfa de fondo, anotaciones, calidad 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 con todas las opciones más una lista de nombres de capas OCG que suprimir.

func renderPageRegion(
    _ pageIndex: Int, cropX: Float, cropY: Float, cropWidth: Float, cropHeight: Float,
    format: Int32 = 0
) throws -> RenderedImage

Renderiza una región rectangular de una página.

func renderPageFit(_ pageIndex: Int, width: Int32, height: Int32, format: Int32 = 0) throws -> RenderedImage

Renderiza una página para que quepa dentro de width×height píxeles, conservando la relación de aspecto.

func renderPageRaw(_ pageIndex: Int, dpi: Int32 = 150) throws -> (image: RenderedImage, width: Int, height: Int)

Renderiza a un buffer RGBA8888 premultiplicado en bruto junto con las dimensiones en píxeles.

func estimateRenderTime(_ pageIndex: Int) throws -> Int32

Estima el coste de renderizado de una página (unidades definidas por la implementación).

OCR

func ocrPageNeedsOcr(_ pageIndex: Int) throws -> Bool

Decide heurísticamente si una página necesita OCR (por ejemplo, una página escaneada).

func ocrExtractText(_ pageIndex: Int, engine: OcrEngine? = nil) throws -> String

Extrae texto mediante OCR. Pasa un OcrEngine personalizado o nil para usar el motor por defecto.

Formularios

func formFields() throws -> [FormField]

Lista todos los campos del formulario con nombre, valor, tipo y flags de solo lectura/obligatorio.

func exportFormData(formatType: Int32) throws -> [UInt8]

Exporta los datos del formulario como bytes FDF/XFDF.

func importFormData(_ dataPath: String) throws -> Int32
func importFormFromFile(_ filename: String) throws -> Bool

Importa datos de formulario desde una ruta de archivo.

Estructura del documento

func outline() throws -> String
func pageLabels() throws -> String
func xmpMetadata() throws -> String
func sourceBytes() throws -> [UInt8]
func planSplitByBookmarks(optionsJson: String = "{}") throws -> String

Lee el esquema (outline) del documento, las etiquetas de página, los metadatos XMP, los bytes de origen en bruto o un plan de división en JSON basado en los marcadores.

Limpieza de contenido

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

Borra cabeceras/pies/artefactos de una sola página, o de todo el documento usando un umbral de frecuencia.

Validación

func validatePdfA(_ level: Int32) throws -> PdfAResults
func validatePdfUa(_ level: Int32) throws -> UaResults
func validatePdfX(_ level: Int32) throws -> PdfXResults

Valida el documento frente a los niveles de conformidad PDF/A, PDF/UA o PDF/X.

func convertToPdfA(_ level: Int32) throws -> Bool

Convierte el documento a PDF/A in situ. Devuelve true si tiene éxito.

Firmas

func sign(_ certificate: Certificate, reason: String, location: String) throws -> Int32

Firma el documento con un certificado, incrustando el motivo y la ubicación.

func signatureCount() throws -> Int
func signature(_ index: Int) throws -> SignatureInfo?
func verifyAllSignatures() throws -> Int32
func hasTimestamp() throws -> Bool
func dss() throws -> Dss?

Inspecciona las firmas existentes, verifica todas las firmas (1=válida, 0=inválida, -1=desconocida), comprueba si hay un sello de tiempo del documento y accede al Document Security Store.

Códigos de barras

func addBarcodeToPage(_ page: Int, _ barcode: BarcodeImage, x: Float, y: Float, width: Float, height: Float) throws

Dibuja un BarcodeImage generado en una página, en la posición y el tamaño dados.


Page

Un handle ligero por página devuelto por Document.page(_:). Todos los accesores delegan en el documento padre.

let index: Int

El índice de página (base cero).

func text() throws -> String
func markdown() throws -> String
func html() throws -> String
func plainText() throws -> String

Extrae la página como texto plano, Markdown o HTML.


Pdf

Una clase para crear PDFs a partir de formatos de origen y guardarlos.

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

Crea un PDF a partir de Markdown, HTML o texto plano.

static func fromImage(_ path: String) throws -> Pdf
static func fromImageBytes(_ bytes: [UInt8]) throws -> Pdf

Crea un PDF de una sola página a partir de un archivo de imagen o de los bytes de una imagen.

static func fromHtmlCss(html: String, css: String, fontBytes: [UInt8] = []) throws -> Pdf

Crea un PDF a partir de HTML + CSS con una fuente incrustada opcional.

static func fromHtmlCssWithFonts(html: String, css: String, fonts: [(String, [UInt8])]) throws -> Pdf

Crea un PDF a partir de HTML + CSS con varias fuentes con nombre.

Métodos

func save(_ path: String) throws
func toBytes() throws -> [UInt8]
func pageCount() throws -> Int
func close()

Guarda en un archivo, obtén los bytes del PDF, cuenta las páginas o libera el handle.


DocumentEditor

Un editor mutable para modificar PDFs existentes: páginas, rotación, geometría, redacción, aplanado, formularios, fusión y guardado.

Apertura y 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 un editor a partir de una ruta o de bytes, y libera el handle al terminar.

Información y metadatos

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

Lee la información del documento y obtén/establece el productor y la fecha de creación.

Operaciones con páginas

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

Elimina, mueve y rota páginas.

Geometría de la 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 márgenes y obtén/establece la geometría de CropBox y MediaBox.

Borrado y redacción

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

Pone en cola y limpia regiones de borrado rectangulares.

func applyAllRedactions() throws
func applyPageRedactions(_ page: Int) throws
func isPageMarkedForRedaction(_ page: Int) throws -> Bool
func unmarkPageForRedaction(_ page: Int) throws

Aplica las redacciones pendientes y gestiona las marcas de redacción 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

Pone en cola regiones de redacción, las cuenta, las aplica de forma destructiva (devuelve los glifos eliminados) o depura únicamente los metadatos/JavaScript/archivos incrustados.

Aplanado

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

Aplana formularios y anotaciones, lee los avisos de aplanado y gestiona las marcas de aplanado por página.

Formularios

func setFormFieldValue(_ name: String, _ value: String) throws
func importFdfBytes(_ data: [UInt8]) throws -> Int32
func importXfdfBytes(_ data: [UInt8]) throws -> Int32

Establece el valor de un campo de formulario, o importa datos 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

Dibuja un código de barras generado en una página.

Operaciones con el 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]

Fusiona otro PDF, convierte a PDF/A, adjunta un archivo o extrae un subconjunto de páginas a bytes.

Guardado

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]

Guarda en un archivo o en bytes, con compresión/GC/linealización opcionales o cifrado por contraseña AES.


DocumentBuilder

Un builder fluido para crear PDFs etiquetados y multipágina desde cero. La mayoría de los métodos devuelven self para encadenar.

static func create() throws -> DocumentBuilder

Crea un nuevo builder de documento.

Metadatos y estructura

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

Establece los metadatos del documento, un script de acción de apertura, el etiquetado PDF/UA, el idioma, el role map y registra fuentes incrustadas.

Páginas

func a4Page() throws -> PageBuilder
func letterPage() throws -> PageBuilder
func page(_ width: Float, _ height: Float) throws -> PageBuilder

Inicia una página A4, Letter o de tamaño personalizado, devolviendo un PageBuilder.

Salida

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()

Construye a bytes, guarda en un archivo o guarda con cifrado AES.


PageBuilder

Un builder fluido para el contenido de una página, devuelto por DocumentBuilder.a4Page() / .letterPage() / .page(_:_:). La mayoría de los métodos devuelven self.

Texto y disposición

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

Establece la fuente y la posición activas, y luego escribe texto, encabezados, párrafos, espaciado, reglas, flujo multicolumna, notas al pie, o inicia una página del mismo tamaño.

Fragmentos en línea

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

Añade fragmentos de texto en línea con estilo y saltos de línea.

Enlaces y 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

Añade anotaciones de enlace de tipo URL/página/con nombre/JavaScript y adjunta scripts a nivel de página o de campo.

Anotaciones de marcado

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

Añade marcado de resaltado/subrayado/tachado/ondulado, notas adhesivas, marcas de agua, sellos y anotaciones de texto libre.

Campos de formulario

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

Añade campos de texto, casillas de verificación, botones, campos de firma, listas desplegables y grupos de opciones de AcroForm.

Códigos de barras e imágenes

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

Dibuja códigos de barras 1-D, códigos QR e imágenes (con texto alternativo opcional o etiquetado como artefacto).

Gráficos vectoriales

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

Dibuja rectángulos, líneas, formas con trazo/discontinuas y texto restringido a un rectángulo.

Tablas

func table(nColumns: Int, widths: [Float], aligns: [Int32], nRows: Int, cellStrings: [String], hasHeader: Bool) throws -> PageBuilder

Almacena en buffer una tabla estática; cellStrings va en orden por filas (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

Construye tablas grandes de forma incremental con filas en streaming, rowspans opcionales, agrupación por lotes y modos de autoajuste.

Finalización

func done() throws
func close()

Finaliza la página y devuelve el control al builder padre.


EmbeddedFont

Una fuente registrada con un DocumentBuilder.

static func fromFile(_ path: String) throws -> EmbeddedFont
static func fromBytes(_ bytes: [UInt8], name: String? = nil) throws -> EmbeddedFont
func close()

Carga una fuente TrueType/OpenType desde un archivo o desde bytes.


BarcodeImage

Genera e inspecciona 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

Genera un código QR o un código de barras de un formato determinado.

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()

Lee la carga útil decodificada, el formato y la confianza, o renderiza el código de barras a bytes PNG o a una cadena SVG.


RenderedImage

Una imagen de página renderizada devuelta por los métodos Document.renderPage*.

let width: Int
let height: Int
let data: [UInt8]
func save(_ path: String) throws
func close()

Dimensiones en píxeles, bytes de imagen codificados y un helper para guardar la imagen en un archivo.


Renderer

Un handle de configuración de renderizador independiente.

static func create(dpi: Int32 = 150, format: Int32 = 0, quality: Int32 = 90, antiAlias: Bool = true) throws -> Renderer
func close()

Crea un renderizador reutilizable con ajustes de DPI, formato (0=PNG, 1=JPEG), calidad JPEG y antialiasing.


OcrEngine

Un motor de OCR respaldado por modelos de detección/reconocimiento.

static func create(detModelPath: String, recModelPath: String, dictPath: String) throws -> OcrEngine
func close()

Crea un motor a partir de las rutas del modelo de detección, el modelo de reconocimiento y el diccionario. Pásalo a Document.ocrExtractText(_:engine:).


Certificate

Un certificado de firma y su clave.

static func loadFromBytes(_ bytes: [UInt8], password: String) throws -> Certificate
static func loadFromPem(certPem: String, keyPem: String) throws -> Certificate

Carga un certificado desde bytes PKCS#12 (con contraseña) o desde cadenas PEM.

func subject() throws -> String
func issuer() throws -> String
func serial() throws -> String
func validity() throws -> CertificateValidity
func isValid() throws -> Bool
func close()

Lee el sujeto, el emisor, el número de serie, la ventana de validez y la validez actual.


SignatureInfo

Detalles de una firma existente, devueltos 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()

Lee los metadatos del firmante, el certificado, el nivel PAdES y el sello de tiempo; verifica la firma (con una comprobación opcional del resumen del mensaje separado).


Timestamp

Un token de sello de tiempo 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()

Analiza un token de sello de tiempo y lee sus campos, o verifícalo.


TsaClient

Un cliente de Autoridad de Sellado de Tiempo (detrás de la característica 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 un endpoint de TSA y solicita sellos de tiempo sobre datos o un hash precalculado.


Dss

El Document Security Store, devuelto 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()

Cuenta y lee los certificados, las CRL y las respuestas OCSP almacenados para la validación a largo plazo.


PdfAResults / UaResults / PdfXResults

Handles de resultados de validación devueltos 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()

Inspecciona la conformidad/accesibilidad, las listas de errores y avisos, y las estadísticas de PDF/UA.


ElementList

Una lista genérica de elementos por página, devuelta 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 los elementos de la página (tipo, texto, rect) o serialízalos a JSON.


Funciones de nivel superior

Funciones libres que operan sobre bytes en bruto o sobre el estado global.

func signBytes(_ pdf: [UInt8], certificate: Certificate, reason: String? = nil, location: String? = nil) throws -> [UInt8]

Firma bytes de PDF en bruto y devuelve el PDF firmado.

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]

Firma a un nivel baseline de PAdES (0=B-B, 1=B-T, 2=B-LT) con una URL de TSA y material de revocación opcionales.

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 con opciones por struct de signBytesPades.

func merge(_ paths: [String]) throws -> [UInt8]

Fusiona los PDFs ubicados en paths (en orden) en un único PDF en memoria.

func addTimestamp(_ pdfData: [UInt8], sigIndex: Int32, tsaUrl: String) throws -> [UInt8]

Añade un sello de tiempo RFC 3161 a una firma y devuelve los bytes del PDF guardado de nuevo.

func setLogLevel(_ level: Int32)
func getLogLevel() -> Int32

Establece o lee el nivel de log global de la librería (0=Off … 5=Trace).


PdfOxide (configuración global)

El enum PdfOxide agrupa la política criptográfica de todo el proceso, la precarga de modelos y la configuración del 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

Inspecciona y configura el proveedor criptográfico, el CBOM/inventario, la política y el modo FIPS.

static func modelManifest() -> String
static func prefetchAvailable() -> Int32
static func prefetchModels(languagesCsv: String) throws -> String

Lee el manifiesto de modelos de OCR y precarga modelos para una lista de idiomas separada por comas.

static func setMaxOpsPerStream(_ limit: Int64) -> Int64
static func setPreserveUnmappedGlyphs(_ preserve: Int32) -> Int32

Ajusta los límites del parser y el comportamiento de mapeo de glifos.


Tipos de valor

Structs simples devueltos por los métodos de extracción.

PdfOxideError

struct PdfOxideError: Error, CustomStringConvertible {
    let code: Int32
    let op: String
}

Se lanza ante cualquier código de error de la C ABI distinto de éxito.

PdfVersion

struct PdfVersion { let major: Int; let minor: Int }

Versión del PDF (por ejemplo, 1.7).

Bbox

struct Bbox { let x: Double; let y: Double; let width: Double; let height: Double }

Un cuadro delimitador alineado a los ejes en unidades del espacio de usuario del PDF.

Char

struct Char { let character: UInt32; let bbox: Bbox; let fontName: String; let fontSize: Double }

Un único carácter extraído (valor escalar Unicode).

Word

struct Word { let text: String; let bbox: Bbox; let fontName: String; let fontSize: Double; let bold: Bool }

Una única palabra extraída.

TextLine

struct TextLine { let text: String; let bbox: Bbox; let wordCount: Int }

Una única línea de texto extraída.

Table

struct Table {
    let rowCount: Int
    let colCount: Int
    let hasHeader: Bool
    func cell(_ row: Int, _ col: Int) -> String
}

Una única tabla extraída; las celdas se leen bajo demanda mediante cell(_:_:).

Font

struct Font { let name: String; let type: String; let encoding: String; let embedded: Bool; let subset: Bool }

Un descriptor de fuente incrustada.

Image

struct Image {
    let width: Int
    let height: Int
    let bitsPerComponent: Int
    let format: String
    let colorspace: String
    let data: [UInt8]
}

Una imagen ráster extraída con sus bytes en bruto.

Annotation

struct Annotation { let type: String; let subtype: String; let content: String; let author: String; let rect: Bbox; let borderWidth: Double }

Los atributos principales de una anotación.

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 extendidos de una anotación, de annotationExtras(_:index:).

Path

struct Path { let bbox: Bbox; let strokeWidth: Double; let hasStroke: Bool; let hasFill: Bool; let operationCount: Int }

Un resumen de la geometría de un trazado vectorial.

SearchResult

struct SearchResult { let text: String; let page: Int; let bbox: Bbox }

Una coincidencia de búsqueda de texto.

FormField

struct FormField { let name: String; let value: String; let type: String; let readonly: Bool; let required: Bool }

Un descriptor de campo de formulario.

QuadPoint

struct QuadPoint { let x1, y1, x2, y2, x3, y3, x4, y4: Double }

Un cuadrilátero de anotación de marcado.

Element

struct Element { let type: String; let text: String; let rect: Bbox }

Un elemento de página genérico de un ElementList.

CertificateValidity

struct CertificateValidity { let notBefore: Int64; let notAfter: Int64 }

La ventana de validez de un certificado (timestamps Unix).

UaStats

struct UaStats { let structElements: Int; let images: Int; let tables: Int; let forms: Int; let annotations: Int; let pages: Int }

Estadísticas de estructura PDF/UA de UaResults.stats().


Ejemplo 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

PDF Oxide ofrece bindings nativos para todos los ecosistemas principales: Rust, Python, Node.js, WASM, C#, Golang, Java, PHP, Ruby, C++, Kotlin, Dart, R, Julia, Zig, Scala, Clojure, Objective-C y Elixir.

Próximos pasos