kompas_window/export_opened_to_raster.py

147 lines
6.5 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 pythoncom
from win32com.client import Dispatch, gencache
import os
from PIL import Image, ImageDraw, ImageFont
def export_opened_to_raster():
try:
# Получаем API интерфейсов версии 5
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)
save_param = None
images = []
application.Visible = True
first_doc_name = None # Для хранения имени первого документа
print("Начинаем обработку документов КОМПАС...")
for i in range(application.Documents.Count):
try:
doc = application.Documents.Open(i)
doc_type = doc.DocumentType
# Проверяем тип документа: чертеж, фрагмент, спецификация
if doc_type in [
k_constants.ksDocumentDrawing,
k_constants.ksDocumentFragment,
k_constants.ksDocumentSpecification,
]:
doc.Active = True
doc_path = doc.Path
doc_name = "-".join(doc.Name.split(".")[:-1])
print(f"Обрабатываем документ: {doc_name}")
doc_api5 = api5_api.ActiveDocument2D()
doc_api7 = module.IKompasDocument(doc)
# Сохраняем имя первого документа
if first_doc_name is None:
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 save_param is None:
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 = f"{doc_path}{ext}/"
filename = f"{doc_name}.{ext}"
full_path = os.path.join(path, filename)
if not os.path.exists(path):
os.makedirs(path)
print(f"Создана папка: {path}")
if ext == "jpg":
doc_api5.SaveAsToRasterFormat(full_path, rasterParJPG)
print(f"Сохранен JPG: {full_path}")
# Открываем сохраненное изображение и добавляем его в список
img = Image.open(full_path)
images.append(img)
if ext == "dxf":
doc_api5.ksSaveToDXF(full_path)
print(f"Сохранен DXF: {full_path}")
except Exception as e:
print(f"Ошибка при обработке документа {i}: {e}")
# Если есть изображения, создаем PDF
if images:
desktop_path = os.path.join(
os.path.expanduser("~"), "Desktop"
) # Путь к рабочему столу
pdf_filename = f"{first_doc_name}_pages.pdf" # Имя PDF-файла
pdf_output_path = os.path.join(desktop_path, pdf_filename) # Полный путь к PDF
# Создаем первую страницу с заголовком
try:
# Попытка загрузить шрифт Arial (или другой шрифт с поддержкой кириллицы)
font = ImageFont.truetype(
"arial.ttf", size=48
) # Размер шрифта можно изменить
except IOError:
print(
"Шрифт Arial не найден. Используется стандартный шрифт (без поддержки кириллицы)."
)
font = ImageFont.load_default()
# Создаем изображение для заголовка с увеличенной высотой
title_image = Image.new("RGB", (images[0].width, 200), color="white")
draw = ImageDraw.Draw(title_image)
# Текст заголовка
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:],
)
print(
f"Многостраничный PDF успешно сохранен на рабочий стол: {pdf_output_path}"
)
return f"PDF сохранен: {pdf_output_path}"
else:
return "Ошибка: Нет документов для обработки."
except Exception as e:
return f"Произошла ошибка: {e}"