from typing import Union, Tuple
from reportlab.lib import units
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
pdfmetrics.registerFont(TTFont('msyh', r'./msyh.ttc'))
'''
用于生成包含content文字内容的水印pdf文件
content: 水印文本内容
filename: 导出的水印文件名
width: 画布宽度,单位:mm
height: 画布高度,单位:mm
font: 对应注册的字体代号
fontsize: 字号大小
angle: 旋转角度
text_stroke_color_rgb: 文字轮廓rgb色
text_fill_color_rgb: 文字填充rgb色
text_fill_alpha: 文字透明度
'''
def create_wartmark(content: str,
filename: str,
width: Union[int, float],
height: Union[int, float],
font: str,
fontsize: int,
angle: Union[int, float] = 45,
text_stroke_color_rgb: Tuple[int, int, int] = (0, 0, 0),
text_fill_color_rgb: Tuple[int, int, int] = (0, 0, 0),
text_fill_alpha: Union[int, float] = 1) -> None:
c = canvas.Canvas(f'{filename}.pdf', pagesize=(width * units.mm, height * units.mm))
c.translate(0.1 * width * units.mm, 0.1 * height * units.mm)
c.rotate(angle)
c.setFont(font, fontsize)
c.setStrokeColorRGB(*text_stroke_color_rgb)
c.setFillColorRGB(*text_fill_color_rgb)
c.setFillAlpha(text_fill_alpha)
c.drawString(0, 0, content)
c.save()
create_wartmark(content='陈文肯',
filename='水印',
width=200,
height=200,
font='msyh',
fontsize=40,
text_fill_alpha=0.3)
from typing import List
from pikepdf import Pdf, Page, Rectangle
'''
向目标pdf文件批量添加水印
target_pdf_path:目标pdf文件路径+文件名
watermark_pad_path:水印pdf文件路径+文件名
nrow:水印平铺的行数
ncol:水印平铺的列数
skip_pages:需要跳过不添加水印的页数
'''
def add_watemark(target_pdf_path: str,
watermark_pdf_path: str,
nrow: int,
ncol: int,
skip_pages: List[int] = []) -> None:
target_pdf = Pdf.open(target_pdf_path)
watermark_pdf = Pdf.open(watermark_pdf_path)
watermark_page = watermark_pdf.pages[0]
for idx, target_page in enumerate(target_pdf.pages):
for x in range(ncol):
for y in range(nrow):
target_page.add_overlay(watermark_page,
Rectangle(target_page.trimbox[2] * x / ncol,
target_page.trimbox[3] * y / nrow,
target_page.trimbox[2] * (x + 1) / ncol,
target_page.trimbox[3] * (y + 1) / nrow
))
target_pdf.save(r'E:\Work\_已添加水印.pdf')
add_watemark(target_pdf_path=r'E:\Work\《电子学会》2022年3月C语言一级真题(含答案).pdf',
watermark_pdf_path=r'E:\Work\水印.pdf',
nrow=3,
ncol=2,
skip_pages=[0])