pdfdancer-client-typescript 1.0.1

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 (52) hide show
  1. package/.eslintrc.js +19 -0
  2. package/README.md +267 -0
  3. package/dist/__tests__/e2e/test-helpers.d.ts +32 -0
  4. package/dist/__tests__/e2e/test-helpers.d.ts.map +1 -0
  5. package/dist/__tests__/e2e/test-helpers.js +157 -0
  6. package/dist/__tests__/e2e/test-helpers.js.map +1 -0
  7. package/dist/client-v1.d.ts +169 -0
  8. package/dist/client-v1.d.ts.map +1 -0
  9. package/dist/client-v1.js +558 -0
  10. package/dist/client-v1.js.map +1 -0
  11. package/dist/exceptions.d.ts +43 -0
  12. package/dist/exceptions.d.ts.map +1 -0
  13. package/dist/exceptions.js +66 -0
  14. package/dist/exceptions.js.map +1 -0
  15. package/dist/index.d.ts +13 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +33 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/models.d.ts +216 -0
  20. package/dist/models.d.ts.map +1 -0
  21. package/dist/models.js +427 -0
  22. package/dist/models.js.map +1 -0
  23. package/dist/paragraph-builder.d.ts +67 -0
  24. package/dist/paragraph-builder.d.ts.map +1 -0
  25. package/dist/paragraph-builder.js +160 -0
  26. package/dist/paragraph-builder.js.map +1 -0
  27. package/example.ts +103 -0
  28. package/fixtures/DancingScript-Regular.ttf +0 -0
  29. package/fixtures/JetBrainsMono-Regular.ttf +0 -0
  30. package/fixtures/ObviouslyAwesome.pdf +0 -0
  31. package/fixtures/README.md +25 -0
  32. package/fixtures/basic-paths.pdf +0 -0
  33. package/fixtures/logo-80.png +0 -0
  34. package/fixtures/mixed-form-types.pdf +0 -0
  35. package/jest.config.js +26 -0
  36. package/package.json +38 -0
  37. package/scripts/release.js +91 -0
  38. package/scripts/test-release.js +59 -0
  39. package/src/__tests__/client-v1.test.ts +111 -0
  40. package/src/__tests__/e2e/form.test.ts +51 -0
  41. package/src/__tests__/e2e/image.test.ts +108 -0
  42. package/src/__tests__/e2e/line.test.ts +134 -0
  43. package/src/__tests__/e2e/page.test.ts +45 -0
  44. package/src/__tests__/e2e/paragraph.test.ts +210 -0
  45. package/src/__tests__/e2e/path.test.ts +72 -0
  46. package/src/__tests__/e2e/test-helpers.ts +132 -0
  47. package/src/client-v1.ts +673 -0
  48. package/src/exceptions.ts +67 -0
  49. package/src/index.ts +34 -0
  50. package/src/models.ts +476 -0
  51. package/src/paragraph-builder.ts +184 -0
  52. package/tsconfig.json +20 -0
