pdfium-native 0.8.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.
@@ -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
+ };
@@ -0,0 +1,105 @@
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_javascript.h"
11
+
12
+ // ---------------------------------------------------------------------------
13
+ // GetJavaScriptActionsWorker — async document-level JavaScript listing
14
+ // ---------------------------------------------------------------------------
15
+ // These are the scripts in the document's /Names /JavaScript tree, which a
16
+ // viewer runs when the document opens. Surfacing them matters mostly for
17
+ // inspection and triage: a PDF arriving from outside that carries
18
+ // document-open JavaScript is worth a second look before it is rendered.
19
+ //
20
+ // pdfium-native never executes any of it — the build has V8 disabled, so the
21
+ // script comes back as inert text.
22
+
23
+ struct JavaScriptActionInfo {
24
+ int index = 0;
25
+ std::u16string name;
26
+ std::u16string script;
27
+ };
28
+
29
+ class GetJavaScriptActionsWorker : public SafeAsyncWorker {
30
+ public:
31
+ GetJavaScriptActionsWorker(Napi::Env env, FPDF_DOCUMENT doc,
32
+ std::shared_ptr<std::atomic<bool>> docAlive)
33
+ : SafeAsyncWorker(env), deferred_(Napi::Promise::Deferred::New(env)),
34
+ doc_(doc), docAlive_(std::move(docAlive)) {}
35
+
36
+ Napi::Promise Promise() { return deferred_.Promise(); }
37
+
38
+ protected:
39
+ void Execute() override {
40
+ std::lock_guard<std::mutex> lock(g_pdfium_mutex);
41
+ if (!docAlive_ || !docAlive_->load()) {
42
+ SetError("Document was destroyed");
43
+ return;
44
+ }
45
+
46
+ int count = FPDFDoc_GetJavaScriptActionCount(doc_);
47
+ if (count <= 0)
48
+ return;
49
+
50
+ actions_.reserve(count);
51
+ for (int i = 0; i < count; i++) {
52
+ FPDF_JAVASCRIPT_ACTION action = FPDFDoc_GetJavaScriptAction(doc_, i);
53
+ if (!action)
54
+ continue;
55
+
56
+ JavaScriptActionInfo info;
57
+ info.index = i;
58
+
59
+ info.name = ReadU16(
60
+ [&](auto *, unsigned long) {
61
+ return FPDFJavaScriptAction_GetName(action, nullptr, 0);
62
+ },
63
+ [&](FPDF_WCHAR *buf, unsigned long len) {
64
+ return FPDFJavaScriptAction_GetName(action, buf, len);
65
+ });
66
+
67
+ info.script = ReadU16(
68
+ [&](auto *, unsigned long) {
69
+ return FPDFJavaScriptAction_GetScript(action, nullptr, 0);
70
+ },
71
+ [&](FPDF_WCHAR *buf, unsigned long len) {
72
+ return FPDFJavaScriptAction_GetScript(action, buf, len);
73
+ });
74
+
75
+ // unlike attachments and signatures, the caller owns this handle
76
+ FPDFDoc_CloseJavaScriptAction(action);
77
+
78
+ actions_.push_back(std::move(info));
79
+ }
80
+ }
81
+
82
+ void OnOK() override {
83
+ Napi::Env env = Env();
84
+ Napi::Array arr = Napi::Array::New(env, actions_.size());
85
+ for (uint32_t i = 0; i < actions_.size(); i++) {
86
+ const auto &info = actions_[i];
87
+ Napi::Object obj = Napi::Object::New(env);
88
+ obj.Set("index", Napi::Number::New(env, info.index));
89
+ SetU16(obj, "name", env, info.name);
90
+ SetU16(obj, "script", env, info.script);
91
+ arr.Set(i, obj);
92
+ }
93
+ deferred_.Resolve(arr);
94
+ }
95
+
96
+ void OnError(const Napi::Error &err) override {
97
+ deferred_.Reject(err.Value());
98
+ }
99
+
100
+ private:
101
+ Napi::Promise::Deferred deferred_;
102
+ FPDF_DOCUMENT doc_;
103
+ std::shared_ptr<std::atomic<bool>> docAlive_;
104
+ std::vector<JavaScriptActionInfo> actions_;
105
+ };
@@ -1,11 +1,20 @@
1
1
  #pragma once
2
2
 
3
3
  #include <atomic>
4
+ #include <cstdio>
4
5
  #include <mutex>
5
6
  #include <napi.h>
6
7
  #include <string>
7
8
  #include <vector>
8
9
 
10
+ #ifdef _WIN32
11
+ #include <io.h>
12
+ #define F_OK 0
13
+ #define access _access
14
+ #else
15
+ #include <unistd.h>
16
+ #endif
17
+
9
18
  #include "fpdf_doc.h"
10
19
  #include "fpdfview.h"
11
20
 
@@ -172,6 +181,19 @@ inline std::u16string ReadU16(GetLen getLen, GetData getData) {
172
181
  len / sizeof(unsigned short) - 1);
173
182
  }
174
183
 
184
+ // read a PDFium null-terminated byte buffer (7-bit ASCII or UTF-8) into a
185
+ // std::string. Both callbacks return the byte length including the null
186
+ // terminator; the terminator is dropped from the result.
187
+ template <typename GetLen, typename GetData>
188
+ inline std::string ReadUtf8(GetLen getLen, GetData getData) {
189
+ unsigned long len = getLen(static_cast<char *>(nullptr), 0);
190
+ if (len < 2)
191
+ return {};
192
+ std::vector<char> buf(len);
193
+ getData(buf.data(), len);
194
+ return std::string(buf.data(), len - 1);
195
+ }
196
+
175
197
  // convert a std::u16string to a Napi::String (empty string if input is empty)
