Browse Source

fix: 继续调试pdf

大侠咬超人 2 days ago
parent
commit
fb7c484989
1 changed files with 37 additions and 4 deletions
  1. 37 4
      app/Services/ExamPdfExportService.php

+ 37 - 4
app/Services/ExamPdfExportService.php

@@ -1316,14 +1316,47 @@ class ExamPdfExportService
                 );
             }
 
-            // 修改渲染脚本,确保在DOMContentLoaded后立即渲染(不使用setTimeout延迟)
+            // 【关键修复】移除原有的DOMContentLoaded异步渲染,改为同步立即渲染
+            // Chrome headless的--print-to-pdf不会等待DOMContentLoaded后的JS执行
+            // 所以我们需要在</body>前添加同步渲染代码
+
+            // 1. 移除原有的DOMContentLoaded监听器(包括setTimeout延迟)
             $html = preg_replace(
-                '/setTimeout\s*\(\s*renderMath\s*,\s*\d+\s*\)\s*;?\s*setTimeout\s*\(\s*renderMath\s*,\s*\d+\s*\)\s*;?/i',
-                '/* 移除延迟渲染,PDF生成时立即渲染 */',
+                '/<script[^>]*>\s*document\.addEventListener\s*\(\s*[\'"]DOMContentLoaded[\'"]\s*,\s*function\s*\(\)\s*\{[\s\S]*?renderMathInElement[\s\S]*?\}\s*\)\s*;?\s*<\/script>/i',
+                '<!-- KaTeX DOMContentLoaded removed, using sync render -->',
                 $html
             );
 
-            Log::info('ExamPdfExportService: 已将KaTeX CDN资源替换为内联资源');
+            // 2. 在</body>前添加同步渲染脚本
+            $syncRenderScript = '
+<script type="text/javascript">
+// 同步执行KaTeX渲染(PDF生成专用)
+(function() {
+    if (typeof renderMathInElement === "function") {
+        try {
+            renderMathInElement(document.body, {
+                delimiters: [
+                    {left: "$$", right: "$$", display: true},
+                    {left: "$", right: "$", display: false},
+                    {left: "\\\\(", right: "\\\\)", display: false},
+                    {left: "\\\\[", right: "\\\\]", display: true}
+                ],
+                throwOnError: false,
+                strict: false,
+                trust: true
+            });
+            console.log("KaTeX sync render completed");
+        } catch(e) {
+            console.error("KaTeX render error:", e);
+        }
+    }
+})();
+</script>
+</body>';
+
+            $html = str_ireplace('</body>', $syncRenderScript, $html);
+
+            Log::info('ExamPdfExportService: KaTeX已改为同步渲染模式');
 
         } catch (\Exception $e) {
             Log::warning('ExamPdfExportService: 内联资源处理失败,保留原始HTML', [