CAD 文件 批量转为PDF或批量打印,还是比较稳定的
1.需要本地安装CAD软件
2.通过 Everything 搜索工具搜索,DWG To PDF.pc3 ,获取到文件目录 ,替换到代码中,
python"> originalValue = ACADPref.PrinterConfigPath \= r"C:\Users\hyh\AppData\Roaming\Autodesk\AutoCAD 2024\R24.3\chs\Plotters"
python">#!/usr/bin/env python
# -*- coding: utf-8 -*-import win32com.client
import time
import os,subprocessdef find_all_sub_files( directory, suffix='.dxf'):''':param directory: 查找的主目录:param suffix: 获取的扩展名:return: 符合扩展名的列表'''all_files = []# 递归遍历目录及其子目录中的所有文件for root, dirs, files in os.walk(directory):for file in files:if file.endswith(suffix):if '~$' not in file:all_files.append(os.path.join(root, file))return all_filesdef close_application(application = "chrome.exe"):# windows系统 关闭谷歌浏览器cmd = "taskkill /f /t /im {}".format(application)# 执行cmd命令,不显示任何输出subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)def cad_to_PDf(pdf_path,doc):# doc = wincad.ActiveDocumentdoc.Utility.Prompt("Hello! Autocad from pywin32com.\n")msp = doc.ModelSpace#print(doc.Name)#print(doc.ActiveLayout.ConfigName)# 设置绘图仪管理器的工作目录ACADPref = doc.Application.preferences.FilesoriginalValue = ACADPref.PrinterConfigPath \= r"C:\Users\hyh\AppData\Roaming\Autodesk\AutoCAD 2024\R24.3\chs\Plotters"#print(ACADPref)#print(originalValue)oplot = doc.PlotConfigurations.Add("PDF", doc.ActiveLayout.ModelType)doc.ActiveLayout.ConfigName = "DWG To PDF.pc3"doc.SetVariable("Filedia", 0)doc.SetVariable("BACKGROUNDPLOT", 0) # 前台打印doc.Plot.QuietErrorMode = Trueprint(pdf_path)doc.Plot.PlotToFile(pdf_path) # 选择打印机,若要采用纸质打印的打印机,则输出就需要将plot.PlotToFile()改为plot.PlotToDevice()# doc.PlotRotation = 0 # 横向打印# doc.StandardScale = 0 # 图纸打印比例# doc.CenterPlot = True # 居中打印# doc.PlotWithPlotStyles = True # 依照样式打印# doc.PlotHidden = False # 隐藏图纸空间对象oplot.Delete()oplot = Noneobj = doc.GetVariable("DBMOD")# print(obj)def cad_conversion(cad_file_dir, save_pdf_path):wincad = win32com.client.Dispatch("AutoCAD.Application")docs = wincad.Documentsdxf_all_list=find_all_sub_files(cad_file_dir, suffix='.dxf')for dxf_path in dxf_all_list:cad_name=dxf_path.split('\\')[-1].replace('.dxf','.pdf')if not os.path.exists(save_pdf_path):os.makedirs(save_pdf_path)pdf_path=os.path.join(save_pdf_path,cad_name)doc = docs.Open(dxf_path)cad_to_PDf( pdf_path, doc)# 关闭CAD文件#doc.Close()doc.Close(False)del doctime.sleep(1)close_application(application="chrome.exe") # 关闭谷歌浏览器,如默认其他浏览器,需要修改 chrome.exewincad.Quit()del wincadif __name__ == '__main__':# CAD文件路径 输出PDF文件路径cad_file = r"D:\Python\CAD\hb" # 输入CAD文件路径output_pdf = r"D:\Python\CAD\hb\export_cad_data\CAD" # 输出PDF文件路径cad_conversion(cad_file, output_pdf)