pdfium-native 0.1.1
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/LICENSE +21 -0
- package/README.md +227 -0
- package/binding.gyp +85 -0
- package/dist/document.d.ts +23 -0
- package/dist/document.d.ts.map +1 -0
- package/dist/document.js +36 -0
- package/dist/document.js.map +1 -0
- package/dist/errors.d.ts +23 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +58 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +33 -0
- package/dist/index.js.map +1 -0
- package/dist/page.d.ts +40 -0
- package/dist/page.d.ts.map +1 -0
- package/dist/page.js +59 -0
- package/dist/page.js.map +1 -0
- package/dist/types.d.ts +120 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/lib/__tests__/document.test.ts +99 -0
- package/lib/__tests__/features.test.ts +72 -0
- package/lib/__tests__/fixtures.ts +71 -0
- package/lib/__tests__/load.test.ts +68 -0
- package/lib/__tests__/page.test.ts +123 -0
- package/lib/__tests__/render.test.ts +103 -0
- package/lib/__tests__/search.test.ts +44 -0
- package/lib/document.ts +40 -0
- package/lib/errors.ts +63 -0
- package/lib/index.ts +63 -0
- package/lib/page.ts +80 -0
- package/lib/types.ts +154 -0
- package/package.json +80 -0
- package/scripts/bundle-lib.mjs +66 -0
- package/scripts/download-pdfium.mjs +84 -0
- package/scripts/generate-fixtures.mjs +194 -0
- package/scripts/install.mjs +80 -0
- package/src/document.h +254 -0
- package/src/napi_helpers.h +50 -0
- package/src/page.h +576 -0
- package/src/pdfium_addon.cc +218 -0
- package/src/render_worker.h +141 -0
- package/src/stb_image_write.c +2 -0
- package/src/stb_image_write.h +1724 -0
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generate test fixture PDFs. Run once with: node scripts/generate-fixtures.mjs
|
|
3
|
+
* Requires: npm install pdf-lib (dev only, not committed)
|
|
4
|
+
*/
|
|
5
|
+
import { writeFileSync, mkdirSync } from 'node:fs';
|
|
6
|
+
import { resolve, dirname } from 'node:path';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import { PDFDocument, StandardFonts, rgb } from 'pdf-lib';
|
|
9
|
+
|
|
10
|
+
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
11
|
+
const fixturesDir = resolve(__dirname, '..', 'test', 'fixtures');
|
|
12
|
+
mkdirSync(fixturesDir, { recursive: true });
|
|
13
|
+
|
|
14
|
+
// --- PDF with metadata ---
|
|
15
|
+
async function createMetadataPdf() {
|
|
16
|
+
const doc = await PDFDocument.create();
|
|
17
|
+
doc.setTitle('Test Document Title');
|
|
18
|
+
doc.setAuthor('Test Author');
|
|
19
|
+
doc.setSubject('Test Subject');
|
|
20
|
+
doc.setKeywords(['test', 'fixture', 'pdfium']);
|
|
21
|
+
doc.setCreator('pdfium-native test');
|
|
22
|
+
doc.setProducer('pdf-lib');
|
|
23
|
+
const page = doc.addPage([612, 792]);
|
|
24
|
+
const font = await doc.embedFont(StandardFonts.Helvetica);
|
|
25
|
+
page.drawText('Metadata test page', { x: 50, y: 700, size: 16, font });
|
|
26
|
+
return doc.save();
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// --- PDF with annotations ---
|
|
30
|
+
async function createAnnotationPdf() {
|
|
31
|
+
const doc = await PDFDocument.create();
|
|
32
|
+
const page = doc.addPage([612, 792]);
|
|
33
|
+
const font = await doc.embedFont(StandardFonts.Helvetica);
|
|
34
|
+
page.drawText('Page with annotations', { x: 50, y: 700, size: 16, font });
|
|
35
|
+
|
|
36
|
+
// add a text annotation (sticky note) via raw PDF dict
|
|
37
|
+
const { PDFName, PDFString } = await import('pdf-lib');
|
|
38
|
+
const annotDict = doc.context.obj({
|
|
39
|
+
Type: 'Annot',
|
|
40
|
+
Subtype: 'Text',
|
|
41
|
+
Rect: [100, 600, 120, 620],
|
|
42
|
+
Contents: PDFString.of('This is a sticky note'),
|
|
43
|
+
C: [1, 0, 0], // red
|
|
44
|
+
Open: true,
|
|
45
|
+
});
|
|
46
|
+
const annotRef = doc.context.register(annotDict);
|
|
47
|
+
|
|
48
|
+
// add a highlight annotation
|
|
49
|
+
const highlightDict = doc.context.obj({
|
|
50
|
+
Type: 'Annot',
|
|
51
|
+
Subtype: 'Highlight',
|
|
52
|
+
Rect: [50, 695, 250, 720],
|
|
53
|
+
Contents: PDFString.of('Highlighted text'),
|
|
54
|
+
C: [1, 1, 0], // yellow
|
|
55
|
+
QuadPoints: [50, 720, 250, 720, 50, 695, 250, 695],
|
|
56
|
+
});
|
|
57
|
+
const highlightRef = doc.context.register(highlightDict);
|
|
58
|
+
|
|
59
|
+
// attach annotations to page
|
|
60
|
+
const pageDict = page.node;
|
|
61
|
+
pageDict.set(PDFName.of('Annots'), doc.context.obj([annotRef, highlightRef]));
|
|
62
|
+
|
|
63
|
+
return doc.save();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// --- PDF with links ---
|
|
67
|
+
async function createLinkPdf() {
|
|
68
|
+
const doc = await PDFDocument.create();
|
|
69
|
+
const page1 = doc.addPage([612, 792]);
|
|
70
|
+
const page2 = doc.addPage([612, 792]);
|
|
71
|
+
const font = await doc.embedFont(StandardFonts.Helvetica);
|
|
72
|
+
|
|
73
|
+
page1.drawText('Page 1 - click links below', { x: 50, y: 700, size: 16, font });
|
|
74
|
+
page1.drawText('Go to page 2', { x: 50, y: 650, size: 12, font, color: rgb(0, 0, 1) });
|
|
75
|
+
page1.drawText('Visit example.com', { x: 50, y: 620, size: 12, font, color: rgb(0, 0, 1) });
|
|
76
|
+
|
|
77
|
+
page2.drawText('Page 2 - target', { x: 50, y: 700, size: 16, font });
|
|
78
|
+
|
|
79
|
+
// create link annotations via raw PDF
|
|
80
|
+
const { PDFName, PDFString } = await import('pdf-lib');
|
|
81
|
+
|
|
82
|
+
// internal link to page 2
|
|
83
|
+
const page2Ref = doc.getPages()[1].ref;
|
|
84
|
+
const internalLink = doc.context.obj({
|
|
85
|
+
Type: 'Annot',
|
|
86
|
+
Subtype: 'Link',
|
|
87
|
+
Rect: [50, 645, 200, 665],
|
|
88
|
+
Dest: [page2Ref, 'Fit'],
|
|
89
|
+
Border: [0, 0, 0],
|
|
90
|
+
});
|
|
91
|
+
const internalLinkRef = doc.context.register(internalLink);
|
|
92
|
+
|
|
93
|
+
// external URI link
|
|
94
|
+
const uriAction = doc.context.obj({
|
|
95
|
+
Type: 'Action',
|
|
96
|
+
S: 'URI',
|
|
97
|
+
URI: PDFString.of('https://example.com'),
|
|
98
|
+
});
|
|
99
|
+
const uriActionRef = doc.context.register(uriAction);
|
|
100
|
+
const externalLink = doc.context.obj({
|
|
101
|
+
Type: 'Annot',
|
|
102
|
+
Subtype: 'Link',
|
|
103
|
+
Rect: [50, 615, 250, 635],
|
|
104
|
+
A: uriActionRef,
|
|
105
|
+
Border: [0, 0, 0],
|
|
106
|
+
});
|
|
107
|
+
const externalLinkRef = doc.context.register(externalLink);
|
|
108
|
+
|
|
109
|
+
const page1Dict = page1.node;
|
|
110
|
+
page1Dict.set(PDFName.of('Annots'), doc.context.obj([internalLinkRef, externalLinkRef]));
|
|
111
|
+
|
|
112
|
+
return doc.save();
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// --- PDF with bookmarks ---
|
|
116
|
+
async function createBookmarkPdf() {
|
|
117
|
+
const doc = await PDFDocument.create();
|
|
118
|
+
const font = await doc.embedFont(StandardFonts.Helvetica);
|
|
119
|
+
|
|
120
|
+
const page1 = doc.addPage([612, 792]);
|
|
121
|
+
page1.drawText('Chapter 1: Introduction', { x: 50, y: 700, size: 20, font });
|
|
122
|
+
|
|
123
|
+
const page2 = doc.addPage([612, 792]);
|
|
124
|
+
page2.drawText('Chapter 2: Getting Started', { x: 50, y: 700, size: 20, font });
|
|
125
|
+
|
|
126
|
+
const page3 = doc.addPage([612, 792]);
|
|
127
|
+
page3.drawText('Chapter 3: Advanced Topics', { x: 50, y: 700, size: 20, font });
|
|
128
|
+
|
|
129
|
+
// build outline tree via raw PDF objects
|
|
130
|
+
const { PDFName, PDFString } = await import('pdf-lib');
|
|
131
|
+
|
|
132
|
+
const page1Ref = doc.getPages()[0].ref;
|
|
133
|
+
const page2Ref = doc.getPages()[1].ref;
|
|
134
|
+
const page3Ref = doc.getPages()[2].ref;
|
|
135
|
+
|
|
136
|
+
// outline items (linked list)
|
|
137
|
+
const item1 = doc.context.obj({
|
|
138
|
+
Title: PDFString.of('Chapter 1'),
|
|
139
|
+
Dest: [page1Ref, 'Fit'],
|
|
140
|
+
});
|
|
141
|
+
const item1Ref = doc.context.register(item1);
|
|
142
|
+
|
|
143
|
+
const item2 = doc.context.obj({
|
|
144
|
+
Title: PDFString.of('Chapter 2'),
|
|
145
|
+
Dest: [page2Ref, 'Fit'],
|
|
146
|
+
});
|
|
147
|
+
const item2Ref = doc.context.register(item2);
|
|
148
|
+
|
|
149
|
+
const item3 = doc.context.obj({
|
|
150
|
+
Title: PDFString.of('Chapter 3'),
|
|
151
|
+
Dest: [page3Ref, 'Fit'],
|
|
152
|
+
});
|
|
153
|
+
const item3Ref = doc.context.register(item3);
|
|
154
|
+
|
|
155
|
+
// link siblings
|
|
156
|
+
item1.set(PDFName.of('Next'), item2Ref);
|
|
157
|
+
item2.set(PDFName.of('Prev'), item1Ref);
|
|
158
|
+
item2.set(PDFName.of('Next'), item3Ref);
|
|
159
|
+
item3.set(PDFName.of('Prev'), item2Ref);
|
|
160
|
+
|
|
161
|
+
// outline root
|
|
162
|
+
const outlines = doc.context.obj({
|
|
163
|
+
Type: 'Outlines',
|
|
164
|
+
First: item1Ref,
|
|
165
|
+
Last: item3Ref,
|
|
166
|
+
Count: 3,
|
|
167
|
+
});
|
|
168
|
+
const outlinesRef = doc.context.register(outlines);
|
|
169
|
+
|
|
170
|
+
// set parent on items
|
|
171
|
+
item1.set(PDFName.of('Parent'), outlinesRef);
|
|
172
|
+
item2.set(PDFName.of('Parent'), outlinesRef);
|
|
173
|
+
item3.set(PDFName.of('Parent'), outlinesRef);
|
|
174
|
+
|
|
175
|
+
// attach to catalog
|
|
176
|
+
doc.catalog.set(PDFName.of('Outlines'), outlinesRef);
|
|
177
|
+
|
|
178
|
+
return doc.save();
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// Generate all fixtures
|
|
182
|
+
const fixtures = [
|
|
183
|
+
['metadata.pdf', createMetadataPdf],
|
|
184
|
+
['annotations.pdf', createAnnotationPdf],
|
|
185
|
+
['links.pdf', createLinkPdf],
|
|
186
|
+
['bookmarks.pdf', createBookmarkPdf],
|
|
187
|
+
];
|
|
188
|
+
|
|
189
|
+
for (const [name, generator] of fixtures) {
|
|
190
|
+
const bytes = await generator();
|
|
191
|
+
const path = resolve(fixturesDir, name);
|
|
192
|
+
writeFileSync(path, bytes);
|
|
193
|
+
console.log(`Created ${path} (${bytes.length} bytes)`);
|
|
194
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Try to download a prebuilt binary from GitHub releases.
|
|
3
|
+
* Falls back to compiling from source if no prebuilt is available.
|
|
4
|
+
*
|
|
5
|
+
* Prebuilt tarball naming: pdfium-v{version}-{platform}-{arch}.tar.gz
|
|
6
|
+
* Contents: build/Release/pdfium.node + build/Release/libpdfium.{dylib,so,dll}
|
|
7
|
+
*/
|
|
8
|
+
import { existsSync, mkdirSync, createWriteStream, readFileSync, unlinkSync } from 'node:fs';
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
import { execSync, execFileSync } from 'node:child_process';
|
|
11
|
+
import { pipeline } from 'node:stream/promises';
|
|
12
|
+
|
|
13
|
+
const root = join(import.meta.dirname, '..');
|
|
14
|
+
const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
|
|
15
|
+
const version = pkg.version;
|
|
16
|
+
const repo = 'xonaman/nodejs-pdfium-native';
|
|
17
|
+
|
|
18
|
+
const platform = process.platform;
|
|
19
|
+
const arch = process.arch;
|
|
20
|
+
const tarName = `pdfium-v${version}-${platform}-${arch}.tar.gz`;
|
|
21
|
+
const releaseUrl = `https://github.com/${repo}/releases/download/v${version}/${tarName}`;
|
|
22
|
+
|
|
23
|
+
const outDir = join(root, 'build', 'Release');
|
|
24
|
+
|
|
25
|
+
async function tryDownload() {
|
|
26
|
+
console.log(`Checking for prebuilt binary: ${tarName}`);
|
|
27
|
+
|
|
28
|
+
try {
|
|
29
|
+
const res = await fetch(releaseUrl, { redirect: 'follow' });
|
|
30
|
+
if (!res.ok) {
|
|
31
|
+
console.log(`No prebuilt binary found (HTTP ${res.status}), will compile from source.`);
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
mkdirSync(outDir, { recursive: true });
|
|
36
|
+
const tmpTar = join(root, tarName);
|
|
37
|
+
|
|
38
|
+
// download to temp file
|
|
39
|
+
const fileStream = createWriteStream(tmpTar);
|
|
40
|
+
const body = res.body;
|
|
41
|
+
if (!body) return false;
|
|
42
|
+
|
|
43
|
+
await pipeline(body, fileStream);
|
|
44
|
+
|
|
45
|
+
// extract tar.gz into project root
|
|
46
|
+
execFileSync('tar', ['xzf', tmpTar, '-C', root], { stdio: 'inherit' });
|
|
47
|
+
unlinkSync(tmpTar);
|
|
48
|
+
|
|
49
|
+
// verify the .node file exists
|
|
50
|
+
const nodeFile = join(outDir, 'pdfium.node');
|
|
51
|
+
if (existsSync(nodeFile)) {
|
|
52
|
+
console.log('Prebuilt binary installed successfully.');
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
console.log('Prebuilt archive extracted but pdfium.node not found, will compile from source.');
|
|
57
|
+
return false;
|
|
58
|
+
} catch (err) {
|
|
59
|
+
console.log(`Failed to download prebuilt binary: ${err.message}`);
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function buildFromSource() {
|
|
65
|
+
console.log('Building from source...');
|
|
66
|
+
execSync('node scripts/download-pdfium.mjs', { stdio: 'inherit', cwd: root });
|
|
67
|
+
execSync('npx node-gyp rebuild', { stdio: 'inherit', cwd: root });
|
|
68
|
+
execSync('node scripts/bundle-lib.mjs', { stdio: 'inherit', cwd: root });
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const nodeFile = join(outDir, 'pdfium.node');
|
|
72
|
+
if (existsSync(nodeFile)) {
|
|
73
|
+
console.log('pdfium.node already exists, skipping install.');
|
|
74
|
+
process.exit(0);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const downloaded = await tryDownload();
|
|
78
|
+
if (!downloaded) {
|
|
79
|
+
await buildFromSource();
|
|
80
|
+
}
|
package/src/document.h
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
#pragma once
|
|
2
|
+
|
|
3
|
+
#include "page.h"
|
|
4
|
+
|
|
5
|
+
#include <atomic>
|
|
6
|
+
#include <memory>
|
|
7
|
+
|
|
8
|
+
// ---------------------------------------------------------------------------
|
|
9
|
+
// PDFiumDocument
|
|
10
|
+
// ---------------------------------------------------------------------------
|
|
11
|
+
|
|
12
|
+
class PDFiumDocument : public Napi::ObjectWrap<PDFiumDocument> {
|
|
13
|
+
public:
|
|
14
|
+
static Napi::Function Init(Napi::Env env) {
|
|
15
|
+
return DefineClass(
|
|
16
|
+
env, "PDFiumDocument",
|
|
17
|
+
{
|
|
18
|
+
InstanceMethod<&PDFiumDocument::GetPageAsync>("getPage"),
|
|
19
|
+
InstanceMethod<&PDFiumDocument::GetBookmarks>("getBookmarks"),
|
|
20
|
+
InstanceMethod<&PDFiumDocument::Destroy>("destroy"),
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
PDFiumDocument(const Napi::CallbackInfo &info)
|
|
25
|
+
: Napi::ObjectWrap<PDFiumDocument>(info),
|
|
26
|
+
docAlive_(std::make_shared<std::atomic<bool>>(true)) {}
|
|
27
|
+
|
|
28
|
+
void SetDocument(FPDF_DOCUMENT doc) { doc_ = doc; }
|
|
29
|
+
|
|
30
|
+
// take ownership of buffer data (needed for FPDF_LoadMemDocument)
|
|
31
|
+
void SetOwnedBuffer(std::vector<uint8_t> buf) {
|
|
32
|
+
ownedBuffer_ = std::move(buf);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// register a page's alive flag so we can invalidate it on destroy
|
|
36
|
+
void RegisterPageAlive(std::shared_ptr<std::atomic<bool>> flag) {
|
|
37
|
+
pageAliveFlags_.push_back(std::move(flag));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// returns the document alive flag (shared with pages)
|
|
41
|
+
std::shared_ptr<std::atomic<bool>> GetDocAlive() const { return docAlive_; }
|
|
42
|
+
|
|
43
|
+
// store the page constructor so we can create instances
|
|
44
|
+
static Napi::FunctionReference pageConstructor;
|
|
45
|
+
|
|
46
|
+
private:
|
|
47
|
+
FPDF_DOCUMENT doc_ = nullptr;
|
|
48
|
+
std::vector<uint8_t> ownedBuffer_;
|
|
49
|
+
std::shared_ptr<std::atomic<bool>> docAlive_;
|
|
50
|
+
std::vector<std::shared_ptr<std::atomic<bool>>> pageAliveFlags_;
|
|
51
|
+
|
|
52
|
+
void EnsureOpen(Napi::Env env) {
|
|
53
|
+
if (!doc_) {
|
|
54
|
+
Napi::Error::New(env, "Document is destroyed")
|
|
55
|
+
.ThrowAsJavaScriptException();
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Gets a page by 0-based index (async). Returns a Promise<PDFiumPage>.
|
|
61
|
+
*/
|
|
62
|
+
Napi::Value GetPageAsync(const Napi::CallbackInfo &info);
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Returns the bookmark tree as a nested array.
|
|
66
|
+
*/
|
|
67
|
+
Napi::Value GetBookmarks(const Napi::CallbackInfo &info) {
|
|
68
|
+
Napi::Env env = info.Env();
|
|
69
|
+
EnsureOpen(env);
|
|
70
|
+
if (env.IsExceptionPending())
|
|
71
|
+
return env.Null();
|
|
72
|
+
|
|
73
|
+
std::lock_guard<std::mutex> lock(g_pdfium_mutex);
|
|
74
|
+
return BuildBookmarkArray(env, nullptr, 0);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
Napi::Array BuildBookmarkArray(Napi::Env env, FPDF_BOOKMARK parent,
|
|
78
|
+
int depth) {
|
|
79
|
+
Napi::Array arr = Napi::Array::New(env);
|
|
80
|
+
if (depth >= MAX_BOOKMARK_DEPTH)
|
|
81
|
+
return arr;
|
|
82
|
+
|
|
83
|
+
uint32_t idx = 0;
|
|
84
|
+
FPDF_BOOKMARK child = FPDFBookmark_GetFirstChild(doc_, parent);
|
|
85
|
+
|
|
86
|
+
while (child) {
|
|
87
|
+
Napi::Object obj = Napi::Object::New(env);
|
|
88
|
+
|
|
89
|
+
// title
|
|
90
|
+
unsigned long titleLen = FPDFBookmark_GetTitle(child, nullptr, 0);
|
|
91
|
+
if (titleLen > 2) {
|
|
92
|
+
std::vector<unsigned short> titleBuf(titleLen / sizeof(unsigned short));
|
|
93
|
+
FPDFBookmark_GetTitle(child, titleBuf.data(), titleLen);
|
|
94
|
+
size_t charCount = titleLen / sizeof(unsigned short) - 1;
|
|
95
|
+
obj.Set("title",
|
|
96
|
+
Napi::String::New(
|
|
97
|
+
env, reinterpret_cast<const char16_t *>(titleBuf.data()),
|
|
98
|
+
charCount));
|
|
99
|
+
} else {
|
|
100
|
+
obj.Set("title", Napi::String::New(env, ""));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// destination page index
|
|
104
|
+
FPDF_DEST dest = FPDFBookmark_GetDest(doc_, child);
|
|
105
|
+
if (dest) {
|
|
106
|
+
int pageIndex = FPDFDest_GetDestPageIndex(doc_, dest);
|
|
107
|
+
obj.Set("pageIndex", Napi::Number::New(env, pageIndex));
|
|
108
|
+
} else {
|
|
109
|
+
// try action → dest
|
|
110
|
+
FPDF_ACTION action = FPDFBookmark_GetAction(child);
|
|
111
|
+
if (action) {
|
|
112
|
+
FPDF_DEST actionDest = FPDFAction_GetDest(doc_, action);
|
|
113
|
+
if (actionDest) {
|
|
114
|
+
int pageIndex = FPDFDest_GetDestPageIndex(doc_, actionDest);
|
|
115
|
+
obj.Set("pageIndex", Napi::Number::New(env, pageIndex));
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// children (recursive)
|
|
121
|
+
Napi::Array children = BuildBookmarkArray(env, child, depth + 1);
|
|
122
|
+
if (children.Length() > 0) {
|
|
123
|
+
obj.Set("children", children);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
arr.Set(idx++, obj);
|
|
127
|
+
child = FPDFBookmark_GetNextSibling(doc_, child);
|
|
128
|
+
}
|
|
129
|
+
return arr;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Closes the document and releases all resources.
|
|
134
|
+
*/
|
|
135
|
+
Napi::Value Destroy(const Napi::CallbackInfo &info) {
|
|
136
|
+
if (doc_) {
|
|
137
|
+
// invalidate all pages first so they can't use dangling pointers
|
|
138
|
+
for (auto &flag : pageAliveFlags_) {
|
|
139
|
+
flag->store(false);
|
|
140
|
+
}
|
|
141
|
+
pageAliveFlags_.clear();
|
|
142
|
+
docAlive_->store(false);
|
|
143
|
+
|
|
144
|
+
std::lock_guard<std::mutex> lock(g_pdfium_mutex);
|
|
145
|
+
FPDF_CloseDocument(doc_);
|
|
146
|
+
doc_ = nullptr;
|
|
147
|
+
}
|
|
148
|
+
return info.Env().Undefined();
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
// ---------------------------------------------------------------------------
|
|
153
|
+
// GetPageWorker — async page loading
|
|
154
|
+
// ---------------------------------------------------------------------------
|
|
155
|
+
|
|
156
|
+
class GetPageWorker : public Napi::AsyncWorker {
|
|
157
|
+
public:
|
|
158
|
+
GetPageWorker(Napi::Env env, FPDF_DOCUMENT doc, int pageIndex,
|
|
159
|
+
PDFiumDocument *docWrapper,
|
|
160
|
+
std::shared_ptr<std::atomic<bool>> docAlive)
|
|
161
|
+
: Napi::AsyncWorker(env), deferred_(Napi::Promise::Deferred::New(env)),
|
|
162
|
+
doc_(doc), pageIndex_(pageIndex), docWrapper_(docWrapper),
|
|
163
|
+
docAlive_(std::move(docAlive)) {}
|
|
164
|
+
|
|
165
|
+
Napi::Promise Promise() { return deferred_.Promise(); }
|
|
166
|
+
|
|
167
|
+
protected:
|
|
168
|
+
void Execute() override {
|
|
169
|
+
std::lock_guard<std::mutex> lock(g_pdfium_mutex);
|
|
170
|
+
|
|
171
|
+
// check that the document hasn't been destroyed while we were queued
|
|
172
|
+
if (!docAlive_ || !docAlive_->load()) {
|
|
173
|
+
SetError("Document was destroyed before page load completed");
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
page_ = FPDF_LoadPage(doc_, pageIndex_);
|
|
178
|
+
if (!page_) {
|
|
179
|
+
SetError("Failed to load page");
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
width_ = FPDF_GetPageWidthF(page_);
|
|
183
|
+
height_ = FPDF_GetPageHeightF(page_);
|
|
184
|
+
objectCount_ = FPDFPage_CountObjects(page_);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
void OnOK() override {
|
|
188
|
+
Napi::Env env = Env();
|
|
189
|
+
Napi::Object pageObj = PDFiumDocument::pageConstructor.New({});
|
|
190
|
+
PDFiumPage *pageWrapper = PDFiumPage::Unwrap(pageObj);
|
|
191
|
+
pageWrapper->SetPage(page_, doc_, pageIndex_);
|
|
192
|
+
pageWrapper->SetDocAlive(docAlive_);
|
|
193
|
+
|
|
194
|
+
// register the page's alive flag with the document for invalidation
|
|
195
|
+
docWrapper_->RegisterPageAlive(pageWrapper->GetAliveFlag());
|
|
196
|
+
|
|
197
|
+
// set dimensions as plain JS properties (no native roundtrip on access)
|
|
198
|
+
pageObj.Set("width", Napi::Number::New(env, width_));
|
|
199
|
+
pageObj.Set("height", Napi::Number::New(env, height_));
|
|
200
|
+
Napi::Object sizeObj = Napi::Object::New(env);
|
|
201
|
+
sizeObj.Set("width", Napi::Number::New(env, width_));
|
|
202
|
+
sizeObj.Set("height", Napi::Number::New(env, height_));
|
|
203
|
+
pageObj.Set("size", sizeObj);
|
|
204
|
+
pageObj.Set("objectCount", Napi::Number::New(env, objectCount_));
|
|
205
|
+
|
|
206
|
+
deferred_.Resolve(pageObj);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
void OnError(const Napi::Error &err) override {
|
|
210
|
+
deferred_.Reject(err.Value());
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
private:
|
|
214
|
+
Napi::Promise::Deferred deferred_;
|
|
215
|
+
FPDF_DOCUMENT doc_;
|
|
216
|
+
int pageIndex_;
|
|
217
|
+
PDFiumDocument *docWrapper_;
|
|
218
|
+
std::shared_ptr<std::atomic<bool>> docAlive_;
|
|
219
|
+
FPDF_PAGE page_ = nullptr;
|
|
220
|
+
float width_ = 0;
|
|
221
|
+
float height_ = 0;
|
|
222
|
+
int objectCount_ = 0;
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
// deferred definition of GetPageAsync (needs GetPageWorker)
|
|
226
|
+
inline Napi::Value
|
|
227
|
+
PDFiumDocument::GetPageAsync(const Napi::CallbackInfo &info) {
|
|
228
|
+
Napi::Env env = info.Env();
|
|
229
|
+
EnsureOpen(env);
|
|
230
|
+
if (env.IsExceptionPending())
|
|
231
|
+
return env.Null();
|
|
232
|
+
|
|
233
|
+
if (info.Length() < 1 || !info[0].IsNumber()) {
|
|
234
|
+
Napi::TypeError::New(env, "Expected page index")
|
|
235
|
+
.ThrowAsJavaScriptException();
|
|
236
|
+
return env.Null();
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
int pageIndex = info[0].As<Napi::Number>().Int32Value();
|
|
240
|
+
|
|
241
|
+
// FPDF_GetPageCount is not thread-safe — acquire mutex
|
|
242
|
+
std::lock_guard<std::mutex> lock(g_pdfium_mutex);
|
|
243
|
+
int numPages = FPDF_GetPageCount(doc_);
|
|
244
|
+
if (pageIndex < 0 || pageIndex >= numPages) {
|
|
245
|
+
Napi::RangeError::New(env, "Page index out of range")
|
|
246
|
+
.ThrowAsJavaScriptException();
|
|
247
|
+
return env.Null();
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
auto *worker = new GetPageWorker(env, doc_, pageIndex, this, docAlive_);
|
|
251
|
+
auto promise = worker->Promise();
|
|
252
|
+
worker->Queue();
|
|
253
|
+
return promise;
|
|
254
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
#pragma once
|
|
2
|
+
|
|
3
|
+
#include <mutex>
|
|
4
|
+
#include <napi.h>
|
|
5
|
+
|
|
6
|
+
#include "fpdfview.h"
|
|
7
|
+
|
|
8
|
+
inline bool g_initialized = false;
|
|
9
|
+
|
|
10
|
+
// PDFium is not thread-safe — serialize all calls through a global mutex.
|
|
11
|
+
// This unblocks the Node.js event loop while waiting for the lock.
|
|
12
|
+
inline std::mutex g_pdfium_mutex;
|
|
13
|
+
|
|
14
|
+
// image format constants
|
|
15
|
+
enum ImageFormat { IMAGE_FORMAT_JPEG = 0, IMAGE_FORMAT_PNG = 1 };
|
|
16
|
+
|
|
17
|
+
// maximum render dimension to prevent OOM (16384 × 16384 × 4 ≈ 1 GB)
|
|
18
|
+
constexpr int MAX_RENDER_DIMENSION = 16384;
|
|
19
|
+
|
|
20
|
+
// maximum bookmark tree recursion depth
|
|
21
|
+
constexpr int MAX_BOOKMARK_DEPTH = 64;
|
|
22
|
+
|
|
23
|
+
// helper: create a { left, bottom, right, top } bounds object
|
|
24
|
+
inline Napi::Object CreateBoundsObject(Napi::Env env, double left,
|
|
25
|
+
double bottom, double right,
|
|
26
|
+
double top) {
|
|
27
|
+
Napi::Object obj = Napi::Object::New(env);
|
|
28
|
+
obj.Set("left", Napi::Number::New(env, left));
|
|
29
|
+
obj.Set("bottom", Napi::Number::New(env, bottom));
|
|
30
|
+
obj.Set("right", Napi::Number::New(env, right));
|
|
31
|
+
obj.Set("top", Napi::Number::New(env, top));
|
|
32
|
+
return obj;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// helper: create bounds from an FS_RECTF struct
|
|
36
|
+
inline Napi::Object CreateBoundsFromRect(Napi::Env env, const FS_RECTF &rect) {
|
|
37
|
+
return CreateBoundsObject(env, rect.left, rect.bottom, rect.right, rect.top);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// helper: create an { r, g, b, a } color object
|
|
41
|
+
inline Napi::Object CreateColorObject(Napi::Env env, unsigned int r,
|
|
42
|
+
unsigned int g, unsigned int b,
|
|
43
|
+
unsigned int a) {
|
|
44
|
+
Napi::Object obj = Napi::Object::New(env);
|
|
45
|
+
obj.Set("r", Napi::Number::New(env, r));
|
|
46
|
+
obj.Set("g", Napi::Number::New(env, g));
|
|
47
|
+
obj.Set("b", Napi::Number::New(env, b));
|
|
48
|
+
obj.Set("a", Napi::Number::New(env, a));
|
|
49
|
+
return obj;
|
|
50
|
+
}
|