百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

Python工具开发:PDF转Word、Word转PDF、PDF转图片、Excel查询

off999 2024-09-21 20:59 33 浏览 0 评论

最近生活中经常需要对Word和PDF两个文件类型进行互转,挺麻烦的,这个时候就有两个选择,要么百度搜索那些在线转换类型的网站,要么只能使用微软office全家桶自带的类型转换,前者因为文件涉及我的个人隐私,所以我不是很想在那些网站上进行转换,虽然说没人在意我那些资料,哈哈!安全点还是好的,那么我就只能选择微软自带的功能了,我之前用过一次感觉还不错很好用,可是当我第三次使用的时候发现,居,居然,要钱了

私信小编01即可获取大量Python学习资源

我还以为微软那个是每天两次机会,没想到居然是一个账号两次机会啊,打扰了,饭都吃不起,那还有钱啊,而且居然这么贵


所以推出了Excel2.0版本,别问为什么,懒得重新绘制界面,拿上个帖子的模板的修修改改,又是个新的,就是那个被吐槽难看的那个模板,我换了个皮又拿出来了,没想到吧!!


好了,不说废话了,新的软件操作简单,先导入文件然后单击按钮就可以了(其实刚设定的时候连按钮都没,直接导入就自动转换了,后面想想,可能有些人不喜欢这种模式,所以改回了传统鼠标单击按钮),现在是可拖放也可导入,随便了,其他我做了限制,不是规定文件不能转换,比如Word转PDF,你导入PDF然后点击Word转PDF就不行,没办法不设置,到时候又软件有bug,转换完,会在左下角提示转换成功和文件路径的


有一个前提要求电脑要有Word,Excel,PDF,不然软件用不了,会闪退

from pdf2docx import Converter
from configparser import ConfigParser
import os
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
from xlrd import *
 
import fitz
import os
import pandas as pd
import sys
import openpyxl
from win32com.client import constants, gencache
class Main_Win(QWidget):
    def __init__(self):
        self.i = 0
        self.filename = ""
        super(Main_Win,self).__init__()
        self.setAcceptDrops(True)
        self.Main_WinUI()
    def Main_WinUI(self):
        self.setWindowTitle('多功能系统')
        self.resize(1700,880)
 
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        newLeft = (screen.width() - size.width()) // 2
        newTop = (screen.height() - size.height()) // 2
        self.move(newLeft, newTop)
        #self.setFixedSize(1700,880)
 
        palette = QPalette()
 
        pix = QPixmap(os.getcwd()+"\\images\\six.png")
        pix = pix.scaled(1300, 880)
        palette.setBrush(QPalette.Background, QBrush(pix))
        self.setPalette(palette)
 
        self.setToolTip('温馨提示:软件仅供参考,有问题可以上论坛交流!')
        QToolTip.setFont(QFont('Times',10,QFont.Black))
 
        self.setWindowIcon(QIcon(os.getcwd()+'\\images\\Book.ico'))
        print(os.getcwd()+'\\images\\Book.ico')
 
 
        self.Main_WinLayout()
        self.show()
    def Main_WinLayout(self):
 
        self.group = QGroupBox(self)
        self.group.setTitle('参数设置区')
        self.group.setGeometry(10,10,400,300)
        self.layout = QGridLayout()
 
        self.label_one = QLabel('<font color=#9370DB>请输入要搜索的关键词:<\\font>')
        self.layout.addWidget(self.label_one,0,0)
 
        self.edit_one = QLineEdit()
        self.edit_one.setAlignment(Qt.AlignCenter)
        self.edit_one.setPlaceholderText('这里输入要搜索的关键词')
        self.layout.addWidget(self.edit_one,0,1)
 
        self.button_one = QPushButton('开始搜索')
        self.layout.addWidget(self.button_one,1,0)
        self.button_one.clicked.connect(self.dialoginfo)
        self.button_two = QPushButton('导入文件')
        self.layout.addWidget(self.button_two, 1, 1)
        self.button_two.clicked.connect(self.groove_five)
 
        self.button_four = QPushButton('PDF转图片')
        self.layout.addWidget(self.button_four, 2, 0)
        self.button_four.clicked.connect(self.Start_PDF_Image)
        self.button_five = QPushButton('Word转PDF')
        self.layout.addWidget(self.button_five, 2, 1)
        self.button_five.clicked.connect(self.Start_Word_PDF)
 
        self.button_six = QPushButton('PDF转Word')
        self.layout.addWidget(self.button_six, 3, 0)
        self.button_six.clicked.connect(self.Start_PDF_Word)
 