176
198
  inline Napi::String ToNapiString(Napi::Env env, const std::u16string &s) {
177
199
  if (s.empty())
@@ -193,6 +215,39 @@ inline void SetU16IfPresent(Napi::Object &obj, const char *key, Napi::Env env,
193
215
  obj.Set(key, ToNapiString(env, s));
194
216
  }
195
217
 
218
+ // ---------------------------------------------------------------------------
219
+ // File output helper
220
+ // ---------------------------------------------------------------------------
221
+
222
+ // Writes bytes to `path`, verifying the parent directory exists first (mirrors
223
+ // RenderWorker). Returns false and sets `err` on failure.
224
+ inline bool WriteBytesToFile(const std::string &path,
225
+ const std::vector<uint8_t> &data,
226
+ std::string &err) {
227
+ auto slash = path.rfind('/');
228
+ if (slash != std::string::npos && slash > 0) {
229
+ std::string parentDir = path.substr(0, slash);
230
+ if (access(parentDir.c_str(), F_OK) != 0) {
231
+ err = "Parent directory does not exist: " + parentDir;
232
+ return false;
233
+ }
234
+ }
235
+
236
+ FILE *f = fopen(path.c_str(), "wb");
237
+ if (!f) {
238
+ err = "Failed to open output file: " + path;
239
+ return false;
240
+ }
241
+ size_t total = data.size();
242
+ size_t wrote = total == 0 ? 0 : fwrite(data.data(), 1, total, f);
243
+ fclose(f);
244
+ if (wrote != total) {
245
+ err = "Failed to write output file: " + path;
246
+ return false;
247
+ }
248
+ return true;
249
+ }
250
+
196
251
  // ---------------------------------------------------------------------------
197
252
  // action type string from FPDF action type constant
198
253
  // ---------------------------------------------------------------------------
package/src/page.h CHANGED
@@ -1,12 +1,14 @@
1
1
  #pragma once
2
2
 
3
3
  #include "annotations_worker.h"
4
+ #include "characters_worker.h"
4
5
  #include "form_fields_worker.h"
5
6
  #include "links_worker.h"
6
7
  #include "objects_worker.h"
7
8
  #include "render_image_worker.h"
8
9
  #include "render_worker.h"
9
10
  #include "search_worker.h"
11
+ #include "structtree_worker.h"
10
12
  #include "text_worker.h"
11
13
 
12
14
  #include <atomic>
@@ -29,6 +31,7 @@ public:
29
31
  {
30
32
  InstanceAccessor<&PDFiumPage::GetNumber>("number"),
31
33
  InstanceMethod<&PDFiumPage::GetText>("getText"),
34
+ InstanceMethod<&PDFiumPage::GetCharacters>("getCharacters"),
32
35
  InstanceMethod<&PDFiumPage::Render>("render"),
33
36
  InstanceMethod<&PDFiumPage::GetObject>("getObject"),
34
37
  InstanceMethod<&PDFiumPage::RenderImage>("renderImage"),
@@ -38,6 +41,7 @@ public:
38
41
  InstanceMethod<&PDFiumPage::GetAnnotationAttachment>(
39
42
  "getAnnotationAttachment"),
40
43
  InstanceMethod<&PDFiumPage::GetFormFields>("getFormFields"),
44
+ InstanceMethod<&PDFiumPage::GetStructTree>("getStructTree"),
41
45
  InstanceMethod<&PDFiumPage::Close>("close"),
42
46
  });
43
47
  }
@@ -107,6 +111,52 @@ private:
107
111
  return promise;
108
112
  }
109
113
 
114
+ /**
115
+ * Extracts every character with its position, font and rotation (async).
116
+ * Optional (start, count) arguments restrict the range; a negative count
117
+ * means "to the end of the page".
118
+ */
119
+ Napi::Value GetCharacters(const Napi::CallbackInfo &info) {
120
+ Napi::Env env = info.Env();
121
+ EnsureOpen(env);
122
+ if (env.IsExceptionPending())
123
+ return env.Null();
124
+
125
+ int start = 0;
126
+ int count = -1;
127
+ if (info.Length() > 0 && info[0].IsNumber())
128
+ start = info[0].As<Napi::Number>().Int32Value();
129
+ if (info.Length() > 1 && info[1].IsNumber())
130
+ count = info[1].As<Napi::Number>().Int32Value();
131
+
132
+ if (start < 0) {
133
+ Napi::RangeError::New(env, "Character start index must not be negative")
134
+ .ThrowAsJavaScriptException();
135
+ return env.Null();
136
+ }
137
+
138
+ auto *worker =
139
+ new GetCharactersWorker(env, page_, start, count, alive_, docAlive_);
140
+ auto promise = worker->Promise();
141
+ worker->Queue();
142
+ return promise;
143
+ }
144
+
145
+ /**
146
+ * Returns the tagged-PDF structure tree for this page (async).
147
+ */
148
+ Napi::Value GetStructTree(const Napi::CallbackInfo &info) {
149
+ Napi::Env env = info.Env();
150
+ EnsureOpen(env);
151
+ if (env.IsExceptionPending())
152
+ return env.Null();
153
+
154
+ auto *worker = new GetStructTreeWorker(env, page_, alive_, docAlive_);
155
+ auto promise = worker->Promise();
156
+ worker->Queue();
157
+ return promise;
158
+ }
159
+
110
160
  /**
111
161
  * Renders the page to a JPEG or PNG buffer (async).
112
162
  */