ComPDFKit Web SDK
    Preparing search index...

    Class ContentEditManager

    Manages page content editing: entering and leaving content edit mode, the text and image boxes of each page, selection, formatting, copy and paste.

    Hierarchy (View Summary)

    Index
    • Adds a listener for an event. Adding the same function twice for one event has no effect.

      Type Parameters

      • K extends keyof ContentEditManagerEvents

      Parameters

      • name: K

        Event name.

      • fn: (...args: ContentEditManagerEvents[K]) => void

        Listener, called with the event arguments.

      • Optionaloptions: { once?: boolean }

        Listener options.

        • Optionalonce?: boolean

          When true, the listener is removed after it runs once.

      Returns void

    • Creates a new image box that puts the pixels into rect (page coordinates, clamped to the page by the safe distance). Recorded in content edit history; fires contentBoxAdded.

      Parameters

      • pageNumber: number

        The page number (1-based); the page must be open for editing.

      • rect: [number, number, number, number]

        The box rectangle [x1, y1, x2, y2] in page coordinates.

      • image: { height: number; pixels: ArrayBuffer; width: number }

        The image width, height and RGBA pixel data.

        • height: number

          Image height in pixels.

        • pixels: ArrayBuffer

          RGBA pixel data.

        • width: number

          Image width in pixels.

      Returns Promise<ContentBox | undefined>

      A promise that resolves with the new box, or undefined when no box was created.

    • Creates a new text box at rect (page coordinates, clamped to the page by the safe distance). Recorded in content edit history; fires contentBoxAdded.

      Parameters

      • pageNumber: number

        The page number (1-based); the page must be open for editing.

      • rect: [number, number, number, number]

        The box rectangle [x1, y1, x2, y2] in page coordinates.

      • Optionaltext: string

        The initial text. Defaults to an empty string.

      • Optionalstyle: NewParagraphStyle

        Optional font name, font size, color ([r, g, b]), bold, italic and text alignment.

      Returns Promise<ContentBox | undefined>

      A promise that resolves with the new box, or undefined when no box was created.

    • Sets the paragraph alignment of the whole box (or the selected text when the box is being edited).

      Parameters

      • target: string | Core.Annotations.Annotation | ContentBox

        A content box or box id; other annotations are rejected with INVALID_SOURCE.

      • alignment: string

        Left / Start, Center, End / JustifyRight, Justify / JustifyAll, or left / center / right / justify (case-insensitive). Other values reject with INVALID_SOURCE.

      Returns Promise<void>

    • After content changes (operations, undo, redo), replaces the page's boxes with the latest list and redraws only the changed areas of the page; fires contentBoxAdded / contentBoxDeleted for boxes that appear or disappear and drops deleted boxes from the selection. Mostly used internally.

      Parameters

      • pageNumber: number

        The page number (1-based).

      • result: ContentEditResult

        The operation result holding the page's boxes.

      • Optionaltouched: number

        Index of the box whose area is redrawn even when its rectangle is unchanged; defaults to result.touched.

      Returns void

    • Character position for the default caret position: 0 at the beginning, the full text length at the end.

      Parameters

      • text: string

        The text of the box.

      Returns number

      0 when the default position is 'start', otherwise the length of text.

    • Clears the copied boxes: pasteContentBoxes then pastes nothing.

      Returns Promise<void>

    • Runs a box operation on a page open for editing: operations that change page content update the page's boxes and redraw them, and those that add undo steps are recorded in content edit history. Mostly used by content boxes and tools.

      Parameters

      • pageNumber: number

        The page number (1-based).

      • op: string

        The operation name.

      • Optionalargs: unknown[]

        The operation arguments; for box operations the first is the box index. Defaults to none.

      Returns Promise<unknown>

      A promise that resolves with the operation's result value.

    • Commit opened pages to PDF content without leaving edit mode, clearing ranges or discarding history.

      Returns Promise<void>

    • Copies these boxes: records them for pasteContentBoxes, replacing the previous copy; does not change the page and is not recorded in history. Cleared when content editing ends.

      Parameters

      • boxes: ContentBox[]

        The boxes to copy; duplicates are ignored. An empty array clears the copy.

      Returns Promise<void>

      A promise that resolves when the boxes have been copied.

    • Deletes these boxes: page by page from back to front, one request per page; the whole call is one history entry. The box being edited stops editing first; deleted boxes leave the selection and contentBoxDeleted fires.

      Parameters

      • boxes: ContentBox[]

        The boxes to delete; duplicates are ignored.

      Returns Promise<void>

    • Gets the box being edited.

      Returns ContentBox | undefined

      The box whose editor is open, or undefined when none is being edited.

    • Stops editing the current box, writes the edited content back to all opened pages, redraws them, and fires contentEditModeEnded.

      Parameters

      • Optional_options: { dispose?: boolean }

        Unused; kept for compatibility.

        • Optionaldispose?: boolean

          Accepted for compatibility; has no effect.

      Returns Promise<void>

      A promise that resolves when the edited content has been written back to all opened pages and contentEditModeEnded has fired. The selection, content edit history and copied boxes are cleared. Does nothing when content edit mode is not active.

      const { documentViewer } = instance.Core;
      const contentEditManager = documentViewer.getContentEditManager();
      if (contentEditManager.isInContentEditMode())
      await contentEditManager.endContentEditMode();
      const data = await documentViewer.getDocument().getFileData(); // includes the edited content
    • Box content: xmlString has one p per paragraph, spanObjects one per paragraph (text and paragraph number only).

      Parameters

      Returns Promise<TextDetails>

      A promise that resolves with xmlString (one HTML-escaped p element per paragraph) and spanObjects (one span per paragraph, text and paragraph index only).

      const { documentViewer } = instance.Core;
      const contentEditManager = documentViewer.getContentEditManager();
      const [box] = await contentEditManager.loadContentBoxes(1); // content edit mode must be active
      const { spanObjects } = await contentEditManager.getContent(box);
      console.log(spanObjects.map(span => span.text).join('\n'));
    • Finds the box at a point by its rectangle (later-drawn boxes are on top and checked first). Only pages open for editing are searched.

      Parameters

      • pageNumber: number

        The page number (1-based).

      • x: number

        Horizontal position in page coordinates.

      • y: number

        Vertical position in page coordinates.

      Returns ContentBox | undefined

      The box, or undefined when there is none at the point.

    • Returns the rectangle (page coordinates) and type of a box.

      Parameters

      • id: string

        Box id.

      Returns ContentBoxAttributes | undefined

      The attributes, or undefined when the box is not found.

    • Finds a box among the opened pages.

      Parameters

      • id: string

        Box id.

      Returns ContentBox | undefined

      The box, or undefined when not found.

    • Gets the boxes of a page that is open for editing.

      Parameters

      • pageNumber: number

        The page number (1-based).

      Returns ContentBox[]

      A copy of the page's boxes in drawing order; empty for pages not opened yet (see loadContentBoxes).

    • The currently copied boxes: source page, type and box (page coordinates) of each. A snapshot; changing it does not affect the copy; a copy in progress is not included.

      Returns { frame: Frame; pageNumber: number; type: string }[]

      The source page, type ('text' or 'object') and rectangle of each copied box; empty when nothing is copied.

      • frame: Frame

        Box rectangle in page coordinates.

      • pageNumber: number

        Source page number (1-based).

      • type: string

        Box kind ('text' or 'object').

    • Gets where the caret is placed when editing of a box starts.

      Returns CursorPosition

      'start' (the default) or 'end'.

    • Gets the font names that can be used for content (same as ContentEdit.getContentEditingFonts).

      Returns string[]

      The font names.

    • Safe distance (pt, page coordinates): minimum distance of editing boxes from the page edge; defaults are 6 for text and 0 for images. type defaults to common: setting common sets both text and image.

      Parameters

      • Optionaltype: SafeDistanceType

        'text', 'image' or 'common'. Defaults to 'common'.

      Returns number

      The safe distance in PDF points.

    • Gets the selected box; with multiple selection, the first one.

      Returns ContentBox | null

      The selected box, or null when none is selected.

    • Gets all selected boxes; they are always on the same page.

      Returns ContentBox[]

      A copy of the selected boxes; empty when none is selected.

    • Combined bounds of the selected boxes (page coordinates); null when nothing is selected. Used to position overlays.

      Returns Frame | null

      The bounds [x1, y1, x2, y2] in page coordinates, or null when nothing is selected.

    • Checks whether any box is being edited.

      Returns boolean

      True when an editor is open on a box.

    • Checks whether content edit mode is active.

      Returns boolean

      true between startContentEditMode and endContentEditMode.

    • Whether replaceText is running (from start to end, failure included); use it to ignore content changes caused by the replacement itself.

      Returns boolean

      True while replaceText runs.

    • Checks whether invisible characters are shown in the box being edited (see toggleInvisibleCharacters).

      Returns boolean

      True when shown; false by default.

    • Checks whether a tool can be used while content edit mode is active.

      Parameters

      • toolName: string

        Tool name.

      Returns boolean

      true when the tool is allowed.

    • Load the page's real text/image models without switching the keyboard editor or selection.

      Parameters

      • pageNumber: number

        The page number (1-based).

      Returns Promise<ContentBox[]>

      A promise that resolves with the page's boxes once the page is open for editing. It rejects with INVALID_SOURCE when content edit mode is not active or the page number is invalid.

      const { documentViewer } = instance.Core;
      const contentEditManager = documentViewer.getContentEditManager();
      await contentEditManager.startContentEditMode();
      const boxes = await contentEditManager.loadContentBoxes(1);
      console.log(boxes.map(box => box.id));
    • Pastes the copied boxes onto page pageNumber, returns the new boxes and selects them. Without point: each box is offset 5pt to the bottom-right of its original position (in-place duplicate), and each further paste of the same copy on the same page adds another 5pt; with point (page coordinates): the top-left of the group is placed at that point, keeping relative positions. Positions are clamped by the safe distance; the whole paste is one history entry. Note: pasted text boxes may be taller than the originals (the engine reflows the content); the text is unchanged.

      Parameters

      • pageNumber: number

        The page to paste onto (1-based).

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

        Optional position in page coordinates for the top-left of the pasted group.

        • x: number

          Horizontal position in page coordinates.

        • y: number

          Vertical position in page coordinates.

      Returns Promise<ContentBox[]>

      A promise that resolves with the pasted boxes; empty when content edit mode is not active or nothing is copied.

    • Removes a listener, or every listener of the event when fn is omitted.

      Type Parameters

      • K extends keyof ContentEditManagerEvents

      Parameters

      • name: K

        Event name.

      • Optionalfn: (...args: ContentEditManagerEvents[K]) => void

        The function that was passed to addEventListener.

      Returns void

    • Replaces the text of search results (from DocumentViewer#search) with replacement as one history entry. Enters content editing mode first when not in it (and stays in it). Page by page: finds all hits of the same search term in the page's text boxes, matches each result to a hit by position, and replaces from back to front within each box (earlier positions are unaffected). options.resultIndexInPage is used only when searchResults has a single result: it states directly which hit on its page it is (0-based); caseSensitive / wholeWord are the search modes, both false by default. The search term is the resultStr of the first result. Where text read from boxes differs from the page text layer (such as missing spaces) results may not match; unmatched results are skipped.

      Parameters

      • searchResults: SearchResult[]

        The search results to replace; the first result's resultStr is the text searched for. Rejects when empty or when the first result has no text.

      • replacement: string

        The replacement text.

      • Optionaloptions: { caseSensitive?: boolean; resultIndexInPage?: number; wholeWord?: boolean }

        Optional: caseSensitive and wholeWord match the search modes (both false by default); resultIndexInPage (0-based) states which hit on its page a single result is.

        • OptionalcaseSensitive?: boolean

          Case-sensitive matching. Defaults to false.

        • OptionalresultIndexInPage?: number

          With a single result: which hit (0-based) on its page it is.

        • OptionalwholeWord?: boolean

          Whole-word matching. Defaults to false.

      Returns Promise<void>

    • Selects one box (null clears the selection); fires contentEditSelectionChange.

      Parameters

      • box: ContentBox | null

        The box to select, or null to clear the selection.

      Returns void

    • Selects these boxes (replacing the previous selection; an empty array clears it); multiple selection only accepts boxes on the page of the first one. Fires contentEditSelectionChange when the selection changes, with the first box as argument (null when none); use getSelectedContentBoxes for all boxes. The same selection does not fire again.

      Parameters

      • boxes: ContentBox[]

        The boxes to select; duplicates and boxes on other pages than the first box are dropped. The annotation layers are redrawn when the selection changes.

      Returns void

    • Replaces the whole box with new content: XML split by p, plain text, or spanObjects (spans with the same paragraph number join into one paragraph). New text keeps the original style, also when isInheritingContentBoxStyles is false (there is no non-inheriting form here).

      Parameters

      • target: string | Core.Annotations.Annotation | ContentBox

        A content box or box id; rejects with INVALID_SOURCE when not found.

      • content: string | SpanObject[]

        The new content: a string (XML with p elements, or plain text), or span objects joined into paragraphs by paragraphIndex.

      • Optional_isInheritingContentBoxStyles: boolean

        Unused; kept for compatibility. The new text always keeps the box's style.

      Returns Promise<void>

      const { documentViewer } = instance.Core;
      const contentEditManager = documentViewer.getContentEditManager();
      const [box] = await contentEditManager.loadContentBoxes(1); // content edit mode must be active
      await contentEditManager.setContent(box, [
      { text: 'New first paragraph', paragraphIndex: 0 },
      { text: 'New second paragraph', paragraphIndex: 1 },
      ]);
    • Sets several text attributes at once; one undo step.

      Parameters

      • attributes: TextAttributes

        The attributes; fontStyle sets bold and italic together.

      • contentBox: ContentBox

        The text content box.

      • Optionalrange: ContentTextRange

        Optional character range (ComPDFKit extension): { startIndex, endIndex }, or layout positions { start, end } such as contentBox.getTextSelectionGeometry().range. Without it the selected text of the open editor, otherwise the whole box.

      Returns Promise<void>

    • Sets where the caret is placed when editing of a box starts.

      Parameters

      • position: CursorPosition

        'start' or 'end'.

      Returns void

    • Sets the safe distance and returns the effective value; not changed unless it is a non-negative number. Boxes are clamped to the page when dragging, resizing, creating (addParagraph / addImage) and pasting.

      Parameters

      • value: number

        The distance in PDF points; negative or non-finite values leave it unchanged.

      • Optionaltype: SafeDistanceType

        'text', 'image', or 'common' (the default), which sets both text and image.

      Returns number

      The safe distance of type after the call.

    • Sets the text color of the whole box (or the selected text when the box is being edited).

      Parameters

      Returns Promise<void>

    • Opens an editing session for the current page (other pages open when drawn); fires contentEditModeStarted.

      Returns Promise<void>

      const { documentViewer } = instance.Core;
      const contentEditManager = documentViewer.getContentEditManager();
      contentEditManager.addEventListener('contentEditModeStarted', () => console.log('Editing page content'));
      await contentEditManager.startContentEditMode();
    • Stops editing the current box (committing is asynchronous; listen to contentBoxEditEnded to wait).

      Returns void

    • Shows / hides invisible characters in the box being edited (spaces as dots, paragraph ends as ¶, drawn on the annotation layer; only for the box being edited).

      Returns void

    • A listener that throws does not affect the others; the error is reported through logger.error.

      Type Parameters

      • K extends keyof ContentEditManagerEvents

      Parameters

      • name: K
      • Optionalargs: ContentEditManagerEvents[K]

      Returns void

    • Like trigger, but awaits the Promise returned by each listener in turn; a failing listener does not affect the others.

      Type Parameters

      • K extends keyof ContentEditManagerEvents

      Parameters

      • name: K
      • Optionalargs: ContentEditManagerEvents[K]

      Returns Promise<void>

    CursorPositions: { END: "end"; START: "start" }

    Where the caret is placed when editing of a box starts.

    Type Declaration

    • ReadonlyEND: "end"

      At the end of the text.

    • ReadonlySTART: "start"

      At the beginning of the text.

    Events: {
        CONTENT_BOX_ADDED: "contentBoxAdded";
        CONTENT_BOX_DELETED: "contentBoxDeleted";
        CONTENT_BOX_EDIT_ENDED: "contentBoxEditEnded";
        CONTENT_BOX_EDIT_STARTED: "contentBoxEditStarted";
        CONTENT_BOX_SELECTION_CHANGE: "contentEditSelectionChange";
        CONTENT_EDIT_ENDED: "contentEditModeEnded";
        CONTENT_EDIT_STARTED: "contentEditModeStarted";
    }

    Names of the events this class triggers.

    Type Declaration

    • ReadonlyCONTENT_BOX_ADDED: "contentBoxAdded"

      'contentBoxAdded': a box was added.

    • ReadonlyCONTENT_BOX_DELETED: "contentBoxDeleted"

      'contentBoxDeleted': a box was deleted.

    • ReadonlyCONTENT_BOX_EDIT_ENDED: "contentBoxEditEnded"

      'contentBoxEditEnded': the editor of a box was closed.

    • ReadonlyCONTENT_BOX_EDIT_STARTED: "contentBoxEditStarted"

      'contentBoxEditStarted': an editor was opened on a box.

    • ReadonlyCONTENT_BOX_SELECTION_CHANGE: "contentEditSelectionChange"

      'contentEditSelectionChange': the selected box, caret or text selection changed.

    • ReadonlyCONTENT_EDIT_ENDED: "contentEditModeEnded"

      'contentEditModeEnded': content edit mode was left.

    • ReadonlyCONTENT_EDIT_STARTED: "contentEditModeStarted"

      'contentEditModeStarted': content edit mode was entered.