如何在PyLatex生成的pdf中添加水印?

时间:2019-01-22 12:02:25

标签: python latex pylatex

我正在尝试将水印添加到PyLatex生成的pdf中。 我尝试使用以下方法。

  1. NoEscape()命令,它显示以下错误:-
(/usr/share/texlive/texmf-dist/tex/latex/base/ts1cmr.fd)
(/usr/share/texlive/texmf-dist/tex/latex/roboto/T1Roboto-LF.fd)
*geometry* driver: auto-detecting
*geometry* detected driver: pdftex
ABD: EverySelectfont initializing macros
(/usr/share/texlive/texmf-dist/tex/context/base/supp-pdf.mkii
[Loading MPS to PDF converter (version 2006.09.02).]
) (/usr/share/texlive/texmf-dist/tex/generic/oberdiek/pdftexcmds.sty)
(/usr/share/texlive/texmf-dist/tex/latex/oberdiek/epstopdf-base.sty
(/usr/share/texlive/texmf-dist/tex/latex/oberdiek/grfext.sty
(/usr/share/texlive/texmf-dist/tex/generic/oberdiek/kvdefinekeys.sty))
(/usr/share/texlive/texmf-dist/tex/latex/oberdiek/kvoptions.sty
(/usr/share/texlive/texmf-dist/tex/generic/oberdiek/kvsetkeys.sty
(/usr/share/texlive/texmf-dist/tex/generic/oberdiek/etexcmds.sty)))
(/usr/share/texlive/texmf-dist/tex/latex/latexconfig/epstopdf-sys.cfg))

! LaTeX Error: Can be used only in preamble.

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

l.68 \usepackage
                [printwatermark]{xwatermark}%
! Undefined control sequence.
l.69 \newwatermark
                  [allpages,color=red!50,angle=45,scale=3,xpos=0,ypos=0]{DRA...

我为此使用了以下代码-

f1 = NoEscape(r'\usepackage[printwatermark]{xwatermark}')
f2 = NoEscape(r'\newwatermark[allpages,color=red!50,angle=45,scale=3,xpos=0,ypos=0]{DRAFT}')
doc.append(f1)
doc.append(f2)
  1. 根据此答案documentation使用了 PyPDF2 。 这种方法的问题在于水印会覆盖原始的pdf内容,理想情况下,它应该充当透明背景。 我使用的代码-
def add_watermark():
    Doc = open('invoice.pdf', 'rb')
    pdfReader = PyPDF2.PdfFileReader(Doc)
    pdfWatermark = PyPDF2.PdfFileReader(open('draft_watermark.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('invoicecopy.pdf', 'wb')
        pdfWriter.write(resultPdfFile)
    Doc.close()
    resultPdfFile.close()

这是添加水印的其他方法吗? 或者,我可以修改当前的实现以实现它吗?

0 个答案:

没有答案