@oiij/js-pdf 0.0.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 oiij <https://github.com/oiij>
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
+ # JS-PDF
2
+
3
+ Features:
4
+
5
+ - Bundle with [tsdown](https://github.com/rolldown/tsdown)
6
+ - Test with [vitest](https://vitest.dev)
7
+
8
+ # Usage
9
+
10
+ ### 安装
11
+
12
+ ```bash
13
+ pnpm add @oiij/js-pdf
14
+ ```
15
+
16
+ ### 使用
17
+
18
+ ```ts
19
+ import { openPdf } from '@oiij/js-pdf'
20
+ const { pdf } = await openPdf()
21
+ ```
22
+
23
+ ## License
24
+
25
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,160 @@
1
+ "use strict";
2
+ //#region rolldown:runtime
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
23
+
24
+ //#endregion
25
+ const file_saver = __toESM(require("file-saver"));
26
+ const jspdf = __toESM(require("jspdf"));
27
+ const jszip = __toESM(require("jszip"));
28
+ const nanoid = __toESM(require("nanoid"));
29
+ const pdfjs_dist = __toESM(require("pdfjs-dist"));
30
+
31
+ //#region src/index.ts
32
+ pdfjs_dist.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs_dist.version}/build/pdf.worker.min.mjs`;
33
+ function file2Buffer(file) {
34
+ return new Promise((resolve, reject) => {
35
+ const reader = new FileReader();
36
+ reader.onload = () => {
37
+ return resolve(reader.result);
38
+ };
39
+ reader.onerror = () => {
40
+ return reject(reader.error?.message);
41
+ };
42
+ reader.readAsArrayBuffer(file);
43
+ });
44
+ }
45
+ function createCanvas(width, height, id) {
46
+ const canvas = document.createElement("canvas");
47
+ const ctx = canvas.getContext("2d");
48
+ canvas.id = id;
49
+ canvas.width = width;
50
+ canvas.height = height;
51
+ return {
52
+ canvas,
53
+ ctx
54
+ };
55
+ }
56
+ function page2Canvas(page, id) {
57
+ return new Promise((resolve, reject) => {
58
+ const pixelRatio = Math.max(window.devicePixelRatio, 2);
59
+ const viewport = page.getViewport({ scale: pixelRatio });
60
+ const { width, height } = viewport;
61
+ const { canvas, ctx } = createCanvas(width, height, `page-${id}-${page._pageIndex}`);
62
+ canvas.style.width = `${width / pixelRatio}px`;
63
+ canvas.style.height = `${height / pixelRatio}px`;
64
+ page.render({
65
+ canvasContext: ctx,
66
+ viewport
67
+ }).promise.then(() => resolve(canvas)).catch((e) => reject(e));
68
+ });
69
+ }
70
+ async function pdf2Canvases(pdf) {
71
+ try {
72
+ const pages = await Promise.all(Array.from({ length: pdf.numPages }).map((_, i) => pdf.getPage(i + 1)));
73
+ const id = (0, nanoid.nanoid)();
74
+ const canvases = await Promise.all(pages.map((page) => page2Canvas(page, id)));
75
+ return {
76
+ pages,
77
+ id,
78
+ canvases
79
+ };
80
+ } catch (error) {
81
+ console.error(error);
82
+ return Promise.reject(error);
83
+ }
84
+ }
85
+ async function openPdf(url) {
86
+ try {
87
+ if (url) {
88
+ const pdf = await (0, pdfjs_dist.getDocument)(url).promise;
89
+ const { pages, id, canvases } = await pdf2Canvases(pdf);
90
+ return {
91
+ pdf,
92
+ pages,
93
+ id,
94
+ canvases
95
+ };
96
+ } else {
97
+ const [fileHandle] = await window.showOpenFilePicker({ types: [{ accept: { "application/pdf": [".pdf"] } }] });
98
+ const file = await fileHandle.getFile();
99
+ const buffer = await file2Buffer(file);
100
+ const pdf = await (0, pdfjs_dist.getDocument)(buffer).promise;
101
+ const { pages, id, canvases } = await pdf2Canvases(pdf);
102
+ return {
103
+ pdf,
104
+ pages,
105
+ id,
106
+ canvases
107
+ };
108
+ }
109
+ } catch (error) {
110
+ console.error(error);
111
+ return Promise.reject(error);
112
+ }
113
+ }
114
+ function canvas2Blob(canvas) {
115
+ return new Promise((resolve, reject) => {
116
+ try {
117
+ canvas.toBlob((blob) => {
118
+ if (blob) return resolve(blob);
119
+ return reject(new Error("canvas to blob error"));
120
+ });
121
+ } catch (error) {
122
+ return reject(error);
123
+ }
124
+ });
125
+ }
126
+ function canvas2Pdf(canvases, fileName) {
127
+ let doc = null;
128
+ canvases.forEach((canvas, i) => {
129
+ const width = Number((canvas.width / 2 / 72 * 25.4).toFixed());
130
+ const height = Number((canvas.height / 2 / 72 * 25.4).toFixed());
131
+ if (!doc) doc = new jspdf.jsPDF({
132
+ unit: "mm",
133
+ format: [width, height]
134
+ });
135
+ if (i > 0) doc.addPage([width, height]);
136
+ doc.setPage(i + 1);
137
+ doc.addImage(canvas, "PNG", 0, 0, width, height);
138
+ if (i === canvases.length - 1) doc.save(fileName);
139
+ return doc;
140
+ });
141
+ }
142
+ function canvas2Zip(canvases, fileName) {
143
+ return new Promise((resolve, reject) => {
144
+ const zip = new jszip.default();
145
+ Promise.all(canvases.map((canvas) => canvas2Blob(canvas))).then((blobs) => {
146
+ blobs.forEach((blob, i) => {
147
+ zip.file(`${canvases[i].id}.jpg`, blob);
148
+ });
149
+ zip.generateAsync({ type: "blob" }).then((blob) => {
150
+ (0, file_saver.saveAs)(blob, `${fileName}.zip`);
151
+ return resolve(blobs);
152
+ }).catch((error) => reject(error));
153
+ }).catch((error) => reject(error));
154
+ });
155
+ }
156
+
157
+ //#endregion
158
+ exports.canvas2Pdf = canvas2Pdf
159
+ exports.canvas2Zip = canvas2Zip
160
+ exports.openPdf = openPdf
@@ -0,0 +1,14 @@
1
+ import { PDFDocumentProxy, PDFPageProxy } from "pdfjs-dist/types/src/display/api";
2
+
3
+ //#region src/index.d.ts
4
+ declare function openPdf(url?: string | URL): Promise<{
5
+ pdf: PDFDocumentProxy;
6
+ pages: PDFPageProxy[];
7
+ id: string;
8
+ canvases: HTMLCanvasElement[];
9
+ }>;
10
+ declare function canvas2Pdf(canvases: HTMLCanvasElement[], fileName: string): void;
11
+ declare function canvas2Zip(canvases: HTMLCanvasElement[], fileName: string): Promise<unknown>;
12
+
13
+ //#endregion
14
+ export { canvas2Pdf, canvas2Zip, openPdf };
@@ -0,0 +1,14 @@
1
+ import { PDFDocumentProxy, PDFPageProxy } from "pdfjs-dist/types/src/display/api";
2
+
3
+ //#region src/index.d.ts
4
+ declare function openPdf(url?: string | URL): Promise<{
5
+ pdf: PDFDocumentProxy;
6
+ pages: PDFPageProxy[];
7
+ id: string;
8
+ canvases: HTMLCanvasElement[];
9
+ }>;
10
+ declare function canvas2Pdf(canvases: HTMLCanvasElement[], fileName: string): void;
11
+ declare function canvas2Zip(canvases: HTMLCanvasElement[], fileName: string): Promise<unknown>;
12
+
13
+ //#endregion
14
+ export { canvas2Pdf, canvas2Zip, openPdf };
package/dist/index.js ADDED
@@ -0,0 +1,134 @@
1
+ import { saveAs } from "file-saver";
2
+ import { jsPDF } from "jspdf";
3
+ import JsZip from "jszip";
4
+ import { nanoid } from "nanoid";
5
+ import { GlobalWorkerOptions, getDocument, version } from "pdfjs-dist";
6
+
7
+ //#region src/index.ts
8
+ GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${version}/build/pdf.worker.min.mjs`;
9
+ function file2Buffer(file) {
10
+ return new Promise((resolve, reject) => {
11
+ const reader = new FileReader();
12
+ reader.onload = () => {
13
+ return resolve(reader.result);
14
+ };
15
+ reader.onerror = () => {
16
+ return reject(reader.error?.message);
17
+ };
18
+ reader.readAsArrayBuffer(file);
19
+ });
20
+ }
21
+ function createCanvas(width, height, id) {
22
+ const canvas = document.createElement("canvas");
23
+ const ctx = canvas.getContext("2d");
24
+ canvas.id = id;
25
+ canvas.width = width;
26
+ canvas.height = height;
27
+ return {
28
+ canvas,
29
+ ctx
30
+ };
31
+ }
32
+ function page2Canvas(page, id) {
33
+ return new Promise((resolve, reject) => {
34
+ const pixelRatio = Math.max(window.devicePixelRatio, 2);
35
+ const viewport = page.getViewport({ scale: pixelRatio });
36
+ const { width, height } = viewport;
37
+ const { canvas, ctx } = createCanvas(width, height, `page-${id}-${page._pageIndex}`);
38
+ canvas.style.width = `${width / pixelRatio}px`;
39
+ canvas.style.height = `${height / pixelRatio}px`;
40
+ page.render({
41
+ canvasContext: ctx,
42
+ viewport
43
+ }).promise.then(() => resolve(canvas)).catch((e) => reject(e));
44
+ });
45
+ }
46
+ async function pdf2Canvases(pdf) {
47
+ try {
48
+ const pages = await Promise.all(Array.from({ length: pdf.numPages }).map((_, i) => pdf.getPage(i + 1)));
49
+ const id = nanoid();
50
+ const canvases = await Promise.all(pages.map((page) => page2Canvas(page, id)));
51
+ return {
52
+ pages,
53
+ id,
54
+ canvases
55
+ };
56
+ } catch (error) {
57
+ console.error(error);
58
+ return Promise.reject(error);
59
+ }
60
+ }
61
+ async function openPdf(url) {
62
+ try {
63
+ if (url) {
64
+ const pdf = await getDocument(url).promise;
65
+ const { pages, id, canvases } = await pdf2Canvases(pdf);
66
+ return {
67
+ pdf,
68
+ pages,
69
+ id,
70
+ canvases
71
+ };
72
+ } else {
73
+ const [fileHandle] = await window.showOpenFilePicker({ types: [{ accept: { "application/pdf": [".pdf"] } }] });
74
+ const file = await fileHandle.getFile();
75
+ const buffer = await file2Buffer(file);
76
+ const pdf = await getDocument(buffer).promise;
77
+ const { pages, id, canvases } = await pdf2Canvases(pdf);
78
+ return {
79
+ pdf,
80
+ pages,
81
+ id,
82
+ canvases
83
+ };
84
+ }
85
+ } catch (error) {
86
+ console.error(error);
87
+ return Promise.reject(error);
88
+ }
89
+ }
90
+ function canvas2Blob(canvas) {
91
+ return new Promise((resolve, reject) => {
92
+ try {
93
+ canvas.toBlob((blob) => {
94
+ if (blob) return resolve(blob);
95
+ return reject(new Error("canvas to blob error"));
96
+ });
97
+ } catch (error) {
98
+ return reject(error);
99
+ }
100
+ });
101
+ }
102
+ function canvas2Pdf(canvases, fileName) {
103
+ let doc = null;
104
+ canvases.forEach((canvas, i) => {
105
+ const width = Number((canvas.width / 2 / 72 * 25.4).toFixed());
106
+ const height = Number((canvas.height / 2 / 72 * 25.4).toFixed());
107
+ if (!doc) doc = new jsPDF({
108
+ unit: "mm",
109
+ format: [width, height]
110
+ });
111
+ if (i > 0) doc.addPage([width, height]);
112
+ doc.setPage(i + 1);
113
+ doc.addImage(canvas, "PNG", 0, 0, width, height);
114
+ if (i === canvases.length - 1) doc.save(fileName);
115
+ return doc;
116
+ });
117
+ }
118
+ function canvas2Zip(canvases, fileName) {
119
+ return new Promise((resolve, reject) => {
120
+ const zip = new JsZip();
121
+ Promise.all(canvases.map((canvas) => canvas2Blob(canvas))).then((blobs) => {
122
+ blobs.forEach((blob, i) => {
123
+ zip.file(`${canvases[i].id}.jpg`, blob);
124
+ });
125
+ zip.generateAsync({ type: "blob" }).then((blob) => {
126
+ saveAs(blob, `${fileName}.zip`);
127
+ return resolve(blobs);
128
+ }).catch((error) => reject(error));
129
+ }).catch((error) => reject(error));
130
+ });
131
+ }
132
+
133
+ //#endregion
134
+ export { canvas2Pdf, canvas2Zip, openPdf };
package/package.json ADDED
@@ -0,0 +1,96 @@
1
+ {
2
+ "name": "@oiij/js-pdf",
3
+ "type": "module",
4
+ "version": "0.0.1",
5
+ "description": "A simple PDF library for JavaScript",
6
+ "author": "oiij",
7
+ "license": "MIT",
8
+ "homepage": "https://github.com/oiij/js-pdf",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git@github.com:oiij/js-pdf.git"
12
+ },
13
+ "bugs": "https://github.com/oiij/js-pdf/issues",
14
+ "keywords": [
15
+ "js-pdf"
16
+ ],
17
+ "sideEffects": false,
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/index.js",
22
+ "require": "./dist/index.cjs"
23
+ }
24
+ },
25
+ "main": "./dist/index.js",
26
+ "module": "./dist/index.js",
27
+ "types": "./dist/index.d.ts",
28
+ "files": [
29
+ "LICENSE",
30
+ "README.md",
31
+ "dist",
32
+ "package.json"
33
+ ],
34
+ "scripts": {
35
+ "dev": "tsdown --watch",
36
+ "build": "tsc --noEmit && tsdown",
37
+ "lint": "eslint .",
38
+ "lint:fix": "eslint . --fix",
39
+ "prepublishOnly": "pnpm build",
40
+ "release": "bumpp && npm publish",
41
+ "awe": "pnpx are-we-esm",
42
+ "nmi": "pnpx node-modules-inspector",
43
+ "start": "esno src/index.ts",
44
+ "test": "vitest",
45
+ "update:deps": "taze -w && pnpm i",
46
+ "type:check": "tsc --noEmit",
47
+ "cz": "czg",
48
+ "commit": "git pull && git add -A && pnpm cz && git push",
49
+ "link": "pnpm link --global",
50
+ "preinstall": "npx only-allow pnpm"
51
+ },
52
+ "peerDependencies": {
53
+ "file-saver": "^2.0.5",
54
+ "jspdf": "^3.0.1",
55
+ "jszip": "^3.10.1",
56
+ "nanoid": "^5.1.5",
57
+ "pdfjs-dist": "^5.1.91"
58
+ },
59
+ "devDependencies": {
60
+ "@antfu/eslint-config": "^4.12.0",
61
+ "@oiij/tsconfig": "^0.0.1",
62
+ "@types/file-saver": "^2.0.7",
63
+ "@types/node": "^22.14.1",
64
+ "@types/wicg-file-system-access": "^2023.10.6",
65
+ "@vitest/ui": "^3.1.2",
66
+ "bumpp": "^10.1.0",
67
+ "commitlint": "^19.8.0",
68
+ "cz-git": "^1.11.1",
69
+ "czg": "^1.11.1",
70
+ "eslint": "^9.25.1",
71
+ "eslint-plugin-format": "^1.0.1",
72
+ "esno": "^4.8.0",
73
+ "file-saver": "^2.0.5",
74
+ "jspdf": "^3.0.1",
75
+ "jszip": "^3.10.1",
76
+ "lint-staged": "^15.5.1",
77
+ "nanoid": "^5.1.5",
78
+ "pdfjs-dist": "^5.1.91",
79
+ "simple-git-hooks": "^2.12.1",
80
+ "taze": "^19.0.4",
81
+ "tsdown": "^0.9.3",
82
+ "typescript": "^5.8.3",
83
+ "vitest": "^3.1.2"
84
+ },
85
+ "simple-git-hooks": {
86
+ "pre-commit": "pnpm lint-staged && pnpm type:check"
87
+ },
88
+ "lint-staged": {
89
+ "*.{js,jsx,ts,tsx}": [
90
+ "pnpm lint:fix"
91
+ ]
92
+ },
93
+ "publishConfig": {
94
+ "access": "public"
95
+ }
96
+ }