pdfium-native 0.7.0 → 0.9.0

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 (48) hide show
  1. package/CHANGELOG.md +42 -1
  2. package/README.md +324 -4
  3. package/dist/document.d.ts +43 -2
  4. package/dist/document.d.ts.map +1 -1
  5. package/dist/document.js +49 -6
  6. package/dist/document.js.map +1 -1
  7. package/dist/errors.d.ts.map +1 -1
  8. package/dist/errors.js +9 -0
  9. package/dist/errors.js.map +1 -1
  10. package/dist/index.d.ts +60 -2
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +55 -0
  13. package/dist/index.js.map +1 -1
  14. package/dist/page.d.ts +35 -1
  15. package/dist/page.d.ts.map +1 -1
  16. package/dist/page.js +51 -0
  17. package/dist/page.js.map +1 -1
  18. package/dist/types.d.ts +255 -0
  19. package/dist/types.d.ts.map +1 -1
  20. package/dist/validate.d.ts +14 -0
  21. package/dist/validate.d.ts.map +1 -0
  22. package/dist/validate.js +16 -0
  23. package/dist/validate.js.map +1 -0
  24. package/lib/document.ts +80 -7
  25. package/lib/errors.ts +10 -0
  26. package/lib/index.ts +159 -0
  27. package/lib/page.ts +80 -0
  28. package/lib/types.ts +280 -0
  29. package/lib/validate.ts +15 -0
  30. package/package.json +1 -1
  31. package/scripts/generate-fixtures.mjs +310 -0
  32. package/scripts/prebuilds.json +10 -10
  33. package/src/annotations_worker.h +111 -0
  34. package/src/assemble_worker.h +235 -0
  35. package/src/attachments_worker.h +44 -45
  36. package/src/attachments_write_worker.h +158 -0
  37. package/src/characters_worker.h +197 -0
  38. package/src/destinations_worker.h +160 -0
  39. package/src/document.h +86 -0
  40. package/src/document_io.h +78 -0
  41. package/src/flatten_worker.h +133 -0
  42. package/src/javascript_worker.h +105 -0
  43. package/src/napi_helpers.h +55 -0
  44. package/src/page.h +82 -0
  45. package/src/pdfium_addon.cc +310 -0
  46. package/src/signatures_worker.h +248 -0
  47. package/src/split_merge_worker.h +2 -93
  48. package/src/structtree_worker.h +164 -0
