59 lines
1.6 KiB
TypeScript
59 lines
1.6 KiB
TypeScript
import jsPDF from 'jspdf';
|
|
import html2canvas from 'html2canvas';
|
|
|
|
export const exportAsPdf = async (elementId: string, fileName: string, action: 'preview' | 'download'): Promise<void> => {
|
|
const input = document.getElementById(elementId);
|
|
if (!input) {
|
|
console.error(`Element with id ${elementId} not found.`);
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const canvas = await html2canvas(input, {
|
|
scale: 2, // Higher scale improves quality
|
|
useCORS: true,
|
|
logging: false,
|
|
});
|
|
|
|
const imgData = canvas.toDataURL('image/png');
|
|
|
|
// A4 dimensions in mm: 210 x 297
|
|
const pdf = new jsPDF({
|
|
orientation: 'portrait',
|
|
unit: 'mm',
|
|
format: 'a4',
|
|
});
|
|
|
|
const pdfWidth = pdf.internal.pageSize.getWidth();
|
|
const pdfHeight = pdf.internal.pageSize.getHeight();
|
|
const canvasWidth = canvas.width;
|
|
const canvasHeight = canvas.height;
|
|
|
|
// Calculate the aspect ratio
|
|
const ratio = canvasWidth / canvasHeight;
|
|
let imgWidth = pdfWidth;
|
|
let imgHeight = imgWidth / ratio;
|
|
|
|
// If the calculated height is greater than the page height, scale down
|
|
if (imgHeight > pdfHeight) {
|
|
imgHeight = pdfHeight;
|
|
imgWidth = imgHeight * ratio;
|
|
}
|
|
|
|
const x = (pdfWidth - imgWidth) / 2;
|
|
const y = 0;
|
|
|
|
pdf.addImage(imgData, 'PNG', x, y, imgWidth, imgHeight);
|
|
|
|
if (action === 'download') {
|
|
pdf.save(`${fileName}.pdf`);
|
|
} else {
|
|
const pdfBlob = pdf.output('blob');
|
|
const pdfUrl = URL.createObjectURL(pdfBlob);
|
|
window.open(pdfUrl, '_blank');
|
|
URL.revokeObjectURL(pdfUrl);
|
|
}
|
|
} catch (error) {
|
|
console.error("Error generating PDF:", error);
|
|
}
|
|
}; |