@pdfme/converter 6.0.3-dev.0 → 6.0.4-dev.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/dist/assets/pdfjs-worker-BpS0tFhy.js +84617 -0
- package/dist/assets/pdfjs-worker-BpS0tFhy.js.map +1 -0
- package/dist/img2pdf-Ca1yX5Sv.js +124 -0
- package/dist/img2pdf-Ca1yX5Sv.js.map +1 -0
- package/dist/img2pdf.d.ts +12 -0
- package/dist/index.browser.d.ts +8 -0
- package/dist/index.js +52 -0
- package/dist/index.js.map +1 -0
- package/dist/index.node.d.ts +8 -0
- package/dist/index.node.js +40 -0
- package/dist/index.node.js.map +1 -0
- package/dist/pdf2img.d.ts +18 -0
- package/dist/pdf2size.d.ts +11 -0
- package/dist/pdfjs-worker-shim.d.ts +3 -0
- package/dist/pdfjs.node.d.ts +1 -0
- package/package.json +5 -1
- package/src/img2pdf.ts +0 -110
- package/src/index.browser.ts +0 -78
- package/src/index.node.ts +0 -45
- package/src/pdf2img.ts +0 -73
- package/src/pdf2size.ts +0 -35
- package/src/pdfjs-dist-webpack.d.ts +0 -20
- package/src/pdfjs-worker-shim.ts +0 -20
- package/src/pdfjs-worker.js +0 -2
- package/src/pdfjs.node.ts +0 -7
- package/src/types.d.ts +0 -1
- package/tsconfig.build.json +0 -14
- package/tsconfig.json +0 -16
- package/vite.config.mts +0 -70
- /package/{src/index.ts → dist/index.d.ts} +0 -0
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { mm2pt, pt2mm } from "@pdfme/common";
|
|
2
|
+
import { PDFDocument } from "@pdfme/pdf-lib";
|
|
3
|
+
//#region src/pdf2img.ts
|
|
4
|
+
async function pdf2img(pdf, options = {}, env) {
|
|
5
|
+
try {
|
|
6
|
+
const { scale = 1, imageType = "jpeg", range = {} } = options;
|
|
7
|
+
const { start = 0, end = Infinity } = range;
|
|
8
|
+
const { getDocument, destroyDocument, createCanvas, canvasToArrayBuffer } = env;
|
|
9
|
+
const pdfDoc = await getDocument(pdf);
|
|
10
|
+
try {
|
|
11
|
+
const numPages = pdfDoc.numPages;
|
|
12
|
+
const startPage = Math.max(start + 1, 1);
|
|
13
|
+
const endPage = Math.min(end + 1, numPages);
|
|
14
|
+
const results = [];
|
|
15
|
+
for (let pageNum = startPage; pageNum <= endPage; pageNum++) {
|
|
16
|
+
const page = await pdfDoc.getPage(pageNum);
|
|
17
|
+
const viewport = page.getViewport({ scale });
|
|
18
|
+
const canvas = createCanvas(viewport.width, viewport.height);
|
|
19
|
+
if (!canvas) throw new Error("Failed to create canvas");
|
|
20
|
+
const context = canvas.getContext("2d");
|
|
21
|
+
if (!context) throw new Error("Failed to get canvas context");
|
|
22
|
+
await page.render({
|
|
23
|
+
canvas,
|
|
24
|
+
canvasContext: context,
|
|
25
|
+
viewport
|
|
26
|
+
}).promise;
|
|
27
|
+
const arrayBuffer = canvasToArrayBuffer(canvas, imageType);
|
|
28
|
+
results.push(arrayBuffer);
|
|
29
|
+
}
|
|
30
|
+
return results;
|
|
31
|
+
} finally {
|
|
32
|
+
await destroyDocument?.(pdfDoc);
|
|
33
|
+
}
|
|
34
|
+
} catch (error) {
|
|
35
|
+
throw new Error(`[@pdfme/converter] pdf2img failed: ${error.message}`);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
//#endregion
|
|
39
|
+
//#region src/pdf2size.ts
|
|
40
|
+
async function pdf2size(pdf, options = {}, env) {
|
|
41
|
+
const { scale = 1 } = options;
|
|
42
|
+
const { getDocument, destroyDocument } = env;
|
|
43
|
+
const pdfDoc = await getDocument(pdf);
|
|
44
|
+
try {
|
|
45
|
+
return await Promise.all(Array.from({ length: pdfDoc.numPages }, async (_, i) => {
|
|
46
|
+
return await pdfDoc.getPage(i + 1).then((page) => {
|
|
47
|
+
const { height, width } = page.getViewport({
|
|
48
|
+
scale,
|
|
49
|
+
rotation: 0
|
|
50
|
+
});
|
|
51
|
+
return {
|
|
52
|
+
height: pt2mm(height),
|
|
53
|
+
width: pt2mm(width)
|
|
54
|
+
};
|
|
55
|
+
});
|
|
56
|
+
}));
|
|
57
|
+
} finally {
|
|
58
|
+
await destroyDocument?.(pdfDoc);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
//#endregion
|
|
62
|
+
//#region src/img2pdf.ts
|
|
63
|
+
function detectImageType(buffer) {
|
|
64
|
+
const bytes = new Uint8Array(buffer);
|
|
65
|
+
if (bytes.length >= 2 && bytes[0] === 255 && bytes[1] === 216) return "jpeg";
|
|
66
|
+
if (bytes.length >= 8 && bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71 && bytes[4] === 13 && bytes[5] === 10 && bytes[6] === 26 && bytes[7] === 10) return "png";
|
|
67
|
+
return "unknown";
|
|
68
|
+
}
|
|
69
|
+
async function img2pdf(imgs, options = {}) {
|
|
70
|
+
try {
|
|
71
|
+
const { scale = 1, size, margin = [
|
|
72
|
+
0,
|
|
73
|
+
0,
|
|
74
|
+
0,
|
|
75
|
+
0
|
|
76
|
+
] } = options;
|
|
77
|
+
if (!Array.isArray(imgs) || imgs.length === 0) throw new Error("Input must be a non-empty array of image buffers");
|
|
78
|
+
const doc = await PDFDocument.create();
|
|
79
|
+
for (const img of imgs) try {
|
|
80
|
+
let image;
|
|
81
|
+
const type = detectImageType(img);
|
|
82
|
+
if (type === "jpeg") image = await doc.embedJpg(img);
|
|
83
|
+
else if (type === "png") image = await doc.embedPng(img);
|
|
84
|
+
else try {
|
|
85
|
+
image = await doc.embedJpg(img);
|
|
86
|
+
} catch {
|
|
87
|
+
image = await doc.embedPng(img);
|
|
88
|
+
}
|
|
89
|
+
const page = doc.addPage();
|
|
90
|
+
const { width: imgWidth, height: imgHeight } = image.scale(scale);
|
|
91
|
+
const pageWidth = size ? mm2pt(size.width) : imgWidth;
|
|
92
|
+
const pageHeight = size ? mm2pt(size.height) : imgHeight;
|
|
93
|
+
page.setSize(pageWidth, pageHeight);
|
|
94
|
+
const [topMargin, rightMargin, bottomMargin, leftMargin] = margin.map(mm2pt);
|
|
95
|
+
const availableWidth = pageWidth - leftMargin - rightMargin;
|
|
96
|
+
const availableHeight = pageHeight - topMargin - bottomMargin;
|
|
97
|
+
const widthRatio = availableWidth / imgWidth;
|
|
98
|
+
const heightRatio = availableHeight / imgHeight;
|
|
99
|
+
const ratio = Math.min(widthRatio, heightRatio, 1);
|
|
100
|
+
const finalWidth = imgWidth * ratio;
|
|
101
|
+
const finalHeight = imgHeight * ratio;
|
|
102
|
+
const x = leftMargin + (availableWidth - finalWidth) / 2;
|
|
103
|
+
const y = bottomMargin + (availableHeight - finalHeight) / 2;
|
|
104
|
+
page.drawImage(image, {
|
|
105
|
+
x,
|
|
106
|
+
y,
|
|
107
|
+
width: finalWidth,
|
|
108
|
+
height: finalHeight
|
|
109
|
+
});
|
|
110
|
+
} catch (error) {
|
|
111
|
+
throw new Error(`Failed to process image: ${error.message}`);
|
|
112
|
+
}
|
|
113
|
+
const pdfUint8Array = await doc.save();
|
|
114
|
+
const buffer = new ArrayBuffer(pdfUint8Array.byteLength);
|
|
115
|
+
new Uint8Array(buffer).set(pdfUint8Array);
|
|
116
|
+
return buffer;
|
|
117
|
+
} catch (error) {
|
|
118
|
+
throw new Error(`[@pdfme/converter] img2pdf failed: ${error.message}`);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
//#endregion
|
|
122
|
+
export { pdf2size as n, pdf2img as r, img2pdf as t };
|
|
123
|
+
|
|
124
|
+
//# sourceMappingURL=img2pdf-Ca1yX5Sv.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"img2pdf-Ca1yX5Sv.js","names":[],"sources":["../src/pdf2img.ts","../src/pdf2size.ts","../src/img2pdf.ts"],"sourcesContent":["import type { PDFDocumentProxy } from 'pdfjs-dist';\nimport type { ImageType } from './types.js';\n\ninterface Environment {\n getDocument: (pdf: ArrayBuffer | Uint8Array) => Promise<PDFDocumentProxy>;\n destroyDocument?: (pdfDoc: PDFDocumentProxy) => Promise<void>;\n createCanvas: (width: number, height: number) => HTMLCanvasElement | OffscreenCanvas;\n canvasToArrayBuffer: (\n canvas: HTMLCanvasElement | OffscreenCanvas,\n imageType: ImageType,\n ) => ArrayBuffer;\n}\n\nexport interface Pdf2ImgOptions {\n scale?: number;\n imageType?: ImageType;\n range?: {\n start?: number;\n end?: number;\n };\n}\n\nexport async function pdf2img(\n pdf: ArrayBuffer | Uint8Array,\n options: Pdf2ImgOptions = {},\n env: Environment,\n): Promise<ArrayBuffer[]> {\n try {\n const { scale = 1, imageType = 'jpeg', range = {} } = options;\n const { start = 0, end = Infinity } = range;\n\n const { getDocument, destroyDocument, createCanvas, canvasToArrayBuffer } = env;\n\n const pdfDoc = await getDocument(pdf);\n try {\n const numPages = pdfDoc.numPages;\n\n const startPage = Math.max(start + 1, 1);\n const endPage = Math.min(end + 1, numPages);\n\n const results: ArrayBuffer[] = [];\n\n for (let pageNum = startPage; pageNum <= endPage; pageNum++) {\n const page = await pdfDoc.getPage(pageNum);\n const viewport = page.getViewport({ scale });\n\n const canvas = createCanvas(viewport.width, viewport.height);\n if (!canvas) {\n throw new Error('Failed to create canvas');\n }\n\n const context = canvas.getContext('2d') as CanvasRenderingContext2D;\n if (!context) {\n throw new Error('Failed to get canvas context');\n }\n\n await page.render({\n canvas: canvas as unknown as HTMLCanvasElement,\n canvasContext: context,\n viewport,\n }).promise;\n const arrayBuffer = canvasToArrayBuffer(canvas, imageType);\n results.push(arrayBuffer);\n }\n\n return results;\n } finally {\n await destroyDocument?.(pdfDoc);\n }\n } catch (error) {\n throw new Error(`[@pdfme/converter] pdf2img failed: ${(error as Error).message}`);\n }\n}\n","import type { PDFDocumentProxy } from 'pdfjs-dist';\nimport { Size, pt2mm } from '@pdfme/common';\n\ninterface Environment {\n getDocument: (pdf: ArrayBuffer | Uint8Array) => Promise<PDFDocumentProxy>;\n destroyDocument?: (pdfDoc: PDFDocumentProxy) => Promise<void>;\n}\n\nexport interface Pdf2SizeOptions {\n scale?: number;\n}\n\nexport async function pdf2size(\n pdf: ArrayBuffer | Uint8Array,\n options: Pdf2SizeOptions = {},\n env: Environment,\n): Promise<Size[]> {\n const { scale = 1 } = options;\n const { getDocument, destroyDocument } = env;\n const pdfDoc = await getDocument(pdf);\n\n try {\n return await Promise.all(\n Array.from({ length: pdfDoc.numPages }, async (_, i) => {\n return await pdfDoc.getPage(i + 1).then((page) => {\n const { height, width } = page.getViewport({ scale, rotation: 0 });\n\n return { height: pt2mm(height), width: pt2mm(width) };\n });\n }),\n );\n } finally {\n await destroyDocument?.(pdfDoc);\n }\n}\n","import { PDFDocument } from '@pdfme/pdf-lib';\nimport { mm2pt } from '@pdfme/common';\nimport type { ImageType } from './types.js';\n\ninterface Img2PdfOptions {\n scale?: number;\n imageType?: ImageType;\n size?: { height: number; width: number }; // in millimeters\n margin?: [number, number, number, number]; // in millimeters [top, right, bottom, left]\n}\n\nfunction detectImageType(buffer: ArrayBuffer): 'jpeg' | 'png' | 'unknown' {\n const bytes = new Uint8Array(buffer);\n\n if (bytes.length >= 2 && bytes[0] === 0xff && bytes[1] === 0xd8) {\n return 'jpeg';\n }\n\n if (\n bytes.length >= 8 &&\n bytes[0] === 0x89 &&\n bytes[1] === 0x50 &&\n bytes[2] === 0x4e &&\n bytes[3] === 0x47 &&\n bytes[4] === 0x0d &&\n bytes[5] === 0x0a &&\n bytes[6] === 0x1a &&\n bytes[7] === 0x0a\n ) {\n return 'png';\n }\n\n return 'unknown';\n}\n\nexport async function img2pdf(\n imgs: ArrayBuffer[],\n options: Img2PdfOptions = {},\n): Promise<ArrayBuffer> {\n try {\n const { scale = 1, size, margin = [0, 0, 0, 0] } = options;\n\n if (!Array.isArray(imgs) || imgs.length === 0) {\n throw new Error('Input must be a non-empty array of image buffers');\n }\n\n const doc = await PDFDocument.create();\n for (const img of imgs) {\n try {\n let image;\n const type = detectImageType(img);\n\n if (type === 'jpeg') {\n image = await doc.embedJpg(img);\n } else if (type === 'png') {\n image = await doc.embedPng(img);\n } else {\n try {\n image = await doc.embedJpg(img);\n } catch {\n image = await doc.embedPng(img);\n }\n }\n\n const page = doc.addPage();\n const { width: imgWidth, height: imgHeight } = image.scale(scale);\n\n // Set page size based on size option or image dimensions\n const pageWidth = size ? mm2pt(size.width) : imgWidth;\n const pageHeight = size ? mm2pt(size.height) : imgHeight;\n page.setSize(pageWidth, pageHeight);\n\n // Convert margins from mm to points\n const [topMargin, rightMargin, bottomMargin, leftMargin] = margin.map(mm2pt);\n\n // Calculate available space for the image after applying margins\n const availableWidth = pageWidth - leftMargin - rightMargin;\n const availableHeight = pageHeight - topMargin - bottomMargin;\n\n // Calculate scaling to fit image within available space while maintaining aspect ratio\n const widthRatio = availableWidth / imgWidth;\n const heightRatio = availableHeight / imgHeight;\n const ratio = Math.min(widthRatio, heightRatio, 1); // Don't upscale images\n\n // Calculate final image dimensions and position\n const finalWidth = imgWidth * ratio;\n const finalHeight = imgHeight * ratio;\n const x = leftMargin + (availableWidth - finalWidth) / 2; // Center horizontally\n const y = bottomMargin + (availableHeight - finalHeight) / 2; // Center vertically\n\n page.drawImage(image, {\n x,\n y,\n width: finalWidth,\n height: finalHeight,\n });\n } catch (error) {\n throw new Error(`Failed to process image: ${(error as Error).message}`);\n }\n }\n const pdfUint8Array = await doc.save();\n // Create a new ArrayBuffer from the Uint8Array to ensure we return only ArrayBuffer\n const buffer = new ArrayBuffer(pdfUint8Array.byteLength);\n const view = new Uint8Array(buffer);\n view.set(pdfUint8Array);\n return buffer;\n } catch (error) {\n throw new Error(`[@pdfme/converter] img2pdf failed: ${(error as Error).message}`);\n }\n}\n"],"mappings":"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"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { ImageType } from './types.js';
|
|
2
|
+
interface Img2PdfOptions {
|
|
3
|
+
scale?: number;
|
|
4
|
+
imageType?: ImageType;
|
|
5
|
+
size?: {
|
|
6
|
+
height: number;
|
|
7
|
+
width: number;
|
|
8
|
+
};
|
|
9
|
+
margin?: [number, number, number, number];
|
|
10
|
+
}
|
|
11
|
+
export declare function img2pdf(imgs: ArrayBuffer[], options?: Img2PdfOptions): Promise<ArrayBuffer>;
|
|
12
|
+
export {};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { Pdf2ImgOptions } from './pdf2img.js';
|
|
2
|
+
import { Pdf2SizeOptions } from './pdf2size.js';
|
|
3
|
+
export declare const pdf2img: (pdf: ArrayBuffer | Uint8Array, options?: Pdf2ImgOptions) => Promise<ArrayBuffer[]>;
|
|
4
|
+
export declare const pdf2size: (pdf: ArrayBuffer | Uint8Array, options?: Pdf2SizeOptions) => Promise<{
|
|
5
|
+
height: number;
|
|
6
|
+
width: number;
|
|
7
|
+
}[]>;
|
|
8
|
+
export { img2pdf } from './img2pdf.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { n as pdf2size$1, r as pdf2img$1, t as img2pdf } from "./img2pdf-Ca1yX5Sv.js";
|
|
2
|
+
import * as pdfjsLib from "pdfjs-dist/legacy/build/pdf.mjs";
|
|
3
|
+
//#region src/pdfjs-worker.js?worker&url
|
|
4
|
+
var pdfjs_worker_default = "" + new URL("assets/pdfjs-worker-BpS0tFhy.js", import.meta.url).href;
|
|
5
|
+
//#endregion
|
|
6
|
+
//#region src/index.browser.ts
|
|
7
|
+
var clonePdfData = (pdf) => pdf instanceof Uint8Array ? new Uint8Array(pdf) : new Uint8Array(pdf);
|
|
8
|
+
var loadingTaskMap = /* @__PURE__ */ new WeakMap();
|
|
9
|
+
var getDocument = async (pdf) => {
|
|
10
|
+
if (typeof Worker !== "undefined" && pdfjsLib.GlobalWorkerOptions.workerSrc !== "" + new URL("assets/pdfjs-worker-BpS0tFhy.js", import.meta.url).href) pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjs_worker_default;
|
|
11
|
+
const loadingTask = pdfjsLib.getDocument({
|
|
12
|
+
data: clonePdfData(pdf),
|
|
13
|
+
isEvalSupported: false
|
|
14
|
+
});
|
|
15
|
+
const document = await loadingTask.promise;
|
|
16
|
+
loadingTaskMap.set(document, { destroy: () => loadingTask.destroy() });
|
|
17
|
+
return document;
|
|
18
|
+
};
|
|
19
|
+
var destroyDocument = async (document) => {
|
|
20
|
+
const loadingTask = loadingTaskMap.get(document);
|
|
21
|
+
loadingTaskMap.delete(document);
|
|
22
|
+
await loadingTask?.destroy();
|
|
23
|
+
};
|
|
24
|
+
function dataURLToArrayBuffer(dataURL) {
|
|
25
|
+
const base64String = dataURL.split(",")[1];
|
|
26
|
+
const byteString = atob(base64String);
|
|
27
|
+
const arrayBuffer = new ArrayBuffer(byteString.length);
|
|
28
|
+
const uintArray = new Uint8Array(arrayBuffer);
|
|
29
|
+
for (let i = 0; i < byteString.length; i++) uintArray[i] = byteString.charCodeAt(i);
|
|
30
|
+
return arrayBuffer;
|
|
31
|
+
}
|
|
32
|
+
var pdf2img = async (pdf, options = {}) => pdf2img$1(pdf, options, {
|
|
33
|
+
getDocument,
|
|
34
|
+
destroyDocument,
|
|
35
|
+
createCanvas: (width, height) => {
|
|
36
|
+
const canvas = document.createElement("canvas");
|
|
37
|
+
canvas.width = width;
|
|
38
|
+
canvas.height = height;
|
|
39
|
+
return canvas;
|
|
40
|
+
},
|
|
41
|
+
canvasToArrayBuffer: (canvas, imageType) => {
|
|
42
|
+
return dataURLToArrayBuffer(canvas.toDataURL(`image/${imageType}`));
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
var pdf2size = async (pdf, options = {}) => pdf2size$1(pdf, options, {
|
|
46
|
+
getDocument,
|
|
47
|
+
destroyDocument
|
|
48
|
+
});
|
|
49
|
+
//#endregion
|
|
50
|
+
export { img2pdf, pdf2img, pdf2size };
|
|
51
|
+
|
|
52
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/index.browser.ts"],"sourcesContent":["import * as pdfjsLib from 'pdfjs-dist/legacy/build/pdf.mjs';\nimport { pdf2img as _pdf2img, Pdf2ImgOptions } from './pdf2img.js';\nimport { pdf2size as _pdf2size, Pdf2SizeOptions } from './pdf2size.js';\nimport workerSrc from './pdfjs-worker.js?worker&url';\n\nconst clonePdfData = (pdf: ArrayBuffer | Uint8Array) =>\n pdf instanceof Uint8Array ? new Uint8Array(pdf) : new Uint8Array(pdf);\n\nconst loadingTaskMap = new WeakMap<object, { destroy: () => Promise<void> }>();\n\nconst getDocument = async (pdf: ArrayBuffer | Uint8Array) => {\n if (\n typeof Worker !== 'undefined' &&\n pdfjsLib.GlobalWorkerOptions.workerSrc !== workerSrc\n ) {\n pdfjsLib.GlobalWorkerOptions.workerSrc = workerSrc;\n }\n\n const loadingTask = pdfjsLib.getDocument({\n data: clonePdfData(pdf),\n isEvalSupported: false,\n });\n const document = await loadingTask.promise;\n loadingTaskMap.set(document, { destroy: () => loadingTask.destroy() });\n return document;\n};\n\nconst destroyDocument = async (document: object) => {\n const loadingTask = loadingTaskMap.get(document);\n loadingTaskMap.delete(document);\n await loadingTask?.destroy();\n};\n\nfunction dataURLToArrayBuffer(dataURL: string): ArrayBuffer {\n // Split out the actual base64 string from the data URL scheme\n const base64String = dataURL.split(',')[1];\n\n // Decode the Base64 string to get the binary data\n const byteString = atob(base64String);\n\n // Create a typed array from the binary string\n const arrayBuffer = new ArrayBuffer(byteString.length);\n const uintArray = new Uint8Array(arrayBuffer);\n\n for (let i = 0; i < byteString.length; i++) {\n uintArray[i] = byteString.charCodeAt(i);\n }\n\n return arrayBuffer;\n}\n\nexport const pdf2img = async (\n pdf: ArrayBuffer | Uint8Array,\n options: Pdf2ImgOptions = {},\n): Promise<ArrayBuffer[]> =>\n _pdf2img(pdf, options, {\n getDocument,\n destroyDocument,\n createCanvas: (width, height) => {\n const canvas = document.createElement('canvas');\n canvas.width = width;\n canvas.height = height;\n return canvas;\n },\n canvasToArrayBuffer: (canvas, imageType) => {\n // Using type assertion to handle the canvas method\n const dataUrl = (canvas as HTMLCanvasElement).toDataURL(`image/${imageType}`);\n return dataURLToArrayBuffer(dataUrl);\n },\n });\n\nexport const pdf2size = async (pdf: ArrayBuffer | Uint8Array, options: Pdf2SizeOptions = {}) =>\n _pdf2size(pdf, options, {\n getDocument,\n destroyDocument,\n });\n\nexport { img2pdf } from './img2pdf.js';\n"],"mappings":";;;;;;AAKA,IAAM,gBAAgB,QACpB,eAAe,aAAa,IAAI,WAAW,IAAI,GAAG,IAAI,WAAW,IAAI;AAEvE,IAAM,iCAAiB,IAAI,SAAmD;AAE9E,IAAM,cAAc,OAAO,QAAkC;AAC3D,KACE,OAAO,WAAW,eAClB,SAAS,oBAAoB,cAAA,KAAA,IAAA,IAAA,mCAAA,OAAA,KAAA,IAAA,CAAA,KAE7B,UAAS,oBAAoB,YAAY;CAG3C,MAAM,cAAc,SAAS,YAAY;EACvC,MAAM,aAAa,IAAI;EACvB,iBAAiB;EAClB,CAAC;CACF,MAAM,WAAW,MAAM,YAAY;AACnC,gBAAe,IAAI,UAAU,EAAE,eAAe,YAAY,SAAS,EAAE,CAAC;AACtE,QAAO;;AAGT,IAAM,kBAAkB,OAAO,aAAqB;CAClD,MAAM,cAAc,eAAe,IAAI,SAAS;AAChD,gBAAe,OAAO,SAAS;AAC/B,OAAM,aAAa,SAAS;;AAG9B,SAAS,qBAAqB,SAA8B;CAE1D,MAAM,eAAe,QAAQ,MAAM,IAAI,CAAC;CAGxC,MAAM,aAAa,KAAK,aAAa;CAGrC,MAAM,cAAc,IAAI,YAAY,WAAW,OAAO;CACtD,MAAM,YAAY,IAAI,WAAW,YAAY;AAE7C,MAAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,IACrC,WAAU,KAAK,WAAW,WAAW,EAAE;AAGzC,QAAO;;AAGT,IAAa,UAAU,OACrB,KACA,UAA0B,EAAE,KAE5B,UAAS,KAAK,SAAS;CACrB;CACA;CACA,eAAe,OAAO,WAAW;EAC/B,MAAM,SAAS,SAAS,cAAc,SAAS;AAC/C,SAAO,QAAQ;AACf,SAAO,SAAS;AAChB,SAAO;;CAET,sBAAsB,QAAQ,cAAc;AAG1C,SAAO,qBADU,OAA6B,UAAU,SAAS,YAAY,CACzC;;CAEvC,CAAC;AAEJ,IAAa,WAAW,OAAO,KAA+B,UAA2B,EAAE,KACzF,WAAU,KAAK,SAAS;CACtB;CACA;CACD,CAAC"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { Pdf2ImgOptions } from './pdf2img.js';
|
|
2
|
+
import { Pdf2SizeOptions } from './pdf2size.js';
|
|
3
|
+
export declare const pdf2img: (pdf: ArrayBuffer | Uint8Array, options?: Pdf2ImgOptions) => Promise<ArrayBuffer[]>;
|
|
4
|
+
export declare const pdf2size: (pdf: ArrayBuffer | Uint8Array, options?: Pdf2SizeOptions) => Promise<{
|
|
5
|
+
height: number;
|
|
6
|
+
width: number;
|
|
7
|
+
}[]>;
|
|
8
|
+
export { img2pdf } from './img2pdf.js';
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { n as pdf2size$1, r as pdf2img$1, t as img2pdf } from "./img2pdf-Ca1yX5Sv.js";
|
|
2
|
+
import * as pdfjsLib from "pdfjs-dist/legacy/build/pdf.mjs";
|
|
3
|
+
import { createCanvas } from "@napi-rs/canvas";
|
|
4
|
+
import { createRequire } from "node:module";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
6
|
+
//#region src/pdfjs.node.ts
|
|
7
|
+
var pdfJsDistRoot = dirname(createRequire(import.meta.url).resolve("pdfjs-dist/package.json"));
|
|
8
|
+
var getPdfJsWasmUrl = () => join(pdfJsDistRoot, "wasm/");
|
|
9
|
+
//#endregion
|
|
10
|
+
//#region src/index.node.ts
|
|
11
|
+
var clonePdfData = (pdf) => pdf instanceof Uint8Array ? new Uint8Array(pdf) : new Uint8Array(pdf);
|
|
12
|
+
var pdfJsWasmUrl = getPdfJsWasmUrl();
|
|
13
|
+
var pdf2img = async (pdf, options = {}) => {
|
|
14
|
+
return pdf2img$1(pdf, options, {
|
|
15
|
+
getDocument: (pdf) => pdfjsLib.getDocument({
|
|
16
|
+
data: clonePdfData(pdf),
|
|
17
|
+
isEvalSupported: false,
|
|
18
|
+
wasmUrl: pdfJsWasmUrl
|
|
19
|
+
}).promise,
|
|
20
|
+
createCanvas: (width, height) => createCanvas(width, height),
|
|
21
|
+
canvasToArrayBuffer: (canvas, imageType) => {
|
|
22
|
+
const nodeCanvas = canvas;
|
|
23
|
+
const buffer = imageType === "png" ? nodeCanvas.toBuffer("image/png") : nodeCanvas.toBuffer("image/jpeg");
|
|
24
|
+
const arrayBuffer = new ArrayBuffer(buffer.byteLength);
|
|
25
|
+
new Uint8Array(arrayBuffer).set(buffer);
|
|
26
|
+
return arrayBuffer;
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
};
|
|
30
|
+
var pdf2size = async (pdf, options = {}) => {
|
|
31
|
+
return pdf2size$1(pdf, options, { getDocument: (pdf) => pdfjsLib.getDocument({
|
|
32
|
+
data: clonePdfData(pdf),
|
|
33
|
+
isEvalSupported: false,
|
|
34
|
+
wasmUrl: pdfJsWasmUrl
|
|
35
|
+
}).promise });
|
|
36
|
+
};
|
|
37
|
+
//#endregion
|
|
38
|
+
export { img2pdf, pdf2img, pdf2size };
|
|
39
|
+
|
|
40
|
+
//# sourceMappingURL=index.node.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.node.js","names":[],"sources":["../src/pdfjs.node.ts","../src/index.node.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { dirname, join } from 'node:path';\n\nconst require = createRequire(import.meta.url);\nconst pdfJsDistRoot = dirname(require.resolve('pdfjs-dist/package.json'));\n\nexport const getPdfJsWasmUrl = (): string => join(pdfJsDistRoot, 'wasm/');\n","import * as pdfjsLib from 'pdfjs-dist/legacy/build/pdf.mjs';\nimport { Canvas, createCanvas } from '@napi-rs/canvas';\nimport { pdf2img as _pdf2img, Pdf2ImgOptions } from './pdf2img.js';\nimport { pdf2size as _pdf2size, Pdf2SizeOptions } from './pdf2size.js';\nimport { getPdfJsWasmUrl } from './pdfjs.node.js';\n\nconst clonePdfData = (pdf: ArrayBuffer | Uint8Array) =>\n pdf instanceof Uint8Array ? new Uint8Array(pdf) : new Uint8Array(pdf);\nconst pdfJsWasmUrl = getPdfJsWasmUrl();\n\nexport const pdf2img = async (\n pdf: ArrayBuffer | Uint8Array,\n options: Pdf2ImgOptions = {},\n): Promise<ArrayBuffer[]> => {\n return _pdf2img(pdf, options, {\n getDocument: (pdf) =>\n pdfjsLib.getDocument({\n data: clonePdfData(pdf),\n isEvalSupported: false,\n wasmUrl: pdfJsWasmUrl,\n }).promise,\n createCanvas: (width, height) => createCanvas(width, height) as unknown as HTMLCanvasElement,\n canvasToArrayBuffer: (canvas, imageType) => {\n const nodeCanvas = canvas as unknown as Canvas;\n const buffer =\n imageType === 'png' ? nodeCanvas.toBuffer('image/png') : nodeCanvas.toBuffer('image/jpeg');\n const arrayBuffer = new ArrayBuffer(buffer.byteLength);\n new Uint8Array(arrayBuffer).set(buffer);\n return arrayBuffer;\n },\n });\n};\n\nexport const pdf2size = async (pdf: ArrayBuffer | Uint8Array, options: Pdf2SizeOptions = {}) => {\n return _pdf2size(pdf, options, {\n getDocument: (pdf) =>\n pdfjsLib.getDocument({\n data: clonePdfData(pdf),\n isEvalSupported: false,\n wasmUrl: pdfJsWasmUrl,\n }).promise,\n });\n};\n\nexport { img2pdf } from './img2pdf.js';\n"],"mappings":";;;;;;AAIA,IAAM,gBAAgB,QADN,cAAc,OAAO,KAAK,IAAI,CACR,QAAQ,0BAA0B,CAAC;AAEzE,IAAa,wBAAgC,KAAK,eAAe,QAAQ;;;ACAzE,IAAM,gBAAgB,QACpB,eAAe,aAAa,IAAI,WAAW,IAAI,GAAG,IAAI,WAAW,IAAI;AACvE,IAAM,eAAe,iBAAiB;AAEtC,IAAa,UAAU,OACrB,KACA,UAA0B,EAAE,KACD;AAC3B,QAAO,UAAS,KAAK,SAAS;EAC5B,cAAc,QACZ,SAAS,YAAY;GACnB,MAAM,aAAa,IAAI;GACvB,iBAAiB;GACjB,SAAS;GACV,CAAC,CAAC;EACL,eAAe,OAAO,WAAW,aAAa,OAAO,OAAO;EAC5D,sBAAsB,QAAQ,cAAc;GAC1C,MAAM,aAAa;GACnB,MAAM,SACJ,cAAc,QAAQ,WAAW,SAAS,YAAY,GAAG,WAAW,SAAS,aAAa;GAC5F,MAAM,cAAc,IAAI,YAAY,OAAO,WAAW;AACtD,OAAI,WAAW,YAAY,CAAC,IAAI,OAAO;AACvC,UAAO;;EAEV,CAAC;;AAGJ,IAAa,WAAW,OAAO,KAA+B,UAA2B,EAAE,KAAK;AAC9F,QAAO,WAAU,KAAK,SAAS,EAC7B,cAAc,QACZ,SAAS,YAAY;EACnB,MAAM,aAAa,IAAI;EACvB,iBAAiB;EACjB,SAAS;EACV,CAAC,CAAC,SACN,CAAC"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { PDFDocumentProxy } from 'pdfjs-dist';
|
|
2
|
+
import type { ImageType } from './types.js';
|
|
3
|
+
interface Environment {
|
|
4
|
+
getDocument: (pdf: ArrayBuffer | Uint8Array) => Promise<PDFDocumentProxy>;
|
|
5
|
+
destroyDocument?: (pdfDoc: PDFDocumentProxy) => Promise<void>;
|
|
6
|
+
createCanvas: (width: number, height: number) => HTMLCanvasElement | OffscreenCanvas;
|
|
7
|
+
canvasToArrayBuffer: (canvas: HTMLCanvasElement | OffscreenCanvas, imageType: ImageType) => ArrayBuffer;
|
|
8
|
+
}
|
|
9
|
+
export interface Pdf2ImgOptions {
|
|
10
|
+
scale?: number;
|
|
11
|
+
imageType?: ImageType;
|
|
12
|
+
range?: {
|
|
13
|
+
start?: number;
|
|
14
|
+
end?: number;
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
export declare function pdf2img(pdf: ArrayBuffer | Uint8Array, options: Pdf2ImgOptions | undefined, env: Environment): Promise<ArrayBuffer[]>;
|
|
18
|
+
export {};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { PDFDocumentProxy } from 'pdfjs-dist';
|
|
2
|
+
import { Size } from '@pdfme/common';
|
|
3
|
+
interface Environment {
|
|
4
|
+
getDocument: (pdf: ArrayBuffer | Uint8Array) => Promise<PDFDocumentProxy>;
|
|
5
|
+
destroyDocument?: (pdfDoc: PDFDocumentProxy) => Promise<void>;
|
|
6
|
+
}
|
|
7
|
+
export interface Pdf2SizeOptions {
|
|
8
|
+
scale?: number;
|
|
9
|
+
}
|
|
10
|
+
export declare function pdf2size(pdf: ArrayBuffer | Uint8Array, options: Pdf2SizeOptions | undefined, env: Environment): Promise<Size[]>;
|
|
11
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const getPdfJsWasmUrl: () => string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pdfme/converter",
|
|
3
|
-
"version": "6.0.
|
|
3
|
+
"version": "6.0.4-dev.1",
|
|
4
4
|
"description": "TypeScript base PDF generator and React base UI. Open source, developed by the community, and completely free to use under the MIT license!",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pdf",
|
|
@@ -22,6 +22,10 @@
|
|
|
22
22
|
},
|
|
23
23
|
"type": "module",
|
|
24
24
|
"sideEffects": false,
|
|
25
|
+
"files": [
|
|
26
|
+
"dist",
|
|
27
|
+
"README.md"
|
|
28
|
+
],
|
|
25
29
|
"main": "./dist/index.js",
|
|
26
30
|
"module": "./dist/index.js",
|
|
27
31
|
"types": "./dist/index.d.ts",
|
package/src/img2pdf.ts
DELETED
|
@@ -1,110 +0,0 @@
|
|
|
1
|
-
import { PDFDocument } from '@pdfme/pdf-lib';
|
|
2
|
-
import { mm2pt } from '@pdfme/common';
|
|
3
|
-
import type { ImageType } from './types.js';
|
|
4
|
-
|
|
5
|
-
interface Img2PdfOptions {
|
|
6
|
-
scale?: number;
|
|
7
|
-
imageType?: ImageType;
|
|
8
|
-
size?: { height: number; width: number }; // in millimeters
|
|
9
|
-
margin?: [number, number, number, number]; // in millimeters [top, right, bottom, left]
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
function detectImageType(buffer: ArrayBuffer): 'jpeg' | 'png' | 'unknown' {
|
|
13
|
-
const bytes = new Uint8Array(buffer);
|
|
14
|
-
|
|
15
|
-
if (bytes.length >= 2 && bytes[0] === 0xff && bytes[1] === 0xd8) {
|
|
16
|
-
return 'jpeg';
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
if (
|
|
20
|
-
bytes.length >= 8 &&
|
|
21
|
-
bytes[0] === 0x89 &&
|
|
22
|
-
bytes[1] === 0x50 &&
|
|
23
|
-
bytes[2] === 0x4e &&
|
|
24
|
-
bytes[3] === 0x47 &&
|
|
25
|
-
bytes[4] === 0x0d &&
|
|
26
|
-
bytes[5] === 0x0a &&
|
|
27
|
-
bytes[6] === 0x1a &&
|
|
28
|
-
bytes[7] === 0x0a
|
|
29
|
-
) {
|
|
30
|
-
return 'png';
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
return 'unknown';
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
export async function img2pdf(
|
|
37
|
-
imgs: ArrayBuffer[],
|
|
38
|
-
options: Img2PdfOptions = {},
|
|
39
|
-
): Promise<ArrayBuffer> {
|
|
40
|
-
try {
|
|
41
|
-
const { scale = 1, size, margin = [0, 0, 0, 0] } = options;
|
|
42
|
-
|
|
43
|
-
if (!Array.isArray(imgs) || imgs.length === 0) {
|
|
44
|
-
throw new Error('Input must be a non-empty array of image buffers');
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
const doc = await PDFDocument.create();
|
|
48
|
-
for (const img of imgs) {
|
|
49
|
-
try {
|
|
50
|
-
let image;
|
|
51
|
-
const type = detectImageType(img);
|
|
52
|
-
|
|
53
|
-
if (type === 'jpeg') {
|
|
54
|
-
image = await doc.embedJpg(img);
|
|
55
|
-
} else if (type === 'png') {
|
|
56
|
-
image = await doc.embedPng(img);
|
|
57
|
-
} else {
|
|
58
|
-
try {
|
|
59
|
-
image = await doc.embedJpg(img);
|
|
60
|
-
} catch {
|
|
61
|
-
image = await doc.embedPng(img);
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
const page = doc.addPage();
|
|
66
|
-
const { width: imgWidth, height: imgHeight } = image.scale(scale);
|
|
67
|
-
|
|
68
|
-
// Set page size based on size option or image dimensions
|
|
69
|
-
const pageWidth = size ? mm2pt(size.width) : imgWidth;
|
|
70
|
-
const pageHeight = size ? mm2pt(size.height) : imgHeight;
|
|
71
|
-
page.setSize(pageWidth, pageHeight);
|
|
72
|
-
|
|
73
|
-
// Convert margins from mm to points
|
|
74
|
-
const [topMargin, rightMargin, bottomMargin, leftMargin] = margin.map(mm2pt);
|
|
75
|
-
|
|
76
|
-
// Calculate available space for the image after applying margins
|
|
77
|
-
const availableWidth = pageWidth - leftMargin - rightMargin;
|
|
78
|
-
const availableHeight = pageHeight - topMargin - bottomMargin;
|
|
79
|
-
|
|
80
|
-
// Calculate scaling to fit image within available space while maintaining aspect ratio
|
|
81
|
-
const widthRatio = availableWidth / imgWidth;
|
|
82
|
-
const heightRatio = availableHeight / imgHeight;
|
|
83
|
-
const ratio = Math.min(widthRatio, heightRatio, 1); // Don't upscale images
|
|
84
|
-
|
|
85
|
-
// Calculate final image dimensions and position
|
|
86
|
-
const finalWidth = imgWidth * ratio;
|
|
87
|
-
const finalHeight = imgHeight * ratio;
|
|
88
|
-
const x = leftMargin + (availableWidth - finalWidth) / 2; // Center horizontally
|
|
89
|
-
const y = bottomMargin + (availableHeight - finalHeight) / 2; // Center vertically
|
|
90
|
-
|
|
91
|
-
page.drawImage(image, {
|
|
92
|
-
x,
|
|
93
|
-
y,
|
|
94
|
-
width: finalWidth,
|
|
95
|
-
height: finalHeight,
|
|
96
|
-
});
|
|
97
|
-
} catch (error) {
|
|
98
|
-
throw new Error(`Failed to process image: ${(error as Error).message}`);
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
const pdfUint8Array = await doc.save();
|
|
102
|
-
// Create a new ArrayBuffer from the Uint8Array to ensure we return only ArrayBuffer
|
|
103
|
-
const buffer = new ArrayBuffer(pdfUint8Array.byteLength);
|
|
104
|
-
const view = new Uint8Array(buffer);
|
|
105
|
-
view.set(pdfUint8Array);
|
|
106
|
-
return buffer;
|
|
107
|
-
} catch (error) {
|
|
108
|
-
throw new Error(`[@pdfme/converter] img2pdf failed: ${(error as Error).message}`);
|
|
109
|
-
}
|
|
110
|
-
}
|
package/src/index.browser.ts
DELETED
|
@@ -1,78 +0,0 @@
|
|
|
1
|
-
import * as pdfjsLib from 'pdfjs-dist/legacy/build/pdf.mjs';
|
|
2
|
-
import { pdf2img as _pdf2img, Pdf2ImgOptions } from './pdf2img.js';
|
|
3
|
-
import { pdf2size as _pdf2size, Pdf2SizeOptions } from './pdf2size.js';
|
|
4
|
-
import workerSrc from './pdfjs-worker.js?worker&url';
|
|
5
|
-
|
|
6
|
-
const clonePdfData = (pdf: ArrayBuffer | Uint8Array) =>
|
|
7
|
-
pdf instanceof Uint8Array ? new Uint8Array(pdf) : new Uint8Array(pdf);
|
|
8
|
-
|
|
9
|
-
const loadingTaskMap = new WeakMap<object, { destroy: () => Promise<void> }>();
|
|
10
|
-
|
|
11
|
-
const getDocument = async (pdf: ArrayBuffer | Uint8Array) => {
|
|
12
|
-
if (
|
|
13
|
-
typeof Worker !== 'undefined' &&
|
|
14
|
-
pdfjsLib.GlobalWorkerOptions.workerSrc !== workerSrc
|
|
15
|
-
) {
|
|
16
|
-
pdfjsLib.GlobalWorkerOptions.workerSrc = workerSrc;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
const loadingTask = pdfjsLib.getDocument({
|
|
20
|
-
data: clonePdfData(pdf),
|
|
21
|
-
isEvalSupported: false,
|
|
22
|
-
});
|
|
23
|
-
const document = await loadingTask.promise;
|
|
24
|
-
loadingTaskMap.set(document, { destroy: () => loadingTask.destroy() });
|
|
25
|
-
return document;
|
|
26
|
-
};
|
|
27
|
-
|
|
28
|
-
const destroyDocument = async (document: object) => {
|
|
29
|
-
const loadingTask = loadingTaskMap.get(document);
|
|
30
|
-
loadingTaskMap.delete(document);
|
|
31
|
-
await loadingTask?.destroy();
|
|
32
|
-
};
|
|
33
|
-
|
|
34
|
-
function dataURLToArrayBuffer(dataURL: string): ArrayBuffer {
|
|
35
|
-
// Split out the actual base64 string from the data URL scheme
|
|
36
|
-
const base64String = dataURL.split(',')[1];
|
|
37
|
-
|
|
38
|
-
// Decode the Base64 string to get the binary data
|
|
39
|
-
const byteString = atob(base64String);
|
|
40
|
-
|
|
41
|
-
// Create a typed array from the binary string
|
|
42
|
-
const arrayBuffer = new ArrayBuffer(byteString.length);
|
|
43
|
-
const uintArray = new Uint8Array(arrayBuffer);
|
|
44
|
-
|
|
45
|
-
for (let i = 0; i < byteString.length; i++) {
|
|
46
|
-
uintArray[i] = byteString.charCodeAt(i);
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
return arrayBuffer;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
export const pdf2img = async (
|
|
53
|
-
pdf: ArrayBuffer | Uint8Array,
|
|
54
|
-
options: Pdf2ImgOptions = {},
|
|
55
|
-
): Promise<ArrayBuffer[]> =>
|
|
56
|
-
_pdf2img(pdf, options, {
|
|
57
|
-
getDocument,
|
|
58
|
-
destroyDocument,
|
|
59
|
-
createCanvas: (width, height) => {
|
|
60
|
-
const canvas = document.createElement('canvas');
|
|
61
|
-
canvas.width = width;
|
|
62
|
-
canvas.height = height;
|
|
63
|
-
return canvas;
|
|
64
|
-
},
|
|
65
|
-
canvasToArrayBuffer: (canvas, imageType) => {
|
|
66
|
-
// Using type assertion to handle the canvas method
|
|
67
|
-
const dataUrl = (canvas as HTMLCanvasElement).toDataURL(`image/${imageType}`);
|
|
68
|
-
return dataURLToArrayBuffer(dataUrl);
|
|
69
|
-
},
|
|
70
|
-
});
|
|
71
|
-
|
|
72
|
-
export const pdf2size = async (pdf: ArrayBuffer | Uint8Array, options: Pdf2SizeOptions = {}) =>
|
|
73
|
-
_pdf2size(pdf, options, {
|
|
74
|
-
getDocument,
|
|
75
|
-
destroyDocument,
|
|
76
|
-
});
|
|
77
|
-
|
|
78
|
-
export { img2pdf } from './img2pdf.js';
|
package/src/index.node.ts
DELETED
|
@@ -1,45 +0,0 @@
|
|
|
1
|
-
import * as pdfjsLib from 'pdfjs-dist/legacy/build/pdf.mjs';
|
|
2
|
-
import { Canvas, createCanvas } from '@napi-rs/canvas';
|
|
3
|
-
import { pdf2img as _pdf2img, Pdf2ImgOptions } from './pdf2img.js';
|
|
4
|
-
import { pdf2size as _pdf2size, Pdf2SizeOptions } from './pdf2size.js';
|
|
5
|
-
import { getPdfJsWasmUrl } from './pdfjs.node.js';
|
|
6
|
-
|
|
7
|
-
const clonePdfData = (pdf: ArrayBuffer | Uint8Array) =>
|
|
8
|
-
pdf instanceof Uint8Array ? new Uint8Array(pdf) : new Uint8Array(pdf);
|
|
9
|
-
const pdfJsWasmUrl = getPdfJsWasmUrl();
|
|
10
|
-
|
|
11
|
-
export const pdf2img = async (
|
|
12
|
-
pdf: ArrayBuffer | Uint8Array,
|
|
13
|
-
options: Pdf2ImgOptions = {},
|
|
14
|
-
): Promise<ArrayBuffer[]> => {
|
|
15
|
-
return _pdf2img(pdf, options, {
|
|
16
|
-
getDocument: (pdf) =>
|
|
17
|
-
pdfjsLib.getDocument({
|
|
18
|
-
data: clonePdfData(pdf),
|
|
19
|
-
isEvalSupported: false,
|
|
20
|
-
wasmUrl: pdfJsWasmUrl,
|
|
21
|
-
}).promise,
|
|
22
|
-
createCanvas: (width, height) => createCanvas(width, height) as unknown as HTMLCanvasElement,
|
|
23
|
-
canvasToArrayBuffer: (canvas, imageType) => {
|
|
24
|
-
const nodeCanvas = canvas as unknown as Canvas;
|
|
25
|
-
const buffer =
|
|
26
|
-
imageType === 'png' ? nodeCanvas.toBuffer('image/png') : nodeCanvas.toBuffer('image/jpeg');
|
|
27
|
-
const arrayBuffer = new ArrayBuffer(buffer.byteLength);
|
|
28
|
-
new Uint8Array(arrayBuffer).set(buffer);
|
|
29
|
-
return arrayBuffer;
|
|
30
|
-
},
|
|
31
|
-
});
|
|
32
|
-
};
|
|
33
|
-
|
|
34
|
-
export const pdf2size = async (pdf: ArrayBuffer | Uint8Array, options: Pdf2SizeOptions = {}) => {
|
|
35
|
-
return _pdf2size(pdf, options, {
|
|
36
|
-
getDocument: (pdf) =>
|
|
37
|
-
pdfjsLib.getDocument({
|
|
38
|
-
data: clonePdfData(pdf),
|
|
39
|
-
isEvalSupported: false,
|
|
40
|
-
wasmUrl: pdfJsWasmUrl,
|
|
41
|
-
}).promise,
|
|
42
|
-
});
|
|
43
|
-
};
|
|
44
|
-
|
|
45
|
-
export { img2pdf } from './img2pdf.js';
|
package/src/pdf2img.ts
DELETED
|
@@ -1,73 +0,0 @@
|
|
|
1
|
-
import type { PDFDocumentProxy } from 'pdfjs-dist';
|
|
2
|
-
import type { ImageType } from './types.js';
|
|
3
|
-
|
|
4
|
-
interface Environment {
|
|
5
|
-
getDocument: (pdf: ArrayBuffer | Uint8Array) => Promise<PDFDocumentProxy>;
|
|
6
|
-
destroyDocument?: (pdfDoc: PDFDocumentProxy) => Promise<void>;
|
|
7
|
-
createCanvas: (width: number, height: number) => HTMLCanvasElement | OffscreenCanvas;
|
|
8
|
-
canvasToArrayBuffer: (
|
|
9
|
-
canvas: HTMLCanvasElement | OffscreenCanvas,
|
|
10
|
-
imageType: ImageType,
|
|
11
|
-
) => ArrayBuffer;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export interface Pdf2ImgOptions {
|
|
15
|
-
scale?: number;
|
|
16
|
-
imageType?: ImageType;
|
|
17
|
-
range?: {
|
|
18
|
-
start?: number;
|
|
19
|
-
end?: number;
|
|
20
|
-
};
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export async function pdf2img(
|
|
24
|
-
pdf: ArrayBuffer | Uint8Array,
|
|
25
|
-
options: Pdf2ImgOptions = {},
|
|
26
|
-
env: Environment,
|
|
27
|
-
): Promise<ArrayBuffer[]> {
|
|
28
|
-
try {
|
|
29
|
-
const { scale = 1, imageType = 'jpeg', range = {} } = options;
|
|
30
|
-
const { start = 0, end = Infinity } = range;
|
|
31
|
-
|
|
32
|
-
const { getDocument, destroyDocument, createCanvas, canvasToArrayBuffer } = env;
|
|
33
|
-
|
|
34
|
-
const pdfDoc = await getDocument(pdf);
|
|
35
|
-
try {
|
|
36
|
-
const numPages = pdfDoc.numPages;
|
|
37
|
-
|
|
38
|
-
const startPage = Math.max(start + 1, 1);
|
|
39
|
-
const endPage = Math.min(end + 1, numPages);
|
|
40
|
-
|
|
41
|
-
const results: ArrayBuffer[] = [];
|
|
42
|
-
|
|
43
|
-
for (let pageNum = startPage; pageNum <= endPage; pageNum++) {
|
|
44
|
-
const page = await pdfDoc.getPage(pageNum);
|
|
45
|
-
const viewport = page.getViewport({ scale });
|
|
46
|
-
|
|
47
|
-
const canvas = createCanvas(viewport.width, viewport.height);
|
|
48
|
-
if (!canvas) {
|
|
49
|
-
throw new Error('Failed to create canvas');
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
const context = canvas.getContext('2d') as CanvasRenderingContext2D;
|
|
53
|
-
if (!context) {
|
|
54
|
-
throw new Error('Failed to get canvas context');
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
await page.render({
|
|
58
|
-
canvas: canvas as unknown as HTMLCanvasElement,
|
|
59
|
-
canvasContext: context,
|
|
60
|
-
viewport,
|
|
61
|
-
}).promise;
|
|
62
|
-
const arrayBuffer = canvasToArrayBuffer(canvas, imageType);
|
|
63
|
-
results.push(arrayBuffer);
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
return results;
|
|
67
|
-
} finally {
|
|
68
|
-
await destroyDocument?.(pdfDoc);
|
|
69
|
-
}
|
|
70
|
-
} catch (error) {
|
|
71
|
-
throw new Error(`[@pdfme/converter] pdf2img failed: ${(error as Error).message}`);
|
|
72
|
-
}
|
|
73
|
-
}
|