使用 pylatex 导出多页 PDF 的问题

使用 pylatex 导出多页 PDF 的问题

多页问题:

我正在尝试导出多页 pdf,但似乎出现错误。我找不到源...

我认为这是因为文本“化学交换”中使用了非标准字母,但理论上我包含了包,utf8所以这应该不是问题......

这是 pylatex 代码:

import pylatex as pl
from pylatex.utils import NoEscape
from pylatex import Command
from pylatex import Package
from pylatex import Figure
import os

videoNumber = 1
slideNumber = 5

class Form(pl.base_classes.Environment):
    """A class to wrap hyperref's form environment."""

    _latex_name = 'Form'

    packages = [pl.Package('hyperref')]
    escape = False
    content_separator = "\n"

def pdf(i):

    dirname = os.getcwd()
    filename = os.path.join(dirname, 'Text_And_Slides\\' + str(videoNumber) + '\\Slides\\' + str(i)) +".jpg"
    print(filename)

    with doc.create(Figure(position='h!')) as slide_pic:
                slide_pic.add_image('1.jpg',width=NoEscape("\linewidth"))

    doc.append(NoEscape(r"\noindent"))
    doc.append(NoEscape(r"\rule{\linewidth}{1pt}"))
    doc.append(NoEscape(r"\linebreak"))

    dirname = os.getcwd()
    filename = os.path.join(dirname, 'Text And Slides\\' + str(videoNumber) + '\\Text\\' + str(i))
    with open(filename+".txt", 'r',encoding="utf8") as myfile:
        text=myfile.read().replace('\n', '')

    doc.append(text)

    doc.append(NoEscape(r"\newline"))
    doc.append(NoEscape(r"\noindent"))
    doc.append(NoEscape(r"\rule{\textwidth}{1pt}"))
    doc.append(NoEscape(r"\newline"))
    doc.append("Notes: ")
    doc.append(NoEscape(r"\newline"))

    doc.append(NoEscape(r"\newcommand\measurepage{\the\dimexpr\pagegoal-\pagetotal-\baselineskip\relax}"))
    doc.append(NoEscape(r"\par")) # <---- This line added
    with doc.create(Form()):
        doc.append(Command('noindent'))
        doc.append(Command('TextField',
                   options=["name=multilinetextbox", "multiline=true",
                            NoEscape("width=\linewidth"),NoEscape("height=\measurepage")],
                   arguments=''))

    doc.append(NoEscape(r"\newpage"))


geometry_options = {
            "head": "1pt",
            "margin": "0.3in",
            "bottom": "0.3in",
            "includeheadfoot": False}
doc = pl.Document('basic',geometry_options=geometry_options)
doc.preamble.append(Command('usepackage', 'helvet'))
doc.preamble.append(Package ('inputenc', options = ['utf8']))
doc.preamble.append(Package('needspace'))

for i in range(1,3):
    pdf(i)

doc.generate_pdf('pdf_test')

以下是生成的 LaTeX 文件:

\documentclass{article}%
\usepackage[T1]{fontenc}%
\usepackage[utf8]{inputenc}%
\usepackage{lmodern}%
\usepackage{textcomp}%
\usepackage{lastpage}%
\usepackage[head=1pt,margin=0.3in,bottom=0.3in,includeheadfoot=False]{geometry}%
\usepackage{graphicx}%
\usepackage{hyperref}%
%
\usepackage{helvet}%
\usepackage[utf8]{inputenc}%
\usepackage{needspace}%
%
\begin{document}%
\normalsize%


\begin{figure}[h!]%
\centering%
\includegraphics[width=\linewidth]{1.jpg}%
\end{figure}

%
\noindent%
\rule{\linewidth}{1pt}%
\linebreak%
Welcome to our MOOC our Massively Online Open Course on Basic Steps in Magnetic Resonance. That is the subject of chapter 4 of Peter Hore's book. The author has chosen an example of chemical exchange for the title page of his book so it is safe to assume that he found this subject particularly interesting. Like many other basic aspects of magnetic resonance the effects of chemical exchange were discovered in the 1950s. The name of Herbert Gutowsky is often associated with this discovery. The theory was developed by Felix Bloch and Harden McConnell. As we shall see chemical reactions that occur during the observation of NMR spectra lead to characteristic effects: line broadening coalescence and line narrowing all of which allow us to determine the rates of reactions. Typically one can study rates that are comparable with differences in chemical shifts. The range of applications is truly staggering. From simple conformational equilibria to internal mobility of biomolecules such as proteins.%
\newline%
\noindent%
\rule{\textwidth}{1pt}%
\newline%
Notes: %
\newline%
\newcommand\measurepage{\the\dimexpr\pagegoal-\pagetotal-\baselineskip\relax}%
\par%
\begin{Form}
\noindent
\TextField[name=multilinetextbox,multiline=true,width=\linewidth,height=\measurepage]{}
\end{Form}%
\newpage%


\begin{figure}[h!]%
\centering%
\includegraphics[width=\linewidth]{1.jpg}%
\end{figure}

%
\noindent%
\rule{\linewidth}{1pt}%
\linebreak%
So the word âchemical exchangeâ has a particular meaning for NMR spectroscopists which is not shared by the entire community of chemists. To explain this point let's consider some simple examples. All of us in first year chemistry must have learned that cyclohexane normally looks like this if it is drawn as a static molecule and that we have protons or generally speaking substituents sticking out from the ring in axial positions and other ones that are in equatorial positions. Now we also know that these can interchange to give another conformation which again has axial and equatorial positions. Now what is curious is that in the static molecule if we could stop it from exchanging we would expect a different chemical shift for the axial position and the equatorial position. One would expect them to have different chemical shifts. Let's not talk about the fact that they are also coupled which is not of interest here. Now it turns out that the chemical shift of the axial proton will be transformed into the chemical shift of an equatorial proton. Whereas the equatorial proton will find itself in the position of an axial proton. Consequently there is an interchange between their chemical shifts. It turns out that this process is extremely fast and therefore difficult to measure with NMR unless we find some way of slowing it down which is actually still a topic of interest. I can take another example of a true chemical reaction. Let's consider some carboxylic acid which looks like this in the acid form. And we have all learned that this can be transformed into the conjugate base by giving a proton to the environment. Now if we think of this carbon{-}13 we can expect its chemical shift to be different from the chemical shift in the conjugate base. And indeed it is. Again such a process tends to be very fast and therefore not easy to measure by NMR. But it turns out that such processes can be slowed down considerably. For example if this carboxylic acid is hidden in the heart of a protein if it belongs to the side{-}chain of a protein to one of the amino{-}acids in the protein the exchange can be slowed down and can become measurable which is of great interest to NMR spectroscopy.%
\newline%
\noindent%
\rule{\textwidth}{1pt}%
\newline%
Notes: %
\newline%
\newcommand\measurepage{\the\dimexpr\pagegoal-\pagetotal-\baselineskip\relax}%
\par%
\begin{Form}
\noindent
\TextField[name=multilinetextbox,multiline=true,width=\linewidth,height=\measurepage]{}
\end{Form}%
\newpage%
\end{document}

这是错误:

CalledProcessError Traceback(最近一次调用最后一次)在()70 pdf(i)71 ---> 72 doc.generate_pdf('pdf_test')

~\Anaconda3\lib\site-packages\pylatex\document.py 在 generate_pdf(self、filepath、clean、clean_tex、compiler、compiler_args、silent) 中 231 尝试:232 output = subprocess.check_output(command, --> 233 stderr=subprocess.STDOUT) 234 除外 (OSError, IOError) 作为 e:235 # 当 python 2 被删除时使用 FileNotFoundError

~\Anaconda3\lib\subprocess.py 在 check_output(timeout、*popenargs、**kwargs) 中 334 335 返回 run(*popenargs、stdout=PIPE、timeout=timeout、check=True、--> 336 **kwargs).stdout 337 338

~\Anaconda3\lib\subprocess.py 在运行(输入、超时、检查、*popenargs、**kwargs)416 中,如果检查和 retcode:417 引发 CalledProcessError(retcode、process.args、--> 418 输出=stdout,stderr=stderr)419 返回 CompletedProcess(process.args、retcode、stdout、stderr)420

