Spaces:
Running
Running
| 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); | |