功能:打开一个指定pdf文件,将pdf文件中第一页显示在窗口上。并且可以切换显示页面。
模块安装:pip install PyMuPDF
pip install PyQt5
代码:
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import fitz
import sys
class PDFWindows(QMainWindow): # 定义类继承自
def __init__(self):
super().__init__() # 调用父类init方法
self.setWindowTitle("PDF读写软件")
self.setGeometry(500, 100, 600, 930)
self.setup_ui()
self.allpages=0
self.t=0
self.wide=600
self.high=900
self.pages=0
self.fname=''
def setup_ui(self):
self.label = QLabel(self)
self.label.move(0,30)
bar = self.menuBar()
filemune = bar.addMenu('文件')
file = QAction("打开",self)
file.triggered.connect(self.showDialog)
filemune.addAction(file)
page_up = QAction("上一页",self)
page_up.setShortcut(Qt.Key_Up)
page_up.triggered.connect(self.pages_up)
filemune.addAction(page_up)
page_down = QAction("下一页",self)
page_down.setShortcut(Qt.Key_Down)
page_down.triggered.connect(self.pages_down)
filemune.addAction(page_down)
def showDialog(self):
self.fname = QFileDialog.getOpenFileName(self,'选择PDF文件',
'./',
"Text Files (*.pdf)"
)
print(self.fname)
if self.fname[0]!="" and self.fname[1]=="Text Files (*.pdf)":
self.image(self.fname[0])
def pages_up(self):
print("上一页")
if self.pages>0:
self.pages=self.pages-1
if self.fname!='':
self.image(self.fname[0])
else:
print(self.fname)
else:
csbox = QMessageBox(QMessageBox.Warning, self.tr("提示"), self.tr("已到第一页!"), QMessageBox.NoButton, self)
csbox.exec_()
def pages_down(self):
print("下一页")
if self.pages < self.allpages-1:
self.pages=self.pages+1
if self.fname!='':
self.image(self.fname[0])
else:
print(self.fname)
else:
csbox = QMessageBox(QMessageBox.Warning, self.tr("提示"), self.tr("已到最后一页!"), QMessageBox.NoButton, self)
csbox.exec_()
def image(self,files):
# 打开文件
doc = fitz.open(files)
self.allpages=int(doc.page_count)
page_one = doc.loadPage(self.pages)
page_pixmap = page_one.getPixmap()
#将Pixmap转换为QImage
image_format = QImage.Format_RGBA8888 if page_pixmap.alpha else QImage.Format_RGB888
page_image = QImage(page_pixmap.samples, page_pixmap.width,
page_pixmap.height, page_pixmap.stride, image_format)
width = page_image.width()
height = page_image.height()
pix = QPixmap.fromImage(page_image)
trans = QTransform()
trans.rotate(0)
new = pix.transformed(trans)
self.label.setFixedSize(self.wide, self.high)
self.label.setScaledContents(True)
self.label.setPixmap(new)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = PDFWindows()
window.show()
sys.exit(app.exec_())
显示界面:
通过上下键切换