from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QMessageBox
from PyQt5.QtCore import Qt
import sys
import os
from comtypes import client
#文件轉(zhuǎn)換腳本
class FileDropWidget(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
layout = QVBoxLayout()
# 設(shè)置窗口標(biāo)題
self.setWindowTitle("word/pdf")
# 隱藏標(biāo)題欄和控制按鈕
self.setWindowFlags(Qt.FramelessWindowHint)
# 設(shè)置窗口置于頂層
self.setWindowFlags(Qt.WindowStaysOnTopHint)
# 獲取屏幕的可用幾何區(qū)域
screen_geometry = QApplication.desktop().availableGeometry()
# 設(shè)置窗口大小
window_width = 400
window_height = 300
self.resize(window_width, window_height)
# 將窗口移動(dòng)到屏幕中心
x = (screen_geometry.width() - window_width) // 2
y = (screen_geometry.height() - window_height) // 2
self.move(x, y)
#拖拉區(qū)域代碼
label = QLabel("拖放Word文件到此區(qū)域")
label.setAlignment(Qt.AlignCenter)
label.setStyleSheet("""
QLabel {
background-color: #EAF2F8;
font-family: Arial;
font-size: 35px;
font-weight: 40px;
color: #333333;
padding: 10px;
border: 4px dashed #CCCCCC;
border-radius: 30px;
}
""")
label.setAcceptDrops(True)
label.installEventFilter(self)
layout.addWidget(label)
self.setLayout(layout)
def eventFilter(self, obj, event):
if event.type() == event.DragEnter:
if event.mimeData().hasUrls():
event.acceptProposedAction()
elif event.type() == event.Drop:
if event.mimeData().hasUrls():
files = [url.toLocalFile() for url in event.mimeData().urls()]
self.handleDroppedFiles(files)
event.acceptProposedAction()
return super().eventFilter(obj, event)
def handleDroppedFiles(self, files):
for file in files:
if file.endswith('.docx') or file.endswith('.doc'):
self.convertToPDF(file)
else:
self.showErrorMessage("請(qǐng)拖放Word文件或類(lèi)似文件!")
def convertToPDF(self, docx_file):
word = client.CreateObject("Word.Application")
word.Visible = False
doc = word.Documents.Open(docx_file)
pdf_file = os.path.splitext(docx_file)[0] + ".pdf"
doc.SaveAs(pdf_file, FileFormat=17)
doc.Close()
# 關(guān)閉 Word 窗口
word.Quit()
# 顯示轉(zhuǎn)換成功的消息框
reply = QMessageBox.question(self, "轉(zhuǎn)換成功", f"已將Word文件轉(zhuǎn)換為PDF文件:\n{pdf_file}\n\n是否繼續(xù)拖放Word文件",
QMessageBox.Yes | QMessageBox.No)
# 根據(jù)用戶(hù)的選擇執(zhí)行相應(yīng)的操作
if reply == QMessageBox.Yes:
# 用戶(hù)選擇繼續(xù)執(zhí)行代碼
print("繼續(xù)執(zhí)行代碼...")
elif reply == QMessageBox.No:
# 用戶(hù)選擇關(guān)閉 Word/PDF 窗口
os.startfile(pdf_file) # 打開(kāi) PDF 文件
if __name__ == "__main__":
app = QApplication(sys.argv)
widget = FileDropWidget()
widget.resize(300, 200)
widget.show()
sys.exit(app.exec_())
拖入word文件到規(guī)定區(qū)域,即可生成PDF格式文件文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-521171.html
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-521171.html
到了這里,關(guān)于python腳本(Word轉(zhuǎn)PDF格式小工具)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!