如何搜索PDF中的图形元素、获取椭圆位置并修改圆形颜色
解决方案
你可以使用PyMuPDF(Python包名fitz)实现你提到的两个需求,它支持解析PDF页面的矢量图形元素,同时支持修改图形属性后重新导出PDF。
依赖安装
执行如下命令安装依赖库:pip install pymupdf
实现代码
import fitz # 打开待处理的PDF doc = fitz.open("test.pdf") blue = fitz.utils.getColor("blue") for page in doc: # 获取当前页面所有矢量图形 draw_items = page.get_drawings() ellipse_list = [] for item in draw_items: # 筛选椭圆类图形 if item["type"] == "ellipse": # 收集椭圆信息 ellipse_info = { "page_index": page.number + 1, "position_bbox": item["rect"], # 椭圆外接矩形坐标,格式为(左x,上y,右x,下y) "has_fill": item["fill"] is not None, "has_stroke": item["stroke"] is not None } ellipse_list.append(ellipse_info) # 判断是否为圆形:宽高差值小于误差阈值即判定为圆形 rect = item["rect"] width = rect.x1 - rect.x0 height = rect.y1 - rect.y0 if abs(width - height) < 1e-3: # 移除原有圆形 page.add_redact_annot(rect) page.apply_redactions() # 重新绘制蓝色圆形,保留原有填充/描边样式 if item["fill"] is not None: page.draw_ellipse(rect, fill=blue, width=item["width"] if item["stroke"] else 0) else: page.draw_ellipse(rect, color=blue, width=item["width"]) # 打印当前页椭圆信息 print(f"第{page.number+1}页椭圆列表:") for info in ellipse_list: print(info) # 保存修改后的PDF doc.save("modified_test.pdf") doc.close()
效果说明
- 运行代码后控制台会输出所有页面的椭圆位置、填充/描边属性信息
- 生成的
modified_test.pdf中所有圆形会被修改为蓝色,其余矩形、椭圆样式保持不变 - 坐标单位可根据你生成PDF时使用的英寸单位自行做数值换算即可
内容的提问来源于stack exchange,提问作者Gangula
相关产品推荐
相关产品推荐