CalledProcessError:命令‘[‘latexmk’、‘--pdf’、‘--interaction=nonstopmode’、‘pdf_test.tex’]’返回非零退出状态 12。

编辑:

我刚刚意识到,如果我多次运行 Python 脚本,则在第二次或第三次运行后,它将输出 pdf……非常奇怪!

非常感谢您的帮助!!

编辑2:

以下是根据评论更新后的代码。但它仍然不起作用……

import pylatex as pl
from pylatex.utils import NoEscape
from pylatex import Command
from pylatex import Package
from pylatex import Figure
import os

videoNumber = 1
slideNumber = 5

class Form(pl.base_classes.Environment):
    """A class to wrap hyperref's form environment."""

    _latex_name = 'Form'

    packages = [pl.Package('hyperref')]
    escape = False
    content_separator = "\n"

def pdf(i):

    dirname = os.getcwd()
    filename = os.path.join(dirname, 'Text_And_Slides\\' + str(videoNumber) + '\\Slides\\' + str(i)) +".jpg"
    print(filename)

    with doc.create(Figure(position='h!')) as slide_pic:
                slide_pic.add_image('1.jpg',width=NoEscape("\linewidth"))

    doc.append(NoEscape(r"\noindent"))
    doc.append(NoEscape(r"\rule{\linewidth}{1pt}"))
    doc.append(NoEscape(r"\linebreak"))

    dirname = os.getcwd()
    filename = os.path.join(dirname, 'Text And Slides\\' + str(videoNumber) + '\\Text\\' + str(i))
    with open(filename+".txt", 'r',encoding="utf8") as myfile:
        text=myfile.read().replace('\n', '')

    doc.append(text)

    doc.append(NoEscape(r"\newline"))
    doc.append(NoEscape(r"\noindent"))
    doc.append(NoEscape(r"\rule{\textwidth}{1pt}"))
    doc.append(NoEscape(r"\newline"))
    doc.append("Notes: ")
    doc.append(NoEscape(r"\newline"))

    doc.append(NoEscape(r"\setlength{\measurepage}{\dimexpr\pagegoal-\pagetotal-\baselineskip}"))
    doc.append(NoEscape(r"\par")) # <---- This line added
    with doc.create(Form()):
        doc.append(Command('noindent'))
        doc.append(Command('TextField',
                   options=["name=multilinetextbox", "multiline=true",
                            NoEscape("width=\linewidth"),NoEscape("height=\measurepage")],
                   arguments=''))

    doc.append(NoEscape(r"\newpage"))


geometry_options = {
            "head": "1pt",
            "margin": "0.3in",
            "bottom": "0.3in",
            "includeheadfoot": False}
doc = pl.Document('basic',geometry_options=geometry_options)
doc.preamble.append(Command('usepackage', 'helvet'))
doc.preamble.append(Package ('inputenc', options = ['utf8']))
doc.preamble.append(Package('needspace'))
doc.preamble.append(NoEscape(r"\newlength{\measurepage}"))

for i in range(1,3):
    pdf(i)

doc.generate_tex('pdf_test')

以下是生成的 LaTeX 输出:

\documentclass{article}%
\usepackage[T1]{fontenc}%
\usepackage[utf8]{inputenc}%
\usepackage{lmodern}%
\usepackage{textcomp}%
\usepackage{lastpage}%
\usepackage[head=1pt,margin=0.3in,bottom=0.3in,includeheadfoot=False]{geometry}%
\usepackage{graphicx}%
\usepackage{hyperref}%
%
\usepackage{helvet}%
\usepackage[utf8]{inputenc}%
\usepackage{needspace}%
\newlength{\measurepage}%
%
\begin{document}%
\normalsize%


\begin{figure}[h!]%
\centering%
\includegraphics[width=\linewidth]{1.jpg}%
\end{figure}

%
\noindent%
\rule{\linewidth}{1pt}%
\linebreak%
Welcome to our MOOC our Massively Online Open Course on Basic Steps in Magnetic Resonance. That is the subject of chapter 4 of Peter Hore's book. The author has chosen an example of chemical exchange for the title page of his book so it is safe to assume that he found this subject particularly interesting. Like many other basic aspects of magnetic resonance the effects of chemical exchange were discovered in the 1950s. The name of Herbert Gutowsky is often associated with this discovery. The theory was developed by Felix Bloch and Harden McConnell. As we shall see chemical reactions that occur during the observation of NMR spectra lead to characteristic effects: line broadening coalescence and line narrowing all of which allow us to determine the rates of reactions. Typically one can study rates that are comparable with differences in chemical shifts. The range of applications is truly staggering. From simple conformational equilibria to internal mobility of biomolecules such as proteins.%
\newline%
\noindent%
\rule{\textwidth}{1pt}%
\newline%
Notes: %
\newline%
\setlength{\measurepage}{\dimexpr\pagegoal-\pagetotal-\baselineskip}%
\par%
\begin{Form}
\noindent
\TextField[name=multilinetextbox,multiline=true,width=\linewidth,height=\measurepage]{}
\end{Form}%
\newpage%


\begin{figure}[h!]%
\centering%
\includegraphics[width=\linewidth]{1.jpg}%
\end{figure}

%
\noindent%
\rule{\linewidth}{1pt}%
\linebreak%
So the word âchemical exchangeâ has a particular meaning for NMR spectroscopists which is not shared by the entire community of chemists. To explain this point let's consider some simple examples. All of us in first year chemistry must have learned that cyclohexane normally looks like this if it is drawn as a static molecule and that we have protons or generally speaking substituents sticking out from the ring in axial positions and other ones that are in equatorial positions. Now we also know that these can interchange to give another conformation which again has axial and equatorial positions. Now what is curious is that in the static molecule if we could stop it from exchanging we would expect a different chemical shift for the axial position and the equatorial position. One would expect them to have different chemical shifts. Let's not talk about the fact that they are also coupled which is not of interest here. Now it turns out that the chemical shift of the axial proton will be transformed into the chemical shift of an equatorial proton. Whereas the equatorial proton will find itself in the position of an axial proton. Consequently there is an interchange between their chemical shifts. It turns out that this process is extremely fast and therefore difficult to measure with NMR unless we find some way of slowing it down which is actually still a topic of interest. I can take another example of a true chemical reaction. Let's consider some carboxylic acid which looks like this in the acid form. And we have all learned that this can be transformed into the conjugate base by giving a proton to the environment. Now if we think of this carbon{-}13 we can expect its chemical shift to be different from the chemical shift in the conjugate base. And indeed it is. Again such a process tends to be very fast and therefore not easy to measure by NMR. But it turns out that such processes can be slowed down considerably. For example if this carboxylic acid is hidden in the heart of a protein if it belongs to the side{-}chain of a protein to one of the amino{-}acids in the protein the exchange can be slowed down and can become measurable which is of great interest to NMR spectroscopy.%
\newline%
\noindent%
\rule{\textwidth}{1pt}%
\newline%
Notes: %
\newline%
\setlength{\measurepage}{\dimexpr\pagegoal-\pagetotal-\baselineskip}%
\par%
\begin{Form}
\noindent
\TextField[name=multilinetextbox,multiline=true,width=\linewidth,height=\measurepage]{}
\end{Form}%
\newpage%
\end{document}

答案1

您必须\setlength在 之后使用\par。以下 LaTeX 代码似乎产生了正确的输出:

\documentclass{article}%
\usepackage[T1]{fontenc}%
\usepackage[utf8]{inputenc}%
\usepackage{lmodern}%
\usepackage{textcomp}%
\usepackage{lastpage}%
\usepackage[head=1pt,margin=0.3in,bottom=0.3in,includeheadfoot=False]{geometry}%
\usepackage{graphicx}%
\usepackage{hyperref}%
%
\usepackage{helvet}%
\usepackage[utf8]{inputenc}%
\usepackage{needspace}%
\newlength{\measurepage}%
%
\begin{document}%
\normalsize%


