npm i pdf-lib
app.component.html
1 2 3 4 5 6 7 8 |
<h2>Select Images</h2> <input type="file" (change)="onFileChange($event)" multiple accept="image/*" /> <div *ngFor="let img of imagePreviews" class="image-preview"> <img [src]="img" /> </div> <button (click)="exportToPDF()">Export to PDF</button> |
app.component.ts
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 58 59 60 61 62 63 64 |
import { Component } from '@angular/core'; import { PDFDocument, rgb } from 'pdf-lib'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { imagePreviews: string[] = []; imageFiles: File[] = []; onFileChange(event: any) { this.imagePreviews = []; this.imageFiles = []; const files = event.target.files; if (files && files.length) { for (let file of files) { this.imageFiles.push(file); const reader = new FileReader(); reader.onload = (e: any) => this.imagePreviews.push(e.target.result); reader.readAsDataURL(file); } } } async exportToPDF() { const pdfDoc = await PDFDocument.create(); for (const file of this.imageFiles) { const imageBytes = await file.arrayBuffer(); let image; let dims; if (file.type === 'image/png') { image = await pdfDoc.embedPng(imageBytes); } else { image = await pdfDoc.embedJpg(imageBytes); } dims = image.scale(1); const page = pdfDoc.addPage([dims.width, dims.height]); page.drawImage(image, { x: 0, y: 0, width: dims.width, height: dims.height }); } const pdfBytes = await pdfDoc.save(); const blob = new Blob([pdfBytes], { type: 'application/pdf' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'images.pdf'; a.click(); URL.revokeObjectURL(url); } } |
app.component.css
1 2 3 4 5 6 7 8 |
.image-preview { margin: 10px 0; } .image-preview img { max-width: 100%; height: auto; border: 1px solid #ccc; } |