# ---------------------------------------------------------------
 
        self.group_two = QGroupBox(self)
        self.group_two.setTitle('输出日志')
        self.group_two.setGeometry(10, 320, 400, 550)
        self.textedit_one = QTextEdit()
        self.textedit_one.setHtml('<font color=red>温馨提示!<\\font>')
        self.textedit_one.setFont(QFont("Times",10))
        self.textedit_one.moveCursor(QTextCursor.End)
        self.textedit_one.insertPlainText("\n目前软件只支持Excel,Word,PDF文件\n")
 
 
        self.layout_two = QGridLayout()
        self.textedit_one.setReadOnly(True)
        self.layout_two.addWidget(self.textedit_one)
        self.group_two.setLayout(self.layout_two)
 
        self.group_three = QGroupBox(self)
        self.layout_two = QHBoxLayout()
        self.group_three.setTitle('订单数据')
        self.group_three.setGeometry(420, 10, 1265, 860)
        self.table_one = QTableWidget()
 
 
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.showMenu)
        self.contextMenu = QMenu(self)
        self.CP = self.contextMenu.addAction('复制')
        self.CP.triggered.connect(lambda:self.selected_tb_text(self.table_one))
        self.CP = self.contextMenu.addAction('打开表格可编辑')
        self.CP.triggered.connect(lambda: self.compile_True(self.table_one))
        self.CP = self.contextMenu.addAction('关闭表格可编辑')
        self.CP.triggered.connect(lambda: self.compile_False(self.table_one))
        self.CP = self.contextMenu.addAction('添加数据')
        self.CP.triggered.connect(lambda: self.appendinfo(self.table_one))
 
 
        self.layout_two.addWidget(self.table_one)
        self.group_three.setLayout(self.layout_two)
        QApplication.processEvents()
 
        self.group.setLayout(self.layout)
    def dialoginfo(self):
        find_str = []
        if self.filename:
            if self.edit_one.text() == "":
                reply=QMessageBox.question(win, '温馨提示!', '大哥,你关键字,怎么也输点吧!', QMessageBox.Yes | QMessageBox.No, (QMessageBox.Yes))
                if reply == QMessageBox.Yes:
                    pass
                else:
                    self.dialoginfo()
            else:
                for i in self.data.to_dict('records'):
                    for value in i.values():
                        if str(value) == str(self.edit_one.text()):
                            find_str.append(i)
                print(find_str)
                if len(find_str):
                    self.textedit_one.moveCursor(QTextCursor.End)
                    self.textedit_one.insertPlainText(f"\n查询成功!!一共{len(find_str)}条数据!!\n")
                    self.table_one.setRowCount(len(find_str))
                    self.table_one.clearContents()
                    for s in range(len(find_str)):
                        for key,value in find_str[s].items():
                            item = QTableWidgetItem(str(value))
                            item.setTextAlignment(Qt.AlignCenter)
                            self.table_one.setItem(s, self.head_list.index(key), item)
                else:
                    self.textedit_one.moveCursor(QTextCursor.End)
                    self.textedit_one.insertPlainText(f"\n查询失败,找不到该条信息!!!\n")
        else:
            reply = QMessageBox.question(win, '温馨提示!', '请先导入文件在查询!!', QMessageBox.Yes | QMessageBox.No , (QMessageBox.Yes))
            if reply == QMessageBox.Yes:
                pass
            else:
                self.dialoginfo()
    def selected_tb_text(self,table_view):
        try:
            indexes = table_view.selectedIndexes()
            indexes_dict = {}
            for index in indexes:
                row, column = index.row(), index.column()
                if row in indexes_dict.keys():
                    indexes_dict[row].append(column)
                else:
                    indexes_dict[row] = [column]
            print(indexes_dict)
            print(row,column)
            text = []
            for row, columns in indexes_dict.items():
                row_data = []
                for column in columns:
                    try:
                        data = table_view.item(row, column).text()
                    except BaseException as e:
                        data = ' '
                    finally:
                        if row_data:
                            row_data = ' ' + data
                        else:
                            row_data = data
 
                        if text:
                            if len(text) % 4 == 0:
                                text.append('\n')
                            text.append(row_data)
                        else:
                            text.append(row_data)
            print(text)
            text_two = ''
            for item in text:
                text_two += item
            try:
                clipboard = QApplication.clipboard()
                clipboard.setText(text_two)  # 复制到粘贴板
            except BaseException as e:
                print(e)
        except BaseException as e:
            print(e)
            clipboard = QApplication.clipboard()
            clipboard.setText(text_two)
            return ''
    def keyPressEvent(self, event):     # 重写键盘监听事件
        # 监听 CTRL+C 组合键,实现复制数据到粘贴板
        if (event.key() == Qt.Key_C) and QApplication.keyboardModifiers() == Qt.ControlModifier:
            text = self.selected_tb_text(self.table_one)
    def showMenu(self, pos):
        print(pos)
        self.contextMenu.exec_(QCursor.pos())
    def groove_five(self):
        self.textedit_one.moveCursor(QTextCursor.End)
        self.textedit_one.insertPlainText("\n正在导入Excel文件..............\n")
        self.filename,ok = QFileDialog.getOpenFileName(self,'想好了在选,记得选EXCAL文件!!!!','C:\\','文件类型默认所有,这个你不用担心:(*.*)')
        self.excal()
    def excal(self):
        print(self.filename)
        self.head_list = []
        self.sum_list = []
        if self.filename[-4:] == "xlsx" or self.filename[-3:] == "xls":
            self.textedit_one.moveCursor(QTextCursor.End)
            self.textedit_one.insertPlainText("\n导入成功!\n")
            self.textedit_one.moveCursor(QTextCursor.End)
            self.textedit_one.insertPlainText(f'\n成功导入Excel文件!,路径为:{self.filename}\n')
            self.data = pd.read_excel(self.filename)
            print("123")
            for i in self.data:
                self.head_list.append(i)
            self.table_one.setRowCount(len(self.data[i].values))
            self.table_one.setColumnCount(len(self.head_list))
            self.table_one.setHorizontalHeaderLabels(self.head_list)
 
            for j in self.head_list:
                for k in self.data[j].values:
                    s = QTableWidgetItem(str(k))
                    s.setTextAlignment(Qt.AlignCenter)
                    self.sum_list.append(k)
                    self.table_one.setItem(len(self.sum_list) - 1,int(self.head_list.index(j)), s)
                self.sum_list.clear()
            self.textedit_one.moveCursor(QTextCursor.End)
            self.textedit_one.insertPlainText(f'目前有{len(self.data[j].values)}条数据!\n')
            self.table_one.setEditTriggers(QAbstractItemView.NoEditTriggers)  # 设置单元格不可编辑
 
        elif self.filename[-4:] == "docx":
            self.textedit_one.moveCursor(QTextCursor.End)
            self.textedit_one.insertPlainText("\n导入成功!\n")
            self.textedit_one.moveCursor(QTextCursor.End)
            self.textedit_one.insertPlainText(f'\n成功导入Word文件!,路径为:{self.filename}\n')
        elif self.filename[-3:] == "pdf":
            self.textedit_one.moveCursor(QTextCursor.End)
            self.textedit_one.insertPlainText("\n导入成功!\n")
            self.textedit_one.moveCursor(QTextCursor.End)
            self.textedit_one.insertPlainText(f'\n成功导入PDF文件!,路径为:{self.filename}\n')
        elif os.path.isdir(self.filename):
            self.textedit_one.moveCursor(QTextCursor.End)
            self.textedit_one.insertPlainText("\n导入成功!\n")
            self.textedit_one.moveCursor(QTextCursor.End)
            self.textedit_one.insertPlainText(f'\n成功导入内含PDF文件的文件夹!,路径为:{self.filename}\n')
 
        else:
            self.textedit_one.moveCursor(QTextCursor.End)
            self.textedit_one.insertPlainText("\n导入失败,请检查是否导入的是后缀为:xlsx,docx,pdf的文件!\n")
 
    def Queryinfomation(self):
        for i in range(self.shape[0]):
            for i2 in range(self.shape[1]):
                Query = self.table_one.item(i,i2).text()
                print(Query)
    def compile_True(self,table_view):
        self.table_one.setEditTriggers(QAbstractItemView.DoubleClicked)
    def compile_False(self,table_view):
        self.table_one.setEditTriggers(QAbstractItemView.NoEditTriggers)
    def appendinfo(self,table_view):
        self.i +=1
        self.table_one.setRowCount(self.i)
 
    def dragEnterEvent(self, QDragEnterEvent):
        if QDragEnterEvent.mimeData().hasText():
            QDragEnterEvent.acceptProposedAction()
    def dropEvent(self, QDropEvent):
        self.filename = QDropEvent.mimeData().text().replace('file:///', '')
        print(self.filename)
        self.excal()
    def closeEvent(self, event):
        reply=QMessageBox.question(self,'Message','确定要退出吗?',QMessageBox.Yes,QMessageBox.No)
        if reply == QMessageBox.Yes:
            sys.exit()
        else:
            event.ignore()
    def pyMuPDF_fitz(self,pdfPath, imagePath):
        pdfDoc = fitz.open(pdfPath)
        for pg in range(pdfDoc.pageCount):
            page = pdfDoc[pg]
            rotate = int(0)
            zoom_x = 1.33333333
            zoom_y = 1.33333333
            mat = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)
            pix = page.getPixmap(matrix=mat, alpha=False)
 
            if not os.path.exists(imagePath):
                os.makedirs(imagePath)
            pix.writePNG(imagePath + '/' + 'images_%s.png' % pg)
    def Start_Word_PDF(self):
        if self.filename[-4:] == "docx" or self.filename[-3:] == "dox":
            reply = QMessageBox.question(win, '温馨提示!', '程序开始执行时,因为计算量大可能会导致卡顿,这是正常现象,请不要乱点,请耐心稍等一会儿!!!', QMessageBox.Yes | QMessageBox.No,(QMessageBox.Yes))
            if reply == QMessageBox.Yes:
                pass
            else:
                self.Start_Word_PDF()
 
            Word_pdf_path = self.filename.replace(self.filename[-4:],"pdf")
            word = gencache.EnsureDispatch('Word.Application')
            doc = word.Documents.Open(self.filename, ReadOnly=1)
            doc.ExportAsFixedFormat(Word_pdf_path,constants.wdExportFormatPDF,Item=constants.wdExportDocumentWithMarkup,CreateBookmarks=constants.wdExportCreateHeadingBookmarks)
            word.Quit(constants.wdDoNotSaveChanges)
            self.textedit_one.moveCursor(QTextCursor.End)
            self.textedit_one.insertPlainText(f"\nWord文件已成功转换PDF文件,请前往Word同目录下查看!!!\n\n生成路径为:{Word_pdf_path}\n")
        else:
            QMessageBox.question(win, '温馨提示!', '请检查是否为Word文件!!',
                                 QMessageBox.Yes | QMessageBox.No, (QMessageBox.Yes))
 
    def Start_PDF_Image(self):
        if self.filename[-3:] == "pdf":
            reply = QMessageBox.question(win, '温馨提示!', '程序开始执行时,因为计算量大可能会导致卡顿,这是正常现象,请不要乱点,耐心稍等一会儿!!!',QMessageBox.Yes | QMessageBox.No, (QMessageBox.Yes))
            if reply == QMessageBox.Yes:
                pass
            else:
                self.Start_PDF_Image()
 
            self.textedit_one.moveCursor(QTextCursor.End)
            self.textedit_one.insertPlainText(f'\n正在转换PDF图片,\n')
            PDF_images_path = os.path.join(os.path.expanduser("~"), 'Desktop//PDF_images')
            self.pyMuPDF_fitz(self.filename, PDF_images_path)
            self.textedit_one.moveCursor(QTextCursor.End)
            self.textedit_one.insertPlainText(f'\nPDF文件已成功转换图片文件,请前往桌面查看!!!\n\n生成路径为:{PDF_images_path}\n')
 
        else:
            QMessageBox.question(win, '温馨提示!', '请检查是否为PDF文件!!',
                                     QMessageBox.Yes | QMessageBox.No, (QMessageBox.Yes))
 
    def Start_PDF_Word(self):
        if os.path.isdir(self.filename):
            QMessageBox.question(win, '温馨提示!', '程序开始执行时,因为计算量大可能会导致卡顿,这是正常现象,请不要乱点,耐心稍等一会儿!!!',
                                         QMessageBox.Yes | QMessageBox.No, (QMessageBox.Yes))
            config_parser = ConfigParser()
            config_parser.read('config.cfg', encoding='utf-8')
            config = config_parser['default']
            for file in os.listdir(self.filename):
                extension_name = os.path.splitext(file)[1]
                if extension_name != '.pdf':
                    continue
                file_name = os.path.splitext(file)[0]
                pdf_file = self.filename + '/' + file
                word_file = self.filename + '/' + file_name + '.docx'
 
                cv = Converter(pdf_file)
                cv.convert(word_file)
                cv.close()
                self.textedit_one.moveCursor(QTextCursor.End)
                self.textedit_one.insertPlainText(f'\nPDF文件已成功转换图片文件,请前往桌面查看!!!\n\n生成路径为:{word_file}\n')
        else:
            QMessageBox.question(win, '温馨提示!', '请导入一个内含PDF文件的文件夹!!!',
                                 QMessageBox.Yes | QMessageBox.No, (QMessageBox.Yes))
