File size: 1,568 Bytes
3dcc61d
 
 
 
 
 
 
9d9a493
 
3dcc61d
 
 
 
 
 
9d9a493
3dcc61d
 
 
 
 
9d9a493
 
 
 
3dcc61d
 
 
 
 
 
 
9d9a493
ba31655
3dcc61d
9d9a493
 
 
3dcc61d
ba31655
 
 
 
 
 
 
 
 
 
 
 
3dcc61d
 
 
 
 
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
import PDFDocument from 'pdfkit';
import fs from 'fs';
import path from 'path';

const optionDefinitions = [
	{name: 'output', alias: 'o', type: String},
	{name: 'input', alias: 'i', type: String},
	{name: 'width', alias: 'w', type: Number},
	{name: 'height', alias: 'h', type: Number},
];

import commandLineArgs from 'command-line-args';
const options = commandLineArgs(optionDefinitions);

const doc = new PDFDocument({
	autoFirstPage: false,
});

const output = options.output || 'out/output.pdf';
doc.pipe(fs.createWriteStream(output));

const input = options.input || 'out';
const isFolder = fs.lstatSync(input).isDirectory();
const files = isFolder ? fs.readdirSync(input) : [input];
console.log('Reading', files.length, 'from', input, '... ');

for (const file of files) {
	if (
		file.endsWith('.jpg') ||
		file.endsWith('.png') ||
		file.endsWith('.jpeg')
	) {
		const imgPath = isFolder ? path.join(input, file) : file;
		const img = doc.openImage(imgPath);

		const pageWidth = options.width || 612;
		const pageHeight = options.height || 792;
		doc.addPage({size: [pageWidth, pageHeight], margin: 0});

		const imgWidth = img.width;
		const imgHeight = img.height;

		const scaleFactor = Math.min(pageWidth / imgWidth, pageHeight / imgHeight);

		const scaledWidth = imgWidth * scaleFactor;
		const scaledHeight = imgHeight * scaleFactor;

		const x = (pageWidth - scaledWidth) / 2;
		const y = (pageHeight - scaledHeight) / 2;

		doc.image(imgPath, x, y, {width: scaledWidth, height: scaledHeight});
	}
}

doc.end();
console.log('PDF saved to', output);