给pdf文件中添加水印,在python中主要用到两个第三方包: reportlab, PyPDF2 。其中 reportlab 主要用于生成水印模板;而 PyPDF2主要用于将水印pdf文件和需要添加水印文件进行合并操作。
安装依赖
pip install ReportLab
pip install PyPDF2
核心代码
from datetime import date
from reportlab.lib import units
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
pdfmetrics.registerFont(TTFont('song', 'resource/simsun.ttc'))
import PyPDF2
class WaterMarkUtils:
@staticmethod
def create_wm_template(content,
width=210,
height=297,
angle=45,
text_stroke_color_rgb=(0, 0, 0),
text_fill_color_rgb=(0, 0, 0),
text_fill_alpha=0.3,
show_date=False,
filename='template'
) -> str:
# 生成水印模板
file_path = f'{filename}.pdf'
c = canvas.Canvas(f'{filename}.pdf', pagesize=(width * units.mm, height * units.mm))
# 画布平移保证文字完整性
c.translate(0.4 * width * units.mm, 0.4 * height * units.mm)
c.rotate(angle)
c.setStrokeColorRGB(*text_stroke_color_rgb)
c.setFont('song', font_size)
# 设置填充色
c.setFillColorRGB(*text_fill_color_rgb)
# 设置字体透明度
c.setFillAlpha(text_fill_alpha)
# 绘制字体内容
if show_date:
cur_date = date.today().__str__()
content += f'({cur_date})'
c.drawString(0, 50, content)
c.drawString(50, 100, content)
c.drawString(100, 150, content)
c.drawString(150, 200, content)
# c.drawString(200, 250, content)
# c.drawString(250, 300, content)
c.save()
return file_path
@staticmethod
def add_watermark(content, source_path, out_path=None,angle=45, show_date=True,):
template_path = WaterMarkUtils.create_wm_template(content, angle=angle, show_date=show_date)
def add_wm_for_page(wm_file, page_pdf):
# 打开水印pdf文件
pdf_reader = PyPDF2.PdfFileReader(wm_file)
page_pdf.mergePage(pdf_reader.getPage(0))
return page_pdf
source_reader = PyPDF2.PdfFileReader(source_path)
target_writer = PyPDF2.PdfFileWriter()
for page in range(source_reader.numPages):
vm_pdf = add_wm_for_page(template_path, source_reader.getPage(page))
target_writer.addPage(vm_pdf)
if not out_path:
target_file_name = source_path.split('.')[0] + '_wm.pdf'
else:
target_file_name = out_path
target_writer.write(open(target_file_name, 'wb'))
🎉🎉🎉 😜😜😜