======================== CODE SNIPPETS ======================== TITLE: Initialize NutrientClient with API Key DESCRIPTION: Demonstrates how to create an instance of the NutrientClient by providing a direct API key for authentication. This is a straightforward method for initial setup. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_0 LANGUAGE: typescript CODE: ``` const client = new NutrientClient({ apiKey: 'nutr_sk_your_secret_key' }); ``` ---------------------------------------- TITLE: Basic Document Conversion (DOCX to PDF) DESCRIPTION: A simple workflow example demonstrating the conversion of a DOCX file to PDF format. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_58 LANGUAGE: typescript CODE: ``` const result = await client .workflow() .addFilePart('document.docx') .outputPdf() .execute(); ``` ---------------------------------------- TITLE: HTML to PDF Conversion DESCRIPTION: Example of converting an HTML file to PDF, with options to configure page layout, margins, and size. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_61 LANGUAGE: typescript CODE: ``` const result = await client .workflow() .addHtmlPart('index.html', undefined, { layout: { size: 'A4', margin: { top: 50, bottom: 50, left: 50, right: 50 } } }) .outputPdf() .execute(); ``` ---------------------------------------- TITLE: Convert Document Format DESCRIPTION: Provides examples of using the `convert` method to change a document's format, such as converting DOCX to PDF and PDF to PNG. It illustrates accessing the converted buffer and MIME type. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_12 LANGUAGE: typescript CODE: ``` // Convert DOCX to PDF const pdfResult = await client.convert('document.docx', 'pdf'); // Supports formats: pdf, pdfa, pdfua, docx, xlsx, pptx, png, jpeg, jpg, webp, html, markdown // Access the PDF buffer const pdfBuffer = pdfResult.buffer; console.log(pdfResult.mimeType); // 'application/pdf' // Save the PDF (Node.js example) const fs = require('fs'); fs.writeFileSync('converted-document.pdf', Buffer.from(pdfResult.buffer)); // Convert PDF to image const imageResult = await client.convert('document.pdf', 'png'); // Access the PNG buffer const pngBuffer = imageResult.buffer; console.log(imageResult.mimeType); // 'image/png' // Save the image (Node.js example) fs.writeFileSync('document-page.png', Buffer.from(imageResult.buffer)); ``` ---------------------------------------- TITLE: Merge Multiple Documents DESCRIPTION: Demonstrates how to merge several documents into a single file using the `merge` method. The example shows passing an array of file inputs and accessing the resulting merged document buffer. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_13 LANGUAGE: typescript CODE: ``` const result = await client.merge([ 'doc1.pdf', 'doc2.pdf', 'doc3.pdf' ]); // Access the merged PDF buffer const pdfBuffer = result.buffer; // Get the MIME type of the output console.log(result.mimeType); // 'application/pdf' // Save the buffer to a file (Node.js example) const fs = require('fs'); fs.writeFileSync('merged-document.pdf', Buffer.from(result.buffer)); ``` ---------------------------------------- TITLE: Get Account Information DESCRIPTION: Retrieves account information associated with the current API key. The returned promise resolves to an AccountInfo object containing details like organization and subscription type. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_3 LANGUAGE: typescript CODE: ``` const accountInfo = await client.getAccountInfo(); console.log(accountInfo.organization); // Access subscription information console.log(accountInfo.subscriptionType); ``` ---------------------------------------- TITLE: Document Merging with Watermark DESCRIPTION: Example of merging multiple PDF documents and applying a text watermark to the combined output. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_59 LANGUAGE: typescript CODE: ``` const result = await client .workflow() .addFilePart('document1.pdf') .addFilePart('document2.pdf') .applyAction(BuildActions.watermarkText('CONFIDENTIAL', { opacity: 0.5, fontSize: 48 })) .outputPdf() .execute(); ``` ---------------------------------------- TITLE: Add Text Watermark to a Document DESCRIPTION: Illustrates adding a text watermark to a document using the `watermarkText` method. Includes examples of setting watermark options like opacity and font size, and saving the result. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_10 LANGUAGE: typescript CODE: ``` const result = await client.watermarkText('document.pdf', 'CONFIDENTIAL', { opacity: 0.5, fontSize: 24 }); // Access the watermarked PDF buffer const pdfBuffer = result.buffer; // Get the MIME type of the output console.log(result.mimeType); // 'application/pdf' // Save the buffer to a file (Node.js example) const fs = require('fs'); fs.writeFileSync('watermarked-document.pdf', Buffer.from(result.buffer)); ``` ---------------------------------------- TITLE: Create PSPDFKit Workflow DESCRIPTION: Demonstrates different methods for creating a workflow instance, either by using an existing client or by instantiating the builder directly with an API key. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_34 LANGUAGE: typescript CODE: ``` const workflow = client.workflow() // Override the client timeout const workflow = client.workflow(60000) // Create a workflow without a client const workflow = new StagedWorkflowBuilder({ apiKey: "your-api-key", }) ``` ---------------------------------------- TITLE: NutrientClient Constructor and Options DESCRIPTION: Details the constructor for the NutrientClient, outlining the required and optional parameters for initializing the client. This includes API key, base URL, and request timeout. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_2 LANGUAGE: APIDOC CODE: ``` new NutrientClient(options: NutrientClientOptions) Options: - apiKey (required): Your API key string or async function returning a token - baseUrl (optional): Custom API base URL (defaults to `https://api.nutrient.io`) - timeout (optional): Request timeout in milliseconds ``` ---------------------------------------- TITLE: Build and Execute Dynamic Workflows DESCRIPTION: Demonstrates how to construct a workflow dynamically by adding file parts and applying actions conditionally. It covers setting the output format and executing the workflow, requiring the PSPDFKit client and specific workflow stages. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_63 LANGUAGE: typescript CODE: ``` const workflow = client.workflow() // Add parts workflow.addFilePart('document.pdf'); // Conditionally add more parts if (includeAppendix) { workflow.addFilePart('appendix.pdf'); } // Conditionally apply actions if (needsWatermark) { (workflow as WorkflowWithPartsStage).applyAction(BuildActions.watermarkText('CONFIDENTIAL')); } // Set output format based on user preference if (outputFormat === 'pdf') { (workflow as WorkflowWithActionsStage).outputPdf(); } else if (outputFormat === 'docx') { (workflow as WorkflowWithActionsStage).outputOffice('docx'); } else { (workflow as WorkflowWithActionsStage).outputImage('png'); } // Execute the workflow const result = await (workflow as WorkflowWithOutputStage).execute(); ``` ---------------------------------------- TITLE: Initialize NutrientClient with Token Provider DESCRIPTION: Shows how to initialize the NutrientClient using an asynchronous function to fetch authentication tokens from a secure source. This method is recommended for enhanced security. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_1 LANGUAGE: typescript CODE: ``` const client = new NutrientClient({ apiKey: async () => { const response = await fetch('/api/get-nutrient-token'); const { token } = await response.json(); return token; } }); ``` ---------------------------------------- TITLE: Apply Instant JSON Annotations DESCRIPTION: Creates an action to apply annotations from an Instant JSON file to the document. The file can be provided via path, Buffer, or URL. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_42 LANGUAGE: typescript CODE: ``` workflow.applyAction(BuildActions.applyInstantJson('/path/to/annotations.json')); ``` ---------------------------------------- TITLE: Rotate PDF Pages with PSPDFKit Client DESCRIPTION: Rotates pages within a PDF document. Supports rotating all pages by a specified angle or targeting specific page ranges using start and end indices. Uses the `rotate` method of the client. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_18 LANGUAGE: TypeScript CODE: ``` const result = await client.rotate('document.pdf', 90); // Rotate specific pages: const result = await client.rotate('document.pdf', 90, { start: 1, end: 3 }); // Pages 1, 2, 3 // Rotate the last page: const result = await client.rotate('document.pdf', 90, { end: -1 }); // Last page // Rotate from page 2 to the second-to-last page: const result = await client.rotate('document.pdf', 90, { start: 2, end: -2 }); ``` ---------------------------------------- TITLE: Complex Multi-step Workflow DESCRIPTION: An advanced workflow combining multiple operations: adding specific page ranges from files, applying OCR, watermarking, creating redaction presets, and outputting to PDF/A format with progress tracking. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_62 LANGUAGE: typescript CODE: ``` const result = await client .workflow() .addFilePart('document.pdf', { pages: { start: 0, end: 5 } }) .addFilePart('appendix.pdf') .applyActions([ BuildActions.ocr({ language: 'english' }), BuildActions.watermarkText('CONFIDENTIAL'), BuildActions.createRedactionsPreset('email-address', 'apply') ]) .outputPdfA({ level: 'pdfa-2b', optimize: { mrcCompression: true } }) .execute({ onProgress: (current, total) => { console.log(`Processing step ${current} of ${total}`); } }); ``` ---------------------------------------- TITLE: PSPDFKit Labs Nutrient DWS Client API DESCRIPTION: Comprehensive API documentation for the PSPDFKit Labs Nutrient DWS Client, covering core document processing functionalities like OCR, watermarking, conversion, and merging. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_8 LANGUAGE: APIDOC CODE: ``` ocr(file: FileInput, language: OcrLanguage | OcrLanguage[]) Performs OCR (Optical Character Recognition) on a document. Parameters: - file: FileInput - The input file to perform OCR on - language: OcrLanguage | OcrLanguage[] - The language(s) to use for OCR Returns: Promise - Promise resolving to the OCR result ``` LANGUAGE: APIDOC CODE: ``` watermarkText(file: FileInput, text: string, options?: TextWatermarkOptions) Adds a text watermark to a document. Parameters: - file: FileInput - The input file to watermark - text: string - The watermark text - options?: TextWatermarkOptions - Watermark options Returns: Promise - Promise resolving to the watermarked document ``` LANGUAGE: APIDOC CODE: ``` watermarkImage(file: FileInput, image: FileInput, options?: ImageWatermarkOptions) Adds an image watermark to a document. Parameters: - file: FileInput - The input file to watermark - image: FileInput - The watermark image - options?: ImageWatermarkOptions - Watermark options Returns: Promise - Promise resolving to the watermarked document ``` LANGUAGE: APIDOC CODE: ``` convert(file: FileInput, targetFormat: string) Converts a document to a different format. Parameters: - file: FileInput - The input file to convert - targetFormat: string - The target format to convert to (e.g., 'pdf', 'png', 'docx') Returns: Promise - Promise resolving to the converted document Supported formats include: pdf, pdfa, pdfua, docx, xlsx, pptx, png, jpeg, jpg, webp, html, markdown. ``` LANGUAGE: APIDOC CODE: ``` merge(files: FileInput[]) Merges multiple documents into one. Parameters: - files: FileInput[] - An array of input files to merge Returns: Promise - Promise resolving to the merged document ``` ---------------------------------------- TITLE: Apply Instant JSON to PDF with PSPDFKit Client DESCRIPTION: Applies Instant JSON data, typically for annotations, to a PDF document. Uses the `applyInstantJson` method with the path to the JSON file containing the data. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_22 LANGUAGE: TypeScript CODE: ``` const result = await client.applyInstantJson('document.pdf', 'annotations.json'); ``` ---------------------------------------- TITLE: PDF Output Configuration DESCRIPTION: Sets the output format of the document workflow to PDF. This method allows for detailed configuration of PDF generation, including optimization, security settings, metadata, and user permissions. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_48 LANGUAGE: APIDOC CODE: ``` workflow.outputPdf(options?) Sets the output format to PDF. Parameters: - options?: object - Additional options for PDF output. - metadata?: object - Document metadata properties like title, author. - labels?: array - Custom labels to add to the document. - userPassword?: string - Password required to open the document. Encrypts the PDF. - ownerPassword?: string - Password required to modify the document. - userPermissions?: array - Permissions granted to users opening the document (e.g., "printing", "modification", "content-copying"). - optimize?: object - PDF optimization settings. - mrcCompression?: boolean - Applies Mixed Raster Content compression. - imageOptimizationQuality?: number - Controls image optimization quality (1-5, 1 is highest). Returns: WorkflowWithOutputStage<'pdf'> - The workflow builder instance for method chaining. Example: // Set output format to PDF with default options // workflow.outputPdf(); // Set output format to PDF with specific options // workflow.outputPdf({ // userPassword: 'secret', // userPermissions: ["printing"], // metadata: { // title: 'Important Document', // author: 'Document System' // }, // optimize: { // mrcCompression: true, // imageOptimizationQuality: 3 // } // }); ``` ---------------------------------------- TITLE: outputPdfUA: Set PDF/UA Output Format DESCRIPTION: Sets the output format to PDF/UA (Universal Accessibility). Allows configuration of metadata, labels, security, and optimization settings. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_50 LANGUAGE: APIDOC CODE: ``` outputPdfUA(options?) Sets the output format to PDF/UA (Universal Accessibility). Parameters: - options?: object - Additional options for PDF/UA output. - options.metadata?: object - Document metadata properties like title, author. - options.labels?: array - Custom labels to add to the document for organization and categorization. - options.userPassword?: string - Password required to open the document. When set, the PDF will be encrypted. - options.ownerPassword?: string - Password required to modify the document. Provides additional security beyond the user password. - options.userPermissions?: array - Array 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?: object - PDF optimization settings to reduce file size and improve performance. - options.optimize.mrcCompression?: boolean - When true, applies Mixed Raster Content compression to reduce file size. - options.optimize.imageOptimizationQuality?: number - Controls the quality of image optimization (1-5, where 1 is highest quality). Returns: WorkflowWithOutputStage<'pdfua'> - The workflow builder instance for method chaining. Example: // Set output format to PDF/UA with default options workflow.outputPdfUA(); // Set output format to PDF/UA with specific options workflow.outputPdfUA({ metadata: { title: 'Accessible Document', author: 'Document System' }, optimize: { mrcCompression: true, imageOptimizationQuality: 3 } }); ``` ---------------------------------------- TITLE: Set Output Format to HTML (TypeScript) DESCRIPTION: Configures the client to output documents as HTML. Users can specify the layout, choosing between 'page' layout which preserves document structure per page, or 'reflow' layout for a continuous text flow. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_53 LANGUAGE: APIDOC CODE: ``` outputHtml(layout: 'page' | 'reflow'): WorkflowWithOutputStage<'html'> - Sets the output format to HTML. - Parameters: - layout: The layout type for HTML conversion. - 'page': Keeps the original document structure, segmented by page. - 'reflow': Converts the document into a continuous flow of text, without page breaks. - Returns: The workflow builder instance for method chaining. - Example: workflow.outputHtml('page'); ``` ---------------------------------------- TITLE: Apply XFDF Annotations with PSPDFKit DESCRIPTION: Creates an action to apply annotations from an XFDF file to a document. Supports options to ignore page rotation and control rich text conversion. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_43 LANGUAGE: typescript CODE: ``` workflow.applyAction(BuildActions.applyXfdf('/path/to/annotations.xfdf')); workflow.applyAction(BuildActions.applyXfdf('/path/to/annotations.xfdf', { ignorePageRotation: true, richTextEnabled: false })); ``` ---------------------------------------- TITLE: Apply Actions to Workflow DESCRIPTION: Details how to apply processing actions to the entire workflow. Supports applying a single action or an array of multiple actions, allowing for complex document transformations. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_36 LANGUAGE: APIDOC CODE: ``` applyAction(action: BuildAction) Applies a single processing action to the workflow. 'action' is an object defining the operation, e.g., watermark, OCR. Returns: WorkflowWithActionsStage Example: workflow.applyAction(BuildActions.watermarkText('DRAFT', { opacity: 0.5 })) applyActions(actions: BuildAction[]) Applies an array of processing actions to the workflow. 'actions' is a list of action objects to be executed sequentially. Returns: WorkflowWithActionsStage Example: workflow.applyActions([ BuildActions.watermarkText('CONFIDENTIAL'), BuildActions.ocr('eng'), BuildActions.flatten() ]) ``` ---------------------------------------- TITLE: Set Output Format to Office Document (TypeScript) DESCRIPTION: Configures the client to output documents in common Office formats like DOCX, XLSX, or PPTX. This method is used to specify the target application format for the document conversion. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_52 LANGUAGE: APIDOC CODE: ``` outputOffice(format: 'docx' | 'xlsx' | 'pptx'): WorkflowWithOutputStage - Sets the output format to an Office document format (DOCX, XLSX, PPTX). - Parameters: - format: The Office format to output. Supported values are 'docx' (Word), 'xlsx' (Excel), or 'pptx' (PowerPoint). - Returns: The workflow builder instance for method chaining. - Example: workflow.outputOffice('docx'); workflow.outputOffice('xlsx'); workflow.outputOffice('pptx'); ``` ---------------------------------------- TITLE: Set Output Format to Image (TypeScript) DESCRIPTION: Configures the client to output documents as images (PNG, JPEG, WEBP). Supports specifying format, resolution (DPI), dimensions (width, height), and page ranges. Aspect ratio is maintained if only one dimension is provided. At least one of width, height, or dpi must be specified in options. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_51 LANGUAGE: APIDOC CODE: ``` outputImage(format: 'png' | 'jpeg' | 'jpg' | 'webp', options?: { pages?: { start?: number, end?: number }, width?: number, height?: number, dpi?: number }): WorkflowWithOutputStage - Sets the output format to an image format (PNG, JPEG, WEBP). - Parameters: - format: The image format to output. Supported values are 'png', 'jpeg', 'jpg', 'webp'. - options: Optional object for additional image output settings. - pages: Specifies which pages to convert. If omitted, all pages are converted. - start: The first page to convert (0-based index). - end: The last page to convert (0-based index). - width: The width of the output image in pixels. Maintains aspect ratio if height is not specified. - height: The height of the output image in pixels. Maintains aspect ratio if width is not specified. - dpi: The resolution in dots per inch. Higher values create larger, more detailed images. - Note: At least one of options.width, options.height, or options.dpi must be specified. - Returns: The workflow builder instance for method chaining. - Example: workflow.outputImage('png', { dpi: 300 }); workflow.outputImage('jpeg', { dpi: 300, pages: { start: 1, end: 3 } }); workflow.outputImage('webp', { width: 1200, height: 800, dpi: 150 }); ``` ---------------------------------------- TITLE: Optimize PDF Document with PSPDFKit Client DESCRIPTION: Optimizes a PDF document to reduce its file size. Supports various options for image compression, grayscale conversion, and quality settings. Uses the `optimize` method. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_29 LANGUAGE: TypeScript CODE: ``` const result = await client.optimize('large-document.pdf', { grayscaleImages: true, mrcCompression: true, imageOptimizationQuality: 2 }); ``` ---------------------------------------- TITLE: Set Output Format to Markdown (TypeScript) DESCRIPTION: Configures the client to output documents in Markdown format. This method simplifies document content into a plain text format suitable for documentation or content management systems. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_54 LANGUAGE: APIDOC CODE: ``` outputMarkdown(): WorkflowWithOutputStage<'markdown'> - Sets the output format to Markdown. - Parameters: None. - Returns: The workflow builder instance for method chaining. - Example: workflow.outputMarkdown(); ``` ---------------------------------------- TITLE: Create Redactions by Preset with PSPDFKit Client DESCRIPTION: Creates redaction annotations based on predefined patterns like 'email-address'. Supports specifying a redaction state, page ranges, and preset options. Uses the `createRedactionsPreset` method. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_24 LANGUAGE: TypeScript CODE: ``` const result = await client.createRedactionsPreset('document.pdf', 'email-address'); // With specific pages const result = await client.createRedactionsPreset( 'document.pdf', 'email-address', 'stage', { start: 0, end: 4 } // Pages 0, 1, 2, 3, 4 ); // With the last 3 pages const result = await client.createRedactionsPreset( 'document.pdf', 'email-address', 'stage', { start: -3, end: -1 } // Last three pages ); ``` ---------------------------------------- TITLE: Add Document Parts to Workflow DESCRIPTION: Covers adding various types of content as parts to a workflow, including files, HTML content, new blank pages, and existing documents by ID. Each method supports chaining and optional parameters for customization. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_35 LANGUAGE: APIDOC CODE: ``` addFilePart(file: FileInput, options?: object, actions?: BuildAction[]) Adds a file part to the workflow. 'file' can be a local path, Buffer, or URL. 'options' can specify page ranges, and 'actions' apply transformations. Returns: WorkflowWithPartsStage Example: workflow.addFilePart('/path/to/document.pdf', { pages: { start: 1, end: 3 } }, [BuildActions.watermarkText('CONFIDENTIAL')]) addHtmlPart(html: FileInput, assets?: FileInput[], options?: object, actions?: BuildAction[]) Adds HTML content as a part. 'html' can be a file path, Buffer, or URL. 'assets' are local files or Buffers (CSS, images). 'options' can define layout, and 'actions' apply transformations. Returns: WorkflowWithPartsStage Example: workflow.addHtmlPart('/path/to/content.html', ['/path/to/style.css'], { layout: { size: 'A4' } }) addNewPage(options?: object, actions?: BuildAction[]) Adds a new blank page to the workflow. 'options' can specify page size and orientation. 'actions' can be applied to the new page. Returns: WorkflowWithPartsStage Example: workflow.addNewPage({ layout: { size: 'A4', orientation: 'portrait' } }) addDocumentPart(documentId: string, options?: object, actions?: BuildAction[]) Adds an existing document by its ID. 'options' can include a 'layer' name or page ranges. 'actions' can be applied to the document part. Returns: WorkflowWithPartsStage Example: workflow.addDocumentPart('doc_12345abcde', { layer: 'content', pages: { start: 0, end: 3 } }) ``` ---------------------------------------- TITLE: outputPdfA: Set PDF/A Output Format DESCRIPTION: Sets the output format to PDF/A, an archival standard. Allows configuration of conformance levels, vectorization, rasterization, metadata, security, and optimization. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_49 LANGUAGE: APIDOC CODE: ``` outputPdfA(options?) Sets the output format to PDF/A (archival PDF). Parameters: - options?: object - Additional options for PDF/A output. - options.conformance?: string - The PDF/A conformance level to target. Options include 'pdfa-1b', 'pdfa-1a', 'pdfa-2b', 'pdfa-2a', 'pdfa-3b', 'pdfa-3a'. Different levels have different requirements for long-term archiving. - options.vectorization?: boolean - When true, attempts to convert raster content to vector graphics where possible, improving quality and reducing file size. - options.rasterization?: boolean - When true, converts vector graphics to raster images, which can help with compatibility in some cases. - options.metadata?: object - Document metadata properties like title, author. - options.labels?: array - Custom labels to add to the document for organization and categorization. - options.userPassword?: string - Password required to open the document. When set, the PDF will be encrypted. - options.ownerPassword?: string - Password required to modify the document. Provides additional security beyond the user password. - options.userPermissions?: array - Array 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?: object - PDF optimization settings to reduce file size and improve performance. - options.optimize.mrcCompression?: boolean - When true, applies Mixed Raster Content compression to reduce file size. - options.optimize.imageOptimizationQuality?: number - Controls the quality of image optimization (1-5, where 1 is highest quality). Returns: WorkflowWithOutputStage<'pdfa'> - The workflow builder instance for method chaining. Example: // Set output format to PDF/A with default options workflow.outputPdfA(); // Set output format to PDF/A with specific options workflow.outputPdfA({ conformance: 'pdfa-2b', vectorization: true, metadata: { title: 'Archive Document', author: 'Document System' }, optimize: { mrcCompression: true } }); ``` ---------------------------------------- TITLE: Handle Workflow Execution Errors DESCRIPTION: Illustrates robust error handling for workflow execution using a try-catch block. It shows how to check the `success` property of the result and iterate through `errors` for detailed step-specific issues, as well as catching unexpected exceptions. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_64 LANGUAGE: typescript CODE: ``` try { const result = await client .workflow() .addFilePart('document.pdf') .outputPdf() .execute(); if (!result.success) { // Handle workflow errors result.errors?.forEach(error => { console.error(`Step ${error.step}: ${error.error.message}`); }); } } catch (error) { // Handle unexpected errors console.error('Workflow execution failed:', error); } ``` ---------------------------------------- TITLE: Apply XFDF to PDF with PSPDFKit Client DESCRIPTION: Applies XFDF data, often used for form data and annotations, to a PDF document. Uses the `applyXfdf` method with the path to the XFDF file. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_23 LANGUAGE: TypeScript CODE: ``` const result = await client.applyXfdf('document.pdf', 'annotations.xfdf'); ``` ---------------------------------------- TITLE: Create Regex Redactions with PSPDFKit DESCRIPTION: Creates an action to add redaction annotations by matching a regular expression pattern. Offers options for redaction appearance, case sensitivity, and specifying the search page range. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_45 LANGUAGE: typescript CODE: ``` workflow.applyAction(BuildActions.createRedactionsRegex('[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}')); workflow.applyAction(BuildActions.createRedactionsRegex('[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', { content: { backgroundColor: '#FF0000', overlayText: 'EMAIL REDACTED' } }, { caseSensitive: false, start: 0, limit: 10 } )); ``` ---------------------------------------- TITLE: Set JSON Output Format DESCRIPTION: Configures the workflow to output content in JSON format. Supports options for extracting plain text, structured text, key-value pairs, and tables, along with language specification for improved text extraction. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_55 LANGUAGE: typescript CODE: ``` workflow.outputJson(); workflow.outputJson({ plainText: true, structuredText: true, keyValuePairs: true, tables: true, language: "english" }); workflow.outputJson({ plainText: true, tables: true, language: ["english", "french", "german"] }); ``` ---------------------------------------- TITLE: Execute Workflow DESCRIPTION: Executes the configured document processing workflow. It can optionally accept a progress callback to monitor the execution status. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_56 LANGUAGE: typescript CODE: ``` const result = await workflow.execute(); const result = await workflow.execute({ onProgress: (current, total) => { console.log(`Processing step ${current} of ${total}`); } }); ``` ---------------------------------------- TITLE: Perform OCR on a Document DESCRIPTION: Demonstrates how to use the `ocr` method to perform Optical Character Recognition on a PDF file using TypeScript. It shows how to access the processed PDF buffer and its MIME type. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_9 LANGUAGE: typescript CODE: ``` const result = await client.ocr('scanned-document.pdf', 'english'); // Access the OCR-processed PDF buffer const pdfBuffer = result.buffer; // Get the MIME type of the output console.log(result.mimeType); // 'application/pdf' // Save the buffer to a file (Node.js example) const fs = require('fs'); fs.writeFileSync('ocr-document.pdf', Buffer.from(result.buffer)); ``` ---------------------------------------- TITLE: extractKeyValuePairs(file, pages?) DESCRIPTION: Extracts key-value pair content from a document. Accepts a file input and an optional page range. Returns a promise resolving to the extracted KVPs data. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_16 LANGUAGE: typescript CODE: ``` const result = await client.extractKeyValuePairs('document.pdf'); // Extract KVPs from specific pages const result = await client.extractKeyValuePairs('document.pdf', { start: 0, end: 2 }); // Pages 0, 1, 2 // Extract KVPs from the last page const result = await client.extractKeyValuePairs('document.pdf', { end: -1 }); // Last page // Extract KVPs from the second-to-last page to the end const result = await client.extractKeyValuePairs('document.pdf', { start: -2 }); // Second-to-last and last page // Access the extracted key-value pairs const kvps = result.data.pages[0].keyValuePairs; // Process the key-value pairs if (kvps && kvps.length > 0) { // Iterate through all key-value pairs kvps.forEach((kvp, index) => { console.log(`KVP ${index + 1}:`); console.log(` Key: ${kvp.key}`); console.log(` Value: ${kvp.value}`); console.log(` Confidence: ${kvp.confidence}`); }); // Create a dictionary from the key-value pairs const dictionary = {}; kvps.forEach(kvp => { dictionary[kvp.key] = kvp.value; }); // Look up specific values console.log(`Invoice Number: ${dictionary['Invoice Number']}`); console.log(`Date: ${dictionary['Date']}`); console.log(`Total Amount: ${dictionary['Total']}`); } ``` ---------------------------------------- TITLE: Create Redactions Preset Action DESCRIPTION: Creates an action to add redaction annotations based on a preset pattern. It allows specifying redaction presets, visual options for annotations, and strategy options like page range and annotation inclusion. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_46 LANGUAGE: typescript CODE: ``` import { BuildActions } from '@pspdfkit/document-workflow-builder'; // Example usage: // workflow.applyAction(BuildActions.createRedactionsPreset('email-address')); // workflow.applyAction(BuildActions.createRedactionsPreset('credit-card-number', { // content: { // backgroundColor: '#000000', // overlayText: 'FINANCIAL DATA' // } // }, { // start: 0, // limit: 5 // })); ``` ---------------------------------------- TITLE: Create Authentication Token DESCRIPTION: Generates a new authentication token with specified parameters, such as a name and expiration duration. The returned promise resolves to an object containing the new token's ID and value. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_4 LANGUAGE: typescript CODE: ``` const token = await client.createToken({ name: 'My API Token', expiresIn: '30d' }); console.log(token.id); // Store the token for future use const tokenId = token.id; const tokenValue = token.token; ``` ---------------------------------------- TITLE: Create Text Redactions with PSPDFKit DESCRIPTION: Creates an action to add redaction annotations by searching for specific text. Allows customization of redaction appearance and search strategy, including case sensitivity and page range. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_44 LANGUAGE: typescript CODE: ``` workflow.applyAction(BuildActions.createRedactionsText('Confidential')); workflow.applyAction(BuildActions.createRedactionsText('Confidential', { content: { backgroundColor: '#000000', overlayText: 'REDACTED', textColor: '#FFFFFF' } }, { caseSensitive: true, start: 2, limit: 5 } )); ``` ---------------------------------------- TITLE: Nutrient DWS Client Error Handling (TypeScript) DESCRIPTION: Demonstrates how to catch and handle various errors thrown by the Nutrient DWS TypeScript Client, such as validation, authentication, API, and network errors. It uses instanceof checks to identify specific error types and access their properties. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_33 LANGUAGE: typescript CODE: ``` import { NutrientError, ValidationError, APIError, AuthenticationError, NetworkError } from 'nutrient-dws-client-typescript'; try { const result = await client.convert('file.docx', 'pdf'); } catch (error) { if (error instanceof ValidationError) { // Invalid input parameters console.error('Invalid input:', error.message, error.details); } else if (error instanceof AuthenticationError) { // Authentication failed console.error('Auth error:', error.message, error.statusCode); } else if (error instanceof APIError) { // API returned an error console.error('API error:', error.message, error.statusCode, error.details); } else if (error instanceof NetworkError) { // Network request failed console.error('Network error:', error.message, error.details); } } ``` ---------------------------------------- TITLE: Add Image Watermark to a Document DESCRIPTION: Shows how to apply an image watermark to a document using the `watermarkImage` method. Covers setting image watermark properties such as opacity and dimensions, and saving the output. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_11 LANGUAGE: typescript CODE: ``` const result = await client.watermarkImage('document.pdf', 'watermark.jpg', { opacity: 0.5, width: { value: 50, unit: "%"}, height: { value: 50, unit: "%"} }); // Access the watermarked PDF buffer const pdfBuffer = result.buffer; // Get the MIME type of the output console.log(result.mimeType); // 'application/pdf' // Save the buffer to a file (Node.js example) const fs = require('fs'); fs.writeFileSync('image-watermarked-document.pdf', Buffer.from(result.buffer)); ``` ---------------------------------------- TITLE: Password Protect PDF Document with PSPDFKit Client DESCRIPTION: Secures a PDF document with user and owner passwords, optionally defining permissions. Returns the protected document buffer and MIME type. Uses the `passwordProtect` method. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_19 LANGUAGE: TypeScript CODE: ``` const result = await client.passwordProtect('document.pdf', 'user123', 'owner456'); // Or with specific permissions: const result = await client.passwordProtect('document.pdf', 'user123', 'owner456', ['printing', 'extract_accessibility']); // Access the password-protected PDF buffer const pdfBuffer = result.buffer; // Get the MIME type of the output console.log(result.mimeType); // 'application/pdf' // Save the buffer to a file (Node.js example) const fs = require('fs'); fs.writeFileSync('protected-document.pdf', Buffer.from(result.buffer)); ``` ---------------------------------------- TITLE: Duplicate and Reorder PDF Pages (TypeScript) DESCRIPTION: Creates a new PDF document containing only the specified pages from an input PDF, allowing for reordering and duplication. Accepts a FileInput and an array of page indices. Returns a promise resolving to a WorkflowOutput object with the new PDF's buffer and MIME type. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_31 LANGUAGE: typescript CODE: ``` // Create a new PDF with only the first and third pages const result = await client.duplicatePages('document.pdf', [0, 2]); // Create a new PDF with pages in a different order const result = await client.duplicatePages('document.pdf', [2, 0, 1]); // Create a new PDF with duplicated pages const result = await client.duplicatePages('document.pdf', [0, 0, 1, 1, 0]); // Create a new PDF with the first and last pages const result = await client.duplicatePages('document.pdf', [0, -1]); // Create a new PDF with the last three pages in reverse order const result = await client.duplicatePages('document.pdf', [-1, -2, -3]); // Access the PDF buffer const pdfBuffer = result.buffer; // Get the MIME type of the output console.log(result.mimeType); // 'application/pdf' // Save the buffer to a file (Node.js example) const fs = require('fs'); fs.writeFileSync('duplicated-pages.pdf', Buffer.from(result.buffer)); ``` ---------------------------------------- TITLE: Add Blank Pages to PDF with PSPDFKit Client DESCRIPTION: Adds a specified number of blank pages to a PDF document. Supports inserting pages at a specific index or appending them to the end. Uses the `addPage` method. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_28 LANGUAGE: TypeScript CODE: ``` // Add 2 blank pages at the end const result = await client.addPage('document.pdf', 2); // Add 1 blank page after the first page (at index 1) const result = await client.addPage('document.pdf', 1, 1); ``` ---------------------------------------- TITLE: Create Redactions by Text with PSPDFKit Client DESCRIPTION: Creates redaction annotations based on specific text content. Supports specifying a redaction state, page ranges, and text options like case sensitivity. Uses the `createRedactionsText` method. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_26 LANGUAGE: TypeScript CODE: ``` const result = await client.createRedactionsText('document.pdf', 'email@example.com'); // With specific pages and options const result = await client.createRedactionsText( 'document.pdf', 'email@example.com', 'stage', { start: 0, end: 4 }, // Pages 0, 1, 2, 3, 4 { caseSensitive: false, includeAnnotations: true } ); // Create redactions on the last 3 pages const result = await client.createRedactionsText( 'document.pdf', 'email@example.com', 'stage', { start: -3, end: -1 } // Last three pages ); ``` ---------------------------------------- TITLE: Create Redactions by Regex with PSPDFKit Client DESCRIPTION: Creates redaction annotations based on a custom regular expression. Supports specifying a redaction state, page ranges, and regex options. Uses the `createRedactionsRegex` method. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_25 LANGUAGE: TypeScript CODE: ``` const result = await client.createRedactionsRegex('document.pdf', 'Account:\s*\d{8,12}'); // With specific pages const result = await client.createRedactionsRegex( 'document.pdf', 'Account:\s*\d{8,12}', 'stage', { start: 0, end: 4 } // Pages 0, 1, 2, 3, 4 ); // With the last 3 pages const result = await client.createRedactionsRegex( 'document.pdf', 'Account:\s*\d{8,12}', 'stage', { start: -3, end: -1 } // Last three pages ); ``` ---------------------------------------- TITLE: extractTable(file, pages?) DESCRIPTION: Extracts table content from a document. Accepts a file input and an optional page range. Returns a promise resolving to the extracted table data. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_15 LANGUAGE: typescript CODE: ``` const result = await client.extractTable('document.pdf'); // Extract tables from specific pages const result = await client.extractTable('document.pdf', { start: 0, end: 2 }); // Pages 0, 1, 2 // Extract tables from the last page const result = await client.extractTable('document.pdf', { end: -1 }); // Last page // Extract tables from the second-to-last page to the end const result = await client.extractTable('document.pdf', { start: -2 }); // Second-to-last and last page // Access the extracted tables const tables = result.data.pages[0].tables; // Process the first table if available if (tables && tables.length > 0) { const firstTable = tables[0]; // Get table dimensions console.log(`Table has ${firstTable.rows.length} rows and ${firstTable.columns.length} columns`); // Access table cells for (let i = 0; i < firstTable.rows.length; i++) { for (let j = 0; j < firstTable.columns.length; j++) { const cell = firstTable.cells.find(cell => cell.rowIndex === i && cell.columnIndex === j); const cellContent = cell?.text || ''; console.log(`Cell [${i}][${j}]: ${cellContent}`); } } // Convert table to CSV let csv = ''; for (let i = 0; i < firstTable.rows.length; i++) { const rowData = []; for (let j = 0; j < firstTable.columns.length; j++) { const cell = firstTable.cells.find(cell => cell.rowIndex === i && cell.columnIndex === j); rowData.push(cell?.text || ''); } csv += rowData.join(',') + '\n'; } console.log(csv); } ``` ---------------------------------------- TITLE: OCR Action with Language DESCRIPTION: Creates an OCR (Optical Character Recognition) action to extract text from images or scanned documents. Supports single or multiple languages for recognition. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_37 LANGUAGE: typescript CODE: ``` workflow.applyAction(BuildActions.ocr('english')); ``` LANGUAGE: typescript CODE: ``` workflow.applyAction(BuildActions.ocr(['english', 'french', 'german'])); ``` LANGUAGE: typescript CODE: ``` workflow.applyAction(BuildActions.ocr({ language: 'english', enhanceResolution: true })); ``` ---------------------------------------- TITLE: Sign PDF Document DESCRIPTION: Applies a digital signature to a PDF document. It accepts the file, optional signature data, and additional options for graphic images. The output is a WorkflowOutput object containing the signed PDF buffer. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_6 LANGUAGE: typescript CODE: ``` const result = await client.sign('document.pdf', { signature: { signatureType: 'cms', flatten: false, cadesLevel: 'b-lt', } }); // Access the signed PDF buffer const pdfBuffer = result.buffer; // Get the MIME type of the output console.log(result.mimeType); // 'application/pdf' // Save the buffer to a file (Node.js example) const fs = require('fs'); fs.writeFileSync('signed-document.pdf', Buffer.from(result.buffer)); ``` ---------------------------------------- TITLE: Add Image Watermark DESCRIPTION: Creates an action to add an image watermark to the document. Supports customization of image source, size, position, rotation, and opacity. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_41 LANGUAGE: typescript CODE: ``` workflow.applyAction(BuildActions.watermarkImage('/path/to/logo.png')); ``` LANGUAGE: typescript CODE: ``` workflow.applyAction(BuildActions.watermarkImage('/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 })); ``` ---------------------------------------- TITLE: Perform Dry Run DESCRIPTION: Executes a dry run of the workflow without generating final output. This is useful for validating the workflow configuration and estimating processing time. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_57 LANGUAGE: typescript CODE: ``` const dryRunResult = await workflow .addFilePart('/path/to/document.pdf') .outputPdf() .dryRun(); ``` ---------------------------------------- TITLE: OCR with Language Selection DESCRIPTION: Demonstrates performing Optical Character Recognition (OCR) on a scanned PDF document, specifying the language for accurate text extraction. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_60 LANGUAGE: typescript CODE: ``` const result = await client .workflow() .addFilePart('scanned-document.pdf') .applyAction(BuildActions.ocr({ language: 'english', enhanceResolution: true })) .outputPdf() .execute(); ``` ---------------------------------------- TITLE: Set PDF Document Metadata with PSPDFKit Client DESCRIPTION: Sets metadata properties like title and author for a PDF document. Uses the `setMetadata` method of the client, accepting an object with metadata key-value pairs. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_20 LANGUAGE: TypeScript CODE: ``` const result = await client.setMetadata('document.pdf', { title: 'My Document', author: 'John Doe' }); ``` ---------------------------------------- TITLE: Set PDF Page Labels with PSPDFKit Client DESCRIPTION: Assigns custom labels to specific page ranges within a PDF document. Uses the `setPageLabels` method, accepting an array of label configurations with page ranges and their corresponding labels. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_21 LANGUAGE: TypeScript CODE: ``` const result = await client.setPageLabels('document.pdf', [ { pages: [0, 1, 2], label: 'Cover' }, { pages: [3, 4, 5], label: 'Chapter 1' } ]); ``` ---------------------------------------- TITLE: Add Text Watermark DESCRIPTION: Creates an action to add a text watermark to the document. Supports customization of text content, size, position, rotation, opacity, font, and color. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_40 LANGUAGE: typescript CODE: ``` workflow.applyAction(BuildActions.watermarkText('CONFIDENTIAL')); ``` LANGUAGE: typescript CODE: ``` workflow.applyAction(BuildActions.watermarkText('DRAFT', { opacity: 0.5, rotation: 45, fontSize: 36, fontColor: '#FF0000', fontStyle: ['bold', 'italic'] })); ``` ---------------------------------------- TITLE: Split PDF by Page Ranges (TypeScript) DESCRIPTION: Splits a PDF document into multiple parts based on specified page ranges. Accepts a FileInput and an array of page range objects. Returns a promise resolving to an array of WorkflowOutput objects, each containing the PDF buffer and MIME type for a split part. SOURCE: https://github.com/pspdfkit-labs/nutrient-dws-client-typescript/blob/main/LLM_DOC.md#_snippet_30 LANGUAGE: typescript CODE: ``` const 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 const 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 (const result of results) { // Access the PDF buffer const pdfBuffer = result.buffer; // Get the MIME type of the output console.log(result.mimeType); // 'application/pdf' // Save the buffer to a file (Node.js example) const fs = require('fs'); fs.writeFileSync(`split-part-${i}.pdf`, Buffer.from(result.buffer)); } ```