How to convert .tex file into .pdf file in windows by using python programming?
I have .tex file and want .pdf file through python code in windows
How to convert .tex file into .pdf file in windows by using python programming?
I have .tex file and want .pdf file through python code in windows
You could use subprocess
module as long as LaTeX distribution is available in your system.
from subprocess import PIPE, Popen, run, TimeoutExpired
proc = Popen(["pdflatex", "main"], stdout=PIPE)
try:
out, err = proc.communicate(timeout=120)
print("Log:")
print(out.decode())
except TimeoutExpired:
proc.kill()
print("Time expired!")
# run(["evince", "main.pdf"])
However, if your document has bibliography with citations and you use biblatex
with the biber
backend, it is necessary to run the following routine:
from subprocess import PIPE, Popen, run, TimeoutExpired
cmd_chain = [
["pdflatex", "main"],
["biber", "main"],
["pdflatex", "main"],
["pdflatex", "main"],
]
for i, cmd in enumerate(cmd_chain):
print("Pass", i+1, ":", " ".join(cmd))
proc = Popen(cmd, stdout=PIPE)
try:
out, err = proc.communicate(timeout=120)
print("Log:")
print(out.decode())
except TimeoutExpired:
proc.kill()
out, err = proc.communicate()
print(err)
# run(["evince", "main.pdf"])
EDIT.
As pointed out in the comments, latexmk
might be a better option to compile a document as it takes care of required no. of passes. However, latexmk is an external tool and needs t be configured.
Here's the python code:
from subprocess import PIPE, Popen, run, TimeoutExpired
# run(["latexmk", "-C"]) # Reset project
proc = Popen(["latexmk", "-gg", "main"], stdout=PIPE)
try:
out, err = proc.communicate(timeout=120)
print("Log:")
print(out.decode())
except TimeoutExpired:
proc.kill()
print("Time expired!")
# run(["evince", "main.pdf"])
import pdflatex
with open('my_file.tex', 'rb') as f:
pdfl = pdflatex.PDFLaTeX.from_binarystring(f.read(), 'my_file'
pdf, log, cp = pdfl.create_pdf()