if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = Main_Win()
    sys.exit(app.exec_())

吸取评论区的建议,新加了PDF转Word,因为win7的分辨率,同时缩小了软件界面,软件在上面的阿里云里,根据需求自行下载正常版和迷你版


迷你版成品图


正常大小的成品图

测试的时候出现闪退现象,大概率是因为电脑没有office全家桶,就是Excel,word,pdf这些软件,小概率是因为你电脑已经有同个类型同个名称的文件了
如果文件较大,卡顿是正常情况,不用理会的,它只是这个软件未响应,不影响电脑正常使用,该打游戏的打游戏,办公的办公,等它处理完就恢复了!!!!!

还有这个排版真的难受,自动给你文字中间加一条线,是啥意思.............

相关推荐

华为云会议app下载(华为云会议下载)

 华为云会议可以在PC客户端或者手机客户端上一键发起立即会议,1秒创会。然后在会中选择企业通讯录中的人加入,系统会自动呼叫这些与会人,接听后即加入会议。ZOOM是一个云会议服务平台,为客户提...

路由器重置方法(路由器重置方法详细步骤)

路由器靠近WAN口边上的有一个小孔用于路由器的重置,路由器配置完成后,我们可能会忘记他的用户名或者是密码,那么我们可以把它恢复到出厂设置,再靠近万口或电源之间,有一个小孔,用一个尖锐的金属查一下大约五...

100个有效qq号以及密码(有效qq号和密码大全)

如果你的电脑知识好的话,不妨用一些复合密码!SHIFT+一些特殊符号,字母,数字!虽然麻烦了点,但总比被人盗号了的好,是吧!最好还用手机绑定一下,这样的话方便改密码也不怕QQ被盗了哦。。。QQ密码找回...

win10家庭中文版下载官网(windows10家庭中文版下载)

你好,激活Win10家庭中文版的方法:1.购买正版Win10家庭中文版激活码,然后在计算机上输入激活码,即可完成激活。2.如果您已经安装了Win10家庭中文版,但尚未激活,可以通过以下步骤激活:-...

电脑截图在哪里找(电脑截图在哪里找图片win10)

截图默认会保存在电脑的剪贴板中,可以通过以下步骤将其保存到本地:1.打开任意一款图片软件,如Paint、Photoshop、Word等。2.按下键盘上的Ctrl+V,或者在软件菜单栏中选择&#...

电脑里一堆microsoft visual

按照系统向下兼容原理,保留2010就可以了.1)你安装的时候是不是把创建快捷键的选项框都没选上,导致在开始菜单中没有找到相应的链接?2)去你的安装目录下,找到Microsoftvisualc++...

windows无法识别usb(windows无法识别usb设备)
windows无法识别usb(windows无法识别usb设备)

