Skip to content

Swift API 레퍼런스

PDF Oxide는 네이티브 C ABI 위에 얹은 관용적인 Swift 바인딩을 제공합니다. CPdfOxide 시스템 라이브러리 모듈이 모듈 맵을 통해 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

메모리 내 바이트(예: S3에서 다운로드했거나 HTTP로 수신한 데이터)로부터 PDF를 엽니다.

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

단일 페이지 또는 문서 전체를 분류합니다(예: 스캔본 vs. 디지털).

영역 추출

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로 렌더링합니다(format0이면 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

소스 형식으로부터 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 지오메트리를 가져오거나 설정합니다.

지우기 및 편집(Redaction)

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]

선택적 압축/GC/선형화 또는 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

1차원 바코드, 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

1차원/2차원 바코드를 생성하고 검사합니다.

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

주체, 발급자, 일련번호, 유효 기간, 현재 유효성을 읽습니다.


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.dss()가 반환하는 Document Security Store입니다.

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

장기 검증을 위해 저장된 인증서, 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]

선택적 TSA URL과 폐기 정보를 사용하여 PAdES 기준 수준(0=B-B, 1=B-T, 2=B-LT)에서 서명합니다.

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 }

추출된 단일 문자(유니코드 스칼라 값)입니다.

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

다음 단계