pdfium-native 0.2.0 → 0.2.3

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.
@@ -1,5 +1,11 @@
1
1
  #include "document.h"
2
2
 
3
+ #include <climits>
4
+
5
+ #include "fpdf_attachment.h"
6
+ #include "fpdf_catalog.h"
7
+ #include "fpdf_signature.h"
8
+
3
9
  Napi::FunctionReference PDFiumDocument::pageConstructor;
4
10
 
5
11
  // ---------------------------------------------------------------------------
@@ -71,6 +77,10 @@ protected:
71
77
  if (useFile_) {
72
78
  doc_ = FPDF_LoadDocument(filePath_.c_str(), pw);
73
79
  } else {
80
+ if (bufferData_.size() > static_cast<size_t>(INT_MAX)) {
81
+ SetError("FORMAT:Buffer too large");
82
+ return;
83
+ }
74
84
  doc_ = FPDF_LoadMemDocument(bufferData_.data(),
75
85
  static_cast<int>(bufferData_.size()), pw);
76
86
  }
@@ -86,16 +96,53 @@ protected:
86
96
  const char *metaTags[] = {"Title", "Author", "Subject", "Keywords",
87
97
  "Creator", "Producer", "CreationDate", "ModDate"};
88
98
  for (int i = 0; i < 8; i++) {
89
- unsigned long len = FPDF_GetMetaText(doc_, metaTags[i], nullptr, 0);
90
- if (len > 2) {
91
- std::vector<unsigned short> buf(len / sizeof(unsigned short));
92
- FPDF_GetMetaText(doc_, metaTags[i], buf.data(), len);
93
- size_t charCount = len / sizeof(unsigned short) - 1;
94
- meta_[i] = std::u16string(
95
- reinterpret_cast<const char16_t *>(buf.data()), charCount);
96
- }
99
+ meta_[i] = ReadU16(
100
+ [&](auto *, unsigned long) {
101
+ return FPDF_GetMetaText(doc_, metaTags[i], nullptr, 0);
102
+ },
103
+ [&](FPDF_WCHAR *buf, unsigned long len) {
104
+ return FPDF_GetMetaText(doc_, metaTags[i], buf, len);
105
+ });
97
106
  }
98
107
  FPDF_GetFileVersion(doc_, &pdfVersion_);
108
+ permissions_ = FPDF_GetDocPermissions(doc_);
109
+
110
+ // tagged PDF flag
111
+ isTagged_ = FPDFCatalog_IsTagged(doc_) != 0;
112
+
113
+ // document language (UTF-16LE encoded)
114
+ language_ = ReadU16(
115
+ [&](auto *, unsigned long) {
116
+ return FPDFCatalog_GetLanguage(doc_, nullptr, 0);
117
+ },
118
+ [&](FPDF_WCHAR *buf, unsigned long len) {
119
+ return FPDFCatalog_GetLanguage(doc_, buf, len);
120
+ });
121
+
122
+ // signature and attachment counts
123
+ signatureCount_ = FPDF_GetSignatureCount(doc_);
124
+ attachmentCount_ = FPDFDoc_GetAttachmentCount(doc_);
125
+
126
+ // file identifiers (raw byte strings → hex)
127
+ auto readFileId = [&](FPDF_FILEIDTYPE idType) -> std::string {
128
+ unsigned long len = FPDF_GetFileIdentifier(doc_, idType, nullptr, 0);
129
+ if (len <= 1)
130
+ return "";
131
+ std::vector<char> buf(len);
132
+ FPDF_GetFileIdentifier(doc_, idType, buf.data(), len);
133
+ // convert raw bytes to hex string
134
+ static const char hex[] = "0123456789abcdef";
135
+ std::string result;
136
+ result.reserve((len - 1) * 2);
137
+ for (unsigned long j = 0; j < len - 1; j++) {
138
+ unsigned char c = static_cast<unsigned char>(buf[j]);
139
+ result.push_back(hex[c >> 4]);
140
+ result.push_back(hex[c & 0x0F]);
141
+ }
142
+ return result;
143
+ };
144
+ permanentId_ = readFileId(FILEIDTYPE_PERMANENT);
145
+ changingId_ = readFileId(FILEIDTYPE_CHANGING);
99
146
  }
100
147
 
