`;
pdfPreview.innerHTML = letterHTML;
}
/**
* Generates and downloads a PDF of the letter preview.
*/
async function downloadPDF() {
const { jsPDF } = window.jspdf;
const content = document.getElementById('pdf-preview');
const downloadButton = document.getElementById('download-pdf-btn');
if (!content) {
console.error("PDF content area not found.");
return;
}
// Show loading state on button
downloadButton.textContent = 'Generating...';
downloadButton.disabled = true;
try {
const canvas = await html2canvas(content, {
scale: 2, // Improve resolution
useCORS: true,
});
const imgData = canvas.toDataURL('image/png');
// A4 page dimensions in pixels at 96 DPI: 794x1123.
// A4 in points: 595 x 842. We'll use this for jsPDF.
const pdf = new jsPDF({
orientation: 'p',
unit: 'pt',
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 to fit the content onto the PDF page
const ratio = Math.min(pdfWidth / canvasWidth, pdfHeight / canvasHeight);
const imgWidth = canvasWidth * ratio * 0.9; // Using 90% of width for margin
const imgHeight = canvasHeight * ratio * 0.9;
const marginX = (pdfWidth - imgWidth) / 2;
const marginY = (pdfHeight - imgHeight) / 2;
pdf.addImage(imgData, 'PNG', marginX, marginY, imgWidth, imgHeight);
pdf.save('Cease-and-Desist-Letter.pdf');
} catch (error) {
console.error("Error generating PDF:", error);
alert("An error occurred while generating the PDF. Please try again.");
} finally {
// Restore button state
downloadButton.textContent = 'Download PDF';
downloadButton.disabled = false;
}
}
// --- Event Listeners ---
tabButtons.forEach(button => {
button.addEventListener('click', () => {
currentTab = parseInt(button.dataset.tab);
updateDisplay();
});
});
nextBtn.addEventListener('click', () => {
if (currentTab < totalTabs) {
currentTab++;
updateDisplay();
}
});
prevBtn.addEventListener('click', () => {
if (currentTab > 1) {
currentTab--;
updateDisplay();
}
});
if (downloadPdfBtn) {
downloadPdfBtn.addEventListener('click', downloadPDF);
}
// --- Initial State ---
updateDisplay();
});
