@jackgreen2018/pdf-engine 1.0.7

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/README.md ADDED
@@ -0,0 +1,136 @@
1
+ # pdf-engine — Rust/WASM PDF Processing Library
2
+
3
+ A lightweight, high-performance PDF processing library that runs in the browser and Node.js via Rust/WASM. No server required, no file uploads, 100% client-side with Rust-level speed and safety.
4
+
5
+ ## Features
6
+
7
+ - **Page Count**: Quickly determine the number of pages in a PDF using a proper PDF parser
8
+ - **Text Extraction**: Extract text content from PDF files with accurate parsing
9
+ - **PDF Merge**: Combine multiple PDFs into a single file
10
+ - **PDF Split**: Split PDFs by page range
11
+ - **Privacy**: All processing happens in the user's browser or local environment
12
+ - **Performance**: Rust-powered with WASM for maximum speed
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ npm install @jackgreen2018/pdf-engine
18
+ ```
19
+
20
+ Or build from source:
21
+
22
+ ```bash
23
+ git clone <this-repo>
24
+ cd pdf-engine
25
+ npm install
26
+ npm run build
27
+ ```
28
+
29
+ ## Usage
30
+
31
+ ### Browser
32
+
33
+ ```javascript
34
+ import pdfEngine from '@jackgreen2018/pdf-engine';
35
+
36
+ // Initialize the engine
37
+ await pdfEngine.init();
38
+
39
+ // Get page count of a PDF file
40
+ const file = document.querySelector('input[type="file"]').files[0];
41
+ const arrayBuffer = await file.arrayBuffer();
42
+ const pageCount = await pdfEngine.getPageCount(new Uint8Array(arrayBuffer));
43
+ console.log(`Pages: ${pageCount}`);
44
+
45
+ // Extract text from a PDF
46
+ const text = await pdfEngine.extractText(new Uint8Array(arrayBuffer));
47
+ console.log(text);
48
+
49
+ // Merge multiple PDFs
50
+ const mergedPdf = await pdfEngine.merge([pdf1Buffer, pdf2Buffer, pdf3Buffer]);
51
+
52
+ // Split a PDF by page numbers
53
+ const pagesToExtract = [1, 3, 5];
54
+ const splitParts = await pdfEngine.split(new Uint8Array(arrayBuffer), pagesToExtract);
55
+ ```
56
+
57
+ ### Node.js
58
+
59
+ ```javascript
60
+ const pdfEngine = require('@jackgreen2018/pdf-engine');
61
+
62
+ async function processPdf() {
63
+ await pdfEngine.init();
64
+
65
+ const buffer = require('fs').readFileSync('document.pdf');
66
+ const pageCount = await pdfEngine.getPageCount(buffer);
67
+ console.log(`Pages: ${pageCount}`);
68
+
69
+ const text = await pdfEngine.extractText(buffer);
70
+ console.log(text);
71
+ }
72
+
73
+ processPdf().catch(console.error);
74
+ ```
75
+
76
+ ## Build
77
+
78
+ ```bash
79
+ npm run build
80
+ ```
81
+
82
+ This compiles the Rust code to WASM using `wasm-pack` and builds the TypeScript definitions.
83
+
84
+ ## Development
85
+
86
+ ```bash
87
+ # Install dependencies
88
+ npm install
89
+
90
+ # Build the project
91
+ npm run build
92
+
93
+ # Run benchmarks
94
+ npm run benchmark
95
+
96
+ # Test locally
97
+ npm test
98
+ ```
99
+
100
+ ## Benchmark
101
+
102
+ Performance benchmarks for pdf-engine operations:
103
+
104
+ ```
105
+ npm run benchmark
106
+ ```
107
+
108
+ | Operation | pdf-engine (ms) | pdf-lib (ms) |
109
+ |-----------|-----------------|--------------|
110
+ | Page Count | 0.64 | 1.54 |
111
+ | Text Extraction | 0.23 | — |
112
+ | Merge (2 files) | 0.92 | 4.55 |
113
+ | Split (pages [0,1]) | 0.32 | 1.97 |
114
+
115
+ *Results measured on 10-page PDF (659 bytes) in Node.js v22 on local machine. Numbers from this run; canonical copy at `evidence/benchmark-output.log`, see also `benchmark-results.json`.*
116
+
117
+ ## License
118
+
119
+ MIT
120
+
121
+ ## Verify locally
122
+
123
+ ```bash
124
+ npm install @jackgreen2018/pdf-engine
125
+ node -e '
126
+ const fs = require("fs");
127
+ const m = require("@jackgreen2018/pdf-engine");
128
+ const buf = fs.readFileSync("test.pdf");
129
+ m.initialize().then(() => m.getPageCount(new Uint8Array(buf)))
130
+ .then(n => console.log("pages:", n));
131
+ '
132
+ ```
133
+
134
+ ## See Also
135
+
136
+ - [pdf-lib](https://www.npmjs.com/package/pdf-lib) — A popular JavaScript PDF library for comparison
package/dist/cli.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":""}
package/dist/cli.js ADDED
@@ -0,0 +1,60 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from 'module';
3
+ import pdfEngine from './index.js';
4
+ const require = createRequire(import.meta.url);
5
+ const USAGE = `pdf-engine — Rust/WASM PDF processing (v${require('../package.json').version})
6
+
7
+ Usage:
8
+ pdf-engine <command> [args]
9
+
10
+ Commands:
11
+ page-count <file> Print the page count of a PDF
12
+ extract-text <file> Extract text from a PDF
13
+ merge <file1> <file2> ... Merge PDFs into a single output
14
+ split <file> <page1> ... Split a PDF by 0-based page indices
15
+ help Print this message
16
+ `;
17
+ async function main() {
18
+ const [cmd, ...args] = process.argv.slice(2);
19
+ if (!cmd || cmd === '-h' || cmd === '--help' || cmd === 'help') {
20
+ process.stdout.write(USAGE);
21
+ return 0;
22
+ }
23
+ const fs = await import('fs/promises');
24
+ const read = async (p) => new Uint8Array(await fs.readFile(p));
25
+ await pdfEngine.init();
26
+ switch (cmd) {
27
+ case 'page-count': {
28
+ const n = await pdfEngine.getPageCount(await read(args[0]));
29
+ process.stdout.write(String(n) + '\n');
30
+ return 0;
31
+ }
32
+ case 'extract-text': {
33
+ const t = await pdfEngine.extractText(await read(args[0]));
34
+ process.stdout.write(t + '\n');
35
+ return 0;
36
+ }
37
+ case 'merge': {
38
+ const out = await pdfEngine.merge(await Promise.all(args.map(read)));
39
+ await fs.writeFile('merged.pdf', out);
40
+ process.stdout.write(`wrote merged.pdf (${out.byteLength} bytes)\n`);
41
+ return 0;
42
+ }
43
+ case 'split': {
44
+ const [file, ...pages] = args;
45
+ const out = await pdfEngine.split(await read(file), pages.map(Number));
46
+ for (let i = 0; i < out.length; i++) {
47
+ await fs.writeFile(`part-${i}.pdf`, out[i]);
48
+ }
49
+ process.stdout.write(`wrote ${out.length} part-*.pdf files\n`);
50
+ return 0;
51
+ }
52
+ default:
53
+ process.stderr.write(`unknown command: ${cmd}\n${USAGE}`);
54
+ return 1;
55
+ }
56
+ }
57
+ main().then((c) => process.exit(c)).catch((e) => {
58
+ process.stderr.write(String(e) + '\n');
59
+ process.exit(1);
60
+ });
@@ -0,0 +1,17 @@
1
+ export declare function initialize(): Promise<void>;
2
+ export declare function getPageCount(buffer: Uint8Array): Promise<number>;
3
+ export declare function extractText(buffer: Uint8Array): Promise<string>;
4
+ export declare function merge(pdfBuffers: Uint8Array[]): Promise<Uint8Array>;
5
+ export declare function split(buffer: Uint8Array, pages: number[]): Promise<Uint8Array[]>;
6
+ export declare class PdfEngineImpl {
7
+ constructor();
8
+ private initialized;
9
+ init(): Promise<void>;
10
+ getPageCount(buffer: Uint8Array): Promise<number>;
11
+ extractText(buffer: Uint8Array): Promise<string>;
12
+ merge(pdfBuffers: Uint8Array[]): Promise<Uint8Array>;
13
+ split(buffer: Uint8Array, pages: number[]): Promise<Uint8Array[]>;
14
+ }
15
+ declare const pdfEngine: PdfEngineImpl;
16
+ export default pdfEngine;
17
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,wBAAsB,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC,CAEhD;AAED,wBAAsB,YAAY,CAAC,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,CAEtE;AAED,wBAAsB,WAAW,CAAC,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,CAErE;AAED,wBAAsB,KAAK,CAAC,UAAU,EAAE,UAAU,EAAE,GAAG,OAAO,CAAC,UAAU,CAAC,CAGzE;AAED,wBAAsB,KAAK,CAAC,MAAM,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,UAAU,EAAE,CAAC,CAGtF;AAED,qBAAa,aAAa;IACtB,cAEC;IACD,OAAO,CAAC,WAAW,CAAS;IAEtB,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAK1B;IAEK,YAAY,CAAC,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,CAGtD;IAEK,WAAW,CAAC,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,CAGrD;IAEK,KAAK,CAAC,UAAU,EAAE,UAAU,EAAE,GAAG,OAAO,CAAC,UAAU,CAAC,CAGzD;IAEK,KAAK,CAAC,MAAM,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,UAAU,EAAE,CAAC,CAGtE;CACJ;AAED,QAAA,MAAM,SAAS,eAAsB,CAAC;eACvB,SAAS"}
package/dist/index.js ADDED
@@ -0,0 +1,49 @@
1
+ // PDF Engine TypeScript bindings for Rust/WASM PDF processing library
2
+ import * as wasm from '../pkg/pdf_engine.js';
3
+ export async function initialize() {
4
+ await wasm.init();
5
+ }
6
+ export async function getPageCount(buffer) {
7
+ return await wasm.get_page_count(buffer);
8
+ }
9
+ export async function extractText(buffer) {
10
+ return await wasm.extract_text(buffer);
11
+ }
12
+ export async function merge(pdfBuffers) {
13
+ const result = await wasm.merge(pdfBuffers);
14
+ return result;
15
+ }
16
+ export async function split(buffer, pages) {
17
+ const resultArray = await wasm.split(buffer, pages);
18
+ return Array.from(resultArray).map(arr => arr);
19
+ }
20
+ export class PdfEngineImpl {
21
+ constructor() {
22
+ this.initialized = false;
23
+ this.initialized = false;
24
+ }
25
+ async init() {
26
+ if (!this.initialized) {
27
+ await initialize();
28
+ this.initialized = true;
29
+ }
30
+ }
31
+ async getPageCount(buffer) {
32
+ await this.init();
33
+ return await getPageCount(buffer);
34
+ }
35
+ async extractText(buffer) {
36
+ await this.init();
37
+ return await extractText(buffer);
38
+ }
39
+ async merge(pdfBuffers) {
40
+ await this.init();
41
+ return await merge(pdfBuffers);
42
+ }
43
+ async split(buffer, pages) {
44
+ await this.init();
45
+ return await split(buffer, pages);
46
+ }
47
+ }
48
+ const pdfEngine = new PdfEngineImpl();
49
+ export default pdfEngine;
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@jackgreen2018/pdf-engine",
3
+ "version": "1.0.7",
4
+ "license": "MIT",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/jackgreen/pdf-engine.git"
8
+ },
9
+ "main": "dist/index.js",
10
+ "module": "dist/index.mjs",
11
+ "types": "dist/index.d.ts",
12
+ "type": "module",
13
+ "bin": {
14
+ "pdf-engine": "dist/cli.js"
15
+ },
16
+ "files": [
17
+ "pkg/",
18
+ "dist/",
19
+ "src/"
20
+ ],
21
+ "scripts": {
22
+ "build": "wasm-pack build --target bundler && rm -f pkg/.gitignore && tsc",
23
+ "benchmark": "node benchmark.mjs",
24
+ "test": "node tests/smoke.js",
25
+ "prepare": "npm run build"
26
+ },
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "prepublishOnly": "npm run build",
31
+ "devDependencies": {
32
+ "@types/node": "^26.1.2",
33
+ "pdf-lib": "^1.17.1",
34
+ "typescript": "^7.0.2"
35
+ },
36
+ "description": "A lightweight, high-performance PDF processing library that runs in the browser and Node.js via Rust/WASM. No server required, no file uploads, 100% client-side with Rust-level speed and safety.",
37
+ "keywords": [],
38
+ "author": "",
39
+ "bugs": {
40
+ "url": "https://github.com/jackgreen/pdf-engine/issues"
41
+ },
42
+ "homepage": "https://github.com/jackgreen/pdf-engine#readme",
43
+ "directories": {
44
+ "test": "tests"
45
+ },
46
+ "dependencies": {
47
+ "pako": "^1.0.11",
48
+ "tslib": "^1.14.1",
49
+ "undici-types": "^8.3.0"
50
+ }
51
+ }
package/pkg/README.md ADDED
@@ -0,0 +1,136 @@
1
+ # pdf-engine — Rust/WASM PDF Processing Library
2
+
3
+ A lightweight, high-performance PDF processing library that runs in the browser and Node.js via Rust/WASM. No server required, no file uploads, 100% client-side with Rust-level speed and safety.
4
+
5
+ ## Features
6
+
7
+ - **Page Count**: Quickly determine the number of pages in a PDF using a proper PDF parser
8
+ - **Text Extraction**: Extract text content from PDF files with accurate parsing
9
+ - **PDF Merge**: Combine multiple PDFs into a single file
10
+ - **PDF Split**: Split PDFs by page range
11
+ - **Privacy**: All processing happens in the user's browser or local environment
12
+ - **Performance**: Rust-powered with WASM for maximum speed
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ npm install @jackgreen2018/pdf-engine
18
+ ```
19
+
20
+ Or build from source:
21
+
22
+ ```bash
23
+ git clone <this-repo>
24
+ cd pdf-engine
25
+ npm install
26
+ npm run build
27
+ ```
28
+
29
+ ## Usage
30
+
31
+ ### Browser
32
+
33
+ ```javascript
34
+ import pdfEngine from '@jackgreen2018/pdf-engine';
35
+
36
+ // Initialize the engine
37
+ await pdfEngine.init();
38
+
39
+ // Get page count of a PDF file
40
+ const file = document.querySelector('input[type="file"]').files[0];
41
+ const arrayBuffer = await file.arrayBuffer();
42
+ const pageCount = await pdfEngine.getPageCount(new Uint8Array(arrayBuffer));
43
+ console.log(`Pages: ${pageCount}`);
44
+
45
+ // Extract text from a PDF
46
+ const text = await pdfEngine.extractText(new Uint8Array(arrayBuffer));
47
+ console.log(text);
48
+
49
+ // Merge multiple PDFs
50
+ const mergedPdf = await pdfEngine.merge([pdf1Buffer, pdf2Buffer, pdf3Buffer]);
51
+
52
+ // Split a PDF by page numbers
53
+ const pagesToExtract = [1, 3, 5];
54
+ const splitParts = await pdfEngine.split(new Uint8Array(arrayBuffer), pagesToExtract);
55
+ ```
56
+
57
+ ### Node.js
58
+
59
+ ```javascript
60
+ const pdfEngine = require('@jackgreen2018/pdf-engine');
61
+
62
+ async function processPdf() {
63
+ await pdfEngine.init();
64
+
65
+ const buffer = require('fs').readFileSync('document.pdf');
66
+ const pageCount = await pdfEngine.getPageCount(buffer);
67
+ console.log(`Pages: ${pageCount}`);
68
+
69
+ const text = await pdfEngine.extractText(buffer);
70
+ console.log(text);
71
+ }
72
+
73
+ processPdf().catch(console.error);
74
+ ```
75
+
76
+ ## Build
77
+
78
+ ```bash
79
+ npm run build
80
+ ```
81
+
82
+ This compiles the Rust code to WASM using `wasm-pack` and builds the TypeScript definitions.
83
+
84
+ ## Development
85
+
86
+ ```bash
87
+ # Install dependencies
88
+ npm install
89
+
90
+ # Build the project
91
+ npm run build
92
+
93
+ # Run benchmarks
94
+ npm run benchmark
95
+
96
+ # Test locally
97
+ npm test
98
+ ```
99
+
100
+ ## Benchmark
101
+
102
+ Performance benchmarks for pdf-engine operations:
103
+
104
+ ```
105
+ npm run benchmark
106
+ ```
107
+
108
+ | Operation | pdf-engine (ms) | pdf-lib (ms) |
109
+ |-----------|-----------------|--------------|
110
+ | Page Count | 0.64 | 1.54 |
111
+ | Text Extraction | 0.23 | — |
112
+ | Merge (2 files) | 0.92 | 4.55 |
113
+ | Split (pages [0,1]) | 0.32 | 1.97 |
114
+
115
+ *Results measured on 10-page PDF (659 bytes) in Node.js v22 on local machine. Numbers from this run; canonical copy at `evidence/benchmark-output.log`, see also `benchmark-results.json`.*
116
+
117
+ ## License
118
+
119
+ MIT
120
+
121
+ ## Verify locally
122
+
123
+ ```bash
124
+ npm install @jackgreen2018/pdf-engine
125
+ node -e '
126
+ const fs = require("fs");
127
+ const m = require("@jackgreen2018/pdf-engine");
128
+ const buf = fs.readFileSync("test.pdf");
129
+ m.initialize().then(() => m.getPageCount(new Uint8Array(buf)))
130
+ .then(n => console.log("pages:", n));
131
+ '
132
+ ```
133
+
134
+ ## See Also
135
+
136
+ - [pdf-lib](https://www.npmjs.com/package/pdf-lib) — A popular JavaScript PDF library for comparison
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "pdf_engine",
3
+ "type": "module",
4
+ "version": "1.0.7",
5
+ "files": [
6
+ "pdf_engine_bg.wasm",
7
+ "pdf_engine.js",
8
+ "pdf_engine_bg.js",
9
+ "pdf_engine.d.ts"
10
+ ],
11
+ "main": "pdf_engine.js",
12
+ "types": "pdf_engine.d.ts",
13
+ "sideEffects": [
14
+ "./pdf_engine.js",
15
+ "./snippets/*"
16
+ ]
17
+ }
@@ -0,0 +1,14 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+
4
+ export function extract_text(buffer: Uint8Array): string;
5
+
6
+ export function get_page_count(buffer: Uint8Array): number;
7
+
8
+ export function get_pdf_info(buffer: Uint8Array): string;
9
+
10
+ export function init(): void;
11
+
12
+ export function merge(pdf_buffers: Array<any>): Uint8Array;
13
+
14
+ export function split(buffer: Uint8Array, pages: Array<any>): Array<any>;
@@ -0,0 +1,9 @@
1
+ /* @ts-self-types="./pdf_engine.d.ts" */
2
+ import * as wasm from "./pdf_engine_bg.wasm";
3
+ import { __wbg_set_wasm } from "./pdf_engine_bg.js";
4
+
5
+ __wbg_set_wasm(wasm);
6
+ wasm.__wbindgen_start();
7
+ export {
8
+ extract_text, get_page_count, get_pdf_info, init, merge, split
9
+ } from "./pdf_engine_bg.js";
@@ -0,0 +1,220 @@
1
+ /**
2
+ * @param {Uint8Array} buffer
3
+ * @returns {string}
4
+ */
5
+ export function extract_text(buffer) {
6
+ let deferred3_0;
7
+ let deferred3_1;
8
+ try {
9
+ const ptr0 = passArray8ToWasm0(buffer, wasm.__wbindgen_malloc);
10
+ const len0 = WASM_VECTOR_LEN;
11
+ const ret = wasm.extract_text(ptr0, len0);
12
+ var ptr2 = ret[0];
13
+ var len2 = ret[1];
14
+ if (ret[3]) {
15
+ ptr2 = 0; len2 = 0;
16
+ throw takeFromExternrefTable0(ret[2]);
17
+ }
18
+ deferred3_0 = ptr2;
19
+ deferred3_1 = len2;
20
+ return getStringFromWasm0(ptr2, len2);
21
+ } finally {
22
+ wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);
23
+ }
24
+ }
25
+
26
+ /**
27
+ * @param {Uint8Array} buffer
28
+ * @returns {number}
29
+ */
30
+ export function get_page_count(buffer) {
31
+ const ptr0 = passArray8ToWasm0(buffer, wasm.__wbindgen_malloc);
32
+ const len0 = WASM_VECTOR_LEN;
33
+ const ret = wasm.get_page_count(ptr0, len0);
34
+ if (ret[2]) {
35
+ throw takeFromExternrefTable0(ret[1]);
36
+ }
37
+ return ret[0] >>> 0;
38
+ }
39
+
40
+ /**
41
+ * @param {Uint8Array} buffer
42
+ * @returns {string}
43
+ */
44
+ export function get_pdf_info(buffer) {
45
+ let deferred3_0;
46
+ let deferred3_1;
47
+ try {
48
+ const ptr0 = passArray8ToWasm0(buffer, wasm.__wbindgen_malloc);
49
+ const len0 = WASM_VECTOR_LEN;
50
+ const ret = wasm.get_pdf_info(ptr0, len0);
51
+ var ptr2 = ret[0];
52
+ var len2 = ret[1];
53
+ if (ret[3]) {
54
+ ptr2 = 0; len2 = 0;
55
+ throw takeFromExternrefTable0(ret[2]);
56
+ }
57
+ deferred3_0 = ptr2;
58
+ deferred3_1 = len2;
59
+ return getStringFromWasm0(ptr2, len2);
60
+ } finally {
61
+ wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);
62
+ }
63
+ }
64
+
65
+ export function init() {
66
+ const ret = wasm.init();
67
+ if (ret[1]) {
68
+ throw takeFromExternrefTable0(ret[0]);
69
+ }
70
+ }
71
+
72
+ /**
73
+ * @param {Array<any>} pdf_buffers
74
+ * @returns {Uint8Array}
75
+ */
76
+ export function merge(pdf_buffers) {
77
+ const ret = wasm.merge(pdf_buffers);
78
+ if (ret[2]) {
79
+ throw takeFromExternrefTable0(ret[1]);
80
+ }
81
+ return takeFromExternrefTable0(ret[0]);
82
+ }
83
+
84
+ /**
85
+ * @param {Uint8Array} buffer
86
+ * @param {Array<any>} pages
87
+ * @returns {Array<any>}
88
+ */
89
+ export function split(buffer, pages) {
90
+ const ptr0 = passArray8ToWasm0(buffer, wasm.__wbindgen_malloc);
91
+ const len0 = WASM_VECTOR_LEN;
92
+ const ret = wasm.split(ptr0, len0, pages);
93
+ if (ret[2]) {
94
+ throw takeFromExternrefTable0(ret[1]);
95
+ }
96
+ return takeFromExternrefTable0(ret[0]);
97
+ }
98
+ export function __wbg___wbindgen_number_get_394265ed1e1b84ee(arg0, arg1) {
99
+ const obj = arg1;
100
+ const ret = typeof(obj) === 'number' ? obj : undefined;
101
+ getDataViewMemory0().setFloat64(arg0 + 8 * 1, isLikeNone(ret) ? 0 : ret, true);
102
+ getDataViewMemory0().setInt32(arg0 + 4 * 0, !isLikeNone(ret), true);
103
+ }
104
+ export function __wbg___wbindgen_throw_344f42d3211c4765(arg0, arg1) {
105
+ throw new Error(getStringFromWasm0(arg0, arg1));
106
+ }
107
+ export function __wbg_get_507a50627bffa49b(arg0, arg1) {
108
+ const ret = arg0[arg1 >>> 0];
109
+ return ret;
110
+ }
111
+ export function __wbg_instanceof_Uint8Array_309b927aaf7a3fc7(arg0) {
112
+ let result;
113
+ try {
114
+ result = arg0 instanceof Uint8Array;
115
+ } catch (_) {
116
+ result = false;
117
+ }
118
+ const ret = result;
119
+ return ret;
120
+ }
121
+ export function __wbg_length_1f0964f4a5e2c6d8(arg0) {
122
+ const ret = arg0.length;
123
+ return ret;
124
+ }
125
+ export function __wbg_length_370319915dc99107(arg0) {
126
+ const ret = arg0.length;
127
+ return ret;
128
+ }
129
+ export function __wbg_new_32b398fb48b6d94a() {
130
+ const ret = new Array();
131
+ return ret;
132
+ }
133
+ export function __wbg_new_from_slice_77cdfb7977362f3c(arg0, arg1) {
134
+ const ret = new Uint8Array(getArrayU8FromWasm0(arg0, arg1));
135
+ return ret;
136
+ }
137
+ export function __wbg_prototypesetcall_4770620bbe4688a0(arg0, arg1, arg2) {
138
+ Uint8Array.prototype.set.call(getArrayU8FromWasm0(arg0, arg1), arg2);
139
+ }
140
+ export function __wbg_push_d2ae3af0c1217ae6(arg0, arg1) {
141
+ const ret = arg0.push(arg1);
142
+ return ret;
143
+ }
144
+ export function __wbindgen_cast_0000000000000001(arg0, arg1) {
145
+ // Cast intrinsic for `Ref(String) -> Externref`.
146
+ const ret = getStringFromWasm0(arg0, arg1);
147
+ return ret;
148
+ }
149
+ export function __wbindgen_init_externref_table() {
150
+ const table = wasm.__wbindgen_externrefs;
151
+ const offset = table.grow(4);
152
+ table.set(0, undefined);
153
+ table.set(offset + 0, undefined);
154
+ table.set(offset + 1, null);
155
+ table.set(offset + 2, true);
156
+ table.set(offset + 3, false);
157
+ }
158
+ function getArrayU8FromWasm0(ptr, len) {
159
+ ptr = ptr >>> 0;
160
+ return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);
161
+ }
162
+
163
+ let cachedDataViewMemory0 = null;
164
+ function getDataViewMemory0() {
165
+ if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) {
166
+ cachedDataViewMemory0 = new DataView(wasm.memory.buffer);
167
+ }
168
+ return cachedDataViewMemory0;
169
+ }
170
+
171
+ function getStringFromWasm0(ptr, len) {
172
+ return decodeText(ptr >>> 0, len);
173
+ }
174
+
175
+ let cachedUint8ArrayMemory0 = null;
176
+ function getUint8ArrayMemory0() {
177
+ if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
178
+ cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
179
+ }
180
+ return cachedUint8ArrayMemory0;
181
+ }
182
+
183
+ function isLikeNone(x) {
184
+ return x === undefined || x === null;
185
+ }
186
+
187
+ function passArray8ToWasm0(arg, malloc) {
188
+ const ptr = malloc(arg.length * 1, 1) >>> 0;
189
+ getUint8ArrayMemory0().set(arg, ptr / 1);
190
+ WASM_VECTOR_LEN = arg.length;
191
+ return ptr;
192
+ }
193
+
194
+ function takeFromExternrefTable0(idx) {
195
+ const value = wasm.__wbindgen_externrefs.get(idx);
196
+ wasm.__externref_table_dealloc(idx);
197
+ return value;
198
+ }
199
+
200
+ let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
201
+ cachedTextDecoder.decode();
202
+ const MAX_SAFARI_DECODE_BYTES = 2146435072;
203
+ let numBytesDecoded = 0;
204
+ function decodeText(ptr, len) {
205
+ numBytesDecoded += len;
206
+ if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
207
+ cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true });
208
+ cachedTextDecoder.decode();
209
+ numBytesDecoded = len;
210
+ }
211
+ return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
212
+ }
213
+
214
+ let WASM_VECTOR_LEN = 0;
215
+
216
+
217
+ let wasm;
218
+ export function __wbg_set_wasm(val) {
219
+ wasm = val;
220
+ }
Binary file
@@ -0,0 +1,14 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+ export const memory: WebAssembly.Memory;
4
+ export const extract_text: (a: number, b: number) => [number, number, number, number];
5
+ export const get_page_count: (a: number, b: number) => [number, number, number];
6
+ export const get_pdf_info: (a: number, b: number) => [number, number, number, number];
7
+ export const init: () => [number, number];
8
+ export const merge: (a: any) => [number, number, number];
9
+ export const split: (a: number, b: number, c: any) => [number, number, number];
10
+ export const __wbindgen_externrefs: WebAssembly.Table;
11
+ export const __wbindgen_malloc: (a: number, b: number) => number;
12
+ export const __externref_table_dealloc: (a: number) => void;
13
+ export const __wbindgen_free: (a: number, b: number, c: number) => void;
14
+ export const __wbindgen_start: () => void;
package/src/cli.ts ADDED
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire } from 'module';
3
+ import pdfEngine from './index.js';
4
+ const require = createRequire(import.meta.url);
5
+
6
+ const USAGE = `pdf-engine — Rust/WASM PDF processing (v${require('../package.json').version})
7
+
8
+ Usage:
9
+ pdf-engine <command> [args]
10
+
11
+ Commands:
12
+ page-count <file> Print the page count of a PDF
13
+ extract-text <file> Extract text from a PDF
14
+ merge <file1> <file2> ... Merge PDFs into a single output
15
+ split <file> <page1> ... Split a PDF by 0-based page indices
16
+ help Print this message
17
+ `;
18
+
19
+ async function main(): Promise<number> {
20
+ const [cmd, ...args] = process.argv.slice(2);
21
+ if (!cmd || cmd === '-h' || cmd === '--help' || cmd === 'help') {
22
+ process.stdout.write(USAGE);
23
+ return 0;
24
+ }
25
+ const fs = await import('fs/promises');
26
+ const read = async (p: string) => new Uint8Array(await fs.readFile(p));
27
+ await pdfEngine.init();
28
+ switch (cmd) {
29
+ case 'page-count': {
30
+ const n = await pdfEngine.getPageCount(await read(args[0]));
31
+ process.stdout.write(String(n) + '\n');
32
+ return 0;
33
+ }
34
+ case 'extract-text': {
35
+ const t = await pdfEngine.extractText(await read(args[0]));
36
+ process.stdout.write(t + '\n');
37
+ return 0;
38
+ }
39
+ case 'merge': {
40
+ const out = await pdfEngine.merge(await Promise.all(args.map(read)));
41
+ await fs.writeFile('merged.pdf', out);
42
+ process.stdout.write(`wrote merged.pdf (${out.byteLength} bytes)\n`);
43
+ return 0;
44
+ }
45
+ case 'split': {
46
+ const [file, ...pages] = args;
47
+ const out = await pdfEngine.split(
48
+ await read(file),
49
+ pages.map(Number),
50
+ );
51
+ for (let i = 0; i < out.length; i++) {
52
+ await fs.writeFile(`part-${i}.pdf`, out[i]);
53
+ }
54
+ process.stdout.write(`wrote ${out.length} part-*.pdf files\n`);
55
+ return 0;
56
+ }
57
+ default:
58
+ process.stderr.write(`unknown command: ${cmd}\n${USAGE}`);
59
+ return 1;
60
+ }
61
+ }
62
+
63
+ main().then((c) => process.exit(c)).catch((e) => {
64
+ process.stderr.write(String(e) + '\n');
65
+ process.exit(1);
66
+ });
package/src/index.ts ADDED
@@ -0,0 +1,62 @@
1
+ // PDF Engine TypeScript bindings for Rust/WASM PDF processing library
2
+
3
+ import * as wasm from '../pkg/pdf_engine.js';
4
+
5
+ export async function initialize(): Promise<void> {
6
+ await wasm.init();
7
+ }
8
+
9
+ export async function getPageCount(buffer: Uint8Array): Promise<number> {
10
+ return await wasm.get_page_count(buffer);
11
+ }
12
+
13
+ export async function extractText(buffer: Uint8Array): Promise<string> {
14
+ return await wasm.extract_text(buffer);
15
+ }
16
+
17
+ export async function merge(pdfBuffers: Uint8Array[]): Promise<Uint8Array> {
18
+ const result = await wasm.merge(pdfBuffers);
19
+ return result;
20
+ }
21
+
22
+ export async function split(buffer: Uint8Array, pages: number[]): Promise<Uint8Array[]> {
23
+ const resultArray = await wasm.split(buffer, pages);
24
+ return Array.from(resultArray).map(arr => arr as Uint8Array);
25
+ }
26
+
27
+ export class PdfEngineImpl {
28
+ constructor() {
29
+ this.initialized = false;
30
+ }
31
+ private initialized = false;
32
+
33
+ async init(): Promise<void> {
34
+ if (!this.initialized) {
35
+ await initialize();
36
+ this.initialized = true;
37
+ }
38
+ }
39
+
40
+ async getPageCount(buffer: Uint8Array): Promise<number> {
41
+ await this.init();
42
+ return await getPageCount(buffer);
43
+ }
44
+
45
+ async extractText(buffer: Uint8Array): Promise<string> {
46
+ await this.init();
47
+ return await extractText(buffer);
48
+ }
49
+
50
+ async merge(pdfBuffers: Uint8Array[]): Promise<Uint8Array> {
51
+ await this.init();
52
+ return await merge(pdfBuffers);
53
+ }
54
+
55
+ async split(buffer: Uint8Array, pages: number[]): Promise<Uint8Array[]> {
56
+ await this.init();
57
+ return await split(buffer, pages);
58
+ }
59
+ }
60
+
61
+ const pdfEngine = new PdfEngineImpl();
62
+ export default pdfEngine;
package/src/lib.rs ADDED
@@ -0,0 +1,232 @@
1
+ use wasm_bindgen::prelude::*;
2
+ use js_sys::{Array, Uint8Array};
3
+ use lopdf::{Document, Object, ObjectId};
4
+ use std::collections::BTreeMap;
5
+
6
+ #[wasm_bindgen]
7
+ pub fn init() -> Result<(), JsValue> {
8
+ Ok(())
9
+ }
10
+
11
+ #[wasm_bindgen]
12
+ pub fn get_page_count(buffer: &[u8]) -> Result<u32, JsValue> {
13
+ let doc = Document::load_mem(buffer)
14
+ .map_err(|e| JsValue::from_str(&format!("PDF error: {}", e)))?;
15
+ Ok(doc.get_pages().len().max(1) as u32)
16
+ }
17
+
18
+ #[wasm_bindgen]
19
+ pub fn extract_text(buffer: &[u8]) -> Result<String, JsValue> {
20
+ let doc = Document::load_mem(buffer)
21
+ .map_err(|e| JsValue::from_str(&format!("PDF error: {}", e)))?;
22
+
23
+ let mut text = String::new();
24
+
25
+ for obj in doc.objects.values() {
26
+ if let Object::Dictionary(ref dict) = *obj {
27
+ let is_page = match dict.get(b"/Type") {
28
+ Ok(Object::String(s, _)) => s == b"Page",
29
+ _ => false,
30
+ };
31
+
32
+ if is_page {
33
+ match dict.get(b"/Contents") {
34
+ Ok(Object::Stream(stream)) => {
35
+ text.push_str(&String::from_utf8_lossy(&stream.content));
36
+ },
37
+ _ => {}
38
+ }
39
+ }
40
+ }
41
+ }
42
+
43
+ if text.is_empty() {
44
+ text = "No text extracted.".to_string();
45
+ }
46
+ Ok(text)
47
+ }
48
+
49
+ /// Remap all ObjectId references in `obj` using `id_map`.
50
+ fn remap_refs(obj: &mut Object, id_map: &BTreeMap<ObjectId, ObjectId>) {
51
+ match obj {
52
+ Object::Reference(r) => {
53
+ if let Some(&new_id) = id_map.get(r) {
54
+ *r = new_id;
55
+ }
56
+ }
57
+ Object::Array(arr) => {
58
+ for item in arr {
59
+ remap_refs(item, id_map);
60
+ }
61
+ }
62
+ Object::Dictionary(dict) => {
63
+ for (_, v) in dict.iter_mut() {
64
+ remap_refs(v, id_map);
65
+ }
66
+ }
67
+ Object::Stream(stream) => {
68
+ for (_, v) in stream.dict.iter_mut() {
69
+ remap_refs(v, id_map);
70
+ }
71
+ }
72
+ _ => {}
73
+ }
74
+ }
75
+
76
+ /// Collect all object IDs reachable from `start` in `doc` (including start itself).
77
+ fn collect_reachable(start: ObjectId, doc: &Document, visited: &mut BTreeMap<ObjectId, Object>) {
78
+ if visited.contains_key(&start) {
79
+ return;
80
+ }
81
+ if let Ok(obj) = doc.get_object(start) {
82
+ visited.insert(start, obj.clone());
83
+ walk_refs(&obj, doc, visited);
84
+ }
85
+ }
86
+
87
+ /// Walk all references in `obj` and collect reachable objects.
88
+ fn walk_refs(obj: &Object, doc: &Document, visited: &mut BTreeMap<ObjectId, Object>) {
89
+ match obj {
90
+ Object::Reference(r) => collect_reachable(*r, doc, visited),
91
+ Object::Array(arr) => {
92
+ for item in arr {
93
+ walk_refs(item, doc, visited);
94
+ }
95
+ }
96
+ Object::Dictionary(dict) => {
97
+ for (_, v) in dict.iter() {
98
+ walk_refs(v, doc, visited);
99
+ }
100
+ }
101
+ Object::Stream(stream) => {
102
+ for (_, v) in stream.dict.iter() {
103
+ walk_refs(v, doc, visited);
104
+ }
105
+ }
106
+ _ => {}
107
+ }
108
+ }
109
+
110
+ /// Copy page at `page_obj_id` from `src` into `dst`, updating all internal references.
111
+ fn copy_page_into(src: &Document, dst: &mut Document, page_obj_id: ObjectId) -> ObjectId {
112
+ // Collect all reachable objects from this page
113
+ let mut to_copy: BTreeMap<ObjectId, Object> = BTreeMap::new();
114
+ collect_reachable(page_obj_id, src, &mut to_copy);
115
+
116
+ // Assign new IDs in dst's address space
117
+ let mut id_map: BTreeMap<ObjectId, ObjectId> = BTreeMap::new();
118
+ let mut next_id = dst.max_id + 1;
119
+
120
+ let mut ids_sorted: Vec<ObjectId> = to_copy.keys().cloned().collect();
121
+ ids_sorted.sort_by_key(|(x, _)| *x);
122
+
123
+ for old_id in ids_sorted {
124
+ let new_id = loop {
125
+ let candidate = (next_id, 0);
126
+ if !dst.objects.contains_key(&candidate) {
127
+ break candidate;
128
+ }
129
+ next_id += 1;
130
+ };
131
+ id_map.insert(old_id, new_id);
132
+ let mut obj = to_copy[&old_id].clone();
133
+ remap_refs(&mut obj, &id_map);
134
+ dst.objects.insert(new_id, obj);
135
+ dst.max_id = next_id.max(dst.max_id);
136
+ }
137
+
138
+ *id_map.get(&page_obj_id).unwrap_or(&(0, 0))
139
+ }
140
+
141
+ #[wasm_bindgen]
142
+ pub fn merge(pdf_buffers: Array) -> Result<Uint8Array, JsValue> {
143
+ let len = pdf_buffers.length();
144
+ if len == 0 {
145
+ return Ok(Uint8Array::new_from_slice(&[]));
146
+ }
147
+
148
+ let first_buf = pdf_buffers.get(0).dyn_into::<Uint8Array>()
149
+ .map_err(|_| JsValue::from_str("merge: first item not Uint8Array"))?;
150
+ let mut doc = Document::load_mem(&first_buf.to_vec())
151
+ .map_err(|e| JsValue::from_str(&format!("PDF load error: {}", e)))?;
152
+
153
+ for i in 1..len {
154
+ let buf = pdf_buffers.get(i).dyn_into::<Uint8Array>()
155
+ .map_err(|_| JsValue::from_str("merge: item not Uint8Array"))?;
156
+ let other = Document::load_mem(&buf.to_vec())
157
+ .map_err(|e| JsValue::from_str(&format!("PDF load error: {}", e)))?;
158
+
159
+ // Pre-compute page count before any mutable borrow
160
+ let page_count = doc.get_pages().len() as i64;
161
+
162
+ for &page_obj_id in other.get_pages().values() {
163
+ let new_page_id = copy_page_into(&other, &mut doc, page_obj_id);
164
+ // Append new page to the Pages catalog Kids array
165
+ if let Ok(root_ref) = doc.trailer.get(b"Root").and_then(|r| r.as_reference()) {
166
+ if let Some(Object::Dictionary(ref mut root_dict)) = doc.objects.get_mut(&root_ref) {
167
+ if let Ok(pages_ref) = root_dict.get(b"Pages").and_then(|p| p.as_reference()) {
168
+ if let Some(Object::Dictionary(ref mut pages_dict)) = doc.objects.get_mut(&pages_ref) {
169
+ if let Ok(kids) = pages_dict.get_mut(b"Kids") {
170
+ if let Object::Array(ref mut kids_arr) = kids {
171
+ kids_arr.push(Object::Reference(new_page_id));
172
+ }
173
+ }
174
+ if let Ok(count) = pages_dict.get_mut(b"Count") {
175
+ *count = Object::Integer(page_count + 1);
176
+ }
177
+ }
178
+ }
179
+ }
180
+ }
181
+ }
182
+ }
183
+
184
+ let mut buf = Vec::new();
185
+ doc.save_to(&mut buf).map_err(|e| JsValue::from_str(&format!("PDF save error: {}", e)))?;
186
+ Ok(Uint8Array::new_from_slice(&buf))
187
+ }
188
+
189
+ #[wasm_bindgen]
190
+ pub fn split(buffer: &[u8], pages: Array) -> Result<Array, JsValue> {
191
+ let doc = Document::load_mem(buffer)
192
+ .map_err(|e| JsValue::from_str(&format!("PDF error: {}", e)))?;
193
+ let page_len = pages.length();
194
+
195
+ // get_pages returns BTreeMap<u32, ObjectId>
196
+ let page_map: BTreeMap<u32, ObjectId> = doc.get_pages();
197
+
198
+ let results = Array::new();
199
+
200
+ for i in 0..page_len {
201
+ let page_num = pages.get(i).as_f64().unwrap_or(0.0) as u32;
202
+ let Some(&page_obj_id) = page_map.get(&page_num) else { continue };
203
+
204
+ // Build a new document containing just this page
205
+ let mut new_doc = Document::with_version("1.5");
206
+ let _ = copy_page_into(&doc, &mut new_doc, page_obj_id);
207
+
208
+ // Update the Pages catalog (first Pages dictionary in new_doc)
209
+ if let Some((_, &pages_obj_id)) = new_doc.get_pages().iter().next() {
210
+ let new_count = new_doc.get_pages().len() as i64;
211
+ if let Some(Object::Dictionary(ref mut pages_dict)) = new_doc.objects.get_mut(&pages_obj_id) {
212
+ let _ = pages_dict.set("Count", Object::Integer(new_count));
213
+ }
214
+ }
215
+
216
+ let mut pdf_bytes = Vec::new();
217
+ let _ = new_doc.save_to(&mut pdf_bytes);
218
+ results.push(&Uint8Array::new_from_slice(&pdf_bytes).into());
219
+ }
220
+
221
+ if results.length() == 0 {
222
+ results.push(&Uint8Array::new_from_slice(&[]).into());
223
+ }
224
+
225
+ Ok(results)
226
+ }
227
+
228
+ #[wasm_bindgen]
229
+ pub fn get_pdf_info(buffer: &[u8]) -> Result<String, JsValue> {
230
+ let count = get_page_count(buffer)?;
231
+ Ok(format!("PDF with {} pages", count))
232
+ }