Desenvolvimento secundário do Python SolidWorks --- Arquivo salvo do SolidWorks como outros formatos

Desenvolvimento secundário do SolidWorks em Python — o SolidWorks salva o arquivo em outros formatos

Desenvolvimento secundário do SolidWorks em Python — o SolidWorks salva o arquivo em outros formatos



1. Conecte-se ao SolidWorks para desenvolvimento secundário

Para conectar-se ao SolidWorks, consulte >> Desenvolvimento secundário do Python SolidWorks — Como conectar o Python ao SolidWorks

2. Função salvar arquivo: SaveAs

Use a função SaveAs para salvar arquivos

1.Definição da função SaveAs

O protótipo da função é o seguinte:

Function SaveAs( _
   ByVal Name As System.String, _
   ByVal Version As System.Integer, _
   ByVal Options As System.Integer, _
   ByVal ExportData As System.Object, _
   ByRef Errors As System.Integer, _
   ByRef Warnings As System.Integer _
) As System.Boolean

Descrição do parâmetro:
Nome : O nome completo do caminho do arquivo salvo, incluindo o nome do sufixo, incluindo as seguintes opções
**Versão **: O formato ao salvar o arquivo, incluindo as seguintes opções

Membro Descrição
swSaveAsCurrentVersion 0 = Este é o comportamento típico de salvamento.
swSaveAsDetachedDrawing 4
swSaveAsFormatProE 2
swSaveAsStandardDesenho 3
swSalvarAsSW98plus Obsoleto e sem suporte.

Opções : Opções ao salvar o arquivo, incluindo as seguintes opções

Membro Descrição
swSaveAsOptions_AvoidRebuildOnSave 8 ou 0x8
swSaveAsOptions_Copy 2 ou 0x2
swSaveAsOptions_DetachedDrawing 128 ou 0x80; Não é uma opção válida para IPartDoc::SaveToFile2
swSaveAsOptions_IgnoreBiography 256 ou 0x100; Remover o histórico de revisões de um arquivo SOLIDWORKS apenas para o nome do arquivo atual
swSaveAsOptions_OverrideSaveEmodel 32 ou 0x20; Salva informações relacionadas ao eDrawings em uma seção do arquivo que está sendo salvo; especificar essa configuração substitui as configurações Ferramentas, Opções, Opções do sistema, Geral, Salvar dados do eDrawings no documento do SOLIDWORKS; não é uma opção válida para IPartDoc::SaveToFile2
swSaveAsOptions_SaveEmodelData Obsoleto.
swSaveAsOptions_SaveReferenced 4 ou 0x4; Suporta peças, montagens e desenhos; esta configuração indica salvar todos os componentes (submontagens e peças) tanto nas montagens quanto nos desenhos; se uma peça possui uma referência externa, então esta configuração indica para salvar a referência externa
swSaveAsOptions_Silent 1 ou 0x1
swSaveAsOptions_UpdateInactiveViews 16 ou 0x10; Não é uma opção válida para IPartDoc::SaveToFile2; esta configuração só é aplicável a um desenho que possua uma ou mais folhas; esta configuração atualiza as visualizações em planilhas inativas

ExportData : Opções ao salvar o arquivo como PDF

Erros : Definição de erros ao salvar arquivos, incluindo as seguintes opções

Membro Descrição
swFileLockError 16 ou 0x10
swFileNameContainsAtSign 8 ou 0x8 = O nome do arquivo não pode conter o símbolo de arroba (@)
swFileNameEmpty 4 ou 0x4 = O nome do arquivo não pode ficar vazio
swFileSaveAsBadEDrawingsVersion 1024 ou 0x400
swFileSaveAsDoNotOverwrite 128 ou 0x80 = Não sobrescrever um arquivo existente
swFileSaveAsInvalidFileExtension 256 ou 0x100 = A extensão do nome do arquivo não corresponde ao tipo de documento do SOLIDWORKS
swFileSaveAsNameExceedsMaxPathLength 2048 ou 0x800 = O nome do arquivo não pode exceder 255 caracteres
swFileSaveAsNoSelection 512 or 0x200 = Save the selected bodies in a part document. Valid option for IPartDoc::SaveToFile2; however, not a valid option for IModelDocExtension::SaveAs
swFileSaveAsNotSupported 4096 or 0x1000 = Save As operation:is not supported was executed is such a way that the resulting file might not be complete, possibly because SOLIDWORKS is hidden; if the error persists after setting SOLIDWORKS to visible and re-attempting the Save As operation, contact SOLIDWORKS API support.
swFileSaveFormatNotAvailable 32 or 0x20 = Save As file type is not valid
swFileSaveRequiresSavingReferences 8192 or 0x2000 = Saving an assembly with renamed components requires saving the references
swFileSaveWithRebuildError Obsolete = See swFileSaveWarning_e
swGenericSaveError 1 or 0x1
swReadOnlySaveError 2 or 0x2

Warnings:另存文件出现警告的定义,包含如下选项

Member Description
swFileSaveWarning_AnimatorCameraViews 128 or 0x80
swFileSaveWarning_AnimatorFeatureEdits 16 or 0x10
swFileSaveWarning_AnimatorLightEdits 64 or 0x40
swFileSaveWarning_AnimatorNeedToSolve 8 or 0x8
swFileSaveWarning_AnimatorSectionViews 256 or 0x100
swFileSaveWarning_EdrwingsBadSelection 32 or 0x20
swFileSaveWarning_MissingOLEObjects 512 or 0x200
swFileSaveWarning_NeedsRebuild 2 or 0x2
swFileSaveWarning_OpenedViewOnly 1024 or 0x400
swFileSaveWarning_RebuildError 1 or 0x1
swFileSaveWarning_ViewsNeedUpdate 4 or 0x4
swFileSaveWarning_XmlInvalid 2048 or 0x800

返回值,返回布尔类型,保存成功放回true,失败返回falese

2.SaveAs函数的使用

2.1除PDF文件外,其他文件另存为新文件只需修改以下代码中的STEP为对应格式后缀名即可,以下代码示例将文件另存为STEP格式

另存为其他文件时需要修改STEP为对应文件格式后缀名

filename=filename[:-6]+‘STEP’

完整代码如下

import win32com.client
import pythoncom

def saveasfile():
    # SolidWorks年份版本
    sldver=2018
    # 建立com连接,如只有一个版本,可以只写"SldWorks.Application"
    swApp=win32com.client.Dispatch(f'SldWorks.Application.{
      
      sldver-1992}')
    # 提升API交互效率
    swApp.CommandInProgress =True
    # 显示SolidWorks界面
    swApp.Visible =True
    # 获取当前激活文档对象
    swModel = swApp.ActiveDoc
    # 获取当前激活文件路径
    filename=swModel.GetPathName
    #将当前文件另存为step格式文件,路径为当前文件路径
    filename=filename[:-6]+'STEP'
    # SaveAs在此对象下调用
    swModel=swModel.Extension
    #错误和警告
    Errors=win32com.client.VARIANT(pythoncom.VT_BYREF | pythoncom.VT_I4, -1)
    Warnings=win32com.client.VARIANT(pythoncom.VT_BYREF | pythoncom.VT_I4, -1)
    # 除PDF文件外,其余格式SaveAs第四个参数均使用Nothing
    Nothing = win32com.client.VARIANT(pythoncom.VT_DISPATCH, None)
    boolstatus = swModel.SaveAs(filename,0,0,Nothing, Errors, Warnings)
    if boolstatus:
        print('文件另存成功')
    else:
        print(f'文件另存失败,出现如下错误:{
      
      Errors}')
        print(f'文件另存失败,出现如下警告:{
      
      Warnings}')

if __name__ == '__main__':
    saveasfile()

2.2PDF文件另存时,需对ExportData进行定义,将后缀名修改为PDF,以下代码示例将文件另存为3D PDF文件格式

相比2.1代码增加的代码如下

# 指定文件类型的数据接口
swExportPDFData = swApp.GetExportFileData(1)
# 将文件另存为3D PDF 格式
swExportPDFData.ExportAs3D = True

完整代码如下

import win32com.client
import pythoncom

def saveasfile():
    # SolidWorks年份版本
    sldver=2018
    # 建立com连接,如只有一个版本,可以只写"SldWorks.Application"
    swApp=win32com.client.Dispatch(f'SldWorks.Application.{
      
      sldver-1992}')
    # 提升API交互效率
    swApp.CommandInProgress =True
    # 显示SolidWorks界面
    swApp.Visible =True
    # 获取当前激活文档对象
    swModel = swApp.ActiveDoc
    # 获取当前激活文件路径
    filename=swModel.GetPathName
    #将当前文件另存为step格式文件,路径为当前文件路径
    filename=filename[:-6]+'PDF'
    # SaveAs在此对象下调用
    swModel=swModel.Extension
    #错误和警告
    Errors=win32com.client.VARIANT(pythoncom.VT_BYREF | pythoncom.VT_I4, -1)
    Warnings=win32com.client.VARIANT(pythoncom.VT_BYREF | pythoncom.VT_I4, -1)
    # 指定文件类型的数据接口
    swExportPDFData = swApp.GetExportFileData(1)
    # 将文件另存为3D PDF 格式
    swExportPDFData.ExportAs3D = True
    boolstatus = swModel.SaveAs(filename,0,0,swExportPDFData, Errors, Warnings)
    if boolstatus:
        print('文件另存成功')
    else:
        print(f'文件另存失败,出现如下错误:{
      
      Errors}')
        print(f'文件另存失败,出现如下警告:{
      
      Warnings}')

if __name__ == '__main__':
    saveasfile()

Acho que você gosta

Origin blog.csdn.net/Bluma/article/details/128970017
Recomendado
Clasificación