pdfium-native 0.8.0 → 0.9.1

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.
@@ -0,0 +1,189 @@
1
+ #pragma once
2
+
3
+ #include "napi_helpers.h"
4
+
5
+ #include <atomic>
6
+ #include <memory>
7
+ #include <string>
8
+ #include <vector>
9
+
10
+ #include "fpdf_structtree.h"
11
+
12
+ // ---------------------------------------------------------------------------
13
+ // GetStructTreeWorker — async tagged-PDF structure tree extraction
14
+ // ---------------------------------------------------------------------------
15
+ // The structure tree is what makes a PDF "tagged": the logical document
16
+ // outline (headings, paragraphs, tables, figures) sitting behind the visual
17
+ // layout. It is what screen readers follow, and it carries the alternate text
18
+ // that accessibility audits check for. `metadata.isTagged` already reports
19
+ // whether a document has one; this reads it.
20
+ //
21
+ // The tree is per-page: PDFium hands back the elements whose content lives on
22
+ // the requested page, not the whole document's tree.
23
+
24
+ // maximum structure tree recursion depth, mirroring MAX_BOOKMARK_DEPTH
25
+ constexpr int MAX_STRUCT_DEPTH = 64;
26
+
27
+ // Maximum number of elements returned for one page.
28
+ //
29
+ // A depth cap alone does not bound the work: PDFium's structure tree is a DAG,
30
+ // and CPDF_StructElement::UpdateKidIfElement resolves EVERY kid slot whose dict
31
+ // matches, so a /K array naming the same child twice gives that element two
32
+ // live children pointing at one node. Flattening that into a tree doubles the
33
+ // node count per level — a 1.8 KB file with a 12-link chain expands to 4095
34
+ // elements, and each extra link doubles it again. Since the whole traversal
35
+ // runs holding g_pdfium_mutex, an unbounded walk would stall every other
36
+ // PDFium call in the process, not just this one.
37
+ //
38
+ // The value is deliberately low enough that reaching it stays cheap: a single
39
+ // page's structure tree covers only that page's own content, so a real document
40
+ // runs to hundreds of elements, not thousands. 20,000 leaves ample headroom
41
+ // while keeping the worst case fast even on an emulated runner.
42
+ constexpr int MAX_STRUCT_NODES = 20000;
43
+
44
+ // read one of the struct element's UTF-16LE string properties
45
+ template <typename Fn> inline std::u16string ReadStructString(Fn fn) {
46
+ return ReadU16([&](auto *, unsigned long) { return fn(nullptr, 0); },
47
+ [&](FPDF_WCHAR *buf, unsigned long len) {
48
+ return fn(buf, len);
49
+ });
50
+ }
51
+
52
+ struct StructElementInfo {
53
+ std::u16string type;
54
+ std::u16string objType;
55
+ std::u16string title;
56
+ std::u16string altText;
57
+ std::u16string actualText;
58
+ std::u16string id;
59
+ std::u16string lang;
60
+ int markedContentId = -1;
61
+ std::vector<StructElementInfo> children;
62
+ };
63
+
64
+ class GetStructTreeWorker : public SafeAsyncWorker {
65
+ public:
66
+ GetStructTreeWorker(Napi::Env env, FPDF_PAGE page,
67
+ std::shared_ptr<std::atomic<bool>> pageAlive,
68
+ std::shared_ptr<std::atomic<bool>> docAlive)
69
+ : SafeAsyncWorker(env), deferred_(Napi::Promise::Deferred::New(env)),
70
+ page_(page), pageAlive_(std::move(pageAlive)),
71
+ docAlive_(std::move(docAlive)) {}
72
+
73
+ Napi::Promise Promise() { return deferred_.Promise(); }
74
+
75
+ protected:
76
+ void Execute() override {
77
+ std::lock_guard<std::mutex> lock(g_pdfium_mutex);
78
+ CHECK_ALIVE();
79
+
80
+ FPDF_STRUCTTREE tree = FPDF_StructTree_GetForPage(page_);
81
+ if (!tree)
82
+ return; // untagged page — an empty tree, not an error
83
+
84
+ int count = FPDF_StructTree_CountChildren(tree);
85
+ for (int i = 0; i < count; i++) {
86
+ if (nodeCount_ >= MAX_STRUCT_NODES)
87
+ break;
88
+ FPDF_STRUCTELEMENT element = FPDF_StructTree_GetChildAtIndex(tree, i);
89
+ if (!element)
90
+ continue;
91
+ roots_.push_back(ReadElement(element, 0));
92
+ }
93
+
94
+ FPDF_StructTree_Close(tree);
95
+ }
96
+
97
+ void OnOK() override {
98
+ Napi::Env env = Env();
99
+ deferred_.Resolve(BuildArray(env, roots_));
100
+ }
101
+
102
+ void OnError(const Napi::Error &err) override {
103
+ deferred_.Reject(err.Value());
104
+ }
105
+
106
+ private:
107
+ StructElementInfo ReadElement(FPDF_STRUCTELEMENT element, int depth) {
108
+ StructElementInfo info;
109
+ nodeCount_++;
110
+
111
+ info.type = ReadStructString([&](FPDF_WCHAR *buf, unsigned long len) {
112
+ return FPDF_StructElement_GetType(element, buf, len);
113
+ });
114
+ info.objType = ReadStructString([&](FPDF_WCHAR *buf, unsigned long len) {
115
+ return FPDF_StructElement_GetObjType(element, buf, len);
116
+ });
117
+ info.title = ReadStructString([&](FPDF_WCHAR *buf, unsigned long len) {
118
+ return FPDF_StructElement_GetTitle(element, buf, len);
119
+ });
120
+ info.altText = ReadStructString([&](FPDF_WCHAR *buf, unsigned long len) {
121
+ return FPDF_StructElement_GetAltText(element, buf, len);
122
+ });
123
+ info.actualText = ReadStructString([&](FPDF_WCHAR *buf, unsigned long len) {
124
+ return FPDF_StructElement_GetActualText(element, buf, len);
125
+ });
126
+ info.id = ReadStructString([&](FPDF_WCHAR *buf, unsigned long len) {
127
+ return FPDF_StructElement_GetID(element, buf, len);
128
+ });
129
+ info.lang = ReadStructString([&](FPDF_WCHAR *buf, unsigned long len) {
130
+ return FPDF_StructElement_GetLang(element, buf, len);
131
+ });
132
+
133
+ info.markedContentId = FPDF_StructElement_GetMarkedContentID(element);
134
+
135
+ // A malformed or hostile PDF can nest structure elements arbitrarily deep,
136
+ // or cycle; stop descending rather than overflow the stack. The node budget
137
+ // additionally bounds *breadth*, which the depth cap does not — see
138
+ // MAX_STRUCT_NODES.
139
+ if (depth >= MAX_STRUCT_DEPTH || nodeCount_ >= MAX_STRUCT_NODES)
140
+ return info;
141
+
142
+ int childCount = FPDF_StructElement_CountChildren(element);
143
+ for (int i = 0; i < childCount; i++) {
144
+ if (nodeCount_ >= MAX_STRUCT_NODES)
145
+ break;
146
+ // returns null for children that are content references rather than
147
+ // elements, which is expected and simply skipped
148
+ FPDF_STRUCTELEMENT child =
149
+ FPDF_StructElement_GetChildAtIndex(element, i);
150
+ if (!child)
151
+ continue;
152
+ info.children.push_back(ReadElement(child, depth + 1));
153
+ }
154
+
155
+ return info;
156
+ }
157
+
158
+ Napi::Array BuildArray(Napi::Env env,
159
+ const std::vector<StructElementInfo> &items) {
160
+ Napi::Array arr = Napi::Array::New(env, items.size());
161
+ for (uint32_t i = 0; i < items.size(); i++) {
162
+ const auto &info = items[i];
163
+ Napi::Object obj = Napi::Object::New(env);
164
+ SetU16(obj, "type", env, info.type);
165
+ SetU16IfPresent(obj, "objType", env, info.objType);
166
+ SetU16IfPresent(obj, "title", env, info.title);
167
+ SetU16IfPresent(obj, "altText", env, info.altText);
168
+ SetU16IfPresent(obj, "actualText", env, info.actualText);
169
+ SetU16IfPresent(obj, "id", env, info.id);
170
+ SetU16IfPresent(obj, "lang", env, info.lang);
171
+ if (info.markedContentId >= 0) {
172
+ obj.Set("markedContentId",
173
+ Napi::Number::New(env, info.markedContentId));
174
+ }
175
+ if (!info.children.empty()) {
176
+ obj.Set("children", BuildArray(env, info.children));
177
+ }
178
+ arr.Set(i, obj);
179
+ }
180
+ return arr;
181
+ }
182
+
183
+ Napi::Promise::Deferred deferred_;
184
+ FPDF_PAGE page_;
185
+ std::shared_ptr<std::atomic<bool>> pageAlive_;
186
+ std::shared_ptr<std::atomic<bool>> docAlive_;
187
+ std::vector<StructElementInfo> roots_;
188
+ int nodeCount_ = 0;
189
+ };