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
@@ -1,12 +1,12 @@
1
1
  {
2
- "darwin-arm64": "5a1d1596a29cb892dc9b813d32f17f4026a93b1dcdc82157df367be1ac3fb351",
3
- "darwin-x64": "870c4133cbb1a43da0fa1698b455c1fec9e497e909c6f30b4d74f348673f0cb1",
4
- "linux-arm": "9993cdebe939c30f812bac0ad66f5c2c46720270dc946c6bb384f3707d04fc0d",
5
- "linux-arm64": "f7d7891e304a1d727e5ab3d57d5b6f832dd1c1176cb12a1d0c2349b17b1f694e",
6
- "linux-musl-arm64": "0480aa7c1b692f641f6469d42764bf023bc121eaa2e20e210150e74a210789bb",
7
- "linux-musl-x64": "88c0c447f99cbb0ca0be062f81b4eb81f26a0a5f2215e64951a98ade54a46bf0",
8
- "linux-ppc64": "faf22918964ab4a4efb175b2edc500f455d69e5623c17dd9aaff53d4e62aaa78",
9
- "linux-x64": "f1710cb87a37e4bee4d3d97c5e5d143e519de18c8f4a9a8a44685bceb88d15de",
10
- "win32-arm64": "99f688bc3b398e57eec49b9763beaa0007a137e6518f2e69207a9c07879519f6",
11
- "win32-x64": "4c90fb7893b530c3c4b9771e9514cd52076072722764adc9f2725fadaf83073b"
2
+ "darwin-arm64": "56bddf0dad15140105f03bb3fd58ed333e77a989fba80af48c5397300a90cd0d",
3
+ "darwin-x64": "1075f8658d706d60e3697a3d0d9a12e3af85d66e3dff64424175c1874ce29726",
4
+ "linux-arm": "841b1753cd31a9538518c51745e987358468f0f19b92d65b82d61bce6dfc911f",
5
+ "linux-arm64": "28de3cd26006c6ceed129d03e3d1955ce0c12a7c5df4d9a0d4ce32406d7719da",
6
+ "linux-musl-arm64": "6a0d7b93baa006fa80ddacf29f369669618e9db4c58200062d1e74c479068b81",
7
+ "linux-musl-x64": "2050dbe6dddfbc3bc1877740d734474afef1546ca425dc3265b3ef08035b8491",
8
+ "linux-ppc64": "5222e7a4370da9cfb65873805f834f047f4398617fac3b05f85e7a2a542c9630",
9
+ "linux-x64": "71bfc07c71aa3e51332b6bdd09d5b07f97c09dd9e2c8de7040846d79fab9d384",
10
+ "win32-arm64": "45983993f978df229c8acdcd84ee406f463524c61375329ed3f8f2a1defff383",
11
+ "win32-x64": "308fd42eab86adc917e3bc278366a6668869d36364e59033fa1b332777c8471a"
12
12
  }
@@ -1,5 +1,6 @@
1
1
  #pragma once
2
2
 
3
+ #include "attachments_worker.h" // shared FPDF_ATTACHMENT read helpers
3
4
  #include "napi_helpers.h"
4
5
 
5
6
  #include <atomic>
@@ -14,9 +15,11 @@
14
15
  // ---------------------------------------------------------------------------
15
16
 
