pdf-oxide 0.3.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +218 -0
  2. package/binding.gyp +35 -0
  3. package/package.json +78 -0
  4. package/src/builders/annotation-builder.ts +367 -0
  5. package/src/builders/conversion-options-builder.ts +257 -0
  6. package/src/builders/index.ts +12 -0
  7. package/src/builders/metadata-builder.ts +317 -0
  8. package/src/builders/pdf-builder.ts +386 -0
  9. package/src/builders/search-options-builder.ts +151 -0
  10. package/src/document-editor-manager.ts +318 -0
  11. package/src/errors.ts +1629 -0
  12. package/src/form-field-manager.ts +666 -0
  13. package/src/hybrid-ml-manager.ts +283 -0
  14. package/src/index.ts +453 -0
  15. package/src/managers/accessibility-manager.ts +338 -0
  16. package/src/managers/annotation-manager.ts +439 -0
  17. package/src/managers/barcode-manager.ts +235 -0
  18. package/src/managers/batch-manager.ts +533 -0
  19. package/src/managers/cache-manager.ts +486 -0
  20. package/src/managers/compliance-manager.ts +375 -0
  21. package/src/managers/content-manager.ts +339 -0
  22. package/src/managers/document-utility-manager.ts +922 -0
  23. package/src/managers/dom-pdf-creator.ts +365 -0
  24. package/src/managers/editing-manager.ts +514 -0
  25. package/src/managers/enterprise-manager.ts +478 -0
  26. package/src/managers/extended-managers.ts +437 -0
  27. package/src/managers/extraction-manager.ts +583 -0
  28. package/src/managers/final-utilities.ts +429 -0
  29. package/src/managers/hybrid-ml-advanced.ts +479 -0
  30. package/src/managers/index.ts +239 -0
  31. package/src/managers/layer-manager.ts +500 -0
  32. package/src/managers/metadata-manager.ts +303 -0
  33. package/src/managers/ocr-manager.ts +756 -0
  34. package/src/managers/optimization-manager.ts +262 -0
  35. package/src/managers/outline-manager.ts +196 -0
  36. package/src/managers/page-manager.ts +289 -0
  37. package/src/managers/pattern-detection.ts +440 -0
  38. package/src/managers/rendering-manager.ts +863 -0
  39. package/src/managers/search-manager.ts +385 -0
  40. package/src/managers/security-manager.ts +345 -0
  41. package/src/managers/signature-manager.ts +1664 -0
  42. package/src/managers/streams.ts +618 -0
  43. package/src/managers/xfa-manager.ts +500 -0
  44. package/src/pdf-creator-manager.ts +494 -0
  45. package/src/properties.ts +522 -0
  46. package/src/result-accessors-manager.ts +867 -0
  47. package/src/tests/advanced-features.test.ts +414 -0
  48. package/src/tests/advanced.test.ts +266 -0
  49. package/src/tests/extended-managers.test.ts +316 -0
  50. package/src/tests/final-utilities.test.ts +455 -0
  51. package/src/tests/foundation.test.ts +315 -0
  52. package/src/tests/high-demand.test.ts +257 -0
  53. package/src/tests/specialized.test.ts +97 -0
  54. package/src/thumbnail-manager.ts +272 -0
  55. package/src/types/common.ts +142 -0
  56. package/src/types/document-types.ts +457 -0
  57. package/src/types/index.ts +6 -0
  58. package/src/types/manager-types.ts +284 -0
  59. package/src/types/native-bindings.ts +517 -0
  60. package/src/workers/index.ts +7 -0
  61. package/src/workers/pool.ts +274 -0
  62. package/src/workers/worker.ts +131 -0