101
148
  void OnOK() override {
@@ -111,17 +158,39 @@ protected:
111
158
  "creator", "producer", "creationDate", "modDate"};
112
159
  Napi::Object metaObj = Napi::Object::New(env);
113
160
  for (int i = 0; i < 8; i++) {
114
- if (meta_[i].empty()) {
115
- metaObj.Set(metaKeys[i], Napi::String::New(env, ""));
116
- } else {
117
- metaObj.Set(metaKeys[i],
118
- Napi::String::New(
119
- env,
120
- reinterpret_cast<const char16_t *>(meta_[i].data()),
121
- meta_[i].size()));
122
- }
161
+ SetU16(metaObj, metaKeys[i], env, meta_[i]);
123
162
  }
124
163
  metaObj.Set("pdfVersion", Napi::Number::New(env, pdfVersion_));
164
+
165
+ // permission flags (ISO 32000-1:2008, Table 22)
166
+ Napi::Object permObj = Napi::Object::New(env);
167
+ permObj.Set("print",
168
+ Napi::Boolean::New(env, (permissions_ & (1 << 2)) != 0));
169
+ permObj.Set("modify",
170
+ Napi::Boolean::New(env, (permissions_ & (1 << 3)) != 0));
171
+ permObj.Set("copy",
172
+ Napi::Boolean::New(env, (permissions_ & (1 << 4)) != 0));
173
+ permObj.Set("annotate",
174
+ Napi::Boolean::New(env, (permissions_ & (1 << 5)) != 0));
175
+ permObj.Set("fillForms",
176
+ Napi::Boolean::New(env, (permissions_ & (1 << 8)) != 0));
177
+ permObj.Set("extractForAccessibility",
178
+ Napi::Boolean::New(env, (permissions_ & (1 << 9)) != 0));
179
+ permObj.Set("assemble",
180
+ Napi::Boolean::New(env, (permissions_ & (1 << 10)) != 0));
181
+ permObj.Set("printHighQuality",
182
+ Napi::Boolean::New(env, (permissions_ & (1 << 11)) != 0));
183
+ metaObj.Set("permissions", permObj);
184
+
185
+ metaObj.Set("isTagged", Napi::Boolean::New(env, isTagged_));
186
+ SetU16(metaObj, "language", env, language_);
187
+ metaObj.Set("signatureCount", Napi::Number::New(env, signatureCount_));
188
+ metaObj.Set("attachmentCount", Napi::Number::New(env, attachmentCount_));
189
+ if (!permanentId_.empty())
190
+ metaObj.Set("permanentId", Napi::String::New(env, permanentId_));
191
+ if (!changingId_.empty())
192
+ metaObj.Set("changingId", Napi::String::New(env, changingId_));
193
+
125
194
  docObj.Set("metadata", metaObj);
126
195
 
127
196
  // for buffer variant, transfer ownership of the copied data
@@ -147,6 +216,13 @@ private:
147
216
  int pageCount_ = 0;
148
217
  std::u16string meta_[8];
149
218
  int pdfVersion_ = 0;
219
+ unsigned long permissions_ = 0xFFFFFFFF;
220
+ bool isTagged_ = false;
221
+ std::u16string language_;
222
+ int signatureCount_ = 0;
223
+ int attachmentCount_ = 0;
224
+ std::string permanentId_;
225
+ std::string changingId_;
150
226
  };
151
227
 
