使用python保存autocad文件(.dwg)

2024-04-16 07:59:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用win32com自动化autocad中的一些简单任务。除了能够保存文件外,它大部分都工作得很好。我的目标是打开一个(模板)文件,根据需要进行调整,然后将文件另存为.dwg文件,同时将模板留空,以便下次使用。你知道吗

下面是我的代码示例:

import win32com.client


acad = win32com.client.dynamic.Dispatch("AutoCAD.Application")
acad.Visible=True

doc = acad.Documents.Open("C:\\Template_folder\\Template.dwg")
doc.SaveAs("C:\\Output_folder\\Document1.dwg")

### Adjust dwg ###

doc.Save()

加载模板文件可以很好地工作,但是在尝试保存文件(使用SaveAs method))时,出现以下错误:

    doc.SaveAs("C:\\Output_folder\\Document1.dwg")
  File "<COMObject Open>", line 3, in SaveAs
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'AutoCAD', 'Error saving the document', 'C:\\Program Files\\Autodesk\\AutoCAD 2019\\HELP\\OLE_ERR.CHM', -2145320861, -2145320861), None)

任何提示或资源将不胜感激!你知道吗


Tags: 文件client模板outputdoctemplateopenfolder
1条回答
网友
1楼 · 发布于 2024-04-16 07:59:10

查看用于AutoCAD的ActiveX API的文档,它看起来像是在调用Documents.Open()时,它应该返回打开的文档并将其设置为活动文档。这就是说,看起来这并不是实际情况。您的问题的解决方案应该如下所示:

import win32com.client

acad = win32com.client.dynamic.Dispatch("AutoCAD.Application")
acad.Visible=True

# Open a new document and set it as the active document
acad.Documents.Open("C:\\Template_folder\\Template.dwg")

# Set the active document before trying to use it
doc = acad.ActiveDocument

# Save the documet
doc.SaveAs("C:\\Output_folder\\Document1.dwg")

### Adjust dwg ###

doc.Save()

你可以在这里找到文档

AutoCAD.Application

Application.Documents

Documents.Open()

Application.ActiveDocument

相关问题 更多 >