You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MathJax经html2canvas转PNG后生成PDF时公式显示加粗/重叠的问题解决咨询

MathJax经html2canvas转PNG后生成PDF时公式显示加粗/重叠的问题解决咨询

嘿各位大佬,我现在在做把MathJax渲染的公式转成PDF的功能,结果发现生成的PDF里公式要么看起来像是加粗了,要么就像是两个表达式重叠在了一起,实在搞不懂哪里出问题了。

公式显示异常的效果

以下是我目前的实现代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MathJax to PDF</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.4.0/jspdf.umd.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
</head>
<body>
    <div id="math-container" style="font-size: 20px;">
        This is some text with MathJax: \(E = mc^2\)
    </div>
    <button onclick="generatePDF()">Generate PDF</button>

    <script>
        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");
        }
    </script>
</body>
</html>

有没有大佬能帮我看看这个问题该怎么解决呀?

备注:内容来源于stack exchange,提问作者Aren Vanyan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 14:23:01