16
17
  struct AnnotationData {
18
+ int index = 0;
17
19
  std::string type;
18
20
  double left = 0, bottom = 0, right = 0, top = 0;
19
21
  bool hasBounds = false;
22
+ std::u16string fileName; // set only for 'fileattachment' annotations
20
23
  std::u16string contents;
21
24
  unsigned int r = 0, g = 0, b = 0, a = 0;
22
25
  bool hasColor = false;
@@ -58,6 +61,7 @@ protected:
58
61
  continue;
59
62
 
60
63
  AnnotationData data;
64
+ data.index = i;
61
65
 
62
66
  FPDF_ANNOTATION_SUBTYPE subtype = FPDFAnnot_GetSubtype(annot);
63
67
  switch (subtype) {
@@ -129,6 +133,14 @@ protected:
129
133
  break;
130
134
  }
131
135
 
136
+ // for file-attachment annotations, surface the embedded file name so
137
+ // callers can decide which annotation to read via getAnnotationAttachment
138
+ if (subtype == FPDF_ANNOT_FILEATTACHMENT) {
139
+ FPDF_ATTACHMENT att = FPDFAnnot_GetFileAttachment(annot);
140
+ if (att)
141
+ data.fileName = ReadAttachmentName(att);
142
+ }
143
+
132
144
  FS_RECTF rect;
133
145
  if (FPDFAnnot_GetRect(annot, &rect)) {
134
146
  data.hasBounds = true;
@@ -213,7 +225,9 @@ protected:
213
225
  for (uint32_t i = 0; i < annotations_.size(); i++) {
214
226
  auto &d = annotations_[i];
215
227
  Napi::Object obj = Napi::Object::New(env);
228
+ obj.Set("index", Napi::Number::New(env, d.index));
216
229
  obj.Set("type", Napi::String::New(env, d.type));
230
+ SetU16IfPresent(obj, "fileName", env, d.fileName);
217
231
  if (d.hasBounds)
218
232
  obj.Set("bounds",
219
233
  CreateBoundsObject(env, d.left, d.bottom, d.right, d.top));
@@ -272,3 +286,100 @@ private:
272
286
  std::shared_ptr<std::atomic<bool>> docAlive_;
273
287
  std::vector<AnnotationData> annotations_;
274
288
  };
289
+
290
+ // ---------------------------------------------------------------------------
291
+ // GetAnnotationAttachmentWorker — read a FileAttachment annotation's bytes
292
+ // ---------------------------------------------------------------------------
293
+ // Complements the document-level embedded-files API (GetAttachmentDataWorker).
294
+ // PDFium keeps "paperclip" file attachments as page-level /FileAttachment
295
+ // annotations whose file lives on the annotation, not in the /EmbeddedFiles
296
+ // name tree. `index` is the annotation index (matching Annotation.index).
297
+
298
+ class GetAnnotationAttachmentWorker : public SafeAsyncWorker {
299
+ public:
300
+ GetAnnotationAttachmentWorker(Napi::Env env, FPDF_PAGE page, int index,
301
+ std::string outputPath,
302
+ std::shared_ptr<std::atomic<bool>> pageAlive,
303
+ std::shared_ptr<std::atomic<bool>> docAlive)
304
+ : SafeAsyncWorker(env), deferred_(Napi::Promise::Deferred::New(env)),
305
+ page_(page), index_(index), outputPath_(std::move(outputPath)),
306
+ pageAlive_(std::move(pageAlive)), docAlive_(std::move(docAlive)) {}
307
+
308
+ Napi::Promise Promise() { return deferred_.Promise(); }
309
+
310
+ protected:
311
+ void Execute() override {
312
+ std::lock_guard<std::mutex> lock(g_pdfium_mutex);
313
+ CHECK_ALIVE();
314
+
315
+ int count = FPDFPage_GetAnnotCount(page_);
316
+ if (index_ < 0 || index_ >= count) {
317
+ SetError("Annotation index out of range");
318
+ return;
319
+ }
320
+
321
+ FPDF_ANNOTATION annot = FPDFPage_GetAnnot(page_, index_);
322
+ if (!annot) {
323
+ SetError("Failed to get annotation");
324
+ return;
325
+ }
326
+ // close the annotation on every exit path (the attachment handle is only
327
+ // read while the annotation is open, before this guard runs)
328
+ struct AnnotGuard {
329
+ FPDF_ANNOTATION a;
330
+ ~AnnotGuard() { FPDFPage_CloseAnnot(a); }
331
+ } guard{annot};
332
+
333
+ if (FPDFAnnot_GetSubtype(annot) != FPDF_ANNOT_FILEATTACHMENT) {
334
+ SetError("Annotation at index " + std::to_string(index_) +
335
+ " is not a file attachment");
336
+ return;
337
+ }
338
+
339
+ FPDF_ATTACHMENT attachment = FPDFAnnot_GetFileAttachment(annot);
340
+ if (!attachment) {
341
+ SetError("File-attachment annotation has no embedded file");
342
+ return;
343
+ }
344
+
345
+ std::string err;
346
+ if (!ReadAttachmentFileBytes(attachment, data_, err)) {
347
+ SetError(err);
348
+ return;
349
+ }
350
+
351
+ if (!outputPath_.empty()) {
352
+ if (!WriteBytesToFile(outputPath_, data_, err)) {
353
+ SetError(err);
354
+ return;
355
+ }
356
+ data_.clear();
357
+ }
358
+ }
359
+
360
+ void OnOK() override {
361
+ Napi::Env env = Env();
362
+ if (!outputPath_.empty()) {
363
+ deferred_.Resolve(env.Undefined());
364
+ return;
365
+ }
366
+ auto *vec = new std::vector<uint8_t>(std::move(data_));
367
+ auto buffer = Napi::Buffer<uint8_t>::New(
368
+ env, vec->data(), vec->size(),
369
+ [](Napi::Env, uint8_t *, std::vector<uint8_t> *v) { delete v; }, vec);
370
+ deferred_.Resolve(buffer);
371
+ }
372
+
373
+ void OnError(const Napi::Error &err) override {
374
+ deferred_.Reject(err.Value());
375
+ }
376
+
377
+ private:
378
+ Napi::Promise::Deferred deferred_;
379
+ FPDF_PAGE page_;
380
+ int index_;
381
+ std::string outputPath_;
382
+ std::shared_ptr<std::atomic<bool>> pageAlive_;
383
+ std::shared_ptr<std::atomic<bool>> docAlive_;
384
+ std::vector<uint8_t> data_;
385
+ };
@@ -0,0 +1,235 @@
1
+ #pragma once
2
+
3
+ #include "document_io.h"
4
+
5
+ #include <string>
6
+ #include <vector>
7
+
8
+ #include "fpdf_edit.h"
9
+ #include "fpdf_ppo.h"
10
+
11
+ // ---------------------------------------------------------------------------
12
+ // Page assembly workers
13
+ // ---------------------------------------------------------------------------
14
+ // splitDocument and mergeDocuments cover the two coarse cases: cut a document
15
+ // into runs, or concatenate whole documents. These two cover the rest —
16
+ // reordering, selecting and duplicating individual pages, and imposing several
17
+ // source pages onto one output sheet.
18
+
19
+ // ---------------------------------------------------------------------------
20
+ // AssemblePagesWorker — build a document from selected pages, in order
21
+ // ---------------------------------------------------------------------------
22
+ // The index list is taken literally: order is preserved and repeats produce
23
+ // repeated pages, which is what makes booklet imposition and page duplication
24
+ // possible.
25
+
26
+ class AssemblePagesWorker : public SafeAsyncWorker {
27
+ public:
28
+ // buffer variant
29
+ AssemblePagesWorker(Napi::Env env, std::vector<uint8_t> data,
30
+ std::vector<int> pages, std::string outputPath,
31
+ std::string password)
32
+ : SafeAsyncWorker(env), deferred_(Napi::Promise::Deferred::New(env)),
33
+ bufferData_(std::move(data)), pages_(std::move(pages)),
34
+ outputPath_(std::move(outputPath)), password_(std::move(password)),
35
+ useFile_(false) {}
36
+
37
+ // file path variant
38
+ AssemblePagesWorker(Napi::Env env, std::string filePath,
39
+ std::vector<int> pages, std::string outputPath,
40
+ std::string password)
41
+ : SafeAsyncWorker(env), deferred_(Napi::Promise::Deferred::New(env)),
42
+ filePath_(std::move(filePath)), pages_(std::move(pages)),
43
+ outputPath_(std::move(outputPath)), password_(std::move(password)),
44
+ useFile_(true) {}
45
+
46
+ Napi::Promise Promise() { return deferred_.Promise(); }
47
+
48
+ protected:
49
+ void Execute() override {
50
+ std::lock_guard<std::mutex> lock(g_pdfium_mutex);
51
+
52
+ std::string loadError;
53
+ FPDF_DOCUMENT srcDoc =
54
+ LoadDoc(bufferData_, filePath_, useFile_, password_, loadError);
55
+ if (!srcDoc) {
56
+ SetError(loadError);
57
+ return;
58
+ }
59
+
60
+ // Report the offending index ourselves — FPDF_ImportPagesByIndex only
61
+ // returns a bare false, which would tell the caller nothing.
62
+ int pageCount = FPDF_GetPageCount(srcDoc);
63
+ for (int page : pages_) {
64
+ if (page < 0 || page >= pageCount) {
65
+ FPDF_CloseDocument(srcDoc);
66
+ SetError("Page index out of range: " + std::to_string(page));
67
+ return;
68
+ }
69
+ }
70
+
71
+ FPDF_DOCUMENT destDoc = FPDF_CreateNewDocument();
72
+ if (!destDoc) {
73
+ FPDF_CloseDocument(srcDoc);
74
+ SetError("Failed to create new PDF document");
75
+ return;
76
+ }
77
+
78
+ FPDF_BOOL ok = FPDF_ImportPagesByIndex(
79
+ destDoc, srcDoc, pages_.data(),
80
+ static_cast<unsigned long>(pages_.size()), 0);
81
+ if (!ok) {
82
+ FPDF_CloseDocument(destDoc);
83
+ FPDF_CloseDocument(srcDoc);
84
+ SetError("Failed to import pages");
85
+ return;
86
+ }
87
+
88
+ std::string saveError;
89
+ if (!SaveDocument(destDoc, outputPath_, resultData_, saveError)) {
90
+ FPDF_CloseDocument(destDoc);
91
+ FPDF_CloseDocument(srcDoc);
92
+ SetError(saveError);
93
+ return;
94
+ }
95
+
96
+ FPDF_CloseDocument(destDoc);
97
+ FPDF_CloseDocument(srcDoc);
98
+ }
99
+
100
+ void OnOK() override {
101
+ Napi::Env env = Env();
102
+ if (!outputPath_.empty()) {
103
+ deferred_.Resolve(env.Undefined());
104
+ return;
105
+ }
106
+ auto *vec = new std::vector<uint8_t>(std::move(resultData_));
107
+ deferred_.Resolve(Napi::Buffer<uint8_t>::New(
108
+ env, vec->data(), vec->size(),
109
+ [](Napi::Env, uint8_t *, std::vector<uint8_t> *v) { delete v; }, vec));
110
+ }
111
+
112
+ void OnError(const Napi::Error &err) override {
113
+ deferred_.Reject(err.Value());
114
+ }
115
+
116
+ private:
117
+ Napi::Promise::Deferred deferred_;
118
+ std::vector<uint8_t> bufferData_;
119
+ std::string filePath_;
120
+ std::vector<int> pages_;
121
+ std::string outputPath_;
122
+ std::string password_;
123
+ bool useFile_;
124
+ std::vector<uint8_t> resultData_;
125
+ };
126
+
127
+ // ---------------------------------------------------------------------------
128
+ // NUpPagesWorker — impose columns x rows source pages onto each output page
129
+ // ---------------------------------------------------------------------------
130
+
131
+ class NUpPagesWorker : public SafeAsyncWorker {
132
+ public:
133
+ // buffer variant
134
+ NUpPagesWorker(Napi::Env env, std::vector<uint8_t> data, int columns,
135
+ int rows, float width, float height, std::string outputPath,
136
+ std::string password)
137
+ : SafeAsyncWorker(env), deferred_(Napi::Promise::Deferred::New(env)),
138
+ bufferData_(std::move(data)), columns_(columns), rows_(rows),
139
+ width_(width), height_(height), outputPath_(std::move(outputPath)),
140
+ password_(std::move(password)), useFile_(false) {}
141
+
142
+ // file path variant
143
+ NUpPagesWorker(Napi::Env env, std::string filePath, int columns, int rows,
144
+ float width, float height, std::string outputPath,
145
+ std::string password)
146
+ : SafeAsyncWorker(env), deferred_(Napi::Promise::Deferred::New(env)),
147
+ filePath_(std::move(filePath)), columns_(columns), rows_(rows),
148
+ width_(width), height_(height), outputPath_(std::move(outputPath)),
149
+ password_(std::move(password)), useFile_(true) {}
150
+
151
+ Napi::Promise Promise() { return deferred_.Promise(); }
152
+
153
+ protected:
154
+ void Execute() override {
155
+ std::lock_guard<std::mutex> lock(g_pdfium_mutex);
156
+
157
+ std::string loadError;
158
+ FPDF_DOCUMENT srcDoc =
159
+ LoadDoc(bufferData_, filePath_, useFile_, password_, loadError);
160
+ if (!srcDoc) {
161
+ SetError(loadError);
162
+ return;
163
+ }
164
+
165
+ if (FPDF_GetPageCount(srcDoc) == 0) {
166
+ FPDF_CloseDocument(srcDoc);
167
+ SetError("Source document has no pages");
168
+ return;
169
+ }
170
+
171
+ // Default the sheet to the first source page, so 2x2 of A4 lands on A4
172
+ // rather than on some unrelated hard-coded size.
173
+ if (width_ <= 0 || height_ <= 0) {
174
+ FS_SIZEF size;
175
+ if (!FPDF_GetPageSizeByIndexF(srcDoc, 0, &size)) {
176
+ FPDF_CloseDocument(srcDoc);
177
+ SetError("Failed to read the source page size");
178
+ return;
179
+ }
180
+ if (width_ <= 0)
181
+ width_ = size.width;
182
+ if (height_ <= 0)
183
+ height_ = size.height;
184
+ }
185
+
186
+ FPDF_DOCUMENT destDoc = FPDF_ImportNPagesToOne(
187
+ srcDoc, width_, height_, static_cast<size_t>(columns_),
188
+ static_cast<size_t>(rows_));
189
+ if (!destDoc) {
190
+ FPDF_CloseDocument(srcDoc);
191
+ SetError("Failed to combine pages");
192
+ return;
193
+ }
194
+
195
+ std::string saveError;
196
+ if (!SaveDocument(destDoc, outputPath_, resultData_, saveError)) {
197
+ FPDF_CloseDocument(destDoc);
198
+ FPDF_CloseDocument(srcDoc);
199
+ SetError(saveError);
200
+ return;
201
+ }
202
+
203
+ FPDF_CloseDocument(destDoc);
204
+ FPDF_CloseDocument(srcDoc);
205
+ }
206
+
207
+ void OnOK() override {
208
+ Napi::Env env = Env();
209
+ if (!outputPath_.empty()) {
210
+ deferred_.Resolve(env.Undefined());
211
+ return;
212
+ }
213
+ auto *vec = new std::vector<uint8_t>(std::move(resultData_));
214
+ deferred_.Resolve(Napi::Buffer<uint8_t>::New(
215
+ env, vec->data(), vec->size(),
216
+ [](Napi::Env, uint8_t *, std::vector<uint8_t> *v) { delete v; }, vec));
217
+ }
218
+
219
+ void OnError(const Napi::Error &err) override {
220
+ deferred_.Reject(err.Value());
221
+ }
222
+
223
+ private:
224
+ Napi::Promise::Deferred deferred_;
225
+ std::vector<uint8_t> bufferData_;
226
+ std::string filePath_;
227
+ int columns_;
228
+ int rows_;
229
+ float width_;
230
+ float height_;
231
+ std::string outputPath_;
232
+ std::string password_;
233
+ bool useFile_;
234
+ std::vector<uint8_t> resultData_;
235
+ };
@@ -3,19 +3,10 @@
3
3
  #include "napi_helpers.h"
4
4
 
5
5
  #include <atomic>
6
- #include <cstdio>
7
6
  #include <memory>
8
7
  #include <string>
9
8
  #include <vector>
10
9
 
11
- #ifdef _WIN32
12
- #include <io.h>
13
- #define F_OK 0
14
- #define access _access
15
- #else
16
- #include <unistd.h>
17
- #endif
18
-
19
10
  #include "fpdf_attachment.h"
20
11
 
21
12
  // ---------------------------------------------------------------------------
@@ -39,6 +30,45 @@ inline std::u16string ReadAttachmentStringValue(FPDF_ATTACHMENT attachment,
39
30
  });
40
31
  }
