You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python定位PDF指定区域并将其保存为PNG?

实现PDF指定区域截取为PNG的方案

你的思路完全可行,用pdfplumber就能独立完成需求,不需要复杂工具组合,下面是具体指引:

工具选择理由

  • PyPDF:仅擅长PDF拆分、合并等基础操作,文本定位和图像裁剪能力薄弱,不适用你的场景。
  • pdfminer:文本提取精度高,但需要手动处理坐标映射、图像渲染,对新手门槛高。
  • pdfplumber:基于pdfminer开发,封装了更易用的API,既能精准获取文本的页码、坐标,又能直接渲染页面并裁剪图像,完美匹配你的需求,是新手首选。

具体实现步骤

1. 定位标题的页码与Y坐标

遍历PDF页面,匹配目标起始标题和下一个标题,记录它们的位置信息:

import pdfplumber

# 替换为你的目标标题
target_start_title = "目标起始标题"
target_end_title = "下一个标题"
start_y = None
end_y = None
target_page = None

with pdfplumber.open("你的文件.pdf") as pdf:
    for page in pdf.pages:
        # 提取页面所有带坐标的文本对象
        text_items = page.extract_words(use_text_flow=True)
        for item in text_items:
            if item["text"] == target_start_title:
                start_y = item["top"]
                target_page = page
            # 找到起始标题后再找结束标题
            elif start_y is not None and item["text"] == target_end_title:
                end_y = item["top"]
                break
        if start_y and end_y:
            break

2. 裁剪指定区域并保存为PNG

拿到坐标后,直接渲染页面并裁剪目标区域:

if target_page and start_y and end_y:
    page_width = target_page.width
    # 将页面渲染为可操作的图像对象
    page_img = target_page.to_image()
    # 裁剪区域:(左, 上, 右, 下)
    cropped_area = page_img.crop((0, start_y, page_width, end_y))
    # 保存为PNG
    cropped_area.save("截取的区域.png", format="PNG")

额外注意事项

  • 如果起始标题和下一个标题不在同一页,需要分步骤截取:先截起始页从start_y到页底,再截中间整页,最后截结束页从页顶到end_y,再用PIL等工具拼接图片。
  • 若标题存在换行、格式差异,可改用模糊匹配,比如target_start_title in item["text"]。

内容的提问来源于stack exchange,提问作者Gaspode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 14:44:57