dxfedit/03_Python_OpenSource_DXF/convert_dxf_to_pdf.py
2025-09-09 18:42:30 +08:00

65 lines
2.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import ezdxf
from ezdxf.addons.drawing import RenderContext, Frontend
from ezdxf.addons.drawing.matplotlib import MatplotlibBackend
import matplotlib.pyplot as plt
import os
import sys
# --- 配置 ---
# 将脚本的父目录项目根目录添加到Python路径中
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_ROOT = os.path.dirname(SCRIPT_DIR)
sys.path.append(PROJECT_ROOT)
INPUT_DXF_NAME = "图签测试.dxf"
OUTPUT_PDF_NAME = "图签测试_from_dxf.pdf"
INPUT_DXF_PATH = os.path.join(SCRIPT_DIR, INPUT_DXF_NAME)
# 确保输出目录存在
output_dir = os.path.join(PROJECT_ROOT, "04_Test_Files", "结果")
os.makedirs(output_dir, exist_ok=True)
OUTPUT_PDF_PATH = os.path.join(output_dir, OUTPUT_PDF_NAME)
def dxf_to_pdf(input_path, output_path):
"""
将指定的 DXF 文件渲染并保存为 PDF。
"""
if not os.path.exists(input_path):
print(f"错误: 输入的 DXF 文件未找到: '{input_path}'")
return
try:
print(f"--- 正在加载 DXF 文件: {os.path.basename(input_path)} ---")
doc = ezdxf.readfile(input_path)
msp = doc.modelspace()
# 创建 Matplotlib Figure 和 Axes
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1])
# 设置渲染上下文和后端
ctx = RenderContext(doc)
out = MatplotlibBackend(ax)
print("--- 开始渲染 DXF 内容 ---")
# 使用 ezdxf 的绘图插件渲染模型空间
Frontend(ctx, out).draw_layout(msp, finalize=True)
print(f"--- 正在将渲染结果保存为 PDF: {os.path.basename(output_path)} ---")
# 保存为 PDFdpi可以调整清晰度bbox_inches='tight'会自动裁剪空白边缘
fig.savefig(output_path, dpi=300, bbox_inches='tight', pad_inches=0.1)
plt.close(fig)
print("\n操作成功!")
print(f"PDF 文件已保存到: '{output_path}'")
except IOError:
print(f"错误: 无法读取文件: '{input_path}'")
except Exception as e:
print(f"处理并转换 DXF 文件时发生未知错误: {e}")
if __name__ == "__main__":
dxf_to_pdf(INPUT_DXF_PATH, OUTPUT_PDF_PATH)