Windows无法识别USB,解决办法如下右键开始菜单打开设备管理器,在通用串行总线控制器中右键点击设备选择“卸载”,完成后重新启动计算机即可解决问题。这有可能是在组策略中禁用了USB口,可以使用快捷键【Win+R】运行gpedit.msc...

2025-11-10 11:51 off999

bios能看到硬盘 开机找不到硬盘

bios里可以看到硬盘,说明硬盘已经被主板识别。进系统找不到,可能硬盘没分区,或者硬盘是动态磁盘,还没有导入或激活。按win+r,输入diskmgmt.msc回车,就打开磁盘管理了,在里面可以给新硬盘...

找回qq聊天记录的方法(找回qq聊天记录怎么找)
  • 找回qq聊天记录的方法(找回qq聊天记录怎么找)
  • 找回qq聊天记录的方法(找回qq聊天记录怎么找)
  • 找回qq聊天记录的方法(找回qq聊天记录怎么找)
  • 找回qq聊天记录的方法(找回qq聊天记录怎么找)
无线网有个红叉(无线网有个红叉,搜索不到网络)

连接失败,路由坏换路由,外网坏,报修无线网络处出现红叉表示设备无法正常工作。请检查网卡驱动是否正常,无线网络开关是否打开。解决方法:查看电脑是否有无线网络开关,且是否打开。进入设备管理器检查网卡驱动是...