152
228
  /**
@@ -11,6 +11,8 @@
11
11
 
12
12
  // stb write callback — appends bytes to a std::vector
13
13
  inline void stb_write_callback(void *context, void *data, int size) {
14
+ if (size <= 0)
15
+ return;
14
16
  auto *out = static_cast<std::vector<uint8_t> *>(context);
15
17
  auto *bytes = static_cast<uint8_t *>(data);
16
18
  out->insert(out->end(), bytes, bytes + size);
@@ -23,12 +25,14 @@ inline void stb_write_callback(void *context, void *data, int size) {
23
25
  class RenderWorker : public Napi::AsyncWorker {
24
26
  public:
25
27
  RenderWorker(Napi::Env env, FPDF_PAGE page, int renderWidth, int renderHeight,
26
- int format, int quality, std::string outputPath,
28
+ int format, int quality, std::string outputPath, int rotation,
29
+ bool transparent, int renderFlags,
27
30
  std::shared_ptr<std::atomic<bool>> pageAlive)
28
31
  : Napi::AsyncWorker(env), deferred_(Napi::Promise::Deferred::New(env)),
29
32
  page_(page), renderWidth_(renderWidth), renderHeight_(renderHeight),
30
33
  format_(format), quality_(quality), outputPath_(std::move(outputPath)),
31
- pageAlive_(std::move(pageAlive)) {}
34
+ rotation_(rotation), transparent_(transparent),
35
+ renderFlags_(renderFlags), pageAlive_(std::move(pageAlive)) {}
32
36
 
33
37
  Napi::Promise Promise() { return deferred_.Promise(); }
34
38
 
@@ -42,30 +46,43 @@ protected:
42
46
  return;
43
47
  }
44
48
 
45
- FPDF_BITMAP bitmap = FPDFBitmap_Create(renderWidth_, renderHeight_, 0);
49
+ FPDF_BITMAP bitmap =
50
+ FPDFBitmap_Create(renderWidth_, renderHeight_, transparent_ ? 1 : 0);
46
51
  if (!bitmap) {
47
52
  SetError("Failed to create bitmap");
48
53
  return;
49
54
  }
50
55
 
51
- FPDFBitmap_FillRect(bitmap, 0, 0, renderWidth_, renderHeight_, 0xFFFFFFFF);
52
- FPDF_RenderPageBitmap(bitmap, page_, 0, 0, renderWidth_, renderHeight_, 0,
53
- FPDF_ANNOT | FPDF_PRINTING);
56
+ if (!transparent_) {
57
+ FPDFBitmap_FillRect(bitmap, 0, 0, renderWidth_, renderHeight_,
58
+ 0xFFFFFFFF);
59
+ }
60
+ FPDF_RenderPageBitmap(bitmap, page_, 0, 0, renderWidth_, renderHeight_,
61
+ rotation_, renderFlags_);
62
+
63
+ int channels = transparent_ ? 4 : 3;
54
64
 
55
- // convert BGRA → RGB for stb (which expects RGB)
65
+ // convert BGRA → RGB or BGRA → RGBA for stb
56
66
  void *bufferData = FPDFBitmap_GetBuffer(bitmap);
57
67
  int stride = FPDFBitmap_GetStride(bitmap);
58
- std::vector<uint8_t> rgb(static_cast<size_t>(renderWidth_) * renderHeight_ *
59
- 3);
68
+ if (!bufferData || stride < renderWidth_ * 4) {
69
+ FPDFBitmap_Destroy(bitmap);
70
+ SetError("Failed to get bitmap buffer");
71
+ return;
72
+ }
73
+ std::vector<uint8_t> pixels(static_cast<size_t>(renderWidth_) *
74
+ static_cast<size_t>(renderHeight_) * channels);
60
75
 
61
76
  for (int y = 0; y < renderHeight_; y++) {
62
77
  auto *row = static_cast<uint8_t *>(bufferData) + y * stride;
63
78
  for (int x = 0; x < renderWidth_; x++) {
64
79
  int srcIdx = x * 4;
65
- int dstIdx = (y * renderWidth_ + x) * 3;
66
- rgb[dstIdx + 0] = row[srcIdx + 2]; // R ← BGRA[2]
67
- rgb[dstIdx + 1] = row[srcIdx + 1]; // G ← BGRA[1]
68
- rgb[dstIdx + 2] = row[srcIdx + 0]; // B ← BGRA[0]
80
+ int dstIdx = (y * renderWidth_ + x) * channels;
81
+ pixels[dstIdx + 0] = row[srcIdx + 2]; // R ← BGRA[2]
82
+ pixels[dstIdx + 1] = row[srcIdx + 1]; // G ← BGRA[1]
83
+ pixels[dstIdx + 2] = row[srcIdx + 0]; // B ← BGRA[0]
84
+ if (transparent_)
85
+ pixels[dstIdx + 3] = row[srcIdx + 3]; // A ← BGRA[3]
69
86
  }
70
87
  }
71
88
 
@@ -75,12 +92,12 @@ protected:
75
92
  int ok;
76
93
  if (format_ == IMAGE_FORMAT_PNG) {
77
94
  ok = stbi_write_png_to_func(stb_write_callback, &encodedData_,
78
- renderWidth_, renderHeight_, 3, rgb.data(),
79
- renderWidth_ * 3);
95
+ renderWidth_, renderHeight_, channels,
96
+ pixels.data(), renderWidth_ * channels);
80
97
  } else {
81
98
  ok = stbi_write_jpg_to_func(stb_write_callback, &encodedData_,
82
- renderWidth_, renderHeight_, 3, rgb.data(),
83
- quality_);
99
+ renderWidth_, renderHeight_, channels,
100
+ pixels.data(), quality_);
84
101
  }
85
102
 
86
103
  if (!ok) {
@@ -136,6 +153,9 @@ private:
136
153
  int format_;
137
154
  int quality_;
138
155
  std::string outputPath_;
156
+ int rotation_;
157
+ bool transparent_;
158
+ int renderFlags_;
139
159
  std::vector<uint8_t> encodedData_;
140
160
  std::shared_ptr<std::atomic<bool>> pageAlive_;
141
161
  };
@@ -0,0 +1,121 @@
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
+ // SearchWorker — async text search
15
+ // ---------------------------------------------------------------------------
16
+
17
+ struct SearchMatchData {
18
+ int charIndex;
19
+ int length;
20
+ std::u16string matchedText;
21
+ struct Rect {
22
+ double left, bottom, right, top;
23
+ };
24
+ std::vector<Rect> rects;
25
+ };
26
+
27
+ class SearchWorker : public Napi::AsyncWorker {
28
+ public:
29
+ SearchWorker(Napi::Env env, FPDF_PAGE page, std::u16string needle,
30
+ unsigned long flags,
31
+ std::shared_ptr<std::atomic<bool>> pageAlive,
32
+ std::shared_ptr<std::atomic<bool>> docAlive)
33
+ : Napi::AsyncWorker(env), deferred_(Napi::Promise::Deferred::New(env)),
34
+ page_(page), needle_(std::move(needle)), flags_(flags),
35
+ pageAlive_(std::move(pageAlive)), docAlive_(std::move(docAlive)) {}
36
+
37
+ Napi::Promise Promise() { return deferred_.Promise(); }
38
+
39
+ protected:
40
+ void Execute() override {
41
+ std::lock_guard<std::mutex> lock(g_pdfium_mutex);
42
+ CHECK_ALIVE();
43
+
44
+ FPDF_TEXTPAGE textPage = FPDFText_LoadPage(page_);
45
+ if (!textPage) {
46
+ SetError("Failed to load text page");
47
+ return;
48
+ }
49
+
50
+ FPDF_SCHHANDLE handle = FPDFText_FindStart(
51
+ textPage, reinterpret_cast<const unsigned short *>(needle_.c_str()),
52
+ flags_, 0);
53
+
54
+ if (handle) {
55
+ while (FPDFText_FindNext(handle)) {
56
+ SearchMatchData match;
57
+ match.charIndex = FPDFText_GetSchResultIndex(handle);
58
+ match.length = FPDFText_GetSchCount(handle);
59
+
60
+ // extract the matched text
61
+ if (match.length > 0 && match.length < INT_MAX) {
62
+ size_t textBufLen = static_cast<size_t>(match.length) + 1;
63
+ std::vector<unsigned short> textBuf(textBufLen);
64
+ int got = FPDFText_GetText(textPage, match.charIndex, match.length,
65
+ textBuf.data());
66
+ if (got > 0) {
67
+ match.matchedText = std::u16string(
68
+ reinterpret_cast<const char16_t *>(textBuf.data()),
69
+ static_cast<size_t>(got - 1));
70
+ }
71
+ }
72
+
73
+ int numRects =
74
+ FPDFText_CountRects(textPage, match.charIndex, match.length);
75
+ for (int r = 0; r < numRects; r++) {
76
+ double left, top, right, bottom;
77
+ if (FPDFText_GetRect(textPage, r, &left, &top, &right, &bottom)) {
78
+ match.rects.push_back({left, bottom, right, top});
79
+ }
80
+ }
81
+ matches_.push_back(std::move(match));
82
+ }
83
+ FPDFText_FindClose(handle);
84
+ }
85
+ FPDFText_ClosePage(textPage);
86
+ }
87
+
88
+ void OnOK() override {
89
+ Napi::Env env = Env();
90
+ Napi::Array results = Napi::Array::New(env, matches_.size());
91
+ for (uint32_t i = 0; i < matches_.size(); i++) {
92
+ auto &m = matches_[i];
93
+ Napi::Object match = Napi::Object::New(env);
94
+ match.Set("charIndex", Napi::Number::New(env, m.charIndex));
95
+ match.Set("length", Napi::Number::New(env, m.length));
96
+ SetU16IfPresent(match, "matchedText", env, m.matchedText);
97
+
98
+ Napi::Array rects = Napi::Array::New(env, m.rects.size());
99
+ for (uint32_t r = 0; r < m.rects.size(); r++) {
100
+ rects.Set(r, CreateBoundsObject(env, m.rects[r].left, m.rects[r].bottom,
101
+ m.rects[r].right, m.rects[r].top));
102
+ }
103
+ match.Set("rects", rects);
104
+ results.Set(i, match);
105
+ }
106
+ deferred_.Resolve(results);
107
+ }
108
+
109
+ void OnError(const Napi::Error &err) override {
110
+ deferred_.Reject(err.Value());
111
+ }
112
+
113
+ private:
114
+ Napi::Promise::Deferred deferred_;
115
+ FPDF_PAGE page_;
116
+ std::u16string needle_;
117
+ unsigned long flags_;
118
+ std::shared_ptr<std::atomic<bool>> pageAlive_;
119
+ std::shared_ptr<std::atomic<bool>> docAlive_;
120
+ std::vector<SearchMatchData> matches_;
121
+ };
@@ -0,0 +1,69 @@
1
+ #pragma once
2
+
3
+ #include "napi_helpers.h"
4
+
5
+ #include <atomic>
6
+ #include <climits>
7
+ #include <memory>
8
+ #include <vector>
9
+
10
+ #include "fpdf_text.h"
11
+
12
+ // ---------------------------------------------------------------------------
13
+ // GetTextWorker — async text extraction
14
+ // ---------------------------------------------------------------------------
15
+
16
+ class GetTextWorker : public Napi::AsyncWorker {
17
+ public:
18
+ GetTextWorker(Napi::Env env, FPDF_PAGE page,
19
+ std::shared_ptr<std::atomic<bool>> pageAlive,
20
+ std::shared_ptr<std::atomic<bool>> docAlive)
21
+ : Napi::AsyncWorker(env), deferred_(Napi::Promise::Deferred::New(env)),
22
+ page_(page), pageAlive_(std::move(pageAlive)),
23
+ docAlive_(std::move(docAlive)) {}
24
+
25
+ Napi::Promise Promise() { return deferred_.Promise(); }
26
+
27
+ protected:
28
+ void Execute() override {
29
+ std::lock_guard<std::mutex> lock(g_pdfium_mutex);
30
+ CHECK_ALIVE();
31
+
32
+ FPDF_TEXTPAGE textPage = FPDFText_LoadPage(page_);
33
+ if (!textPage) {
34
+ SetError("Failed to load text page");
35
+ return;
36
+ }
37
+
38
+ int charCount = FPDFText_CountChars(textPage);
39
+ if (charCount > 0 && charCount < INT_MAX) {
40
+ size_t bufLen = static_cast<size_t>(charCount) + 1;
41
+ textBuf_.resize(bufLen);
42
+ FPDFText_GetText(textPage, 0, charCount, textBuf_.data());
43
+ textLen_ = charCount;
44
+ }
45
+ FPDFText_ClosePage(textPage);
46
+ }
47
+
48
+ void OnOK() override {
49
+ Napi::Env env = Env();
50
+ if (textLen_ == 0) {
51
+ deferred_.Resolve(Napi::String::New(env, ""));
52
+ } else {
53
+ deferred_.Resolve(Napi::String::New(
54
+ env, reinterpret_cast<const char16_t *>(textBuf_.data()), textLen_));
55
+ }
56
+ }
57
+
58
+ void OnError(const Napi::Error &err) override {
59
+ deferred_.Reject(err.Value());
60
+ }
61
+
62
+ private:
63
+ Napi::Promise::Deferred deferred_;
64
+ FPDF_PAGE page_;
65
+ std::shared_ptr<std::atomic<bool>> pageAlive_;
66
+ std::shared_ptr<std::atomic<bool>> docAlive_;
67
+ std::vector<unsigned short> textBuf_;
68
+ int textLen_ = 0;
69
+ };