Created
June 10, 2026 20:41
-
-
Save autioch/d47f06909372d10d4a51424448f1ab0d to your computer and use it in GitHub Desktop.
png2pdf.js
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
| // merge-png-to-pdf.js | |
| // | |
| // Instalacja: | |
| // npm install pdf-lib | |
| // | |
| // Uruchomienie: | |
| // node merge-png-to-pdf.js output.pdf image1.png image2.png image3.png | |
| import { existsSync, readFileSync, writeFileSync } from 'fs'; | |
| import { extname } from 'path'; | |
| import { PDFDocument } from 'pdf-lib'; | |
| async function mergePngToPdf(outputFile, inputFiles) { | |
| if (!inputFiles.length) { | |
| throw new Error('Brak plików PNG.'); | |
| } | |
| const pdfDoc = await PDFDocument.create(); | |
| for (const file of inputFiles) { | |
| if (!existsSync(file)) { | |
| throw new Error(`Plik nie istnieje: ${file}`); | |
| } | |
| const ext = extname(file).toLowerCase(); | |
| if (ext !== '.png') { | |
| throw new Error(`Nieobsługiwany format: ${file}`); | |
| } | |
| const imageBytes = readFileSync(file); | |
| const pngImage = await pdfDoc.embedPng(imageBytes); | |
| const width = pngImage.width; | |
| const height = pngImage.height; | |
| const page = pdfDoc.addPage([width, height]); | |
| page.drawImage(pngImage, { | |
| x: 0, | |
| y: 0, | |
| width, | |
| height, | |
| }); | |
| console.log(`Dodano: ${file} (${width}x${height})`); | |
| } | |
| const pdfBytes = await pdfDoc.save(); | |
| writeFileSync(outputFile, pdfBytes); | |
| console.log(`\nPDF zapisany: ${outputFile}`); | |
| } | |
| async function main() { | |
| const [, , outputFile, ...inputFiles] = process.argv; | |
| if (!outputFile || inputFiles.length === 0) { | |
| console.log(` | |
| Użycie: | |
| node merge-png-to-pdf.js output.pdf image1.png image2.png ... | |
| Przykład: | |
| node merge-png-to-pdf.js dokument.pdf 1.png 2.png 3.png | |
| `); | |
| process.exit(1); | |
| } | |
| try { | |
| await mergePngToPdf(outputFile, inputFiles); | |
| } catch (err) { | |
| console.error('Błąd:', err.message); | |
| process.exit(1); | |
| } | |
| } | |
| main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment