Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Nutrient DWS Python Client
https://github.com/pspdfkit/nutrient-dws-client-python
Admin
Python client library for Nutrient Document Web Services (DWS) API.
Tokens:
57,869
Snippets:
332
Trust Score:
9.9
License:
MIT
Update:
1 week ago
Context
Chat
Benchmark
87.5
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Set up development environment Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/README.md Clone the repository, install in development mode, and run type checking, linting, and formatting tools. ```bash # Clone the repository git clone https://github.com/PSPDFKit/nutrient-dws-client-python.git cd nutrient-dws-client-python # Install in development mode pip install -e ".[dev]" # Run type checking mypy src/ # Run linting ruff check src/ # Run formatting ruff format src/ ``` -------------------------------- ### output_image() usage examples Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Sets the output format to an image format. Examples show PNG with dpi, JPEG with dpi and page range, and WEBP with width, height, and dpi. At least one of width, height, or dpi must be specified. ```python # Set output format to PNG with dpi specified workflow.output_image('png', {'dpi': 300}) # Set output format to JPEG with specific options workflow.output_image('jpeg', { 'dpi': 300, 'pages': {'start': 1, 'end': 3} }) # Set output format to WEBP with specific dimensions workflow.output_image('webp', { 'width': 1200, 'height': 800, 'dpi': 150 }) ``` -------------------------------- ### output_office() usage examples Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Sets the output format to an Office document format. Examples show DOCX, XLSX, and PPTX formats. ```python # Set output format to Word document (DOCX) workflow.output_office('docx') # Set output format to Excel spreadsheet (XLSX) workflow.output_office('xlsx') # Set output format to PowerPoint presentation (PPTX) workflow.output_office('pptx') ``` -------------------------------- ### Install nutrient-dws with pip Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/README.md Install the Nutrient DWS Python client package using pip. ```bash pip install nutrient-dws ``` -------------------------------- ### Initialize NutrientClient with API key Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/README.md Create a NutrientClient instance with your API key. This is the starting point for all document processing operations. ```python from nutrient_dws import NutrientClient client = NutrientClient(api_key='your_api_key') ``` -------------------------------- ### apply_actions example Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Applies multiple actions to the workflow: watermark, OCR, and flatten. ```python # Apply multiple actions to the workflow workflow.apply_actions([ BuildActions.watermark_text('DRAFT', {'opacity': 0.5}), BuildActions.ocr('english'), BuildActions.flatten() ]) ``` -------------------------------- ### create_token() Example Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Creates a new authentication token with the given parameters. The response includes the token ID and access token. ```python token = await client.create_token({ 'expirationTime': 3600 }) print(token['id']) # Store the token for future use token_id = token['id'] token_value = token['accessToken'] ``` -------------------------------- ### output_pdf() usage examples Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Shows how to set the output format to PDF with default options and with specific options like user password, permissions, metadata, and optimization. ```python # Set output format to PDF with default options workflow.output_pdf() # Set output format to PDF with specific options workflow.output_pdf({ 'user_password': 'secret', 'user_permissions': ["printing"], 'metadata': { 'title': 'Important Document', 'author': 'Document System' }, 'optimize': { 'mrcCompression': True, 'imageOptimizationQuality': 3 } }) ``` -------------------------------- ### Quick start: client.parse() with spatial and markdown output Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/README.md Shows how to initialize NutrientClient with separate Processor and Extract API keys, then call parse() to get spatial elements (default) or whole-document Markdown. The Extract key is used only for parse(); other methods use the Processor key. Spatial output requires an OCR-capable mode; mode='text' is markdown-only. ```python import asyncio from nutrient_dws import NutrientClient async def main(): client = NutrientClient( api_key='your_processor_key', extract_api_key='your_extract_key', ) # Spatial elements (default) — paragraphs, tables, formulas, pictures, etc. response = await client.parse('contract.pdf', mode='understand') for element in response['output']['elements']: if element['type'] == 'table': print(element['rowCount'], element['columnCount']) # Whole-document Markdown from a born-digital PDF response = await client.parse( 'report.pdf', mode='text', output_format='markdown', ) print(response['output']['markdown']) asyncio.run(main()) ``` -------------------------------- ### output_pdfa() usage examples Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Shows how to set the output format to PDF/A with default options and with specific options like conformance level, vectorization, metadata, and optimization. ```python # Set output format to PDF/A with default options workflow.output_pdfa() # Set output format to PDF/A with specific options workflow.output_pdfa({ 'conformance': 'pdfa-2b', 'vectorization': True, 'metadata': { 'title': 'Archive Document', 'author': 'Document System' }, 'optimize': { 'mrcCompression': True } }) ``` -------------------------------- ### get_account_info() Example Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Retrieves account information for the current API key. The returned dictionary includes subscription information. ```python account_info = await client.get_account_info() # Access subscription information print(account_info['subscriptionType']) ``` -------------------------------- ### apply_action examples Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Shows two ways to call apply_action: applying a watermark action with opacity and rotation, and applying an OCR action. ```python # Apply a watermark action workflow.apply_action( BuildActions.watermark_text('CONFIDENTIAL', { 'opacity': 0.3, 'rotation': 45 }) ) # Apply an OCR action workflow.apply_action(BuildActions.ocr('english')) ``` -------------------------------- ### sign() Example Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Signs a PDF document with the given signature data. The result contains the signed PDF buffer and MIME type. ```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) ``` -------------------------------- ### add_html_part examples Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Shows two ways to call add_html_part: adding HTML content from a file, and adding HTML with assets (CSS, images) and options (layout size). ```python # Add HTML content from a file workflow.add_html_part('/path/to/content.html') # Add HTML with assets and options workflow.add_html_part( '/path/to/content.html', ['/path/to/style.css', '/path/to/image.png'], {'layout': {'size': 'A4'}} ) ``` -------------------------------- ### add_file_part examples Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Shows two ways to call add_file_part: adding a file from a local path, and adding a file with options (pages) and actions (watermark). ```python # Add a PDF file from a local path workflow.add_file_part('/path/to/document.pdf') # Add a file with options and actions workflow.add_file_part( '/path/to/document.pdf', {'pages': {'start': 1, 'end': 3}}, [BuildActions.watermark_text('CONFIDENTIAL')] ) ``` -------------------------------- ### Create redactions with preset pattern Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Creates redaction annotations using preset patterns like 'email-address' or 'credit-card-number'. The second example includes custom appearance and search options (start, limit). ```python # Create redactions for email addresses using preset workflow.apply_action(BuildActions.create_redactions_preset('email-address')) # Create redactions for credit card numbers with custom appearance workflow.apply_action(BuildActions.create_redactions_preset('credit-card-number', { 'content': { 'backgroundColor': '#000000', 'overlayText': 'FINANCIAL DATA' } }, { 'start': 0, 'limit': 5 } )) ``` -------------------------------- ### add_new_page examples Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Shows two ways to call add_new_page: adding a simple blank page, and adding a new page with specific options (A4 portrait). ```python # Add a simple blank page workflow.add_new_page() # Add a new page with specific options workflow.add_new_page({ 'layout': {'size': 'A4', 'orientation': 'portrait'} }) ``` -------------------------------- ### Use direct methods for document processing Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/README.md Example of using async methods to convert a document to PDF, extract text, add a watermark, and merge multiple documents. Requires an API key and the nutrient-dws package. ```python import asyncio from nutrient_dws import NutrientClient async def main(): client = NutrientClient(api_key='your_api_key') # Convert a document pdf_result = await client.convert('document.docx', 'pdf') # Extract text text_result = await client.extract_text('document.pdf') # Add a watermark watermarked_doc = await client.watermark_text('document.pdf', 'CONFIDENTIAL') # Merge multiple documents merged_pdf = await client.merge(['doc1.pdf', 'doc2.pdf', 'doc3.pdf']) asyncio.run(main()) ``` -------------------------------- ### delete_token() Example Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Deletes an authentication token by ID. Includes an example of a token management function that revokes a user token and handles errors. ```python await client.delete_token('token-id-123') # Example in a token management function async def revoke_user_token(token_id: str) -> bool: try: await client.delete_token(token_id) print(f'Token {token_id} successfully revoked') return True except Exception as error: print(f'Failed to revoke token: {error}') return False ``` -------------------------------- ### apply_instant_json: Apply Instant JSON and save output Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Applies an Instant JSON file to a PDF document. The example shows how to call the method and then access the resulting buffer, MIME type, and save the buffer to a file. ```python result = await client.apply_instant_json('document.pdf', 'annotations.json') # Access the modified 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('annotated-document.pdf', 'wb') as f: f.write(pdf_buffer) ``` -------------------------------- ### BuildActions.ocr() - OCR action examples Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Creates an OCR action to extract text from images or scanned documents. Accepts a single language string, a list of languages, or a dict with 'language' and 'enhanceResolution' options. ```python # Basic OCR with English language workflow.apply_action(BuildActions.ocr('english')) # OCR with multiple languages workflow.apply_action(BuildActions.ocr(['english', 'french', 'german'])) # OCR with options (via dict syntax) workflow.apply_action(BuildActions.ocr({ 'language': 'english', 'enhanceResolution': True })) ``` -------------------------------- ### Apply a single action to the workflow Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Applies a watermark action with opacity and font size to the workflow. This is the example for Stage 2. ```python workflow.apply_action(BuildActions.watermark_text('CONFIDENTIAL', { 'opacity': 0.5, 'fontSize': 48 })) ``` -------------------------------- ### output_html() usage example Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Sets the output format to HTML with the 'page' layout, which keeps the original document structure segmented by page. ```python # Set output format to HTML workflow.output_html('page') ``` -------------------------------- ### BuildActions.watermark_image() - Image watermark examples Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Creates an action to add an image watermark. The image parameter accepts a file path, bytes, or file-like object. Options include opacity, width, height, top, left, and rotation. ```python # Simple image watermark workflow.apply_action(BuildActions.watermark_image('/path/to/logo.png')) # Customized image watermark workflow.apply_action(BuildActions.watermark_image('/path/to/logo.png', { 'opacity': 0.3, 'width': {'value': 50, 'unit': '%'}, 'height': {'value': 50, 'unit': '%'}, 'top': {'value': 10, 'unit': 'px'}, 'left': {'value': 10, 'unit': 'px'}, 'rotation': 0 })) ``` -------------------------------- ### output_pdfua() usage examples Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Sets the output format to PDF/UA. The first call uses default options; the second passes metadata and optimization options including mrcCompression and imageOptimizationQuality. ```python # Set output format to PDF/UA with default options workflow.output_pdfua() # Set output format to PDF/UA with specific options workflow.output_pdfua({ 'metadata': { 'title': 'Accessible Document', 'author': 'Document System' }, 'optimize': { 'mrcCompression': True, 'imageOptimizationQuality': 3 } }) ``` -------------------------------- ### Apply annotations from XFDF file with default and custom options Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Creates an action to apply annotations from an XFDF file. The options parameter is optional and can include ignorePageRotation (default False) and richTextEnabled (default True). The example shows both default usage and custom options. ```python # Apply annotations from XFDF file with default options workflow.apply_action(BuildActions.apply_xfdf('/path/to/annotations.xfdf')) # Apply annotations with specific options workflow.apply_action(BuildActions.apply_xfdf('/path/to/annotations.xfdf', { 'ignorePageRotation': True, 'richTextEnabled': False })) ``` -------------------------------- ### BuildActions.watermark_text() - Text watermark examples Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Creates an action to add a text watermark. Options include opacity, rotation, fontSize, fontColor, and fontStyle. The default rotation is 0 and opacity ranges from 0 (transparent) to 1 (opaque). ```python # Simple text watermark workflow.apply_action(BuildActions.watermark_text('CONFIDENTIAL')) # Customized text watermark workflow.apply_action(BuildActions.watermark_text('DRAFT', { 'opacity': 0.5, 'rotation': 45, 'fontSize': 36, 'fontColor': '#FF0000', 'fontStyle': ['bold', 'italic'] })) ``` -------------------------------- ### BuildActions.rotate() - Rotate pages examples Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Creates an action to rotate pages by 90, 180, or 270 degrees. The rotate_by parameter must be one of these literal values. ```python # Rotate pages by 90 degrees workflow.apply_action(BuildActions.rotate(90)) # Rotate pages by 180 degrees workflow.apply_action(BuildActions.rotate(180)) ``` -------------------------------- ### add_document_part examples Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Shows two ways to call add_document_part: adding a document by ID, and adding a document with a specific layer and page range. ```python # Add a document by ID workflow.add_document_part('doc_12345abcde') # Add a document with a specific layer and options workflow.add_document_part( 'doc_12345abcde', { 'layer': 'content', 'pages': {'start': 0, 'end': 3} } ) ``` -------------------------------- ### Add file parts to a workflow Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Creates a workflow and adds two file parts ('document.pdf' and 'appendix.pdf') using method chaining. This is the initial example for Stage 1. ```python workflow = (client.workflow() .add_file_part('document.pdf') .add_file_part('appendix.pdf')) ``` -------------------------------- ### optimize: Optimize a PDF for size reduction Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Optimizes a PDF document for size reduction. Accepts an optional OptimizePdf options dictionary. The example enables grayscaleImages, mrcCompression, and imageOptimizationQuality 2, then saves the optimized buffer. ```python result = await client.optimize('large-document.pdf', { 'grayscaleImages': True, 'mrcCompression': True, 'imageOptimizationQuality': 2 }) # Access the optimized 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('optimized-document.pdf', 'wb') as f: f.write(pdf_buffer) ``` -------------------------------- ### create_redactions_preset: Create redactions with preset and save output Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Creates redaction annotations based on a preset pattern. The example shows three calls: default, with specific pages, and with the last three pages. It then accesses the resulting buffer, MIME type, and saves the buffer to a file. ```python result = await client.create_redactions_preset('document.pdf', 'email-address') # With specific pages result = await client.create_redactions_preset( 'document.pdf', 'email-address', 'stage', {'start': 0, 'end': 4} # Pages 0, 1, 2, 3, 4 ) # With the last 3 pages result = await client.create_redactions_preset( 'document.pdf', 'email-address', 'stage', {'start': -3, 'end': -1} # Last three pages ) # Access the document with redactions pdf_buffer = result['buffer'] # Get the MIME type of the output print(result['mimeType']) # 'application/pdf' # Save the buffer to a file with open('redacted-document.pdf', 'wb') as f: f.write(pdf_buffer) ``` -------------------------------- ### apply_xfdf: Apply XFDF with and without options Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Applies an XFDF file to a PDF document. The example shows two calls: one without options and one with options (ignorePageRotation and richTextEnabled). It then accesses the resulting buffer, MIME type, and saves the buffer to a file. ```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} ) # Access the modified 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('xfdf-applied-document.pdf', 'wb') as f: f.write(pdf_buffer) ``` -------------------------------- ### Extract key-value pairs with client.extract_key_value_pairs Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Calls client.extract_key_value_pairs with a file and optional page range. Shows how to access the returned key-value pairs, iterate over them, and build a dictionary for lookups. Page ranges can be specified with start and end indices, including negative indices for pages from the end. ```python result = await client.extract_key_value_pairs('document.pdf') # Extract KVPs from specific pages result = await client.extract_key_value_pairs('document.pdf', {'start': 0, 'end': 2}) # Pages 0, 1, 2 # Extract KVPs from the last page result = await client.extract_key_value_pairs('document.pdf', {'end': -1}) # Last page # Extract KVPs from the second-to-last page to the end result = await client.extract_key_value_pairs('document.pdf', {'start': -2}) # Second-to-last and last page # Access the extracted key-value pairs kvps = result['data']['pages'][0]['keyValuePairs'] # Process the key-value pairs if kvps and len(kvps) > 0: # Iterate through all key-value pairs for index, kvp in enumerate(kvps): print(f'KVP {index + 1}:') print(f' Key: {kvp["key"]}') print(f' Value: {kvp["value"]}') print(f' Confidence: {kvp["confidence"]}') # Create a dictionary from the key-value pairs dictionary = {} for kvp in kvps: dictionary[kvp['key']] = kvp['value'] # Look up specific values print(f'Invoice Number: {dictionary.get("Invoice Number")}') print(f'Date: {dictionary.get("Date")}') print(f'Total Amount: {dictionary.get("Total")}') ``` -------------------------------- ### Create redactions with regex pattern Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Creates redaction annotations for email addresses using a regex pattern. The first example uses default options, the second specifies custom appearance and search options (caseSensitive, start, limit). ```python # Create redactions for email addresses workflow.apply_action(BuildActions.create_redactions_regex(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}')) # Create redactions with custom appearance and search options workflow.apply_action(BuildActions.create_redactions_regex(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', { 'content': { 'backgroundColor': '#FF0000', 'overlayText': 'EMAIL REDACTED' } }, { 'caseSensitive': False, 'start': 0, 'limit': 10 } )) ``` -------------------------------- ### Create redactions for text with default and custom options Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Creates an action to add redaction annotations based on text search. The options parameter can specify visual aspects like backgroundColor, overlayText, and textColor. The strategy_options parameter can set caseSensitive, start, and limit. The example shows both default and custom usage. ```python # Create redactions for all occurrences of "Confidential" workflow.apply_action(BuildActions.create_redactions_text('Confidential')) # Create redactions with custom appearance and search options workflow.apply_action(BuildActions.create_redactions_text('Confidential', { 'content': { 'backgroundColor': '#000000', 'overlayText': 'REDACTED', 'textColor': '#FFFFFF' } }, { 'caseSensitive': True, 'start': 2, 'limit': 5 } )) ``` -------------------------------- ### split: Split a PDF into multiple parts by page ranges Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Splits a PDF into multiple documents based on page ranges. Accepts a list of PageRange dictionaries with start and end indices (0-based, negative allowed). Returns a list of BufferOutput objects. The example shows splitting into three parts and saving each. ```python results = await client.split('document.pdf', [ {'start': 0, 'end': 2}, # Pages 0, 1, 2 {'start': 3, 'end': 5} # Pages 3, 4, 5 ]) # Split using negative indices results = await client.split('document.pdf', [ {'start': 0, 'end': 2}, # First three pages {'start': 3, 'end': -3}, # Middle pages {'start': -2, 'end': -1} # Last two pages ]) # Process each resulting PDF for i, result in enumerate(results): # Access the 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(f'split-part-{i}.pdf', 'wb') as f: f.write(pdf_buffer) ``` -------------------------------- ### Project directory structure Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/README.md Shows the layout of the source and test directories, including the main client module and supporting packages. ```text src/ ├── nutrient_dws/ │ ├── builder/ # Builder classes and constants │ ├── generated/ # Generated type definitions │ ├── types/ # Type definitions │ ├── client.py # Main NutrientClient class │ ├── errors.py # Error classes │ ├── http.py # HTTP layer │ ├── inputs.py # Input handling │ ├── workflow.py # Workflow factory │ └── __init__.py # Public exports ├── nutrient_dws_scripts/ # CLI scripts for coding agents └── tests/ # Test files ``` -------------------------------- ### get_account_info() Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Gets account information for the current API key. Returns an AccountInfo dictionary containing subscription details. ```APIDOC ## get_account_info() ### Description Gets account information for the current API key. ### Method Async method ### Parameters None ### Request Example ```python account_info = await client.get_account_info() ``` ### Response #### Success Response - **AccountInfo** - Account information dictionary #### Response Example ```python print(account_info['subscriptionType']) ``` ``` -------------------------------- ### BuildActions.apply_instant_json(file) Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Creates an action to apply annotations from an Instant JSON file to the document. The file can be provided as a path, bytes, or file-like object. ```APIDOC ## BuildActions.apply_instant_json(file) ### Description Creates an action to apply annotations from an Instant JSON file to the document. ### Parameters - `file: FileInput` - Instant JSON file input (file path, bytes, or file-like object). ### Example ```python # Apply annotations from Instant JSON file workflow.apply_action(BuildActions.apply_instant_json('/path/to/annotations.json')) ``` ``` -------------------------------- ### Create a document processing workflow with NutrientClient Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/README.md Builds a workflow by adding file parts, applying a watermark action, setting PDF output options, and executing. Uses the fluent builder pattern with staged interfaces. Requires a valid API key. ```python from nutrient_dws.builder.constant import BuildActions async def main(): client = NutrientClient(api_key='your_api_key') result = await (client .workflow() .add_file_part('document.pdf') .add_file_part('appendix.pdf') .apply_action(BuildActions.watermark_text('CONFIDENTIAL', { 'opacity': 0.5, 'fontSize': 48 })) .output_pdf({ 'optimize': { 'mrcCompression': True, 'imageOptimizationQuality': 2 } }) .execute()) asyncio.run(main()) ``` -------------------------------- ### output_image(format, options?) Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Sets the output format to an image format (PNG, JPEG, WEBP). Accepts the format and optional options for pages, width, height, and dpi. Returns the workflow builder for chaining. ```APIDOC ## output_image(format, options?) ### Description Sets the output format to an image format (PNG, JPEG, WEBP). ### Method output_image ### Parameters - `format: Literal['png', 'jpeg', 'jpg', 'webp']` - The image format to output. - PNG: Lossless compression, supports transparency, best for graphics and screenshots - JPEG/JPG: Lossy compression, smaller file size, best for photographs - WEBP: Modern format with both lossy and lossless compression, good for web use - `options: dict[str, Any] | None` - Additional options for image output, such as resolution, quality, etc. (optional) **Note: At least one of options['width'], options['height'], or options['dpi'] must be specified.** - `options['pages']: dict[str, int]` - Specifies which pages to convert to images. If omitted, all pages are converted. - `options['pages']['start']: int` - The first page to convert (0-based index). - `options['pages']['end']: int` - The last page to convert (0-based index). - `options['width']: int` - The width of the output image in pixels. If specified without height, aspect ratio is maintained. - `options['height']: int` - The height of the output image in pixels. If specified without width, aspect ratio is maintained. - `options['dpi']: int` - The resolution in dots per inch. Higher values create larger, more detailed images. Common values: 72 (web), 150 (standard), 300 (print quality), 600 (high quality). ### Returns `WorkflowWithOutputStage` - The workflow builder instance for method chaining. ### Example ```python # Set output format to PNG with dpi specified workflow.output_image('png', {'dpi': 300}) # Set output format to JPEG with specific options workflow.output_image('jpeg', { 'dpi': 300, 'pages': {'start': 1, 'end': 3} }) # Set output format to WEBP with specific dimensions workflow.output_image('webp', { 'width': 1200, 'height': 800, 'dpi': 150 }) ``` ``` -------------------------------- ### Set output format to Markdown with output_markdown() Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Sets the output format to Markdown with default options. Returns the workflow builder instance for method chaining. ```python # Set output format to Markdown with default options workflow.output_markdown() ``` -------------------------------- ### Convert documents with client.convert (DOCX to PDF and PDF to PNG) Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Shows two conversions: DOCX to PDF and PDF to PNG, each accessing the buffer and MIME type, and saving the output file. The comment lists supported formats. ```python # Convert DOCX to PDF pdf_result = await client.convert('document.docx', 'pdf') # Supports formats: pdf, pdfa, pdfua, docx, xlsx, pptx, png, jpeg, jpg, webp, html, markdown # Access the PDF buffer pdf_buffer = pdf_result['buffer'] print(pdf_result['mimeType']) # 'application/pdf' # Save the PDF with open('converted-document.pdf', 'wb') as f: f.write(pdf_buffer) # Convert PDF to image image_result = await client.convert('document.pdf', 'png') # Access the PNG buffer png_buffer = image_result['buffer'] print(image_result['mimeType']) # 'image/png' # Save the image with open('document-page.png', 'wb') as f: f.write(png_buffer) ``` -------------------------------- ### Create a workflow from a client and override timeout Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Shows three ways to create a workflow: from a client with default settings, from a client with a custom timeout in milliseconds, and directly using StagedWorkflowBuilder with an API key. ```python # Creating Workflow from a client workflow = client.workflow() # Override the client timeout workflow = client.workflow(60000) # Create a workflow without a client from nutrient_dws.builder.builder import StagedWorkflowBuilder workflow = StagedWorkflowBuilder({ 'apiKey': 'your-api-key' }) ``` -------------------------------- ### apply_redactions - Apply staged redactions Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Applies redaction annotations that were previously staged. The example shows staging redactions with create_redactions_text, then applying them with apply_redactions, and saving the final redacted document. ```python # Stage redactions from a createRedaction Method: staged_result = await client.create_redactions_text( 'document.pdf', 'email@example.com', 'stage' ) result = await client.apply_redactions(staged_result['buffer']) # Access the final redacted document pdf_buffer = result['buffer'] # Get the MIME type of the output print(result['mimeType']) # 'application/pdf' # Save the buffer to a file with open('final-redacted-document.pdf', 'wb') as f: f.write(pdf_buffer) ``` -------------------------------- ### Apply annotations from Instant JSON file Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Creates an action to apply annotations from an Instant JSON file. The file parameter accepts a file path, bytes, or file-like object. The action is passed to workflow.apply_action. ```python # Apply annotations from Instant JSON file workflow.apply_action(BuildActions.apply_instant_json('/path/to/annotations.json')) ``` -------------------------------- ### create_redactions_ai() Examples Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Uses AI to redact sensitive information. Shows staging, applying, and page range options. The result contains the redacted PDF buffer and MIME type. ```python # Stage redactions result = await client.create_redactions_ai( 'document.pdf', 'Remove all emails' ) # Apply redactions immediately result = await client.create_redactions_ai( 'document.pdf', 'Remove all PII', 'apply' ) # Redact only specific pages result = await client.create_redactions_ai( 'document.pdf', 'Remove all emails', 'stage', {'start': 0, 'end': 4} # Pages 0, 1, 2, 3, 4 ) # Redact only the last 3 pages result = await client.create_redactions_ai( 'document.pdf', 'Remove all PII', 'stage', {'start': -3, 'end': -1} # Last three pages ) # Access the redacted 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('redacted-document.pdf', 'wb') as f: f.write(pdf_buffer) ``` -------------------------------- ### apply_instant_json(file, instant_json_file) Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Applies Instant JSON to a document. Returns the modified document as a BufferOutput. ```APIDOC ## apply_instant_json(file, instant_json_file) ### Description Applies Instant JSON to a document. ### Method apply_instant_json ### Parameters - `file: FileInput` - The PDF file to modify - `instant_json_file: FileInput` - The Instant JSON file to apply ### Returns `BufferOutput` - The modified document ### Request Example ```python result = await client.apply_instant_json('document.pdf', 'annotations.json') # Access the modified 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('annotated-document.pdf', 'wb') as f: f.write(pdf_buffer) ``` ``` -------------------------------- ### BuildActions.flatten() - Flatten annotations examples Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Creates an action to flatten annotations into the document content, making them non-interactive but permanently visible. Optionally accepts a list of annotation IDs; if omitted, all annotations are flattened. ```python # Flatten all annotations workflow.apply_action(BuildActions.flatten()) # Flatten specific annotations workflow.apply_action(BuildActions.flatten(['annotation1', 'annotation2'])) ``` -------------------------------- ### execute(options?) Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Executes the workflow and returns the result. Accepts an optional progress callback. ```APIDOC ## execute(options?) ### Description Executes the workflow and returns the result. ### Method execute(options?) ### Parameters #### Optional Parameters - `on_progress: Callable[[int, int], None] | None` - Callback for progress updates (optional). ### Returns `TypedWorkflowResult` - The workflow result. ### Example ```python # Execute the workflow with default options result = await workflow.execute() # Execute with progress tracking def progress_callback(current: int, total: int) -> None: print(f'Processing step {current} of {total}') result = await workflow.execute(on_progress=progress_callback) ``` ``` -------------------------------- ### set_page_labels: Set page labels and save output Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Sets page labels for a PDF document. The example shows how to call the method and then access the resulting buffer, MIME type, and save the buffer to a file. ```python result = await client.set_page_labels('document.pdf', [ {'pages': [0, 1, 2], 'label': 'Cover'}, {'pages': [3, 4, 5], 'label': 'Chapter 1'} ]) # Access the updated 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('labeled-document.pdf', 'wb') as f: f.write(pdf_buffer) ``` -------------------------------- ### NutrientClient(api_key, base_url?, timeout?) Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Constructor for the main client used to interact with the Nutrient DWS Processor API. Accepts an API key or an async token provider function, with optional custom base URL and timeout. ```APIDOC ## NutrientClient(api_key, base_url?, timeout?) ### Description Creates a new NutrientClient instance for interacting with the Nutrient DWS Processor API. ### Method Constructor ### Parameters - `api_key` (str | Callable[[], Awaitable[str] | str]) - Required - Your API key string or async function returning a token - `base_url` (str | None) - Optional - Custom API base URL (defaults to `https://api.nutrient.io`) - `timeout` (int | None) - Optional - Request timeout in milliseconds ### Request Example ```python from nutrient_dws import NutrientClient client = NutrientClient(api_key='your_api_key') ``` ### Response Returns a `NutrientClient` instance. ``` -------------------------------- ### split(file, page_ranges) Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Splits a PDF document into multiple parts based on page ranges. Each page range is specified as a dictionary with start and end indices, and the method returns a list of PDF documents. ```APIDOC ## split(file, page_ranges) ### Description Splits a PDF document into multiple parts based on page ranges. Each page range is specified as a dictionary with start and end indices, and the method returns a list of PDF documents. ### Method SDK Method ### Endpoint client.split(file, page_ranges) ### Parameters - `file: FileInput` - Required - The PDF file to split. - `page_ranges: list[PageRange]` - Required - List of page ranges to extract. Each range is a dict with `start` and `end` keys (0-based, negative indices count from end). ### Returns `list[BufferOutput]` - A list of PDF documents, one for each page range. ### Request Example ```python results = await client.split('document.pdf', [ {'start': 0, 'end': 2}, # Pages 0, 1, 2 {'start': 3, 'end': 5} # Pages 3, 4, 5 ]) # Split using negative indices results = await client.split('document.pdf', [ {'start': 0, 'end': 2}, # First three pages {'start': 3, 'end': -3}, # Middle pages {'start': -2, 'end': -1} # Last two pages ]) ``` ### Response Example ```python # Process each resulting PDF for i, result in enumerate(results): # Access the 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(f'split-part-{i}.pdf', 'wb') as f: f.write(pdf_buffer) ``` ``` -------------------------------- ### output_pdf(options?) Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Sets the output format to PDF. Accepts an optional dictionary of options for PDF output, such as encryption, metadata, and optimization. Returns the workflow builder instance for method chaining. ```APIDOC ## output_pdf(options?) ### Description Sets the output format to PDF. Accepts an optional dictionary of options for PDF output, such as encryption, metadata, and optimization. Returns the workflow builder instance for method chaining. ### Method output_pdf ### Parameters - `options: dict[str, Any] | None` (optional) - Additional options for PDF output. - `options['metadata']: dict[str, Any]` - Document metadata properties like title, author. - `options['labels']: list[dict[str, Any]]` - Custom labels to add to the document for organization and categorization. - `options['user_password']: str` - Password required to open the document. When set, the PDF will be encrypted. - `options['owner_password']: str` - Password required to modify the document. Provides additional security beyond the user password. - `options['user_permissions']: list[str]` - List of permissions granted to users who open the document with the user password. Options include: "printing", "modification", "content-copying", "annotation", "form-filling", etc. - `options['optimize']: dict[str, Any]` - PDF optimization settings to reduce file size and improve performance. - `options['optimize']['mrcCompression']: bool` - When True, applies Mixed Raster Content compression to reduce file size. - `options['optimize']['imageOptimizationQuality']: int` - Controls the quality of image optimization (1-5, where 1 is highest quality). ### Returns `WorkflowWithOutputStage` - The workflow builder instance for method chaining. ### Example ```python # Set output format to PDF with default options workflow.output_pdf() # Set output format to PDF with specific options workflow.output_pdf({ 'user_password': 'secret', 'user_permissions': ["printing"], 'metadata': { 'title': 'Important Document', 'author': 'Document System' }, 'optimize': { 'mrcCompression': True, 'imageOptimizationQuality': 3 } }) ``` ``` -------------------------------- ### output_pdfua(options?) Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Sets the output format to PDF/UA (Universal Accessibility). Accepts optional dictionary for metadata, labels, passwords, permissions, and optimization settings. Returns the workflow builder for chaining. ```APIDOC ## output_pdfua(options?) ### Description Sets the output format to PDF/UA (Universal Accessibility). ### Method output_pdfua ### Parameters - `options: dict[str, Any] | None` - Additional options for PDF/UA output (optional): - `options['metadata']: dict[str, Any]` - Document metadata properties like title, author. - `options['labels']: list[dict[str, Any]]` - Custom labels to add to the document for organization and categorization. - `options['user_password']: str` - Password required to open the document. When set, the PDF will be encrypted. - `options['owner_password']: str` - Password required to modify the document. Provides additional security beyond the user password. - `options['user_permissions']: list[str]` - List of permissions granted to users who open the document with the user password. Options include: "printing", "modification", "content-copying", "annotation", "form-filling", etc. - `options['optimize']: dict[str, Any]` - PDF optimization settings to reduce file size and improve performance. - `options['optimize']['mrcCompression']: bool` - When True, applies Mixed Raster Content compression to reduce file size. - `options['optimize']['imageOptimizationQuality']: int` - Controls the quality of image optimization (1-5, where 1 is highest quality). ### Returns `WorkflowWithOutputStage` - The workflow builder instance for method chaining. ### Example ```python # Set output format to PDF/UA with default options workflow.output_pdfua() # Set output format to PDF/UA with specific options workflow.output_pdfua({ 'metadata': { 'title': 'Accessible Document', 'author': 'Document System' }, 'optimize': { 'mrcCompression': True, 'imageOptimizationQuality': 3 } }) ``` ``` -------------------------------- ### create_token(params) Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Creates a new authentication token. Accepts parameters for token creation and returns the created token information. ```APIDOC ## create_token(params) ### Description Creates a new authentication token. ### Method Async method ### Parameters - `params` (CreateAuthTokenParameters) - Required - Parameters for creating the token ### Request Example ```python token = await client.create_token({ 'expirationTime': 3600 }) ``` ### Response #### Success Response - **CreateAuthTokenResponse** - The created token information #### Response Example ```python print(token['id']) token_id = token['id'] token_value = token['accessToken'] ``` ``` -------------------------------- ### NutrientClient Constructor Signature Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Shows the constructor signature for NutrientClient. The api_key can be a string or an async callable returning a string. base_url defaults to 'https://api.nutrient.io' and timeout is in milliseconds. ```python NutrientClient(api_key: str | Callable[[], Awaitable[str] | str], base_url: str | None = None, timeout: int | None = None) ``` -------------------------------- ### output_office(format) Source: https://github.com/pspdfkit/nutrient-dws-client-python/blob/main/src/nutrient_dws_scripts/LLM_DOC.md Sets the output format to an Office document format (DOCX, XLSX, PPTX). Accepts the format and returns the workflow builder for chaining. ```APIDOC ## output_office(format) ### Description Sets the output format to an Office document format (DOCX, XLSX, PPTX). ### Method output_office ### Parameters - `format: Literal['docx', 'xlsx', 'pptx']` - The Office format to output ('docx' for Word, 'xlsx' for Excel, or 'pptx' for PowerPoint). ### Returns `WorkflowWithOutputStage` - The workflow builder instance for method chaining. ### Example ```python # Set output format to Word document (DOCX) workflow.output_office('docx') # Set output format to Excel spreadsheet (XLSX) workflow.output_office('xlsx') # Set output format to PowerPoint presentation (PPTX) workflow.output_office('pptx') ``` ```