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

时间:2018-05-16 09:05:25

标签: python latex pylatex

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

我在程序所在的目录中有一个图像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'.

1 个答案:

答案 0 :(得分:1)

要在文档的所有页面上实现背景图像,您可以首先在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文件,因为这是我的第一篇答覆,我不确定如何处理,但我分享了一些图片。希望对您有所帮助。 有关更多信息,我建议阅读以下书籍:Al Sweigart撰写的第13章,“使用Python自动化无聊的东西”。