如何在 pylatex 中添加页面背景图片?
How do I add a page background image in 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'.
要在文档的所有页面上实现背景图像,您可以先在 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)
- 示例水印是这个:watermark3.pdf
- 初始PDF文档:basic_maketitle2.pdf
- 最终文档:PDF_Watermark.pdf
PS: 水印、初始生成的pdf和.py文件必须在同一目录下。我无法上传 PDF 文件,因为这是我的第一个答案 post,我不太确定我怎么能上传,但我分享了一些图片。我希望它会有所帮助。
有关更多信息,我建议阅读以下书籍:"Automate the boring stuff with Python",第 13 章,Al Sweigart 着。
我已经编写了以下代码,并通过使用 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'.
要在文档的所有页面上实现背景图像,您可以先在 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)
- 示例水印是这个:watermark3.pdf
- 初始PDF文档:basic_maketitle2.pdf
- 最终文档:PDF_Watermark.pdf
PS: 水印、初始生成的pdf和.py文件必须在同一目录下。我无法上传 PDF 文件,因为这是我的第一个答案 post,我不太确定我怎么能上传,但我分享了一些图片。我希望它会有所帮助。 有关更多信息,我建议阅读以下书籍:"Automate the boring stuff with Python",第 13 章,Al Sweigart 着。