-
-
Save renatamarques97/ce8561b3f61e4d6a569644cc890bba9f to your computer and use it in GitHub Desktop.
Convert images in a folder to PDF
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| toPdf.js | |
| Gather all JPG, JPEG and PNG images in a folder and convert them to | |
| individual files in an output folder named after the source folder name | |
| $ node toPdf.js [source/folder/path] | |
| The script will, within the current directory, create a folder with the | |
| same name as the input folder and add all generated PDF files to it. | |
| */ | |
| const path = require('path'); | |
| const fs = require('fs'); | |
| const PDFDocument = require('pdfkit'); | |
| if (process.argv.length < 3) { | |
| console.error('[ERROR] Expected the path of invoices source folder as argument.'); | |
| process.exit(1); | |
| } | |
| const sourceFolderPath = process.argv[2]; | |
| const outputFolderName = sourceFolderPath.split('/').pop(); | |
| const outputFolderPath = path.join(__dirname, outputFolderName); | |
| !fs.existsSync(outputFolderPath) && fs.mkdirSync(outputFolderPath); | |
| fs.readdir(sourceFolderPath, function (err, files) { | |
| if (err) { | |
| console.error(`[ERROR] Unable to scan directory: ${err}`); | |
| process.exit(1); | |
| } | |
| files.forEach(function (file) { | |
| if (!(file.match(/\.(jpg|jpeg|png)$/i) || []).length) { | |
| return console.info(`[INFO] File ${file} not converted due to unsupported type`); | |
| } | |
| const doc = new PDFDocument({ | |
| margin: 20, | |
| size: [500, 800] | |
| }); | |
| const outputFileName = file.replace(/\.(jpg|jpeg|png)$/i, ''); | |
| doc.pipe(fs.createWriteStream(`${outputFolderName}/${outputFileName}.pdf`)); | |
| doc.image(`${sourceFolderPath}/${file}`, { | |
| fit: [460, 760], | |
| align: 'left', | |
| valign: 'top', | |
| dpi: 200 | |
| }); | |
| doc.end(); | |
| console.info(`[INFO] Successfuly converted ${sourceFolderPath}/${file} to ${outputFolderPath}/${outputFileName}.pdf`); | |
| }); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment