from flask import Flask, request, render_template_string, send_file import markdown import imgkit import os from io import BytesIO import base64 app = Flask(__name__) # Ensure a temporary directory exists for saving files os.makedirs("temp", exist_ok=True) @app.route("/", methods=["GET", "POST"]) def index(): preview_html = None download_available = False download_type = "png" file_path = None if request.method == "POST": markdown_text = request.form.get("markdown_text") download_type = request.form.get("download_type", "png") if markdown_text: # 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 = "temp/output.html" with open(html_path, "w") as f: f.write(full_html) # Generate preview HTML preview_html = full_html download_available = True if download_type == "html": file_path = html_path else: # PNG # Convert HTML to PNG using imgkit png_path = "temp/output.png" imgkit.from_string(full_html, png_path, options={"quiet": ""}) file_path = png_path # Handle download if requested if "download" in request.form: return send_file( file_path, as_attachment=True, download_name=f"output.{download_type}", mimetype="text/html" if download_type == "html" else "image/png" ) return render_template_string("""