-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
1781 lines (1453 loc) · 58.9 KB
/
client.py
File metadata and controls
1781 lines (1453 loc) · 58.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Main client for interacting with the Nutrient Document Web Services API."""
from collections.abc import Awaitable, Callable
from typing import TYPE_CHECKING, Any, Literal, cast
from nutrient_dws.builder.builder import StagedWorkflowBuilder
from nutrient_dws.builder.constant import BuildActions
from nutrient_dws.builder.staged_builders import (
ApplicableAction,
BufferOutput,
ContentOutput,
JsonContentOutput,
OutputFormat,
TypedWorkflowResult,
WorkflowInitialStage,
WorkflowWithPartsStage,
)
from nutrient_dws.errors import NutrientError, ValidationError
from nutrient_dws.http import (
NutrientClientOptions,
RedactRequestData,
RequestConfig,
SignRequestData,
SignRequestOptions,
send_request,
)
from nutrient_dws.inputs import (
FileInput,
get_pdf_page_count,
is_remote_file_input,
is_valid_pdf,
process_file_input,
process_remote_file_input,
)
from nutrient_dws.types.account_info import AccountInfo
from nutrient_dws.types.build_actions import (
ApplyXfdfActionOptions,
BaseCreateRedactionsOptions,
CreateRedactionsStrategyOptionsPreset,
CreateRedactionsStrategyOptionsRegex,
CreateRedactionsStrategyOptionsText,
ImageWatermarkActionOptions,
SearchPreset,
TextWatermarkActionOptions,
)
from nutrient_dws.types.build_output import (
JSONContentOutputOptions,
Label,
Metadata,
OptimizePdf,
PDFOutputOptions,
PDFUserPermission,
)
from nutrient_dws.types.create_auth_token import (
CreateAuthTokenParameters,
CreateAuthTokenResponse,
)
from nutrient_dws.types.misc import OcrLanguage, PageRange, Pages
from nutrient_dws.types.redact_data import RedactOptions
from nutrient_dws.types.sign_request import CreateDigitalSignature
if TYPE_CHECKING:
from nutrient_dws.types.input_parts import FilePartOptions
def normalize_page_params(
pages: PageRange | None = None,
page_count: int | None = None,
) -> Pages:
"""Normalize page parameters according to the requirements:
- start and end are inclusive
- start defaults to 0 (first page)
- end defaults to -1 (last page)
- negative end values loop from the end of the document.
Args:
pages: The page parameters to normalize
page_count: The total number of pages in the document (required for negative indices)
Returns:
Normalized page parameters
"""
start = pages.get("start", 0) if pages else 0
end = pages.get("end", -1) if pages else -1
# Handle negative end values if page_count is provided
if page_count is not None and start < 0:
start = page_count + start
if page_count is not None and end < 0:
end = page_count + end
return {"start": start, "end": end}
class NutrientClient:
"""Main client for interacting with the Nutrient Document Web Services API.
Example:
Server-side usage with an API key:
```python
client = NutrientClient(api_key='your_api_key')
```
Client-side usage with token provider:
```python
async def get_token():
# Your token retrieval logic here
return 'your-token'
client = NutrientClient(api_key=get_token)
```
"""
def __init__(
self,
api_key: str | Callable[[], str | Awaitable[str]],
base_url: str | None = None,
timeout: int | None = None,
) -> None:
"""Create a new NutrientClient instance.
Args:
api_key: API key or API key getter
base_url: DWS Base url
timeout: DWS request timeout
Raises:
ValidationError: If options are invalid
"""
options = NutrientClientOptions(
apiKey=api_key, baseUrl=base_url, timeout=timeout
)
self._validate_options(options)
self.options = options
def _validate_options(self, options: NutrientClientOptions) -> None:
"""Validate client options.
Args:
options: Configuration options to validate
Raises:
ValidationError: If options are invalid
"""
if not options:
raise ValidationError("Client options are required")
if not options.get("apiKey"):
raise ValidationError("API key is required")
api_key = options["apiKey"]
if not (isinstance(api_key, str) or callable(api_key)):
raise ValidationError(
"API key must be a string or a function that returns a string"
)
base_url = options.get("baseUrl")
if base_url is not None and not isinstance(base_url, str):
raise ValidationError("Base URL must be a string")
async def get_account_info(self) -> AccountInfo:
"""Get account information for the current API key.
Returns:
Account information
Example:
```python
account_info = await client.get_account_info()
print(account_info['subscriptionType'])
```
"""
response: Any = await send_request(
{
"method": "GET",
"endpoint": "/account/info",
"data": None,
"headers": None,
},
self.options,
)
return cast("AccountInfo", response["data"])
async def create_token(
self, params: CreateAuthTokenParameters
) -> CreateAuthTokenResponse:
"""Create a new authentication token.
Args:
params: Parameters for creating the token
Returns:
The created token information
Example:
```python
token = await client.create_token({
'allowedOperations': ['annotations_api'],
'expirationTime': 3600 # 1 hour
})
print(token['id'])
```
"""
response: Any = await send_request(
{
"method": "POST",
"endpoint": "/tokens",
"data": params,
"headers": None,
},
self.options,
)
return cast("CreateAuthTokenResponse", response["data"])
async def delete_token(self, token_id: str) -> None:
"""Delete an authentication token.
Args:
token_id: ID of the token to delete
Example:
```python
await client.delete_token('token-id-123')
```
"""
await send_request(
{
"method": "DELETE",
"endpoint": "/tokens",
"data": cast("Any", {"id": token_id}),
"headers": None,
},
self.options,
)
def workflow(self, override_timeout: int | None = None) -> WorkflowInitialStage:
r"""Create a new WorkflowBuilder for chaining multiple operations.
Args:
override_timeout: Set a custom timeout for the workflow (in milliseconds)
Returns:
A new WorkflowBuilder instance
Example:
```python
result = await client.workflow() \\
.add_file_part('document.docx') \\
.apply_action(BuildActions.ocr('english')) \\
.output_pdf() \\
.execute()
```
"""
options = self.options.copy()
if override_timeout is not None:
options["timeout"] = override_timeout
return StagedWorkflowBuilder(options)
def _process_typed_workflow_result(
self, result: TypedWorkflowResult
) -> BufferOutput | ContentOutput | JsonContentOutput:
"""Helper function that takes a TypedWorkflowResult, throws any errors, and returns the specific output type.
Args:
result: The TypedWorkflowResult to process
Returns:
The specific output type from the result
Raises:
NutrientError: If the workflow was not successful or if output is missing
"""
if not result["success"]:
# If there are errors, throw the first one
errors = result.get("errors")
if errors and len(errors) > 0:
raise errors[0]["error"]
# If no specific errors but operation failed
raise NutrientError(
"Workflow operation failed without specific error details",
"WORKFLOW_ERROR",
)
# Check if output exists
output = result.get("output")
if not output:
raise NutrientError(
"Workflow completed successfully but no output was returned",
"MISSING_OUTPUT",
)
return output
async def sign(
self,
pdf: FileInput,
data: CreateDigitalSignature | None = None,
options: SignRequestOptions | None = None,
) -> BufferOutput:
"""Sign a PDF document.
Args:
pdf: The PDF file to sign
data: Signature data
options: Additional options (image, graphicImage)
Returns:
The signed PDF file output
Example:
```python
result = await client.sign('document.pdf', {
'signatureType': 'cms',
'flatten': False,
'cadesLevel': 'b-lt'
})
# Access the signed PDF buffer
pdf_buffer = result['buffer']
# Get the MIME type of the output
print(result['mimeType']) # 'application/pdf'
# Save the buffer to a file
with open('signed-document.pdf', 'wb') as f:
f.write(pdf_buffer)
```
"""
# Normalize the file input
if is_remote_file_input(pdf):
normalized_file = await process_remote_file_input(str(pdf))
else:
normalized_file = await process_file_input(pdf)
if not is_valid_pdf(normalized_file[0]):
raise ValidationError("Invalid pdf file", {"input": pdf})
# Prepare optional files
normalized_image = None
normalized_graphic_image = None
if options:
if "image" in options:
image = options["image"]
if is_remote_file_input(image):
normalized_image = await process_remote_file_input(str(image))
else:
normalized_image = await process_file_input(image)
if "graphicImage" in options:
graphic_image = options["graphicImage"]
if is_remote_file_input(graphic_image):
normalized_graphic_image = await process_remote_file_input(
str(graphic_image)
)
else:
normalized_graphic_image = await process_file_input(graphic_image)
request_data = {
"file": normalized_file,
"data": data,
}
if normalized_image:
request_data["image"] = normalized_image
if normalized_graphic_image:
request_data["graphicImage"] = normalized_graphic_image
response: Any = await send_request(
{
"method": "POST",
"endpoint": "/sign",
"data": cast("SignRequestData", request_data),
"headers": None,
},
self.options,
)
buffer = response["data"]
return {
"mimeType": "application/pdf",
"filename": "output.pdf",
"buffer": buffer,
}
async def watermark_text(
self,
file: FileInput,
text: str,
options: TextWatermarkActionOptions | None = None,
) -> BufferOutput:
"""Add a text watermark to a document.
This is a convenience method that uses the workflow builder.
Args:
file: The input file to watermark
text: The watermark text
options: Watermark options
Returns:
The watermarked document
Example:
```python
result = await client.watermark_text('document.pdf', 'CONFIDENTIAL', {
'opacity': 0.5,
'fontSize': 24
})
# Access the watermarked PDF buffer
pdf_buffer = result['buffer']
# Save the buffer to a file
with open('watermarked-document.pdf', 'wb') as f:
f.write(pdf_buffer)
```
"""
watermark_action = BuildActions.watermark_text(text, options)
builder = self.workflow().add_file_part(file, None, [watermark_action])
result = await builder.output_pdf().execute()
return cast("BufferOutput", self._process_typed_workflow_result(result))
async def watermark_image(
self,
file: FileInput,
image: FileInput,
options: ImageWatermarkActionOptions | None = None,
) -> BufferOutput:
"""Add an image watermark to a document.
This is a convenience method that uses the workflow builder.
Args:
file: The input file to watermark
image: The watermark image. Can be a file path (string or Path),
bytes, file-like object, or a URL to a remote image.
options: Watermark options
Returns:
The watermarked document
Example:
```python
# Using a local file path
result = await client.watermark_image('document.pdf', 'watermark.png', {
'opacity': 0.5
})
# Using a Path object
from pathlib import Path
result = await client.watermark_image('document.pdf', Path('logo.png'))
# Using bytes (e.g., from a database or API)
with open('logo.png', 'rb') as f:
image_bytes = f.read()
result = await client.watermark_image('document.pdf', image_bytes)
# Using a remote URL
result = await client.watermark_image(
'document.pdf',
'https://example.com/logo.png'
)
# Access the watermarked PDF buffer
pdf_buffer = result['buffer']
```
"""
watermark_action = BuildActions.watermark_image(image, options)
builder = self.workflow().add_file_part(file, None, [watermark_action])
result = await builder.output_pdf().execute()
return cast("BufferOutput", self._process_typed_workflow_result(result))
async def convert(
self,
file: FileInput,
target_format: OutputFormat,
) -> BufferOutput | ContentOutput | JsonContentOutput:
"""Convert a document to a different format.
This is a convenience method that uses the workflow builder.
Args:
file: The input file to convert
target_format: The target format to convert to
Returns:
The specific output type based on the target format
Example:
```python
# Convert DOCX to PDF
pdf_result = await client.convert('document.docx', 'pdf')
pdf_buffer = pdf_result['buffer']
# Convert PDF to image
image_result = await client.convert('document.pdf', 'png')
png_buffer = image_result['buffer']
# Convert to HTML
html_result = await client.convert('document.pdf', 'html')
html_content = html_result['content']
```
"""
builder = self.workflow().add_file_part(file)
if target_format == "pdf":
result = await builder.output_pdf().execute()
elif target_format == "pdfa":
result = await builder.output_pdfa().execute()
elif target_format == "pdfua":
result = await builder.output_pdfua().execute()
elif target_format == "docx":
result = await builder.output_office("docx").execute()
elif target_format == "xlsx":
result = await builder.output_office("xlsx").execute()
elif target_format == "pptx":
result = await builder.output_office("pptx").execute()
elif target_format == "html":
result = await builder.output_html("page").execute()
elif target_format == "markdown":
result = await builder.output_markdown().execute()
elif target_format in ["png", "jpeg", "jpg", "webp"]:
result = await builder.output_image(
cast("Literal['png', 'jpeg', 'jpg', 'webp']", target_format),
{"dpi": 300},
).execute()
else:
raise ValidationError(f"Unsupported target format: {target_format}")
return self._process_typed_workflow_result(result)
async def ocr(
self,
file: FileInput,
language: OcrLanguage | list[OcrLanguage],
) -> BufferOutput:
"""Perform OCR (Optical Character Recognition) on a document.
This is a convenience method that uses the workflow builder.
Args:
file: The input file to perform OCR on
language: The language(s) to use for OCR. Can be a single language
or a list of languages for multi-language documents.
Returns:
The OCR result
Example:
```python
# Single language OCR
result = await client.ocr('scanned-document.pdf', 'english')
# Multi-language OCR for documents with mixed content
result = await client.ocr('multilang-document.pdf', ['english', 'german', 'french'])
# Access the OCR-processed PDF buffer
pdf_buffer = result['buffer']
```
"""
ocr_action = BuildActions.ocr(language)
builder = self.workflow().add_file_part(file, None, [ocr_action])
result = await builder.output_pdf().execute()
return cast("BufferOutput", self._process_typed_workflow_result(result))
async def extract_text(
self,
file: FileInput,
pages: PageRange | None = None,
) -> JsonContentOutput:
"""Extract text content from a document.
This is a convenience method that uses the workflow builder.
Args:
file: The file to extract text from
pages: Optional page range to extract text from
Returns:
The extracted text data
Example:
```python
result = await client.extract_text('document.pdf')
print(result['data'])
# Extract text from specific pages
result = await client.extract_text('document.pdf', {'start': 0, 'end': 2})
# Access the extracted text content
text_content = result['data']['pages'][0]['plainText']
```
"""
normalized_pages = normalize_page_params(pages) if pages else None
part_options = (
cast("FilePartOptions", {"pages": normalized_pages})
if normalized_pages
else None
)
result = (
await self.workflow()
.add_file_part(file, part_options)
.output_json(
cast("JSONContentOutputOptions", {"plainText": True, "tables": False})
)
.execute()
)
return cast("JsonContentOutput", self._process_typed_workflow_result(result))
async def extract_table(
self,
file: FileInput,
pages: PageRange | None = None,
) -> JsonContentOutput:
"""Extract table content from a document.
This is a convenience method that uses the workflow builder.
Args:
file: The file to extract table from
pages: Optional page range to extract tables from
Returns:
The extracted table data
Example:
```python
result = await client.extract_table('document.pdf')
# Access the extracted tables
tables = result['data']['pages'][0]['tables']
# Process the first table if available
if tables and len(tables) > 0:
first_table = tables[0]
print(f"Table has {len(first_table['rows'])} rows")
```
"""
normalized_pages = normalize_page_params(pages) if pages else None
part_options = (
cast("FilePartOptions", {"pages": normalized_pages})
if normalized_pages
else None
)
result = (
await self.workflow()
.add_file_part(file, part_options)
.output_json(
cast("JSONContentOutputOptions", {"plainText": False, "tables": True})
)
.execute()
)
return cast("JsonContentOutput", self._process_typed_workflow_result(result))
async def extract_key_value_pairs(
self,
file: FileInput,
pages: PageRange | None = None,
) -> JsonContentOutput:
"""Extract key value pair content from a document.
This is a convenience method that uses the workflow builder.
Args:
file: The file to extract KVPs from
pages: Optional page range to extract KVPs from
Returns:
The extracted KVPs data
Example:
```python
result = await client.extract_key_value_pairs('document.pdf')
# Access the extracted key-value pairs
kvps = result['data']['pages'][0]['keyValuePairs']
# Process the key-value pairs
if kvps and len(kvps) > 0:
for kvp in kvps:
print(f"Key: {kvp['key']}, Value: {kvp['value']}")
```
"""
normalized_pages = normalize_page_params(pages) if pages else None
part_options = (
cast("FilePartOptions", {"pages": normalized_pages})
if normalized_pages
else None
)
result = (
await self.workflow()
.add_file_part(file, part_options)
.output_json(
cast(
"JSONContentOutputOptions",
{"plainText": False, "tables": False, "keyValuePairs": True},
)
)
.execute()
)
return cast("JsonContentOutput", self._process_typed_workflow_result(result))
async def set_page_labels(
self,
pdf: FileInput,
labels: list[Label],
) -> BufferOutput:
"""Set page labels for a PDF document.
This is a convenience method that uses the workflow builder.
Args:
pdf: The PDF file to modify
labels: Array of label objects with pages and label properties
Returns:
The document with updated page labels
Example:
```python
result = await client.set_page_labels('document.pdf', [
{'pages': [0, 1, 2], 'label': 'Cover'},
{'pages': [3, 4, 5], 'label': 'Chapter 1'}
])
```
"""
# Validate PDF
if is_remote_file_input(pdf):
normalized_file = await process_remote_file_input(str(pdf))
else:
normalized_file = await process_file_input(pdf)
if not is_valid_pdf(normalized_file[0]):
raise ValidationError("Invalid pdf file", {"input": pdf})
result = (
await self.workflow()
.add_file_part(pdf)
.output_pdf(cast("PDFOutputOptions", {"labels": labels}))
.execute()
)
return cast("BufferOutput", self._process_typed_workflow_result(result))
async def password_protect(
self,
file: FileInput,
user_password: str,
owner_password: str,
permissions: list[PDFUserPermission] | None = None,
) -> BufferOutput:
"""Password protect a PDF document.
This is a convenience method that uses the workflow builder.
Args:
file: The file to protect
user_password: Password required to open the document
owner_password: Password required to modify the document
permissions: Optional array of permissions granted when opened with user password
Returns:
The password-protected document
Example:
```python
result = await client.password_protect('document.pdf', 'user123', 'owner456')
# Or with specific permissions:
result = await client.password_protect(
'document.pdf',
'user123',
'owner456',
['printing', 'extract_accessibility']
)
```
"""
pdf_options: PDFOutputOptions = {
"user_password": user_password,
"owner_password": owner_password,
}
if permissions:
pdf_options["user_permissions"] = permissions
result = (
await self.workflow().add_file_part(file).output_pdf(pdf_options).execute()
)
return cast("BufferOutput", self._process_typed_workflow_result(result))
async def set_metadata(
self,
pdf: FileInput,
metadata: Metadata,
) -> BufferOutput:
"""Set metadata for a PDF document.
This is a convenience method that uses the workflow builder.
Args:
pdf: The PDF file to modify
metadata: The metadata to set (title and/or author)
Returns:
The document with updated metadata
Example:
```python
result = await client.set_metadata('document.pdf', {
'title': 'My Document',
'author': 'John Doe'
})
```
"""
# Validate PDF
if is_remote_file_input(pdf):
normalized_file = await process_remote_file_input(str(pdf))
else:
normalized_file = await process_file_input(pdf)
if not is_valid_pdf(normalized_file[0]):
raise ValidationError("Invalid pdf file", {"input": pdf})
result = (
await self.workflow()
.add_file_part(pdf)
.output_pdf(cast("PDFOutputOptions", {"metadata": metadata}))
.execute()
)
return cast("BufferOutput", self._process_typed_workflow_result(result))
async def apply_instant_json(
self,
pdf: FileInput,
instant_json_file: FileInput,
) -> BufferOutput:
"""Apply Instant JSON to a document.
This is a convenience method that uses the workflow builder.
Args:
pdf: The PDF file to modify
instant_json_file: The Instant JSON file to apply
Returns:
The modified document
Example:
```python
result = await client.apply_instant_json('document.pdf', 'annotations.json')
```
"""
# Validate PDF
if is_remote_file_input(pdf):
normalized_file = await process_remote_file_input(str(pdf))
else:
normalized_file = await process_file_input(pdf)
if not is_valid_pdf(normalized_file[0]):
raise ValidationError("Invalid pdf file", {"input": pdf})
apply_json_action = BuildActions.apply_instant_json(instant_json_file)
result = (
await self.workflow()
.add_file_part(pdf, None, [apply_json_action])
.output_pdf()
.execute()
)
return cast("BufferOutput", self._process_typed_workflow_result(result))
async def apply_xfdf(
self,
pdf: FileInput,
xfdf_file: FileInput,
options: ApplyXfdfActionOptions | None = None,
) -> BufferOutput:
"""Apply XFDF to a document.
This is a convenience method that uses the workflow builder.
Args:
pdf: The PDF file to modify
xfdf_file: The XFDF file to apply
options: Optional settings for applying XFDF
Returns:
The modified document
Example:
```python
result = await client.apply_xfdf('document.pdf', 'annotations.xfdf')
# Or with options:
result = await client.apply_xfdf(
'document.pdf', 'annotations.xfdf',
{'ignorePageRotation': True, 'richTextEnabled': False}
)
```
"""
# Validate PDF
if is_remote_file_input(pdf):
normalized_file = await process_remote_file_input(str(pdf))
else:
normalized_file = await process_file_input(pdf)
if not is_valid_pdf(normalized_file[0]):
raise ValidationError("Invalid pdf file", {"input": pdf})
apply_xfdf_action = BuildActions.apply_xfdf(xfdf_file, options)
result = (
await self.workflow()
.add_file_part(pdf, None, [apply_xfdf_action])
.output_pdf()
.execute()
)
return cast("BufferOutput", self._process_typed_workflow_result(result))
async def merge(self, files: list[FileInput]) -> BufferOutput:
"""Merge multiple documents into a single document.
This is a convenience method that uses the workflow builder.
Args:
files: The files to merge
Returns:
The merged document
Example:
```python
result = await client.merge(['doc1.pdf', 'doc2.pdf', 'doc3.pdf'])
# Access the merged PDF buffer
pdf_buffer = result['buffer']
```
"""
if not files or len(files) < 2:
raise ValidationError("At least 2 files are required for merge operation")
builder = self.workflow()
# Add first file
workflow_builder = builder.add_file_part(files[0])
# Add remaining files
for file in files[1:]:
workflow_builder = workflow_builder.add_file_part(file)
result = await workflow_builder.output_pdf().execute()
return cast("BufferOutput", self._process_typed_workflow_result(result))
async def flatten(
self,
pdf: FileInput,
annotation_ids: list[str | int] | None = None,
) -> BufferOutput:
"""Flatten annotations in a PDF document.
This is a convenience method that uses the workflow builder.
Args:
pdf: The PDF file to flatten
annotation_ids: Optional list of specific annotation IDs to flatten.
If not provided, all annotations are flattened. IDs can be
strings or integers.
Returns:
The flattened document
Example:
```python
# Flatten all annotations
result = await client.flatten('annotated-document.pdf')
# Flatten specific annotations by string ID
result = await client.flatten('annotated-document.pdf', ['annotation1', 'annotation2'])
# Flatten specific annotations by integer ID
result = await client.flatten('annotated-document.pdf', [1, 2, 3])
# Mix of string and integer IDs
result = await client.flatten('annotated-document.pdf', ['note1', 2, 'highlight3'])
```
"""
# Validate PDF
if is_remote_file_input(pdf):