Created
February 5, 2026 11:45
-
-
Save aspose-com-gists/c7692febc5ebee1d3069b712e000176d to your computer and use it in GitHub Desktop.
How to Convert LaTeX to PNG in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Complete working example: Flask app that renders LaTeX to PNG | |
| import io | |
| from flask import Flask, request, send_file, abort | |
| from aspose.tex import TexDocument, ImageFormat, RenderOptions | |
| app = Flask(__name__) | |
| def render_latex_to_png(latex_string): | |
| """ | |
| Renders the given LaTeX string to a PNG image and returns a BytesIO stream. | |
| """ | |
| try: | |
| # Initialize TexDocument with the LaTeX source | |
| tex_doc = TexDocument(latex_string) | |
| # Optional: customize rendering options | |
| options = RenderOptions() | |
| options.margin = 4 # small margin around the equation | |
| options.dpi = 200 | |
| options.background_color = (255, 255, 255) # white background | |
| # Render to an in‑memory stream | |
| img_stream = io.BytesIO() | |
| tex_doc.render_to_stream(img_stream, ImageFormat.Png, options) | |
| img_stream.seek(0) # reset pointer for reading | |
| return img_stream | |
| except Exception as e: | |
| # Log the exception or handle it as needed | |
| raise RuntimeError(f"Rendering failed: {e}") | |
| @app.route("/latex-to-png", methods=["POST"]) | |
| def latex_to_png(): | |
| """ | |
| Flask route that accepts a LaTeX string via POST and returns a PNG image. | |
| """ | |
| latex = request.form.get("latex") | |
| if not latex: | |
| abort(400, "Parameter 'latex' is required.") | |
| try: | |
| png_stream = render_latex_to_png(latex) | |
| return send_file(png_stream, mimetype="image/png") | |
| except RuntimeError as err: | |
| abort(500, str(err)) | |
| if __name__ == "__main__": | |
| # Run the Flask development server | |
| app.run(host="0.0.0.0", port=5000, debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment