import fitz
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QScrollArea, QVBoxLayout, \
QHBoxLayout, QPushButton, QLineEdit,QFileDialog
from PyQt5.QtGui import QImage, QPixmap
class Window(QWidget): # 定义类继承自
def __init__(self):
super().__init__() # 调用父类init方法
self.label = None
self.page_num = 0
self.file_path = str(QFileDialog.getOpenFileUrl()[0]).replace("PyQt5.QtCore.QUrl('file:///","").replace("')","")
print(self.file_path)
self.doc = fitz.open(self.file_path)
# self.doc =self.file_path
self.setWindowTitle("Rogabet PDF reader")
self.resize(1250, 800)
self.setup_ui()
self.generatePDFView()
def setup_ui(self):
vLayout = QVBoxLayout(self)
hLayout = QHBoxLayout(self)
self.nextpageBtn = QPushButton("下一页")
self.prevpageBtn = QPushButton("上一页")
self.pageLineEdit = QLineEdit()
self.pageLineEdit.setEnabled(False)
self.pageLineEdit.setMaximumWidth(80)
self.pageLineEdit.setAlignment(Qt.AlignCenter)
self.pageLineEdit.setText(str(self.page_num) + "/" + str(self.doc.pageCount))
hLayout.addStretch(30)
hLayout.addWidget(self.prevpageBtn)
hLayout.addWidget(self.pageLineEdit)
hLayout.addWidget(self.nextpageBtn)
hLayout.addStretch(30)
self.scrollarea = QScrollArea(self)
self.label = QLabel("标签显示文字")
self.tocDict = {}
self.scrollarea.setWidget(self.label)
vLayout.addWidget(self.scrollarea)
vLayout.addLayout(hLayout)
self.nextpageBtn.clicked.connect(self.nextpage)
self.prevpageBtn.clicked.connect(self.prevpage)
def prevpage(self):
if self.page_num <= 0:
self.page_num = self.doc.pageCount
self.page_num -= 1
# if self.page_num >= self.doc.pageCount:
# self.page_num -= self.doc.pageCount
self.pageLineEdit.setText(str(self.page_num) + "/" + str(self.doc.pageCount))
self.updatePdfView()
def nextpage(self):
self.page_num += 1
if self.page_num >= self.doc.pageCount:
self.page_num -= self.doc.pageCount
self.pageLineEdit.setText(str(self.page_num) + "/" + str(self.doc.pageCount))
self.updatePdfView()
def updatePdfView(self):
self.scrollarea.verticalScrollBar().setValue(0)
self.generatePDFView()
def generatePDFView(self):
self.doc = fitz.open(self.file_path)
trans_a = 200
trans_b = 200
trans = fitz.Matrix(trans_a / 100, trans_b / 100).prerotate(0)
pix = self.doc[self.page_num].get_pixmap(matrix=trans)
fmt = QImage.Format_RGBA8888 if pix.alpha else QImage.Format_RGB888
pageImage = QImage(pix.samples, pix.width, pix.height, pix.stride, fmt)
pixmap = QPixmap()
pixmap.convertFromImage(pageImage)
self.label.setPixmap(QPixmap(pixmap))
self.label.resize(pixmap.size())
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())