-1

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

2 Answers2

2

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"])
Celdor
  • 2,437
  • 2
  • 23
  • 44
  • Would it be easier to compile with latexmk instead of manually calling latex+biber+latex? (depending on the page breaks, you might actually need two passes after biber) – samcarter_is_at_topanswers.xyz Mar 10 '23 at 20:20
  • Thanks. I have added the snippet for latexmk. It's a good point and OP should probably start using this approach as long as latexmk is configured in OS. – Celdor Mar 11 '23 at 00:35
  • :thumbsup:! I think as long latexmk is used with the `-pdf` option, it does not require much configuration. It should be included in almost all tex distributions by default. – samcarter_is_at_topanswers.xyz Mar 11 '23 at 11:58
0
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()

ref : https://pypi.org/project/pdflatex/

autitya
  • 71
  • 5