如何使用Python打印PDF文件内所有对象(文本、图片、矢量图形等)
解决方案
PyMuPDF没有内置的统一接口直接导出所有类型的页面对象,但我们可以将不同类型元素的提取逻辑封装到同一个流程中,输出你需要的标准化格式,实现代码如下:
import fitz def extract_all_pdf_objects(pdf_path): doc = fitz.open(pdf_path) all_objects = [] # 遍历所有页面 for page_idx in range(len(doc)): page = doc.load_page(page_idx) # 1. 提取文本对象 text_dict = page.get_text("dict") for block in text_dict["blocks"]: if block["type"] == 0: # 文本块 for line in block["lines"]: for span in line["spans"]: obj = { "type": "TEXT", "content": span["text"], "position": f"{round(span['bbox'][0], 2)},{round(span['bbox'][1], 2)}", "font": span["font"], "font_size": round(span["size"], 2), "page": page_idx + 1 } all_objects.append(obj) # 2. 提取图片对象 images = page.get_images(full=True) for img in images: xref, smask_xref, width, height, bpc, colorspace, _, name, _, _ = img # 获取图片在页面上的位置 img_rects = page.get_image_rects(xref) for rect in img_rects: obj = { "type": "IMAGE", "content": f"Image {name} (size: {width}x{height})", "position": f"{round(rect[0], 2)},{round(rect[1], 2)}", "xref": xref, "page": page_idx + 1 } all_objects.append(obj) # 3. 提取矢量图形对象 drawings = page.get_drawings() for idx, draw in enumerate(drawings): obj = { "type": "VECTOR_GRAPHIC", "content": f"Path with {len(draw['items'])} segments", "position": f"{round(draw['rect'][0], 2)},{round(draw['rect'][1], 2)}", "fill_color": draw.get("fill"), "stroke_color": draw.get("color"), "page": page_idx + 1 } all_objects.append(obj) return all_objects # 调用示例 if __name__ == "__main__": objects = extract_all_pdf_objects("test.pdf") for obj_idx, obj in enumerate(objects): print(f"Object{obj_idx}") for k, v in obj.items(): print(f" {k.upper()}:{v}") print()
补充说明
- 你之前直接遍历xref拿不到文本的原因:PDF的文本内容存储在页面的内容流中,属于压缩/编码后的流式数据,不是独立的顶层xref对象,必须经过内容流解析才能提取出可读的文本及对应位置属性。
- 如果需要额外提取字体、页面对象属性,可以在代码中补充
doc.get_page_fonts()、页面对象的xref属性读取逻辑即可。
内容的提问来源于stack exchange,提问作者Basj
相关产品推荐
相关产品推荐

