Swift API 参考
PDF Oxide 在原生 C ABI 之上提供符合 Swift 习惯的绑定。一个 CPdfOxide 系统库模块通过模块映射(module map)暴露 cbindgen 生成的头文件,PdfOxide 则是 Swift 封装层。句柄由类持有(在 deinit 中释放),返回的 C 字符串和缓冲区会被复制到 Swift 的 String/[UInt8] 中,非成功的错误码则以 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
关于 Rust API,参见 Rust API 参考。关于 Python API,参见 Python API 参考。关于类型细节,参见 类型与枚举。
所有页索引均从 0 开始计数。大多数方法都是 throws 方法,在遇到非成功的 C-ABI 错误码时抛出 PdfOxideError。
Document
用于打开、提取、渲染和检查 PDF 文件的核心类。通过静态 open* 工厂方法获取实例。
打开
static func open(_ path: String) throws -> Document
从文件路径打开一个 PDF。
static func openFromBytes(_ bytes: [UInt8]) throws -> Document
从内存中的字节打开 PDF(例如从 S3 下载或通过 HTTP 接收到的数据)。
static func openWithPassword(_ path: String, password: String) throws -> Document
使用用户密码或所有者密码打开一个加密的 PDF。
static func openFromDocxBytes(_ bytes: [UInt8]) throws -> Document
static func openFromPptxBytes(_ bytes: [UInt8]) throws -> Document
static func openFromXlsxBytes(_ bytes: [UInt8]) throws -> Document
将内存字节中的 Office 文档(DOCX、PPTX、XLSX)转换为 Document。
func authenticate(_ password: String) throws -> Bool
对已打开的加密文档进行身份验证。成功时返回 true。
func close()
立即释放原生句柄(幂等;也会在 deinit 中运行)。
文档信息
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
通用的文档元数据访问器。page(_:) 返回给定索引的轻量级 Page 句柄。
文本提取
func extractText(_ page: Int) throws -> String
从单个页面提取纯文本。
func extractChars(_ pageIndex: Int) throws -> [Char]
提取逐字符的定位信息和字体元数据。
func extractWords(_ pageIndex: Int) throws -> [Word]
提取带有边界框、字体名称/字号和粗体标志的单词。
func extractTextLines(_ pageIndex: Int) throws -> [TextLine]
提取按行分组的文本,附带单词数量和边界框。
func extractTables(_ pageIndex: Int) throws -> [Table]
检测并提取表格,包含行、列、表头和单元格文本。
func extractStructuredJson(_ page: Int) throws -> String
提取页面内容的结构化 JSON 表示。
自动提取与分类
func extractTextAuto(_ pageIndex: Int) throws -> String
自动检测最佳提取路径并返回页面文本。
func extractAllText() throws -> String
从文档的每一页提取文本。
func extractPageAuto(_ pageIndex: Int, optionsJson: String = "{}") throws -> String
使用 JSON 配置的选项自动提取页面。
func classifyPage(_ pageIndex: Int) throws -> String
func classifyDocument() throws -> String
对单个页面或整个文档进行分类(例如扫描件还是数字文档)。
区域提取
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]
提取限定在 (x, y, w, h) 矩形内的内容(PDF 用户空间坐标点,原点位于左下角)。
转换
func toPlainText(_ page: Int) throws -> String
func toMarkdown(_ page: Int) throws -> String
func toHtml(_ page: Int) throws -> String
将单个页面转换为纯文本、Markdown 或 HTML。
func toPlainTextAll() throws -> String
func toMarkdownAll() throws -> String
func toHtmlAll() throws -> String
将所有页面转换为纯文本、Markdown 或 HTML。
Office 导出
func toDocx() throws -> [UInt8]
func toPptx() throws -> [UInt8]
func toXlsx() throws -> [UInt8]
将文档导出为 DOCX、PPTX 或 XLSX 字节。
图像、字体与路径
func embeddedImages(_ pageIndex: Int) throws -> [Image]
从页面提取嵌入的栅格图像(含原始字节)。
func embeddedFonts(_ pageIndex: Int) throws -> [Font]
列出页面上的嵌入字体,包含类型、编码和子集标志。
func extractPaths(_ pageIndex: Int) throws -> [Path]
从页面提取矢量路径(直线、曲线、形状)。
func fontsToJson(_ pageIndex: Int) throws -> String
func fontSize(_ pageIndex: Int, fontIndex: Int) throws -> Float
将页面字体序列化为 JSON,或读取单个字体的字号。
注释
func pageAnnotations(_ pageIndex: Int) throws -> [Annotation]
从页面提取注释(类型、子类型、内容、作者、矩形)。
func annotationsToJson(_ pageIndex: Int) throws -> String
将页面的注释序列化为 JSON。
func annotationExtras(_ pageIndex: Int, index: Int) throws -> AnnotationExtras
读取扩展的注释属性(颜色、日期、标志、URI、图标、四点坐标)。
搜索
func search(_ pageIndex: Int, _ term: String, _ caseSensitive: Bool) throws -> [SearchResult]
在单个页面上搜索文本。
func searchAll(_ term: String, _ caseSensitive: Bool) throws -> [SearchResult]
在整个文档中搜索文本。
func searchResultsToJson(_ pageIndex: Int, _ term: String, caseSensitive: Bool) throws -> String
搜索页面并将匹配结果序列化为 JSON。
页面几何
func pageWidth(_ pageIndex: Int) throws -> Float
func pageHeight(_ pageIndex: Int) throws -> Float
func pageRotation(_ pageIndex: Int) throws -> Int
func pageElements(_ pageIndex: Int) throws -> ElementList
读取页面尺寸、旋转角度,以及页面的通用元素列表。
渲染
func renderPage(_ pageIndex: Int, format: Int32 = 0) throws -> RenderedImage
将页面渲染为 RenderedImage(format 为 0 时输出 PNG,为 1 时输出 JPEG)。
func renderPageZoom(_ pageIndex: Int, zoom: Float, format: Int32 = 0) throws -> RenderedImage
按缩放系数渲染页面。
func renderPageThumbnail(_ pageIndex: Int, size: Int, format: Int32 = 0) throws -> RenderedImage
渲染一张适配 size 像素范围内的缩略图。
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
使用完整的渲染选项进行渲染(DPI、背景色/透明度、注释、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
使用完整选项进行渲染,并额外指定一组需要隐藏的 OCG 图层名称。
func renderPageRegion(
_ pageIndex: Int, cropX: Float, cropY: Float, cropWidth: Float, cropHeight: Float,
format: Int32 = 0
) throws -> RenderedImage
渲染页面的某个矩形区域。
func renderPageFit(_ pageIndex: Int, width: Int32, height: Int32, format: Int32 = 0) throws -> RenderedImage
将页面渲染至适配 width×height 像素范围内,并保持宽高比。
func renderPageRaw(_ pageIndex: Int, dpi: Int32 = 150) throws -> (image: RenderedImage, width: Int, height: Int)
渲染为原始的预乘 RGBA8888 缓冲区,并返回像素尺寸。
func estimateRenderTime(_ pageIndex: Int) throws -> Int32
估算页面的渲染开销(单位由实现定义)。
OCR
func ocrPageNeedsOcr(_ pageIndex: Int) throws -> Bool
启发式判断某个页面是否需要 OCR(例如扫描页面)。
func ocrExtractText(_ pageIndex: Int, engine: OcrEngine? = nil) throws -> String
通过 OCR 提取文本。传入自定义的 OcrEngine,或传入 nil 使用默认引擎。
表单
func formFields() throws -> [FormField]
列出所有表单字段,含名称、值、类型,以及只读/必填标志。
func exportFormData(formatType: Int32) throws -> [UInt8]
将表单数据导出为 FDF/XFDF 字节。
func importFormData(_ dataPath: String) throws -> Int32
func importFormFromFile(_ filename: String) throws -> Bool
从文件路径导入表单数据。
文档结构
func outline() throws -> String
func pageLabels() throws -> String
func xmpMetadata() throws -> String
func sourceBytes() throws -> [UInt8]
func planSplitByBookmarks(optionsJson: String = "{}") throws -> String
读取文档大纲、页面标签、XMP 元数据、原始源字节,或基于书签的 JSON 拆分方案。
内容清理
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
擦除单个页面上的页眉/页脚/杂质内容,或基于出现频率阈值在整个文档范围内擦除。
校验
func validatePdfA(_ level: Int32) throws -> PdfAResults
func validatePdfUa(_ level: Int32) throws -> UaResults
func validatePdfX(_ level: Int32) throws -> PdfXResults
针对 PDF/A、PDF/UA 或 PDF/X 一致性级别校验文档。
func convertToPdfA(_ level: Int32) throws -> Bool
就地将文档转换为 PDF/A。成功时返回 true。
签名
func sign(_ certificate: Certificate, reason: String, location: String) throws -> Int32
使用证书对文档签名,并嵌入签名原因和位置。
func signatureCount() throws -> Int
func signature(_ index: Int) throws -> SignatureInfo?
func verifyAllSignatures() throws -> Int32
func hasTimestamp() throws -> Bool
func dss() throws -> Dss?
检查已有签名,校验所有签名(1=有效,0=无效,-1=未知),检查是否存在文档时间戳,并访问文档安全存储区(Document Security Store)。
条码
func addBarcodeToPage(_ page: Int, _ barcode: BarcodeImage, x: Float, y: Float, width: Float, height: Float) throws
将生成的 BarcodeImage 按给定位置和尺寸绘制到页面上。
Page
由 Document.page(_:) 返回的轻量级单页句柄。所有访问器都会派发到所属文档。
let index: Int
从 0 开始计数的页索引。
func text() throws -> String
func markdown() throws -> String
func html() throws -> String
func plainText() throws -> String
将页面提取为纯文本、Markdown 或 HTML。
用于从源格式创建 PDF 并保存的类。
工厂方法
static func fromMarkdown(_ md: String) throws -> Pdf
static func fromHtml(_ html: String) throws -> Pdf
static func fromText(_ text: String) throws -> Pdf
从 Markdown、HTML 或纯文本创建 PDF。
static func fromImage(_ path: String) throws -> Pdf
static func fromImageBytes(_ bytes: [UInt8]) throws -> Pdf
从图像文件或图像字节创建单页 PDF。
static func fromHtmlCss(html: String, css: String, fontBytes: [UInt8] = []) throws -> Pdf
从 HTML + CSS 创建 PDF,可选嵌入一个字体。
static func fromHtmlCssWithFonts(html: String, css: String, fonts: [(String, [UInt8])]) throws -> Pdf
从 HTML + CSS 创建 PDF,并嵌入多个命名字体。
方法
func save(_ path: String) throws
func toBytes() throws -> [UInt8]
func pageCount() throws -> Int
func close()
保存到文件、获取 PDF 字节、统计页数,或释放句柄。
DocumentEditor
用于修改现有 PDF 的可变编辑器:页面、旋转、几何、密文涂黑(redaction)、扁平化、表单、合并及保存。
打开与生命周期
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()
从路径或字节打开编辑器,并在完成后释放句柄。
信息与元数据
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
读取文档信息,并获取/设置生成者(producer)和创建日期。
页面操作
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
删除、移动和旋转页面。
页面几何
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
裁剪页边距,并获取/设置 CropBox 和 MediaBox 几何。
擦除与密文涂黑
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
加入和清除矩形擦除区域。
func applyAllRedactions() throws
func applyPageRedactions(_ page: Int) throws
func isPageMarkedForRedaction(_ page: Int) throws -> Bool
func unmarkPageForRedaction(_ page: Int) throws
应用待处理的密文涂黑,并管理逐页的涂黑标记。
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
加入涂黑区域、统计数量、破坏性地应用涂黑(返回被移除的字形数),或仅清除元数据/JavaScript/嵌入文件。
扁平化
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
扁平化表单和注释、读取扁平化警告,并管理逐页的扁平化标记。
表单
func setFormFieldValue(_ name: String, _ value: String) throws
func importFdfBytes(_ data: [UInt8]) throws -> Int32
func importXfdfBytes(_ data: [UInt8]) throws -> Int32
设置表单字段值,或从字节导入 FDF/XFDF 数据。
条码
func addBarcodeToPage(_ page: Int, _ barcode: BarcodeImage, x: Float, y: Float, width: Float, height: Float) throws
将生成的条码绘制到页面上。
文档操作
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]
合并另一个 PDF、转换为 PDF/A、附加文件,或将页面子集提取为字节。
保存
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]
保存到文件或字节,可选压缩/垃圾回收/线性化,或使用 AES 密码加密。
DocumentBuilder
用于从零开始创建带标签、多页 PDF 的流式构建器。大多数方法返回 self 以支持链式调用。
static func create() throws -> DocumentBuilder
创建一个新的文档构建器。
元数据与结构
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
设置文档元数据、打开动作脚本、PDF/UA 标签、语言、角色映射,并注册嵌入字体。
页面
func a4Page() throws -> PageBuilder
func letterPage() throws -> PageBuilder
func page(_ width: Float, _ height: Float) throws -> PageBuilder
开始一个 A4、Letter 或自定义尺寸的页面,并返回一个 PageBuilder。
输出
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()
构建为字节、保存到文件,或使用 AES 加密保存。
PageBuilder
用于构建单个页面内容的流式构建器,由 DocumentBuilder.a4Page() / .letterPage() / .page(_:_:) 返回。大多数方法返回 self。
文本与版面
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
设置当前字体和位置,然后写入文本、标题、段落、间距、分隔线、多栏排版、脚注,或开始一个相同尺寸的新页面。
内联文本片段
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
追加带样式的内联文本片段和换行符。
链接与脚本
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
添加 URL/页面/命名/JavaScript 链接注释,并附加页面级或字段级脚本。
标记注释
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
添加高亮/下划线/删除线/波浪线标记、便签、水印、印章和自由文本注释。
表单字段
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
添加 AcroForm 文本字段、复选框、按钮、签名字段、组合框和单选按钮组。
条码与图像
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
绘制一维条码、QR 码和图像(可选附带替代文本或标记为杂质)。
矢量图形
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
绘制矩形、直线、描边/虚线形状,以及限定在矩形内的文本。
表格
func table(nColumns: Int, widths: [Float], aligns: [Int32], nRows: Int, cellStrings: [String], hasHeader: Bool) throws -> PageBuilder
缓冲一个静态表格;cellStrings 按行主序排列(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
通过流式逐行推送增量构建大型表格,支持可选的跨行(rowspan)、分批和自动适配模式。
收尾
func done() throws
func close()
完成页面并将控制权交还给父构建器。
EmbeddedFont
向 DocumentBuilder 注册的字体。
static func fromFile(_ path: String) throws -> EmbeddedFont
static func fromBytes(_ bytes: [UInt8], name: String? = nil) throws -> EmbeddedFont
func close()
从文件或字节加载 TrueType/OpenType 字体。
BarcodeImage
生成并检查一维/二维条码。
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
生成 QR 码或给定格式的条码。
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()
读取解码后的载荷、格式和置信度,或将条码渲染为 PNG 字节或 SVG 字符串。
RenderedImage
由 Document.renderPage* 方法返回的已渲染页面图像。
let width: Int
let height: Int
let data: [UInt8]
func save(_ path: String) throws
func close()
像素尺寸、编码后的图像字节,以及一个用于将图像保存到文件的辅助方法。
Renderer
独立的渲染器配置句柄。
static func create(dpi: Int32 = 150, format: Int32 = 0, quality: Int32 = 90, antiAlias: Bool = true) throws -> Renderer
func close()
创建一个可复用的渲染器,带有 DPI、格式(0=PNG,1=JPEG)、JPEG 质量和抗锯齿设置。
OcrEngine
由检测/识别模型支撑的 OCR 引擎。
static func create(detModelPath: String, recModelPath: String, dictPath: String) throws -> OcrEngine
func close()
从检测模型、识别模型和字典路径创建一个引擎。将它传给 Document.ocrExtractText(_:engine:)。
Certificate
签名证书及密钥。
static func loadFromBytes(_ bytes: [UInt8], password: String) throws -> Certificate
static func loadFromPem(certPem: String, keyPem: String) throws -> Certificate
从 PKCS#12 字节(带密码)或 PEM 字符串加载证书。
func subject() throws -> String
func issuer() throws -> String
func serial() throws -> String
func validity() throws -> CertificateValidity
func isValid() throws -> Bool
func close()
读取主题(subject)、签发者(issuer)、序列号、有效期窗口和当前有效性。
SignatureInfo
已有签名的详细信息,由 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()
读取签名者元数据、证书、PAdES 级别和时间戳;校验签名(可选附带分离式消息摘要检查)。
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()
解析时间戳令牌并读取其字段,或对其进行校验。
TsaClient
时间戳颁发机构(TSA)客户端(位于 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()
配置一个 TSA 端点,并基于数据或预先计算的哈希请求时间戳。
Dss
文档安全存储区(Document Security Store),由 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()
统计并读取为长期验证(LTV)而存储的证书、CRL 和 OCSP 响应。
PdfAResults / UaResults / PdfXResults
由 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()
检查合规性/无障碍性、错误与警告列表,以及 PDF/UA 统计信息。
ElementList
通用的逐页元素列表,由 Document.pageElements(_:) 返回。
func count() throws -> Int
func element(_ index: Int) throws -> Element
func all() throws -> [Element]
func toJson() throws -> String
func close()
遍历页面元素(类型、文本、矩形),或将它们序列化为 JSON。
顶层函数
在原始字节或全局状态上操作的自由函数。
func signBytes(_ pdf: [UInt8], certificate: Certificate, reason: String? = nil, location: String? = nil) throws -> [UInt8]
对原始 PDF 字节签名并返回签名后的 PDF。
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]
按 PAdES 基线级别(0=B-B,1=B-T,2=B-LT)签名,可选指定 TSA URL 和吊销材料。
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]
signBytesPades 的结构体选项变体。
func merge(_ paths: [String]) throws -> [UInt8]
将 paths 处的 PDF(按顺序)合并为单个内存中的 PDF。
func addTimestamp(_ pdfData: [UInt8], sigIndex: Int32, tsaUrl: String) throws -> [UInt8]
为某个签名添加 RFC 3161 时间戳,并返回重新保存后的 PDF 字节。
func setLogLevel(_ level: Int32)
func getLogLevel() -> Int32
设置或读取全局库日志级别(0=Off … 5=Trace)。
PdfOxide(全局配置)
PdfOxide 枚举将进程范围内的加密策略、模型预取和解析器配置纳入同一命名空间。
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
检查并配置加密提供方、CBOM/清单、策略,以及 FIPS 模式。
static func modelManifest() -> String
static func prefetchAvailable() -> Int32
static func prefetchModels(languagesCsv: String) throws -> String
读取 OCR 模型清单,并为逗号分隔的语言列表预取模型。
static func setMaxOpsPerStream(_ limit: Int64) -> Int64
static func setPreserveUnmappedGlyphs(_ preserve: Int32) -> Int32
调整解析器限制和字形映射行为。
值类型
由提取方法返回的纯结构体。
PdfOxideError
struct PdfOxideError: Error, CustomStringConvertible {
let code: Int32
let op: String
}
在遇到任何非成功的 C-ABI 错误码时抛出。
PdfVersion
struct PdfVersion { let major: Int; let minor: Int }
PDF 版本(例如 1.7)。
Bbox
struct Bbox { let x: Double; let y: Double; let width: Double; let height: Double }
PDF 用户空间单位中的轴对齐边界框。
Char
struct Char { let character: UInt32; let bbox: Bbox; let fontName: String; let fontSize: Double }
单个提取出的字符(Unicode 标量值)。
Word
struct Word { let text: String; let bbox: Bbox; let fontName: String; let fontSize: Double; let bold: Bool }
单个提取出的单词。
TextLine
struct TextLine { let text: String; let bbox: Bbox; let wordCount: Int }
单个提取出的文本行。
Table
struct Table {
let rowCount: Int
let colCount: Int
let hasHeader: Bool
func cell(_ row: Int, _ col: Int) -> String
}
单个提取出的表格;单元格通过 cell(_:_:) 按需读取。
Font
struct Font { let name: String; let type: String; let encoding: String; let embedded: Bool; let subset: Bool }
嵌入字体描述符。
Image
struct Image {
let width: Int
let height: Int
let bitsPerComponent: Int
let format: String
let colorspace: String
let data: [UInt8]
}
带有原始字节的提取栅格图像。
Annotation
struct Annotation { let type: String; let subtype: String; let content: String; let author: String; let rect: Bbox; let borderWidth: Double }
注释的核心属性。
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]
}
来自 annotationExtras(_:index:) 的扩展注释属性。
Path
struct Path { let bbox: Bbox; let strokeWidth: Double; let hasStroke: Bool; let hasFill: Bool; let operationCount: Int }
矢量路径的几何摘要。
SearchResult
struct SearchResult { let text: String; let page: Int; let bbox: Bbox }
一个文本搜索匹配。
FormField
struct FormField { let name: String; let value: String; let type: String; let readonly: Bool; let required: Bool }
表单字段描述符。
QuadPoint
struct QuadPoint { let x1, y1, x2, y2, x3, y3, x4, y4: Double }
标记注释的四边形。
Element
struct Element { let type: String; let text: String; let rect: Bbox }
来自 ElementList 的通用页面元素。
CertificateValidity
struct CertificateValidity { let notBefore: Int64; let notAfter: Int64 }
证书的有效期窗口(Unix 时间戳)。
UaStats
struct UaStats { let structElements: Int; let images: Int; let tables: Int; let forms: Int; let annotations: Int; let pages: Int }
来自 UaResults.stats() 的 PDF/UA 结构统计信息。
完整示例
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 为所有主流生态系统提供原生绑定:Rust, Python, Node.js, WASM, C#, Golang, Java, PHP, Ruby, C++, Kotlin, Dart, R, Julia, Zig, Scala, Clojure, Objective-C, Elixir。
后续步骤
- 类型与枚举 — 所有共享类型与枚举
- Page API 参考 — 各绑定间一致的逐页迭代方式
- Swift 快速上手 — 教程