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,197 @@
1
+ #pragma once
2
+
3
+ #include "napi_helpers.h"
4
+
5
+ #include <atomic>
6
+ #include <climits>
7
+ #include <memory>
8
+ #include <string>
9
+ #include <vector>
10
+
11
+ #include "fpdf_text.h"
12
+
13
+ // ---------------------------------------------------------------------------
14
+ // GetCharactersWorker — async positioned text extraction
15
+ // ---------------------------------------------------------------------------
16
+ // page.getText() flattens a page to a single string and throws the geometry
17
+ // away. This worker keeps it: every character comes back with its bounding box,
18
+ // baseline origin, font and rotation, which is what layout reconstruction,
19
+ // coordinate mapping and redaction targeting all need.
20
+ //
21
+ // A dense page can hold tens of thousands of characters, so the range options
22
+ // exist to let callers page through instead of materialising everything.
23
+
24
+ // Encode a Unicode code point as UTF-16. PDFium stores text page characters in
25
+ // wchar_t, which is 32-bit on POSIX and 16-bit on Windows, so a code point
26
+ // above the BMP arrives whole on one platform and pre-split on the other.
27
+ // Splitting it here makes both behave the same on the JS side.
28
+ inline std::u16string CodePointToU16(unsigned int codePoint) {
29
+ if (codePoint == 0 || codePoint > 0x10FFFF)
30
+ return {};
31
+ if (codePoint <= 0xFFFF)
32
+ return std::u16string(1, static_cast<char16_t>(codePoint));
33
+
34
+ unsigned int v = codePoint - 0x10000;
35
+ std::u16string out;
36
+ out.push_back(static_cast<char16_t>(0xD800 + (v >> 10)));
37
+ out.push_back(static_cast<char16_t>(0xDC00 + (v & 0x3FF)));
38
+ return out;
39
+ }
40
+
41
+ struct CharacterInfo {
42
+ int index = 0;
43
+ unsigned int unicode = 0;
44
+ double left = 0, bottom = 0, right = 0, top = 0;
45
+ bool hasBounds = false;
46
+ double originX = 0, originY = 0;
47
+ bool hasOrigin = false;
48
+ double fontSize = 0;
49
+ std::string fontName;
50
+ int fontFlags = 0;
51
+ int fontWeight = -1;
52
+ float angle = 0;
53
+ bool isGenerated = false;
54
+ bool isHyphen = false;
55
+ bool hasUnicodeMapError = false;
56
+ };
57
+
58
+ class GetCharactersWorker : public SafeAsyncWorker {
59
+ public:
60
+ GetCharactersWorker(Napi::Env env, FPDF_PAGE page, int start, int count,
61
+ std::shared_ptr<std::atomic<bool>> pageAlive,
62
+ std::shared_ptr<std::atomic<bool>> docAlive)
63
+ : SafeAsyncWorker(env), deferred_(Napi::Promise::Deferred::New(env)),
64
+ page_(page), start_(start), count_(count),
65
+ pageAlive_(std::move(pageAlive)), docAlive_(std::move(docAlive)) {}
66
+
67
+ Napi::Promise Promise() { return deferred_.Promise(); }
68
+
69
+ protected:
70
+ void Execute() override {
71
+ std::lock_guard<std::mutex> lock(g_pdfium_mutex);
72
+ CHECK_ALIVE();
73
+
74
+ FPDF_TEXTPAGE textPage = FPDFText_LoadPage(page_);
75
+ if (!textPage) {
76
+ SetError("Failed to load text page");
77
+ return;
78
+ }
79
+
80
+ int charCount = FPDFText_CountChars(textPage);
81
+ if (charCount <= 0) {
82
+ FPDFText_ClosePage(textPage);
83
+ return;
84
+ }
85
+
86
+ if (start_ >= charCount) {
87
+ FPDFText_ClosePage(textPage);
88
+ return;
89
+ }
90
+
91
+ // count_ < 0 means "to the end of the page"
92
+ int end = charCount;
93
+ if (count_ >= 0) {
94
+ // start_ + count_ cannot overflow: both are non-negative and bounded by
95
+ // the caller-side 32-bit index guard
96
+ long long requestedEnd =
97
+ static_cast<long long>(start_) + static_cast<long long>(count_);
98
+ if (requestedEnd < end)
99
+ end = static_cast<int>(requestedEnd);
100
+ }
101
+
102
+ characters_.reserve(static_cast<size_t>(end - start_));
103
+ for (int i = start_; i < end; i++) {
104
+ CharacterInfo info;
105
+ info.index = i;
106
+ info.unicode = FPDFText_GetUnicode(textPage, i);
107
+
108
+ double left, right, bottom, top;
109
+ if (FPDFText_GetCharBox(textPage, i, &left, &right, &bottom, &top)) {
110
+ info.hasBounds = true;
111
+ info.left = left;
112
+ info.right = right;
113
+ info.bottom = bottom;
114
+ info.top = top;
115
+ }
116
+
117
+ double x, y;
118
+ if (FPDFText_GetCharOrigin(textPage, i, &x, &y)) {
119
+ info.hasOrigin = true;
120
+ info.originX = x;
121
+ info.originY = y;
122
+ }
123
+
124
+ info.fontSize = FPDFText_GetFontSize(textPage, i);
125
+ info.fontWeight = FPDFText_GetFontWeight(textPage, i);
126
+
127
+ int flags = 0;
128
+ info.fontName = ReadUtf8(
129
+ [&](char *, unsigned long) {
130
+ return FPDFText_GetFontInfo(textPage, i, nullptr, 0, &flags);
131
+ },
132
+ [&](char *buf, unsigned long len) {
133
+ return FPDFText_GetFontInfo(textPage, i, buf, len, &flags);
134
+ });
135
+ info.fontFlags = flags;
136
+
137
+ // PDFium already normalizes the angle to [0, 2pi), so a negative value
138
+ // can only be its -1 error return; report 0 instead of a bogus angle
139
+ float angle = FPDFText_GetCharAngle(textPage, i);
140
+ info.angle = angle < 0 ? 0.0f : angle;
141
+
142
+ // each of these returns -1 on error, which is not "true"
143
+ info.isGenerated = FPDFText_IsGenerated(textPage, i) == 1;
144
+ info.isHyphen = FPDFText_IsHyphen(textPage, i) == 1;
145
+ info.hasUnicodeMapError = FPDFText_HasUnicodeMapError(textPage, i) == 1;
146
+
147
+ characters_.push_back(std::move(info));
148
+ }
149
+
150
+ FPDFText_ClosePage(textPage);
151
+ }
152
+
153
+ void OnOK() override {
154
+ Napi::Env env = Env();
155
+ Napi::Array arr = Napi::Array::New(env, characters_.size());
156
+ for (uint32_t i = 0; i < characters_.size(); i++) {
157
+ const auto &info = characters_[i];
158
+ Napi::Object obj = Napi::Object::New(env);
159
+ obj.Set("index", Napi::Number::New(env, info.index));
160
+ SetU16(obj, "char", env, CodePointToU16(info.unicode));
161
+ obj.Set("unicode", Napi::Number::New(env, info.unicode));
162
+ if (info.hasBounds) {
163
+ obj.Set("bounds", CreateBoundsObject(env, info.left, info.bottom,
164
+ info.right, info.top));
165
+ }
166
+ if (info.hasOrigin) {
167
+ obj.Set("x", Napi::Number::New(env, info.originX));
168
+ obj.Set("y", Napi::Number::New(env, info.originY));
169
+ }
170
+ obj.Set("fontSize", Napi::Number::New(env, info.fontSize));
171
+ obj.Set("fontName", Napi::String::New(env, info.fontName));
172
+ obj.Set("fontFlags", Napi::Number::New(env, info.fontFlags));
173
+ if (info.fontWeight >= 0)
174
+ obj.Set("fontWeight", Napi::Number::New(env, info.fontWeight));
175
+ obj.Set("angle", Napi::Number::New(env, info.angle));
176
+ obj.Set("isGenerated", Napi::Boolean::New(env, info.isGenerated));
177
+ obj.Set("isHyphen", Napi::Boolean::New(env, info.isHyphen));
178
+ obj.Set("hasUnicodeMapError",
179
+ Napi::Boolean::New(env, info.hasUnicodeMapError));
180
+ arr.Set(i, obj);
181
+ }
182
+ deferred_.Resolve(arr);
183
+ }
184
+
185
+ void OnError(const Napi::Error &err) override {
186
+ deferred_.Reject(err.Value());
187
+ }
188
+
189
+ private:
190
+ Napi::Promise::Deferred deferred_;
191
+ FPDF_PAGE page_;
192
+ int start_;
193
+ int count_;
194
+ std::shared_ptr<std::atomic<bool>> pageAlive_;
195
+ std::shared_ptr<std::atomic<bool>> docAlive_;
196
+ std::vector<CharacterInfo> characters_;
197
+ };
@@ -0,0 +1,160 @@
1
+ #pragma once
2
+
3
+ #include "napi_helpers.h"
4
+
5
+ #include <atomic>
6
+ #include <memory>
7
+ #include <string>
8
+ #include <vector>
9
+
10
+ // ---------------------------------------------------------------------------
11
+ // GetNamedDestinationsWorker — async named-destination listing
12
+ // ---------------------------------------------------------------------------
13
+ // Named destinations are the document's table of anchors: /Dests entries that
14
+ // GoTo actions and external links target by name rather than by page. Listing
15
+ // them turns "#Chapter2" in an incoming link into a page index, and gives a
16
+ // document's internal structure without walking every link on every page.
17
+
18
+ inline const char *DestinationViewString(unsigned long view) {
19
+ switch (view) {
20
+ case PDFDEST_VIEW_XYZ:
21
+ return "xyz";
22
+ case PDFDEST_VIEW_FIT:
23
+ return "fit";
24
+ case PDFDEST_VIEW_FITH:
25
+ return "fitH";
26
+ case PDFDEST_VIEW_FITV:
27
+ return "fitV";
28
+ case PDFDEST_VIEW_FITR:
29
+ return "fitR";
30
+ case PDFDEST_VIEW_FITB:
31
+ return "fitB";
32
+ case PDFDEST_VIEW_FITBH:
33
+ return "fitBH";
34
+ case PDFDEST_VIEW_FITBV:
35
+ return "fitBV";
36
+ default:
37
+ return "unknown";
38
+ }
39
+ }
40
+
41
+ struct NamedDestinationInfo {
42
+ std::u16string name;
43
+ int pageIndex = -1;
44
+ const char *view = "unknown";
45
+ std::vector<float> viewParams;
46
+ bool hasX = false, hasY = false, hasZoom = false;
47
+ float x = 0, y = 0, zoom = 0;
48
+ };
49
+
50
+ class GetNamedDestinationsWorker : public SafeAsyncWorker {
51
+ public:
52
+ GetNamedDestinationsWorker(Napi::Env env, FPDF_DOCUMENT doc,
53
+ std::shared_ptr<std::atomic<bool>> docAlive)
54
+ : SafeAsyncWorker(env), deferred_(Napi::Promise::Deferred::New(env)),
55
+ doc_(doc), docAlive_(std::move(docAlive)) {}
56
+
57
+ Napi::Promise Promise() { return deferred_.Promise(); }
58
+
59
+ protected:
60
+ void Execute() override {
61
+ std::lock_guard<std::mutex> lock(g_pdfium_mutex);
62
+ if (!docAlive_ || !docAlive_->load()) {
63
+ SetError("Document was destroyed");
64
+ return;
65
+ }
66
+
67
+ unsigned long count = FPDF_CountNamedDests(doc_);
68
+ if (count == 0)
69
+ return;
70
+
71
+ destinations_.reserve(count);
72
+ for (unsigned long i = 0; i < count; i++) {
73
+ NamedDestinationInfo info;
74
+
75
+ // FPDF_GetNamedDest uses an in/out byte length rather than the usual
76
+ // two-pass protocol, and despite the header calling the buffer a
77
+ // wchar_t* it is written as UTF-16LE on every platform.
78
+ long nameLen = 0;
79
+ FPDF_DEST dest =
80
+ FPDF_GetNamedDest(doc_, static_cast<int>(i), nullptr, &nameLen);
81
+ if (!dest)
82
+ continue;
83
+
84
+ if (nameLen >= 2 && nameLen % 2 == 0) {
85
+ std::vector<unsigned short> buf(static_cast<size_t>(nameLen) /
86
+ sizeof(unsigned short));
87
+ long outLen = nameLen;
88
+ FPDF_GetNamedDest(doc_, static_cast<int>(i), buf.data(), &outLen);
89
+ if (outLen == nameLen) {
90
+ info.name = std::u16string(reinterpret_cast<const char16_t *>(
91
+ buf.data()),
92
+ buf.size() - 1);
93
+ }
94
+ }
95
+
96
+ info.pageIndex = FPDFDest_GetDestPageIndex(doc_, dest);
97
+
98
+ unsigned long numParams = 0;
99
+ FS_FLOAT params[4] = {0, 0, 0, 0};
100
+ unsigned long view = FPDFDest_GetView(dest, &numParams, params);
101
+ info.view = DestinationViewString(view);
102
+ if (numParams > 4)
103
+ numParams = 4;
104
+ info.viewParams.assign(params, params + numParams);
105
+
106
+ FPDF_BOOL hasX = 0, hasY = 0, hasZoom = 0;
107
+ FS_FLOAT x = 0, y = 0, zoom = 0;
108
+ if (FPDFDest_GetLocationInPage(dest, &hasX, &hasY, &hasZoom, &x, &y,
109
+ &zoom)) {
110
+ info.hasX = hasX != 0;
111
+ info.hasY = hasY != 0;
112
+ info.hasZoom = hasZoom != 0;
113
+ info.x = x;
114
+ info.y = y;
115
+ info.zoom = zoom;
116
+ }
117
+
118
+ destinations_.push_back(std::move(info));
119
+ }
120
+ }
121
+
122
+ void OnOK() override {
123
+ Napi::Env env = Env();
124
+ Napi::Array arr = Napi::Array::New(env, destinations_.size());
125
+ for (uint32_t i = 0; i < destinations_.size(); i++) {
126
+ const auto &info = destinations_[i];
127
+ Napi::Object obj = Napi::Object::New(env);
128
+ SetU16(obj, "name", env, info.name);
129
+ if (info.pageIndex >= 0)
130
+ obj.Set("pageIndex", Napi::Number::New(env, info.pageIndex));
131
+ obj.Set("view", Napi::String::New(env, info.view));
132
+
133
+ Napi::Array params = Napi::Array::New(env, info.viewParams.size());
134
+ for (uint32_t j = 0; j < info.viewParams.size(); j++) {
135
+ params.Set(j, Napi::Number::New(env, info.viewParams[j]));
136
+ }
137
+ obj.Set("viewParams", params);
138
+
139
+ if (info.hasX)
140
+ obj.Set("destX", Napi::Number::New(env, info.x));
141
+ if (info.hasY)
142
+ obj.Set("destY", Napi::Number::New(env, info.y));
143
+ if (info.hasZoom)
144
+ obj.Set("destZoom", Napi::Number::New(env, info.zoom));
145
+
146
+ arr.Set(i, obj);
147
+ }
148
+ deferred_.Resolve(arr);
149
+ }
150
+
151
+ void OnError(const Napi::Error &err) override {
152
+ deferred_.Reject(err.Value());
153
+ }
154
+
155
+ private:
156
+ Napi::Promise::Deferred deferred_;
157
+ FPDF_DOCUMENT doc_;
158
+ std::shared_ptr<std::atomic<bool>> docAlive_;
159
+ std::vector<NamedDestinationInfo> destinations_;
160
+ };
package/src/document.h CHANGED
@@ -2,7 +2,10 @@
2
2
 
