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合并

相关推荐
花酒锄作田6 小时前
使用 pkgutil 实现动态插件系统
python
前端付豪10 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽11 小时前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战11 小时前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋17 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者1 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者1 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh2 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅2 天前
Python函数入门详解(定义+调用+参数)
python
曲幽2 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama