dxf2png get white background
Wananrd opened this issue · comments
I am a AI student. I am not good at CAD. My project needs to use dxf to png.
I following the document learned how to transform, it succeed in 99.99% .dxf files, but some of them failed.
Please help me find where is problems and how to solve it.
Here is my dxf img and code.
address_dxf.zip
`import ezdxf
from ezdxf.addons.drawing import Frontend, RenderContext, pymupdf, layout, config
import os
def dxf2png(file_name, save_folder):
if file_name.endswith(".dxf"):
try:
doc = ezdxf.readfile(filename=file_name)
# 这里是你的其他处理代码
msp = doc.modelspace()
# 1. create the render context
context = RenderContext(doc)
# 2. create the backend
backend = pymupdf.PyMuPdfBackend()
# 3. create and configure the frontend
cfg = config.Configuration(background_policy=config.BackgroundPolicy.WHITE)
frontend = Frontend(context, backend, config=cfg)
# 4. draw the modelspace
frontend.draw_layout(msp)
# 5. create an A4 page layout
page = layout.Page(891, 891, layout.Units.mm, margins=layout.Margins.all(20))
# 6. get the PDF rendering as bytes
png_bytes = backend.get_pixmap_bytes(page, fmt="png", dpi=96)
# 7. save png
save_name = file_name.split("\")[-1].split(".dxf")[0] + ".png"
save_file = os.path.join(save_folder, save_name)
with open(save_file, "wb") as fp:
fp.write(png_bytes)
except ezdxf.lldxf.const.DXFStructureError as e:
print("捕获到DXFStructureError异常:", e)
# 这里是处理异常的代码
if name == "main":
# 单独文件处理
dxf_file = "3B7P-L12100-1.dxf"
save_folder = "./result"
dxf2png(dxf_file, save_folder)`