`;
let scheduleTableHtml = `Pmt # Date Payment ($) Principal ($) Interest ($) Extra ($) Total Principal ($) Balance ($) Cum. Int. ($) `;
schedule.forEach(row => {
scheduleTableHtml += `
${row.paymentNumber} ${row.paymentDate} ${lat_formatCurrency(row.paymentAmount)}
${lat_formatCurrency(row.principalPaid)} ${lat_formatCurrency(row.interestPaid)}
${lat_formatCurrency(row.extraPaidThisMonth)} ${lat_formatCurrency(row.totalPrincipalThisPayment)}
${lat_formatCurrency(row.remainingBalance)} ${lat_formatCurrency(row.cumulativeInterest)}
`;
});
const totalRow = schedule[schedule.length -1]; // Last row has cumulative interest. Principal paid is input principal.
scheduleTableHtml += `
Totals
${lat_formatCurrency(summary.totalPaidWithExtras)}
${lat_formatCurrency(summary.totalInterestWithExtras)}
${lat_formatCurrency(inputs.principal)}
`;
const interpretationNote_pdf = `This schedule estimates loan repayment. Extra payments shorten terms and reduce total interest. Actual lender figures may vary slightly.`;
pdfContentEl.innerHTML = `
${scheduleTableHtml}
Loan Amortization Schedule Report
${summaryHtmlPdf}
Amortization Table
Note: ${interpretationNote_pdf}
`;
document.body.appendChild(pdfContentEl);
html2canvas(pdfContentEl, { scale: 2, useCORS: true, logging:true, width: pdfContentEl.scrollWidth, windowHeight: pdfContentEl.scrollHeight }).then(canvas => {
const imgData = canvas.toDataURL('image/png');
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = pdf.internal.pageSize.getHeight();
const pageMargin = 30;
const contentWidth = pdfWidth - 2 * pageMargin;
const singlePageCanvasHeightEquivalent = (pdfHeight - 2 * pageMargin) * (canvas.width / contentWidth);
let numPages = Math.ceil(canvas.height / singlePageCanvasHeightEquivalent);
for (let i = 0; i < numPages; i++) {
if (i > 0) pdf.addPage();
let sourceY = i * singlePageCanvasHeightEquivalent;
let sourceHeight = Math.min(singlePageCanvasHeightEquivalent, canvas.height - sourceY);
const tempCanvas = document.createElement('canvas');
tempCanvas.width = canvas.width;
tempCanvas.height = sourceHeight;
const ctx = tempCanvas.getContext('2d');
// Draw the relevant slice of the full content canvas onto the temporary page canvas
ctx.drawImage(canvas, 0, sourceY, canvas.width, sourceHeight, 0, 0, canvas.width, sourceHeight);
const pageImgData = tempCanvas.toDataURL('image/png');
// Calculate the height of this image slice when fit to PDF page width
const pageImgHeight = (sourceHeight * contentWidth) / canvas.width;
pdf.addImage(pageImgData, 'PNG', pageMargin, pageMargin, contentWidth, pageImgHeight, undefined, 'FAST');
}
pdf.save('Loan_Amortization_Schedule.pdf');
if(document.body.contains(pdfContentEl)) document.body.removeChild(pdfContentEl);
}).catch(err => {
console.error("LAT PDF Error:", err); alert("Error generating PDF. See console.");
if(document.body.contains(pdfContentEl)) document.body.removeChild(pdfContentEl);
});
}
document.addEventListener('DOMContentLoaded', function() {
// Set default values for quicker testing
const principalEl = document.getElementById('lat_loanPrincipal');
if (principalEl && !principalEl.value) principalEl.value = '100000';
const rateEl = document.getElementById('lat_annualInterestRate');
if (rateEl && !rateEl.value) rateEl.value = '5';
const durationEl = document.getElementById('lat_loanTermDuration');
if (durationEl && !durationEl.value) durationEl.value = '10'; // Default 10 years
const startDateEl = document.getElementById('lat_loanStartDate');
if (startDateEl && !startDateEl.value) {
startDateEl.value = new Date().toISOString().split('T')[0];
}
if (!document.getElementById('lat_loanPrincipal')) {
console.error("Critical input 'lat_loanPrincipal' not found.");
}
});
