pdfrx_web
    Preparing search index...

    Class PdfDocument

    Index
    formCalculationEnabled: boolean = true

    Whether setFormFieldValue recomputes dependent calculated fields (AFSimple_Calculate) after a change. Default true.

    permissions: PdfPermissions | null

    Encryption/permission info, or null if the document is not encrypted.

    sourceName: string

    Identifier of the document's source (e.g. uri%... or data%...); used in error messages.

    • Subscribes to a document event (see PdfDocumentEventMap) and returns an unsubscribe function.

      For missingFonts, queries already discovered while the document was opening are replayed to the new listener on a microtask, so late subscribers do not miss them.

      Type Parameters

      Parameters

      • event: E

        The event name to subscribe to.

      • listener: (event: PdfDocumentEventMap[E]) => void

        The callback to invoke when the value changes.

      Returns () => void

      A function that removes the listener.

    • Routes a cross-page synchronization batch to its arrangement pages and emits one annotationsChanged event after the applied operations. This is a notification batch, not a rollback transaction: a later failure can leave earlier PDFium mutations applied. Use page methods for independent local CRUD on one page.

      Parameters

      Returns Promise<void>

      The resulting Promise.

    • Creates an independent, fully materialized document from the current logical state. The caller owns the returned document and must dispose it.

      Pending page, outline, and Link edits are applied to the returned document, whose hasPendingChanges is therefore false. The source document on which this method is called is not materialized or otherwise modified; its pending state remains unchanged.

      catalog: "preserve" chooses the sole imported source as its base when possible and preserves that source's catalog. catalog: "rebuild" imports the arranged pages into a new empty PDF and omits objects not reachable from those pages, whether they originated in the source PDF or from subsequent edits. Rebuilding does not inherit existing physical document-level outlines, metadata, name trees, signatures, or AcroForm configuration. Pending logical page, outline, and Link edits are still applied to the returned document.

      Parameters

      Returns Promise<PdfDocument>

      The resulting Promise.

    • Creates page objects from declarative path, text, and image content in one worker round trip. The returned pages are not added to the document's logical pages arrangement; pass the desired final array to setPages.

      Coordinates and matrices use PDF page space: points, a bottom-left origin, and a y-axis pointing up. Fonts previously registered with PdfrxEngine.addFontData are embedded when a text run names their face. Image and emoji buffers are transferred to the worker and detached.

      Parameters

      Returns Promise<PdfPage[]>

      Newly created, currently unplaced pages in specification order.

      const document = await engine.createNew();
      const pages = await document.createPagesFromContents([{
      width: 595,
      height: 842,
      objects: [{
      kind: 'text',
      runs: [{ text: 'Quarterly report', fontFace: null, x: 48, y: 790, fontSize: 24 }],
      }],
      }]);
      document.setPages(pages);
      const pdfBytes = await document.encodePdf();

      Existing arranged pages remain unchanged until setPages is called, so generated pages can be inserted, reordered, or discarded synchronously. Multiple calls may accumulate source pages before one final arrangement.

    • Closes the document and releases its native handles (and the form environment). Idempotent; after disposal all page operations resolve to null/empty or reject. Runs the onDispose hook supplied at open time.

      Returns Promise<void>

      The resulting Promise.

    • Builds and applies a batch of convenient raw PDF-object edits.

      Raw targets and object numbers address the physical PDF object graph, not pending edits created by setPages, setPage, setOutline, or Link-annotation CRUD. Raw editing does not materialize those edits automatically. Call materialize explicitly before inspecting raw objects and constructing a related edit batch; otherwise the batch can target the old page tree, outline, annotations, or object numbers. Calling encodePdf first is also sufficient because it calls materialize.

      The callback only records operations. If it throws or rejects, the worker is never called and the document is unchanged. By default, the completed batch is then applied directly in one worker command. This avoids copying the PDF, but it is not a rollback boundary: if PDFium applies some operations and a later operation fails, the earlier changes can remain.

      Pass { atomic: true } for complete all-or-nothing behavior. That mode applies the batch to an independent materialized copy and makes this PdfDocument adopt the copy only after every operation succeeds. It keeps the original native document on failure, at the cost of copying and reloading the entire PDF (with time and peak-memory costs proportional to document size).

      Atomic success replaces the native document and reconstructs pages. Existing PdfPage references continue to address the same page indices, but callers should prefer reading document.pages again afterward.

      Raw edits do not describe their GUI impact. A viewer displaying this document must therefore be refreshed explicitly—for @pdfrx/viewer, use PdfrxViewer.refreshPages(), PdfrxViewer.refreshDocument(), or PdfrxViewer.reloadDocument() according to the scope and whether PDFium itself must be reconstructed.

      Parameters

      Returns Promise<void>

      The resulting Promise.

      await document.editRawObjects(
      (editor) => {
      const preferences = editor.createDictionary({
      HideToolbar: { kind: 'boolean', value: true },
      DisplayDocTitle: { kind: 'boolean', value: true },
      });
      editor.setDictionaryValue(
      editor.catalog(),
      'ViewerPreferences',
      preferences.reference,
      );
      },
      { atomic: true },
      );

      // The engine cannot infer which viewer caches the raw edit affects.
      await viewer.refreshDocument();
    • Serializes the current logical state to PDF bytes, including pending page, outline, and Link-annotation edits. In-place encoding writes them into this document with materialize first; copy and compact encoding materialize only a temporary document.

      Parameters

      Returns Promise<Uint8Array<ArrayBufferLike>>

      The resulting Promise.

    • Exports a versioned, structured-cloneable snapshot across the current arrangement. This stays on PdfDocument because snapshots can span pages; use PdfPage.loadAnnotations for a single-page read. A physical source page placed more than once is exported once, using its first arrangement page number, because all placements share the same stable ids and annotation state.

      Returns Promise<PdfAnnotationSnapshot>

      The resulting Promise.

    • Reads the document catalog as a structured value. Indirect references remain references, so cyclic PDF graphs are never expanded. Stream data is decoded; set includeRawStreamData to also receive its encoded bytes.

      This reads the physical PDF object graph in the worker, not pending logical state created by setPages, setPage, setOutline, or Link-annotation CRUD. When hasPendingChanges is true, call materialize first (or use in-place encodePdf) before interpreting affected page-tree dictionaries, page references, outlines, annotations, or other catalog data.

      Parameters

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

        Options that customize the operation.

      Returns Promise<
          {
              generationNumber: number;
              object: PdfRawObject
              | null;
              objectNumber: number;
          },
      >

      The resolved Promise.

    • Returns the current value of the named field, or undefined if it is not found.

      Parameters

      • name: string

        The name to look up.

      Returns Promise<string | undefined>

      The resolved Promise.

    • Reads one indirect PDF object as a structured value. Indirect references remain references, so cyclic PDF graphs are never expanded. Stream data is decoded; set includeRawStreamData to also receive its encoded bytes.

      Object numbers and references belong to the physical PDF object graph in the worker. Pending edits from setPages, setPage, setOutline, or Link-annotation edits exist only in logical state and can disagree with that graph. Call materialize first (or use in-place encodePdf) before reading affected objects or retaining object numbers for later edits.

      Parameters

      • objectNumber: number

        The object number.

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

        Options that customize the operation.

      Returns Promise<
          {
              generationNumber: number;
              object: PdfRawObject
              | null;
              objectNumber: number;
          },
      >

      The resolved Promise.

    • True if other is a PdfDocument backed by the same native handle. Note this compares handles, not document contents.

      Parameters

      • other: unknown

        The other value (unknown).

      Returns boolean

      Whether the condition is satisfied.

    • Loads all AcroForm fields across the document's currently loaded pages, grouped by fully-qualified name (widgets that share a name — e.g. a radio group — merge into one field). Returns an empty array for documents without a form. Reflects live values, including ones changed by setFormFieldValue or interactive editing.

      Returns Promise<PdfFormField[]>

      The resolved Promise.

    • Loads remaining pages in chunks of roughly loadUnitDurationMs worth of work. onPageLoadProgress can return false to stop loading further pages.

      Parameters

      • OptionalonPageLoadProgress: (loadedPageCount: number, totalPageCount: number) => boolean | Promise<boolean>

        The callback invoked when the corresponding event occurs.

      • loadUnitDurationMs: number = 250

        The loadUnitDurationMs value (number).

      Returns Promise<void>

      The resolved Promise.

    • Maps a zero-based physical page index in this document's native PDF to its current 1-based position in pages, or returns null when that physical page is not present.

      "Source" here means the page owned by this document before the lightweight arrangement in pages is applied. It is the same distinction exposed by PdfPage.sourceDocument and the internal PdfPage.sourcePageIndex: PDFium reports outlines, links, and form notifications against the native PDF page tree, while setPages creates a separate in-memory order of placement proxies.

      This is how destinations from the PDF itself — outline entries and internal links, which PDFium reports as physical page indices — are translated into page numbers callers can navigate to after setPages.

      Two caveats are inherent rather than fixable: a page placed twice can only resolve to one position (the first wins), and a page removed from the arrangement has no position at all, so destinations into it become null.

      Parameters

      • physicalPageIndex: number

        The 0-based physical page index.

      Returns number | null

      The resulting number or null.

    • Turns the Unicode contents of a FreeText spec into a stable PDF appearance. Call this after constructing the spec and before passing that same object to PdfPage.addAnnotation or PdfPage.updateAnnotation.

      This step is necessary because a PDF cannot simply inherit browser text rendering. Han characters can require different glyphs for Japanese, Simplified Chinese, Traditional Chinese, and Korean, while modern color emoji must be rasterized and embedded as image runs. The method also measures the resolved fonts and wraps the text to the annotation rectangle.

      The supplied spec is mutated in place: fontFace, appearanceLines, and appearanceRuns are replaced.

      language is optional. Kana and Hangul identify Japanese and Korean without a hint, and a browser automatically contributes navigator.languages / navigator.language. Pass an explicit BCP-47 value when Han-only text is ambiguous, when the document language should override the browser locale, or when running on a server. Server integrations commonly use document metadata, the signed-in user's locale, or a parsed Accept-Language preference.

      Parameters

      Returns Promise<void>

      The resulting Promise.

      const spec: PdfAnnotationSpec = {
      subtype: 'freeText',
      rect: { left: 40, bottom: 700, right: 260, top: 750 },
      // Han-only text is ambiguous without a language or browser locale.
      contents: '契約内容 😀',
      fontSize: 14,
      };

      await document.prepareFreeTextAppearance(spec, { language: 'ja' });
      await document.pages[0]!.addAnnotation(spec);

      In a browser whose locale represents the intended reader, the explicit option can be omitted:

      await document.prepareFreeTextAppearance(spec);
      

      The default services work in browsers and server runtimes: browser-native emoji is preferred, with a lazily downloaded, version-pinned Noto Emoji PNG fallback. @pdfrx/viewer also supplies its browser font resolver and exact Canvas measurement. Direct engine integrations can pass services for private or offline fonts/assets, persistent server caches, or a different text/emoji renderer.

      If subtype is not freeText, or rect/contents is absent, the method returns without changing the spec.

      For runtime behavior and complete customization examples, read the Text, language, and emoji appearance guide. To turn the analyzed runs into ordinary PDF page text and images, see the practical multilingual Unicode page-content pipeline.

    • Reloads page metadata (e.g. after document modification).

      Parameters

      • OptionalpageNumbersToReload: number[]

        The pageNumbersToReload value (number[]).

      Returns Promise<void>

      The resulting Promise.

    • Sets the value of the field identified by fully-qualified name, routed through the form-fill module so the widget appearance regenerates and the change is visible on the next render. When formCalculationEnabled is set (the default), dependent calculated fields (AFSimple_Calculate) are recomputed afterwards. Fires one formFieldsChanged event using the supplied mutation origin (api by default). The interpretation of value depends on the field type — see PdfFormFieldValue.

      Parameters

      Returns Promise<void>

      The resulting Promise.

    • Replaces a single slot (1-based), keeping every other page in place — the common case for GUI editing (doc.setPage(3, doc.pages[2]!.rotatedCW90())). Like setPages, this touches no PDF data.

      Setting a page that is already present elsewhere reuses its logical identity, so ID-based destinations cannot distinguish the two placements. Use PdfPage.duplicate; see that method for examples and details.

      Parameters

      • pageNumber: number

        The 1-based page number.

      • page: PdfPage

        The page to process.

      • options: PdfPageMutationOptions = {}

        Options that customize the operation.

      Returns void

    • Replaces the page arrangement — the one way to reorder, rotate, remove, duplicate, and import pages, and the cheap, synchronous counterpart to materialize.

      Nothing is sent to the worker and the PDF is not rebuilt: the pages are proxies (including those returned by PdfPage.rotatedTo) over pages that stay loaded, so reordering and rotating are immediate and free, and undo is just setting the previous array back. Page numbers are assigned automatically from the array order. This is what GUI page editing wants; call encodePdf (or materialize) when pending edits finally have to become a real PDF.

      Pages may come from other documents — those must stay open for as long as they are referenced. Page numbers are reassigned to match the new order, so callers can pass pages in any arrangement.

      Reusing the same PdfPage in more than one slot also reuses its logical identity, making ID-based destinations unable to distinguish those placements. Use PdfPage.duplicate when each occurrence must have its own destination identity; see that method for examples and details.

      Fires pageStatusChanged for every slot.

      Parameters

      Returns void

      const p = doc.pages;
      doc.setPages([p[2]!, p[0]!.rotatedCW90(), p[1]!]); // reorder + rotate
      doc.setPages(doc.pages.filter((x) => x !== p[2])); // remove
      doc.setPages([...doc.pages, ...other.pages]); // import from another doc
      await doc.encodePdf(); // now it becomes a PDF

      if pages is empty, or a page belongs to a disposed document.