npm i sharp
npm i pdf-lib
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 |
const fs = require('fs'); const path = require('path'); const sharp = require('sharp'); const { PDFDocument } = require('pdf-lib'); const imagesFolder = './images'; const outputPdfPath = './output.pdf'; const supportedExtensions = ['.jpg', '.jpeg', '.png', '.webp']; (async () => { const files = fs.readdirSync(imagesFolder) .filter(file => supportedExtensions.includes(path.extname(file).toLowerCase())); const pdfDoc = await PDFDocument.create(); for (const file of files) { const imagePath = path.join(imagesFolder, file); const ext = path.extname(file).toLowerCase(); const imageBuffer = fs.readFileSync(imagePath); // Resize image (optional) const resizedBuffer = await sharp(imageBuffer) .resize({ width: 595, height: 842, fit: 'contain', background: 'white' }) .toFormat('jpeg') // Force to jpeg to avoid format errors .toBuffer(); let embeddedImage; if (ext === '.png') { embeddedImage = await pdfDoc.embedPng(resizedBuffer); } else { embeddedImage = await pdfDoc.embedJpg(resizedBuffer); // Use embedJpg for jpg/jpeg/webp } const page = pdfDoc.addPage([595, 842]); const { width, height } = embeddedImage.scale(1); page.drawImage(embeddedImage, { x: (595 - width) / 2, y: (842 - height) / 2, width, height }); console.log(`Added: ${file}`); } const pdfBytes = await pdfDoc.save(); fs.writeFileSync(outputPdfPath, pdfBytes); console.log(`✅ PDF saved as: ${outputPdfPath}`); })(); |