2
4

More than 3 years have passed since last update.

Python用のDXFファイル読み書きライブラリ「ezdxf 」を使ってDXFファイルをPNGに変換する

Last updated at Posted at 2020-09-13

モジュールのバージョン

python v3.8.5
ezdxf v0.14
matplotlib v3.3.1

サンプルのDXFファイルを生成する

このサイトのソースコードをマルパクリしました。
ありがたや🙏
image.png

import ezdxf
import math

DXFVERSION  = 'R2010'
NUMCORNERS = 5

def create_dxf():
    """ 五芒星のDXFファイルを生成
    """
    # 星の角座標計算
    startangle = math.pi / 2.0
    pitchangle = math.pi * 2.0 / 5.0

    # オフセットと半径
    offset_x, offset_y, radius = 100, 100, 10

    points = []
    for i in range(0, NUMCORNERS):
        angle = startangle + pitchangle * i
        if 2.0 * math.pi < angle:
            angle = angle - 2.0 * math.pi
        x = math.cos(angle) * radius + offset_x
        y = math.sin(angle) * radius + offset_y
        points.append((x, y))

    # DXFインスタンス生成
    dxf = ezdxf.new(DXFVERSION)
    modelspace = dxf.modelspace()

    # 五芒星描画
    last, i, count = -1, 0, 0
    while count < NUMCORNERS + 1:
        if 0 <= last:
            modelspace.add_line(points[i], points[last])
        last = i
        i += 2
        if NUMCORNERS <= i:
            i -= NUMCORNERS
        count += 1

    # DXFファイル出力
    dxf.saveas('/<出力先のパス>/star.dxf')

if __name__ == "__main__":
    create_dxf()

 

DXFファイルをPNGファイルに変換する

ezdxfはDXFファイルを画像やPDFにするためのアドオンを持っているので、それを利用して変換します。

import ezdxf
from ezdxf import recover
from ezdxf.addons.drawing import matplotlib


def convert_dxf_to_png():
    try:
        dxf, auditor = recover.readfile('/<DXFファイルのパス>/star.dxf')
    except IOError as ioerror:
        print(ioerror)
        raise ioerror
    except ezdxf.DXFStructureError as dxf_structure_error:
        print(dxf_structure_error)
        raise dxf_structure_error

    if not auditor.has_errors:
        matplotlib.qsave(dxf.modelspace(), '/<出力先のパス>/star.png')

if __name__ == "__main__":
    convert_dxf_to_png()

こんな短いコードでDXFファイルをPNGに変換できました。
拡張子を「.jpg」とか「.pdf」にしても機能します。
Python便利!!!
image.png

2
4
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4