41
32
 
33
+ // read an attachment's file name (from the filespec /UF or /F entry)
34
+ inline std::u16string ReadAttachmentName(FPDF_ATTACHMENT attachment) {
35
+ return ReadU16(
36
+ [&](auto *, unsigned long) {
37
+ return FPDFAttachment_GetName(attachment, nullptr, 0);
38
+ },
39
+ [&](FPDF_WCHAR *buf, unsigned long len) {
40
+ return FPDFAttachment_GetName(attachment, buf, len);
41
+ });
42
+ }
43
+
44
+ // Reads the full decoded bytes of an attachment via the two-pass
45
+ // FPDFAttachment_GetFile protocol (null buffer → size, then copy). A
46
+ // zero-length embedded file yields an empty vector and success. Returns false
47
+ // and sets `err` on failure. Shared by the document-level and annotation-level
48
+ // attachment readers.
49
+ inline bool ReadAttachmentFileBytes(FPDF_ATTACHMENT attachment,
50
+ std::vector<uint8_t> &out,
51
+ std::string &err) {
52
+ unsigned long outLen = 0;
53
+ if (!FPDFAttachment_GetFile(attachment, nullptr, 0, &outLen)) {
54
+ err = "Failed to read attachment file data";
55
+ return false;
56
+ }
57
+ out.clear();
58
+ // skip the copy for a zero-length embedded file, where out.data() would be
59
+ // null and the copy is a no-op anyway
60
+ if (outLen > 0) {
61
+ out.resize(outLen);
62
+ unsigned long written = 0;
63
+ if (!FPDFAttachment_GetFile(attachment, out.data(), outLen, &written) ||
64
+ written != outLen) {
65
+ err = "Failed to read attachment file data";
66
+ return false;
67
+ }
68
+ }
69
+ return true;
70
+ }
71
+
42
72
  // ---------------------------------------------------------------------------
