`;
slipContentDiv.innerHTML = slipHtml;
// Update the detach/return form elements
returnTripName.textContent = data.tripName;
returnTripDate.textContent = data.date;
};
generateBtn.addEventListener("click", function() {
generateSlip();
showTab(1); // Switch to Dashboard
});
// --- PDF Download ---
pdfBtn.addEventListener("click", function() {
var jsPDF = window.jspdf.jsPDF;
var tripSlug = tripNameInput.value.replace(/[^a-zA-Z0-9\s]/g, '').replace(/\s/g, '_').substring(0, 30) || 'Field_Trip';
var fileName = `${tripSlug}_Permission_Slip.pdf`;
html2canvas(exportArea, {
scale: 2,
useCORS: true,
backgroundColor: '#ffffff'
}).then(function(canvas) {
var imgData = canvas.toDataURL('image/png');
var doc = new jsPDF({
orientation: 'p',
unit: 'pt',
format: 'letter'
});
var pdfWidth = doc.internal.pageSize.getWidth();
var pdfHeight = doc.internal.pageSize.getHeight();
var imgProps = doc.getImageProperties(imgData);
var imgWidth = imgProps.width;
var imgHeight = imgProps.height;
var margin = 40;
var usableWidth = pdfWidth - (2 * margin);
var ratio = usableWidth / imgWidth;
var scaledHeight = imgHeight * ratio;
// --- FIXED PAGINATION LOGIC ---
var usablePageHeight = pdfHeight - (2 * margin); // Height available between top/bottom margins
var heightLeft = scaledHeight;
var position = 0; // Tracks the cumulative Y offset on the canvas
while (heightLeft > 0) {
// Draw the scaled image (which is too tall) starting at a negative Y position
// The position tracks how much of the canvas has already been drawn/offset.
// The margin is applied consistently to the drawing area (Y position relative to page top).
doc.addImage(imgData, 'PNG', margin, position + margin, usableWidth, scaledHeight);
heightLeft -= usablePageHeight;
position -= usablePageHeight; // Move the canvas view up for the next page
if (heightLeft > 0) {
doc.addPage();
}
}
// --- END FIXED PAGINATION LOGIC ---
doc.save(fileName);
}).catch(function(err) {
console.error("PST PDF Error:", err);
// alert("An error occurred while generating the PDF."); // Per spec
});
});
// --- Initial Load ---
generateSlip();
showTab(0);
});
