
Code: Select all
MathJax to PDF
This is some text with MathJax: \(E = mc^2\)
Generate PDF
async function generatePDF() {
const mathContainer = document.getElementById("math-container");
// Step 1: Render MathJax in the container
await MathJax.typesetPromise([mathContainer]);
// Step 2: Remove the raw LaTeX source (e.g., \(E = mc^2\)) after rendering
// MathJax inserts the rendered output in an element with class 'mjx-chtml'
const renderedMath = mathContainer.querySelector('.mjx-chtml');
if (renderedMath) {
// Clear the container and only append the rendered output
mathContainer.innerHTML = '';
mathContainer.appendChild(renderedMath); // Keep only the rendered content
}
// Step 3: Convert the container to an image using html2canvas
const canvas = await html2canvas(mathContainer, {
backgroundColor: "#ffffff", // Set background color to white for clarity
scale: 2, // Higher scale for better resolution
});
const imgData = canvas.toDataURL("image/png");
// Step 4: Add the image to the PDF using jsPDF
const { jsPDF } = window.jspdf;
const pdf = new jsPDF();
pdf.text("MathJax in PDF Example", 10, 10);
pdf.addImage(imgData, "PNG", 10, 20, 180, canvas.height / canvas.width * 180); // Scale to fit
pdf.save("mathjax_fixed.pdf");
}