ComPDF React Native - v3.0.0
    Preparing search index...

    Class CPDFDocument

    Provides document-level operations for the PDF reader.

    3.0.0

    Operations that require a mounted native reader reject when the reader reference is unavailable.

    Index

    Annotation Replies

    • Adds a plain reply to an annotation.

      Mark and review state replies are managed by dedicated state APIs and are not created by this method.

      Parameters

      • annotation: CPDFAnnotation

        The parent annotation to reply to.

      • options: { content: string; title?: string }

        Reply content and optional author/title.

      Returns Promise<CPDFReplyAnnotation | null>

      The created plain reply annotation, or null if creation failed.

      const annotations = await pdfReaderRef.current?._pdfDocument
      .pageAtIndex(0)
      .getAnnotations();
      const reply = await pdfReaderRef.current?._pdfDocument.addAnnotationReply(
      annotations[0],
      { content: 'Please review this highlight.', title: 'ComPDFKit' }
      );
    • Gets all replies attached to an annotation.

      Returned reply objects include their content, markState, and reviewState. Native mark/review state replies are implementation details and are not exposed through a public replyType field.

      Parameters

      Returns Promise<CPDFReplyAnnotation[]>

      Replies attached to the annotation.

      const replies = await pdfReaderRef.current?._pdfDocument
      .getAnnotationReplies(annotation);
    • Updates a plain annotation reply.

      Parameters

      • reply: CPDFReplyAnnotation

        The plain reply annotation to update.

      • options: { content: string; title?: string }

        Updated reply content and optional author/title.

      Returns Promise<boolean>

      true when the reply was updated.

      const replies = await pdfReaderRef.current?._pdfDocument
      .getAnnotationReplies(annotation);
      await pdfReaderRef.current?._pdfDocument.updateAnnotationReply(replies[0], {
      content: 'Updated reply content.',
      });
    • Removes a plain annotation reply.

      Parameters

      Returns Promise<boolean>

      true when the reply was removed.

      const replies = await pdfReaderRef.current?._pdfDocument
      .getAnnotationReplies(annotation);
      await pdfReaderRef.current?._pdfDocument.removeAnnotationReply(replies[0]);
    • Removes all plain replies attached to an annotation.

      Mark and review state replies are preserved.

      Parameters

      Returns Promise<boolean>

      true when all plain replies were removed.

      await pdfReaderRef.current?._pdfDocument
      .removeAllAnnotationReplies(annotation);

    Annotations

    • Removes an annotation from the current page.

      Parameters

      Returns Promise<boolean>

      await pdfReaderRef?.current?._pdfDocument.removeAnnotation(annotation);
      
    • Sets the mark state of an annotation or annotation reply.

      Parameters

      Returns Promise<boolean>

      true when the state was updated.

      await pdfReaderRef.current?._pdfDocument.setAnnotationMarkState(
      annotation,
      CPDFAnnotationMarkState.MARKED
      );

      const replies = await pdfReaderRef.current?._pdfDocument
      .getAnnotationReplies(annotation);
      if (replies?.length) {
      await pdfReaderRef.current?._pdfDocument.setAnnotationMarkState(
      replies[0],
      CPDFAnnotationMarkState.UNMARKED
      );
      }
    • Gets the mark state of an annotation or annotation reply.

      Parameters

      • annotation: CPDFAnnotation

        The annotation or reply annotation to query.

      Returns Promise<CPDFAnnotationMarkState>

      The current mark state.

      const state = await pdfReaderRef.current?._pdfDocument
      .getAnnotationMarkState(annotation);
    • Sets the review state of an annotation or annotation reply.

      Parameters

      Returns Promise<boolean>

      true when the state was updated.

      await pdfReaderRef.current?._pdfDocument.setAnnotationReviewState(
      annotation,
      CPDFAnnotationReviewState.ACCEPTED
      );

      const replies = await pdfReaderRef.current?._pdfDocument
      .getAnnotationReplies(annotation);
      if (replies?.length) {
      await pdfReaderRef.current?._pdfDocument.setAnnotationReviewState(
      replies[0],
      CPDFAnnotationReviewState.COMPLETED
      );
      }
    • Gets the review state of an annotation or annotation reply.

      Parameters

      • annotation: CPDFAnnotation

        The annotation or reply annotation to query.

      Returns Promise<CPDFAnnotationReviewState>

      The current review state.

      const state = await pdfReaderRef.current?._pdfDocument
      .getAnnotationReviewState(annotation);
    • Renders the current appearance of an annotation to a base64-encoded image string.

      This API renders the annotation appearance from the PDF page. It does not return the original source asset for annotations backed by external content.

      Parameters

      Returns Promise<string>

      const page = pdfReaderRef.current?._pdfDocument.pageAtIndex(0);
      const annotations = await page?.getAnnotations();
      const annotation = annotations?.[0];

      if (annotation) {
      const base64 = await pdfReaderRef.current?._pdfDocument.renderAnnotationAppearance(
      annotation,
      {
      scale: 4,
      compression: CPDFPageCompression.PNG,
      }
      );
      }
    • Updates the specified annotation in the document. For modifiable properties, please refer to the update method of CPDFAnnotation and its subclasses.

      Parameters

      Returns Promise<void>

      A promise that resolves when the operation completes.

      // update markup annotation
      const markupAnnotation = annotation as CPDFMarkupAnnotation;
      markupAnnotation.update({
      title: 'ComPDFKit',
      content: 'Updated content',
      markupText: 'Updated markup text',
      color: '#FF0000',
      alpha: 255
      });
      await pdfReaderRef.current?._pdfDocument.updateAnnotation(annotation);

      CPDFAnnotation - Base class for all annotations

    • Adds annotations to the document.

      Parameters

      Returns Promise<void>

      A promise that resolves when the operation completes.

      const annotations: CPDFAnnotation[] = [
      new CPDFNoteAnnotation({
      page: 0,
      rect: { left: 100, top: 100, right: 150, bottom: 150 },
      contents: 'This is a note annotation',
      color: '#FFFF00',
      }),
      new CPDFMarkupAnnotation({
      page: 1,
      rect: { left: 50, top: 50, right: 200, bottom: 100 },
      markupText: 'Highlighted text',
      type: 'highlight',
      color: '#00FF00',
      }),
      ];
      await pdfReaderRef.current?._pdfDocument.addAnnotations(annotations);

      CPDFAnnotation - Base class for all annotations

    Bookmarks and Outline

    • Gets the outline root of the document.

      Returns Promise<CPDFOutline | null>

      A promise that resolves to the outline root, or null when no outline is available.

      const outlineRoot = await pdfReaderRef?.current?._pdfDocument.getOutlineRoot();
      

      CPDFOutline - Document outline class

    • if document has no outline, create a new outline root.

      Returns Promise<CPDFOutline | null>

      A promise that resolves to the newly created outline root, or null if it cannot be created.

      const outlineRoot = await pdfReaderRef?.current?._pdfDocument.getOutlineRoot();
      if (!outlineRoot) {
      outlineRoot = await pdfReaderRef?.current?._pdfDocument.newOutlineRoot();
      }

      CPDFOutline - Document outline class

    • Adds a new outline item under the given parent.

      Parameters

      • parentUuid: string

        UUID of parent outline.

      • title: string

        Title of the new outline.

      • insertIndex: number = -1

        Insert position within parent's children. Use -1 to append.

      • pageIndex: number

        Target page index for the outline destination.

      Returns Promise<boolean>

      await pdfReaderRef.current?._pdfDocument.addOutline('parent_outline_id', 'New Section', -1, 0);
      
    • Removes an outline by its UUID.

      Parameters

      • outlineId: string

        UUID of the outline to remove.

      Returns Promise<boolean>

      await pdfReaderRef.current?._pdfDocument.removeOutline(outline.uuid);
      
    • Updates an outline by UUID.

      Parameters

      • outlineId: string

        UUID of the outline to update.

      • newTitle: string

        New title.

      • newPageIndex: number

        New destination page index.

      Returns Promise<boolean>

      await pdfReaderRef.current?._pdfDocument.updateOutline(id, 'Chapter 1', 0);
      
    • Moves an outline under a new parent by UUID.

      Parameters

      • outlineId: string

        UUID of outline to move.

      • newParentId: string

        UUID of the new parent outline (empty string for root).

      • insertIndex: number

        Insert position within new parent's children. Use -1 to append.

      Returns Promise<boolean>

      await pdfReaderRef.current?._pdfDocument.moveOutline(outlineId, parentId, -1);
      
    • Retrieves all bookmarks in the current document.

      Returns Promise<CPDFBookmark[]>

      A promise that resolves to an array of CPDFBookmark objects.

      const bookmarks = await pdfReaderRef.current?._pdfDocument.getBookmarks();
      console.log('Number of bookmarks:', bookmarks.length);

      CPDFBookmark

    • Removes a bookmark at the specified page index.

      Parameters

      • pageIndex: number

        The index of the page whose bookmark should be removed.

      Returns Promise<boolean>

      A promise that resolves to true if the bookmark was successfully removed, otherwise false.

      const removeResult = await pdfReaderRef.current?._pdfDocument.removeBookmark(2);
      
    • Checks if a bookmark exists at the specified page index.

      Parameters

      • pageIndex: number

        The index of the page to check for a bookmark.

      Returns Promise<boolean>

      A promise that resolves to whether the specified page has a bookmark.

      const hasBookmark = await pdfReaderRef.current?._pdfDocument.hasBookmark(2);
      
    • Adds a bookmark at the specified page index with the given title.

      Parameters

      • title: string

        The title of the bookmark to be added.

      • pageIndex: number

        The index of the page where the bookmark should be added.

      Returns Promise<boolean>

      A promise that resolves to true if the bookmark was successfully added, otherwise false.

      const addResult = await pdfReaderRef.current?._pdfDocument.addBookmark('Chapter 1', 2);
      
    • Updates an existing bookmark with new title and page index.

      Parameters

      • bookmark: CPDFBookmark

        The bookmark object containing updated information.

      Returns Promise<boolean>

      A promise that resolves to true if the bookmark was successfully updated, otherwise false.

      const updateResult = await pdfReaderRef.current?._pdfDocument.updateBookmark(bookmark);
      

    Constructors

    Content Editing

    • Removes the specified edit area from the document.

      Parameters

      Returns Promise<void>

      A promise that resolves when the operation completes.

      // first addEventListener to listen for edit area selected event
      pdfReaderRef.current?.addEventListener('onEditAreaSelected', (editArea : CPDFEditArea) => {
      // store the selected edit area
      this.selectedEditArea = editArea;
      });
      // then remove the selected edit area
      await pdfReaderRef.current?.removeEditArea(editArea);
    • Creates a new text area in the content editor on the specified page. This method is only supported on the Android platform.

      Parameters

      • options: {
            pageIndex: number;
            content: string;
            offset: { x: number; y: number };
            maxWidth?: number;
            attr?: CPDFEditorTextAttr;
        }

        Configuration options for the new text area

        • pageIndex: number

          The index of the page where the text area will be created

        • content: string

          The text content to display

        • offset: { x: number; y: number }

          The position (x, y) where the text area will be placed

        • OptionalmaxWidth?: number

          Optional maximum width of the text area

        • Optionalattr?: CPDFEditorTextAttr

          Optional text attributes (font color, size, alignment, etc.)

      Returns Promise<boolean>

      true if the text area was created successfully, otherwise false

      await pdfReaderRef.current?._pdfDocument.createNewTextArea({
      pageIndex: 0,
      content: 'Hello World',
      offset: { x: 100, y: 100 },
      maxWidth: 300,
      attr: { fontColor: '#000000', fontSize: 20 }
      });

      Throws an error if not running on Android platform

    • Creates a new image area in the content editor on the specified page. This method is only supported on the Android platform.

      Parameters

      • options: {
            pageIndex: number;
            imageData: CPDFImageData;
            offset: { x: number; y: number };
            width?: number;
        }

        Configuration options for the new image area

        • pageIndex: number

          The index of the page where the image area will be created

        • imageData: CPDFImageData

          The CPDFImageData instance containing the image source

        • offset: { x: number; y: number }

          The position (x, y) where the image area will be placed

        • Optionalwidth?: number

          Optional width of the image area (default: 200)

      Returns Promise<boolean>

      true if the image area was created successfully, otherwise false

      - Android Assets Path:
      const imageData = CPDFImageData.fromAsset('image.png');

      - Android Content URI:
      const imageData = CPDFImageData.fromUri('content://media/external/images/media/12345');

      - Android File Path:
      const imageData = CPDFImageData.fromPath('/storage/emulated/0/Download/image.png');

      - iOS File Path:
      const imageData = CPDFImageData.fromPath('/var/mobile/Containers/Data/Application/.../Documents/image.png');

      - Base64 String:
      const imageData = CPDFImageData.fromBase64('iVBORw0KGgoAAAANSUhEUgAAAAUA...');

      await pdfReaderRef.current?._pdfDocument.createNewImageArea({
      pageIndex: 0,
      imageData: imageData,
      offset: { x: 100, y: 100 },
      width: 200
      });

      Throws an error if not running on Android platform

    Document Information

    • Gets the file name of the PDF document.

      Returns Promise<string>

      A promise that resolves to the current PDF file name.

      const fileName = await pdfReaderRef.current?._pdfDocument.getFileName();
      
    • Checks if the PDF document is encrypted.

      Returns Promise<boolean>

      A promise that resolves to true when the document is encrypted.

      const isEncrypted = await pdfReaderRef.current?._pdfDocument.isEncrypted();
      
    • Checks if the PDF document is an image document. This is a time-consuming operation that depends on the document size.

      Returns Promise<boolean>

      A promise that resolves to true when the document contains image content.

      const isImageDoc = await pdfReaderRef.current?._pdfDocument.isImageDoc();
      
    • Gets the current document's permissions. There are three types of permissions: No restrictions: [CPDFDocumentPermissions.NONE] If the document has an open password and an owner password, using the open password will grant [CPDFDocumentPermissions.USER] permissions, and using the owner password will grant [CPDFDocumentPermissions.OWNER] permissions.

      Returns Promise<string>

      A promise that resolves to the permissions available for the current document.

      const permissions = await pdfReaderRef.current?._pdfDocument.getPermissions();
      
    • Check if owner permissions are unlocked

      Returns Promise<boolean>

      A promise that resolves to true when owner permissions are unlocked.

      const unlocked = await pdfReaderRef.current?._pdfDocument.checkOwnerUnlocked();
      
    • Get the total number of pages in the current document

      Returns Promise<number>

      A promise that resolves to the total number of pages in the document.

      const pageCount = await pdfReaderRef.current?._pdfDocument.getPageCount();
      
    • Retrieves the path of the current document. On Android, if the document was opened via a URI, the URI will be returned.

      This function returns the path of the document being viewed. If the document was opened through a file URI on Android, the URI string will be returned instead of a file path.

      Returns Promise<string>

      A promise that resolves to the path (or URI) of the current document. If the native view reference is not found, the promise will be rejected with an error.

      const documentPath = await pdfReaderRef.current?._pdfDocument.getDocumentPath();
      

      Will reject with an error message if the native view reference cannot be found.

    • Gets the document information, such as title, author, subject, keywords, creation date, modification date, and producer.

      Returns Promise<CPDFInfo>

      A promise that resolves to a CPDFInfo object containing the document information.

      const info = await pdfReaderRef?.current?._pdfDocument.getInfo();
      console.log(info.title);

      CPDFInfo - Document information class

    • Gets major version string of document.

      Returns Promise<number>

      a Promise that resolves to the major version number.

      const majorVersion = await pdfReaderRef?.current?._pdfDocument.getMajorVersion();
      console.log(majorVersion);
    • Gets minor version string of document.

      Returns Promise<number>

      a Promise that resolves to the minor version number.

      const minorVersion = await pdfReaderRef?.current?._pdfDocument.getMinorVersion();
      console.log(minorVersion);
    • Gets permission information of document, including whether printing, copying, modifying, annotating, filling forms, etc. are allowed.

      Returns Promise<CPDFDocumentPermissionInfo>

      a Promise that resolves to the CPDFDocumentPermissionInfo object.

      const permissionsInfo = await pdfReaderRef?.current?._pdfDocument.getPermissionsInfo();
      

    Document Lifecycle

    • Reopens a specified document in the current CPDFReaderView component.

      Parameters

      • document: string

        The file path of the PDF document.

        • (Android) For a local storage file path:
           document = 'file:///storage/emulated/0/Download/sample.pdf'
        
        • (Android) For a content URI:
           document = 'content://...'
        
        • (Android) For an asset file path:
           document = "file:///android_asset/..."
        
      • password: string | null = null

        The password for the document, which can be null or empty.

      • pageIndex: number = 0

      Returns Promise<boolean>

      A promise that resolves to true if the document is successfully opened, otherwise false.

      await pdfReaderRef.current?._pdfDocument.open(document, 'password');
      
    • Checks whether the document has been modified

      Returns Promise<boolean>

      Returns a Promise indicating if the document has been modified. true: The document has been modified, false: The document has not been modified. If the native view reference cannot be found, a rejected Promise will be returned.

      const hasChange = await pdfReaderRef.current?._pdfDocument.hasChange();
      

    Forms

    • Removes a form widget from the current page.

      Parameters

      Returns Promise<boolean>

      A promise that resolves to the requested state.

      await pdfReaderRef?.current?._pdfDocument.removeWidget(widget);
      

      CPDFWidget - Base class for all form widgets

    • Adds an image signature to the widget.

      Parameters

      • signatureWidget: CPDFSignatureWidget
      • imagePath: string

        The path of the image to be added as a signature.

      Returns Promise<boolean>

      A promise that resolves to true when the signature image is added; otherwise, false.

      android support uri format:
      await pdfDocument.addSignatureImage(signatureWidget, 'content://media/external/images/media/123');
      file path:
      const result = await pdfDocument.addSignatureImage(signatureWidget, '/path/to/image');
      if (result) {
      await pdfDocument.updateAp(signatureWidget);
      }
    • Updates the appearance of the specified widget.

      Parameters

      • widget: CPDFWidget

        The form widget whose properties or appearance will be updated.

      Returns Promise<boolean>

      A promise that resolves to true when the widget appearance is updated; otherwise, false.

      await pdfDocument.updateAp(signatureWidget);
      
    • Adds form widgets to the document.

      Parameters

      • widgets: CPDFWidget[]

        The form widgets to add to the document.

      Returns Promise<void>

      A promise that resolves when the operation completes.

      const widgets = [
      new CPDFCheckboxWidget({
      title: CPDFWidgetUtil.createFieldName("Checkbox"),
      page: 0,
      rect: { left: 361, top: 778, right: 442, bottom: 704 },
      isChecked: true,
      checkStyle: CPDFCheckStyle.CIRCLE,
      checkColor: "#3CE930",
      fillColor: "#e0e0e0",
      borderColor: "#000000",
      borderWidth: 5,
      })
      ];
      await pdfReaderRef.current?._pdfDocument.addWidgets(widgets);

      CPDFWidget - Base class for all form widgets

    Images and Fonts

    • Extracts images from the current document into the specified output directory.

      The output path is a directory, not a single file path. The SDK writes images directly into this directory, creates it when needed, and does not clear existing files or create an extra child directory for each call.

      Parameters

      • directoryPath: string

        The actual output directory where extracted images are saved.

      • pages: number[] | null = []

        Zero-based page indexes. Empty or null means all pages.

      Returns Promise<CPDFExtractImageResult>

      A structured result containing success, count, directoryPath, and imagePaths.

      const result = await pdfReaderRef.current?._pdfDocument.extractImages(
      '/data/user/0/com.example/files/extracted-images',
      [0]
      );

    Import and Export

    • Exports annotations from the current PDF document to an XFDF file.

      Returns Promise<string>

      The path of the XFDF file if export is successful; an empty string if the export fails.

      const exportXfdfFilePath = await pdfReaderRef.current?._pdfDocument.exportAnnotations();
      
    • Delete all comments in the current document

      Returns Promise<boolean>

      A promise that resolves to true when all annotations are removed; otherwise, false.

      const removeResult = await pdfReaderRef.current?._pdfDocument.removeAllAnnotations();
      
    • Imports annotations from the specified XFDF file into the current PDF document.

      Parameters

      • xfdfFile: string

        Path of the XFDF file to be imported.

      Returns Promise<boolean>

      true if the import is successful; otherwise, false.

      // Android - assets file
      const testXfdf = 'file:///android_asset/test.xfdf';
      const importResult = await pdfReaderRef.current?._pdfDocument.importAnnotations(testXfdf);

      // Android - file path
      const testXfdf = '/data/user/0/com.compdfkit.reactnative.example/xxx/xxx.xfdf';
      const importResult = await pdfReaderRef.current?._pdfDocument.importAnnotations(testXfdf);

      // Android - Uri
      const xfdfUri = 'content://xxxx'
      const importResult = await pdfReaderRef.current?._pdfDocument.importAnnotations(xfdfUri);

      // iOS
    • Imports the form data from the specified XFDF file into the current PDF document.

      Parameters

      • xfdfFile: string

        Path of the XFDF file to be imported.

      Returns Promise<boolean>

      true if the import is successful; otherwise, false.

      const xfdfFile = '/data/user/0/com.compdfkit.reactnative.example/xxx/xxx.xfdf';
      // or use Uri on the Android Platform.
      const xfdfFile = 'content://xxxx';
      const importResult = await pdfReaderRef.current?._pdfDocument.importWidgets(xfdfFile);
    • exports the form data from the current PDF document to an XFDF file.

      Returns Promise<string>

      The path of the XFDF file if export is successful; an empty string if the export fails.

      const exportXfdfFilePath = await pdfReaderRef.current?._pdfDocument.exportWidgets();
      
    • Invokes the system's print service to print the current document.

      Returns Promise<void>

      A promise that resolves when the operation completes.

      await pdfReaderRef.current?._pdfDocument.printDocument();
      
    • Flatten all pages of the current document

      Parameters

      • savePath: string

        The path to save the flattened document. On Android, you can pass a Uri.

      • fontSubset: boolean

        Whether to include the font subset when saving.

      Returns Promise<boolean>

      Returns 'true' if the flattened document is saved successfully, otherwise 'false'.

      const savePath = 'file:///storage/emulated/0/Download/flatten.pdf';
      // or use Uri on the Android Platform.
      const savePath = await ComPDFKit.createUri('flatten_test.pdf', 'compdfkit', 'application/pdf');
      const fontSubset = true;
      const result = await pdfReaderRef.current?._pdfDocument.flattenAllPages(savePath, fontSubset);
      await pdfReaderRef.current?.reloadPagesPreservingPosition();
    • Saves the document to the specified directory.

      Parameters

      • savePath: string

        Specifies the path where the document should be saved.

         On Android, both file paths and URIs are supported. For example:
         - File path: `/data/user/0/com.compdfkit.flutter.example/cache/temp/PDF_Document.pdf`
         - URI: `content://media/external/file/1000045118`
        
      • removeSecurity: boolean

        Whether to remove the document's password.

      • fontSubset: boolean

        Whether to embed font subsets into PDF. Defaults to true.

      Returns Promise<boolean>

      Returns 'true' if the document is saved successfully, otherwise 'false'.

      const savePath = 'file:///storage/emulated/0/Download/save.pdf';
      const removeSecurity = false;
      const fontSubset = true;
      const result = await pdfReaderRef.current?._pdfDocument.saveAs(savePath, removeSecurity, fontSubset);
    • Imports another PDF document and inserts it at a specified position in the current document.

      This method imports an external PDF document into the current document, allowing you to choose which pages to import and where to insert the document.

      Parameters

      • filePath: string

        The path of the PDF document to import. Must be a valid, accessible path on the device.

      • pages: number[] | null = []

        The collection of pages to import, represented as an array of integers. If null or an empty array is passed, the entire document will be imported.

      • insertPosition: number = -1

        The position to insert the external document into the current document. This value must be provided. If not specified, the document will be inserted at the end of the current document.

      • password: string | null = ""

        The password for the document, if it is encrypted. If the document is not encrypted, an empty string '' can be passed.

      Returns Promise<boolean>

      Returns a Promise<boolean> indicating whether the document import was successful.

      • true indicates success
      • false or an error indicates failure
      const filePath = '/data/user/0/com.compdfkit.flutter.example/cache/temp/PDF_Document.pdf';
      const pages = [0]; // The pages to import from the document
      const insertPosition = 0; // The position to insert, 0 means insert at the beginning of the document
      const password = ''; // The password for the document, if encrypted
      const importResult = await pdfReaderRef.current?._pdfDocument.importDocument(filePath, pages, insertPosition, password);

      If the native view reference cannot be found, the promise will be rejected with an error.

    • Splits the specified pages from the current document and saves them as a new document.

      This function extracts the given pages from the current PDF document and saves them as a new document at the provided save path.

      Parameters

      • savePath: string

        The path where the new document will be saved.

      • pages: number[] = []

        The array of page numbers to be extracted and saved in the new document.

      Returns Promise<boolean>

      A Promise that resolves to true if the operation is successful, or false if it fails.

      const savePath = '/data/user/0/com.compdfkit.flutter.example/cache/temp/PDF_Document.pdf';
      const pages = [0, 2, 4]; // Pages to extract from the current document
      const result = await pdfReaderRef.current?.splitDocumentPages(savePath, pages);

      If the native view reference is not found, the promise will be rejected with an error message.

    Pages

    • Get the page object at the specified index

      Parameters

      • pageIndex: number

        The index of the page to retrieve

      Returns CPDFPage

      The page object at the specified index

    • Inserts a blank page at the specified index in the document.

      This method allows adding a blank page of a specified size at a specific index within the PDF document. It is useful for document editing scenarios where page insertion is needed.

      Parameters

      • pageIndex: number

        The index position where the blank page will be inserted. Must be a valid index within the document.

      • pageSize: CPDFPageSize = CPDFPageSize.a4

        The size of the blank page to insert. Defaults to A4 size if not specified. Custom page sizes can be used by creating an instance of CPDFPageSize with custom dimensions.

      Returns Promise<boolean>

      A Promise that resolves to a boolean value indicating the success or failure of the blank page insertion. Resolves to true if the insertion was successful, false otherwise.

      const pageSize = CPDFPageSize.a4;
      // Custom page size
      // const pageSize = new CPDFPageSize(500, 800);
      const result = await pdfReaderRef.current?._pdfDocument.insertBlankPage(0, pageSize);
    • Inserts an image as a new page into the current document at the specified index.

      The image will be placed on a blank page with the given dimensions. The imagePath should point to a valid image resource accessible by the native platform (for example, a file path, content URI on Android, or bundled asset path).

      Parameters

      • pageIndex: number

        Zero-based index at which the new image page will be inserted. Must be a valid index within the document (inserting at 0 places the page at the beginning).

      • imagePath: string

        Path or URI to the image to be inserted (platform-dependent). The image format should be supported by the underlying platform (e.g., PNG, JPEG).

      • pageSize: CPDFPageSize = CPDFPageSize.a4

        The size of the page to create for the image. Defaults to A4 size if not provided.

      Returns Promise<boolean>

      A Promise that resolves to true if the image page was successfully inserted, or false if the operation failed.

      // Android file path:
      const imagePath = 'file:///storage/emulated/0/Download/photo.jpg';

      // Android content URI:
      const imagePath = 'content://media/external/images/media/12345';

      // Android asset path:
      const imagePath = 'file:///assets/photo.jpg';

      // iOS file path:
      const imagePath = 'var/mobile/Containers/Data/Application/.../Documents/photo.jpg';

      // insert image page at index 2
      const success = await pdfReaderRef.current?._pdfDocument.insertImagePage(2, imagePath, CPDFPageSize.custom(imageWidth, imageHeight));

      // need reload pages after inserting image page.
      if (success) {
      await pdfReaderRef.current?.reloadPagesPreservingPosition();
      }
    • Removes the pages at the specified indices from the current document.

      The provided array should contain zero-based page indices to remove. Behavior for duplicate indices or out-of-range indices depends on the native implementation; callers should ensure indices are valid and unique where possible.

      Parameters

      • pageIndices: number[]

        An array of zero-based page indices identifying the pages to remove.

      Returns Promise<boolean>

      A Promise that resolves to true if the pages were successfully removed, or false on failure.

      const result = await pdfReaderRef.current?._pdfDocument.removePages([0, 2, 5]);
      // need reload pages after removing pages.
      if (result){
      await pdfReaderRef.current?.reloadPagesPreservingPosition();
      }
    • Copies a page and inserts the duplicated page at the target index.

      Both indexes are zero-based. pageIndex must point to an existing page. insertIndex accepts 0..pageCount, and -1 appends the copied page to the end of the current document.

      Parameters

      • pageIndex: number

        The zero-based index of the source page to duplicate.

      • insertIndex: number

        The zero-based insertion index for the copied page, or -1 to append.

      Returns Promise<boolean>

      A Promise that resolves to true if the page was copied successfully, or false otherwise.

      const copied = await pdfReaderRef.current?._pdfDocument.copyPage(0, -1);
      if (copied) {
      await pdfReaderRef.current?.reloadPagesPreservingPosition();
      }
    • Moves a page from one index to another within the current document.

      This operation reorders pages so that the page originally at fromIndex will be placed at toIndex. Both indices are zero-based. If toIndex is greater than the current page count or either index is invalid, the operation may fail.

      Parameters

      • fromIndex: number

        The zero-based index of the page to move.

      • toIndex: number

        The zero-based target index where the page should be inserted.

      Returns Promise<boolean>

      A Promise that resolves to true if the page was moved successfully, or false if the operation failed.

      const moved = await pdfReaderRef.current?._pdfDocument.movePage(4, 1);
      // need reload pages after moving page.
      if (moved){
      await pdfReaderRef.current?.reloadPagesPreservingPosition();
      }
    • Gets the size of the specified page.

      Parameters

      • pageIndex: number

        The index of the page (0-based).

      Returns Promise<CPDFPageSize>

      The size of the specified page as a CPDFPageSize object.

      const size = await pdfReaderRef?.current?._pdfDocument.getPageSize(pageIndex);
      

      Error If the native view reference cannot be found.

      This method retrieves the dimensions of a specific page in the PDF document.

      2.5.0

    • Renders a PDF page into a base64-encoded image string.

      Converts the specified page of the currently loaded PDF document into an image with the given dimensions, background color, and optional annotations or form fields. Useful for generating page thumbnails or exporting a page snapshot.

      Parameters

      • options: {
            pageIndex: number;
            width: number;
            height: number;
            backgroundColor?: `#${string}`;
            drawAnnot?: boolean;
            drawForm?: boolean;
            pageCompression?: CPDFPageCompression;
        }

        Rendering options

        • pageIndex: number

          The index of the page to render (0-based).

        • width: number

          The width of the rendered image in pixels.

        • height: number

          The height of the rendered image in pixels.

        • OptionalbackgroundColor?: `#${string}`

          The background color of the rendered page. Only supported on Android.

        • OptionaldrawAnnot?: boolean

          Whether to draw annotations on the page. Only supported on Android.

        • OptionaldrawForm?: boolean

          Whether to draw form fields on the page. Only supported on Android.

        • OptionalpageCompression?: CPDFPageCompression

          The compression format used for rendering (e.g., PNG or JPEG).

      Returns Promise<string>

      A Promise that resolves to a base64-encoded image string.

      const size = await pdfReaderRef.current?._pdfDocument.getPageSize(pageIndex);
      const image = await pdfReaderRef.current?._pdfDocument.renderPage({
      pageIndex,
      width: size.width,
      height: size.height,
      backgroundColor: '#FFFFFF',
      drawAnnot: true,
      drawForm: true,
      });
      console.log(image); // iVBORw0KGgo...

      Error If the native view reference cannot be found.

      • Rendering is performed on the native thread.
      • For iOS, only the basic rendering parameters are supported.

      2.5.0

    Security

    • Whether the owner password is correct. If the password is correct, the document will be unlocked with full owner permissions.

      Parameters

      • password: string

        password The owner password to be verified.

      Returns Promise<boolean>

      A promise that resolves to true if the owner password is correct, otherwise false.

      const check = await pdfReaderRef.current?._pdfDocument.checkOwnerPassword('ownerPassword');
      
    • Remove the user password and owner permission password set in the document, and perform an incremental save.

      Returns Promise<boolean>

      A promise that resolves to true when the passwords are removed; otherwise, false.

      const result = await pdfReaderRef.current?._pdfDocument.removePassword();
      
    • This method sets the document password, including the user password for access restrictions and the owner password for granting permissions.

      • To enable permissions like printing or copying, the owner password must be set; otherwise, the settings will not take effect.

      Parameters

      • userPassword: string

        The user password for document access restrictions.

      • ownerPassword: string

        The owner password to grant permissions (e.g., printing, copying).

      • allowsPrinting: boolean

        Whether printing is allowed (true or false).

      • allowsCopying: boolean

        Whether copying is allowed (true or false).

      • encryptAlgo: string

        The encryption algorithm to use (e.g., CPDFDocumentEncryptAlgo.rc4).

      Returns Promise<boolean>

      A promise that resolves to true if the password is successfully set, otherwise false.

      const success = await pdfReaderRef.current?._pdfDocument.setPassword(
      'user_password',
      'owner_password',
      false,
      false,
      CPDFDocumentEncryptAlgo.rc4
      );
    • Get the encryption algorithm of the current document

      Returns Promise<string>

      A promise that resolves to the document encryption algorithm.

      const encryptAlgo = await pdfReaderRef.current?._pdfDocument.getEncryptAlgo();
      

    Text and Search

    • get textSearcher(): CPDFTextSearcher

      Get the text searcher for the current document.

      Returns CPDFTextSearcher

      The text searcher instance for the current document.

    Watermarks

    • Creates a document watermark. This changes the current document in memory and does not save it to disk automatically.

      Parameters

      Returns Promise<boolean>

      await pdfReaderRef.current?._pdfDocument.createWatermark(
      createTextWatermark({
      textContent: 'Confidential',
      pages: [0, 1],
      textColor: '#FF0000',
      fontSize: 28,
      opacity: 0.75,
      })
      );
    • Returns the number of watermarks in the current document.

      Returns Promise<number>

      const count = await pdfReaderRef.current?._pdfDocument.getWatermarkCount();
      
    • Returns a watermark at the given 0-based index, or null when not found.

      Parameters

      • index: number
      • options: { exportImage?: boolean } = {}

      Returns Promise<CPDFWatermark | null>

      const watermark = await pdfReaderRef.current?._pdfDocument.getWatermark(0, {
      exportImage: true,
      });
    • Returns all watermarks in the current document.

      Parameters

      • options: { exportImages?: boolean } = {}

      Returns Promise<CPDFWatermark[]>

      const watermarks = await pdfReaderRef.current?._pdfDocument.getWatermarks({
      exportImages: false,
      });
    • Updates the watermark at the given 0-based index.

      Parameters

      Returns Promise<boolean>

      const watermark = await pdfReaderRef.current?._pdfDocument.getWatermark(0);
      if (watermark) {
      await pdfReaderRef.current?._pdfDocument.updateWatermark(
      watermark.index,
      copyWatermark(watermark, { opacity: 0.45 })
      );
      }
    • Removes one watermark at the given 0-based index.

      Parameters

      • index: number

      Returns Promise<boolean>

      const removed = await pdfReaderRef.current?._pdfDocument.removeWatermark(0);
      
    • Removes all watermarks in the current document.

      Returns Promise<boolean>

      const removedAll = await pdfReaderRef.current?._pdfDocument.removeAllWatermarks();