Last active
October 20, 2022 03:40
-
-
Save xtornasol512/3c9f77723293a256d71874ca08b02f24 to your computer and use it in GitHub Desktop.
A useful function to call latexmk on python
This file contains 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
from tempfile import TemporaryDirectory as TempD | |
import subprocess # nosec | |
from os import path | |
import base64 | |
import shlex | |
def generate_tex_pdf(tex_string): | |
""" Generic Function to convert a template string to pdf """ | |
with TemporaryDirectory() as tempdir: | |
filename = "output.tex" | |
path_tex = os.path.join(tempdir, filename) | |
path_pdf = os.path.join(tempdir, 'output.pdf') | |
logger.info(F"Path TEX: {path_tex}") | |
command = (F"latexmk -interaction=nonstopmode -silent -pdf -f {path_tex}") | |
args = shlex.split(command) | |
os.chdir(tempdir) | |
try: | |
with open(path_tex,'wb+') as f: | |
if isinstance(tex_string, bytes): | |
f.write(tex_string) | |
else: | |
f.write(tex_string.encode()) | |
process = subprocess.run(args, check=True, shell=False) # nosec B603 | |
# Write pdf file | |
with open(path_pdf, 'rb') as f: | |
pdf = f.read() | |
return pdf | |
except subprocess.CalledProcessError as e: | |
""" Softly catch non zero status """ | |
if not os.path.exists(path_pdf): | |
with open(os.path.join(tempdir, 'output.log'), 'rb') as g: | |
pdf_log = g.read() | |
logger.info(F"Latex ERROR output: {pdf_log}") | |
raise e | |
with open(path_pdf, 'rb') as f: | |
pdf = f.read() | |
return pdf | |
except Exception as e: | |
# Log if there was an error | |
logger.error(F'[Generate_tex_pdf]: {e}, type: {type(e)}') | |
raise e |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment