当前位置:首页>python>【CAD图纸批量打印太繁琐?我用Python模拟人工操作,一键解放双手!!】

【CAD图纸批量打印太繁琐?我用Python模拟人工操作,一键解放双手!!】

  • 2026-10-11 17:33:02
【CAD图纸批量打印太繁琐?我用Python模拟人工操作,一键解放双手!!】

“带你横跨办公自动化的数据江海”

@摸鱼

闻道有先后,术业有专攻。

各位大佬好!

~我依旧是你们的老朋友摸鱼~

♥ 1

在职场摸爬滚打的这十多年里,我用Python悄悄干了不少“正事”——不知不觉攒下了一整套办公自动化的实用项目技巧。去年10月初创立了公众号 「码海听潮」 ,初衷很简单:把重复的劳动交给代码,把摸鱼的时间留给生活。

目前已经吭哧吭哧更新了第100篇原创文章,每一篇都是实操干货,不讲虚的,只聊怎么用代码真正解放双手,帮大家早点下班、准点摸鱼

♥ 2

♥ 3好叻,多了不说,少了不唠,咱直接上干货。

办公需求场景

从崩溃到优雅的进化

接上篇文章批量把CAD图纸转PDF的需求。现在老板发话:必须用中望CAD将全部CAD图纸打印出来。假如这种“重任”落到了大佬你的头上,敢问阁下打算如何应对?

  • 需求的dwg格式的cad文档

办公痛点分析

01

 痛点1:重复劳动效率极其低下,耗时惊人

    • 人工操作需要逐个打开图纸 → 点击“智能打印” → 选择打印范围→ 选择本地打印机→ 设置相关参数  →打印→ 关闭图纸。如果文件夹里有几十上百个图纸,这种机械、重复的点击操作会占用大量时间,且中途极易因疲劳操作出错或中断。

    02

     痛点2:图纸比例与纸张尺寸需反复手工调整

      • 不同DWG图纸可能采用不同的图框尺寸(A0/A1/A2/A3/A4)或自定义比例。人工转换时,每次都要检查并手动选择合适的纸张大小、打印范围(窗口/范围/布局)、以及是否“布满图纸”。稍有疏忽,可能出现图框被裁切、比例失真、或者空白边距过大等问题。

      由此可见若的话若操作成千上百个cad文档,整个操作流程繁琐且耗时,高频次的鼠标点击和键盘输入使操作者手指疲劳,堪称"键盘敲冒烟"式的体力劳动,加上人工疲劳操作极易导致遗漏文件夹。于是乎这时候,按以往的 “解题套路”,Python 的专属 BGM 该响起来了 ——go~ go~ go~,救苦救难的大救星这不就来了!!

      @摸鱼

      问题拆解思路

      1. 遍历cad文档文件夹

      遍历指定文件夹中的dwg格式的cad文件,生成待处理文件路径列表。

      2. 逐个自动化操作cad文档

      循环打开每一个cad文档,基于uiautomation自动化库操作打印cad文档

      下面,我就用python代码让各位大佬见识一下,什么叫"传统文化遇上赛博效率"(仅展示部分代码,非完整代码,需完整代码看文章末尾说明~)

      import sysfrom PyQt6.QtWidgets import (    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,    QPushButton, QTextEdit, QLabel, QFileDialog, QProgressBar,    QGroupBox, QMessageBox)from PyQt6.QtCore import Qt, QSettingsfrom PyQt6.QtGui import QFont, QPalette, QColor, QTextCursorimport timeimport osclass CADToPDFApp(QMainWindow):    def __init__(self):        super().__init__()        self.cad_path = ''        self.folder_path = ''        # 初始化QSettings        self.settings = QSettings("CADToPDF", "Settings")        self.init_ui()        self.load_settings()    def init_ui(self):        self.setWindowTitle("中望CAD模拟人工批量打印CAD图纸(欢迎关注微信公账号:码海听潮)")        self.setFixedSize(800, 650)        # 主窗口居中        screen = QApplication.primaryScreen().geometry()        self.move(            (screen.width() - self.width()) // 2,            (screen.height() - self.height()) // 2        )        # 中央部件        central_widget = QWidget()        self.setCentralWidget(central_widget)        # 主布局        main_layout = QVBoxLayout(central_widget)        main_layout.setSpacing(15)        main_layout.setContentsMargins(25, 20, 25, 20)        # 设置组        settings_group = QGroupBox(" 基本设置")        settings_group.setStyleSheet("""            QGroupBox {                font-weight: bold;                border: 2px solid #3498db;                border-radius: 8px;                margin-top: 10px;                padding-top: 25px;                padding-bottom: 10px;                background-color: white;            }            QGroupBox::title {                subcontrol-origin: margin;                left: 15px;                padding: 0 8px 0 8px;                color: #2980b9;                font-size: 13px;            }        """)        settings_layout = QVBoxLayout()        settings_layout.setSpacing(12)        # CAD路径设置        cad_layout = QHBoxLayout()        cad_label = QLabel("中望CAD程序:")        cad_label.setFixedWidth(80)        cad_label.setStyleSheet("font-weight: normal; font-size: 12px;")        self.cad_path_edit = QLabel(self.cad_path.replace('"', ''))        self.cad_path_edit.setWordWrap(True)        self.cad_path_edit.setStyleSheet("""            QLabel {                padding: 8px;                border: 1px solid #bdc3c7;                border-radius: 5px;                background-color: #f8f9fa;                font-size: 11px;                min-height: 20px;            }        """)        cad_browse_btn = QPushButton("浏览")        cad_browse_btn.setFixedWidth(90)        cad_browse_btn.setStyleSheet("""            QPushButton {                background-color: #3498db;                color: white;                border: none;                border-radius: 5px;                padding: 8px;                font-size: 12px;            }            QPushButton:hover {                background-color: #2980b9;            }        """)        cad_browse_btn.clicked.connect(self.browse_cad_path)        cad_layout.addWidget(cad_label)        cad_layout.addWidget(self.cad_path_edit)        cad_layout.addWidget(cad_browse_btn)        settings_layout.addLayout(cad_layout)        # 文件夹路径设置        folder_layout = QHBoxLayout()        folder_label = QLabel("CAD图纸目录:")        folder_label.setFixedWidth(80)        folder_label.setStyleSheet("font-weight: normal; font-size: 12px;")        self.folder_path_edit = QLabel(self.folder_path)        self.folder_path_edit.setWordWrap(True)        self.folder_path_edit.setStyleSheet("""            QLabel {                padding: 8px;                border: 1px solid #bdc3c7;                border-radius: 5px;                background-color: #f8f9fa;                font-size: 11px;                min-height: 20px;            }        """)        folder_browse_btn = QPushButton("浏览")        folder_browse_btn.setFixedWidth(90)        folder_browse_btn.setStyleSheet("""            QPushButton {                background-color: #3498db;                color: white;                border: none;                border-radius: 5px;                padding: 8px;                font-size: 12px;            }            QPushButton:hover {                background-color: #2980b9;            }        """)        folder_browse_btn.clicked.connect(self.browse_folder_path)        folder_layout.addWidget(folder_label)        folder_layout.addWidget(self.folder_path_edit)        folder_layout.addWidget(folder_browse_btn)        settings_layout.addLayout(folder_layout)        settings_group.setLayout(settings_layout)        main_layout.addWidget(settings_group)        # 按钮组        button_layout = QHBoxLayout()        button_layout.setSpacing(15)        self.start_btn = QPushButton("▶️ 开始打印")        self.start_btn.setMinimumHeight(45)        self.start_btn.setStyleSheet("""            QPushButton {                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,                    stop:0 #27ae60, stop:1 #229954);                color: white;                border: none;                border-radius: 8px;                font-weight: bold;                font-size: 14px;                padding: 10px;            }            QPushButton:hover {                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,                    stop:0 #2ecc71, stop:1 #27ae60);            }            QPushButton:pressed {                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,                    stop:0 #229954, stop:1 #1e8449);            }            QPushButton:disabled {                background: #95a5a6;                color: #ecf0f1;            }        """)        self.start_btn.clicked.connect(self.start_conversion)        self.clear_btn = QPushButton("🗑️ 清空日志")        self.clear_btn.setMinimumHeight(45)        self.clear_btn.setStyleSheet("""            QPushButton {                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,                    stop:0 #e67e22, stop:1 #d35400);                color: white;                border: none;                border-radius: 8px;                font-weight: bold;                font-size: 14px;                padding: 10px;            }            QPushButton:hover {                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,                    stop:0 #f39c12, stop:1 #e67e22);            }            QPushButton:pressed {                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,                    stop:0 #d35400, stop:1 #a04000);            }        """)        self.clear_btn.clicked.connect(self.clear_log)        self.stop_btn = QPushButton("⏹️ 停止")        self.stop_btn.setMinimumHeight(45)        self.stop_btn.setEnabled(False)        self.stop_btn.setStyleSheet("""            QPushButton {                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,                    stop:0 #e74c3c, stop:1 #c0392b);                color: white;                border: none;                border-radius: 8px;                font-weight: bold;                font-size: 14px;                padding: 10px;            }            QPushButton:hover {                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,                    stop:0 #ec7063, stop:1 #e74c3c);            }            QPushButton:disabled {                background: #95a5a6;                color: #ecf0f1;            }        """)        button_layout.addWidget(self.start_btn)        button_layout.addWidget(self.clear_btn)        button_layout.addWidget(self.stop_btn)        main_layout.addLayout(button_layout)        # 进度条        self.progress_bar = QProgressBar()        self.progress_bar.setTextVisible(True)        self.progress_bar.setStyleSheet("""            QProgressBar {                border: 2px solid #bdc3c7;                border-radius: 8px;                text-align: center;                font-weight: bold;                height: 25px;                background-color: #ecf0f1;            }            QProgressBar::chunk {                background: qlineargradient(x1:0, y1:0, x2:1, y2:0,                    stop:0 #27ae60, stop:1 #2ecc71);                border-radius: 6px;            }        """)        main_layout.addWidget(self.progress_bar)        # 日志组        log_group = QGroupBox("📝 处理日志")        log_group.setStyleSheet("""            QGroupBox {                font-weight: bold;                border: 2px solid #8e44ad;                border-radius: 8px;                margin-top: 10px;                padding-top: 25px;                background-color: white;            }            QGroupBox::title {                subcontrol-origin: margin;                left: 15px;                padding: 0 8px 0 8px;                color: #8e44ad;                font-size: 13px;            }        """)        log_layout = QVBoxLayout()        self.log_text = QTextEdit()        self.log_text.setReadOnly(True)        self.log_text.setStyleSheet("""            QTextEdit {                border: 2px solid #bdc3c7;                border-radius: 6px;                background-color: #2c3e50;                color: #ecf0f1;                font-family: 'Consolas', 'Courier New', monospace;                font-size: 11px;                padding: 10px;                line-height: 1.4;            }            QScrollBar:vertical {                border: none;                background: #34495e;                width: 10px;                border-radius: 5px;            }            QScrollBar::handle:vertical {                background: #7f8c8d;                border-radius: 5px;                min-height: 20px;            }            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {                height: 0px;            }        """)        log_layout.addWidget(self.log_text)        log_group.setLayout(log_layout)        main_layout.addWidget(log_group)        # 底部状态栏        self.status_bar = self.statusBar()        self.status_bar.showMessage("✅ 程序就绪 | 请设置路径后点击开始转换")        self.status_bar.setStyleSheet("""            QStatusBar {                color: #2c3e50;                font-size: 11px;                padding: 5px;                background-color: #ecf0f1;                border-top: 1px solid #bdc3c7;            }        """)    def load_settings(self):        """从QSettings加载保存的设置"""        saved_cad_path = self.settings.value("cad_path", "")        if saved_cad_path and os.path.exists(saved_cad_path):            self.cad_path = f'"{saved_cad_path}"'            self.cad_path_edit.setText(saved_cad_path)        saved_folder_path = self.settings.value("folder_path", "")        if saved_folder_path and os.path.exists(saved_folder_path):            self.folder_path = saved_folder_path            self.folder_path_edit.setText(saved_folder_path)    def save_settings(self):        """保存设置到QSettings"""        cad_path_value = self.cad_path.replace('"', '')        if cad_path_value:            self.settings.setValue("cad_path", cad_path_value)        if self.folder_path:            self.settings.setValue("folder_path", self.folder_path)    def browse_cad_path(self):        file_path, _ = QFileDialog.getOpenFileName(            self,             "选择中望CAD执行文件",            os.path.dirname(self.cad_path.replace('"', '')),            "可执行文件 (*.exe);;所有文件 (*.*)"        )        if file_path:            self.cad_path = f'"{file_path}"'            self.cad_path_edit.setText(file_path)            self.save_settings()            self.log_message(f"已设置CAD路径: {file_path}")    def browse_folder_path(self):        folder_path = QFileDialog.getExistingDirectory(            self,            "选择CAD图纸文件夹",            self.folder_path        )        if folder_path:            self.folder_path = os.path.normpath(folder_path)            self.folder_path_edit.setText(folder_path)            self.save_settings()            self.log_message(f"已设置图纸目录: {folder_path}")    def log_message(self, message):        timestamp = time.strftime("%H:%M:%S")        self.log_text.append(f"[{timestamp}] {message}")        cursor = self.log_text.textCursor()        cursor.movePosition(QTextCursor.MoveOperation.End)        self.log_text.setTextCursor(cursor)    def start_conversion(self):        """开始转换(仅界面演示)"""        if not os.path.exists(self.cad_path.replace('"', '')):            QMessageBox.warning(self, "警告", "CAD程序路径不存在!")            return        if not os.path.exists(self.folder_path):            QMessageBox.warning(self, "警告", "图纸目录不存在!")            return        self.save_settings()        self.log_message("开始转换...")        self.log_message("【演示模式】实际转换逻辑已移除")    def clear_log(self):        self.log_text.clear()        self.status_bar.showMessage("✅ 日志已清空")    def closeEvent(self, event):        self.save_settings()        event.accept()def main():    app = QApplication(sys.argv)    app.setOrganizationName("CADToPDF")    app.setApplicationName("CADToPDF")    app.setStyle('Fusion')    palette = QPalette()    palette.setColor(QPalette.ColorRole.Window, QColor(240, 242, 245))    palette.setColor(QPalette.ColorRole.WindowText, QColor(44, 62, 80))    palette.setColor(QPalette.ColorRole.Base, QColor(255, 255, 255))    palette.setColor(QPalette.ColorRole.AlternateBase, QColor(245, 245, 245))    palette.setColor(QPalette.ColorRole.ToolTipBase, QColor(255, 255, 255))    palette.setColor(QPalette.ColorRole.ToolTipText, QColor(44, 62, 80))    palette.setColor(QPalette.ColorRole.Text, QColor(44, 62, 80))    palette.setColor(QPalette.ColorRole.Button, QColor(240, 242, 245))    palette.setColor(QPalette.ColorRole.ButtonText, QColor(44, 62, 80))    palette.setColor(QPalette.ColorRole.Highlight, QColor(52, 152, 219))    palette.setColor(QPalette.ColorRole.HighlightedText, QColor(255, 255, 255))    app.setPalette(palette)    font = QFont("Microsoft YaHei", 9)    app.setFont(font)    window = CADToPDFApp()    window.show()    sys.exit(app.exec())if __name__ == "__main__":    main()

      最终所有cad图纸都模拟人工自动打印,完美实现了之前既定的需求,录屏如下:(由于完整视频时长有点长,简单做了加速不切屏处理)

      通过上面Python自动化脚本,仅用十分钟的时间就完成原需手动操作数小时甚至数天的工作任务。从最初准备手动人工机械操作的麻木到用python实现高效自动化的畅快,工作效率获得指数级提升,终于实现了不加班熬夜的自由!

      大佬们也可以举一反三,参照上面的代码思路根据自己工作中的实际情况来具体问题具体分析,实现自己定制化的需求。

      结语

      当Python遇见办公,牛马打工人终于笑出了猪叫声

      【职场人必看】每天早上一睁眼,想到又要面对:

      1.📊 堆积如山的Excel表格

      2.📑 机械重复的复制粘贴

      3.✍️ 永远改不完的各类文档

      4.诸如此类的更多........

      是不是连Ctrl+Alt+Delete的心都有了?

      别慌!别急,摸鱼这位“职场外挂”已经带着Python代码来拯救你了!

      友情提示:考虑到没有python环境的朋友需要打包好的成品exe,摸鱼早已贴心打包好,本篇文章代码打包的exe截图如下:

      另外,《码海听潮》公众号所有文章码和exe程序已打包好上传绿联nas私有云,有需要的大佬扫一扫上面博主的个人微信二维码,需要的大佬需支付9.9元永久拥有公众号资源(写原创干货费时费力,属实不易),邀请您进入社区群获取下载链接!!,群内提供python办公自动化交流问题,解决问题,且码海听潮微信公众号文章发布会第一时间会更新到群里,非诚勿扰哈!

      码海听潮官方社区群如下:

      赶紧微信扫一扫下方二维码添加摸鱼君微信

      最新文章

      随机文章