The fraction is already in its simplest form as the Greatest Common Divisor (GCD) is 1.
`;
} else {
stepsHtml = `
1. The original fraction is ${originalNum} / ${originalDen}.
2. We found the Greatest Common Divisor (GCD) of ${originalNum} and ${originalDen} is ${gcd}.
3. We divided both the numerator and the denominator by the GCD (${gcd}):
- Numerator: ${originalNum} ÷ ${gcd} = ${simplifiedNum}
- Denominator: ${originalDen} ÷ ${gcd} = ${simplifiedDen}
`;
}
resultsContent.innerHTML = `
Simplified Fraction
${simplifiedNum} / ${simplifiedDen}
Simplification Steps
${stepsHtml}
`;
// Fade in the results container for a smooth user experience
resultsContainer.style.display = 'block';
setTimeout(() => {
resultsContainer.style.opacity = 1;
}, 10); // A small timeout to allow the display property to apply
};
/**
* Generates and triggers the download of a PDF with the results.
*/
const downloadPDF = () => {
// Ensure jsPDF is loaded
if (typeof window.jspdf === 'undefined') {
errorMessage.textContent = 'PDF library is not loaded. Please try again.';
console.error('jsPDF is not defined.');
return;
}
const { jsPDF } = window.jspdf;
// Get the current results from the DOM to ensure consistency
const originalNum = parseInt(numeratorInput.value, 10);
const originalDen = parseInt(denominatorInput.value, 10);
const commonDivisor = findGcd(originalNum, originalDen);
const simplifiedNum = originalNum / commonDivisor;
const simplifiedDen = originalDen / commonDivisor;
const doc = new jsPDF();
// Add Title
doc.setFontSize(22);
doc.text("Fraction Simplification Report", 105, 20, { align: 'center' });
doc.setFontSize(12);
doc.setTextColor(100);
doc.text(`Generated on: ${new Date().toLocaleDateString('en-US')}`, 105, 28, { align: 'center' });
// Use autoTable for a professional, tabular layout
doc.autoTable({
startY: 40,
head: [['Item', 'Value']],
body: [
['Original Fraction', `${originalNum} / ${originalDen}`],
['Greatest Common Divisor (GCD)', `${commonDivisor}`],
['Simplified Numerator', `${simplifiedNum}`],
['Simplified Denominator', `${simplifiedDen}`],
],
theme: 'grid',
headStyles: {
fillColor: [37, 99, 235], // blue-600
textColor: 255,
fontStyle: 'bold',
},
styles: {
cellPadding: 3,
fontSize: 12,
},
alternateRowStyles: {
fillColor: [243, 244, 246] // gray-100
},
});
// Add a final result summary section
const finalY = doc.lastAutoTable.finalY + 15;
doc.setFontSize(16);
doc.setFont('helvetica', 'bold');
doc.text("Final Simplified Result", 14, finalY);
doc.setFontSize(26);
doc.setTextColor(37, 99, 235); // blue-600
doc.text(`${simplifiedNum} / ${simplifiedDen}`, 105, finalY + 12, { align: 'center' });
// Save the PDF
doc.save('Fraction_Simplification_Report.pdf');
};
// --- 3. EVENT LISTENERS ---
// Attach event listeners to the buttons.
simplifyBtn.addEventListener('click', calculateAndDisplay);
downloadPdfBtn.addEventListener('click', downloadPDF);
});