import PyPDF2
from pathlib import Path
from typing import Tuple
然后,我们定义一个函数stamp()来添加覆盖原有文字的图章。
from pathlib import Path
from typing import Union, Literal, List
from PyPDF2 import PdfWriter, PdfReader
def stamp(
content_pdf: Path,
stamp_pdf: Path,
pdf_result: Path,
page_indices: Union[Literal["ALL"], List[int]] = "ALL",
reader = PdfReader(stamp_pdf)
image_page = reader.pages[0]
writer = PdfWriter()
reader = PdfReader(content_pdf)
if page_indices == "ALL":
page_indices = list(range(0, len(reader.pages)))
for index in page_indices:
content_page = reader.pages[index]
mediabox = content_page.mediabox
content_page.merge_page(image_page)
content_page.mediabox = mediabox
writer.add_page(content_page)
with open(pdf_result, "wb") as fp:
writer.write(fp)
下面是将图章覆盖模式添加到文字上面的效果图,具体可以根据自身的需求进行调整。
现在,我们可以调用watermark()这个函数来给PDF文档添加水印图章。
下面是一个示例:
from pathlib import Path
from typing import Union, Literal, List
from PyPDF2 import PdfWriter, PdfReader
def watermark(
content_pdf: Path,
stamp_pdf: Path,
pdf_result: Path,
page_indices: Union[Literal["ALL"], List[int]] = "ALL",
reader = PdfReader(content_pdf)
if page_indices == "ALL":
page_indices = list(range(0, len(reader.pages)))
writer = PdfWriter()
for index in page_indices:
content_page = reader.pages[index]
mediabox = content_page.mediabox
# You need to load it again, as the last time it was overwritten
reader_stamp = PdfReader(stamp_pdf)
image_page = reader_stamp.pages[0]
image_page.merge_page(content_page)
image_page.mediabox = mediabox
writer.add_page(image_page)
with open(pdf_result, "wb") as fp:
writer.write(fp)