package/README.md ADDED
@@ -0,0 +1,218 @@
1
+ # PDF Oxide for Node.js — The Fastest PDF Toolkit for JavaScript & TypeScript
2
+
3
+ The fastest Node.js PDF library for text extraction, image extraction, and markdown conversion. Powered by a pure-Rust core, exposed to Node.js through a native N-API addon. 0.8ms mean per document, 5× faster than PyMuPDF, 15× faster than pypdf. 100% pass rate on 3,830 real-world PDFs. MIT / Apache-2.0 licensed.
4
+
5
+ [![npm](https://img.shields.io/npm/v/pdf-oxide)](https://www.npmjs.com/package/pdf-oxide)
6
+ [![License: MIT OR Apache-2.0](https://img.shields.io/badge/License-MIT%20OR%20Apache--2.0-blue.svg)](https://opensource.org/licenses)
7
+
8
+ > **Part of the [PDF Oxide](https://github.com/yfedoseev/pdf_oxide) toolkit.** Same Rust core, same speed, same 100% pass rate as the [Rust](https://docs.rs/pdf_oxide), [Python](../python/README.md), [Go](../go/README.md), [C# / .NET](../csharp/README.md), and [WASM](../wasm-pkg/README.md) bindings.
9
+ >
10
+ > Need to run in browsers, Deno, Bun, or Cloudflare Workers? Use the [WASM build](../wasm-pkg/README.md) instead — same API, no native binaries.
11
+
12
+ ## Quick Start
13
+
14
+ ```bash
15
+ npm install pdf-oxide
16
+ ```
17
+
18
+ ```javascript
19
+ const { PdfDocument } = require("pdf-oxide");
20
+
21
+ const doc = new PdfDocument("paper.pdf");
22
+ const text = doc.extractText(0);
23
+ const markdown = doc.toMarkdown(0);
24
+ doc.close();
25
+ ```
26
+
27
+ TypeScript:
28
+
29
+ ```typescript
30
+ import { PdfDocument } from "pdf-oxide";
31
+
32
+ const doc = new PdfDocument("paper.pdf");
33
+ const text: string = doc.extractText(0);
34
+ const markdown: string = doc.toMarkdown(0);
35
+ doc.close();
36
+ ```
37
+
38
+ ## Why pdf_oxide?
39
+
40
+ - **Fast** — 0.8ms mean per document, 5× faster than PyMuPDF, 15× faster than pypdf, 29× faster than pdfplumber
41
+ - **Reliable** — 100% pass rate on 3,830 test PDFs, zero panics, zero timeouts, no segfaults
42
+ - **Complete** — Text extraction, image extraction, search, form fields, PDF creation, and editing in one package
43
+ - **Permissive license** — MIT / Apache-2.0 — use freely in commercial and closed-source projects
44
+ - **Pure Rust core** — Memory-safe, panic-free, no C dependencies beyond the N-API glue
45
+ - **Native binaries** — Pre-built `.node` addons for Linux, macOS, and Windows (x64 + ARM64)
46
+ - **Full TypeScript support** — Type definitions ship in the package
47
+
48
+ ## Performance
49
+
50
+ Benchmarked on 3,830 PDFs from three independent public test suites (veraPDF, Mozilla pdf.js, DARPA SafeDocs). Text extraction libraries only. Single-thread, 60s timeout, no warm-up.
51
+
52
+ | Library | Mean | p99 | Pass Rate | License |
53
+ |---------|------|-----|-----------|---------|
54
+ | **PDF Oxide** | **0.8ms** | **9ms** | **100%** | **MIT / Apache-2.0** |
55
+ | PyMuPDF | 4.6ms | 28ms | 99.3% | AGPL-3.0 |
56
+ | pypdfium2 | 4.1ms | 42ms | 99.2% | Apache-2.0 |
57
+ | pdftext | 7.3ms | 82ms | 99.0% | GPL-3.0 |
58
+ | pdfminer | 16.8ms | 124ms | 98.8% | MIT |
59
+ | pypdf | 12.1ms | 97ms | 98.4% | BSD-3 |
60
+
61
+ 99.5% text parity vs PyMuPDF and pypdfium2 across the full corpus. The Node.js binding adds negligible overhead — extraction stays within ~25% of direct Rust calls on real-world fixtures.
62
+
63
+ ## Installation
64
+
65
+ ```bash
66
+ npm install pdf-oxide
67
+ ```
68
+
69
+ Pre-built native addons for:
70
+
71
+ | Platform | x64 | ARM64 |
72
+ |---|---|---|
73
+ | Linux (glibc) | Yes | Yes |
74
+ | Linux (musl) | Yes | Yes |
75
+ | macOS | Yes | Yes (Apple Silicon) |
76
+ | Windows | Yes | Yes |
77
+
78
+ Requires Node.js 18 or newer. No system dependencies. No Rust toolchain required.
79
+
80
+ ## API Tour
81
+
82
+ ### Open a document
83
+
84
+ ```javascript
85
+ const { PdfDocument } = require("pdf-oxide");
86
+
87
+ const doc = new PdfDocument("report.pdf");
88
+ console.log(`Pages: ${doc.getPageCount()}`);
89
+
90
+ const { major, minor } = doc.getVersion();
91
+ console.log(`PDF version: ${major}.${minor}`);
92
+
93
+ doc.close();
94
+ ```
95
+
96
+ Use `using` for automatic cleanup (Node.js 22+):
97
+
98
+ ```javascript
99
+ {
100
+ using doc = new PdfDocument("report.pdf");
101
+ const text = doc.extractText(0);
102
+ } // doc.close() called automatically
103
+ ```
104
+
105
+ ### Text extraction
106
+
107
+ ```javascript
108
+ const text = doc.extractText(0); // single page
109
+ const markdown = doc.toMarkdown(0); // single page → Markdown
110
+ const html = doc.toHtml(0); // single page → HTML
111
+ const plain = doc.toPlainText(0); // single page → plain text
112
+
113
+ const allMarkdown = doc.toMarkdownAll(); // entire document
114
+ const allHtml = doc.toHtmlAll();
115
+ ```
116
+
117
+ ### Iterate all pages
118
+
119
+ ```javascript
120
+ const doc = new PdfDocument("document.pdf");
121
+ const pageCount = doc.getPageCount();
122
+
123
+ const pages = [];
124
+ for (let i = 0; i < pageCount; i++) {
125
+ pages.push(doc.extractText(i));
126
+ }
127
+
128
+ doc.close();
129
+ ```
130
+
131
+ ### Async wrapper
132
+
133
+ ```javascript
134
+ async function extractAll(filePath) {
135
+ const doc = new PdfDocument(filePath);
136
+ try {
137
+ const pageCount = doc.getPageCount();
138
+ const pages = [];
139
+ for (let i = 0; i < pageCount; i++) {
140
+ pages.push(doc.extractText(i));
141
+ }
142
+ return pages;
143
+ } finally {
144
+ doc.close();
145
+ }
146
+ }
147
+
148
+ const pages = await extractAll("document.pdf");
149
+ ```
150
+
151
+ ### Error handling
152
+
153
+ All methods throw on failure. Catch with try/catch:
154
+
155
+ ```javascript
156
+ try {
157
+ const text = doc.extractText(0);
158
+ } catch (err) {
159
+ console.error("Extraction failed:", err.message);
160
+ } finally {
161
+ doc.close();
162
+ }
163
+ ```
164
+
165
+ ## Other languages
166
+
167
+ PDF Oxide ships the same Rust core through six bindings:
168
+
169
+ - **Rust** — `cargo add pdf_oxide` — see [docs.rs/pdf_oxide](https://docs.rs/pdf_oxide)
170
+ - **Python** — `pip install pdf_oxide` — see [python/README.md](../python/README.md)
171
+ - **Go** — `go get github.com/yfedoseev/pdf_oxide/go` — see [go/README.md](../go/README.md)
172
+ - **C# / .NET** — `dotnet add package PdfOxide` — see [csharp/README.md](../csharp/README.md)
173
+ - **WASM (browsers, Deno, Bun, edge runtimes)** — `npm install pdf-oxide-wasm` — see [wasm-pkg/README.md](../wasm-pkg/README.md)
174
+
175
+ A bug fix in the Rust core lands in every binding on the next release.
176
+
177
+ ## Documentation
178
+
179
+ - **[Full Documentation](https://pdf.oxide.fyi)** — Complete documentation site
180
+ - **[JavaScript Getting Started](https://pdf.oxide.fyi/docs/getting-started/javascript)** — Step-by-step Node.js guide
181
+ - **[Main Repository](https://github.com/yfedoseev/pdf_oxide)** — Rust core, CLI, MCP server, all bindings
182
+ - **[Performance Benchmarks](https://pdf.oxide.fyi/docs/performance)** — Full benchmark methodology and results
183
+ - **[GitHub Issues](https://github.com/yfedoseev/pdf_oxide/issues)** — Bug reports and feature requests
184
+
185
+ ## Use Cases
186
+
187
+ - **RAG / LLM pipelines** — Convert PDFs to clean Markdown for retrieval-augmented generation with LangChain.js, LlamaIndex.js, or any framework
188
+ - **Document processing at scale** — Extract text, images, and metadata from thousands of PDFs in seconds
189
+ - **Server-side PDF rendering** — Extract structured content for search indexing, archival, or transformation pipelines
190
+ - **PDF generation** — Create invoices, reports, certificates, and templated documents programmatically
191
+ - **PyMuPDF alternative** — MIT licensed, 5× faster, no AGPL restrictions, no Python required
192
+
193
+ ## Why I built this
194
+
195
+ I needed PyMuPDF's speed without its AGPL license, and I needed it in more than one language. Nothing existed that ticked all three boxes — fast, MIT, multi-language — so I wrote it. The Rust core is what does the real work; the bindings for Python, Go, JS/TS, C#, and WASM are thin shells around the same code, so a bug fix in one lands in all of them. It now passes 100% of the veraPDF + Mozilla pdf.js + DARPA SafeDocs test corpora (3,830 PDFs) on every platform I've tested.
196
+
197
+ If it's useful to you, a star on GitHub genuinely helps. If something's broken or missing, [open an issue](https://github.com/yfedoseev/pdf_oxide/issues) — I read all of them.
198
+
199
+ — Yury
200
+
201
+ ## License
202
+
203
+ Dual-licensed under [MIT](https://github.com/yfedoseev/pdf_oxide/blob/main/LICENSE-MIT) or [Apache-2.0](https://github.com/yfedoseev/pdf_oxide/blob/main/LICENSE-APACHE) at your option. Unlike AGPL-licensed alternatives, pdf_oxide can be used freely in any project — commercial or open-source — with no copyleft restrictions.
204
+
205
+ ## Citation
206
+
207
+ ```bibtex
208
+ @software{pdf_oxide,
209
+ title = {PDF Oxide: Fast PDF Toolkit for Rust, Python, Go, JavaScript, and C#},
210
+ author = {Yury Fedoseev},
211
+ year = {2025},
212
+ url = {https://github.com/yfedoseev/pdf_oxide}
213
+ }
214
+ ```
215
+
216
+ ---
217
+
218
+ **JavaScript** + **TypeScript** + **Rust core** | MIT / Apache-2.0 | 100% pass rate on 3,830 PDFs | 0.8ms mean | 5× faster than the industry leaders
package/binding.gyp ADDED
@@ -0,0 +1,35 @@
1
+ {
2
+ "targets": [
3
+ {
4
+ "target_name": "pdf_oxide",
5
+ "sources": ["binding.cc"],
6
+ "include_dirs": [
7
+ "<!@(node -p \"require('node-addon-api').include\")"
8
+ ],
9
+ "dependencies": [
10
+ "<!(node -p \"require('node-addon-api').gyp\")"
11
+ ],
12
+ "cflags": ["-Wall", "-Wextra"],
13
+ "cflags_cc": ["-fexceptions"],
14
+ "xcode_settings": {
15
+ "GCC_ENABLE_CPP_EXCEPTIONS": "YES",
16
+ "CLANG_CXX_LIBRARY": "libc++"
17
+ },
18
+ "msvs_settings": {
19
+ "VCCLCompilerTool": {
20
+ "ExceptionHandling": 1
21
+ }
22
+ },
23
+ "libraries": ["-lpdf_oxide"],
24
+ "library_dirs": [
25
+ "<!@(pwd)/../lib"
26
+ ],
27
+ "link_settings": {
28
+ "libraries": ["-lpdf_oxide"],
29
+ "library_dirs": [
30
+ "<!@(pwd)/../lib"
31
+ ]
32
+ }
33
+ }
34
+ ]
35
+ }
package/package.json ADDED
@@ -0,0 +1,78 @@
1
+ {
2
+ "name": "pdf-oxide",
3
+ "version": "0.3.24",
4
+ "type": "module",
5
+ "description": "High-performance PDF parsing and text extraction library with multi-language support",
6
+ "main": "lib/index.js",
7
+ "types": "lib/index.d.ts",
8
+ "scripts": {
9
+ "prebuild": "npm run compile:ts",
10
+ "build": "npm run compile:ts && node scripts/fix-esm-imports.js && node-gyp build",
11
+ "compile:ts": "tsc",
12
+ "typecheck": "tsc --noEmit",
13
+ "clean:ts": "rimraf lib/",
14
+ "clean": "npm run clean:ts && node-gyp clean",
15
+ "install": "npm run build",
16
+ "test": "node --test tests/smoke.test.mjs"
17
+ },
18
+ "files": [
19
+ "lib/",
20
+ "src/",
21
+ "binding.gyp",
22
+ "package.json",
23
+ "README.md"
24
+ ],
25
+ "keywords": [
26
+ "pdf",
27
+ "text-extraction",
28
+ "pdf-parsing",
29
+ "rust-ffi",
30
+ "native-binding"
31
+ ],
32
+ "author": "PDF Oxide Contributors",
33
+ "license": "MIT",
34
+ "homepage": "https://github.com/yfedoseev/pdf_oxide",
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "https://github.com/yfedoseev/pdf_oxide.git",
38
+ "directory": "nodejs"
39
+ },
40
+ "engines": {
41
+ "node": ">=18.0.0"
42
+ },
43
+ "exports": {
44
+ ".": {
45
+ "import": "./lib/index.js",
46
+ "types": "./lib/index.d.ts"
47
+ },
48
+ "./builders": {
49
+ "import": "./lib/builders/index.js",
50
+ "types": "./lib/builders/index.d.ts"
51
+ },
52
+ "./managers": {
53
+ "import": "./lib/managers/index.js",
54
+ "types": "./lib/managers/index.d.ts"
55
+ },
56
+ "./errors": {
57
+ "import": "./lib/errors.js",
58
+ "types": "./lib/errors.d.ts"
59
+ }
60
+ },
61
+ "gypfile": true,
62
+ "binary": {
63
+ "module_name": "pdf_oxide",
64
+ "module_path": "./build/Release/",
65
+ "host": "https://github.com/releases/download/",
66
+ "remote_path": "./v{version}/{module_name}-v{version}-{node_abi}-{platform}-{arch}.tar.gz",
67
+ "package_name": "{module_name}-v{version}-{node_abi}-{platform}-{arch}.tar.gz"
68
+ },
69
+ "devDependencies": {
70
+ "@types/node": "^18.0.0",
71
+ "node-gyp": "^9.3.1",
72
+ "rimraf": "^5.0.0",
73
+ "typescript": "^5.3.0"
74
+ },
75
+ "dependencies": {
76
+ "node-addon-api": "^8.7.0"
77
+ }
78
+ }
@@ -0,0 +1,367 @@
1
+ /**
2
+ * Builder for creating PDF annotations
3
+ *
4
+ * Configures annotation properties like content, appearance, author, and behavior.
5
+ *
6
+ * @example
7
+ * ```typescript
8
+ * import { AnnotationBuilder } from 'pdf_oxide';
9
+ *
10
+ * const annotation = AnnotationBuilder.create()
11
+ * .type('highlight')
12
+ * .content('Important section')
13
+ * .author('Reviewer')
14
+ * .color([1, 1, 0]) // Yellow
15
+ * .build();
16
+ *
17
+ * pdf.addAnnotation(annotation);
18
+ * ```
19
+ */
20
+
21
+ interface AnnotationBounds {
22
+ x: number;
23
+ y: number;
24
+ width: number;
25
+ height: number;
26
+ }
27
+
28
+ export interface Annotation {
29
+ type: string;
30
+ content: string;
31
+ author?: string;
32
+ subject?: string;
33
+ color: number[];
34
+ opacity: number;
35
+ bounds?: AnnotationBounds;
36
+ creationDate: Date;
37
+ modificationDate: Date;
38
+ flags: number;
39
+ reply?: string;
40
+ }
41
+
42
+ export class AnnotationBuilder {
43
+ private _type: string = 'text';
44
+ private _content: string = '';
45
+ private _author?: string;
46
+ private _subject?: string;
47
+ private _color: number[] = [1, 0, 0]; // Default: red (RGB normalized 0-1)
48
+ private _opacity: number = 1.0;
49
+ private _bounds?: AnnotationBounds;
50
+ private _creationDate: Date = new Date();
51
+ private _modificationDate: Date = new Date();
52
+ private _flags: number = 0;
53
+ private _reply?: string;
54
+
55
+ /**
56
+ * Creates a new AnnotationBuilder instance
57
+ * @private
58
+ */
59
+ private constructor() {}
60
+
61
+ /**
62
+ * Creates a new AnnotationBuilder instance
63
+ * @returns New builder instance
64
+ */
65
+ static create(): AnnotationBuilder {
66
+ return new AnnotationBuilder();
67
+ }
68
+
69
+ /**
70
+ * Creates a text annotation (comment/note)
71
+ * @returns This builder for chaining
72
+ */
73
+ asText(): this {
74
+ this._type = 'text';
75
+ return this;
76
+ }
77
+
78
+ /**
79
+ * Creates a highlight annotation
80
+ * @returns This builder for chaining
81
+ */
82
+ asHighlight(): this {
83
+ this._type = 'highlight';
84
+ return this;
85
+ }
86
+
87
+ /**
88
+ * Creates an underline annotation
89
+ * @returns This builder for chaining
90
+ */
91
+ asUnderline(): this {
92
+ this._type = 'underline';
93
+ return this;
94
+ }
95
+
96
+ /**
97
+ * Creates a strikeout annotation
98
+ * @returns This builder for chaining
99
+ */
100
+ asStrikeout(): this {
101
+ this._type = 'strikeout';
102
+ return this;
103
+ }
104
+
105
+ /**
106
+ * Creates a squiggly (wavy underline) annotation
107
+ * @returns This builder for chaining
108
+ */
109
+ asSquiggly(): this {
110
+ this._type = 'squiggly';
111
+ return this;
112
+ }
113
+
114
+ /**
115
+ * Sets the annotation type
116
+ * @param type - Annotation type ('text', 'highlight', 'underline', 'strikeout', 'squiggly')
117
+ * @returns This builder for chaining
118
+ */
119
+ type(type: string): this {
120
+ const validTypes = ['text', 'highlight', 'underline', 'strikeout', 'squiggly', 'note'];
121
+ if (!validTypes.includes(type)) {
122
+ throw new Error(`Invalid annotation type. Must be one of: ${validTypes.join(', ')}`);
123
+ }
124
+ this._type = type;
125
+ return this;
126
+ }
127
+
128
+ /**
129
+ * Sets the annotation content/text
130
+ * @param content - The annotation content
131
+ * @returns This builder for chaining
132
+ */
133
+ content(content: string): this {
134
+ if (typeof content !== 'string') {
135
+ throw new Error('Content must be a string');
136
+ }
137
+ this._content = content;
138
+ return this;
139
+ }
140
+
141
+ /**
142
+ * Sets the author of the annotation
143
+ * @param author - The author name
144
+ * @returns This builder for chaining
145
+ */
146
+ author(author: string): this {
147
+ if (typeof author !== 'string') {
148
+ throw new Error('Author must be a string');
149
+ }
150
+ this._author = author.length > 0 ? author : undefined;
151
+ return this;
152
+ }
153
+
154
+ /**
155
+ * Sets the subject/title of the annotation
156
+ * @param subject - The annotation subject
157
+ * @returns This builder for chaining
158
+ */
159
+ subject(subject: string): this {
160
+ if (typeof subject !== 'string') {
161
+ throw new Error('Subject must be a string');
162
+ }
163
+ this._subject = subject.length > 0 ? subject : undefined;
164
+ return this;
165
+ }
166
+
167
+ /**
168
+ * Sets the color of the annotation (RGB, normalized 0-1)
169
+ * @param rgb - RGB color array [r, g, b] with values 0-1
170
+ * @returns This builder for chaining
171
+ *
172
+ * @example
173
+ * ```typescript
174
+ * builder.color([1, 1, 0]); // Yellow
175
+ * builder.color([1, 0, 0]); // Red
176
+ * builder.color([0, 1, 0]); // Green
177
+ * ```
178
+ */
179
+ color(rgb: number[]): this {
180
+ if (!Array.isArray(rgb) || rgb.length !== 3) {
181
+ throw new Error('Color must be an array of 3 RGB values [r, g, b]');
182
+ }
183
+ if (!rgb.every((c) => typeof c === 'number' && c >= 0 && c <= 1)) {
184
+ throw new Error('RGB values must be numbers between 0 and 1');
185
+ }
186
+ this._color = [...rgb];
187
+ return this;
188
+ }
189
+
190
+ /**
191
+ * Sets the color using common color names
192
+ * @param colorName - Color name (e.g., 'red', 'yellow', 'green', 'blue')
193
+ * @returns This builder for chaining
194
+ *
195
+ * @example
196
+ * ```typescript
197
+ * builder.colorName('yellow');
198
+ * builder.colorName('red');
199
+ * ```
200
+ */
201
+ colorName(colorName: string): this {
202
+ const colors: Record<string, number[]> = {
203
+ red: [1, 0, 0],
204
+ green: [0, 1, 0],
205
+ blue: [0, 0, 1],
206
+ yellow: [1, 1, 0],
207
+ cyan: [0, 1, 1],
208
+ magenta: [1, 0, 1],
209
+ white: [1, 1, 1],
210
+ black: [0, 0, 0],
211
+ gray: [0.5, 0.5, 0.5],
212
+ orange: [1, 0.5, 0],
213
+ purple: [0.5, 0, 0.5],
214
+ };
215
+
216
+ const lowerColorName = colorName.toLowerCase();
217
+ if (!colors[lowerColorName]) {
218
+ const available = Object.keys(colors).join(', ');
219
+ throw new Error(`Unknown color. Available colors: ${available}`);
220
+ }
221
+
222
+ this._color = [...colors[lowerColorName]];
223
+ return this;
224
+ }
225
+
226
+ /**
227
+ * Sets the opacity/transparency (0-1)
228
+ * @param opacity - Opacity value (0=transparent, 1=opaque)
229
+ * @returns This builder for chaining
230
+ */
231
+ opacity(opacity: number): this {
232
+ if (typeof opacity !== 'number' || opacity < 0 || opacity > 1) {
233
+ throw new Error('Opacity must be a number between 0 and 1');
234
+ }
235
+ this._opacity = opacity;
236
+ return this;
237
+ }
238
+
239
+ /**
240
+ * Sets the bounding box for the annotation
241
+ * @param bounds - Bounding box {x, y, width, height}
242
+ * @returns This builder for chaining
243
+ *
244
+ * @example
245
+ * ```typescript
246
+ * builder.bounds({x: 100, y: 200, width: 150, height: 30});
247
+ * ```
248
+ */
249
+ bounds(bounds: AnnotationBounds): this {
250
+ if (typeof bounds !== 'object' || bounds === null) {
251
+ throw new Error('Bounds must be an object');
252
+ }
253
+ const { x, y, width, height } = bounds;
254
+ if (![x, y, width, height].every((v) => typeof v === 'number' && v >= 0)) {
255
+ throw new Error('Bounds must have numeric x, y, width, height values >= 0');
256
+ }
257
+ this._bounds = { x, y, width, height };
258
+ return this;
259
+ }
260
+
261
+ /**
262
+ * Sets the creation date
263
+ * @param date - The creation date
264
+ * @returns This builder for chaining
265
+ */
266
+ creationDate(date: Date): this {
267
+ if (!(date instanceof Date)) {
268
+ throw new Error('creationDate must be a Date object');
269
+ }
270
+ this._creationDate = new Date(date);
271
+ return this;
272
+ }
273
+
274
+ /**
275
+ * Sets the modification date
276
+ * @param date - The modification date
277
+ * @returns This builder for chaining
278
+ */
279
+ modificationDate(date: Date): this {
280
+ if (!(date instanceof Date)) {
281
+ throw new Error('modificationDate must be a Date object');
282
+ }
283
+ this._modificationDate = new Date(date);
284
+ return this;
285
+ }
286
+
287
+ /**
288
+ * Sets the annotation to be printed
289
+ * @returns This builder for chaining
290
+ */
291
+ printable(): this {
292
+ this._flags |= 4; // Print flag
293
+ return this;
294
+ }
295
+
296
+ /**
297
+ * Sets the annotation to NOT be printed
298
+ * @returns This builder for chaining
299
+ */
300
+ notPrintable(): this {
301
+ this._flags &= ~4; // Clear print flag
302
+ return this;
303
+ }
304
+
305
+ /**
306
+ * Sets whether the annotation is locked (read-only)
307
+ * @param locked - Whether to lock the annotation
308
+ * @returns This builder for chaining
309
+ */
310
+ locked(locked: boolean): this {
311
+ if (typeof locked !== 'boolean') {
312
+ throw new Error('locked must be a boolean');
313
+ }
314
+ if (locked) {
315
+ this._flags |= 128; // Locked flag
316
+ } else {
317
+ this._flags &= ~128;
318
+ }
319
+ return this;
320
+ }
321
+
322
+ /**
323
+ * Sets a reply to this annotation
324
+ * @param replyContent - Content of the reply
325
+ * @returns This builder for chaining
326
+ */
327
+ reply(replyContent: string): this {
328
+ if (typeof replyContent !== 'string') {
329
+ throw new Error('Reply content must be a string');
330
+ }
331
+ this._reply = replyContent;
332
+ return this;
333
+ }
334
+
335
+ /**
336
+ * Builds and returns the annotation object
337
+ * @returns Immutable annotation object
338
+ */
339
+ build(): Annotation {
340
+ if (!this._bounds && this._type !== 'text') {
341
+ throw new Error(`Annotation type "${this._type}" requires bounds to be set`);
342
+ }
343
+
344
+ return {
345
+ type: this._type,
346
+ content: this._content,
347
+ author: this._author,
348
+ subject: this._subject,
349
+ color: [...this._color],
350
+ opacity: this._opacity,
351
+ bounds: this._bounds ? { ...this._bounds } : undefined,
352
+ creationDate: new Date(this._creationDate),
353
+ modificationDate: new Date(this._modificationDate),
354
+ flags: this._flags,
355
+ reply: this._reply,
356
+ };
357
+ }
358
+ }
359
+
360
+ /**
361
+ * Create a new AnnotationBuilder with static factory
362
+ * @deprecated Use AnnotationBuilder.create() instead
363
+ * @returns New builder instance
364
+ */
365
+ export function createAnnotationBuilder(): AnnotationBuilder {
366
+ return AnnotationBuilder.create();
367
+ }