pdfium-native 0.6.1 → 0.8.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.
- package/CHANGELOG.md +21 -1
- package/README.md +62 -0
- package/dist/document.d.ts +16 -1
- package/dist/document.d.ts.map +1 -1
- package/dist/document.js +23 -0
- package/dist/document.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/page.d.ts +14 -1
- package/dist/page.d.ts.map +1 -1
- package/dist/page.js +10 -0
- package/dist/page.js.map +1 -1
- package/dist/types.d.ts +30 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/validate.d.ts +14 -0
- package/dist/validate.d.ts.map +1 -0
- package/dist/validate.js +16 -0
- package/dist/validate.js.map +1 -0
- package/lib/document.ts +38 -1
- package/lib/index.ts +2 -0
- package/lib/page.ts +28 -0
- package/lib/types.ts +32 -0
- package/lib/validate.ts +15 -0
- package/package.json +1 -1
- package/scripts/generate-fixtures.mjs +108 -0
- package/scripts/prebuilds.json +10 -10
- package/src/annotations_worker.h +111 -0
- package/src/attachments_worker.h +279 -0
- package/src/document.h +48 -0
- package/src/page.h +32 -0
package/package.json
CHANGED
|
@@ -444,6 +444,112 @@ async function createBorderAnnotationPdf() {
|
|
|
444
444
|
return doc.save();
|
|
445
445
|
}
|
|
446
446
|
|
|
447
|
+
// --- ZUGFeRD / Factur-X PDF/A-3 with an embedded invoice XML ---
|
|
448
|
+
// The structured invoice (factur-x.xml) is embedded in the /EmbeddedFiles name
|
|
449
|
+
// tree; a second plain-text attachment exercises multi-attachment enumeration.
|
|
450
|
+
const FACTUR_X_XML = `<?xml version="1.0" encoding="UTF-8"?>
|
|
451
|
+
<rsm:CrossIndustryInvoice xmlns:rsm="urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100" xmlns:ram="urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:100">
|
|
452
|
+
<rsm:ExchangedDocumentContext>
|
|
453
|
+
<ram:GuidelineSpecifiedDocumentContextParameter>
|
|
454
|
+
<ram:ID>urn:cen.eu:en16931:2017</ram:ID>
|
|
455
|
+
</ram:GuidelineSpecifiedDocumentContextParameter>
|
|
456
|
+
</rsm:ExchangedDocumentContext>
|
|
457
|
+
<rsm:ExchangedDocument>
|
|
458
|
+
<ram:ID>RE-2025-0001</ram:ID>
|
|
459
|
+
<ram:TypeCode>380</ram:TypeCode>
|
|
460
|
+
<ram:IssueDateTime>
|
|
461
|
+
<ram:DateTimeString format="102">20250101</ram:DateTimeString>
|
|
462
|
+
</ram:IssueDateTime>
|
|
463
|
+
</rsm:ExchangedDocument>
|
|
464
|
+
</rsm:CrossIndustryInvoice>
|
|
465
|
+
`;
|
|
466
|
+
|
|
467
|
+
async function createEInvoicePdf() {
|
|
468
|
+
const { AFRelationship } = await import('pdf-lib');
|
|
469
|
+
const doc = await PDFDocument.create();
|
|
470
|
+
doc.setTitle('ZUGFeRD / Factur-X invoice');
|
|
471
|
+
doc.setProducer('pdfium-native test');
|
|
472
|
+
const page = doc.addPage([612, 792]);
|
|
473
|
+
const font = await doc.embedFont(StandardFonts.Helvetica);
|
|
474
|
+
page.drawText('Invoice RE-2025-0001', { x: 50, y: 700, size: 16, font });
|
|
475
|
+
page.drawText('Structured data embedded as factur-x.xml', { x: 50, y: 670, size: 11, font });
|
|
476
|
+
|
|
477
|
+
await doc.attach(Buffer.from(FACTUR_X_XML, 'utf8'), 'factur-x.xml', {
|
|
478
|
+
mimeType: 'text/xml',
|
|
479
|
+
description: 'Factur-X invoice',
|
|
480
|
+
creationDate: new Date('2025-01-01T12:00:00Z'),
|
|
481
|
+
modificationDate: new Date('2025-01-01T12:00:00Z'),
|
|
482
|
+
afRelationship: AFRelationship.Alternative,
|
|
483
|
+
});
|
|
484
|
+
|
|
485
|
+
await doc.attach(Buffer.from('Human-readable notes.\n', 'utf8'), 'notes.txt', {
|
|
486
|
+
mimeType: 'text/plain',
|
|
487
|
+
description: 'Supplementary notes',
|
|
488
|
+
creationDate: new Date('2025-01-01T12:00:00Z'),
|
|
489
|
+
modificationDate: new Date('2025-01-01T12:00:00Z'),
|
|
490
|
+
afRelationship: AFRelationship.Supplement,
|
|
491
|
+
});
|
|
492
|
+
|
|
493
|
+
return doc.save();
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
// --- PDF with a page-level FileAttachment annotation ---
|
|
497
|
+
// PDFium exposes "paperclip" file attachments as /FileAttachment annotations
|
|
498
|
+
// whose embedded file lives on the annotation itself, NOT in the
|
|
499
|
+
// /EmbeddedFiles name tree (that is the document-level attachment API). A plain
|
|
500
|
+
// Text annotation precedes it so tests can exercise stable annotation indices
|
|
501
|
+
// and the "not a file attachment" error path.
|
|
502
|
+
const ATTACHMENT_REPORT_TXT = 'Quarterly report attachment.\nSecond line.\n';
|
|
503
|
+
|
|
504
|
+
async function createFileAttachmentAnnotationPdf() {
|
|
505
|
+
const doc = await PDFDocument.create();
|
|
506
|
+
const page = doc.addPage([612, 792]);
|
|
507
|
+
const font = await doc.embedFont(StandardFonts.Helvetica);
|
|
508
|
+
page.drawText('Page with a file-attachment annotation', { x: 50, y: 700, size: 14, font });
|
|
509
|
+
|
|
510
|
+
const { PDFName, PDFString } = await import('pdf-lib');
|
|
511
|
+
|
|
512
|
+
const fileBytes = Buffer.from(ATTACHMENT_REPORT_TXT, 'utf8');
|
|
513
|
+
|
|
514
|
+
// embedded file stream (FlateDecode, so extraction proves a lossless decode)
|
|
515
|
+
const embeddedFile = doc.context.flateStream(fileBytes, {
|
|
516
|
+
Type: 'EmbeddedFile',
|
|
517
|
+
Subtype: 'text/plain',
|
|
518
|
+
Params: { Size: fileBytes.length },
|
|
519
|
+
});
|
|
520
|
+
const embeddedFileRef = doc.context.register(embeddedFile);
|
|
521
|
+
|
|
522
|
+
const fileSpec = doc.context.obj({
|
|
523
|
+
Type: 'Filespec',
|
|
524
|
+
F: PDFString.of('report.txt'),
|
|
525
|
+
UF: PDFString.of('report.txt'),
|
|
526
|
+
EF: doc.context.obj({ F: embeddedFileRef }),
|
|
527
|
+
});
|
|
528
|
+
const fileSpecRef = doc.context.register(fileSpec);
|
|
529
|
+
|
|
530
|
+
// Text annotation first → the FileAttachment annotation lands at index 1
|
|
531
|
+
const textAnnot = doc.context.obj({
|
|
532
|
+
Type: 'Annot',
|
|
533
|
+
Subtype: 'Text',
|
|
534
|
+
Rect: [50, 600, 70, 620],
|
|
535
|
+
Contents: PDFString.of('Just a sticky note'),
|
|
536
|
+
});
|
|
537
|
+
const textAnnotRef = doc.context.register(textAnnot);
|
|
538
|
+
|
|
539
|
+
const fileAnnot = doc.context.obj({
|
|
540
|
+
Type: 'Annot',
|
|
541
|
+
Subtype: 'FileAttachment',
|
|
542
|
+
Rect: [100, 600, 120, 620],
|
|
543
|
+
Contents: PDFString.of('See attached report'),
|
|
544
|
+
FS: fileSpecRef,
|
|
545
|
+
Name: 'Paperclip',
|
|
546
|
+
});
|
|
547
|
+
const fileAnnotRef = doc.context.register(fileAnnot);
|
|
548
|
+
|
|
549
|
+
page.node.set(PDFName.of('Annots'), doc.context.obj([textAnnotRef, fileAnnotRef]));
|
|
550
|
+
return doc.save();
|
|
551
|
+
}
|
|
552
|
+
|
|
447
553
|
// --- PDF with form fields ---
|
|
448
554
|
async function createFormFieldsPdf() {
|
|
449
555
|
const doc = await PDFDocument.create();
|
|
@@ -518,6 +624,8 @@ const fixtures = [
|
|
|
518
624
|
['rich-bookmarks.pdf', createRichBookmarkPdf],
|
|
519
625
|
['border-annotations.pdf', createBorderAnnotationPdf],
|
|
520
626
|
['form-fields.pdf', createFormFieldsPdf],
|
|
627
|
+
['einvoice-zugferd.pdf', createEInvoicePdf],
|
|
628
|
+
['file-attachment-annotation.pdf', createFileAttachmentAnnotationPdf],
|
|
521
629
|
];
|
|
522
630
|
|
|
523
631
|
for (const [name, generator] of fixtures) {
|
package/scripts/prebuilds.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
|
-
"darwin-arm64": "
|
|
3
|
-
"darwin-x64": "
|
|
4
|
-
"linux-arm": "
|
|
5
|
-
"linux-arm64": "
|
|
6
|
-
"linux-musl-arm64": "
|
|
7
|
-
"linux-musl-x64": "
|
|
8
|
-
"linux-ppc64": "
|
|
9
|
-
"linux-x64": "
|
|
10
|
-
"win32-arm64": "
|
|
11
|
-
"win32-x64": "
|
|
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"
|
|
12
12
|
}
|
package/src/annotations_worker.h
CHANGED
|
@@ -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 (!WriteAttachmentBytesToFile(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,279 @@
|
|
|
1
|
+
#pragma once
|
|
2
|
+
|
|
3
|
+
#include "napi_helpers.h"
|
|
4
|
+
|
|
5
|
+
#include <atomic>
|
|
6
|
+
#include <cstdio>
|
|
7
|
+
#include <memory>
|
|
8
|
+
#include <string>
|
|
9
|
+
#include <vector>
|
|
10
|
+
|
|
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
|
+
#include "fpdf_attachment.h"
|
|
20
|
+
|
|
21
|
+
// ---------------------------------------------------------------------------
|
|
22
|
+
// Embedded-file (attachment) helpers
|
|
23
|
+
// ---------------------------------------------------------------------------
|
|
24
|
+
// PDF/A-3 documents (ZUGFeRD / Factur-X / XRechnung e-invoices) carry the
|
|
25
|
+
// structured invoice as an embedded XML file in the /EmbeddedFiles name tree.
|
|
26
|
+
// FPDFDoc_GetAttachmentCount already surfaces detection via metadata; these
|
|
27
|
+
// workers add the ability to enumerate attachment metadata and read the raw
|
|
28
|
+
// bytes so callers can pull out factur-x.xml / zugferd-invoice.xml / etc.
|
|
29
|
+
|
|
30
|
+
// read a UTF-16LE string value from an attachment's params dictionary
|
|
31
|
+
inline std::u16string ReadAttachmentStringValue(FPDF_ATTACHMENT attachment,
|
|
32
|
+
const char *key) {
|
|
33
|
+
return ReadU16(
|
|
34
|
+
[&](auto *, unsigned long) {
|
|
35
|
+
return FPDFAttachment_GetStringValue(attachment, key, nullptr, 0);
|
|
36
|
+
},
|
|
37
|
+
[&](FPDF_WCHAR *buf, unsigned long len) {
|
|
38
|
+
return FPDFAttachment_GetStringValue(attachment, key, buf, len);
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// read an attachment's file name (from the filespec /UF or /F entry)
|
|
43
|
+
inline std::u16string ReadAttachmentName(FPDF_ATTACHMENT attachment) {
|
|
44
|
+
return ReadU16(
|
|
45
|
+
[&](auto *, unsigned long) {
|
|
46
|
+
return FPDFAttachment_GetName(attachment, nullptr, 0);
|
|
47
|
+
},
|
|
48
|
+
[&](FPDF_WCHAR *buf, unsigned long len) {
|
|
49
|
+
return FPDFAttachment_GetName(attachment, buf, len);
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Reads the full decoded bytes of an attachment via the two-pass
|
|
54
|
+
// FPDFAttachment_GetFile protocol (null buffer → size, then copy). A
|
|
55
|
+
// zero-length embedded file yields an empty vector and success. Returns false
|
|
56
|
+
// and sets `err` on failure. Shared by the document-level and annotation-level
|
|
57
|
+
// attachment readers.
|
|
58
|
+
inline bool ReadAttachmentFileBytes(FPDF_ATTACHMENT attachment,
|
|
59
|
+
std::vector<uint8_t> &out,
|
|
60
|
+
std::string &err) {
|
|
61
|
+
unsigned long outLen = 0;
|
|
62
|
+
if (!FPDFAttachment_GetFile(attachment, nullptr, 0, &outLen)) {
|
|
63
|
+
err = "Failed to read attachment file data";
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
out.clear();
|
|
67
|
+
// skip the copy for a zero-length embedded file, where out.data() would be
|
|
68
|
+
// null and the copy is a no-op anyway
|
|
69
|
+
if (outLen > 0) {
|
|
70
|
+
out.resize(outLen);
|
|
71
|
+
unsigned long written = 0;
|
|
72
|
+
if (!FPDFAttachment_GetFile(attachment, out.data(), outLen, &written) ||
|
|
73
|
+
written != outLen) {
|
|
74
|
+
err = "Failed to read attachment file data";
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return true;
|
|
79
|
+
}
|
|
80
|
+
|
|
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
|
+
// ---------------------------------------------------------------------------
|
|
111
|
+
// GetAttachmentsWorker — async attachment metadata listing
|
|
112
|
+
// ---------------------------------------------------------------------------
|
|
113
|
+
// Deliberately cheap: reads only dictionary entries (name, subtype, dates)
|
|
114
|
+
// and never decodes the file streams. Use GetAttachmentDataWorker to fetch the
|
|
115
|
+
// bytes of a specific attachment.
|
|
116
|
+
|
|
117
|
+
struct AttachmentInfo {
|
|
118
|
+
int index = 0;
|
|
119
|
+
std::u16string name;
|
|
120
|
+
std::u16string mimeType;
|
|
121
|
+
std::u16string creationDate;
|
|
122
|
+
std::u16string modDate;
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
class GetAttachmentsWorker : public SafeAsyncWorker {
|
|
126
|
+
public:
|
|
127
|
+
GetAttachmentsWorker(Napi::Env env, FPDF_DOCUMENT doc,
|
|
128
|
+
std::shared_ptr<std::atomic<bool>> docAlive)
|
|
129
|
+
: SafeAsyncWorker(env), deferred_(Napi::Promise::Deferred::New(env)),
|
|
130
|
+
doc_(doc), docAlive_(std::move(docAlive)) {}
|
|
131
|
+
|
|
132
|
+
Napi::Promise Promise() { return deferred_.Promise(); }
|
|
133
|
+
|
|
134
|
+
protected:
|
|
135
|
+
void Execute() override {
|
|
136
|
+
std::lock_guard<std::mutex> lock(g_pdfium_mutex);
|
|
137
|
+
if (!docAlive_ || !docAlive_->load()) {
|
|
138
|
+
SetError("Document was destroyed");
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
int count = FPDFDoc_GetAttachmentCount(doc_);
|
|
143
|
+
if (count <= 0)
|
|
144
|
+
return;
|
|
145
|
+
|
|
146
|
+
attachments_.reserve(count);
|
|
147
|
+
for (int i = 0; i < count; i++) {
|
|
148
|
+
FPDF_ATTACHMENT attachment = FPDFDoc_GetAttachment(doc_, i);
|
|
149
|
+
if (!attachment)
|
|
150
|
+
continue;
|
|
151
|
+
|
|
152
|
+
AttachmentInfo info;
|
|
153
|
+
info.index = i;
|
|
154
|
+
|
|
155
|
+
info.name = ReadU16(
|
|
156
|
+
[&](auto *, unsigned long) {
|
|
157
|
+
return FPDFAttachment_GetName(attachment, nullptr, 0);
|
|
158
|
+
},
|
|
159
|
+
[&](FPDF_WCHAR *buf, unsigned long len) {
|
|
160
|
+
return FPDFAttachment_GetName(attachment, buf, len);
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
info.mimeType = ReadU16(
|
|
164
|
+
[&](auto *, unsigned long) {
|
|
165
|
+
return FPDFAttachment_GetSubtype(attachment, nullptr, 0);
|
|
166
|
+
},
|
|
167
|
+
[&](FPDF_WCHAR *buf, unsigned long len) {
|
|
168
|
+
return FPDFAttachment_GetSubtype(attachment, buf, len);
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
info.creationDate = ReadAttachmentStringValue(attachment, "CreationDate");
|
|
172
|
+
info.modDate = ReadAttachmentStringValue(attachment, "ModDate");
|
|
173
|
+
|
|
174
|
+
attachments_.push_back(std::move(info));
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
void OnOK() override {
|
|
179
|
+
Napi::Env env = Env();
|
|
180
|
+
Napi::Array arr = Napi::Array::New(env, attachments_.size());
|
|
181
|
+
for (uint32_t i = 0; i < attachments_.size(); i++) {
|
|
182
|
+
const auto &info = attachments_[i];
|
|
183
|
+
Napi::Object obj = Napi::Object::New(env);
|
|
184
|
+
obj.Set("index", Napi::Number::New(env, info.index));
|
|
185
|
+
SetU16(obj, "name", env, info.name);
|
|
186
|
+
SetU16(obj, "mimeType", env, info.mimeType);
|
|
187
|
+
SetU16IfPresent(obj, "creationDate", env, info.creationDate);
|
|
188
|
+
SetU16IfPresent(obj, "modDate", env, info.modDate);
|
|
189
|
+
arr.Set(i, obj);
|
|
190
|
+
}
|
|
191
|
+
deferred_.Resolve(arr);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
void OnError(const Napi::Error &err) override {
|
|
195
|
+
deferred_.Reject(err.Value());
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
private:
|
|
199
|
+
Napi::Promise::Deferred deferred_;
|
|
200
|
+
FPDF_DOCUMENT doc_;
|
|
201
|
+
std::shared_ptr<std::atomic<bool>> docAlive_;
|
|
202
|
+
std::vector<AttachmentInfo> attachments_;
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
// ---------------------------------------------------------------------------
|
|
206
|
+
// GetAttachmentDataWorker — async read of a single attachment's bytes
|
|
207
|
+
// ---------------------------------------------------------------------------
|
|
208
|
+
|
|
209
|
+
class GetAttachmentDataWorker : public SafeAsyncWorker {
|
|
210
|
+
public:
|
|
211
|
+
GetAttachmentDataWorker(Napi::Env env, FPDF_DOCUMENT doc, int index,
|
|
212
|
+
std::string outputPath,
|
|
213
|
+
std::shared_ptr<std::atomic<bool>> docAlive)
|
|
214
|
+
: SafeAsyncWorker(env), deferred_(Napi::Promise::Deferred::New(env)),
|
|
215
|
+
doc_(doc), index_(index), outputPath_(std::move(outputPath)),
|
|
216
|
+
docAlive_(std::move(docAlive)) {}
|
|
217
|
+
|
|
218
|
+
Napi::Promise Promise() { return deferred_.Promise(); }
|
|
219
|
+
|
|
220
|
+
protected:
|
|
221
|
+
void Execute() override {
|
|
222
|
+
std::lock_guard<std::mutex> lock(g_pdfium_mutex);
|
|
223
|
+
if (!docAlive_ || !docAlive_->load()) {
|
|
224
|
+
SetError("Document was destroyed");
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
int count = FPDFDoc_GetAttachmentCount(doc_);
|
|
229
|
+
if (index_ < 0 || index_ >= count) {
|
|
230
|
+
SetError("Attachment index out of range");
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
FPDF_ATTACHMENT attachment = FPDFDoc_GetAttachment(doc_, index_);
|
|
235
|
+
if (!attachment) {
|
|
236
|
+
SetError("Failed to get attachment");
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
std::string err;
|
|
241
|
+
if (!ReadAttachmentFileBytes(attachment, data_, err)) {
|
|
242
|
+
SetError(err);
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
if (!outputPath_.empty()) {
|
|
247
|
+
if (!WriteAttachmentBytesToFile(outputPath_, data_, err)) {
|
|
248
|
+
SetError(err);
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
data_.clear();
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
void OnOK() override {
|
|
256
|
+
Napi::Env env = Env();
|
|
257
|
+
if (!outputPath_.empty()) {
|
|
258
|
+
deferred_.Resolve(env.Undefined());
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
auto *vec = new std::vector<uint8_t>(std::move(data_));
|
|
262
|
+
auto buffer = Napi::Buffer<uint8_t>::New(
|
|
263
|
+
env, vec->data(), vec->size(),
|
|
264
|
+
[](Napi::Env, uint8_t *, std::vector<uint8_t> *v) { delete v; }, vec);
|
|
265
|
+
deferred_.Resolve(buffer);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
void OnError(const Napi::Error &err) override {
|
|
269
|
+
deferred_.Reject(err.Value());
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
private:
|
|
273
|
+
Napi::Promise::Deferred deferred_;
|
|
274
|
+
FPDF_DOCUMENT doc_;
|
|
275
|
+
int index_;
|
|
276
|
+
std::string outputPath_;
|
|
277
|
+
std::shared_ptr<std::atomic<bool>> docAlive_;
|
|
278
|
+
std::vector<uint8_t> data_;
|
|
279
|
+
};
|
package/src/document.h
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
#pragma once
|
|
2
2
|
|
|
3
|
+
#include "attachments_worker.h"
|
|
3
4
|
#include "bookmarks_worker.h"
|
|
4
5
|
#include "page.h"
|
|
5
6
|
|
|
@@ -21,6 +22,8 @@ public:
|
|
|
21
22
|
{
|
|
22
23
|
InstanceMethod<&PDFiumDocument::GetPage>("getPage"),
|
|
23
24
|
InstanceMethod<&PDFiumDocument::GetBookmarks>("getBookmarks"),
|
|
25
|
+
InstanceMethod<&PDFiumDocument::GetAttachments>("getAttachments"),
|
|
26
|
+
InstanceMethod<&PDFiumDocument::GetAttachment>("getAttachment"),
|
|
24
27
|
InstanceMethod<&PDFiumDocument::Destroy>("destroy"),
|
|
25
28
|
});
|
|
26
29
|
}
|
|
@@ -82,6 +85,51 @@ private:
|
|
|
82
85
|
return promise;
|
|
83
86
|
}
|
|
84
87
|
|
|
88
|
+
/**
|
|
89
|
+
* Returns metadata for every embedded file / attachment (async).
|
|
90
|
+
*/
|
|
91
|
+
Napi::Value GetAttachments(const Napi::CallbackInfo &info) {
|
|
92
|
+
Napi::Env env = info.Env();
|
|
93
|
+
EnsureOpen(env);
|
|
94
|
+
if (env.IsExceptionPending())
|
|
95
|
+
return env.Null();
|
|
96
|
+
|
|
97
|
+
auto *worker = new GetAttachmentsWorker(env, doc_, docAlive_);
|
|
98
|
+
auto promise = worker->Promise();
|
|
99
|
+
worker->Queue();
|
|
100
|
+
return promise;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Reads the raw bytes of the attachment at `index` (async). Resolves to a
|
|
105
|
+
* Buffer, or writes to an optional output path and resolves to undefined.
|
|
106
|
+
*/
|
|
107
|
+
Napi::Value GetAttachment(const Napi::CallbackInfo &info) {
|
|
108
|
+
Napi::Env env = info.Env();
|
|
109
|
+
EnsureOpen(env);
|
|
110
|
+
if (env.IsExceptionPending())
|
|
111
|
+
return env.Null();
|
|
112
|
+
|
|
113
|
+
if (info.Length() < 1 || !info[0].IsNumber()) {
|
|
114
|
+
Napi::TypeError::New(env, "Expected attachment index")
|
|
115
|
+
.ThrowAsJavaScriptException();
|
|
116
|
+
return env.Null();
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
int index = info[0].As<Napi::Number>().Int32Value();
|
|
120
|
+
|
|
121
|
+
std::string outputPath;
|
|
122
|
+
if (info.Length() > 1 && info[1].IsString()) {
|
|
123
|
+
outputPath = info[1].As<Napi::String>().Utf8Value();
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
auto *worker = new GetAttachmentDataWorker(env, doc_, index,
|
|
127
|
+
std::move(outputPath), docAlive_);
|
|
128
|
+
auto promise = worker->Promise();
|
|
129
|
+
worker->Queue();
|
|
130
|
+
return promise;
|
|
131
|
+
}
|
|
132
|
+
|
|
85
133
|
/**
|
|
86
134
|
* Closes the document and releases all resources.
|
|
87
135
|
*/
|
package/src/page.h
CHANGED
|
@@ -35,6 +35,8 @@ public:
|
|
|
35
35
|
InstanceMethod<&PDFiumPage::GetLinks>("getLinks"),
|
|
36
36
|
InstanceMethod<&PDFiumPage::Search>("search"),
|
|
37
37
|
InstanceMethod<&PDFiumPage::GetAnnotations>("getAnnotations"),
|
|
38
|
+
InstanceMethod<&PDFiumPage::GetAnnotationAttachment>(
|
|
39
|
+
"getAnnotationAttachment"),
|
|
38
40
|
InstanceMethod<&PDFiumPage::GetFormFields>("getFormFields"),
|
|
39
41
|
InstanceMethod<&PDFiumPage::Close>("close"),
|
|
40
42
|
});
|
|
@@ -345,6 +347,36 @@ private:
|
|
|
345
347
|
return promise;
|
|
346
348
|
}
|
|
347
349
|
|
|
350
|
+
/**
|
|
351
|
+
* Reads the embedded file of the FileAttachment annotation at `index`
|
|
352
|
+
* (async). Resolves to a Buffer, or writes to an optional output path and
|
|
353
|
+
* resolves to undefined.
|
|
354
|
+
*/
|
|
355
|
+
Napi::Value GetAnnotationAttachment(const Napi::CallbackInfo &info) {
|
|
356
|
+
Napi::Env env = info.Env();
|
|
357
|
+
EnsureOpen(env);
|
|
358
|
+
if (env.IsExceptionPending())
|
|
359
|
+
return env.Null();
|
|
360
|
+
|
|
361
|
+
if (info.Length() < 1 || !info[0].IsNumber()) {
|
|
362
|
+
Napi::TypeError::New(env, "Expected annotation index")
|
|
363
|
+
.ThrowAsJavaScriptException();
|
|
364
|
+
return env.Null();
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
int index = info[0].As<Napi::Number>().Int32Value();
|
|
368
|
+
|
|
369
|
+
std::string outputPath;
|
|
370
|
+
if (info.Length() > 1 && info[1].IsString())
|
|
371
|
+
outputPath = info[1].As<Napi::String>().Utf8Value();
|
|
372
|
+
|
|
373
|
+
auto *worker = new GetAnnotationAttachmentWorker(
|
|
374
|
+
env, page_, index, std::move(outputPath), alive_, docAlive_);
|
|
375
|
+
auto promise = worker->Promise();
|
|
376
|
+
worker->Queue();
|
|
377
|
+
return promise;
|
|
378
|
+
}
|
|
379
|
+
|
|
348
380
|
/**
|
|
349
381
|
* Returns all form fields on the page (async). Returns a
|
|
350
382
|
* Promise<FormField[]>.
|