Skip to content

Server

render_latex_snippet(latex_snippet, template=DEFAULT_TEMPLATE) async

Render latex_snippet to a png and return it.

See documentation for tex2image.latex_to_png for more information on the template parameter.

Source code in src/tex2image/server.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
@app.get(
    "/render_latex_snippet",
    response_model=None,
    responses={200: {"content": {"image/png": {}}}, 500: {"model": Message}},
)
async def render_latex_snippet(
    latex_snippet: str, template: str | None = DEFAULT_TEMPLATE
) -> FileResponse | JSONResponse:
    """Render `latex_snippet` to a png and return it.

    See
    [documentation for tex2image.latex_to_png](https://tex2image.readthedocs.io/en/latest/renderer#tex2image.rendering.render_latex_to_png)
    for more information on the `template` parameter.
    """
    temp_dir = TemporaryDirectory()
    temp_dir_name = Path(temp_dir.name)
    try:
        image_file = render_latex_to_png(latex_snippet, temp_dir_name, template)
    except CalledProcessError:
        return JSONResponse(
            status_code=500,
            content=Message(message="Exception while rendering.").model_dump(),
        )
    return FileResponse(
        image_file, media_type="image/png", background=BackgroundTask(temp_dir.cleanup)
    )

run_server(host, port)

Serve the tex2image server using uvicorn and FastAPI on host:port.

Navigate to [host]:[port]/docs to view automatic interactive API documentation (provided by Swagger UI).

Parameters:

Name Type Description Default
host str

The host to listen on.

required
port int

The port to listen on.

required

Example:

run_server("127.0.0.1", 8000)
Source code in src/tex2image/server.py
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
def run_server(host: str, port: int) -> None:
    """Serve the tex2image server using uvicorn and FastAPI on `host`:`port`.

    Navigate to [host]:[port]/docs to view automatic interactive API documentation
    (provided by Swagger UI).

    Parameters:
        host: The host to listen on.

        port: The port to listen on.

    Example:

    ```bash
    run_server("127.0.0.1", 8000)
    ```
    """
    logging.getLogger("uvicorn.access").addFilter(PingFilter())
    uvicorn.run(app, host=host, port=port)