-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
225 lines (201 loc) · 5.63 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
const fs = require("fs");
const sharp = require("sharp");
const {
getDocument,
OPS,
GlobalWorkerOptions,
} = require("pdfjs-dist/legacy/build/pdf.js");
const pdfjsWorker = require("pdfjs-dist/legacy/build/pdf.worker.entry");
const { jsPDF } = require("jspdf");
const doDelay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function sharpsFromPdf(src, options = {}) {
const { sharpOptions, delay = -1, handler = () => {} } = options;
GlobalWorkerOptions.workerSrc = options.workerSrc ? pdfjsWorker : "";
// doc
const docTask = getDocument(src);
docTask.onProgress = ({ loaded, total }) => {
if (loaded <= total) handler("loading", { loaded, total });
};
const doc = await docTask.promise;
const pages = doc._pdfInfo.numPages;
handler("loaded", { pages });
// images
const images = [];
for (let p = 0; p < pages; p++) {
const page = await doc.getPage(p + 1);
const ops = await page.getOperatorList();
const pageImages = ops.fnArray.length;
for (let i = 0; i < pageImages; i++) {
try {
if (
ops.fnArray[i] === OPS.paintJpegXObject ||
ops.fnArray[i] === OPS.paintImageXObject ||
ops.fnArray[i] === OPS.paintInlineImageXObject
) {
const name = ops.argsArray[i][0];
const img = await page.objs.get(name);
const { width, height, kind } = img;
const size = img.data.length;
const channels = size / width / height;
const image = sharp(img.data, {
...sharpOptions,
raw: { width, height, channels },
});
const item = {
name,
kind,
width,
height,
channels,
size,
image,
pages,
pageIndex: p,
pageImages,
pageImageIndex: i,
};
images.push(item);
handler("image", item);
if (delay >= 0) await doDelay(delay);
} else {
handler("skip", {
pages,
pageIndex: p,
pageImages,
pageImageIndex: i,
});
}
} catch (error) {
handler("error", {
pages,
pageIndex: p,
pageImages,
pageImageIndex: i,
error,
});
}
}
}
handler("done", images);
return images;
}
function isSharp(image) {
return image && typeof image.metadata === "function";
}
async function sharpsToPdf(images, output, options = {}) {
const {
pdfOptions: po = {},
imageOptions: io = {},
autoSize = false,
init,
} = options;
const doc = new jsPDF({ ...po, unit: "pt" });
// init handler
init && init({ doc, pages, pageWidth, pageHeight });
let pageWidth = doc.internal.pageSize.getWidth();
let pageHeight = doc.internal.pageSize.getHeight();
const pages = images.length;
doc.deletePage(1);
for (let index = 0; index < images.length; index++) {
let item = images[index];
if (isSharp(item)) item = { image: item };
const { image, options: _io = {} } = item;
if (!isSharp(image)) continue;
const o = { ...io, ..._io };
const fit = _io.fit || (io.fit && _io.fit !== false);
const margin = o.margin || 0;
// imageData
const { data, info } = await image.toBuffer({ resolveWithObject: true });
// addPage
const pageFormat = autoSize
? [info.width + margin, info.height + margin]
: po.format || "a4";
const orientation = autoSize
? info.width > info.height
? "l"
: "p"
: po.orientation || "p";
doc.addPage(pageFormat, orientation);
// page width/height
if (autoSize) {
pageWidth = info.width + margin;
pageHeight = info.height + margin;
}
// image format
const format = o.format || (await image.metadata()).format.toUpperCase();
if (!format) continue;
if (o.format) image.toFormat(o.format.toLowerCase());
// image width/height
let width, height;
if (autoSize) {
width = info.width;
height = info.height;
} else {
const scale = fit
? Math.min(pageWidth / info.width, pageHeight / info.height)
: 1;
width = o.width || info.width * scale;
height = o.height || info.height * scale;
if (fit && o.margin) {
width -= o.margin * 2;
height -= o.margin * 2;
}
}
// image x/y
const x = o.x || (pageWidth - width) / 2;
const y = o.y || (pageHeight - height) / 2;
// page handler
let addImage =
o.handler &&
o.handler({
doc,
pages,
pageWidth,
pageHeight,
index,
image,
options: o,
imageData: data,
format,
x,
y,
width,
height,
});
if (addImage instanceof Promise) addImage = await addImage;
if (addImage !== false) {
doc.addImage(
data,
format,
x,
y,
width,
height,
o.alias,
o.compression || "NONE",
o.rotation || 0
);
}
}
if (typeof output === "string") {
// write PDF file
// return doc.save(output, { returnPromise: true }).then(() => {
// return { size: fs.statSync(output).size };
// });
const buffer = Buffer.from(doc.output("arraybuffer"));
return new Promise((resolve, reject) => {
fs.writeFile(output, buffer, (err) => {
if (err) reject(err);
else resolve({ size: buffer.length });
});
});
} else if (typeof output?.type === "string") {
return doc.output(output.type, output.options);
} else {
return doc.output();
}
}
module.exports = {
sharpsFromPdf,
sharpsToPdf,
};