简体   繁体   中英

Converting TeX file to image in Python

Using this accepted answer as a reference , I've been trying to replicate the pandas DF to TeX to PDF to png recipe. However, my Python 3 (using a Jupyter Notebook thru Anaconda Navigator) is giving me some trouble.

I've installed MiKTeX at the following default location on my local disk:

C:\Users\USERNAME\AppData\Local\Programs\MiKTeX\2.9

I also installed LaTex at the following location:

C:\Users\USERNAME\AppData\Local\Programs\Python\Python36-32\Lib\site-packages\notebook\static\components\MathJax\extensions\TeX

However, when I run the chunk of code using my Pandas df object:

filename = 'out.tex'
pdffile = 'out.pdf'
outname = 'out.png'

template = r'''\documentclass[preview]{{standalone}}
\usepackage{{booktabs}}
\begin{{document}}
{}
\end{{document}}
'''

with open(filename, 'wb') as f:
    f.write(bytes(template.format(df.to_latex()),'UTF-8'))


subprocess.call(['pdflatex', filename], shell=True)
subprocess.call(['convert', '-density', '300', pdffile, '-quality', '90', outname])

It's simply returning "4", and the only file created from my original df is " out.tex ". I'd like the DF to be turned into a png image so I can keep the full process in my Notebook script.

Any advice would be much appreciated. Thanks.

I solved this issue using the following two process calls:

subprocess.call('latex -interaction=batchmode -output-directory='+ outpath + ' ' + input_tex_file, shell=True, stdout=open(os.devnull, 'wb'))
subprocess.call('dvipng -q* -T tight -o ' + output_png_file + ' ' + input_dvi_file, shell=True, stdout=open(os.devnull, 'wb'))

You'll have to create .tex file first from your raw latex data. Then these commands first create a .dvi file (and some additional auxiliary files) from the .tex file. You can then use dvipng ( https://ctan.org/pkg/dvipng?lang=en ) to create a .png file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM