Python—PDF文件中添加水印文字

in TEST with 1 comment
import os
import tempfile
from pdfrw import PdfReader, PdfWriter, PageMerge
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.pagesizes import letter, landscape
from reportlab.lib.colors import Color
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

# 设置字体路径并将字体注册到pdfmetrics中
FONT_PATH = "/System/Library/Fonts/Supplemental/Arial Unicode.ttf"
pdfmetrics.registerFont(TTFont("Arial Unicode", FONT_PATH))


def add_watermark_to_pdf(input_pdf_path, output_pdf_path, watermark_text):
    """
    在PDF文件中添加水印文字

    :param input_pdf_path: 待处理的PDF文件路径
    :param output_pdf_path: 生成的带水印的PDF文件路径
    :param watermark_text: 水印文字
    """
    # 读取PDF文件
    input_pdf = PdfReader(input_pdf_path)
    # 新建一个PdfWriter对象用于写入新的PDF文件
    pdf_writer = PdfWriter()

    for pdf_page in input_pdf.pages:
        # 获取页面大小
        page_width = float(pdf_page.MediaBox[2])
        page_height = float(pdf_page.MediaBox[3])

        # 创建一个PDF画布并设置大小
        c = Canvas(None, pagesize=(page_width, page_height))
        # 设置字体
        c.setFont("Arial Unicode", 36)
        # 保存画布状态
        c.saveState()
        # 将画布中心定位在页面中心
        c.translate(page_width / 2, page_height / 2)
        # 旋转画布
        c.rotate(45)
        # 设置水印透明度
        alpha = 0.2
        # 设置水印颜色
        fill_color = Color(0, 0, 0, alpha)
        c.setFillColor(fill_color)
        # 在画布中心添加水印文字
        c.drawCentredString(2, 0, watermark_text)
        # 恢复画布状态
        c.restoreState()

        # 将画布转换为PDF页面并合并到原始页面上
        c.showPage()
        with tempfile.NamedTemporaryFile(delete=True) as watermark_temp:
            watermark_temp.write(c.getpdfdata())
            watermark_temp.flush()
            watermark_page = PageMerge().add(pdf_page).add(
                PdfReader(watermark_temp.name).pages[0]).render()
            pdf_writer.addPage(watermark_page)

    # 将新生成的PDF文件写入到磁盘
    with open(output_pdf_path, "wb") as output_file:
        pdf_writer.write(output_file)


if __name__ == "__main__":
    # 测试
    input_pdf_path = "/Users/liuliang/Desktop/测试PDF测试PDF.pdf"
    output_pdf_path = "/Users/liuliang/Desktop/NEW.pdf"
    watermark_text = "TEST_测试124"

    # 添加水印到PDF文件中
    add_watermark_to_pdf(input_pdf_path, output_pdf_path, watermark_text)