@shuji-bonji/pdf-reader-mcp 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.ja.md +2 -2
  3. package/README.md +4 -3
  4. package/dist/index.js +27 -1
  5. package/dist/index.js.map +1 -1
  6. package/dist/services/actual-text-service.d.ts +99 -0
  7. package/dist/services/actual-text-service.d.ts.map +1 -0
  8. package/dist/services/actual-text-service.js +196 -0
  9. package/dist/services/actual-text-service.js.map +1 -0
  10. package/dist/services/content-stream-service.d.ts +70 -0
  11. package/dist/services/content-stream-service.d.ts.map +1 -0
  12. package/dist/services/content-stream-service.js +524 -0
  13. package/dist/services/content-stream-service.js.map +1 -0
  14. package/dist/services/pdfjs-service.d.ts +50 -5
  15. package/dist/services/pdfjs-service.d.ts.map +1 -1
  16. package/dist/services/pdfjs-service.js +145 -29
  17. package/dist/services/pdfjs-service.js.map +1 -1
  18. package/dist/services/struct-tree-service.d.ts +2 -61
  19. package/dist/services/struct-tree-service.d.ts.map +1 -1
  20. package/dist/services/struct-tree-service.js +6 -131
  21. package/dist/services/struct-tree-service.js.map +1 -1
  22. package/dist/services/struct-tree-walker.d.ts +93 -0
  23. package/dist/services/struct-tree-walker.d.ts.map +1 -0
  24. package/dist/services/struct-tree-walker.js +177 -0
  25. package/dist/services/struct-tree-walker.js.map +1 -0
  26. package/dist/tools/tier1/read-text.d.ts.map +1 -1
  27. package/dist/tools/tier1/read-text.js +3 -1
  28. package/dist/tools/tier1/read-text.js.map +1 -1
  29. package/dist/tools/tier1/search-text.d.ts.map +1 -1
  30. package/dist/tools/tier1/search-text.js +20 -10
  31. package/dist/tools/tier1/search-text.js.map +1 -1
  32. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -5,6 +5,71 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.9.2] - 2026-07-25
