@triplef/pdf 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Eugen Hildt
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,25 @@
1
+ # @triplef/pdf
2
+
3
+ Single-owner pdfjs integration for the tripleF (3F) apps — the one and only place that depends on `pdfjs-dist`.
4
+
5
+ - `PdfService.extractText(buffer)` → per-page text layer (`string[]`, aligned 1:1 with pages; `''` for pages without a text layer, e.g. scanned pages).
6
+ - `PdfService.renderPages(buffer, scale?)` → per-page PNG buffers (`{ buffer, mimeType: 'image/png', pageNumber }`), white background, rendered via pdfjs' built-in `NodeCanvasFactory` on top of `@napi-rs/canvas` (a runtime dependency of this package).
7
+
8
+ ## Usage
9
+
10
+ ```ts
11
+ import { PdfModule } from '@triplef/pdf';
12
+
13
+ @Module({
14
+ imports: [PdfModule.registerAsync({ global: true })],
15
+ })
16
+ export class AppModule {}
17
+ ```
18
+
19
+ Then inject `PdfService` wherever it is needed.
20
+
21
+ ## Notes
22
+
23
+ - Uses the pdfjs **legacy Node build** (`pdfjs-dist/legacy/build/pdf.mjs`) with standard fonts and CMaps resolved from the installed `pdfjs-dist` package, so CJK documents extract and render correctly.
24
+ - No `isEvalSupported` option: pdfjs ≥5.7 removed it together with the PostScript `eval` path (CVE-2024-4367 surface).
25
+ - Post-processing (e.g. JPEG re-encode for token efficiency) is intentionally left to the consuming app.
@@ -0,0 +1,2 @@
1
+ export { PdfModule, PdfOptions, PdfPage, PdfService } from './pdf/index.js';
2
+ import '@nestjs/common';
package/dist/index.mjs ADDED
@@ -0,0 +1,112 @@
1
+ import { Injectable, Module } from '@nestjs/common';
2
+ import { createRequire } from 'module';
3
+ import path from 'path';
4
+
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __decorateClass = (decorators, target, key, kind) => {
7
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
8
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
9
+ if (decorator = decorators[i])
10
+ result = (decorator(result)) || result;
11
+ return result;
12
+ };
13
+ var DEFAULT_RENDER_SCALE = 2;
14
+ var PdfService = class {
15
+ /**
16
+ * Extract the text layer, one entry per page and aligned with the page
17
+ * order of renderPages(). A page without a text layer (scanned/image-only)
18
+ * yields ''. Throws when the buffer is not a parseable pdf.
19
+ */
20
+ async extractText(buffer) {
21
+ const loadingTask = await this.loadDocument(buffer);
22
+ try {
23
+ const document = await loadingTask.promise;
24
+ const pages = [];
25
+ for (let pageNumber = 1; pageNumber <= document.numPages; pageNumber++) {
26
+ const page = await document.getPage(pageNumber);
27
+ const { items } = await page.getTextContent();
28
+ pages.push(toPageText(items));
29
+ page.cleanup();
30
+ }
31
+ return pages;
32
+ } finally {
33
+ await loadingTask.destroy();
34
+ }
35
+ }
36
+ /**
37
+ * Render every page to a PNG at the given scale with a white background
38
+ * (transparent pages would re-encode poorly to JPEG downstream). Entries
39
+ * carry 1-based page numbers aligned with extractText().
40
+ */
41
+ async renderPages(buffer, scale = DEFAULT_RENDER_SCALE) {
42
+ const loadingTask = await this.loadDocument(buffer);
43
+ try {
44
+ const document = await loadingTask.promise;
45
+ const pages = [];
46
+ for (let pageNumber = 1; pageNumber <= document.numPages; pageNumber++) {
47
+ pages.push(await renderPage(document, pageNumber, scale));
48
+ }
49
+ return pages;
50
+ } finally {
51
+ await loadingTask.destroy();
52
+ }
53
+ }
54
+ /**
55
+ * Open the document with the legacy Node build; pdfjs standard fonts and
56
+ * CMaps resolve from the installed package — createRequire with the file's
57
+ * own url keeps the resolution working from the compiled dist too.
58
+ */
59
+ async loadDocument(buffer) {
60
+ const { getDocument } = await import('pdfjs-dist/legacy/build/pdf.mjs');
61
+ const pdfjsPath = path.dirname(createRequire(import.meta.url).resolve("pdfjs-dist/package.json"));
62
+ const params = {
63
+ data: new Uint8Array(buffer),
64
+ standardFontDataUrl: path.join(pdfjsPath, `standard_fonts${path.sep}`),
65
+ cMapUrl: path.join(pdfjsPath, `cmaps${path.sep}`),
66
+ cMapPacked: true
67
+ };
68
+ return getDocument(params);
69
+ }
70
+ };
71
+ PdfService = __decorateClass([
72
+ Injectable()
73
+ ], PdfService);
74
+ function toPageText(items) {
75
+ return items.map((item) => !item.str ? "" : item.hasEOL ? `${item.str}
76
+ ` : `${item.str} `).join("").trim();
77
+ }
78
+ async function renderPage(document, pageNumber, scale) {
79
+ const page = await document.getPage(pageNumber);
80
+ const viewport = page.getViewport({ scale });
81
+ const { canvas, context } = document.canvasFactory.create(
82
+ Math.ceil(viewport.width),
83
+ Math.ceil(viewport.height)
84
+ );
85
+ await page.render({
86
+ // napi-rs canvas/context are structurally the DOM types the renderer
87
+ // drives at runtime; the pdfjs params expect the DOM interfaces.
88
+ canvasContext: context,
89
+ canvas,
90
+ viewport,
91
+ background: "rgb(255,255,255)"
92
+ }).promise;
93
+ page.cleanup();
94
+ return { buffer: canvas.toBuffer("image/png"), mimeType: "image/png", pageNumber };
95
+ }
96
+
97
+ // src/pdf/pdf.module.ts
98
+ var PdfModule = class {
99
+ static registerAsync(options) {
100
+ return {
101
+ global: options?.global,
102
+ module: PdfModule,
103
+ exports: [PdfService],
104
+ providers: [PdfService]
105
+ };
106
+ }
107
+ };
108
+ PdfModule = __decorateClass([
109
+ Module({})
110
+ ], PdfModule);
111
+
112
+ export { PdfModule, PdfService };
@@ -0,0 +1,22 @@
1
+ import { DynamicModule } from '@nestjs/common';
2
+
3
+ interface PdfOptions {
4
+ global?: boolean;
5
+ }
6
+ interface PdfPage {
7
+ buffer: Buffer;
8
+ mimeType: 'image/png';
9
+ pageNumber: number;
10
+ }
11
+
12
+ declare class PdfModule {
13
+ static registerAsync(options?: PdfOptions): DynamicModule;
14
+ }
15
+
16
+ declare class PdfService {
17
+ extractText(buffer: Buffer): Promise<string[]>;
18
+ renderPages(buffer: Buffer, scale?: number): Promise<PdfPage[]>;
19
+ private loadDocument;
20
+ }
21
+
22
+ export { PdfModule, type PdfOptions, type PdfPage, PdfService };
@@ -0,0 +1,112 @@
1
+ import { Injectable, Module } from '@nestjs/common';
2
+ import { createRequire } from 'module';
3
+ import path from 'path';
4
+
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __decorateClass = (decorators, target, key, kind) => {
7
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
8
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
9
+ if (decorator = decorators[i])
10
+ result = (decorator(result)) || result;
11
+ return result;
12
+ };
13
+ var DEFAULT_RENDER_SCALE = 2;
14
+ var PdfService = class {
15
+ /**
16
+ * Extract the text layer, one entry per page and aligned with the page
17
+ * order of renderPages(). A page without a text layer (scanned/image-only)
18
+ * yields ''. Throws when the buffer is not a parseable pdf.
19
+ */
20
+ async extractText(buffer) {
21
+ const loadingTask = await this.loadDocument(buffer);
22
+ try {
23
+ const document = await loadingTask.promise;
24
+ const pages = [];
25
+ for (let pageNumber = 1; pageNumber <= document.numPages; pageNumber++) {
26
+ const page = await document.getPage(pageNumber);
27
+ const { items } = await page.getTextContent();
28
+ pages.push(toPageText(items));
29
+ page.cleanup();
30
+ }
31
+ return pages;
32
+ } finally {
33
+ await loadingTask.destroy();
34
+ }
35
+ }
36
+ /**
37
+ * Render every page to a PNG at the given scale with a white background
38
+ * (transparent pages would re-encode poorly to JPEG downstream). Entries
39
+ * carry 1-based page numbers aligned with extractText().
40
+ */
41
+ async renderPages(buffer, scale = DEFAULT_RENDER_SCALE) {
42
+ const loadingTask = await this.loadDocument(buffer);
43
+ try {
44
+ const document = await loadingTask.promise;
45
+ const pages = [];
46
+ for (let pageNumber = 1; pageNumber <= document.numPages; pageNumber++) {
47
+ pages.push(await renderPage(document, pageNumber, scale));
48
+ }
49
+ return pages;
50
+ } finally {
51
+ await loadingTask.destroy();
52
+ }
53
+ }
54
+ /**
55
+ * Open the document with the legacy Node build; pdfjs standard fonts and
56
+ * CMaps resolve from the installed package — createRequire with the file's
57
+ * own url keeps the resolution working from the compiled dist too.
58
+ */
59
+ async loadDocument(buffer) {
60
+ const { getDocument } = await import('pdfjs-dist/legacy/build/pdf.mjs');
61
+ const pdfjsPath = path.dirname(createRequire(import.meta.url).resolve("pdfjs-dist/package.json"));
62
+ const params = {
63
+ data: new Uint8Array(buffer),
64
+ standardFontDataUrl: path.join(pdfjsPath, `standard_fonts${path.sep}`),
65
+ cMapUrl: path.join(pdfjsPath, `cmaps${path.sep}`),
66
+ cMapPacked: true
67
+ };
68
+ return getDocument(params);
69
+ }
70
+ };
71
+ PdfService = __decorateClass([
72
+ Injectable()
73
+ ], PdfService);
74
+ function toPageText(items) {
75
+ return items.map((item) => !item.str ? "" : item.hasEOL ? `${item.str}
76
+ ` : `${item.str} `).join("").trim();
77
+ }
78
+ async function renderPage(document, pageNumber, scale) {
79
+ const page = await document.getPage(pageNumber);
80
+ const viewport = page.getViewport({ scale });
81
+ const { canvas, context } = document.canvasFactory.create(
82
+ Math.ceil(viewport.width),
83
+ Math.ceil(viewport.height)
84
+ );
85
+ await page.render({
86
+ // napi-rs canvas/context are structurally the DOM types the renderer
87
+ // drives at runtime; the pdfjs params expect the DOM interfaces.
88
+ canvasContext: context,
89
+ canvas,
90
+ viewport,
91
+ background: "rgb(255,255,255)"
92
+ }).promise;
93
+ page.cleanup();
94
+ return { buffer: canvas.toBuffer("image/png"), mimeType: "image/png", pageNumber };
95
+ }
96
+
97
+ // src/pdf/pdf.module.ts
98
+ var PdfModule = class {
99
+ static registerAsync(options) {
100
+ return {
101
+ global: options?.global,
102
+ module: PdfModule,
103
+ exports: [PdfService],
104
+ providers: [PdfService]
105
+ };
106
+ }
107
+ };
108
+ PdfModule = __decorateClass([
109
+ Module({})
110
+ ], PdfModule);
111
+
112
+ export { PdfModule, PdfService };
package/package.json ADDED
@@ -0,0 +1,86 @@
1
+ {
2
+ "name": "@triplef/pdf",
3
+ "description": "tripleF (3F) PDF domain — single-owner pdfjs integration: per-page text-layer extraction and page rendering for the apps.",
4
+ "version": "0.1.0",
5
+ "packageManager": "pnpm@11.25.0",
6
+ "license": "MIT",
7
+ "type": "module",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.mjs"
12
+ },
13
+ "./pdf": {
14
+ "types": "./dist/pdf/index.d.ts",
15
+ "import": "./dist/pdf/index.mjs"
16
+ }
17
+ },
18
+ "main": "dist/index.mjs",
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "https://github.com/ehildt/tripleF.git"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "author": {
30
+ "email": "eugen.hildt@gmail.com",
31
+ "name": "Eugen Hildt"
32
+ },
33
+ "bugs": {
34
+ "email": "eugen.hildt@gmail.com"
35
+ },
36
+ "scripts": {
37
+ "prepare": "husky",
38
+ "build": "pnpm tsup",
39
+ "depcheck": "npx depcheck .",
40
+ "depcruise": "npx dependency-cruiser -c .depcruise.mjs --ts-config tsconfig.json src",
41
+ "format": "prettier --write .",
42
+ "lint": "eslint ./src",
43
+ "lint-staged": "npx lint-staged --allow-empty",
44
+ "ncu:update": "npx npm-check-updates -u --format group --dep prod,dev,optional,packageManager,peer",
45
+ "ncu:interactive": "npx npm-check-updates -u --interactive --format group",
46
+ "ncu:validate": "npx npm-check-updates -e 2 --packageFile=./package.json",
47
+ "prebuild": "rimraf dist",
48
+ "test": "vitest run",
49
+ "test:watch": "vitest",
50
+ "test:cov": "vitest run --coverage",
51
+ "lint:unused": "npx ts-unused-exports ./tsconfig.exclude.json --maxIssues=6"
52
+ },
53
+ "dependencies": {
54
+ "@napi-rs/canvas": "^0.1.100",
55
+ "pdfjs-dist": "~5.7.284"
56
+ },
57
+ "devDependencies": {
58
+ "@changesets/cli": "^3.0.2",
59
+ "@eslint/js": "^10.0.1",
60
+ "@types/eslint": "^9.6.1",
61
+ "@types/node": "^26.4.1",
62
+ "@vitest/coverage-v8": "4.1.11",
63
+ "depcheck": "^1.4.7",
64
+ "dependency-cruiser": "^18.2.0",
65
+ "eslint": "^10.10.0",
66
+ "eslint-config-prettier": "^10.1.8",
67
+ "eslint-plugin-prettier": "^5.5.6",
68
+ "eslint-plugin-simple-import-sort": "^14.0.0",
69
+ "eslint-plugin-sonarjs": "^4.2.0",
70
+ "globals": "^17.12.0",
71
+ "husky": "^9.1.7",
72
+ "jiti": "^2.7.0",
73
+ "lint-staged": "^17.4.1",
74
+ "npm-check-updates": "^23.1.0",
75
+ "prettier": "^3.9.6",
76
+ "rimraf": "^6.1.3",
77
+ "ts-unused-exports": "^11.0.1",
78
+ "tsup": "^8.5.1",
79
+ "typescript": "^5.9.3",
80
+ "typescript-eslint": "^8.69.0",
81
+ "vitest": "^4.1.11"
82
+ },
83
+ "peerDependencies": {
84
+ "@nestjs/common": "^11.2.3"
85
+ }
86
+ }