43
73
  // GetAttachmentsWorker — async attachment metadata listing
44
74
  // ---------------------------------------------------------------------------
@@ -169,46 +199,15 @@ protected:
169
199
  return;
170
200
  }
171
201
 
172
- // first pass: query the decoded byte length (buffer null → size only)
173
- unsigned long outLen = 0;
174
- if (!FPDFAttachment_GetFile(attachment, nullptr, 0, &outLen)) {
175
- SetError("Failed to read attachment file data");
202
+ std::string err;
203
+ if (!ReadAttachmentFileBytes(attachment, data_, err)) {
204
+ SetError(err);
176
205
  return;
177
206
  }
178
207
 
179
- // second pass: copy the bytes (skip for a zero-length embedded file, where
180
- // data_.data() would be null and the copy is a no-op anyway)
181
- if (outLen > 0) {
182
- data_.resize(outLen);
183
- unsigned long written = 0;
184
- if (!FPDFAttachment_GetFile(attachment, data_.data(), outLen, &written) ||
185
- written != outLen) {
186
- SetError("Failed to read attachment file data");
187
- return;
188
- }
189
- }
190
-
191
208
  if (!outputPath_.empty()) {
192
- // verify parent directory exists (mirrors RenderWorker)
193
- auto slash = outputPath_.rfind('/');
194
- if (slash != std::string::npos && slash > 0) {
195
- std::string parentDir = outputPath_.substr(0, slash);
196
- if (access(parentDir.c_str(), F_OK) != 0) {
197
- SetError("Parent directory does not exist: " + parentDir);
198
- return;
199
- }
200
- }
201
-
202
- FILE *f = fopen(outputPath_.c_str(), "wb");
203
- if (!f) {
204
- SetError("Failed to open output file: " + outputPath_);
205
- return;
206
- }
207
- size_t total = data_.size();
208
- size_t wrote = total == 0 ? 0 : fwrite(data_.data(), 1, total, f);
209
- fclose(f);
210
- if (wrote != total) {
211
- SetError("Failed to write output file: " + outputPath_);
209
+ if (!WriteBytesToFile(outputPath_, data_, err)) {
210
+ SetError(err);
212
211
  return;
213
212
  }
214
213
  data_.clear();
@@ -0,0 +1,158 @@
1
+ #pragma once
2
+
3
+ #include "document_io.h"
4
+
5
+ #include <string>
6
+ #include <vector>
7
+
8
+ #include "fpdf_attachment.h"
9
+
10
+ // ---------------------------------------------------------------------------
11
+ // AddAttachmentsWorker — embed files into a copy of a document
12
+ // ---------------------------------------------------------------------------
13
+ // This is the one write path in the library, and PDFium's embedding API is
14
+ // much narrower than the read side. Against the pinned chromium/7920 build it
15
+ // reaches exactly three things:
16
+ //
17
+ // /UF + /F the file name (FPDFDoc_AddAttachment)
18
+ // the stream the file bytes (FPDFAttachment_SetFile)
19
+ // /Params Size, CreationDate, ModDate, CheckSum
20
+ // (FPDFAttachment_SetStringValue)
21
+ //
22
+ // It cannot set /Subtype (the MIME type) or /AFRelationship: both sit on the
23
+ // filespec dict or the stream dict, not in the /Params sub-dictionary that
24
+ // SetStringValue writes to, and PDFium exposes no setter for either.
25
+ // /Desc is out of reach too — FPDFAttachment_SetDescription exists upstream but
26
+ // not in chromium/7920.
27
+ //
28
+ // A file embedded this way is therefore a valid PDF attachment but NOT a
29
+ // conformant PDF/A-3 / ZUGFeRD / Factur-X e-invoice. See the note on
30
+ // addAttachments() in the docs.
31
+
32
+ struct AttachmentToAdd {
33
+ std::u16string name;
34
+ std::vector<uint8_t> data;
35
+ std::u16string creationDate;
36
+ std::u16string modDate;
37
+ };
38
+
39
+ class AddAttachmentsWorker : public SafeAsyncWorker {
40
+ public:
41
+ // buffer variant
42
+ AddAttachmentsWorker(Napi::Env env, std::vector<uint8_t> data,
43
+ std::vector<AttachmentToAdd> attachments,
44
+ std::string outputPath, std::string password)
45
+ : SafeAsyncWorker(env), deferred_(Napi::Promise::Deferred::New(env)),
46
+ bufferData_(std::move(data)), attachments_(std::move(attachments)),
47
+ outputPath_(std::move(outputPath)), password_(std::move(password)),
48
+ useFile_(false) {}
49
+
50
+ // file path variant
51
+ AddAttachmentsWorker(Napi::Env env, std::string filePath,
52
+ std::vector<AttachmentToAdd> attachments,
53
+ std::string outputPath, std::string password)
54
+ : SafeAsyncWorker(env), deferred_(Napi::Promise::Deferred::New(env)),
55
+ filePath_(std::move(filePath)), attachments_(std::move(attachments)),
56
+ outputPath_(std::move(outputPath)), password_(std::move(password)),
57
+ useFile_(true) {}
58
+
59
+ Napi::Promise Promise() { return deferred_.Promise(); }
60
+
61
+ protected:
62
+ void Execute() override {
63
+ std::lock_guard<std::mutex> lock(g_pdfium_mutex);
64
+
65
+ std::string loadError;
66
+ FPDF_DOCUMENT doc =
67
+ LoadDoc(bufferData_, filePath_, useFile_, password_, loadError);
68
+ if (!doc) {
69
+ SetError(loadError);
70
+ return;
71
+ }
72
+
73
+ for (const auto &item : attachments_) {
74
+ FPDF_ATTACHMENT attachment =
75
+ FPDFDoc_AddAttachment(doc, ToWideString(item.name));
76
+ if (!attachment) {
77
+ FPDF_CloseDocument(doc);
78
+ // AddAttachment also rejects a name that already exists in the
79
+ // embedded-files name tree, which is the likely cause here.
80
+ SetError("Failed to add attachment (empty or duplicate name): " +
81
+ Utf8Of(item.name));
82
+ return;
83
+ }
84
+
85
+ // SetFile must come first: it rebuilds the embedded-file stream and its
86
+ // /Params, discarding anything already written there.
87
+ if (!FPDFAttachment_SetFile(attachment, doc, item.data.data(),
88
+ static_cast<unsigned long>(
89
+ item.data.size()))) {
90
+ FPDF_CloseDocument(doc);
91
+ SetError("Failed to write attachment data: " + Utf8Of(item.name));
92
+ return;
93
+ }
94
+
95
+ // SetFile stamps CreationDate with the current time; an explicit value
96
+ // overwrites it, which is also what makes output reproducible.
97
+ if (!item.creationDate.empty()) {
98
+ FPDFAttachment_SetStringValue(attachment, "CreationDate",
99
+ ToWideString(item.creationDate));
100
+ }
101
+ if (!item.modDate.empty()) {
102
+ FPDFAttachment_SetStringValue(attachment, "ModDate",
103
+ ToWideString(item.modDate));
104
+ }
105
+ }
106
+
107
+ std::string saveError;
108
+ if (!SaveDocument(doc, outputPath_, resultData_, saveError)) {
109
+ FPDF_CloseDocument(doc);
110
+ SetError(saveError);
111
+ return;
112
+ }
113
+
114
+ FPDF_CloseDocument(doc);
115
+ }
116
+
117
+ void OnOK() override {
118
+ Napi::Env env = Env();
119
+ if (!outputPath_.empty()) {
120
+ deferred_.Resolve(env.Undefined());
121
+ return;
122
+ }
123
+ auto *vec = new std::vector<uint8_t>(std::move(resultData_));
124
+ deferred_.Resolve(Napi::Buffer<uint8_t>::New(
125
+ env, vec->data(), vec->size(),
126
+ [](Napi::Env, uint8_t *, std::vector<uint8_t> *v) { delete v; }, vec));
127
+ }
128
+
129
+ void OnError(const Napi::Error &err) override {
130
+ deferred_.Reject(err.Value());
131
+ }
132
+
133
+ private:
134
+ // FPDF_WIDESTRING is a NUL-terminated UTF-16LE string; std::u16string
135
+ // already stores exactly that and guarantees the terminator.
136
+ static FPDF_WIDESTRING ToWideString(const std::u16string &s) {
137
+ return reinterpret_cast<FPDF_WIDESTRING>(s.c_str());
138
+ }
139
+
140
+ // best-effort ASCII rendering of a name, for error messages only
141
+ static std::string Utf8Of(const std::u16string &s) {
142
+ std::string out;
143
+ out.reserve(s.size());
144
+ for (char16_t c : s) {
145
+ out.push_back(c < 0x80 ? static_cast<char>(c) : '?');
146
+ }
147
+ return out;
148
+ }
149
+
150
+ Napi::Promise::Deferred deferred_;
151
+ std::vector<uint8_t> bufferData_;
152
+ std::string filePath_;
153
+ std::vector<AttachmentToAdd> attachments_;
154
+ std::string outputPath_;
155
+ std::string password_;
156
+ bool useFile_ = false;
157
+ std::vector<uint8_t> resultData_;
158
+ };