@@ -0,0 +1,248 @@
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_signature.h"
11
+
12
+ // ---------------------------------------------------------------------------
13
+ // Digital signature helpers
14
+ // ---------------------------------------------------------------------------
15
+ // PDFium reads the signature *dictionary* only — it performs no cryptographic
16
+ // verification whatsoever. These workers surface what the PDF itself declares:
17
+ // the encoding (/SubFilter), the signing reason and time, the DocMDP
18
+ // certification level and the byte ranges the digest covers. Verifying the
19
+ // PKCS#7 blob against those ranges is the caller's job;
20
+ // GetSignatureContentsWorker hands the blob over untouched.
21
+
22
+ // read a signature's /SubFilter, /M etc. — these are 7-bit ASCII, not UTF-16LE
23
+ template <typename Fn> inline std::string ReadSignatureString(Fn fn) {
24
+ return ReadUtf8([&](char *, unsigned long) { return fn(nullptr, 0); },
25
+ [&](char *buf, unsigned long len) { return fn(buf, len); });
26
+ }
27
+
28
+ // Reads the raw /Contents bytes of a signature (a DER-encoded PKCS#1 or PKCS#7
29
+ // binary) via the two-pass protocol. An empty /Contents yields an empty vector
30
+ // and success. Returns false and sets `err` on failure.
31
+ inline bool ReadSignatureContentsBytes(FPDF_SIGNATURE signature,
32
+ std::vector<uint8_t> &out,
33
+ std::string &err) {
34
+ unsigned long len = FPDFSignatureObj_GetContents(signature, nullptr, 0);
35
+ out.clear();
36
+ if (len == 0)
37
+ return true;
38
+
39
+ out.resize(len);
40
+ if (FPDFSignatureObj_GetContents(signature, out.data(), len) != len) {
41
+ err = "Failed to read signature contents";
42
+ return false;
43
+ }
44
+ return true;
45
+ }
46
+
47
+ // ---------------------------------------------------------------------------
48
+ // GetSignaturesWorker — async signature metadata listing
49
+ // ---------------------------------------------------------------------------
50
+ // Deliberately cheap in the same sense as GetAttachmentsWorker: it reads
51
+ // dictionary entries and the byte-range array, but reports /Contents only by
52
+ // its length. Use GetSignatureContentsWorker to fetch the blob itself.
53
+
54
+ struct SignatureInfo {
55
+ int index = 0;
56
+ std::string subFilter;
57
+ std::u16string reason;
58
+ std::string time;
59
+ unsigned int docMdpPermission = 0;
60
+ std::vector<int> byteRange;
61
+ unsigned long contentsLength = 0;
62
+ };
63
+
64
+ class GetSignaturesWorker : public SafeAsyncWorker {
65
+ public:
66
+ GetSignaturesWorker(Napi::Env env, FPDF_DOCUMENT doc,
67
+ std::shared_ptr<std::atomic<bool>> docAlive)
68
+ : SafeAsyncWorker(env), deferred_(Napi::Promise::Deferred::New(env)),
69
+ doc_(doc), docAlive_(std::move(docAlive)) {}
70
+
71
+ Napi::Promise Promise() { return deferred_.Promise(); }
72
+
73
+ protected:
74
+ void Execute() override {
75
+ std::lock_guard<std::mutex> lock(g_pdfium_mutex);
76
+ if (!docAlive_ || !docAlive_->load()) {
77
+ SetError("Document was destroyed");
78
+ return;
79
+ }
80
+
81
+ int count = FPDF_GetSignatureCount(doc_);
82
+ if (count <= 0)
83
+ return;
84
+
85
+ signatures_.reserve(count);
86
+ for (int i = 0; i < count; i++) {
87
+ FPDF_SIGNATURE signature = FPDF_GetSignatureObject(doc_, i);
88
+ if (!signature)
89
+ continue;
90
+
91
+ SignatureInfo info;
92
+ info.index = i;
93
+
94
+ info.subFilter = ReadSignatureString(
95
+ [&](char *buf, unsigned long len) {
96
+ return FPDFSignatureObj_GetSubFilter(signature, buf, len);
97
+ });
98
+
99
+ info.reason = ReadU16(
100
+ [&](auto *, unsigned long) {
101
+ return FPDFSignatureObj_GetReason(signature, nullptr, 0);
102
+ },
103
+ [&](FPDF_WCHAR *buf, unsigned long len) {
104
+ return FPDFSignatureObj_GetReason(signature, buf, len);
105
+ });
106
+
107
+ info.time = ReadSignatureString([&](char *buf, unsigned long len) {
108
+ return FPDFSignatureObj_GetTime(signature, buf, len);
109
+ });
110
+
111
+ // 1-3 for a certification (DocMDP) signature, 0 for an ordinary one
112
+ info.docMdpPermission =
113
+ FPDFSignatureObj_GetDocMDPPermission(signature);
114
+
115
+ // /ByteRange is a flat array of (offset, length) pairs; the length here
116
+ // counts ints, not bytes
117
+ unsigned long rangeLen =
118
+ FPDFSignatureObj_GetByteRange(signature, nullptr, 0);
119
+ if (rangeLen > 0) {
120
+ info.byteRange.resize(rangeLen);
121
+ if (FPDFSignatureObj_GetByteRange(signature, info.byteRange.data(),
122
+ rangeLen) != rangeLen) {
123
+ info.byteRange.clear();
124
+ }
125
+ }
126
+
127
+ info.contentsLength =
128
+ FPDFSignatureObj_GetContents(signature, nullptr, 0);
129
+
130
+ signatures_.push_back(std::move(info));
131
+ }
132
+ }
133
+
134
+ void OnOK() override {
135
+ Napi::Env env = Env();
136
+ Napi::Array arr = Napi::Array::New(env, signatures_.size());
137
+ for (uint32_t i = 0; i < signatures_.size(); i++) {
138
+ const auto &info = signatures_[i];
139
+ Napi::Object obj = Napi::Object::New(env);
140
+ obj.Set("index", Napi::Number::New(env, info.index));
141
+ obj.Set("subFilter", Napi::String::New(env, info.subFilter));
142
+ SetU16IfPresent(obj, "reason", env, info.reason);
143
+ if (!info.time.empty())
144
+ obj.Set("time", Napi::String::New(env, info.time));
145
+ if (info.docMdpPermission > 0) {
146
+ obj.Set("docMdpPermission",
147
+ Napi::Number::New(env, info.docMdpPermission));
148
+ }
149
+
150
+ Napi::Array range = Napi::Array::New(env, info.byteRange.size());
151
+ for (uint32_t j = 0; j < info.byteRange.size(); j++) {
152
+ range.Set(j, Napi::Number::New(env, info.byteRange[j]));
153
+ }
154
+ obj.Set("byteRange", range);
155
+
156
+ obj.Set("contentsLength",
157
+ Napi::Number::New(env, static_cast<double>(info.contentsLength)));
158
+ arr.Set(i, obj);
159
+ }
160
+ deferred_.Resolve(arr);
161
+ }
162
+
163
+ void OnError(const Napi::Error &err) override {
164
+ deferred_.Reject(err.Value());
165
+ }
166
+
167
+ private:
168
+ Napi::Promise::Deferred deferred_;
169
+ FPDF_DOCUMENT doc_;
170
+ std::shared_ptr<std::atomic<bool>> docAlive_;
171
+ std::vector<SignatureInfo> signatures_;
172
+ };
173
+
174
+ // ---------------------------------------------------------------------------
175
+ // GetSignatureContentsWorker — async read of a single signature's /Contents
176
+ // ---------------------------------------------------------------------------
177
+
178
+ class GetSignatureContentsWorker : public SafeAsyncWorker {
179
+ public:
180
+ GetSignatureContentsWorker(Napi::Env env, FPDF_DOCUMENT doc, int index,
181
+ std::string outputPath,
182
+ std::shared_ptr<std::atomic<bool>> docAlive)
183
+ : SafeAsyncWorker(env), deferred_(Napi::Promise::Deferred::New(env)),
184
+ doc_(doc), index_(index), outputPath_(std::move(outputPath)),
185
+ docAlive_(std::move(docAlive)) {}
186
+
187
+ Napi::Promise Promise() { return deferred_.Promise(); }
188
+
189
+ protected:
190
+ void Execute() override {
191
+ std::lock_guard<std::mutex> lock(g_pdfium_mutex);
192
+ if (!docAlive_ || !docAlive_->load()) {
193
+ SetError("Document was destroyed");
194
+ return;
195
+ }
196
+
197
+ int count = FPDF_GetSignatureCount(doc_);
198
+ if (index_ < 0 || index_ >= count) {
199
+ SetError("Signature index out of range");
200
+ return;
201
+ }
202
+
203
+ FPDF_SIGNATURE signature = FPDF_GetSignatureObject(doc_, index_);
204
+ if (!signature) {
205
+ SetError("Failed to get signature");
206
+ return;
207
+ }
208
+
209
+ std::string err;
210
+ if (!ReadSignatureContentsBytes(signature, data_, err)) {
211
+ SetError(err);
212
+ return;
213
+ }
214
+
215
+ if (!outputPath_.empty()) {
216
+ if (!WriteBytesToFile(outputPath_, data_, err)) {
217
+ SetError(err);
218
+ return;
219
+ }
220
+ data_.clear();
221
+ }
222
+ }
223
+
224
+ void OnOK() override {
225
+ Napi::Env env = Env();
226
+ if (!outputPath_.empty()) {
227
+ deferred_.Resolve(env.Undefined());
228
+ return;
229
+ }
230
+ auto *vec = new std::vector<uint8_t>(std::move(data_));
231
+ auto buffer = Napi::Buffer<uint8_t>::New(
232
+ env, vec->data(), vec->size(),
233
+ [](Napi::Env, uint8_t *, std::vector<uint8_t> *v) { delete v; }, vec);
234
+ deferred_.Resolve(buffer);
235
+ }
236
+
237
+ void OnError(const Napi::Error &err) override {
238
+ deferred_.Reject(err.Value());
239
+ }
240
+
241
+ private:
242
+ Napi::Promise::Deferred deferred_;
243
+ FPDF_DOCUMENT doc_;
244
+ int index_;
245
+ std::string outputPath_;
246
+ std::shared_ptr<std::atomic<bool>> docAlive_;
247
+ std::vector<uint8_t> data_;
248
+ };
@@ -1,103 +1,12 @@
1
1
  #pragma once