\begin{figure}[h!]%
\centering%
\includegraphics[width=\linewidth]{example-image-duck}%
\end{figure}

%
\noindent%
\rule{\linewidth}{1pt}%
\linebreak%
Welcome to our MOOC our Massively Online Open Course on Basic Steps in Magnetic Resonance. That is the subject of chapter 4 of Peter Hore's book. The author has chosen an example of chemical exchange for the title page of his book so it is safe to assume that he found this subject particularly interesting. Like many other basic aspects of magnetic resonance the effects of chemical exchange were discovered in the 1950s. The name of Herbert Gutowsky is often associated with this discovery. The theory was developed by Felix Bloch and Harden McConnell. As we shall see chemical reactions that occur during the observation of NMR spectra lead to characteristic effects: line broadening coalescence and line narrowing all of which allow us to determine the rates of reactions. Typically one can study rates that are comparable with differences in chemical shifts. The range of applications is truly staggering. From simple conformational equilibria to internal mobility of biomolecules such as proteins.%
\newline%
\noindent%
\rule{\textwidth}{1pt}%
\newline%
Notes: %
\newline%
\par%
\setlength{\measurepage}{\dimexpr\pagegoal-\pagetotal-\baselineskip}%
\begin{Form}
\noindent
\TextField[name=multilinetextbox,multiline=true,width=\linewidth,height=\measurepage]{}
\end{Form}%
\newpage%


\begin{figure}[h!]%
\centering%
\includegraphics[width=\linewidth]{example-image-duck}%
\end{figure}

%
\noindent%
\rule{\linewidth}{1pt}%
\linebreak%
So the word âchemical exchangeâ has a particular meaning for NMR spectroscopists which is not shared by the entire community of chemists. To explain this point let's consider some simple examples. All of us in first year chemistry must have learned that cyclohexane normally looks like this if it is drawn as a static molecule and that we have protons or generally speaking substituents sticking out from the ring in axial positions and other ones that are in equatorial positions. Now we also know that these can interchange to give another conformation which again has axial and equatorial positions. Now what is curious is that in the static molecule if we could stop it from exchanging we would expect a different chemical shift for the axial position and the equatorial position. One would expect them to have different chemical shifts. Let's not talk about the fact that they are also coupled which is not of interest here. Now it turns out that the chemical shift of the axial proton will be transformed into the chemical shift of an equatorial proton. Whereas the equatorial proton will find itself in the position of an axial proton. Consequently there is an interchange between their chemical shifts. It turns out that this process is extremely fast and therefore difficult to measure with NMR unless we find some way of slowing it down which is actually still a topic of interest. I can take another example of a true chemical reaction. Let's consider some carboxylic acid which looks like this in the acid form. And we have all learned that this can be transformed into the conjugate base by giving a proton to the environment. Now if we think of this carbon{-}13 we can expect its chemical shift to be different from the chemical shift in the conjugate base. And indeed it is. Again such a process tends to be very fast and therefore not easy to measure by NMR. But it turns out that such processes can be slowed down considerably. For example if this carboxylic acid is hidden in the heart of a protein if it belongs to the side{-}chain of a protein to one of the amino{-}acids in the protein the exchange can be slowed down and can become measurable which is of great interest to NMR spectroscopy.%
\newline%
\noindent%
\rule{\textwidth}{1pt}%
\newline%
Notes: %
\newline%
\par%
\setlength{\measurepage}{\dimexpr\pagegoal-\pagetotal-\baselineskip}%
\begin{Form}
\noindent
\TextField[name=multilinetextbox,multiline=true,width=\linewidth,height=\measurepage]{}
\end{Form}%
\newpage%
\end{document}

我所做的唯一更改是替换我没有的图像文件并更改\par和的顺序\setlength{\measurepage}

如果您想要多次包含此代码片段,定义如下命令可能是一个好主意:

\newcommand*\MeasurePage{\par\setlength{\measurepage}{\dimexpr\pagegoal-\pagetotal-\baselineskip}}

然后再次使用该代码,而不是相同的代码。

相关内容