9
+
10
+ ### Documentation
11
+
12
+ - **The server now sends `instructions` on `initialize`.** A client loads them into its system
13
+ context before calling a single tool, which makes it the earliest point at which this server's
14
+ scope can be stated — earlier than any tool description.
15
+
16
+ What it states: **everything this server returns is an observation, not a verdict.** Extracted
17
+ text, tables, the structure tree, fonts and the *structure* of signature fields are evidence.
18
+ Whether a signature is mathematically valid, or whether a file conforms to anything, is
19
+ pdf-verify-mcp's answer. Where an observation here disagrees with a verdict there, the verdict
20
+ wins — this server reads the file, the validator applies the rules.
21
+
22
+ Behaviour is unchanged; no tool was added, removed or altered.
23
+
24
+ ## [0.9.1] - 2026-07-20
25
+
26
+ ### Fixed
27
+
28
+ - **🔴 `read_text` / `search_text` が `/ActualText` を解決するように**
29
+ ([#18](https://github.com/shuji-bonji/pdf-reader-mcp/issues/18))。0.9.0 は #15 を「明示」で閉じており、
30
+ **同一サーバ内で「この PDF に Difficult と書いてあるか」の答えが Yes/No に割れた**ままでした
31
+ (`extract_structured_text` は `Difficult`、`search_text("Difficult")` は 0 件)。本リリースで
32
+ ISO 32000-2 §14.9.4 が定める**置換テキストの 2 経路をどちらも解決**します。
33
+ - **経路 1 — 構造要素の `/ActualText`**(PDF 1.4)。`StructTreeRoot` を走査し、要素が持つ
34
+ マーク付きコンテンツ参照(`/Pg` + `/MCID`)を pdfjs の MCID に対応づけて置換します。
35
+ 要素に `/ActualText` があればその**サブツリー全体**が置換対象なので、内側の `/ActualText` には
36
+ 降りません(§14.9.4「a character substitution for the content **enclosed by**…」)。
37
+ - **経路 2 — マーク付きコンテンツの `/ActualText`**(PDF 1.5、`Span` の property list)。
38
+ pdfjs の `getTextContent({ includeMarkedContent: true })` は property list を捨てて `/MCID` しか
39
+ 渡さないため、**コンテンツストリームを自前で走査**します(新規 `content-stream-service`)。
40
+ この経路は**タグ無し文書にも現れる**ので、構造木経由では原理的に届きません。
41
+ - **位置合わせは出現順インデックス**です。スキャナは `BMC`/`BDC`/`EMC` の順序だけを記録し、
42
+ pdfjs が出すマーカーと 1:1 で対応させます(座標マッチ不要)。**数が食い違ったページは
43
+ 経路 2 を丸ごと諦めます** — 生グリフを返すのは 0.9.0 までの既知の挙動ですが、
44
+ ズレた位置に置換テキストを差し込むのは新しい壊れ方なので。`/Contents` 配列の結合と
45
+ Form XObject の `Do` 追跡は pdfjs と同じ順序に揃えてあります。
46
+ - **R-14.9.4-3 に対応**: 「consecutive な `/ActualText` の間に語区切りを入れてはならない」。
47
+ 行グルーピングより優先されます(条文の EXAMPLE がまさに行跨ぎのハイフネーションのため)。
48
+ - `search_text` の `note` は #15 の一律警告から、**実際に解決できなかったページ**を名指しし、
49
+ さらに**理由**(`encrypted` / `unaligned`)を伝えるものに変わりました。暗号化が理由のときは
50
+ 「他のツールでも解決できない」と言い切ります(`extract_structured_text` も pdf-lib 経由なので)。
51
+ 内部 API では `searchText()` が `unresolvedReason` を返します。
52
+ - 副次的な変更: 空文字の EOL 項目が行頭に余分な空白を生んでいたのを止めました
53
+ (`"…\n This is…"` → `"…\nThis is…"`)。
54
+ - **暗号化 PDF では両経路を無効化**します。§7.6.2 が暗号化するのは**文字列とストリームだけ**なので、
55
+ 構造木は普通に歩けてしまう一方、そこに入っている文字列は暗号文です。reader は pdf-lib を
56
+ `ignoreEncryption` で読む(=復号はしない)ため、`/ActualText` として返るのは RC4 の出力でした。
57
+ 実測: `PDF32000_2008.pdf`(オーナーパスワードのみ・ビューアでは普通に開く)は
58
+ **18026 件**の `/ActualText` を持ち、その全てが `&)ð` のようなバイト列。#18 はこれを
59
+ **本文の置換に使う**ので、1 ページ目の表題が
60
+ `Document management&)ð — 6±o Portable document format` になっていました。
61
+ `doc.isEncrypted` で `struct-tree-walker` の文字列読み取りと
62
+ コンテンツストリーム走査の両方を止めます(`extract_structured_text` /
63
+ `extract_tables` の `/ActualText`・`/Alt`・`/Lang` にも同じ穴があり、あわせて塞がります)。
64
+ - 新フィクスチャ `actual-text-span.pdf`(**タグ無し**・§14.9.4 EXAMPLE の「Druk-/ker → Drucker」と
65
+ 連続 ActualText の「Bäcke-/rei → Bäckerei」)と `encrypted-actualtext.pdf`
66
+ (RC4 40-bit・`/ActualText` が暗号文。pdf-lib では作れないので手書き)、
67
+ ST-8・ST-10〜ST-15、`tests/tier1/actual-text-service.test.ts` を追加。
68
+ - `searchText()` の戻り値が `SearchMatch[]` → `{ matches, unresolvedPages, unresolvedReason }`
69
+ になりました(内部 API)。
70
+ - 構造木の走査部分を `struct-tree-walker.ts` に分離(pdfjs に依存しない部分だけを切り出し、
71
+ `actual-text-service` から循環インポートなしに使うため)。`struct-tree-service` は再エクスポートします。
72
+
8
73
  ## [0.9.0] - 2026-07-19
9
74
 
10
75
  > spec ⇄ reader 相互チェック(2026-07-19。`Document-Note/mcps/PDFfamily/reviews/` の 2 レポート)で
package/README.ja.md CHANGED
@@ -30,8 +30,8 @@ PDF 内部構造解析に特化した MCP (Model Context Protocol) サーバー
30
30
  | ---------------- | ----------------------------------------------------- |
31
31
  | `get_page_count` | ページ数の軽量取得 |
32
32
  | `get_metadata` | メタデータ抽出(タイトル、著者、PDF版、タグ有無等) |
33
- | `read_text` | テキスト抽出(Y座標ベースの読み順保持。`split_columns: 2 \| 3` で **タグなし** 多カラム PDF、`compact_whitespace` で 帳票 の U+3000 連続空白を畳み込み)。**生グリフ**を返すため、タグ付き PDF の本文は論理順 + `/ActualText` 解決の `extract_structured_text` を推奨 |
34
- | `search_text` | 全文検索(前後コンテキスト付き)。グリフレベルの検索のため `/ActualText` 置換で運ばれる語はヒットしない(タグ付き文書で 0 件のときは `note` で案内) |
33
+ | `read_text` | テキスト抽出(Y座標ベースの読み順保持。`split_columns: 2 \| 3` で **タグなし** 多カラム PDF、`compact_whitespace` で 帳票 の U+3000 連続空白を畳み込み)。`/ActualText` 置換(§14.9.4。構造要素・`Span` マーク付きコンテンツの両経路)を解決。**論理順**が要るタグ付き PDF の本文は `extract_structured_text` を推奨 |
34
+ | `search_text` | 全文検索(前後コンテキスト付き)。`read_text` と同じテキスト(`/ActualText` 解決済み)を検索するため、ヒット=読み手に見えている語(位置合わせできなかったページがあれば `note` で名指し) |
35
35
  | `read_images` | 画像抽出(base64、メタデータ付き) |
36
36
  | `read_url` | URLからリモートPDFを取得して処理 |
37
37
  | `summarize` | 全体概要レポート(メタデータ + テキスト + 画像数) |
package/README.md CHANGED
@@ -30,8 +30,8 @@ While typical PDF MCP servers are thin wrappers for text extraction, this projec
30
30
  | ---------------- | -------------------------------------------------------- |
31
31
  | `get_page_count` | Lightweight page count retrieval |
32
32
  | `get_metadata` | Full metadata extraction (title, author, PDF version...) |
33
- | `read_text` | Text extraction with Y-coordinate reading order (opt-in `split_columns: 2 \| 3` for untagged multi-column PDFs, `compact_whitespace` for Japanese forms). Emits **raw glyphs** — for tagged PDFs prefer `extract_structured_text`, which returns logical content order and resolves `/ActualText` |
34
- | `search_text` | Full-text search with surrounding context. Glyph-level: text carried in `/ActualText` replacements will not match (a `note` says so when a tagged document yields zero matches) |
33
+ | `read_text` | Text extraction with Y-coordinate reading order (opt-in `split_columns: 2 \| 3` for untagged multi-column PDFs, `compact_whitespace` for Japanese forms). Resolves `/ActualText` replacements (§14.9.4, both the structure-element and the `Span` marked-content path). For **logical** order in tagged PDFs, prefer `extract_structured_text` |
34
+ | `search_text` | Full-text search with surrounding context. Searches the same text `read_text` returns, `/ActualText` included, so a hit means what a reader sees (a `note` names any page whose marked content could not be aligned) |
35
35
  | `read_images` | Image extraction as base64 with metadata |
36
36
  | `read_url` | Fetch and process remote PDFs from URLs |
37
37
  | `summarize` | Quick overview report (metadata + text + image count) |
@@ -207,7 +207,8 @@ extract_tables({ file_path: "/path/to/kaisei-tsutatsu.pdf", pages: "1" })
207
207
  A table that continues across a page break is reported as ONE table —
208
208
  `pages` is an array (e.g. `## Table 3 — Pages 5–7`), and a table touching
209
209
  the requested `pages` range is returned whole. Cell text honours
210
- `/ActualText` replacements. Untagged PDFs return an empty result with a
210
+ `/ActualText` replacements (as do `read_text` and `search_text` since #18).
211
+ Untagged PDFs return an empty result with a
211
212
  `note` recommending the column-aware fallback below.
212
213
 
213
214
  ### Read Untagged Multi-Column PDF
package/dist/index.js CHANGED
@@ -16,10 +16,36 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
16
16
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
17
17
  import { SERVER_NAME, SERVER_VERSION } from './constants.js';
18
18
  import { registerAllTools } from './tools/index.js';
19
+ /**
20
+ * `initialize` の応答としてクライアントへ返す説明(family 規約: PDFfamily specs/06)。
21
+ *
22
+ * **reader の出力は「観測」であって「判定」ではない。** ツール説明にも書いてあるが、
23
+ * `instructions` はクライアントのシステムコンテキストに直接載るため、ツールを 1 つも
24
+ * 呼ばないうちに読まれる — 射程を伝える位置としてはここが最も早い。
25
+ * 先例は pdf-spec-mcp v0.4.5(Issue #13)。
26
+ */
27
+ const INSTRUCTIONS = `This server OBSERVES what is inside a PDF. It does not judge whether it is correct.
28
+
29
+ Everything it returns is an observation: extracted text, tables, the structure tree, fonts,
30
+ annotations, images, and the *structure* of signature fields. Treat the output as evidence,
31
+ never as a verdict.
32
+
33
+ What it does NOT do:
34
+ - No cryptographic verification. inspect_signatures reads signature fields structurally and
35
+ says so explicitly; whether a signature is mathematically valid is pdf-verify-mcp's answer
36
+ (verify_signatures / verify_integrity).
37
+ - No conformance judgement. validate_tagged / validate_metadata are deprecated in favour of
38
+ pdf-verify-mcp's validate_conformance, which delegates to veraPDF.
39
+ - No incremental-update history, no object-ID-to-coordinate mapping, no OCR.
40
+
41
+ Where an observation here and a verdict from pdf-verify-mcp disagree, the verdict wins —
42
+ this server reads the file, the validator applies the rules.
43
+
44
+ For what the specification *requires*, ask pdf-spec-mcp. This server never quotes ISO clauses.`;
19
45
  const server = new McpServer({
20
46
  name: SERVER_NAME,
21
47
  version: SERVER_VERSION,
22
- });
48
+ }, { instructions: INSTRUCTIONS });
23
49
  // Register all tools
24
50
  registerAllTools(server);
25
51
  // Start the server with stdio transport
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AACA;;;;;GAKG;AAEH,8CAA8C;AAC9C,sEAAsE;AACtE,sEAAsE;AACtE,MAAM,mBAAmB,GAAG,OAAO,CAAC,GAAG,CAAC;AACxC,MAAM,oBAAoB,GAAG,OAAO,CAAC,IAAI,CAAC;AAC1C,OAAO,CAAC,GAAG,GAAG,CAAC,GAAG,IAAe,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,EAAE,GAAG,IAAI,CAAC,CAAC;AACtE,OAAO,CAAC,IAAI,GAAG,CAAC,GAAG,IAAe,EAAE,EAAE,CAAC,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,GAAG,IAAI,CAAC,CAAC;AAExE,OAAO,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AACpE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AACjF,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AAEpD,MAAM,MAAM,GAAG,IAAI,SAAS,CAAC;IAC3B,IAAI,EAAE,WAAW;IACjB,OAAO,EAAE,cAAc;CACxB,CAAC,CAAC;AAEH,qBAAqB;AACrB,gBAAgB,CAAC,MAAM,CAAC,CAAC;AAEzB,wCAAwC;AACxC,KAAK,UAAU,IAAI;IACjB,MAAM,SAAS,GAAG,IAAI,oBAAoB,EAAE,CAAC;IAC7C,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IAChC,OAAO,CAAC,KAAK,CAAC,GAAG,WAAW,KAAK,cAAc,oBAAoB,CAAC,CAAC;AACvE,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC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MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IAChC,OAAO,CAAC,KAAK,CAAC,GAAG,WAAW,KAAK,cAAc,oBAAoB,CAAC,CAAC;AACvE,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;IACrB,OAAO,CAAC,KAAK,CAAC,cAAc,EAAE,KAAK,CAAC,CAAC;IACrC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC"}
@@ -0,0 +1,99 @@
1
+ /**
2
+ * `/ActualText` resolution for coordinate-order text extraction (#18).
3
+ *
4
+ * ISO 32000-2 §14.9.4:
5
+ *
6
+ * > The ActualText value **shall** be used as a **replacement, not a
7
+ * > description**, for the content, providing text that is equivalent to what a
8
+ * > person would see when viewing the content. The value of ActualText is a
9
+ * > character substitution for the content enclosed by the structure element or
10
+ * > marked-content sequence.
11
+ *
12
+ * A text-extracting tool that ignores it therefore returns text that is *not*
13
+ * equivalent to what a person sees — which is what #15 documented and #18 fixes.
14
+ *
15
+ * Replacement text lives in two places, and this module resolves both:
16
+ *
17
+ * 1. **structure element** `/ActualText` (PDF 1.4) — found by walking
18
+ * `StructTreeRoot` and mapping the element's marked-content references
19
+ * (`/Pg` + `/MCID`) onto the MCIDs pdfjs reports;
20
+ * 2. **marked-content sequence** `/ActualText` (PDF 1.5, a `Span` property
21
+ * list) — found by scanning the content stream, because pdfjs drops
22
+ * property lists (see `content-stream-service`). This one occurs in
23
+ * **untagged** documents too, so path 1 alone cannot reach it.
24
+ *
25
+ * ## How the two streams are aligned
26
+ *
27
+ * The scanner records `BMC` / `BDC` / `EMC` in content-stream order; pdfjs emits
28
+ * one marker per such operator, in the same order. So the *n*-th begin marker
29
+ * from pdfjs is the *n*-th begin event from the scan — no coordinate matching.
30
+ * When the two disagree on how many there are, the alignment is unknown and
31
+ * path 2 is abandoned for that page (path 1 is unaffected: it keys off MCIDs
32
+ * pdfjs supplies itself). Returning raw glyphs is the old, documented
33
+ * behaviour; attaching replacement text to the wrong glyphs would be new damage.
34
+ */
35
+ import type { PDFDocument as PdfLibDocument } from 'pdf-lib';
36
+ /** A pdfjs text item, reduced to what reading order and joining need. */
37
+ export interface PositionedText {
38
+ str: string;
39
+ /** `[a, b, c, d, e, f]` — `e`/`f` are the X/Y of the item's origin. */
40
+ transform: number[];
41
+ width: number;
42
+ height: number;
43
+ /**
44
+ * Set when this item is `/ActualText` standing in for the glyphs it replaced.
45
+ * `adjacentToPrevious` records that the sequence it came from directly
46
+ * followed another one that also had `/ActualText`, which is the condition
47
+ * §14.9.4's "no word break" requirement turns on — and which is no longer
48
+ * recoverable once the items have been sorted into reading order.
49
+ */
50
+ replacement?: {
51
+ adjacentToPrevious: boolean;
52
+ };
53
+ }
54
+ /** A pdfjs `getTextContent({ includeMarkedContent: true })` item. */
55
+ interface RawItem {
56
+ type?: string;
57
+ id?: string | null;
58
+ tag?: string;
59
+ str?: string;
60
+ width?: number;
61
+ height?: number;
62
+ transform?: number[];
63
+ hasEOL?: boolean;
64
+ }
65
+ /**
66
+ * Map every MCID that a structure element with `/ActualText` owns to that text.
67
+ *
68
+ * The element's replacement covers everything it encloses, descendants
69
+ * included, so the walk stops descending once it finds an `/ActualText`: an
70
+ * inner one would be substituting for content the outer one has already
71
+ * replaced. Keyed by pdfjs's marked-content id (`p7R_mc3`) so no page bookkeeping
72
+ * is needed at lookup time.
73
+ */
74
+ export declare function buildStructActualTextMap(doc: PdfLibDocument): Map<string, string>;
75
+ /**
76
+ * Fold a page's pdfjs items into positioned text, substituting `/ActualText`.
77
+ *
78
+ * A replaced region collapses to a single item carrying the replacement string,
79
+ * placed at the first glyph it replaced and as wide as the region — so the
80
+ * caller's Y/X sort still puts it where the reader sees it. A region containing
81
+ * no glyphs at all (replacement text over a Figure, say) inherits the previous
82
+ * item's position, which is the only ordering information available.
83
+ *
84
+ * @param structActualText MCID → replacement, from `buildStructActualTextMap`.
85
+ * @param spanActualText Begin-marker index → replacement, from the content
86
+ * stream scan. Undefined when alignment is unknown.
87
+ */
88
+ export declare function foldActualText(rawItems: RawItem[], structActualText: ReadonlyMap<string, string>, spanActualText: ReadonlyMap<number, string> | undefined): PositionedText[];
89
+ /**
90
+ * Build the `Span`-level replacement map for one page, or `undefined` when the
91
+ * content stream and pdfjs disagree about how many marked-content sequences the
92
+ * page has (see the module comment for why that is fatal to the alignment).
93
+ *
94
+ * @param pageIndex 0-based.
95
+ * @param pdfjsBeginCount How many begin markers pdfjs reported for the page.
96
+ */
97
+ export declare function buildSpanActualTextMap(doc: PdfLibDocument, pageIndex: number, pdfjsBeginCount: number): Map<number, string> | undefined;
98
+ export {};
99
+ //# sourceMappingURL=actual-text-service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"actual-text-service.d.ts","sourceRoot":"","sources":["../../src/services/actual-text-service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAEH,OAAO,KAAK,EAAE,WAAW,IAAI,cAAc,EAAE,MAAM,SAAS,CAAC;AAK7D,yEAAyE;AACzE,MAAM,WAAW,cAAc;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,uEAAuE;IACvE,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf;;;;;;OAMG;IACH,WAAW,CAAC,EAAE;QAAE,kBAAkB,EAAE,OAAO,CAAA;KAAE,CAAC;CAC/C;AAED,qEAAqE;AACrE,UAAU,OAAO;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,EAAE,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACnB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;IACrB,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB;AAED;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CAAC,GAAG,EAAE,cAAc,GAAG,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAkBjF;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,cAAc,CAC5B,QAAQ,EAAE,OAAO,EAAE,EACnB,gBAAgB,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,EAC7C,cAAc,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,GACtD,cAAc,EAAE,CA0GlB;AAED;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CACpC,GAAG,EAAE,cAAc,EACnB,SAAS,EAAE,MAAM,EACjB,eAAe,EAAE,MAAM,GACtB,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,CAYjC"}
@@ -0,0 +1,196 @@
1
+ /**
2
+ * `/ActualText` resolution for coordinate-order text extraction (#18).
3
+ *
4
+ * ISO 32000-2 §14.9.4:
5
+ *
6
+ * > The ActualText value **shall** be used as a **replacement, not a
7
+ * > description**, for the content, providing text that is equivalent to what a
8
+ * > person would see when viewing the content. The value of ActualText is a
9
+ * > character substitution for the content enclosed by the structure element or
10
+ * > marked-content sequence.
11
+ *
12
+ * A text-extracting tool that ignores it therefore returns text that is *not*
13
+ * equivalent to what a person sees — which is what #15 documented and #18 fixes.
14
+ *
15
+ * Replacement text lives in two places, and this module resolves both:
16
+ *
17
+ * 1. **structure element** `/ActualText` (PDF 1.4) — found by walking
18
+ * `StructTreeRoot` and mapping the element's marked-content references
19
+ * (`/Pg` + `/MCID`) onto the MCIDs pdfjs reports;
20
+ * 2. **marked-content sequence** `/ActualText` (PDF 1.5, a `Span` property
21
+ * list) — found by scanning the content stream, because pdfjs drops
22
+ * property lists (see `content-stream-service`). This one occurs in
23
+ * **untagged** documents too, so path 1 alone cannot reach it.
24
+ *
25
+ * ## How the two streams are aligned
26
+ *
27
+ * The scanner records `BMC` / `BDC` / `EMC` in content-stream order; pdfjs emits
28
+ * one marker per such operator, in the same order. So the *n*-th begin marker
29
+ * from pdfjs is the *n*-th begin event from the scan — no coordinate matching.
30
+ * When the two disagree on how many there are, the alignment is unknown and
31
+ * path 2 is abandoned for that page (path 1 is unaffected: it keys off MCIDs
32
+ * pdfjs supplies itself). Returning raw glyphs is the old, documented
33
+ * behaviour; attaching replacement text to the wrong glyphs would be new damage.
34
+ */
35
+ import { scanPageMarkedContent } from './content-stream-service.js';
36
+ import { collectContentRefs, walkStructTree } from './struct-tree-walker.js';
37
+ /**
38
+ * Map every MCID that a structure element with `/ActualText` owns to that text.
39
+ *
40
+ * The element's replacement covers everything it encloses, descendants
41
+ * included, so the walk stops descending once it finds an `/ActualText`: an
42
+ * inner one would be substituting for content the outer one has already
43
+ * replaced. Keyed by pdfjs's marked-content id (`p7R_mc3`) so no page bookkeeping
44
+ * is needed at lookup time.
45
+ */
46
+ export function buildStructActualTextMap(doc) {
47
+ const map = new Map();
48
+ const roots = walkStructTree(doc);
49
+ if (!roots)
50
+ return map;
51
+ const visit = (element) => {
52
+ if (element.actualText !== null) {
53
+ const refs = collectContentRefs(element);
54
+ for (const ref of refs) {
55
+ map.set(`p${ref.pageObjNum}R_mc${ref.mcid}`, element.actualText);
56
+ }
57
+ // Do not descend: the whole subtree is what this text replaces.
58
+ return;
59
+ }
60
+ for (const child of element.children)
61
+ visit(child);
62
+ };
63
+ for (const root of roots)
64
+ visit(root);
65
+ return map;
66
+ }
67
+ /**
68
+ * Fold a page's pdfjs items into positioned text, substituting `/ActualText`.
69
+ *
70
+ * A replaced region collapses to a single item carrying the replacement string,
71
+ * placed at the first glyph it replaced and as wide as the region — so the
72
+ * caller's Y/X sort still puts it where the reader sees it. A region containing
73
+ * no glyphs at all (replacement text over a Figure, say) inherits the previous
74
+ * item's position, which is the only ordering information available.
75
+ *
76
+ * @param structActualText MCID → replacement, from `buildStructActualTextMap`.
77
+ * @param spanActualText Begin-marker index → replacement, from the content
78
+ * stream scan. Undefined when alignment is unknown.
79
+ */
80
+ export function foldActualText(rawItems, structActualText, spanActualText) {
81
+ const out = [];
82
+ /** How many marked-content sequences are currently open. */
83
+ let depth = 0;
84
+ let beginIndex = -1;
85
+ /** The replacement currently being accumulated, if any. */
86
+ let open = null;
87
+ /** True while nothing but the closing of a replacement has been emitted. */
88
+ let lastEmittedWasReplacement = false;
89
+ let sawTextSinceReplacement = true;
90
+ let lastTransform = null;
91
+ let lastHeight = 0;
92
+ const closeOpen = () => {
93
+ if (!open)
94
+ return;
95
+ const transform = open.transform ?? lastTransform ?? [1, 0, 0, 1, 0, 0];
96
+ const width = open.transform ? Math.max(0, open.maxX - open.minX) : 0;
97
+ out.push({
98
+ str: open.text,
99
+ transform,
100
+ width,
101
+ height: open.height || lastHeight,
102
+ replacement: {
103
+ // §14.9.4: "If each of two (or more) consecutive structure or
104
+ // marked-content sequences has an ActualText entry, they shall be
105
+ // treated as if no word break is present between them." Consecutive
106
+ // means nothing came between — hence `sawTextSinceReplacement`.
107
+ adjacentToPrevious: lastEmittedWasReplacement && !sawTextSinceReplacement,
108
+ },
109
+ });
110
+ lastEmittedWasReplacement = true;
111
+ sawTextSinceReplacement = false;
112
+ lastTransform = transform;
113
+ open = null;
114
+ };
115
+ for (const item of rawItems) {
116
+ const type = item.type;
117
+ if (type === 'beginMarkedContent' || type === 'beginMarkedContentProps') {
118
+ beginIndex++;
119
+ // Already inside a replacement? The outer one covers this too: §14.9.4
120
+ // makes ActualText a substitution for everything the sequence encloses.
121
+ const replacementText = open
122
+ ? undefined
123
+ : (spanActualText?.get(beginIndex) ??
124
+ (item.id ? structActualText.get(item.id) : undefined));
125
+ if (replacementText !== undefined) {
126
+ open = { text: replacementText, depth, transform: null, minX: 0, maxX: 0, height: 0 };
127
+ }
128
+ depth++;
129
+ continue;
130
+ }
131
+ if (type === 'endMarkedContent') {
132
+ if (depth > 0)
133
+ depth--;
134
+ if (open && depth === open.depth)
135
+ closeOpen();
136
+ continue;
137
+ }
138
+ if (type !== undefined)
139
+ continue; // an unrecognised marker
140
+ // A text item.
141
+ const transform = item.transform;
142
+ const width = item.width ?? 0;
143
+ const height = item.height ?? 0;
144
+ if (open) {
145
+ // Swallowed by the replacement, but its geometry positions it.
146
+ if (transform) {
147
+ if (!open.transform) {
148
+ open.transform = transform;
149
+ open.minX = transform[4];
150
+ open.maxX = transform[4] + width;
151
+ open.height = height;
152
+ }
153
+ else {
154
+ open.maxX = Math.max(open.maxX, transform[4] + width);
155
+ }
156
+ }
157
+ continue;
158
+ }
159
+ const str = item.hasEOL ? '' : (item.str ?? '');
160
+ if (!transform)
161
+ continue;
162
+ lastTransform = transform;
163
+ if (height)
164
+ lastHeight = height;
165
+ if (!str)
166
+ continue;
167
+ out.push({ str, transform, width, height });
168
+ lastEmittedWasReplacement = false;
169
+ sawTextSinceReplacement = true;
170
+ }
171
+ closeOpen();
172
+ return out;
173
+ }
174
+ /**
175
+ * Build the `Span`-level replacement map for one page, or `undefined` when the
176
+ * content stream and pdfjs disagree about how many marked-content sequences the
177
+ * page has (see the module comment for why that is fatal to the alignment).
178
+ *
179
+ * @param pageIndex 0-based.
180
+ * @param pdfjsBeginCount How many begin markers pdfjs reported for the page.
181
+ */
182
+ export function buildSpanActualTextMap(doc, pageIndex, pdfjsBeginCount) {
183
+ const events = scanPageMarkedContent(doc, pageIndex);
184
+ if (!events)
185
+ return pdfjsBeginCount === 0 ? new Map() : undefined;
186
+ const begins = events.filter((e) => e.kind === 'begin');
187
+ if (begins.length !== pdfjsBeginCount)
188
+ return undefined;
189
+ const map = new Map();
190
+ begins.forEach((event, index) => {
191
+ if (event.actualText !== undefined)
192
+ map.set(index, event.actualText);
193
+ });
194
+ return map;
195
+ }
196
+ //# sourceMappingURL=actual-text-service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"actual-text-service.js","sourceRoot":"","sources":["../../src/services/actual-text-service.ts"],"names":[],"mappings":"AAA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AAO,SAAS,CAAC;IAExD,MAAM,GAAG,GAAG,IAAI,GAAG,EAAkB,CAAC;IACtC,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;QAC9B,IAAI,KAAK,CAAC,UAAU,KAAK,SAAS;YAAE,GAAG,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,UAAU,CAAC,CAAC;IACvE,CAAC,CAAC,CAAC;IACH,OAAO,GAAG,CAAC;AACb,CAAC"}
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Content-stream scanner for marked-content property lists (#18).
3
+ *
4
+ * ISO 32000-2 §14.9.4 puts replacement text in exactly two places:
5
+ *
6
+ * 1. a **structure element**'s `/ActualText` (PDF 1.4), reachable from the
7
+ * structure tree — see `struct-tree-service`;
8
+ * 2. a **marked-content sequence**'s `/ActualText` (PDF 1.5), carried in the
9
+ * property list of a `Span` tag — which lives only in the content stream.
10
+ *
11
+ * Case 2 occurs in **untagged** documents too, so no amount of structure-tree
12
+ * work reaches it, and pdfjs does not hand it over either: its
13
+ * `getTextContent({ includeMarkedContent: true })` reports where each
14
+ * marked-content sequence begins and ends and keeps `/MCID`, but discards the
15
+ * rest of the property list (pdfjs-dist 4.x, `case OPS.beginMarkedContentProps`
16
+ * in `getTextContent` reads `args[1].get("MCID")` and nothing else).
17
+ *
18
+ * So the property lists have to be read from the content stream directly. This
19
+ * scanner does **not** decode glyphs — it only records the *order* of
20
+ * `BMC` / `BDC` / `EMC` operators. That order is 1:1 with the markers pdfjs
21
+ * emits, so the two streams are aligned by index rather than by coordinate,
22
+ * which is what makes the approach cheap to verify: if the counts differ, the
23
+ * alignment is known to be wrong and the caller falls back instead of
24
+ * corrupting the text.
25
+ *
26
+ * Two ordering rules are mirrored from pdfjs so the indices line up:
27
+ *
28
+ * - a page's `/Contents` array is one stream, concatenated with white space
29
+ * between the parts (§7.8.2: the division may occur only between lexical
30
+ * tokens);
31
+ * - `Do` on a **Form** XObject is walked inline at that point, using the
32
+ * form's own `/Resources` and falling back to the parent's — exactly what
33
+ * pdfjs's `case OPS.paintXObject` does.
34
+ */
35
+ import { type PDFDocument } from 'pdf-lib';
36
+ /**
37
+ * One `BMC` / `BDC` / `EMC` operator, in content-stream order.
38
+ *
39
+ * `EMC` carries no data; it is recorded so that nesting can be reconstructed by
40
+ * the consumer without re-parsing.
41
+ */
42
+ export interface MarkedContentEvent {
43
+ kind: 'begin' | 'end';
44
+ /** The tag operand of `BMC` / `BDC` (e.g. `Span`, `P`, `Artifact`). */
45
+ tag?: string;
46
+ /** `/ActualText` from the property list, already decoded to a JS string. */
47
+ actualText?: string;
48
+ }
49
+ /**
50
+ * Decode a PDF *text string* (§7.9.2.2) from its raw bytes.
51
+ *
52
+ * Mirrors pdf-lib's `PDFString.decodeText` (UTF-16BE when the BOM is present,
53
+ * else PDFDocEncoding) and adds the UTF-8 BOM that PDF 2.0 introduced, which
54
+ * pdf-lib 1.x does not handle.
55
+ */
56
+ export declare function decodeTextString(bytes: Uint8Array): string;
57
+ /**
58
+ * Scan one page's content for marked-content operators, in stream order.
59
+ *
60
+ * Returns `null` when the page's content cannot be read (missing or undecodable
61
+ * stream). Callers must treat `null` — and any count that disagrees with pdfjs's
62
+ * marker count — as "alignment unknown" and skip replacement: a scanner that is
63
+ * off by one sequence would move replacement text onto the wrong glyphs. Failing
64
+ * to resolve `/ActualText` leaves the pre-existing behaviour (raw glyphs, plus
65
+ * the #15 note); mis-resolving it would be a new and worse failure.
66
+ *
67
+ * @param pageIndex 0-based page index.
68
+ */
69
+ export declare function scanPageMarkedContent(doc: PDFDocument, pageIndex: number): MarkedContentEvent[] | null;
70
+ //# sourceMappingURL=content-stream-service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"content-stream-service.d.ts","sourceRoot":"","sources":["../../src/services/content-stream-service.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAEH,OAAO,EAIL,KAAK,WAAW,EAUjB,MAAM,SAAS,CAAC;AAEjB;;;;;GAKG;AACH,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,OAAO,GAAG,KAAK,CAAC;IACtB,uEAAuE;IACvE,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,4EAA4E;IAC5E,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAwDD;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAQ1D;AAqXD;;;;;;;;;;;GAWG;AACH,wBAAgB,qBAAqB,CACnC,GAAG,EAAE,WAAW,EAChB,SAAS,EAAE,MAAM,GAChB,kBAAkB,EAAE,GAAG,IAAI,CA0C7B"}