3
3
  #include "attachments_worker.h"
4
4
  #include "bookmarks_worker.h"
5
+ #include "destinations_worker.h"
6
+ #include "javascript_worker.h"
5
7
  #include "page.h"
8
+ #include "signatures_worker.h"
6
9
 
7
10
  #include <algorithm>
8
11
  #include <atomic>
@@ -24,6 +27,13 @@ public:
24
27
  InstanceMethod<&PDFiumDocument::GetBookmarks>("getBookmarks"),
25
28
  InstanceMethod<&PDFiumDocument::GetAttachments>("getAttachments"),
26
29
  InstanceMethod<&PDFiumDocument::GetAttachment>("getAttachment"),
30
+ InstanceMethod<&PDFiumDocument::GetSignatures>("getSignatures"),
31
+ InstanceMethod<&PDFiumDocument::GetSignatureContents>(
32
+ "getSignatureContents"),
33
+ InstanceMethod<&PDFiumDocument::GetJavaScriptActions>(
34
+ "getJavaScriptActions"),
35
+ InstanceMethod<&PDFiumDocument::GetNamedDestinations>(
36
+ "getNamedDestinations"),
27
37
  InstanceMethod<&PDFiumDocument::Destroy>("destroy"),
28
38
  });
29
39
  }
@@ -130,6 +140,82 @@ private:
130
140
  return promise;
