Created
February 4, 2026 08:22
-
-
Save aspose-com-gists/54781af4a044ae258427bc1a67cd1625 to your computer and use it in GitHub Desktop.
How to Convert LaTeX to PNG Using Aspose.Tex in Python via .NET
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
| import io | |
| from flask import Flask, request, send_file, abort | |
| import aspose.tex as tex | |
| from aspose.tex.render import ImageRenderOptions | |
| app = Flask(__name__) | |
| @app.route("/render", methods=["POST"]) | |
| def render_latex(): | |
| """ | |
| This example demonstrates how to convert LaTeX to PNG using Aspose.TeX in Python. | |
| It receives a LaTeX string via POST and returns the rendered PNG image. | |
| """ | |
| latex = request.form.get("latex") | |
| if not latex: | |
| abort(400, "Missing LaTeX content in the request.") | |
| try: | |
| # Load the LaTeX source into a TeXDocument | |
| document = tex.TeXDocument(latex) | |
| # Set rendering options: PNG format, 300 DPI, modest margins | |
| options = ImageRenderOptions() | |
| options.image_format = tex.ImageFormat.PNG | |
| options.dpi = 300 | |
| options.margin = tex.Margin(10, 10, 10, 10) | |
| # Render to a byte array | |
| png_bytes = document.render_to_bytes(options) | |
| # Return the PNG as an HTTP response | |
| return send_file( | |
| io.BytesIO(png_bytes), | |
| mimetype="image/png", | |
| as_attachment=False, | |
| download_name="formula.png" | |
| ) | |
| except Exception as e: | |
| # Provide a clear error message for troubleshooting | |
| abort(500, f"Rendering failed: {str(e)}") | |
| 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