当前位置:   article > 正文

CAD 文件(DXF / DWG)转换为(DXF / PDF / PNG / SVG)

CAD 文件(DXF / DWG)转换为(DXF / PDF / PNG / SVG)

方法一Github

这个是ezdxf出品的,可以使用命令行的方式进行转换

ezdxf draw -o file.<png|svg|pdf> <file.dxf>
  • 1

也可以自己改动代码
examples/addons/drawing/pdf_export.py
但是直接运行会有误,以下是我改动后的代码:

from ezdxf.addons import odafc
import ezdxf
import os
import json
import re
import pathlib
import time
from ezdxf.addons.drawing import Frontend, RenderContext
from ezdxf.addons.drawing import pymupdf, layout

def transparency(filepath):
    doc = ezdxf.readfile(filepath)
    msp = doc.modelspace()
    backend = pymupdf.PyMuPdfBackend()
    Frontend(RenderContext(doc), backend).draw_layout(msp)
    pdf_bytes = backend.get_pdf_bytes(
        layout.Page(0, 0, layout.Units.mm), settings=layout.Settings(scale=10)
    )
    pdf_file = os.path.join(os.path.dirname(filepath), os.path.basename(filepath).split(".")[0] + "_dwg.pdf")
    (pathlib.Path(pdf_file)).write_bytes(pdf_bytes)
def export(filepath: pathlib.Path, layout_names=("Model",), scale=1):
    print(f"\nprocessing: {filepath.name}")
    t0 = time.perf_counter()
    doc = ezdxf.readfile(filepath)
    t1 = time.perf_counter()
    print(f"loading time: {t1 - t0: .3f} seconds")
    for layout_name in layout_names:
        outname = filepath.stem + f"-[{layout_name}]" + ".pdf"
        CWD = os.path.dirname(filepath)
        outname = pathlib.Path(CWD+"/"+outname)
        print(outname)
        t1 = time.perf_counter()
        if layout_name == "Model":
            dxf_layout = doc.modelspace()
            page = layout.Page(
                0,  # auto-detect
                0,  # auto-detect
                layout.Units.mm,  # 1 drawing unit = 1mm
                layout.Margins.all(0),
                max_width=1189,  # limit page width to 1189mm
                max_height=841,  # limit page height to 841mm
            )
            settings = layout.Settings(scale=scale)
        else:
            try:
                dxf_layout = doc.paperspace(layout_name)
            except KeyError:
                print(f"Layout '{layout_name}' not found")
                continue
            page = layout.Page.from_dxf_layout(dxf_layout)
            settings = layout.Settings(
                fit_page=False,
                scale=dxf_layout.get_plot_unit_scale_factor() * scale,
            )

        backend = pymupdf.PyMuPdfBackend()
        # You can get the content bounding box in DXF drawing units, before you create the
        # PDF output to calculate page size, margins, scaling factor and so on ...
        # content_extents = backend.bbox()

        Frontend(RenderContext(doc), backend).draw_layout(dxf_layout)
        pdf_bytes = backend.get_pdf_bytes(page, settings=settings)
        t2 = time.perf_counter()
        print(f"render time: {t2 - t1: .3f} seconds")
        
        (outname).write_bytes(pdf_bytes)

class dwg_analysis:
    def __init__(self, filepath, format):
        self.filepath = filepath
        self.format = format

    def dwg2data(self):
        
        dxf_file = os.path.join(os.path.dirname(self.filepath), os.path.basename(self.filepath).split(".")[0] + ".dxf")
        odafc.convert(self.filepath, dxf_file, version='R2000', replace=True)  
        
        doc = ezdxf.readfile(dxf_file)
        msp = doc.modelspace()
        pdf_file = export(pathlib.Path(dxf_file),["Model", "PLAN", "SECTION"],)
        # pdf_file = transparency(dxf_file)

        data = {}
                 # 获取TEXT实体
        texts = msp.query('TEXT')
        text_data = []
        if self.format == "dwg_text":
            for text in texts:
                decoded_str = re.sub(r'\\U\+([0-9A-Fa-f]{4})', lambda m: chr(int(m.group(1), 16)), text.dxf.text)
                text_data.append(decoded_str)
            filtered_list = [item for item in text_data if not (isinstance(item, (int, float)) or (isinstance(item, str) and str.isdigit(item)) or (isinstance(item, str) and item.isdigit()))]
            data['document'] = self.remove_duplicates(filtered_list)
            data['metadata'] =  pdf_file
            data['format'] =  format
            return data

        for text in texts:
            decoded_str = re.sub(r'\\U\+([0-9A-Fa-f]{4})', lambda m: chr(int(m.group(1), 16)), text.dxf.text)
            text_info = {
                'text': decoded_str,
                'insert': (text.dxf.insert[0], text.dxf.insert[1]),
                'height': text.dxf.height,
                'rotation': text.dxf.rotation,
                'style': text.dxf.style,
                'layer': text.dxf.layer
            }
            text_data.append(text_info)

        data['TEXT'] = text_data
                # 获取LINE实体
        lines = msp.query('LINE')
        line_data = []
        for line in lines:
            line_data.append({
                'start': (line.dxf.start[0], line.dxf.start[1]),
                'end': (line.dxf.end[0], line.dxf.end[1])
            })
        data['LINE'] = line_data

        # 获取POLYLINE实体
        polylines = msp.query('POLYLINE')
        polyline_data = []
        for polyline in polylines:
            points = []
            for point in polyline.points():
                points.append((point[0], point[1]))
            polyline_data.append(points)
        data['POLYLINE'] = polyline_data

        # 获取CIRCLE实体
        circles = msp.query('CIRCLE')
        circle_data = []
        for circle in circles:
            circle_data.append({
                'center': (circle.dxf.center[0], circle.dxf.center[1]),
                'radius': circle.dxf.radius
            })
        data['CIRCLE'] = circle_data

        # 获取ARC实体
        arcs = msp.query('ARC')
        arc_data = []
        for arc in arcs:
            arc_data.append({
                'center': (arc.dxf.center[0], arc.dxf.center[1]),
                'radius': arc.dxf.radius,
                'start_angle': arc.dxf.start_angle,
                'end_angle': arc.dxf.end_angle
            })
        data['ARC'] = arc_data

        # 获取ELLIPSE实体
        ellipses = msp.query('ELLIPSE')
        ellipse_data = []
        for ellipse in ellipses:
            ellipse_data.append({
                'center': (ellipse.dxf.center[0], ellipse.dxf.center[1]),
                'major_axis': (ellipse.dxf.major_axis[0], ellipse.dxf.major_axis[1]),
                'ratio': ellipse.dxf.ratio,
                'start_param': ellipse.dxf.start_param,
                'end_param': ellipse.dxf.end_param
            })
        data['ELLIPSE'] = ellipse_data

        return data
    def remove_duplicates(self,lst):
        res = []
        seen = {}
        for i in lst:
            if i not in seen:
                seen[i] = 1
                res.append(i)
        return res


# 示例调用
if __name__ == "__main__":
    # DWG文件路径
    DWG_path = "/home/hyh/data/Maintenance_test_data/AIN.dwg"
    format = "dwg_text"
    dwf = dwg_analysis(DWG_path,format)
    dwf_txt = dwf.dwg2data()
    output_path = os.path.join(os.path.dirname(DWG_path), os.path.basename(DWG_path).split(".")[0] + "_" +format+ ".json")
    with open(output_path, 'w', encoding='utf-8') as f:
        json.dump(dwf_txt, f, ensure_ascii=False, indent=4)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185

方法二Github

一位国内大神出品的项目

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/689484

推荐阅读
相关标签