| import os, subprocess, re, shutil |
|
|
| def render_pdf(latex_code, output_path): |
| |
| match = re.search(r"(\\documentclass.*\\end\{document\})", latex_code, re.DOTALL) |
| if match: |
| clean_code = match.group(1).strip() |
| else: |
| |
| match_block = re.search(r"```(?:latex)?\n?(.*?)\n?```", latex_code, re.DOTALL) |
| clean_code = match_block.group(1).strip() if match_block else latex_code.strip() |
|
|
| |
| if "\\end{document}" not in clean_code: |
| clean_code += "\n\\end{document}" |
|
|
| tex_filename = "final_output.tex" |
| with open(tex_filename, "w") as f: |
| f.write(clean_code) |
|
|
| try: |
| |
| |
| result = subprocess.run( |
| ["pdflatex", "-interaction=nonstopmode", tex_filename], |
| check=False, |
| stdout=subprocess.PIPE, |
| stderr=subprocess.PIPE |
| ) |
|
|
| if os.path.exists("final_output.pdf"): |
| shutil.move("final_output.pdf", output_path) |
| return True |
| else: |
| |
| print(f"LaTeX StdOut: {result.stdout.decode()[:500]}") |
| return False |
| |
| except Exception as e: |
| print(f"❌ System Error: {str(e)}") |
| return False |