131
141
  }
132
142
 
143
+ /**
144
+ * Returns metadata for every digital signature in the document (async).
145
+ */
146
+ Napi::Value GetSignatures(const Napi::CallbackInfo &info) {
147
+ Napi::Env env = info.Env();
148
+ EnsureOpen(env);
149
+ if (env.IsExceptionPending())
150
+ return env.Null();
151
+
152
+ auto *worker = new GetSignaturesWorker(env, doc_, docAlive_);
153
+ auto promise = worker->Promise();
154
+ worker->Queue();
155
+ return promise;
156
+ }
157
+
158
+ /**
159
+ * Reads the raw /Contents bytes (PKCS#1 / PKCS#7 DER) of the signature at
160
+ * `index` (async). Resolves to a Buffer, or writes to an optional output
161
+ * path and resolves to undefined.
162
+ */
163
+ Napi::Value GetSignatureContents(const Napi::CallbackInfo &info) {
164
+ Napi::Env env = info.Env();
165
+ EnsureOpen(env);
166
+ if (env.IsExceptionPending())
167
+ return env.Null();
168
+
169
+ if (info.Length() < 1 || !info[0].IsNumber()) {
170
+ Napi::TypeError::New(env, "Expected signature index")
171
+ .ThrowAsJavaScriptException();
172
+ return env.Null();
173
+ }
174
+
175
+ int index = info[0].As<Napi::Number>().Int32Value();
176
+
177
+ std::string outputPath;
178
+ if (info.Length() > 1 && info[1].IsString()) {
179
+ outputPath = info[1].As<Napi::String>().Utf8Value();
180
+ }
181
+
182
+ auto *worker = new GetSignatureContentsWorker(
183
+ env, doc_, index, std::move(outputPath), docAlive_);
184
+ auto promise = worker->Promise();
185
+ worker->Queue();
186
+ return promise;
187
+ }
188
+
189
+ /**
190
+ * Returns every document-level JavaScript action (async).
191
+ */
192
+ Napi::Value GetJavaScriptActions(const Napi::CallbackInfo &info) {
193
+ Napi::Env env = info.Env();
194
+ EnsureOpen(env);
195
+ if (env.IsExceptionPending())
196
+ return env.Null();
197
+
198
+ auto *worker = new GetJavaScriptActionsWorker(env, doc_, docAlive_);
199
+ auto promise = worker->Promise();
200
+ worker->Queue();
201
+ return promise;
202
+ }
203
+
204
+ /**
205
+ * Returns every named destination in the document (async).
206
+ */
207
+ Napi::Value GetNamedDestinations(const Napi::CallbackInfo &info) {
208
+ Napi::Env env = info.Env();
209
+ EnsureOpen(env);
210
+ if (env.IsExceptionPending())
211
+ return env.Null();
212
+
213
+ auto *worker = new GetNamedDestinationsWorker(env, doc_, docAlive_);
214
+ auto promise = worker->Promise();
215
+ worker->Queue();
216
+ return promise;
217
+ }
218
+
133
219
  /**
134
220
  * Closes the document and releases all resources.
135
221
  */
