from flask import Flask, request, jsonify, send_file, render_template_string from flask_cors import CORS import os import subprocess import tempfile import shutil from pathlib import Path app = Flask(__name__) CORS(app) def read_file(filepath): """Read index.html content""" try: with open(filepath, 'r', encoding='utf-8') as f: return f.read() except FileNotFoundError: return "

Frontend not found

Please ensure index.html is in the same directory as app.py

" @app.route('/') def index(): """Serve the frontend HTML""" html_content = read_file('index.html') return render_template_string(html_content) @app.route('/docs') def docs(): """API documentation""" docs_html = ''' LaTeX Compiler API Documentation

LaTeX Compiler API Documentation

Endpoints

POST /compile

Compile LaTeX code to PDF

Request Methods:

  • File Upload: multipart/form-data with 'file' field (.tex file)
  • JSON: application/json with {"code": "LaTeX source code"}

Success Response:

Content-Type: application/pdf
PDF file binary data

Error Response:

{
  "error": "Compilation failed",
  "log": "LaTeX error log details..."
}

GET /

Serve the web frontend interface

GET /docs

Display this API documentation

Example Usage

cURL - JSON Request:

curl -X POST http://localhost:7860/compile \\
  -H "Content-Type: application/json" \\
  -d '{"code": "\\\\documentclass{article}\\\\begin{document}Hello\\\\end{document}"}' \\
  --output output.pdf

cURL - File Upload:

curl -X POST http://localhost:7860/compile \\
  -F "file=@document.tex" \\
  --output output.pdf

Python Example:

import requests

latex_code = r"""
\\documentclass{article}
\\begin{document}
Hello from Python!
\\end{document}
"""

response = requests.post(
    'http://localhost:7860/compile',
    json={'code': latex_code}
)

if response.status_code == 200:
    with open('output.pdf', 'wb') as f:
        f.write(response.content)
else:
    print(response.json())

⚠️ Notes

← Back to Compiler
''' return docs_html @app.route('/compile', methods=['POST']) def compile_latex(): """Compile LaTeX code to PDF""" temp_dir = None try: # Create temporary directory temp_dir = tempfile.mkdtemp() tex_file = os.path.join(temp_dir, 'document.tex') pdf_file = os.path.join(temp_dir, 'document.pdf') # Get LaTeX code from request latex_code = None if request.is_json: data = request.get_json() latex_code = data.get('code', '') elif 'file' in request.files: file = request.files['file'] if file.filename == '': return jsonify({'error': 'No file selected'}), 400 latex_code = file.read().decode('utf-8') else: return jsonify({'error': 'No LaTeX code provided. Send JSON with "code" field or upload .tex file'}), 400 if not latex_code: return jsonify({'error': 'Empty LaTeX code'}), 400 # Write LaTeX code to file with open(tex_file, 'w', encoding='utf-8') as f: f.write(latex_code) # Detect which engine to use based on packages engine = 'pdflatex' if '\\usepackage{fontspec}' in latex_code or '\\setmainfont' in latex_code: engine = 'xelatex' # Compile with appropriate LaTeX engine result = subprocess.run( [engine, '-interaction=nonstopmode', '-output-directory', temp_dir, tex_file], capture_output=True, text=True, timeout=30 ) # Check if PDF was created if os.path.exists(pdf_file): return send_file(pdf_file, mimetype='application/pdf', as_attachment=True, download_name='compiled.pdf') else: # Compilation failed, return error log log_file = os.path.join(temp_dir, 'document.log') error_log = '' if os.path.exists(log_file): with open(log_file, 'r', encoding='utf-8', errors='ignore') as f: error_log = f.read() return jsonify({ 'error': f'Compilation failed with {engine}', 'log': error_log or result.stderr or result.stdout }), 400 except subprocess.TimeoutExpired: return jsonify({'error': 'Compilation timeout (30s limit exceeded)'}), 408 except Exception as e: return jsonify({'error': f'Server error: {str(e)}'}), 500 finally: # Clean up temporary files if temp_dir and os.path.exists(temp_dir): try: shutil.rmtree(temp_dir) except Exception: pass if __name__ == '__main__': app.run(host='0.0.0.0', port=7860, debug=False)