Skip to content

Rendering

DEFAULT_TEMPLATE = '\n\\documentclass[border=10pt, 12pt, preview]{standalone}\n\n\\usepackage{amsfonts}\n\\usepackage{amsmath}\n\\usepackage{amssymb}\n\n\\begin{document}\n\nSNIPPET_CONTENT\n\n\\end{document}\n' module-attribute

The default template for latex_to_png.

This is passed to DEFAULT_TEMPLATE.format(snippet=latex_snippet) in latex_to_png.

render_latex_to_png(latex_snippet, temp_dir, template=DEFAULT_TEMPLATE)

Render latex_snippet to snippet.png in temp_dir.

Note that this function expects temp_dir_name to be empty when executed. The function may still work if it is not empty, but there are no guarantees.

If the function successfully completes, then temp_dir should contain a file called snippet.png. The directory may also contain auxiliary files generated from the compilation process.

Parameters:

Name Type Description Default
latex_snippet str

The latex code to render.

required
temp_dir Path

The directory in which the generated image will be saved.

required
template str | None

If None, then the latex_snippet will be directly passed to pdflatex. Otherwise, template.replace("SNIPPET_CONTENT", latex_snippet) will be passed to pdflatex.

DEFAULT_TEMPLATE

Example:

from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as temp_dir:
    image_file_path = render_latex_to_png("Pythagorean Theorem: $a^2 + b^2 = c^2$.", Path(temp_dir))
    # Do something with the image here, before temp_dir gets deleted...
Source code in src/tex2image/rendering.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
def render_latex_to_png(
    latex_snippet: str, temp_dir: Path, template: str | None = DEFAULT_TEMPLATE
) -> Path:
    """Render `latex_snippet` to `snippet.png` in `temp_dir`.

    Note that this function expects `temp_dir_name` to be empty when executed.
    The function may still work if it is not empty, but there are no guarantees.

    If the function successfully completes, then `temp_dir` should contain a file
    called `snippet.png`.
    The directory may also contain auxiliary files generated from the compilation
    process.

    Parameters:
        latex_snippet: The latex code to render.

        temp_dir: The directory in which the generated image will be saved.

        template: If None, then the latex_snippet will be directly passed to
            `pdflatex`.
            Otherwise, `template.replace("SNIPPET_CONTENT", latex_snippet)` will be
            passed to `pdflatex`.

    Example:

    ```python
    from pathlib import Path
    from tempfile import TemporaryDirectory

    with TemporaryDirectory() as temp_dir:
        image_file_path = render_latex_to_png("Pythagorean Theorem: $a^2 + b^2 = c^2$.", Path(temp_dir))
        # Do something with the image here, before temp_dir gets deleted...
    ```
    """
    (temp_dir / "main.tex").write_text(
        template.replace("SNIPPET_CONTENT", latex_snippet)
        if template is not None
        else latex_snippet
    )

    run_pdflatex(temp_dir, "main.tex")
    run_pdftoppm(temp_dir, "main.pdf", "main.png")

    return temp_dir / "main.png"

run_pdflatex(directory, file_name)

Run pdflatex with sensible arguments to convert tex source to PDF.

Source code in src/tex2image/rendering.py
82
83
84
85
86
87
88
89
90
91
def run_pdflatex(directory: Path, file_name: str) -> None:
    """Run `pdflatex` with sensible arguments to convert tex source to PDF."""
    _ensure_installed("pdflatex")
    latex_result = subprocess.run(
        ["pdflatex", "-interaction=batchmode", file_name],
        cwd=directory,
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )
    latex_result.check_returncode()

run_pdftoppm(directory, input_file_name, output_file_name)

Run pdftoppm with sensible arguments to convert PDF to PNG.

Source code in src/tex2image/rendering.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def run_pdftoppm(directory: Path, input_file_name: str, output_file_name) -> None:
    """Run `pdftoppm` with sensible arguments to convert PDF to PNG."""
    _ensure_installed("pdftoppm")
    with open(directory / output_file_name, "w") as image_file:
        pdftoppm_result = subprocess.run(
            [
                "pdftoppm",
                "-png",
                "-r",
                "300",
                "-x",
                "1",
                "-y",
                "1",
                "-W",
                "-2",
                "-H",
                "-2",
                str(directory / input_file_name),
            ],
            stdout=image_file,
            stderr=subprocess.DEVNULL,
        )
    pdftoppm_result.check_returncode()