@@ -0,0 +1,78 @@
1
+ #pragma once
2
+
3
+ #include "napi_helpers.h"
4
+
5
+ #include <climits>
6
+ #include <string>
7
+ #include <vector>
8
+
9
+ #include "fpdf_save.h"
10
+
11
+ // ---------------------------------------------------------------------------
12
+ // Document load/save plumbing shared by the document-producing workers
13
+ // ---------------------------------------------------------------------------
14
+ // Split, merge, assemble and n-up all follow the same shape: open one or more
15
+ // source documents, build a new one, then hand the result back either as a
16
+ // Buffer or written to a path.
17
+
18
+ // ---------------------------------------------------------------------------
19
+ // FPDF_FILEWRITE adapter — collects saved PDF bytes into a std::vector
20
+ // ---------------------------------------------------------------------------
21
+
22
+ struct VectorFileWrite : FPDF_FILEWRITE {
23
+ std::vector<uint8_t> data;
24
+
25
+ VectorFileWrite() {
26
+ version = 1;
27
+ WriteBlock = [](FPDF_FILEWRITE_ *self, const void *buf,
28
+ unsigned long size) -> int {
29
+ auto *w = static_cast<VectorFileWrite *>(self);
30
+ auto *bytes = static_cast<const uint8_t *>(buf);
31
+ w->data.insert(w->data.end(), bytes, bytes + size);
32
+ return 1;
33
+ };
34
+ }
35
+ };
36
+
37
+ // helper: save a document to buffer or file, returning the buffer data
38
+ static inline bool SaveDocument(FPDF_DOCUMENT doc,
39
+ const std::string &outputPath,
40
+ std::vector<uint8_t> &outData,
41
+ std::string &outError) {
42
+ VectorFileWrite writer;
43
+ if (!FPDF_SaveAsCopy(doc, &writer, 0)) {
44
+ outError = "Failed to save PDF document";
45
+ return false;
46
+ }
47
+
48
+ if (!outputPath.empty()) {
49
+ return WriteBytesToFile(outputPath, writer.data, outError);
50
+ }
51
+ outData = std::move(writer.data);
52
+ return true;
53
+ }
54
+
55
+ // helper: load a document from buffer or file path
56
+ static inline FPDF_DOCUMENT LoadDoc(const std::vector<uint8_t> &bufferData,
57
+ const std::string &filePath, bool useFile,
58
+ const std::string &password,
59
+ std::string &outError) {
60
+ const char *pw = password.empty() ? nullptr : password.c_str();
61
+ FPDF_DOCUMENT doc;
62
+
63
+ if (useFile) {
64
+ doc = FPDF_LoadDocument(filePath.c_str(), pw);
65
+ } else {
66
+ if (bufferData.size() > static_cast<size_t>(INT_MAX)) {
67
+ outError = "FORMAT:Buffer too large";
68
+ return nullptr;
69
+ }
70
+ doc = FPDF_LoadMemDocument(bufferData.data(),
71
+ static_cast<int>(bufferData.size()), pw);
72
+ }
73
+
74
+ if (!doc) {
75
+ outError = GetPdfiumErrorMessage();
76
+ }
77
+ return doc;
78
+ }
@@ -0,0 +1,133 @@
1
+ #pragma once
2
+
3
+ #include "document_io.h"
4
+
5
+ #include <string>
6
+ #include <vector>
7
+
8
+ #include "fpdf_flatten.h"
9
+
10
+ // ---------------------------------------------------------------------------
11
+ // FlattenDocumentWorker — bake annotations and widgets into page content
12
+ // ---------------------------------------------------------------------------
13
+ // Flattening merges each annotation's appearance stream into the page's own
14
+ // content stream and drops the annotation. The result renders identically
15
+ // everywhere but is no longer interactive — the usual reason to do it is
16
+ // archiving, or handing a filled form to a system that ignores annotations.
17
+ //
18
+ // This does NOT initialise a form-fill environment, so it bakes in the
19
+ // appearance streams the document already carries rather than regenerating
20
+ // them. For any PDF whose widgets have valid /AP entries — which is what every
21
+ // mainstream producer writes — that is exactly right. A form flagged
22
+ // /NeedAppearances, meaning "viewer, please regenerate these", is the case it
23
+ // cannot help with.
24
+
25
+ class FlattenDocumentWorker : public SafeAsyncWorker {
26
+ public:
27
+ // buffer variant
28
+ FlattenDocumentWorker(Napi::Env env, std::vector<uint8_t> data, int flag,
29
+ std::vector<int> pages, std::string outputPath,
30
+ std::string password)
31
+ : SafeAsyncWorker(env), deferred_(Napi::Promise::Deferred::New(env)),
32
+ bufferData_(std::move(data)), flag_(flag), pages_(std::move(pages)),
33
+ outputPath_(std::move(outputPath)), password_(std::move(password)),
34
+ useFile_(false) {}
35
+
36
+ // file path variant
37
+ FlattenDocumentWorker(Napi::Env env, std::string filePath, int flag,
38
+ std::vector<int> pages, std::string outputPath,
39
+ std::string password)
40
+ : SafeAsyncWorker(env), deferred_(Napi::Promise::Deferred::New(env)),
41
+ filePath_(std::move(filePath)), flag_(flag), pages_(std::move(pages)),
42
+ outputPath_(std::move(outputPath)), password_(std::move(password)),
43
+ useFile_(true) {}
44
+
45
+ Napi::Promise Promise() { return deferred_.Promise(); }
46
+
47
+ protected:
48
+ void Execute() override {
49
+ std::lock_guard<std::mutex> lock(g_pdfium_mutex);
50
+
51
+ std::string loadError;
52
+ FPDF_DOCUMENT doc =
53
+ LoadDoc(bufferData_, filePath_, useFile_, password_, loadError);
54
+ if (!doc) {
55
+ SetError(loadError);
56
+ return;
57
+ }
58
+
59
+ int pageCount = FPDF_GetPageCount(doc);
60
+
61
+ std::vector<int> targets = pages_;
62
+ if (targets.empty()) {
63
+ targets.reserve(pageCount);
64
+ for (int i = 0; i < pageCount; i++)
65
+ targets.push_back(i);
66
+ } else {
67
+ for (int page : targets) {
68
+ if (page < 0 || page >= pageCount) {
69
+ FPDF_CloseDocument(doc);
70
+ SetError("Page index out of range: " + std::to_string(page));
71
+ return;
72
+ }
73
+ }
74
+ }
75
+
76
+ for (int index : targets) {
77
+ FPDF_PAGE page = FPDF_LoadPage(doc, index);
78
+ if (!page) {
79
+ FPDF_CloseDocument(doc);
80
+ SetError("Failed to load page " + std::to_string(index));
81
+ return;
82
+ }
83
+
84
+ int result = FPDFPage_Flatten(page, flag_);
85
+ FPDF_ClosePage(page);
86
+
87
+ // FLATTEN_NOTHINGTODO simply means the page had no annotations, which is
88
+ // a normal outcome rather than a failure. Only FLATTEN_FAIL is an error,
89
+ // and PDFium gives no reason for it.
90
+ if (result == FLATTEN_FAIL) {
91
+ FPDF_CloseDocument(doc);
92
+ SetError("Failed to flatten page " + std::to_string(index));
93
+ return;
94
+ }
95
+ }
96
+
97
+ std::string saveError;
98
+ if (!SaveDocument(doc, outputPath_, resultData_, saveError)) {
99
+ FPDF_CloseDocument(doc);
100
+ SetError(saveError);
101
+ return;
102
+ }
103
+
104
+ FPDF_CloseDocument(doc);
105
+ }
106
+
107
+ void OnOK() override {
108
+ Napi::Env env = Env();
109
+ if (!outputPath_.empty()) {
110
+ deferred_.Resolve(env.Undefined());
111
+ return;
112
+ }
113
+ auto *vec = new std::vector<uint8_t>(std::move(resultData_));
114
+ deferred_.Resolve(Napi::Buffer<uint8_t>::New(
115
+ env, vec->data(), vec->size(),
116
+ [](Napi::Env, uint8_t *, std::vector<uint8_t> *v) { delete v; }, vec));
117
+ }
118
+
119
+ void OnError(const Napi::Error &err) override {
120
+ deferred_.Reject(err.Value());
121
+ }
122
+
123
+ private:
124
+ Napi::Promise::Deferred deferred_;
125
+ std::vector<uint8_t> bufferData_;
126
+ std::string filePath_;
127
+ int flag_ = FLAT_NORMALDISPLAY;
128
+ std::vector<int> pages_;
129
+ std::string outputPath_;
130
+ std::string password_;
131
+ bool useFile_ = false;
132
+ std::vector<uint8_t> resultData_;
133
+ };