2
2
 
3
- #include "napi_helpers.h"
3
+ #include "document_io.h"
4
4
 
5
- #include <climits>
6
- #include <cstdio>
5
+ #include <string>
7
6
  #include <vector>
8
7
 
9
- #ifdef _WIN32
10
- #include <io.h>
11
- #define F_OK 0
12
- #define access _access
13
- #else
14
- #include <unistd.h>
15
- #endif
16
-
17
8
  #include "fpdf_edit.h"
18
9
  #include "fpdf_ppo.h"
19
- #include "fpdf_save.h"
20
-
21
- // ---------------------------------------------------------------------------
22
- // FPDF_FILEWRITE adapter — collects saved PDF bytes into a std::vector
23
- // ---------------------------------------------------------------------------
24
-
25
- struct VectorFileWrite : FPDF_FILEWRITE {
26
- std::vector<uint8_t> data;
27
-
28
- VectorFileWrite() {
29
- version = 1;
30
- WriteBlock = [](FPDF_FILEWRITE_ *self, const void *buf,
31
- unsigned long size) -> int {
32
- auto *w = static_cast<VectorFileWrite *>(self);
33
- auto *bytes = static_cast<const uint8_t *>(buf);
34
- w->data.insert(w->data.end(), bytes, bytes + size);
35
- return 1;
36
- };
37
- }
38
- };
39
-
40
- // helper: save a document to buffer or file, returning the buffer data
41
- static inline bool SaveDocument(FPDF_DOCUMENT doc,
42
- const std::string &outputPath,
43
- std::vector<uint8_t> &outData,
44
- std::string &outError) {
45
- VectorFileWrite writer;
46
- if (!FPDF_SaveAsCopy(doc, &writer, 0)) {
47
- outError = "Failed to save PDF document";
48
- return false;
49
- }
50
-
51
- if (!outputPath.empty()) {
52
- auto slash = outputPath.rfind('/');
53
- if (slash != std::string::npos && slash > 0) {
54
- std::string parentDir = outputPath.substr(0, slash);
55
- if (access(parentDir.c_str(), F_OK) != 0) {
56
- outError = "Parent directory does not exist: " + parentDir;
57
- return false;
58
- }
59
- }
60
- FILE *f = fopen(outputPath.c_str(), "wb");
61
- if (!f) {
62
- outError = "Failed to open output file: " + outputPath;
63
- return false;
64
- }
65
- size_t written = fwrite(writer.data.data(), 1, writer.data.size(), f);
66
- fclose(f);
67
- if (written != writer.data.size()) {
68
- outError = "Failed to write output file: " + outputPath;
69
- return false;
70
- }
71
- } else {
72
- outData = std::move(writer.data);
73
- }
74
- return true;
75
- }
76
-
77
- // helper: load a document from buffer or file path
78
- static inline FPDF_DOCUMENT LoadDoc(const std::vector<uint8_t> &bufferData,
79
- const std::string &filePath, bool useFile,
80
- const std::string &password,
81
- std::string &outError) {
82
- const char *pw = password.empty() ? nullptr : password.c_str();
83
- FPDF_DOCUMENT doc;
84
-
85
- if (useFile) {
86
- doc = FPDF_LoadDocument(filePath.c_str(), pw);
87
- } else {
88
- if (bufferData.size() > static_cast<size_t>(INT_MAX)) {
89
- outError = "FORMAT:Buffer too large";
90
- return nullptr;
91
- }
92
- doc = FPDF_LoadMemDocument(bufferData.data(),
93
- static_cast<int>(bufferData.size()), pw);
94
- }
95
-
96
- if (!doc) {
97
- outError = GetPdfiumErrorMessage();
98
- }
99
- return doc;
100
- }
101
10
 
102
11
  // ---------------------------------------------------------------------------
103
12
  // SplitDocumentWorker — split a PDF into multiple documents at given indices
@@ -0,0 +1,164 @@
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
+ // read one of the struct element's UTF-16LE string properties
28
+ template <typename Fn> inline std::u16string ReadStructString(Fn fn) {
29
+ return ReadU16([&](auto *, unsigned long) { return fn(nullptr, 0); },
30
+ [&](FPDF_WCHAR *buf, unsigned long len) {
31
+ return fn(buf, len);
32
+ });
33
+ }
34
+
35
+ struct StructElementInfo {
36
+ std::u16string type;
37
+ std::u16string objType;
38
+ std::u16string title;
39
+ std::u16string altText;
40
+ std::u16string actualText;
41
+ std::u16string id;
42
+ std::u16string lang;
43
+ int markedContentId = -1;
44
+ std::vector<StructElementInfo> children;
45
+ };
46
+
47
+ class GetStructTreeWorker : public SafeAsyncWorker {
48
+ public:
49
+ GetStructTreeWorker(Napi::Env env, FPDF_PAGE page,
50
+ std::shared_ptr<std::atomic<bool>> pageAlive,
51
+ std::shared_ptr<std::atomic<bool>> docAlive)
52
+ : SafeAsyncWorker(env), deferred_(Napi::Promise::Deferred::New(env)),
53
+ page_(page), pageAlive_(std::move(pageAlive)),
54
+ docAlive_(std::move(docAlive)) {}
55
+
56
+ Napi::Promise Promise() { return deferred_.Promise(); }
57
+
58
+ protected:
59
+ void Execute() override {
60
+ std::lock_guard<std::mutex> lock(g_pdfium_mutex);
61
+ CHECK_ALIVE();
62
+
63
+ FPDF_STRUCTTREE tree = FPDF_StructTree_GetForPage(page_);
64
+ if (!tree)
65
+ return; // untagged page — an empty tree, not an error
66
+
67
+ int count = FPDF_StructTree_CountChildren(tree);
68
+ for (int i = 0; i < count; i++) {
69
+ FPDF_STRUCTELEMENT element = FPDF_StructTree_GetChildAtIndex(tree, i);
70
+ if (!element)
71
+ continue;
72
+ roots_.push_back(ReadElement(element, 0));
73
+ }
74
+
75
+ FPDF_StructTree_Close(tree);
76
+ }
77
+
78
+ void OnOK() override {
79
+ Napi::Env env = Env();
80
+ deferred_.Resolve(BuildArray(env, roots_));
81
+ }
82
+
83
+ void OnError(const Napi::Error &err) override {
84
+ deferred_.Reject(err.Value());
85
+ }
86
+
87
+ private:
88
+ StructElementInfo ReadElement(FPDF_STRUCTELEMENT element, int depth) {
89
+ StructElementInfo info;
90
+
91
+ info.type = ReadStructString([&](FPDF_WCHAR *buf, unsigned long len) {
92
+ return FPDF_StructElement_GetType(element, buf, len);
93
+ });
94
+ info.objType = ReadStructString([&](FPDF_WCHAR *buf, unsigned long len) {
95
+ return FPDF_StructElement_GetObjType(element, buf, len);
96
+ });
97
+ info.title = ReadStructString([&](FPDF_WCHAR *buf, unsigned long len) {
98
+ return FPDF_StructElement_GetTitle(element, buf, len);
99
+ });
100
+ info.altText = ReadStructString([&](FPDF_WCHAR *buf, unsigned long len) {
101
+ return FPDF_StructElement_GetAltText(element, buf, len);
102
+ });
103
+ info.actualText = ReadStructString([&](FPDF_WCHAR *buf, unsigned long len) {
104
+ return FPDF_StructElement_GetActualText(element, buf, len);
105
+ });
106
+ info.id = ReadStructString([&](FPDF_WCHAR *buf, unsigned long len) {
107
+ return FPDF_StructElement_GetID(element, buf, len);
108
+ });
109
+ info.lang = ReadStructString([&](FPDF_WCHAR *buf, unsigned long len) {
110
+ return FPDF_StructElement_GetLang(element, buf, len);
111
+ });
112
+
113
+ info.markedContentId = FPDF_StructElement_GetMarkedContentID(element);
114
+
115
+ // A malformed or hostile PDF can nest structure elements arbitrarily deep,
116
+ // or cycle; stop descending rather than overflow the stack.
117
+ if (depth >= MAX_STRUCT_DEPTH)
118
+ return info;
119
+
120
+ int childCount = FPDF_StructElement_CountChildren(element);
121
+ for (int i = 0; i < childCount; i++) {
122
+ // returns null for children that are content references rather than
123
+ // elements, which is expected and simply skipped
124
+ FPDF_STRUCTELEMENT child =
125
+ FPDF_StructElement_GetChildAtIndex(element, i);
126
+ if (!child)
127
+ continue;
128
+ info.children.push_back(ReadElement(child, depth + 1));
129
+ }
130
+
131
+ return info;
132
+ }
133
+
134
+ Napi::Array BuildArray(Napi::Env env,
135
+ const std::vector<StructElementInfo> &items) {
136
+ Napi::Array arr = Napi::Array::New(env, items.size());
137
+ for (uint32_t i = 0; i < items.size(); i++) {
138
+ const auto &info = items[i];
139
+ Napi::Object obj = Napi::Object::New(env);
140
+ SetU16(obj, "type", env, info.type);
141
+ SetU16IfPresent(obj, "objType", env, info.objType);
142
+ SetU16IfPresent(obj, "title", env, info.title);
143
+ SetU16IfPresent(obj, "altText", env, info.altText);
144
+ SetU16IfPresent(obj, "actualText", env, info.actualText);
145
+ SetU16IfPresent(obj, "id", env, info.id);
146
+ SetU16IfPresent(obj, "lang", env, info.lang);
147
+ if (info.markedContentId >= 0) {
148
+ obj.Set("markedContentId",
149
+ Napi::Number::New(env, info.markedContentId));
150
+ }
151
+ if (!info.children.empty()) {
152
+ obj.Set("children", BuildArray(env, info.children));
153
+ }
154
+ arr.Set(i, obj);
155
+ }
156
+ return arr;
157
+ }
158
+
159
+ Napi::Promise::Deferred deferred_;
160
+ FPDF_PAGE page_;
161
+ std::shared_ptr<std::atomic<bool>> pageAlive_;
162
+ std::shared_ptr<std::atomic<bool>> docAlive_;
163
+ std::vector<StructElementInfo> roots_;
164
+ };