thinkpad笔记本官网首页(thinkpad官方商城)

官方网站 国内:http://www.thinkworld.com.cn   国内用户只需要访问国内即可。  ThinkPad,中文名为“思考本”,在2005年以前是IBMPC事业部旗下的便携式计算机...

win7什么版本最好用(win7哪个版本最稳定流畅)

Windows7旗舰版,最好,最稳定。Windows7,是由微软公司(Microsoft)开发的操作系统,内核版本号为WindowsNT6.1。Windows7可供选择的版本有:简易版(Sta...

win7自带虚拟光驱怎么使用(win7系统虚拟光驱安装教程)

以DAEMONTools为例,360软件管家里面就有最新版的下.安装后使用方法如下:第一种方法:在虚拟光驱界面中,你先按一下中间工具栏最左边“+”符号的按钮,添加镜像文件(可以一次添加多个),这...

电脑装系统蓝屏(电脑装系统蓝屏重启开不了机)

蓝屏的原因往往集中在不兼容的硬件和驱动程序、有问题的软件、病毒等。解决办法:1、病毒的原因。使用电脑管家杀毒。2、内存的原因。用橡皮擦把内存条的金手指擦拭一下,把氧化层擦掉,确保内存条安装、运行正常。...

u盘安装软件(u盘安装软件到电视)

第一种情况:软件安装包可以直接下载的。在电脑上将软件安装包下载到本地硬盘,然后将下载好软件安装包拷贝到U盘上即可拿到别的电脑上去安装。分可为exe格式的和rar格式,exe格式直接安装,rar格式的解...

取消回复欢迎 发表评论: