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.
@@ -493,6 +493,253 @@ async function createEInvoicePdf() {
493
493
  return doc.save();
494
494
  }
495
495
 
496
+ // --- Tagged PDF with a real structure tree ---
497
+ // tagged.pdf only sets /MarkInfo, which is enough for metadata.isTagged but
498
+ // leaves nothing for getStructTree() to read. PDFium needs more than a
499
+ // /StructTreeRoot: CPDF_StructTree::LoadPageTree bails unless the root has a
500
+ // /ParentTree AND the page has /StructParents, then it looks up that key,
501
+ // expects an array of leaf element dicts, and walks /P upwards to rebuild the
502
+ // tree. All of that is assembled by hand below.
503
+ //
504
+ // The page content deliberately carries no BDC/EMC marked-content operators:
505
+ // PDFium reads the structure purely from the dictionaries, so the /K marked
506
+ // content IDs are enough to exercise the API.
507
+ async function createStructTreePdf() {
508
+ const doc = await PDFDocument.create();
509
+ const font = await doc.embedFont(StandardFonts.Helvetica);
510
+ const page = doc.addPage([300, 400]);
511
+ page.drawText('Main heading', { x: 50, y: 340, size: 18, font });
512
+ page.drawText('A paragraph of body text.', { x: 50, y: 300, size: 11, font });
513
+
514
+ const { PDFName, PDFString, PDFNumber } = await import('pdf-lib');
515
+
516
+ const structTreeRoot = doc.context.obj({ Type: 'StructTreeRoot' });
517
+ const structTreeRootRef = doc.context.register(structTreeRoot);
518
+
519
+ const documentElem = doc.context.obj({
520
+ Type: 'StructElem',
521
+ S: 'Document',
522
+ P: structTreeRootRef,
523
+ Lang: PDFString.of('en-US'),
524
+ });
525
+ const documentRef = doc.context.register(documentElem);
526
+
527
+ const child = (props) =>
528
+ doc.context.register(
529
+ doc.context.obj({
530
+ Type: 'StructElem',
531
+ P: documentRef,
532
+ Pg: page.ref,
533
+ ...props,
534
+ }),
535
+ );
536
+
537
+ const headingRef = child({ S: 'H1', T: PDFString.of('Main heading'), K: 0 });
538
+ const paragraphRef = child({ S: 'P', K: 1, Lang: PDFString.of('de-DE') });
539
+ const figureRef = child({
540
+ S: 'Figure',
541
+ K: 2,
542
+ Alt: PDFString.of('A red square'),
543
+ ActualText: PDFString.of('Figure 1'),
544
+ ID: PDFString.of('fig1'),
545
+ });
546
+
547
+ documentElem.set(PDFName.of('K'), doc.context.obj([headingRef, paragraphRef, figureRef]));
548
+ structTreeRoot.set(PDFName.of('K'), doc.context.obj([documentRef]));
549
+
550
+ // ParentTree: key 0 -> the leaf elements whose content sits on this page.
551
+ // PDFium walks each one's /P chain back up to the root.
552
+ structTreeRoot.set(
553
+ PDFName.of('ParentTree'),
554
+ doc.context.obj({
555
+ Nums: [0, [headingRef, paragraphRef, figureRef]],
556
+ }),
557
+ );
558
+
559
+ page.node.set(PDFName.of('StructParents'), PDFNumber.of(0));
560
+ doc.catalog.set(PDFName.of('StructTreeRoot'), structTreeRootRef);
561
+ doc.catalog.set(PDFName.of('MarkInfo'), doc.context.obj({ Marked: true }));
562
+
563
+ return doc.save();
564
+ }
565
+
566
+ // --- PDF with document-level JavaScript and named destinations ---
567
+ // pdf-lib builds neither, so both name trees are written by hand. The
568
+ // destinations deliberately use both storage forms PDFium understands: the
569
+ // modern /Names /Dests name tree and the legacy /Dests catalog dictionary.
570
+ const OPEN_ACTION_JS = 'app.alert("Opened");';
571
+ const HELPER_JS = 'function helper() { return 42; }';
572
+
573
+ async function createNavigationPdf() {
574
+ const doc = await PDFDocument.create();
575
+ const font = await doc.embedFont(StandardFonts.Helvetica);
576
+ const pages = [];
577
+ for (let i = 1; i <= 3; i++) {
578
+ const page = doc.addPage([300, 400]);
579
+ page.drawText(`Section ${i}`, { x: 50, y: 300, size: 20, font });
580
+ pages.push(page);
581
+ }
582
+
583
+ const { PDFName, PDFString } = await import('pdf-lib');
584
+
585
+ // document-level JavaScript, as a /Names /JavaScript name tree
586
+ const jsAction = (script) =>
587
+ doc.context.register(doc.context.obj({ S: 'JavaScript', JS: PDFString.of(script) }));
588
+
589
+ const javaScriptTree = doc.context.obj({
590
+ Names: [
591
+ PDFString.of('OpenAction'),
592
+ jsAction(OPEN_ACTION_JS),
593
+ PDFString.of('Helper'),
594
+ jsAction(HELPER_JS),
595
+ ],
596
+ });
597
+
598
+ // named destinations in the /Names /Dests name tree. Name-tree entries must
599
+ // be sorted by name, which is why these read Alpha/Beta rather than
600
+ // Section1/Section2.
601
+ const destsTree = doc.context.obj({
602
+ Names: [
603
+ PDFString.of('Alpha'),
604
+ [pages[0].ref, 'XYZ', 50, 700, 2],
605
+ PDFString.of('Beta'),
606
+ [pages[1].ref, 'Fit'],
607
+ ],
608
+ });
609
+
610
+ doc.catalog.set(
611
+ PDFName.of('Names'),
612
+ doc.context.obj({ JavaScript: javaScriptTree, Dests: destsTree }),
613
+ );
614
+
615
+ // legacy form: a plain /Dests dictionary on the catalog
616
+ doc.catalog.set(PDFName.of('Dests'), doc.context.obj({ Legacy: [pages[2].ref, 'FitH', 250] }));
617
+
618
+ return doc.save();
619
+ }
620
+
621
+ // --- Four-page PDF whose pages identify themselves ---
622
+ // Each page carries its own number as text, so assembly tests can verify
623
+ // order, selection and duplication by reading the pages back.
624
+ async function createFourPagePdf() {
625
+ const doc = await PDFDocument.create();
626
+ const font = await doc.embedFont(StandardFonts.Helvetica);
627
+ for (let i = 1; i <= 4; i++) {
628
+ const page = doc.addPage([300, 400]);
629
+ page.drawText(`Page ${i}`, { x: 50, y: 300, size: 24, font });
630
+ }
631
+ return doc.save();
632
+ }
633
+
634
+ // --- PDF exercising positioned text extraction ---
635
+ // Three runs on one page, each drawn at a known baseline origin: two font
636
+ // sizes, a regular/bold font switch, and a 45-degree rotated run. That is
637
+ // enough to pin down every geometry field getCharacters() reports without
638
+ // depending on glyph outlines.
639
+ async function createPositionedTextPdf() {
640
+ const doc = await PDFDocument.create();
641
+ const page = doc.addPage([400, 300]);
642
+ const regular = await doc.embedFont(StandardFonts.Helvetica);
643
+ const bold = await doc.embedFont(StandardFonts.HelveticaBold);
644
+
645
+ page.drawText('AB', { x: 50, y: 250, size: 24, font: regular });
646
+ page.drawText('CD', { x: 50, y: 200, size: 12, font: bold });
647
+ page.drawText('EF', { x: 200, y: 100, size: 18, font: regular, rotate: degrees(45) });
648
+
649
+ return doc.save();
650
+ }
651
+
652
+ // --- PDF with two AcroForm signature fields ---
653
+ // PDFium finds signatures by walking Catalog -> /AcroForm -> /Fields and
654
+ // keeping the entries whose /FT is /Sig, so the fields have to be built by
655
+ // hand — pdf-lib cannot create signature fields.
656
+ //
657
+ // The /Contents blobs and /ByteRange offsets below are FAKE: they are fixed
658
+ // byte patterns, not a real PKCS#7 structure, and the offsets do not describe
659
+ // this file. That is deliberate and sufficient, because PDFium performs no
660
+ // cryptographic verification — it hands back whatever the dictionary says. The
661
+ // fixture proves the extraction path, never signature validity.
662
+ const SIG_CONTENTS_HEX = '308006092a864886f70d010702a0803080020101';
663
+ const CERT_SIG_CONTENTS_HEX = '3082010a0282010100c0ffee';
664
+
665
+ async function createSignedPdf() {
666
+ const doc = await PDFDocument.create();
667
+ const page = doc.addPage([612, 792]);
668
+ const font = await doc.embedFont(StandardFonts.Helvetica);
669
+ page.drawText('Signed document', { x: 50, y: 700, size: 16, font });
670
+
671
+ const { PDFName, PDFString, PDFHexString } = await import('pdf-lib');
672
+
673
+ // ordinary approval signature — no /Reference, so no DocMDP permission
674
+ const sigValueRef = doc.context.register(
675
+ doc.context.obj({
676
+ Type: 'Sig',
677
+ Filter: 'Adobe.PPKLite',
678
+ SubFilter: 'adbe.pkcs7.detached',
679
+ ByteRange: [0, 840, 1560, 1234],
680
+ Contents: PDFHexString.of(SIG_CONTENTS_HEX),
681
+ Reason: PDFString.of('I approve this document'),
682
+ M: PDFString.of("D:20250101120000+01'00'"),
683
+ Name: PDFString.of('Test Signer'),
684
+ }),
685
+ );
686
+
687
+ const sigFieldRef = doc.context.register(
688
+ doc.context.obj({
689
+ FT: 'Sig',
690
+ T: PDFString.of('Signature1'),
691
+ V: sigValueRef,
692
+ Type: 'Annot',
693
+ Subtype: 'Widget',
694
+ Rect: [50, 600, 250, 650],
695
+ F: 4,
696
+ P: page.ref,
697
+ }),
698
+ );
699
+
700
+ // certification signature — /Reference -> /DocMDP -> /TransformParams /P 2
701
+ const certValueRef = doc.context.register(
702
+ doc.context.obj({
703
+ Type: 'Sig',
704
+ Filter: 'Adobe.PPKLite',
705
+ SubFilter: 'ETSI.CAdES.detached',
706
+ ByteRange: [0, 200, 900, 300],
707
+ Contents: PDFHexString.of(CERT_SIG_CONTENTS_HEX),
708
+ M: PDFString.of('D:20250202093000Z'),
709
+ Reference: [
710
+ {
711
+ Type: 'SigRef',
712
+ TransformMethod: 'DocMDP',
713
+ TransformParams: { Type: 'TransformParams', P: 2, V: '1.2' },
714
+ },
715
+ ],
716
+ }),
717
+ );
718
+
719
+ const certFieldRef = doc.context.register(
720
+ doc.context.obj({
721
+ FT: 'Sig',
722
+ T: PDFString.of('Certification'),
723
+ V: certValueRef,
724
+ Type: 'Annot',
725
+ Subtype: 'Widget',
726
+ Rect: [50, 520, 250, 570],
727
+ F: 4,
728
+ P: page.ref,
729
+ }),
730
+ );
731
+
732
+ doc.catalog.set(
733
+ PDFName.of('AcroForm'),
734
+ doc.context.obj({ Fields: [sigFieldRef, certFieldRef], SigFlags: 3 }),
735
+ );
736
+ page.node.set(PDFName.of('Annots'), doc.context.obj([sigFieldRef, certFieldRef]));
737
+
738
+ // pdf-lib would otherwise re-read the AcroForm to regenerate widget
739
+ // appearances, which these hand-built signature fields do not need
740
+ return doc.save({ updateFieldAppearances: false });
741
+ }
742
+
496
743
  // --- PDF with a page-level FileAttachment annotation ---
497
744
  // PDFium exposes "paperclip" file attachments as /FileAttachment annotations
498
745
  // whose embedded file lives on the annotation itself, NOT in the
@@ -626,6 +873,11 @@ const fixtures = [
626
873
  ['form-fields.pdf', createFormFieldsPdf],
627
874
  ['einvoice-zugferd.pdf', createEInvoicePdf],
628
875
  ['file-attachment-annotation.pdf', createFileAttachmentAnnotationPdf],
876
+ ['signed.pdf', createSignedPdf],
877
+ ['positioned-text.pdf', createPositionedTextPdf],
878
+ ['four-page.pdf', createFourPagePdf],
879
+ ['navigation.pdf', createNavigationPdf],
880
+ ['struct-tree.pdf', createStructTreePdf],
629
881
  ];
630
882
 
631
883
  for (const [name, generator] of fixtures) {
@@ -1,12 +1,12 @@
1
1
  {
2
- "darwin-arm64": "9d76d56e7e685da9d415411df4993a124cf6be500ae2d631b1880812dbfead43",
3
- "darwin-x64": "6dbbe1a646553762ad5191be43dd6805f30eb2bd5a25105800e31a6b20f41d21",
4
- "linux-arm": "72553376e4e57b76e52824452afdc0c0727e51ccdecb9560b16b06c06ef026a1",
5
- "linux-arm64": "19f04d13c4af82f108bc6192f11350f236228b105f732d90b9a4f8cd5833e631",
6
- "linux-musl-arm64": "7ea611029af4cd52c178ab075d700908e8a55e882dfa37e28cc2e189ddf944df",
7
- "linux-musl-x64": "5e5bb01d9dfd394fdf56dbec6fb6c460aaa503de118245059d928e9b9215d1ac",
8
- "linux-ppc64": "d3435ee735ae2a38234435d7cf8218c30838b95b5e3a93d1601d1ec1df0d957b",
9
- "linux-x64": "898b335f4b11747860779c35f4efbcb5f871f92280fb36f7946d295a361b3c61",
10
- "win32-arm64": "4d79a6587d326d0ff6ff9a100363fcfa7b483ee9634c6a92ef2d7918eb8bf430",
11
- "win32-x64": "2cdcd4ea8ed992a7d9e43b1ce0a90c539780e73d5cd4dc35c10b4bd2391f4a56"
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
  }
@@ -349,7 +349,7 @@ protected:
349
349
  }
350
350
 
351
351
  if (!outputPath_.empty()) {
352
- if (!WriteAttachmentBytesToFile(outputPath_, data_, err)) {
352
+ if (!WriteBytesToFile(outputPath_, data_, err)) {
353
353
  SetError(err);
354
354
  return;
355
355
  }
@@ -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
  // ---------------------------------------------------------------------------
@@ -78,35 +69,6 @@ inline bool ReadAttachmentFileBytes(FPDF_ATTACHMENT attachment,
78
69
  return true;
79
70
  }
80
71
 
81
- // Writes bytes to `path`, verifying the parent directory exists first (mirrors
82
- // RenderWorker). Returns false and sets `err` on failure.
83
- inline bool WriteAttachmentBytesToFile(const std::string &path,
84
- const std::vector<uint8_t> &data,
85
- std::string &err) {
86
- auto slash = path.rfind('/');
87
- if (slash != std::string::npos && slash > 0) {
88
- std::string parentDir = path.substr(0, slash);
89
- if (access(parentDir.c_str(), F_OK) != 0) {
90
- err = "Parent directory does not exist: " + parentDir;
91
- return false;
92
- }
93
- }
94
-
95
- FILE *f = fopen(path.c_str(), "wb");
96
- if (!f) {
97
- err = "Failed to open output file: " + path;
98
- return false;
99
- }
100
- size_t total = data.size();
101
- size_t wrote = total == 0 ? 0 : fwrite(data.data(), 1, total, f);
102
- fclose(f);
103
- if (wrote != total) {
104
- err = "Failed to write output file: " + path;
105
- return false;
106
- }
107
- return true;
108
- }
109
-
110
72
  // ---------------------------------------------------------------------------
111
73
  // GetAttachmentsWorker — async attachment metadata listing
112
74
  // ---------------------------------------------------------------------------
@@ -244,7 +206,7 @@ protected:
244
206
  }
245
207
 
246
208
  if (!outputPath_.empty()) {
247
- if (!WriteAttachmentBytesToFile(outputPath_, data_, err)) {
209
+ if (!WriteBytesToFile(outputPath_, data_, err)) {
248
210
  SetError(err);
249
211
  return;
250
212
  }