python - 如何在 pylatex 中添加页面背景图像?

标签 python latex pylatex

我编写了以下代码,并使用 NoEscape 模块给出了用于绘制背景的 Latex 命令。

我在与程序相同的目录中有一个图像reportbg.png。现在,我希望此图像作为背景出现在报告的所有页面中。

types = ('../Faults/*.png', '../Faults/*.jpg')
imgnames = []
for files in types:
    imgnames.extend(natsort.natsorted(glob.glob(files)))

geometry_options = { "head": "30pt",
                 "margin": "0.3in",
                 "top": "0.2in",
                 "bottom": "0.4in",
                 "includeheadfoot": True}

doc = Document(geometry_options=geometry_options)
first_page = PageStyle("firstpage")
doc.preamble.append(first_page)
doc.change_document_style("firstpage")

new_comm1 = NoEscape(r'\usepackage{wallpaper}')
doc.append(new_comm1)
new_comm2 = NoEscape(r'\CenterWallPaper{reportbg.png}')
doc.append(new_comm2)

with doc.create(Section('Faults identified')):
    doc.append("Report")
    with doc.create(Subsection('Fault pictures')):
        for i,imgname in enumerate(imgnames): 
            with doc.create(Figure(position='h!')) as f_pic:
                f_pic.add_image(imgname, width='220px')
                f_pic.add_caption('Height: '+str(56)+', Angle: '+str(20))
                doc.append('Some regular text')

但是,我收到以下错误:

! LaTeX Error: Can be used only in preamble.

See the LaTeX manual or LaTeX Companion for explanation.
Type  H <return>  for immediate help.
...                                              

l.23 \usepackage
            {wallpaper}%
! Undefined control sequence.
l.24 \CenterWallPaper
                 {reportbg.png}%
<../Faults/1.jpg, id=1, 1927.2pt x 1084.05pt> <use ../Faults/1.jpg>
<../Faults/2.jpg, id=2, 1927.2pt x 1084.05pt> <use ../Faults/2.jpg>
<../Faults/3.jpg, id=3, 1927.2pt x 1084.05pt> <use ../Faults/3.jpg>
<../Faults/4.jpg, id=4, 1003.75pt x 1003.75pt> <use ../Faults/4.jpg>

LaTeX Warning: '!h' float specifier changed to '!ht'.

最佳答案

要在文档的所有页面上实现背景图像,您可以先在 pylatex 中生成 PDF 文档,然后使用 PyPDF2 添加图像作为水印。为此,您需要将“reportbg.png”图像转换为 pdf 格式 (reportbg.pdf)。

这是一个基于 pylatex 文档 ( https://jeltef.github.io/PyLaTeX/current/examples/basic.html ) 的修改示例:

代码

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

class Document_Watermark():

    def __init__(self, doc):
        self.doc = doc
        self.fill_document()
        self.create_document()
        self.Watermark()

    def fill_document(self):
        """Add a section, a subsection and some text to the document.

        :param doc: the document
        :type doc: :class:`pylatex.document.Document` instance
        """
        with self.doc.create(Section('A section')):
            self.doc.append('Some regular text and some ')
            self.doc.append(italic('italic text. '))

            with self.doc.create(Subsection('A subsection')):
                self.doc.append('Also some crazy characters: $&#{}')
    def create_document(self):
        # Add stuff to the document
        with self.doc.create(Section('A second section')):
            self.doc.append('Some text.')

        self.doc.generate_pdf('basic_maketitle2', clean_tex=False, compiler='pdflatex')
        tex = self.doc.dumps()  # The document as string in LaTeX syntax
    def Watermark(self):
        Doc = open('basic_maketitle2.pdf', 'rb')
        pdfReader = PyPDF2.PdfFileReader(Doc)
        pdfWatermark = PyPDF2.PdfFileReader(open('watermark3.pdf', 'rb'))
        pdfWriter = PyPDF2.PdfFileWriter()

        for pageNum in range(0, pdfReader.numPages):
            pageObj = pdfReader.getPage(pageNum)
            pageObj.mergePage(pdfWatermark.getPage(0))
            pdfWriter.addPage(pageObj)
            resultPdfFile = open('PDF_Watermark.pdf', 'wb')
            pdfWriter.write(resultPdfFile)
        Doc.close()
        resultPdfFile.close()



# Basic document
doc = Document('basic')


# Document with `\maketitle` command activated
doc = Document()

doc.preamble.append(Command('title', 'Awesome Title'))
doc.preamble.append(Command('author', 'Anonymous author'))
doc.preamble.append(Command('date', NoEscape(r'\today')))
doc.append(NoEscape(r'\maketitle'))

Document_Watermark(doc)

PS:水印、初始生成的pdf和.py文件必须位于同一目录。我无法上传 PDF 文件,因为这是我的第一篇回答帖子,我不太确定如何上传,但我分享了一些图像。我希望这会有所帮助。 有关更多信息,我建议阅读以下书籍:“用 Python 自动处理无聊的事情”,第 13 章,作者:Al Sweigart。

关于python - 如何在 pylatex 中添加页面背景图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50366624/

相关文章:

python - 转置和连接字符串

python - 从字典列表中提取字符串

vim - 使用 vim 的 `gqap' 有时会异常缩进

emacs - 禁止 emacs 自动填充选定区域

Python:PyLaTeX 超链接到 URL

python - 我是否正确地将日期对象发送到请求正文? Python

Python - 更优雅地清除终端屏幕

emacs - 一键 Emacs LaTeX 编译?

python - PyLaTeX:pylatex.errors.CompilerError:未找到 LaTex 编译器