PyMuPDF分析PDF图纸

百度搜的PyMuPDF的使用都是千篇一律,就几个简单用法,建议还是去翻官方网站的教程。最近要对Autocad 和SolidWorks 转换成PDF的图纸进行分析,一直摸不着头脑,看了官方网站才了解一些。转换成PDF的图纸元素叫 Shape 和 Graphics,还有一点 text blocks,官方的源码例子如下,简单好用:

import pymupdf  #已经不叫fitz了,就是pymupdf,如果版本老,就卸载fitz
doc = pymupdf.open("some.file")
page = doc[0]
paths = page.get_drawings()  # extract existing drawings  最重要的一句
# this is a list of "paths", which can directly be drawn again using Shape
# -------------------------------------------------------------------------
#
# define some output page with the same dimensions
outpdf = pymupdf.open()
outpage = outpdf.new_page(width=page.rect.width, height=page.rect.height)
shape = outpage.new_shape()  # make a drawing canvas for the output page
# --------------------------------------
# loop through the paths and draw them
# --------------------------------------
for path in paths:
    # ------------------------------------
    # draw each entry of the 'items' list
    # ------------------------------------
    for item in path["items"]:  # these are the draw commands
        if item[0] == "l":  # line
            shape.draw_line(item[1], item[2])
        elif item[0] == "re":  # rectangle
            shape.draw_rect(item[1])
        elif item[0] == "qu":  # quad
            shape.draw_quad(item[1])
        elif item[0] == "c":  # curve
            shape.draw_bezier(item[1], item[2], item[3], item[4])  //贝塞尔曲线
        else:
            raise ValueError("unhandled drawing", item)
    # ------------------------------------------------------
    # all items are drawn, now apply the common properties
    # to finish the path
    # ------------------------------------------------------
    shape.finish(
        fill=path["fill"],  # fill color
        color=path["color"],  # line color
        dashes=path["dashes"],  # line dashing
        even_odd=path.get("even_odd", True),  # control color of overlaps
        closePath=path["closePath"],  # whether to connect last and first point
        lineJoin=path["lineJoin"],  # how line joins should look like
        lineCap=max(path["lineCap"]),  # how line ends should look like
        width=path["width"],  # line width
        stroke_opacity=path.get("stroke_opacity", 1),  # same value for both
        fill_opacity=path.get("fill_opacity", 1),  # opacity parameters
        )
# all paths processed - commit the shape to its page
shape.commit()
outpdf.save("drawings-page-0.pdf")

如何删除Drawings:

paths = page.get_drawings()
rect = paths[0]["rect"]  # rectangle of the 1st drawing
page.add_redact_annot(rect)
page.apply_redactions(0,2,1)  # potentially set options for any of images, drawings, text

如何创建Drawings,for example: draw a circle:

# Draw a circle on the page using the Page method
page.draw_circle((center_x, center_y), radius, color=(1, 0, 0), width=2)

# Draw a circle on the page using a Shape object
shape = page.new_shape()
shape.draw_circle((center_x, center_y), radius)
shape.finish(color=(1, 0, 0), width=2)
shape.commit(overlay=True)

The Shape object can be used to combine multiple drawings that should receive common properties as specified by Shape.finish().

### 使用 PyMuPDF (Fitz) 提取 PDF 中的文本 PyMuPDF 是一个功能强大且灵活的库,能够高效地处理 PDF 文件中的各种内容,包括但不限于文本、片和其他嵌入对象。以下是关于如何使用 PyMuPDF 提取 PDF 文件中文本的具体方法。 #### 安装 PyMuPDF 在开始之前,请确保已安装 `pymupdf` 库。可以通过 pip 工具轻松完成安装: ```bash pip install pymupdf ``` --- #### 示例代码:提取 PDF 中的所有文本 以下是一段完整的 Python 代码示例,展示如何利用 PyMuPDF 提取 PDF 文件中的全部文本内容: ```python import fitz # PyMuPDF 的别名 def extract_text_from_pdf(pdf_path): """ 提取指定 PDF 文件中的所有文本。 参数: pdf_path (str): 输入 PDF 文件的路径 返回: str: 整个 PDF 文件中的文本内容 """ doc = fitz.open(pdf_path) # 打开 PDF 文件 total_text = "" for page_num in range(len(doc)): # 遍历每一页 page = doc.load_page(page_num) # 加载当前页 text = page.get_text("text") # 提取页面上的文本 total_text += text + "\n" # 将文本追加到总字符串中 return total_text.strip() # 移除多余的空白字符 # 主程序入口 if __name__ == "__main__": input_pdf_path = "example.pdf" # 替换为实际的 PDF 文件路径 extracted_text = extract_text_from_pdf(input_pdf_path) print(extracted_text) # 输出提取的文本 ``` 上述代码实现了从给定 PDF 文件中逐页加载并提取文本的功能[^3]。 --- #### 自定义提取逻辑 除了提取整篇文档的文本外,还可以根据需求自定义提取行为。例如,只提取某几页的内容或者过滤掉不需要的部分。 ##### 只提取部分页面的文本 如果只需要提取特定范围内的页面(如第 2 至第 5 页),可以调整循环条件如下所示: ```python start_page = 1 # 开始页码(索引从 0 开始) end_page = 4 # 结束页码(包含) for page_num in range(start_page, end_page + 1): page = doc.load_page(page_num) text = page.get_text("text") total_text += text + "\n" ``` --- #### 提取带样式的文本(如加粗或斜体) 类似于 `pdfplumber` 的实现方式,PyMuPDF 同样支持按样式筛选文本。通过解析页面上的字形属性,可识别出特殊格式的文本,例如 **加粗** 或 *斜体* 字符。 以下是一个检测加粗字体的例子: ```python def is_bold(font_name): """ 判断字体名称是否表示加粗风格 """ return "bold" in font_name.lower() def extract_bold_text(pdf_path): """ 提取 PDF 文件中的加粗文本。 参数: pdf_path (str): 输入 PDF 文件的路径 返回: list: 包含所有加粗文本的列表 """ doc = fitz.open(pdf_path) bold_texts = [] for page_num in range(len(doc)): page = doc.load_page(page_num) blocks = page.get_text("dict")["blocks"] # 获取页面块信息 for block in blocks: if block["type"] != 0: # 类型为 0 表示文本块 continue lines = block["lines"] for line in lines: spans = line["spans"] for span in spans: if is_bold(span["font"]): # 检查字体是否为加粗 bold_texts.append(span["text"]) return bold_texts # 测试函数 input_pdf_path = "example.pdf" bold_texts = extract_bold_text(input_pdf_path) print(bold_texts) ``` 这段代码会遍历每个页面的文本块,并逐一检查其中是否存在加粗字体的字符[^2]。 --- #### 注意事项 - 并非所有的 PDF 文件都以纯文本形式存储内容。有些可能是由扫描仪生成的文件,这种情况下需要借助 OCR 技术才能提取有用的信息。 - 对于受密码保护的 PDF 文件,在尝试读取前需调用相应的解锁接口提供正确的密钥[^1]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值