中望CAD二次开发-批量打印pdf

1.选择DWG文件路径

2.选择保存pdf路径

3开始转换

自动打印


import time
# import yaml
import win32com.client
import pythoncom

import os
import pygetwindow
from pathlib import Path
import webbrowser





def scr(outpath, paper_size):
    
    acaddoc = acad.ActiveDocument

   
    min = acaddoc.GetVariable("extmin")[0:2]
    max = acaddoc.GetVariable("extmax")[0:2]
    print('当前处理文件名:%s' % (acaddoc.name))
    def APoint(x, y):
        """坐标点转化为浮点数"""
        # 需要两个点的坐标
        return win32com.client.VARIANT(pythoncom.VT_ARRAY | pythoncom.VT_R8, (x, y))
    layout = acaddoc.layouts.item('Model')  # 先来个layout对象
    plot = acaddoc.Plot
    # Ret_dict = dict()
    # RetVa = layout.GetPlotStyleTableNames()  # 获取当前可用的打印样式名称
    # RetVal = filter(lambda x: x[-3:] != 'stb', list(RetVa))  # 将后缀为stb的文件过滤,否则选择stb格式的文件会报错
    # print('可用的打印样式如下:')
    # for re_index, name in enumerate(list(RetVal)):
    #     Ret_dict[re_index] = name
    #     print(str(re_index) + ' - ' + name)
    # sty_sh = input('请选择打印样式(输入数字即可,tips:选择格式必须为ctb):')
    # print('您选的打印样式为:%s' % (Ret_dict[eval(sty_sh)]))
    acaddoc.SetVariable('BACKGROUNDPLOT', 0)  # 前台打印
    layout.StyleSheet = 'Monochrome.ctb'  # 选择打印样式
    layout.PlotWithLineweights = True  # 打印线宽
    layout.ConfigName = 'DWG to PDF.pc5'  # 选择打印机#""
    #
    layout.UseStandardScale = True  # 选用标准的比例
    layout.StandardScale = 0 # 图纸打印比例

    layout.CenterPlot = True  # 居中打印
    layout.PlotWithPlotStyles = True  # 依照样式打印
    layout.PlotHidden = False  # 隐藏图纸空间对象
    # cad_number = 1
    # zb_array = np.zeros([cad_number, 4])  # 用来储存图框的坐标点
    # print('请打开ZWCAD点击图纸坐标点,连续选择两个点,第一个点为左下角,第二个为右上角')
    # for zb_2 in range(2):
    #     # 防止点击错误出现出现闪退
    #     xun = 1
    #     while xun:
    #         try:
    #             zb_scr = acaddoc.Utility.GetPoint()  # 通过鼠标点击获取坐标
    #             zb_array[0][zb_2] = zb_scr[0]  # 将x坐标保存到数组中
    #             zb_array[0][zb_2 + 2] = zb_scr[1]  # 将坐标y保存到数组中
    #             xun = 0
    #         except:
    #             print('重新选择(请点击正确区域)')
    #     if zb_2 == 0:
    #         print('左下角的坐标点为:%s' % (list(zb_scr)))
    #     else:
    #         print('右上角的坐标点为:%s' % (list(zb_scr)))
    if paper_size == "A1":
        layout.CanonicalMediaName = 'ISO_expand_A1_(594.00_x_841.00_MM)'
    elif paper_size== "A2":
        layout.CanonicalMediaName = 'ISO_expand_A2_(420.00_x_594.00_MM)'
    elif paper_size == "A3":
        layout.CanonicalMediaName ='ISO_expand_A3_(297.00_x_420.00_MM)'
    else:
        layout.CanonicalMediaName = 'ISO_expand_A4_(210.00_x_297.00_MM)'
    # layout.CanonicalMediaName = 'ISO_expand_A3_(297.00_x_420.00_MM)'
    # acaddoc.name
    # number = acaddoc.name.split('-')[1][0:5]

    if (max[0]-min[0]<max[1]-min[1]):

        layout.PlotRotation =0# 横向打印
    else:
        layout.PlotRotation =1 #纵向打印
    # # print(layout.PlotRotation)
    po1 = APoint(min[0], min[1])
    po2 = APoint(max[0], max[1])
    # print(min)
    # print(max)
    # print(po1)
    # print(po2)

    layout.PlotType = 4  # 设置安装坐标窗口打印,若无此行,按照窗口显示的打印
    layout.SetWindowToPlot(po1, po2)  # 设置打印窗口的坐标
    # AcPlotType.acExtents
    # acDisplay:打印当前显示中的所有内容。
    # acExtents:打印当前所选空间范围内的所有内容。
    # acLimits:打印当前空间限制范围内的所有内容。
    # acView:打印由ViewToPlot属性命名的视图。
    # acWindow:打印SetWindowToPlot方法指定的窗口中的所有内容。
    # acLayout:打印位于指定纸张大小边距内的所有内容,原点从“布局”选项卡中的0, 0坐标位置计算得出。从模型空间打印时,此选项不可用。
    #acaddoc.Plot.DisplayPlotPreview(AcPreviewMode.acFullPreview)
    #acad.acad.ActiveDocument.Plot.DisplayPlotPreview(win32com.client.constants.acFullPreview)

    plot.PlotToFile(outpath + '/' + acaddoc.name[:-4] + ".pdf")


    # firefoxPath = result['firefox_Path']
    filename = Path(outpath + '/' + acaddoc.name[:-4] + ".pdf")
    # webbrowser.register("firefox", None, webbrowser.BackgroundBrowser(firefoxPath))
    # webbrowser.get('firefox').open(filename.absolute().as_uri(), new=1, autoraise=True)
    webbrowser.open(filename, new=1, autoraise=True)
    # webbrowser.open(outpath + '/' + acaddoc.name[:-4] + ".pdf", new=2)
    print(acaddoc.name[:-4] + ".pdf---文件已保存到" + outpath)
    print()



def main(dwgpath, outpath):
    global acad

    filenames = os.listdir(dwgpath)
    dwgcount = 0

    for i in range(len(filenames)):
            if (filenames[i].endswith('.dwg')):
                dwgcount += 1
        # print(filenames)
    acad = win32com.client.Dispatch("ZWCAD.Application.2020")
    while True:
            outfile = os.listdir(outpath)
            i = len(outfile)
            if (len(outfile) == dwgcount):
                break
            while (len(outfile) < dwgcount):
                # 等待3秒
                if (i >= len(filenames)):
                    break
                # time.sleep(1)
                if (filenames[i].endswith('.dwl') or filenames[i].endswith('.bak')):
                    i += 1
                    continue
                filename = os.path.join(dwgpath, filenames[i])
                # print(acad.Documents.Count==0)
                if acad.Documents.Count == 0 or acad.ActiveDocument.name != filenames[i]:
                    doc = acad.Documents.Open(filename)
                scr(outpath,  "A3")
                doc = acad.ActiveDocument
                doc.Close()
                # doc = acad.Documents(filename).Close(False)
                i += 1

    pdfcount = len(os.listdir(outpath))
    print()

    print("所有文件已处理完毕,一共" + str(pdfcount) + "个文件")

GUI函数

from time import sleep
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
import qtawesome
from PyQt5.QtCore import QObject, pyqtSignal, QEventLoop, QTimer, QThread, QTime
from PyQt5.QtGui import QTextCursor
from PyQt5.QtWidgets import QTextEdit,QPushButton
import demo
import Auto_print
import Window_print
import time
import os

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *


class MyThread(QThread):
    signalForText = pyqtSignal(str)

    def write(self, text):
        self.signalForText.emit(str(text))  # 发射信号
    def __init__(self,data=None, parent=None):
        super(MyThread, self).__init__(parent)
        self.data = data




    def run(self):
        if(QThread.currentThread().data=='Window_print'):
            Window_print.main(dwg_path,out_path)
        elif(QThread.currentThread().data=='Auto_print'):


            Auto_print.main(dwgpath, outpath)


class MainUi(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.init_ui()
        self.th = MyThread()
        self.th.signalForText.connect(self.onUpdateText)
        sys.stdout = self.th

    def onUpdateText(self, text):
        cursor = self.process.textCursor()
        cursor.movePosition(QTextCursor.End)
        cursor.insertText(text)
        self.process.setTextCursor(cursor)
        self.process.ensureCursorVisible()

    def init_ui(self):
        """Creates UI window on launch."""
        # Button for generating the master list.
        pushButton = QPushButton('自动打印', self)

        pushButton.setGeometry(QtCore.QRect(30, 30, 150, 40))
        pushButton.setStyleSheet("background:rgba(53,142,255,1);border-radius:10px;padding:2px 4px;")
        pushButton.setObjectName("pushButton")
        # btnGenMast.move(450, 50)
        # btnGenMast.resize(100, 200)
        pushButton.clicked.connect(self.auto_print)

        pushButton1 = QPushButton('窗口打印', self)
        pushButton1.setGeometry(QtCore.QRect(200, 30, 150, 40))
        pushButton1.setStyleSheet("background:rgba(53,142,255,1);border-radius:10px;padding:2px 4px;")
        pushButton1.setObjectName("pushButton1")
        # btnGenMast.move(450, 50)
        # btnGenMast.resize(100, 200)
        pushButton1.clicked.connect(self.window_print)

        pushButton2 = QPushButton('退出系统', self)
        pushButton2.setGeometry(QtCore.QRect(370, 30, 150, 40))
        pushButton2.setStyleSheet("background:rgba(53,142,255,1);border-radius:10px;padding:2px 4px;")
        pushButton2.setObjectName("pushButton2")
        # btnGenMast.move(450, 50)
        # btnGenMast.resize(100, 200)
        pushButton2.clicked.connect(self.handleCalc3)


        # Create the text output widget.
        self.process = QTextEdit(self, readOnly=True)
        self.process.ensureCursorVisible()
        self.process.setLineWrapColumnOrWidth(500)
        self.process.setLineWrapMode(QTextEdit.FixedPixelWidth)
        self.process.setFixedWidth(490)
        self.process.setFixedHeight(600)
        self.process.move(30, 110)

        # Set window size and title, then show the window.
        self.setGeometry(300, 500, 550, 750)
        self.setWindowTitle('CAD自动打印PDF系统')
        # self.setWindowFlags(Qt.WindowStaysOnTopHint)
        self.show()
        # self.setFixedSize(800, 400)
        # self.main_widget = QtWidgets.QWidget()  # 创建窗口主部件
        # self.main_layout = QtWidgets.QGridLayout()  # 创建主部件的网格布局
        # self.main_widget.setLayout(self.main_layout)  # 设置窗口主部件布局为网格布局
        #
        # self.widget = QtWidgets.QWidget()
        # self.widget.setObjectName('widget')
        # self.layout = QtWidgets.QGridLayout()
        # self.widget.setLayout(self.layout)  # 设置部件布局为网格
        #
        # self.main_layout.addWidget(self.widget, 0, 2, 12, 10)
        # self.setCentralWidget(self.main_widget)  # 设置窗口主部件
        #
        # self.bar_widget = QtWidgets.QWidget()  # 顶部搜索框部件
        # self.bar_layout = QtWidgets.QGridLayout()  # 顶部搜索框网格布局
        # self.bar_widget.setLayout(self.bar_layout)
        # self.search_button = QtWidgets.QPushButton( "搜索")
        # self.search_button.clicked.connect(self.search)
        # self.search_button.setObjectName('button')
        # # self.search_button.setFont(qtawesome.font( 16))
        # # self.bar_widget_search_input = QtWidgets.QLineEdit()  # 搜索框
        # # self.bar_widget_search_input.setPlaceholderText("输入搜索内容")
        # #
        # # self.bar_layout.addWidget(self.search_button, 0, 0, 1, 1)
        # # self.bar_layout.addWidget(self.bar_widget_search_input, 0, 1, 1, 8)
        #
        # self.layout.addWidget(self.bar_widget, 0, 0, 1, 9)
        #
        # self.recommend_label = QtWidgets.QLabel("进程显示:")
        # self.recommend_label.setObjectName('lable')
        #
        # self.recommend_widget = QtWidgets.QWidget()
        # self.recommend_layout = QtWidgets.QGridLayout()
        # self.recommend_widget.setLayout(self.recommend_layout)
        #
        # self.process = QTextEdit(self, readOnly=True)
        # self.process.ensureCursorVisible()
        # self.process.setLineWrapColumnOrWidth(800)
        # self.process.setLineWrapMode(QTextEdit.FixedPixelWidth)
        # self.process.setFixedWidth(500)
        # self.process.setFixedHeight(250)
        # self.process.move(30, 50)
        #
        # self.recommend_layout.addWidget(self.process, 0, 1)
        # self.layout.addWidget(self.recommend_label, 1, 0, 1, 9)
        # self.layout.addWidget(self.recommend_widget, 2, 0, 2, 9)
        #
        # # 使用QSS和部件属性美化窗口部件
        # # self.bar_widget_search_input.setStyleSheet(
        # #     '''QLineEdit{
        # #             border:1px solid gray;
        # #             width:300px;
        # #             border-radius:10px;
        # #             padding:2px 4px;
        # #     }''')
        # self.widget.setStyleSheet('''
        #     QWidget#widget{
        #         color:#232C51;
        #         background:white;
        #         border-top:1px solid darkGray;
        #         border-bottom:1px solid darkGray;
        #         border-right:1px solid darkGray;
        #     }
        #     QLabel#lable{
        #         border:none;
        #         font-size:16px;
        #         font-weight:700;
        #         font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
        #     }
        #     QPushButton#button:hover{border-left:4px solid red;font-weight:700;}
        # ''')
    def window_print(self):
        global dwg_path, out_path
        dwg_path = QtWidgets.QFileDialog.getExistingDirectory(None, "选择保存CAD图纸的文件夹", "D:/")  # 起始路径

        # fname.setAcceptMode(QFileDialog.AcceptOpen)
        # fname, _ = fname.getOpenFileName()
        # if fname == '':
        #     return
        # filepath = os.path.normpath(fname)
        # sname = filepath.split(os.sep)
        print("保存CAD图纸的文件路径是:%s" % dwg_path)
        out_path = QtWidgets.QFileDialog.getExistingDirectory(None, "选择保存PDF图纸文件夹", "D:/")  # 起始路径

        print("保存PDF图纸的文件路径是:%s" % out_path)
        time.sleep(1)

        try:
            self.t = MyThread('Window_print')

            self.t.start()


        except Exception as e:

            raise e

    def auto_print(self):
        global dwgpath, outpath
        dwgpath = QtWidgets.QFileDialog.getExistingDirectory(None, "选择保存CAD图纸的文件夹", "D:/")  # 起始路径

        # fname.setAcceptMode(QFileDialog.AcceptOpen)
        # fname, _ = fname.getOpenFileName()
        # if fname == '':
        #     return
        # filepath = os.path.normpath(fname)
        # sname = filepath.split(os.sep)
        print("保存CAD图纸的文件路径是:%s" % dwgpath)
        outpath = QtWidgets.QFileDialog.getExistingDirectory(None, "选择保存PDF图纸文件夹", "D:/")  # 起始路径

        print("保存PDF图纸的文件路径是:%s" % outpath)
        time.sleep(1)

        try:
            self.t = MyThread('Auto_print')

            self.t.start()


        except Exception as e:

            raise e
    def handleCalc3(self):
        os._exit(0)

    # def genMastClicked(self):
    #     """Runs the main function."""
    #     print('Running...')
    #     self.search()
    #
    #     loop = QEventLoop()
    #     QTimer.singleShot(2000, loop.quit)
    #     loop.exec_()

    def closeEvent(self, event):
        """Shuts down application on close."""
        # Return stdout to defaults.
        sys.stdout = sys.__stdout__
        super().closeEvent(event)
def main():
    app = QtWidgets.QApplication(sys.argv)
    app.aboutToQuit.connect(app.deleteLater)
    gui = MainUi()
    gui.show()

    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值