@@ -0,0 +1,673 @@
1
+ /**
2
+ * PDFDancer TypeScript Client V1
3
+ *
4
+ * A TypeScript client that closely mirrors the Python Client class structure and functionality.
5
+ * Provides session-based PDF manipulation operations with strict validation.
6
+ */
7
+
8
+ import {
9
+ PdfDancerException,
10
+ FontNotFoundException,
11
+ HttpClientException,
12
+ SessionException,
13
+ ValidationException
14
+ } from './exceptions';
15
+ import {
16
+ ObjectRef,
17
+ Position,
18
+ ObjectType,
19
+ Font,
20
+ Image,
21
+ Paragraph,
22
+ FindRequest,
23
+ DeleteRequest,
24
+ MoveRequest,
25
+ AddRequest,
26
+ ModifyRequest,
27
+ ModifyTextRequest,
28
+ ShapeType,
29
+ PositionMode,
30
+ BoundingRect
31
+ } from './models';
32
+ import { ParagraphBuilder } from './paragraph-builder';
33
+
34
+ /**
35
+ * REST API client for interacting with the PDFDancer PDF manipulation service.
36
+ * This client provides a convenient TypeScript interface for performing PDF operations
37
+ * including session management, object searching, manipulation, and retrieval.
38
+ * Handles authentication, session lifecycle, and HTTP communication transparently.
39
+ *
40
+ * Mirrors the Python Client class functionality exactly.
41
+ */
42
+ export class ClientV1 {
43
+ private _token: string;
44
+ private _baseUrl: string;
45
+ private _readTimeout: number;
46
+ private _pdfBytes: Uint8Array;
47
+ private _sessionId!: string;
48
+
49
+ /**
50
+ * Creates a new client with PDF data.
51
+ * This constructor initializes the client, uploads the PDF data to create
52
+ * a new session, and prepares the client for PDF manipulation operations.
53
+ */
54
+ constructor(
55
+ token: string,
56
+ pdfData: Uint8Array | File | ArrayBuffer,
57
+ baseUrl: string = "http://localhost:8080",
58
+ readTimeout: number = 30000
59
+ ) {
60
+ // Strict validation like Python client
61
+ if (!token || !token.trim()) {
62
+ throw new ValidationException("Authentication token cannot be null or empty");
63
+ }
64
+
65
+ this._token = token.trim();
66
+ this._baseUrl = baseUrl.replace(/\/$/, ''); // Remove trailing slash
67
+ this._readTimeout = readTimeout;
68
+
69
+ // Process PDF data with validation
70
+ this._pdfBytes = this._processPdfData(pdfData);
71
+ }
72
+
73
+ /**
74
+ * Initialize the client by creating a session.
75
+ * Must be called after constructor before using the client.
76
+ */
77
+ async init(): Promise<void> {
78
+ this._sessionId = await this._createSession();
79
+ }
80
+
81
+ /**
82
+ * Process PDF data from various input types with strict validation.
83
+ * Equivalent to readFile() method in Python client.
84
+ */
85
+ private _processPdfData(pdfData: Uint8Array | File | ArrayBuffer): Uint8Array {
86
+ if (!pdfData) {
87
+ throw new ValidationException("PDF data cannot be null");
88
+ }
89
+
90
+ try {
91
+ if (pdfData instanceof Uint8Array) {
92
+ if (pdfData.length === 0) {
93
+ throw new ValidationException("PDF data cannot be empty");
94
+ }
95
+ return pdfData;
96
+ } else if (pdfData instanceof ArrayBuffer) {
97
+ const uint8Array = new Uint8Array(pdfData);
98
+ if (uint8Array.length === 0) {
99
+ throw new ValidationException("PDF data cannot be empty");
100
+ }
101
+ return uint8Array;
102
+ } else if (pdfData instanceof File) {
103
+ // Note: File reading will be handled asynchronously in the session creation
104
+ return new Uint8Array(); // Placeholder, will be replaced in _createSession
105
+ } else {
106
+ throw new ValidationException(`Unsupported PDF data type: ${typeof pdfData}`);
107
+ }
108
+ } catch (error) {
109
+ if (error instanceof ValidationException) {
110
+ throw error;
111
+ }
112
+ throw new PdfDancerException(`Failed to process PDF data: ${error}`, error as Error);
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Extract meaningful error messages from API response.
118
+ * Parses JSON error responses with _embedded.errors structure.
119
+ */
120
+ private async _extractErrorMessage(response?: Response): Promise<string> {
121
+ if (!response) {
122
+ return "Unknown error";
123
+ }
124
+
125
+ try {
126
+ const errorData = await response.json() as any;
127
+
128
+ // Check for embedded errors structure
129
+ if (errorData._embedded?.errors) {
130
+ const errors = errorData._embedded.errors;
131
+ if (Array.isArray(errors)) {
132
+ const messages = errors
133
+ .filter(error => error.message)
134
+ .map(error => error.message);
135
+
136
+ if (messages.length > 0) {
137
+ return messages.join("; ");
138
+ }
139
+ }
140
+ }
141
+
142
+ // Check for top-level message
143
+ if (errorData.message) {
144
+ return errorData.message;
145
+ }
146
+
147
+ // Fallback to response text or status
148
+ return await response.text() || `HTTP ${response.status}`;
149
+ } catch {
150
+ // If JSON parsing fails, return response text or status
151
+ try {
152
+ return await response.text() || `HTTP ${response.status}`;
153
+ } catch {
154
+ return `HTTP ${response.status}`;
155
+ }
156
+ }
157
+ }
158
+
159
+ /**
160
+ * Creates a new PDF processing session by uploading the PDF data.
161
+ * Equivalent to createSession() method in Python client.
162
+ */
163
+ private async _createSession(): Promise<string> {
164
+ try {
165
+ const formData = new FormData();
166
+
167
+ // Handle File objects by reading their content
168
+ if (this._pdfBytes instanceof File) {
169
+ formData.append('pdf', this._pdfBytes, 'document.pdf');
170
+ } else {
171
+ const blob = new Blob([this._pdfBytes.buffer as ArrayBuffer], { type: 'application/pdf' });
172
+ formData.append('pdf', blob, 'document.pdf');
173
+ }
174
+
175
+ const response = await fetch(`${this._baseUrl}/session/create`, {
176
+ method: 'POST',
177
+ headers: {
178
+ 'Authorization': `Bearer ${this._token}`
179
+ },
180
+ body: formData,
181
+ signal: this._readTimeout > 0 ? AbortSignal.timeout(this._readTimeout) : undefined
182
+ });
183
+
184
+ if (!response.ok) {
185
+ const errorMessage = await this._extractErrorMessage(response);
186
+ throw new HttpClientException(`Failed to create session: ${errorMessage}`, response);
187
+ }
188
+
189
+ const sessionId = (await response.text()).trim();
190
+
191
+ if (!sessionId) {
192
+ throw new SessionException("Server returned empty session ID");
193
+ }
194
+
195
+ return sessionId;
196
+ } catch (error) {
197
+ if (error instanceof HttpClientException || error instanceof SessionException) {
198
+ throw error;
199
+ }
200
+ const errorMessage = error instanceof Error ? error.message : String(error);
201
+ throw new HttpClientException(`Failed to create session: ${errorMessage}`, undefined, error as Error);
202
+ }
203
+ }
204
+
205
+ /**
206
+ * Make HTTP request with session headers and error handling.
207
+ * Equivalent to retrieve() method pattern in Python client.
208
+ */
209
+ private async _makeRequest(
210
+ method: string,
211
+ path: string,
212
+ data?: Record<string, any>,
213
+ params?: Record<string, string>
214
+ ): Promise<Response> {
215
+ const url = new URL(`${this._baseUrl}${path}`);
216
+ if (params) {
217
+ Object.entries(params).forEach(([key, value]) => {
218
+ url.searchParams.append(key, value);
219
+ });
220
+ }
221
+
222
+ const headers: Record<string, string> = {
223
+ 'Authorization': `Bearer ${this._token}`,
224
+ 'X-Session-Id': this._sessionId,
225
+ 'Content-Type': 'application/json'
226
+ };
227
+
228
+ try {
229
+ const response = await fetch(url.toString(), {
230
+ method,
231
+ headers,
232
+ body: data ? JSON.stringify(data) : undefined,
233
+ signal: this._readTimeout > 0 ? AbortSignal.timeout(this._readTimeout) : undefined
234
+ });
235
+
236
+ // Handle FontNotFoundException specifically like Python client
237
+ if (response.status === 404) {
238
+ try {
239
+ const errorData = await response.json() as any;
240
+ if (errorData.error === 'FontNotFoundException') {
241
+ throw new FontNotFoundException(errorData.message || 'Font not found');
242
+ }
243
+ } catch (e) {
244
+ if (e instanceof FontNotFoundException) {
245
+ throw e;
246
+ }
247
+ // Continue with normal error handling if JSON parsing fails
248
+ }
249
+ }
250
+
251
+ if (!response.ok) {
252
+ const errorMessage = await this._extractErrorMessage(response);
253
+ throw new HttpClientException(`API request failed: ${errorMessage}`, response);
254
+ }
255
+
256
+ return response;
257
+ } catch (error) {
258
+ if (error instanceof FontNotFoundException || error instanceof HttpClientException) {
259
+ throw error;
260
+ }
261
+ const errorMessage = error instanceof Error ? error.message : String(error);
262
+ throw new HttpClientException(`API request failed: ${errorMessage}`, undefined, error as Error);
263
+ }
264
+ }
265
+
266
+ // Search Operations - matching Python client exactly
267
+
268
+ /**
269
+ * Searches for PDF objects matching the specified criteria.
270
+ * This method provides flexible search capabilities across all PDF content,
271
+ * allowing filtering by object type and position constraints.
272
+ */
273
+ async find(objectType?: ObjectType, position?: Position): Promise<ObjectRef[]> {
274
+ const requestData = new FindRequest(objectType, position).toDict();
275
+ const response = await this._makeRequest('POST', '/pdf/find', requestData);
276
+
277
+ const objectsData = await response.json() as any[];
278
+ return objectsData.map((objData: any) => this._parseObjectRef(objData));
279
+ }
280
+
281
+ /**
282
+ * Searches for paragraph objects at the specified position.
283
+ * Equivalent to findParagraphs() in Python client.
284
+ */
285
+ async findParagraphs(position?: Position): Promise<ObjectRef[]> {
286
+ return this.find(ObjectType.PARAGRAPH, position);
287
+ }
288
+
289
+ /**
290
+ * Searches for image objects at the specified position.
291
+ * Equivalent to findImages() in Python client.
292
+ */
293
+ async findImages(position?: Position): Promise<ObjectRef[]> {
294
+ return this.find(ObjectType.IMAGE, position);
295
+ }
296
+
297
+ /**
298
+ * Searches for form field objects at the specified position.
299
+ * Equivalent to findForms() in Python client.
300
+ */
301
+ async findForms(position?: Position): Promise<ObjectRef[]> {
302
+ return this.find(ObjectType.FORM, position);
303
+ }
304
+
305
+ /**
306
+ * Searches for vector path objects at the specified position.
307
+ * Equivalent to findPaths() in Python client.
308
+ */
309
+ async findPaths(position?: Position): Promise<ObjectRef[]> {
310
+ return this.find(ObjectType.PATH, position);
311
+ }
312
+
313
+ /**
314
+ * Searches for text line objects at the specified position.
315
+ * Equivalent to findTextLines() in Python client.
316
+ */
317
+ async findTextLines(position?: Position): Promise<ObjectRef[]> {
318
+ return this.find(ObjectType.TEXT_LINE, position);
319
+ }
320
+
321
+ // Page Operations
322
+
323
+ /**
324
+ * Retrieves references to all pages in the PDF document.
325
+ * Equivalent to getPages() in Python client.
326
+ */
327
+ async getPages(): Promise<ObjectRef[]> {
328
+ const response = await this._makeRequest('POST', '/pdf/page/find');
329
+ const pagesData = await response.json() as any[];
330
+ return pagesData.map((pageData: any) => this._parseObjectRef(pageData));
331
+ }
332
+
333
+ /**
334
+ * Retrieves a reference to a specific page by its page index.
335
+ * Equivalent to getPage() in Python client.
336
+ */
337
+ async getPage(pageIndex: number): Promise<ObjectRef | null> {
338
+ if (pageIndex < 0) {
339
+ throw new ValidationException(`Page index must be >= 0, got ${pageIndex}`);
340
+ }
341
+
342
+ const params = { pageIndex: pageIndex.toString() };
343
+ const response = await this._makeRequest('POST', '/pdf/page/find', undefined, params);
344
+
345
+ const pagesData = await response.json() as any[];
346
+ if (!pagesData || pagesData.length === 0) {
347
+ return null;
348
+ }
349
+
350
+ return this._parseObjectRef(pagesData[0]);
351
+ }
352
+
353
+ /**
354
+ * Deletes a page from the PDF document.
355
+ * Equivalent to deletePage() in Python client.
356
+ */
357
+ async deletePage(pageRef: ObjectRef): Promise<boolean> {
358
+ if (!pageRef) {
359
+ throw new ValidationException("Page reference cannot be null");
360
+ }
361
+
362
+ const requestData = pageRef.toDict();
363
+ const response = await this._makeRequest('DELETE', '/pdf/page/delete', requestData);
364
+ return await response.json() as boolean;
365
+ }
366
+
367
+ // Manipulation Operations
368
+
369
+ /**
370
+ * Deletes the specified PDF object from the document.
371
+ * Equivalent to delete() in Python client.
372
+ */
373
+ async delete(objectRef: ObjectRef): Promise<boolean> {
374
+ if (!objectRef) {
375
+ throw new ValidationException("Object reference cannot be null");
376
+ }
377
+
378
+ const requestData = new DeleteRequest(objectRef).toDict();
379
+ const response = await this._makeRequest('DELETE', '/pdf/delete', requestData);
380
+ return await response.json() as boolean;
381
+ }
382
+
383
+ /**
384
+ * Moves a PDF object to a new position within the document.
385
+ * Equivalent to move() in Python client.
386
+ */
387
+ async move(objectRef: ObjectRef, position: Position): Promise<boolean> {
388
+ if (!objectRef) {
389
+ throw new ValidationException("Object reference cannot be null");
390
+ }
391
+ if (!position) {
392
+ throw new ValidationException("Position cannot be null");
393
+ }
394
+
395
+ const requestData = new MoveRequest(objectRef, position).toDict();
396
+ const response = await this._makeRequest('PUT', '/pdf/move', requestData);
397
+ return await response.json() as boolean;
398
+ }
399
+
400
+ // Add Operations
401
+
402
+ /**
403
+ * Adds an image to the PDF document.
404
+ * Equivalent to addImage() methods in Python client.
405
+ */
406
+ async addImage(image: Image, position?: Position): Promise<boolean> {
407
+ if (!image) {
408
+ throw new ValidationException("Image cannot be null");
409
+ }
410
+
411
+ if (position) {
412
+ image.setPosition(position);
413
+ }
414
+
415
+ if (!image.getPosition()) {
416
+ throw new ValidationException("Image position is null");
417
+ }
418
+
419
+ return this._addObject(image);
420
+ }
421
+
422
+ /**
423
+ * Adds a paragraph to the PDF document.
424
+ * Equivalent to addParagraph() in Python client with validation.
425
+ */
426
+ async addParagraph(paragraph: Paragraph): Promise<boolean> {
427
+ if (!paragraph) {
428
+ throw new ValidationException("Paragraph cannot be null");
429
+ }
430
+ if (!paragraph.getPosition()) {
431
+ throw new ValidationException("Paragraph position is null");
432
+ }
433
+ if (paragraph.getPosition()!.pageIndex === undefined) {
434
+ throw new ValidationException("Paragraph position page index is null");
435
+ }
436
+ if (paragraph.getPosition()!.pageIndex! < 0) {
437
+ throw new ValidationException("Paragraph position page index is less than 0");
438
+ }
439
+
440
+ return this._addObject(paragraph);
441
+ }
442
+
443
+ /**
444
+ * Internal method to add any PDF object.
445
+ * Equivalent to addObject() in Python client.
446
+ */
447
+ private async _addObject(pdfObject: Image | Paragraph): Promise<boolean> {
448
+ const requestData = new AddRequest(pdfObject).toDict();
449
+ const response = await this._makeRequest('POST', '/pdf/add', requestData);
450
+ return await response.json() as boolean;
451
+ }
452
+
453
+ // Modify Operations
454
+
455
+ /**
456
+ * Modifies a paragraph object or its text content.
457
+ * Equivalent to modifyParagraph() methods in Python client.
458
+ */
459
+ async modifyParagraph(objectRef: ObjectRef, newParagraph: Paragraph | string): Promise<boolean> {
460
+ if (!objectRef) {
461
+ throw new ValidationException("Object reference cannot be null");
462
+ }
463
+ if (newParagraph === null || newParagraph === undefined) {
464
+ throw new ValidationException("New paragraph cannot be null");
465
+ }
466
+
467
+ if (typeof newParagraph === 'string') {
468
+ // Text modification
469
+ const requestData = new ModifyTextRequest(objectRef, newParagraph).toDict();
470
+ const response = await this._makeRequest('PUT', '/pdf/text/paragraph', requestData);
471
+ return await response.json() as boolean;
472
+ } else {
473
+ // Object modification
474
+ const requestData = new ModifyRequest(objectRef, newParagraph).toDict();
475
+ const response = await this._makeRequest('PUT', '/pdf/modify', requestData);
476
+ return await response.json() as boolean;
477
+ }
478
+ }
479
+
480
+ /**
481
+ * Modifies a text line object.
482
+ * Equivalent to modifyTextLine() in Python client.
483
+ */
484
+ async modifyTextLine(objectRef: ObjectRef, newText: string): Promise<boolean> {
485
+ if (!objectRef) {
486
+ throw new ValidationException("Object reference cannot be null");
487
+ }
488
+ if (newText === null || newText === undefined) {
489
+ throw new ValidationException("New text cannot be null");
490
+ }
491
+
492
+ const requestData = new ModifyTextRequest(objectRef, newText).toDict();
493
+ const response = await this._makeRequest('PUT', '/pdf/text/line', requestData);
494
+ return await response.json() as boolean;
495
+ }
496
+
497
+ // Font Operations
498
+
499
+ /**
500
+ * Finds available fonts matching the specified name and size.
501
+ * Equivalent to findFonts() in Python client.
502
+ */
503
+ async findFonts(fontName: string, fontSize: number): Promise<Font[]> {
504
+ if (!fontName || !fontName.trim()) {
505
+ throw new ValidationException("Font name cannot be null or empty");
506
+ }
507
+ if (fontSize <= 0) {
508
+ throw new ValidationException(`Font size must be positive, got ${fontSize}`);
509
+ }
510
+
511
+ const params = { fontName: fontName.trim() };
512
+ const response = await this._makeRequest('GET', '/font/find', undefined, params);
513
+
514
+ const fontNames = await response.json() as string[];
515
+ return fontNames.map((name: string) => new Font(name, fontSize));
516
+ }
517
+
518
+ /**
519
+ * Registers a custom font for use in PDF operations.
520
+ * Equivalent to registerFont() in Python client.
521
+ */
522
+ async registerFont(ttfFile: Uint8Array | File): Promise<string> {
523
+ if (!ttfFile) {
524
+ throw new ValidationException("TTF file cannot be null");
525
+ }
526
+
527
+ try {
528
+ let fontData: Uint8Array;
529
+ let filename: string;
530
+
531
+ if (ttfFile instanceof Uint8Array) {
532
+ if (ttfFile.length === 0) {
533
+ throw new ValidationException("Font data cannot be empty");
534
+ }
535
+ fontData = ttfFile;
536
+ filename = 'font.ttf';
537
+ } else if (ttfFile instanceof File) {
538
+ if (ttfFile.size === 0) {
539
+ throw new ValidationException("Font file is empty");
540
+ }
541
+ fontData = new Uint8Array(await ttfFile.arrayBuffer());
542
+ filename = ttfFile.name;
543
+ } else {
544
+ throw new ValidationException(`Unsupported font file type: ${typeof ttfFile}`);
545
+ }
546
+
547
+ // Upload font file
548
+ const formData = new FormData();
549
+ const blob = new Blob([fontData.buffer as ArrayBuffer], { type: 'font/ttf' });
550
+ formData.append('ttfFile', blob, filename);
551
+
552
+ const response = await fetch(`${this._baseUrl}/font/register`, {
553
+ method: 'POST',
554
+ headers: {
555
+ 'Authorization': `Bearer ${this._token}`,
556
+ 'X-Session-Id': this._sessionId
557
+ },
558
+ body: formData,
559
+ signal: AbortSignal.timeout(30000)
560
+ });
561
+
562
+ if (!response.ok) {
563
+ const errorMessage = await this._extractErrorMessage(response);
564
+ throw new HttpClientException(`Font registration failed: ${errorMessage}`, response);
565
+ }
566
+
567
+ return (await response.text()).trim();
568
+ } catch (error) {
569
+ if (error instanceof ValidationException || error instanceof HttpClientException) {
570
+ throw error;
571
+ }
572
+ const errorMessage = error instanceof Error ? error.message : String(error);
573
+ throw new PdfDancerException(`Failed to read font file: ${errorMessage}`, error as Error);
574
+ }
575
+ }
576
+
577
+ // Document Operations
578
+
579
+ /**
580
+ * Downloads the current state of the PDF document with all modifications applied.
581
+ * Equivalent to getPDFFile() in Python client.
582
+ */
583
+ async getPdfFile(): Promise<Uint8Array> {
584
+ const response = await this._makeRequest('GET', `/session/${this._sessionId}/pdf`);
585
+ return new Uint8Array(await response.arrayBuffer());
586
+ }
587
+
588
+ /**
589
+ * Saves the current PDF to a file (browser environment).
590
+ * Downloads the PDF in the browser.
591
+ */
592
+ async savePdf(filename: string = 'document.pdf'): Promise<void> {
593
+ if (!filename) {
594
+ throw new ValidationException("Filename cannot be null or empty");
595
+ }
596
+
597
+ try {
598
+ const pdfData = await this.getPdfFile();
599
+
600
+ // Create blob and download link
601
+ const blob = new Blob([pdfData.buffer as ArrayBuffer], { type: 'application/pdf' });
602
+ const url = URL.createObjectURL(blob);
603
+
604
+ const link = document.createElement('a');
605
+ link.href = url;
606
+ link.download = filename;
607
+ document.body.appendChild(link);
608
+ link.click();
609
+ document.body.removeChild(link);
610
+
611
+ URL.revokeObjectURL(url);
612
+ } catch (error) {
613
+ const errorMessage = error instanceof Error ? error.message : String(error);
614
+ throw new PdfDancerException(`Failed to save PDF file: ${errorMessage}`, error as Error);
615
+ }
616
+ }
617
+
618
+ // Utility Methods
619
+
620
+ /**
621
+ * Parse JSON object data into ObjectRef instance.
622
+ */
623
+ private _parseObjectRef(objData: any): ObjectRef {
624
+ const positionData = objData.position || {};
625
+ const position = positionData ? this._parsePosition(positionData) : new Position();
626
+
627
+ const objectType = ObjectType[objData.type as keyof typeof ObjectType];
628
+
629
+ return new ObjectRef(
630
+ objData.internalId,
631
+ position,
632
+ objectType
633
+ );
634
+ }
635
+
636
+ /**
637
+ * Parse JSON position data into Position instance.
638
+ */
639
+ private _parsePosition(posData: any): Position {
640
+ const position = new Position();
641
+ position.pageIndex = posData.pageIndex;
642
+ position.textStartsWith = posData.textStartsWith;
643
+
644
+ if (posData.shape) {
645
+ position.shape = ShapeType[posData.shape as keyof typeof ShapeType];
646
+ }
647
+ if (posData.mode) {
648
+ position.mode = PositionMode[posData.mode as keyof typeof PositionMode];
649
+ }
650
+
651
+ if (posData.boundingRect) {
652
+ const rectData = posData.boundingRect;
653
+ position.boundingRect = new BoundingRect(
654
+ rectData.x,
655
+ rectData.y,
656
+ rectData.width,
657
+ rectData.height
658
+ );
659
+ }
660
+
661
+ return position;
662
+ }
663
+
664
+ // Builder Pattern Support
665
+
666
+ /**
667
+ * Creates a new ParagraphBuilder for fluent paragraph construction.
668
+ * Equivalent to paragraphBuilder() in Python client.
669
+ */
670
+ paragraphBuilder(): ParagraphBuilder {
671
+ return new ParagraphBuilder(this);
672
+ }
673
+ }