import io import os import tempfile from pathlib import Path from pylatex import Document import streamlit as st def compile_latex(source: str) -> bytes: """ Compile LaTeX source into a PDF and return its raw bytes. Parameters: ---------- source : str A complete LaTeX document body (e.g. including \\begin{document}…). Returns: ------- bytes The compiled PDF file contents. """ with tempfile.TemporaryDirectory() as tmpdir: # ドキュメントを初期化 doc = Document("document", documentclass="article", font_size="10pt") doc.append(source) base_path = os.path.join(tmpdir, "document") # compiler 引数で pdflatex を指定。latexmk があれば省略可。 _ = doc.generate_pdf( filepath=base_path, compiler="pdflatex", clean=True, clean_tex=True, silent=True, ) return Path(base_path + ".pdf").read_bytes() def main(): st.title("LaTeX Compiler") prompt = st.text_area( "Enter full LaTeX source", value=( r"\documentclass{article}" "\n" r"\begin{document}" "\n" r"Hello, world!" "\n" r"\end{document}" ), height=200, ) if st.button("Compile to PDF"): with st.spinner("Compiling…"): pdf_bytes = compile_latex(prompt) st.success("Compilation succeeded") st.download_button( "Download PDF", data=pdf_bytes, file_name="output.pdf", mime="application/pdf", ) if __name__ == "__main__": main()