-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathindex.ts
More file actions
205 lines (174 loc) · 5.99 KB
/
index.ts
File metadata and controls
205 lines (174 loc) · 5.99 KB
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
import fs from 'fs';
import path from 'path';
import crypto from 'crypto';
import { spawn } from 'child_process';
import { glob } from 'glob';
import rimraf from 'rimraf';
export interface Options {
bin?: string;
format: 'png' | 'jpeg' | 'tiff' | 'ps' | 'eps' | 'pdf' | 'svg';
antialias?: 'default' | 'none' | 'gray' | 'subpixel' | 'fast' | 'good' | 'best';
range?: { f?: number, l?: number };
filter?: 'odd' | 'even';
singlefile?: boolean;
resolution?: number | { x: number, y: number };
scale?: number | { x: number, y: number };
crop?: { x?: number, y?: number, W?: number, H?: number, sz?: number };
cropbox?: boolean;
mono?: boolean;
gray?: boolean;
transparent?: boolean;
level2?: boolean;
level3?: boolean;
originPageSizes?: boolean;
icc?: string;
jpegopt?: string;
paper?: string | { w: number, h: number };
nocrop?: boolean;
expand?: boolean;
noshrink?: boolean;
nocenter?: boolean;
duplex?: boolean;
ownerPassword?: string;
userPassword?: string;
}
const DEFAULT_BIN = 'pdftocairo';
const getOptionArgs = (options: Options): string[] => {
const args: string[] = [];
args.push(`-${options.format}`);
if (options.range) {
if (typeof options.range.f === 'number') args.push(`-f ${options.range.f}`);
if (typeof options.range.l === 'number') args.push(`-l ${options.range.l}`);
}
if (options.filter) {
const arg = options.filter === 'odd' ? '-o' : '-e';
args.push(arg);
}
if (options.singlefile) args.push('-singlefile');
if (options.resolution) {
if (typeof options.resolution === 'number') {
args.push(`-r ${options.resolution}`);
} else {
if (typeof options.resolution.x === 'number') {
args.push(`-rx ${options.resolution.x}`);
}
if (typeof options.resolution.y === 'number') {
args.push(`-ry ${options.resolution.y}`);
}
}
}
if (options.scale) {
if (typeof options.scale === 'number') {
args.push(`-scale-to ${options.scale}`);
} else {
if (typeof options.scale.x === 'number') {
args.push(`-scale-to-x ${options.scale.x}`);
}
if (typeof options.scale.y === 'number') {
args.push(`-scale-to-y ${options.scale.y}`);
}
}
}
if (options.paper) {
if (typeof options.paper === 'string') {
args.push(`-paper ${options.paper}`);
} else {
if (typeof options.paper.w === 'number') {
args.push(`-paperw ${options.paper.w}`);
}
if (typeof options.paper.h === 'number') {
args.push(`-paperh ${options.paper.h}`);
}
}
}
if (options.crop) {
if (options.crop.x) args.push(`-x ${options.crop.x}`);
if (options.crop.y) args.push(`-y ${options.crop.y}`);
if (options.crop.H) args.push(`-H ${options.crop.H}`);
if (options.crop.W) args.push(`-W ${options.crop.W}`);
if (options.crop.sz) args.push(`-sz ${options.crop.sz}`);
}
if (options.cropbox) args.push('-cropbox');
if (options.mono) args.push('-mono');
if (options.gray) args.push('-gray');
if (options.antialias) args.push(`-antialias ${options.antialias}`);
if (options.level2) args.push('-level2');
if (options.level3) args.push('-level3');
if (options.transparent) args.push('-transp');
if (options.originPageSizes) args.push('-origpagesizes');
if (options.icc) args.push(`-icc ${options.icc}`);
if (options.jpegopt) args.push(`-jpegopt ${options.jpegopt}`);
if (options.nocrop) args.push('-nocrop');
if (options.expand) args.push('-expand');
if (options.noshrink) args.push('-noshrink');
if (options.nocenter) args.push('-nocenter');
if (options.duplex) args.push('-duplex');
if (options.ownerPassword) args.push(`-opw ${options.ownerPassword}`);
if (options.userPassword) args.push(`-upw ${options.userPassword}`);
args.push('-q');
return args;
};
const findFiles = async (pattern: string): Promise<string[]> => glob(pattern);
class PDFToCairo {
private bin: string;
private args: string[] = [];
private input: string | Buffer;
private tmps: string[] = [];
public constructor(file: string | Buffer, options: Options) {
this.input = file;
this.bin = options.bin || process.env.PDFTOCAIRO_PATH || DEFAULT_BIN;
this.args.push(...getOptionArgs(options));
}
// overload signature
public async output(): Promise<Buffer[]>;
public async output(outputFile: string): Promise<null>;
public async output(outputFile?: string): Promise<Buffer[] | null> {
// '-' means reading PDF file from stdin
const inputPath = typeof this.input === 'string' ? this.input : '-';
const outputPath = outputFile || path.join(await this.makeTempDir(), 'result');
this.args.push(inputPath, outputPath);
const child = spawn(this.bin, this.args, { shell: true });
if (typeof this.input !== 'string') {
child.stdin.setDefaultEncoding('utf-8');
child.stdin.write(this.input);
child.stdin.end();
}
return new Promise((resolve, reject) => {
let errMsg: string;
child.stderr.on('data', (data) => {
errMsg = `${data}`;
});
child.on('close', async (code) => {
if (code !== 0) {
reject(new Error(`[code ${code}] ${errMsg || 'unknown error'}`));
return;
}
if (typeof outputFile === 'string') {
resolve(null);
} else {
const files = await findFiles(`${outputPath}*`);
const buffers = await Promise.all(
files.sort().map((file) => fs.promises.readFile(file)),
);
this.cleanUpTemp();
resolve(buffers);
}
});
});
}
private async makeTempDir(): Promise<string> {
const uniqueId = crypto.randomBytes(16).toString('hex');
const outputPath = path.join('/tmp', uniqueId);
await fs.promises.mkdir(outputPath);
this.tmps.push(outputPath);
return outputPath;
}
private cleanUpTemp(): void {
try {
this.tmps.forEach((f) => rimraf.sync(f));
} catch (error) {
// ignore
}
}
}
export const input = (file: string | Buffer, options: Options) => new PDFToCairo(file, options);