johan855
johan855

Reputation: 1626

Import custom latex script into pylatex document

I'm trying to generate a .pdf file using PyLaTeX. I see PyLaTeX has a predefined syntax to generate LaTeX documents and then export them, but I want to simply load a LaTeX file I have already built and not recreate it through the PyLaTeX syntax.

The code I am trying to use now is the following, and even if everything works, I get the "raw" code for the document:

from pylatex import Document, Section, Subsection, Command
from pylatex.utils import italic, NoEscape

latex_document = 'path'
with open(latex_document) as file:
    tex= file.read()

doc = Document('basic')
doc.append(tex)
doc.generate_pdf(clean_tex=False)

Upvotes: 5

Views: 5374

Answers (1)

pentavalentcarbon
pentavalentcarbon

Reputation: 180

You need to wrap tex with NoEscape, so that PyLaTeX will interpret the string contents literally.

If the contents of the file path are

\begin{equation}
  \hat{H}\Psi = E\Psi
\end{equation}

then doc.append(tex) creates

\begin{document}%
\normalsize%
\textbackslash{}begin\{equation\}\newline%
  \textbackslash{}hat\{H\}\textbackslash{}Psi = E\textbackslash{}Psi\newline%
\textbackslash{}end\{equation\}\newline%
%
\end{document}

and doc.append(NoEscape(tex)) creates

\begin{document}%
\normalsize%
\begin{equation}
  \hat{H}\Psi = E\Psi
\end{equation}
%
\end{document}

Upvotes: 4

Related Questions