@molecule/api-document-text-pdfjs

Provider bond · pdf · API (Node) · v1.1.1 · Apache-2.0

pdf.js document text provider for molecule.dev — extract the text of a PDF document in this process

npm install @molecule/api-document-text-pdfjs

npm · Source on GitHub · Implements @molecule/api-document-text

How it works

@molecule/api-document-text-pdfjs is a provider bond on the API (Node) side: it implements the pdf core interface (@molecule/api-document-text) with a concrete vendor or library behind it.

Your code calls the core; you wire this provider once at startup. Swapping vendors later is one line in that wiring, not a rewrite.

import { setProvider, extractDocumentText } from '@molecule/api-document-text'
import { provider as pdfjs } from '@molecule/api-document-text-pdfjs'

setProvider(pdfjs)
const doc = await extractDocumentText({ data: bytes })

Works with: @molecule/api-document-text

Reference

pdf.js document text provider for @molecule/api-document-text.

Extract the text of a PDF document in this process — pdf.js through unpdf, no vendor account, no browser, no network. Wire it with the core's setProvider and call extractDocumentText.

Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit src/index.ts JSDoc, not this file.

Quick Start

import { setProvider, extractDocumentText } from '@molecule/api-document-text'
import { provider as pdfjs } from '@molecule/api-document-text-pdfjs'

setProvider(pdfjs)
const doc = await extractDocumentText({ data: bytes })

Type

provider

Installation

npm install @molecule/api-document-text-pdfjs @molecule/api-document-text pdfjs-dist unpdf

API

Interfaces

PdfjsDocumentTextConfig

Options for createProvider(). Every field has a documented default.

interface PdfjsDocumentTextConfig {
  /**
   * Characters the joined `text` may hold before it is cut (`truncated: true`).
   * Defaults to 500,000 — the cap the hosted molecule.dev service mirrors.
   */
  maxTextChars?: number

  /**
   * The default page bound when a call passes no `options.maxPages`.
   * Defaults to 500 — the bound the hosted molecule.dev service mirrors.
   */
  maxPages?: number
}

Classes

PdfjsDocumentTextProvider

pdf.js document text provider. Every extraction is bounded: the joined text at maxTextChars, the returned pages at the call's maxPages (this provider's maxPages config is the default). The parse itself is bounded by the document bytes the caller hands in — keep the input sized (the hosted service caps it at 8 MB; an in-process bond has no such cap).

class PdfjsDocumentTextProvider implements DocumentTextProvider {
  readonly name = 'pdfjs'

  private readonly maxTextChars: number
  private readonly defaultMaxPages: number

  /**
   * Create the provider.
   *
   * @param config - Options; each falls back to its default.
   */
  constructor(config: PdfjsDocumentTextConfig = {}) {
    this.maxTextChars = config.maxTextChars ?? DOCUMENT_TEXT_LIMITS.maxTextChars
    this.defaultMaxPages = config.maxPages ?? DOCUMENT_TEXT_LIMITS.maxPages
  }

  /**
   * Extracts the text of one PDF document — no network.
   *
   * @param input - The document bytes, plus a password for an encrypted document.
   * @param options - Extract options (page bound, per-page texts).
   * @returns The extracted text.
   */
  async extract(
    input: { data: Uint8Array; password?: string },
    options?: DocumentTextOptions,
  ): Promise<DocumentTextResult> {
    if (!(input?.data instanceof Uint8Array) || input.data.length === 0) {
      fail('"data" must be non-empty PDF bytes (Uint8Array or Buffer).')
    }
    if (input.password !== undefined) {
      if (typeof input.password !== 'string' || input.password.length === 0) {
        fail('"password" must be non-empty text when given.')
      }
      if (input.password.length > DOCUMENT_TEXT_LIMITS.maxPasswordChars) {
        fail(
          `"password" is ${input.password.length} characters; the limit is ${DOCUMENT_TEXT_LIMITS.maxPasswordChars}.`,
        )
      }
    }
    const maxPages = options?.maxPages ?? this.defaultMaxPages
    if (
      typeof maxPages !== 'number' ||
      !Number.isInteger(maxPages) ||
      maxPages < 1 ||
      maxPages > DOCUMENT_TEXT_LIMITS.maxPages
    ) {
      fail(`"maxPages" must be an integer from 1 to ${DOCUMENT_TEXT_LIMITS.maxPages}.`)
    }
    const includePages = options?.includePages ?? true
    if (typeof includePages !== 'boolean') {
      fail('"includePages" must be a boolean.')
    }

    const pdf = await getDocumentProxy(
      input.data,
      input.password !== undefined ? { password: input.password } : undefined,
    )
    const { totalPages, text: pageTexts } = await extractText(pdf, { mergePages: false })

    const kept = pageTexts
      .slice(0, maxPages)
      .map((pageText, i) => ({ pageNumber: i + 1, text: pageText }))
    const joined = kept.map((p) => p.text).join('\n\n')
    const truncated = joined.length > this.maxTextChars
    const text = truncated ? joined.slice(0, this.maxTextChars) : joined

    let info: DocumentTextInfo | undefined
    try {
      const meta = await getMeta(pdf)
      const raw = meta?.info
      const picked: DocumentTextInfo = {}
      const keys = {
        title: 'Title',
        author: 'Author',
        subject: 'Subject',
        creator: 'Creator',
        producer: 'Producer',
      } as const
      for (const key of ['title', 'author', 'subject', 'creator', 'producer'] as const) {
        const value = metaString(raw?.[keys[key]])
        if (value !== undefined) picked[key] = value
      }
      if (Object.keys(picked).length > 0) info = picked
    } catch (_error) {
      // Metadata is optional; a document that refuses to open its info dict
      // still yields its text.
    }

    return {
      text,
      pages: includePages ? kept : [],
      pageCount: totalPages,
      truncated,
      pagesOmitted: totalPages - (includePages ? kept.length : 0),
      ...(info !== undefined ? { info } : {}),
    }
  }
}

Functions

createProvider(config)

Create a pdf.js document text provider.

function createProvider(config?: PdfjsDocumentTextConfig): DocumentTextProvider
  • config — Options; each falls back to its default.

Returns: A DocumentTextProvider backed by pdf.js in this process.

Constants

provider

The provider implementation (wire with the core's setProvider).

const provider: DocumentTextProvider

DOCUMENT_TEXT_LIMITS

Caps the provider applies (the hosted molecule.dev service mirrors them).

const DOCUMENT_TEXT_LIMITS: {
  readonly maxTextChars: 500000
  readonly maxPages: 500
  readonly maxPasswordChars: 256
}

Core Interface

Implements @molecule/api-document-text interface.

Bond Wiring

Setup function to register this provider with the core interface:

import { setProvider } from '@molecule/api-document-text'
import { provider } from '@molecule/api-document-text-pdfjs'

export function setupDocumentTextPdfjs(): void {
  setProvider(provider)
}

Injection Notes

Requirements

Peer dependencies:

  • @molecule/api-document-text >=1.0.0

Runtime Dependencies

  • @molecule/api-document-text

  • pdfjs-dist

  • unpdf

  • Text extraction is not OCR. A scanned or image-only page yields empty text — the words are pixels. Route those pages through the OCR service (@molecule/api-ocr) on rendered page images instead.

  • Encrypted documents need password; a wrong or missing password is a password error (PasswordException as the cause), never a silent empty result.

  • This process parses the bytes you hand it — keep the input sized. The hosted molecule.dev service caps a document at 8 MB; this bond has no cap of its own (an oversized document is your memory to spend).

  • Caps applied to the result: 500,000 characters of joined text (truncated), the returned pages at maxPages (default 500; pagesOmitted reports the rest — a bound never silently drops pages).

  • CJK and other non-Latin text decodes through the pdfjs-dist package this bond installs (its packed CMaps load from disk, not the network).

  • The extracted text is untrusted input: it is content parsed out of an arbitrary document.