from flask import Flask, request, render_template_string, send_file import markdown import imgkit import os import traceback from io import BytesIO app = Flask(__name__) # Use a directory within the app's working directory to avoid permission issues TEMP_DIR = os.path.join(os.getcwd(), "temp") # Create temporary directory if it doesn't exist try: os.makedirs(TEMP_DIR, exist_ok=True) except Exception as e: print(f"Error creating temp directory: {e}") @app.route("/", methods=["GET", "POST"]) def index(): preview_html = None download_available = False download_type = "png" error_message = None markdown_text = request.form.get("markdown_text", "") if request.method == "POST" else "" if request.method == "POST" and markdown_text: try: # Convert Markdown to HTML html_content = markdown.markdown(markdown_text, extensions=['fenced_code', 'tables']) # Prepare HTML with basic styling full_html = f"""
{html_content} """ # Save HTML to a temporary file html_path = os.path.join(TEMP_DIR, "output.html") with open(html_path, "w", encoding="utf-8") as f: f.write(full_html) # Generate preview HTML preview_html = full_html download_available = True download_type = request.form.get("download_type", "png") if "download" in request.form: if download_type == "html": return send_file( html_path, as_attachment=True, download_name="output.html", mimetype="text/html" ) else: # PNG # Convert HTML to PNG using imgkit png_path = os.path.join(TEMP_DIR, "output.png") imgkit.from_string(full_html, png_path, options={"quiet": ""}) return send_file( png_path, as_attachment=True, download_name="output.png", mimetype="image/png" ) except Exception as e: error_message = f"Error processing request: {str(e)}" print(f"Error: {traceback.format_exc()}") return render_template_string("""{{ error_message }}
{% endif %} {% if preview_html %}