kompas_window/save_to_iges.py

86 lines
3.3 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.

# pip install pywin32
import pythoncom
from win32com.client import Dispatch, gencache
import os
import sys
def save_opened_to_iges():
try:
# Инициализация COM системы
pythoncom.CoInitialize()
# Получаем API интерфейсы
api5_module = gencache.EnsureModule("{0422828C-F174-495E-AC5D-D31014DBBE87}", 0, 1, 0)
if api5_module is None:
raise Exception("Не удалось загрузить API Kompas 5")
api5_api = api5_module.KompasObject(
Dispatch("Kompas.Application.5")._oleobj_.QueryInterface(
api5_module.KompasObject.CLSID, pythoncom.IID_IDispatch
)
)
module = gencache.EnsureModule("{69AC2981-37C0-4379-84FD-5DD2F3C0A520}", 0, 1, 0)
if module is None:
raise Exception("Не удалось загрузить API Kompas 7")
api = module.IKompasAPIObject(
Dispatch("Kompas.Application.7")._oleobj_.QueryInterface(
module.IKompasAPIObject.CLSID, pythoncom.IID_IDispatch
)
)
k_constants = gencache.EnsureModule(
"{75C9F5D0-B5B8-4526-8681-9903C567D2ED}", 0, 1, 0
).constants
application = module.IApplication(api)
application.Visible = True
result = []
ext = "igs"
saved_files = 0
for i in range(application.Documents.Count):
try:
doc = application.Documents.Open(i)
doc_type = doc.DocumentType
if doc_type in [k_constants.ksDocumentPart, k_constants.ksDocumentAssembly]:
doc.Active = True
doc_path = doc.Path
doc_name = os.path.splitext(doc.Name)[0]
save_path = os.path.join(doc_path, ext)
os.makedirs(save_path, exist_ok=True)
filename = f"{doc_name}.{ext}"
full_path = os.path.normpath(os.path.join(save_path, filename))
doc_3d = module.IKompasDocument3D(doc)
doc_api5 = api5_api.ActiveDocument3D()
save_params = doc_api5.AdditionFormatParam()
save_params.Init()
save_params.format = k_constants.ksConverterToIGES
doc_api5.SaveAsToAdditionFormat(full_path, save_params)
saved_files += 1
result.append(f"Успешно сохранено: {full_path}")
except Exception as e:
result.append(f"Ошибка при обработке документа {i} ({doc.Name}): {str(e)}")
if saved_files > 0:
result.insert(0, f"\nУспешно сохранено файлов: {saved_files}")
else:
result.append("Не найдено подходящих документов для сохранения")
return "\n".join(result)
except Exception as e:
return f"Критическая ошибка: {str(e)}"
finally:
pythoncom.CoUninitialize()
if __name__ == "__main__":
print(save_opened_to_iges())