Here's a basic example assuming you're using jspdf
and optionally html2canvas
if you're working with HTML content.
1. Install jsPDF (and html2canvas if needed)
bashnpm install jspdf html2canvas
2. Component Code (TypeScript)
tsimport { Component } from '@angular/core';
import jsPDF from 'jspdf';
@Component({
selector: 'app-download-pdf',
templateUrl: './download-pdf.component.html'
})
export class DownloadPdfComponent {
dataArray = [
{ title: 'Item 1', description: 'Description 1' },
{ title: 'Item 2', description: 'Description 2' },
{ title: 'Item 3', description: 'Description 3' }
];
async downloadPDF() {
const doc = new jsPDF();
this.dataArray.forEach((item, index) => {
const yPosition = 10 + (index * 30); // space between items
doc.text(`Title: ${item.title}`, 10, yPosition);
doc.text(`Description: ${item.description}`, 10, yPosition + 10);
// Optional: Add image
// const imgData = 'data:image/png;base64,...'; // use real image data
// doc.addImage(imgData, 'PNG', 10, yPosition + 20, 50, 30);
});
doc.save('sample.pdf');
}
}
3. HTML Template
html<button (click)="downloadPDF()">Download PDF</button>
To Add Image Dynamically from URL or Base64:
If you're loading an image for each item:
tsloadImage(url: string): Promise<string> {
return new Promise((resolve) => {
const img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d')!;
ctx.drawImage(img, 0, 0);
resolve(canvas.toDataURL('image/png'));
};
img.src = url;
});
}
And in your loop:
tsfor (const [index, item] of this.dataArray.entries()) {
const yPosition = 10 + (index * 50);
doc.text(`Title: ${item.title}`, 10, yPosition);
if (item.imageUrl) {
const imgData = await this.loadImage(item.imageUrl);
doc.addImage(imgData, 'PNG', 10, yPosition + 10, 50, 30);
}
}
Great! If you're getting HTML content via document.getElementById(...)
and want to convert it into a PDF using jsPDF, the typical approach is to use html2canvas
to convert the HTML element to a canvas image, and then insert that image into the PDF.
Here’s a complete working example for Angular:
✅ Step-by-step Guide
1. Install Dependencies
bashnpm install jspdf html2canvas
2. Component HTML
html<!-- This is the content you want to convert to PDF -->
<div id="pdf-content">
<h1>{{ title }}</h1>
<p>{{ description }}</p>
</div>
<!-- Button to download the PDF -->
<button (click)="downloadPDF()">Download PDF</button>
3. Component TypeScript
tsimport { Component } from '@angular/core';
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';
@Component({
selector: 'app-download-pdf',
templateUrl: './download-pdf.component.html'
})
export class DownloadPdfComponent {
title = 'My PDF Title';
description = 'This is some content that will be converted into a PDF.';
async downloadPDF() {
const element = document.getElementById('pdf-content');
if (!element) {
console.error('Element not found');
return;
}
const canvas = await html2canvas(element);
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF({
orientation: 'portrait',
unit: 'mm',
format: 'a4'
});
const imgProps = pdf.getImageProperties(imgData);
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
pdf.save('download.pdf');
}
}
🔄 To Do This for an Array of Items (One at a Time)
If you want to dynamically render each item from an array into the same HTML element (one at a time), and save each as a separate page in the PDF:
Example:
tsdataArray = [
{ title: 'Item 1', description: 'Description 1' },
{ title: 'Item 2', description: 'Description 2' },
{ title: 'Item 3', description: 'Description 3' }
];
async downloadAllToPDF() {
const pdf = new jsPDF();
for (let i = 0; i < this.dataArray.length; i++) {
const item = this.dataArray[i];
// Update your HTML content dynamically
this.title = item.title;
this.description = item.description;
// Wait for the DOM to update
await new Promise(resolve => setTimeout(resolve, 100));
const element = document.getElementById('pdf-content');
if (!element) continue;
const canvas = await html2canvas(element);
const imgData = canvas.toDataURL('image/png');
const imgProps = pdf.getImageProperties(imgData);
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
if (i > 0) pdf.addPage();
pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
}
pdf.save('all-items.pdf');
}
No comments:
Post a Comment