Python给PDF添加水印(极速版)

使用PyMuPDF给PDF文件添加水印,秒级处理!!!直接上代码

python 复制代码
from PyPDF2 import PdfReader, PdfWriter

def add_watermark_pymupdf(input_pdf, watermark_pdf, output_pdf,
                          position='full', opacity=0.3):
    """
    使用PyMuPDF给PDF添加水印文件

    Args:
        input_pdf: 输入PDF路径
        watermark_pdf: 水印PDF文件路径
        output_pdf: 输出PDF路径
        position: 水印位置 ('full', 'center', 'bottom-right', 'top-left')
        opacity: 水印透明度 (0.0-1.0)

    Returns:
        处理后的PDF路径
    """
    start_time = time.time()

    # 打开源PDF和水印PDF
    src_doc = fitz.open(input_pdf)
    watermark_doc = fitz.open(watermark_pdf)

    # 获取水印页面(假设水印PDF只有一页)
    watermark_page = watermark_doc[0]

    # 获取水印页面尺寸
    watermark_rect = watermark_page.rect
    watermark_width = watermark_rect.width
    watermark_height = watermark_rect.height

    total_pages = len(src_doc)
    print(f"开始处理 {total_pages} 页PDF...")

    # 处理每一页
    for page_num in range(total_pages):
        if page_num % 10 == 0:
            print(f"处理进度: {page_num + 1}/{total_pages}")

        page = src_doc[page_num]
        page_rect = page.rect
        page_width = page_rect.width
        page_height = page_rect.height

        # 全页面覆盖
        scale_x = page_width / watermark_width
        scale_y = page_height / watermark_height
        scale = min(scale_x, scale_y)

        new_width = watermark_width * scale
        new_height = watermark_height * scale

        x = (page_width - new_width) / 2
        y = (page_height - new_height) / 2

        clip_rect = fitz.Rect(0, 0, watermark_width, watermark_height)

        # 创建要插入的矩形区域
        target_rect = fitz.Rect(x, y, x + new_width, y + new_height)

        # 插入水印
        page.show_pdf_page(
            target_rect,  # 在页面上的位置
            watermark_doc,  # 水印文档
            0,  # 水印页码
            clip=clip_rect,  # 裁剪区域
            keep_proportion=True,  # 保持比例
            overlay=True,  # 覆盖模式(作为水印)
            oc=0  # 可选内容组(用于透明度)
        )

    # 保存输出
    src_doc.save(output_pdf)
    src_doc.close()
    watermark_doc.close()

    elapsed = time.time() - start_time
    # print(f"处理完成!耗时: {elapsed:.2f}秒,平均每页: {elapsed / total_pages:.3f}秒")

    return output_pdf

注意 :水印可以直接插入到PDF中,然后使用脚本将水印PDF目标PDF合并

相关推荐
SelectDB8 小时前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
荣码16 小时前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
金銀銅鐵1 天前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li1 天前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸1 天前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学1 天前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田2 天前
Pydantic校验配置文件
python
hboot2 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi3 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi3 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab