PDF Web SDK Documentation

Comprehensive Guide for Developers: UI & SDK Integration, Configuration, and API Reference

PDF Web SDK
    Preparing search index...

    SDK Operations

    The sdk.IDocumentModel interface is the central hub for all document interactions. It combines state properties, core lifecycle operations, and a comprehensive set of editing commands.

    When you open a document using PdfSdk.openDocument or PdfSdk.openBlankDocument, you receive an instance of IDocumentModel.

    const document = await PdfSdk.openDocument({ file });
    // document implements IDocumentModel

    Optional open parameters include password, readOnly and path — the host-app file path of the document. The path is stored on the session (document.filePath) and is what the UI's Save writes back to, so the host can keep the document in its original location.

    Retrieve basic metadata and status information.

    console.log(`Title: ${document.title}`);
    console.log(`Pages: ${document.getNumPages()}`);
    console.log(`Modified: ${document.isModified}`);
    Method Description
    sdk.IDocumentModel.getNumPages Returns the total number of pages.
    sdk.IDocumentModel.getPage Retrieves a specific PageModel by index.
    sdk.IDocumentModel.getPages Returns an array of all PageModel objects.
    sdk.IDocumentModel.changeDocName Renames the document instance in memory.
    sdk.IDocumentModel.dispose Releases resources associated with the document.

    Export the document to various formats.

    // Export as a Blob
    const blob = await document.exportDocument({ as: 'blob' });

    // Export as a File
    const file = await document.exportDocument({ as: 'file', name: 'output.pdf' });

    After persisting an export yourself (headless save flow), you can mark the document as saved: sdk.IDocumentModel.clearDocumentHistory clears the undo/redo history so isModified/hasUndo reset, and document.filePath can be updated to the new location.

    Manage the structure of the document by adding, removing, or modifying pages.

    // Set the rotation of the first page to 90 degrees (page numbers are 1-based)
    await document.rotatePages({
    range: [1],
    angle: 90,
    });

    // Delete the second page
    await document.deletePages({
    range: [2],
    });
    Method Description
    sdk.IDocumentModel.deletePages Removes specified pages from the document.
    sdk.IDocumentModel.rotatePages Sets the rotation of specified pages (0/90/180/270).
    sdk.IDocumentModel.movePages Moves pages to a new location within the document.
    sdk.IDocumentModel.insertPagesFromFile Inserts pages from another PDF file.
    sdk.IDocumentModel.insertBlankPages Inserts new blank pages.
    sdk.IDocumentModel.insertDuplicatePages Duplicates existing pages.
    sdk.IDocumentModel.resizePages Changes the dimensions of specified pages.
    sdk.IDocumentModel.reversePage Reverses the order of pages in a range.
    sdk.IDocumentModel.replaceWithBlankPages Replaces content of specified pages with blank pages.
    sdk.IDocumentModel.replaceWithDuplicatePages Replaces pages with duplicates of other pages.
    sdk.IDocumentModel.replaceWithPagesFromFile Replaces pages with content from another PDF.
    sdk.IDocumentModel.changePagesBackground Sets a background color or image for pages.
    sdk.IDocumentModel.changePagesMargin Adjusts the margins of specified pages.

    Create, modify, and remove annotations (comments, shapes, stamps).

    // Add a sticky note (a PDF Text annotation) — AnnotsTypes is exported from '@avanquest/pdf-web-viewer/sdk'
    await document.createAnnotation({
    pageIndex: 0,
    params: {
    T: AnnotsTypes.TEXT,
    rect: [100, 100, 150, 150],
    contents: 'Please review',
    },
    });
    Method Description
    sdk.IDocumentModel.createAnnotation Creates a new annotation (sticky note, shape, ink, stamp, etc.).
    sdk.IDocumentModel.deleteAnnotations Removes existing annotations.
    sdk.IDocumentModel.changeAnnotationProperties Updates properties like color, opacity, or content.
    sdk.IDocumentModel.whiteoutPage Redacts a region of the page (permanently removes content).
    sdk.IDocumentModel.createWidgetAnnotation Creates form fields or other widget annotations.
    sdk.IDocumentModel.autoOrderAnnotation Automatically reorders annotations based on position.
    sdk.IDocumentModel.changeAnnotOrder Changes the Z-order of an annotation.
    sdk.IDocumentModel.orderAnnotation Moves an annotation to a specific index in the order.
    sdk.IDocumentModel.canChangeAnnotZOrder Checks if annotation Z-order can be changed.

    Modify the actual content of the PDF, including text and images.

    Method Description
    sdk.IDocumentModel.replaceText Finds and replaces text strings.
    sdk.IDocumentModel.createTextBlock Adds new text to the page.
    sdk.IDocumentModel.deleteTextBlocks Removes text blocks.
    sdk.IDocumentModel.editPageText Edits existing text content.
    sdk.IDocumentModel.editTextParagraphs Edits text at the paragraph level.
    sdk.IDocumentModel.insertChar Inserts a single character.
    sdk.IDocumentModel.transformTextBlock Moves, scales, or rotates a text block.
    sdk.IDocumentModel.changeFontAttributes Changes font family, size, style, color, and highlight / strikeout / underline colors.
    sdk.IDocumentModel.changeListStyle Modifies list formatting (bullets, numbering).
    sdk.IDocumentModel.changeParaAttrs Modifies paragraph attributes (alignment, etc).
    sdk.IDocumentModel.getTextAsTable Extracts text content structured as a table.
    sdk.IDocumentModel.canChangeTextBlockZOrder Checks if text block Z-order can be changed.
    Method Description
    sdk.IDocumentModel.insertImageContentElement Inserts an image file onto a page.
    sdk.IDocumentModel.cropImage Crops an image element on the page.
    sdk.IDocumentModel.deleteContentElements Removes specific content objects (images, text).
    sdk.IDocumentModel.copyContentElement Copies an element to the clipboard.
    sdk.IDocumentModel.pasteContentElement Pastes an element from the clipboard.
    sdk.IDocumentModel.copyTextBlock Copies a text block to the clipboard.
    sdk.IDocumentModel.pasteTextBlock Pastes a text block from the clipboard.
    sdk.IDocumentModel.changeElementMatrix Applies a transformation matrix to an element.
    sdk.IDocumentModel.changeElementOrder Changes the Z-order of content elements.
    sdk.IDocumentModel.createClip Creates a clipping path.
    sdk.IDocumentModel.deleteClip Removes a clipping path.
    sdk.IDocumentModel.transformClip Transforms a clipping path.
    sdk.IDocumentModel.transformContent Transforms generic content elements.
    sdk.IDocumentModel.canChangeElementZOrder Checks if element Z-order can be changed.

    Handle interactive forms and digital signatures.

    // Fill a form field
    await document.changeAcroformValue({
    field: 'ClientName',
    value: 'John Doe',
    });
    Method Description
    sdk.IDocumentModel.fillSignCreate Creates a Fill & Sign field.
    sdk.IDocumentModel.fillSignDelete Deletes a Fill & Sign field.
    sdk.IDocumentModel.fillSignUpdate Updates a Fill & Sign field.
    sdk.IDocumentModel.importAcroformsFdfData Imports form data from an FDF file.
    sdk.IDocumentModel.changeAcroformValue Sets the value of a form field.
    sdk.IDocumentModel.resetAcroformsFdfData Resets form fields to their default values.
    sdk.IDocumentModel.exportAcroformsFdfData Exports form data.
    sdk.IDocumentModel.exportFillSignAsset Exports a Fill & Sign asset (signature/initials).
    sdk.IDocumentModel.isESignAllowed Checks if the document allows e-signing.

    Add headers, footers, watermarks, and page numbers.

    // Add "Page 1 of n" numbers at the bottom center of every page
    await document.insertPageNumber({
    font: { family: 'Arial', size: 12, color: '#000000', style: EFontStyle.REGULAR },
    format: 'Page %1% of %2%',
    position: 4, // bottom center
    range: [`1-${document.getNumPages()}`],
    });
    Method Description
    sdk.IDocumentModel.insertHeader Adds a header to specified pages.
    sdk.IDocumentModel.deleteHeader Removes headers.
    sdk.IDocumentModel.insertPageNumber Adds automatic page numbering.
    sdk.IDocumentModel.deletePageNumber Removes page numbering.
    sdk.IDocumentModel.insertWatermark Adds a text or image watermark.
    sdk.IDocumentModel.deleteWatermark Removes watermarks.
    sdk.IDocumentModel.insertBatesNumbering Applies Bates numbering for legal documents.
    sdk.IDocumentModel.deleteBatesNumbering Removes Bates numbering.

    Manage bookmarks, attachments, and layers.

    // Add a bookmark
    await document.addBookmark({
    title: 'Section 1',
    pageIndex: 0,
    parentIndex: [],
    });
    Method Description
    sdk.IDocumentModel.addBookmark Adds a new bookmark to the outline.
    sdk.IDocumentModel.bookmarkAddBefore Adds a bookmark before a specific node.
    sdk.IDocumentModel.bookmarkAddAfter Adds a bookmark after a specific node.
    sdk.IDocumentModel.bookmarkAddChild Adds a child bookmark.
    sdk.IDocumentModel.deleteBookmark Removes a bookmark.
    sdk.IDocumentModel.deleteAllBookmarks Removes all bookmarks.
    sdk.IDocumentModel.moveBookmark Repositions a bookmark in the hierarchy.
    sdk.IDocumentModel.patchBookmark Updates bookmark properties.
    sdk.IDocumentModel.addAttachment Attaches a file to the PDF.
    sdk.IDocumentModel.deleteAttachment Removes an attachment.
    sdk.IDocumentModel.saveAttachment Saves an attachment to a file.
    sdk.IDocumentModel.exportAttachment Exports a specific attachment.
    sdk.IDocumentModel.exportAllAttachments Exports all attachments.
    sdk.IDocumentModel.setOCGroupState Controls the visibility of Optional Content Groups (Layers).
    sdk.IDocumentModel.updateLayerStates Updates the state of multiple layers.

    A claim names an operation the document went through — 'Ocr', 'Create.CombineFiles', 'Edit.Optimize.ReduceFileSize'. listDocumentClaims() returns all of them for a document, and the viewer passes the same list to every save and export callback, so a host can see what was done to the file it receives.

    The list is ordered oldest first — what the file brought with it, then what happened to it since, then the operation that produced it if it is an artefact — and deduplicated on first occurrence. Sort it yourself if you need a canonical form to compare or hash.

    const claims = await document.listDocumentClaims();
    console.log('Operations applied:', claims); // ['Edit.Text.Modify', 'Pages.Rotate']

    The list describes this document's bytes — not everything that happened in the session:

    • an operation that changes the document (rotate, edit text, watermark, redact) lands here;

    • an operation that produces a separate file (compress, sanitize, split, extract, OCR, convert) does not: the open document is exactly as it was, so its claims are unchanged. The claim belongs to the file that came out, and every such method hands the two back together, so there is nothing to compose:

      const { data, claims } = await document.compress(quality);
      // claims: ['Edit.Text.Modify', 'Pages.Rotate', 'Edit.Optimize.ReduceFileSize']
    • a document derived from another — a merge result, a signed revision, a PDF built from a URL or converted from an Office file on open ('Create.PDFFromOffice') — inherits its sources' claims, so the chain survives the reopen instead of restarting from the empty ledger the core gives every file it opens. Seed it with openDocument({ file, claims }): that is the only way in, and it is fixed for the document's life, because everything the document goes through afterwards is the core's to record.

    Manage document security and permissions.

    // Unlock a password-protected document
    await document.ownerAuthorization('password123');
    Method Description
    sdk.IDocumentModel.listDocumentClaims Returns every claim the document carries.
    sdk.IDocumentModel.ownerAuthorization Unlocks the document with an owner password.
    sdk.IDocumentModel.setSecurityPermissions Sets security permissions (requires owner access).
    sdk.IDocumentModel.isOperationPermitted Checks if a specific operation is allowed.
    sdk.IDocumentModel.applyRedactions Permanently applies redaction annotations.
    sdk.IDocumentModel.changeDocumentProperties Updates document metadata (Title, Author, etc.).

    Extract content and data from the document.

    Method Description
    sdk.IDocumentModel.extractImages Extracts all images from the document.
    sdk.IDocumentModel.extractImage Extracts a specific image.
    sdk.IDocumentModel.extractPages Extracts pages as a new document.
    sdk.IDocumentModel.exportComments Exports annotations/comments.
    sdk.IDocumentModel.convertToText Exports the text of all pages as a .txt file.
    sdk.IDocumentModel.convertToImages Exports every page as a PNG, zipped into one .zip file.
    sdk.IDocumentModel.extractStructuredContent Returns role-labelled, AI-friendly content as a plain object.
    sdk.IDocumentModel.convertToJson Exports the structured content as a pretty-printed .json file.
    sdk.IDocumentModel.convertToMarkdown Exports the structured content as a .md file for LLMs.
    sdk.IDocumentModel.documentExportStampAppearance Exports the appearance of a stamp.
    sdk.IDocumentModel.getMeasurementViewports Retrieves measurement viewports.
    sdk.IDocumentModel.createMeasurementCalibration Calibrates measurement tools.

    extractStructuredContent, convertToJson and convertToMarkdown run locally on the page content the viewer already loads: no server call, no OCR, no ML. Like convertToText and convertToImages, they are gated by the document's "copy content" permission, not by whether it has an owner password: when copying is allowed they run without it; when it is denied they throw PdfEditorAccessDeniedError until sdk.IDocumentModel.ownerAuthorization succeeds. Both converters return the file together with its claim ('Convert.PdfToJson' / 'Convert.PdfToMarkdown').

    Options ( sdk.IStructuredContentOptions): pages takes 0-based indexes (all pages by default; duplicates are ignored; an empty list or an out-of-range or non-integer index throws RangeError) and include takes the content kinds (unknown kinds are ignored; a list with no known kind throws RangeError). document.pdfVersion is the version the document is saved as, not the source file's header version.

    Progress and cancellation. All five local converters (convertToText, convertToImages, extractStructuredContent, convertToJson, convertToMarkdown) accept sdk.IConvertOptions: onProgress(completedPages, totalPages) is called after each page, and an aborted signal stops the work before the next page (the call rejects with an AbortError).

    const controller = new AbortController();
    const { data } = await document.convertToMarkdown({
    onProgress: (done, total) => console.log(`${Math.round((done / total) * 100)}%`),
    signal: controller.signal,
    });
    // convertToText / convertToImages take the same options as their last argument:
    await document.convertToText(undefined, { signal: controller.signal });

    Schema. The result ( sdk.IPdfStructuredContent, schemaVersion: '1.0') holds include (the effective kinds), optional document, outline and attachments, and the requested pages. Each page has a 1-based pageNumber, crop-box width/height, rotation, and its blocks in reading order. A block has a stable id (p{pageNumber}-b{n}), a role, the text, and a bbox of [x0, y0, x1, y1] in PDF points from the crop box's top-left corner.

    Roles (heuristic, from font sizes, position and repetition):

    • heading: carries a level from 1 to 6, ranked by font size; bold short lines and outline titles count too;
    • listItem: carries the source listMarker and ordered;
    • paragraph: everything else;
    • pageHeader, pageFooter, pageNumber: text repeated in the top/bottom 8% of pages, or a lone page number.

    Content kinds ( sdk.PdfContentKind). A kind that is not included is left out of the result (its key is absent). DEFAULT_CONTENT_KINDS is every kind except headersFooters.

    Kind Adds Default
    documentInfo document: title, author, dates, PDF version, page count on
    outline outline: the bookmark tree with target page numbers on
    text page blocks: headings, paragraphs and list items on
    headersFooters keeps pageHeader / pageFooter / pageNumber blocks off
    layout per-block lines with bbox and font (family, size, bold, italic) on
    annotations page annotations: comments and markup with author, dates, replies on
    links page links: URI or target page, plus the linked text on
    formFields page formFields: name, type, value, options, read-only, required on
    fillSign page fillSign: Fill & Sign items on
    attachments attachments: embedded file names, descriptions and sizes on
    import { PdfContentKind } from '@avanquest/pdf-web-viewer/sdk';

    // Compact text only: blocks without per-line layout
    const content = await document.extractStructuredContent({ include: [PdfContentKind.Text] });

    // Form data of the first two pages
    const { pages } = await document.extractStructuredContent({
    pages: [0, 1],
    include: [PdfContentKind.FormFields],
    });

    Markdown conventions. convertToMarkdown renders the same structured content:

    • YAML front matter with pages, plus title and author when present;
    • the outline as a ## Outline nested list, with → page N after each entry;
    • a <!-- page: N --> marker before each page;
    • #…###### headings, - / 1. list items (numeric markers keep their source number; letter and roman markers stay in the text after - ), and paragraphs with lines joined and dehyphenated;
    • **bold** / *italic* / ***bold italic*** emphasis per run of lines;
    • headers, footers and page numbers are dropped, or kept as <!-- header: … -->, <!-- footer: … --> and <!-- page number: … --> comments when headersFooters is included;
    • per-page Comments, Links, Form fields and Fill & Sign lists, and ## Attachments at the end;
    • PDF text never becomes raw HTML (< that would open a tag is written as &lt;), and only http(s), mailto, ftp, tel and relative URIs become links; other URIs (javascript:, data:, …) stay as plain text. Still sanitize the HTML if you render the Markdown in a page.
    const markdown = await (await document.convertToMarkdown()).data.text();
    

    RAG example. Split the blocks into chunks at each heading, and keep the page number and bbox so that answers can cite their source:

    const { pages } = await document.extractStructuredContent({ include: [PdfContentKind.Text] });

    const chunks: { title: string; text: string; sources: { pageNumber: number; bbox: number[] }[] }[] = [];
    for (const page of pages) {
    for (const block of page.blocks ?? []) {
    if (block.role === 'heading' || chunks.length === 0) {
    chunks.push({ title: block.role === 'heading' ? block.text : '', text: '', sources: [] });
    }
    const chunk = chunks[chunks.length - 1];
    chunk.text += `${block.text}\n`;
    chunk.sources.push({ pageNumber: page.pageNumber, bbox: block.bbox });
    }
    }
    // Embed chunk.text; answer with "page {pageNumber}" and highlight bbox in the viewer.

    Optimize the document for storage or distribution.

    Method Description
    sdk.IDocumentModel.compress Compresses the document to reduce file size.
    sdk.IDocumentModel.sanitize Removes sensitive information and metadata.
    sdk.IDocumentModel.removeMetadata Strips metadata from the document.

    Manage the history of changes.

    if (document.hasUndo) {
    await document.undo();
    }
    Method Description
    sdk.IDocumentModel.undo Reverts the last action.
    sdk.IDocumentModel.redo Reapplies the last undone action.
    sdk.IDocumentModel.changeDocumentHistory Modifies the history stack directly.
    sdk.IDocumentModel.doTransactionAsync Groups multiple operations into a single transaction.
    Property Type Description
    id string Unique identifier for the document instance.
    title string The document title from metadata.
    author string The document author.
    isModified boolean true if the document has unsaved changes.
    isSigned boolean true if the document contains digital signatures.
    security IDocumentSecurity Security settings and permissions.
    undoRedoHistory IDocumentHistory Information about the undo/redo stack.
    permissions string Raw permissions string.
    bookmarks PdfBookmark[] Document bookmarks structure.
    layers PdfLayer[] List of optional content groups (layers).
    attachments PdfAttachmentModel[] List of file attachments.
    Event Type Description
    onCommandExecuting Observable Emits before a command runs.
    onCommandExecuted Observable Emits after a command completes successfully.
    onCommandFailed Observable Emits if a command throws an error.
    onIsModifiedChanged Observable Emits when the modification state changes.
    onPagesChanged Observable Emits when pages are added, removed, or moved.
    onUndoRedoChanged Observable Emits when the history stack changes.
    onBookmarksChanged Observable Emits when bookmarks are modified.