kompas_window/export_opened_to_raster.py

181 lines
7.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.

import os
import pythoncom
from win32com.client import Dispatch, gencache
from PIL import Image, ImageDraw, ImageFont
def export_opened_to_raster():
try:
# Инициализация счетчиков
counters = {
'total_processed': 0,
'jpg_created': 0,
'dxf_created': 0,
'pdf_created': 0,
'errors': 0
}
# Списки для хранения путей к файлам
created_files = {
'jpg': [],
'dxf': [],
'pdf': None
}
# Получаем API интерфейсов
api5_module = gencache.EnsureModule("{0422828C-F174-495E-AC5D-D31014DBBE87}", 0, 1, 0)
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)
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
print("=== НАЧАЛО ОБРАБОТКИ ДОКУМЕНТОВ ===")
# Обработка документов
for i in range(application.Documents.Count):
try:
doc = application.Documents.Open(i)
counters['total_processed'] += 1
doc_type = doc.DocumentType
if doc_type not in [
k_constants.ksDocumentDrawing,
k_constants.ksDocumentFragment,
k_constants.ksDocumentSpecification,
]:
continue
doc_path = doc.Path
doc_name = os.path.splitext(doc.Name)[0]
print(f"\nОбработка документа {counters['total_processed']}: {doc_name}")
doc_api5 = api5_api.ActiveDocument2D()
doc_api7 = module.IKompasDocument(doc)
# Сохраняем имя первого документа для PDF
if 'first_doc_name' not in locals():
first_doc_name = doc_api7.LayoutSheets.ItemByNumber(1).Stamp.Text(2).Str
if doc_type == k_constants.ksDocumentSpecification:
doc_api5 = api5_api.SpcActiveDocument()
if doc_api5 and 'rasterParJPG' not in locals():
rasterParJPG = doc_api5.RasterFormatParam()
rasterParJPG.Init()
rasterParJPG.colorBPP = 8
rasterParJPG.colorType = 3
rasterParJPG.extResolution = 96
rasterParJPG.format = 0
rasterParJPG.greyScale = False
# Создаем папки и сохраняем файлы
for ext in ["jpg", "dxf"]:
path = os.path.join(doc_path, ext)
os.makedirs(path, exist_ok=True)
full_path = os.path.join(path, f"{doc_name}.{ext}")
try:
if ext == "jpg":
doc_api5.SaveAsToRasterFormat(full_path, rasterParJPG)
counters['jpg_created'] += 1
created_files['jpg'].append(full_path)
print(f"Создан JPG: {full_path}")
# Загружаем изображение для PDF
img = Image.open(full_path)
if 'images' not in locals():
images = []
images.append(img)
elif ext == "dxf":
doc_api5.ksSaveToDXF(full_path)
counters['dxf_created'] += 1
created_files['dxf'].append(full_path)
print(f"Создан DXF: {full_path}")
except Exception as e:
print(f"Ошибка при создании {ext.upper()}: {str(e)}")
counters['errors'] += 1
except Exception as e:
print(f"Ошибка при обработке документа {i}: {str(e)}")
counters['errors'] += 1
# Создаем PDF отчет, если есть изображения
if 'images' in locals() and images:
try:
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
pdf_filename = f"{first_doc_name}_pages.pdf"
pdf_output_path = os.path.join(desktop_path, pdf_filename)
# Создаем титульную страницу
title_image = Image.new("RGB", (images[0].width, 200), color="white")
draw = ImageDraw.Draw(title_image)
try:
font = ImageFont.truetype("arial.ttf", size=48)
except:
font = ImageFont.load_default()
title_text = f"{first_doc_name}\nВсего страниц: {len(images)}"
draw.text((10, 50), title_text, fill="black", font=font, spacing=10)
images.insert(0, title_image)
# Сохраняем PDF
images[0].save(
pdf_output_path,
"PDF",
resolution=96.0,
save_all=True,
append_images=images[1:],
)
counters['pdf_created'] += 1
created_files['pdf'] = pdf_output_path
print(f"\nСоздан PDF отчет: {pdf_output_path}")
except Exception as e:
print(f"Ошибка при создании PDF: {str(e)}")
counters['errors'] += 1
# Формируем итоговый отчет
report = [
f"Всего обработано документов: {counters['total_processed']}",
f"Создано JPG файлов: {counters['jpg_created']}",
f"Создано DXF файлов: {counters['dxf_created']}",
f"Создано PDF отчетов: {counters['pdf_created']}",
f"Ошибок при обработке: {counters['errors']}",
]
if created_files['jpg']:
report.append("\nJPG файлы:")
report.extend(created_files['jpg'])
if created_files['dxf']:
report.append("\nDXF файлы:")
report.extend(created_files['dxf'])
if created_files['pdf']:
report.append("\nPDF отчет:")
report.append(created_files['pdf'])
return "\n".join(report)
except Exception as e:
return f"Критическая ошибка: {str(e)}"