我正在开发一个图形界面来自动加载并显示pdf。
到目前为止我做了什么
我成功将图像加载到Qlabel
然后显示中。我想更改和加载 pdf 文件,但它不起作用,因为这是图像而不是 pdf 文件。
我通过加载图像得到什么:
我渴望得到什么。
我想加载类似于图像加载的 pdf 文件。
编码:
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication,QMainWindow,QLabel,QSizePolicy,QAction
from PyQt5.QtPrintSupport import QPrintDialog,QPrinter
from PyQt5.QtGui import QImage,QIcon,QPixmap
class MainWindow(QtWidgets.QMainWindow):
def __init__(self,parent=None):
super(MainWindow, self).__init__(parent)
self.setWindowTitle('PDF loading')
self.loadLabel=QtWidgets.QLabel()
self.loadLabel.setSizePolicy(QtWidgets.QSizePolicy.Ignored,QtWidgets.QSizePolicy.Ignored)
self.setCentralWidget(self.loadLabel)
self.image = QtGui.QImage()
if self.image.load('image\test.jpg'):
self.loadLabel.setPixmap(QtGui.QPixmap.fromImage(self.image))
self.resize(self.image.width(),self.image.height())
self.createActions()
self.createMenus()
self.createToolBars()
def createActions(self):
self.PrintAction=QAction(QIcon('image\test.jpg'),self.tr('Test'),self)
self.PrintAction.triggered.connect(self.slotPrint)
def createMenus(self):
PrintMenu=self.menuBar().addMenu(self.tr('Test'))
PrintMenu.addAction(self.PrintAction)
def createToolBars(self):
fileToolBar=self.addToolBar('Print')
fileToolBar.addAction(self.PrintAction)
def slotPrint(self):
printer=QPrinter()
printDialog=QPrintDialog(printer,self)
if printDialog.exec_():
painter=QPainter(printer)
rect=painter.viewport()
size=self.image.size()
size.scale(rect.size(),Qt.KeepAspectRatio)
painter.setViewport(rect.x(),rect.y(),size.width(),size.height())
painter.setWindow(self.image.rect)
painter.drawImage(0,0,self.image)
if __name__ == '__main__':
app=QApplication(sys.argv)
main=MainWindow()
main.show()
sys.exit(app.exec_())
感谢您的帮助,谢谢
- - -编辑 - - -
我试图实现代码,但它并没有真正起作用。我做错了什么。我只是得到空白页?
编辑代码:
import sys
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
PDFJS = 'file:///C:/Users/se/Desktop/Python_Coding/Stackoverflow/QPrint and PDF Preview/123.pdf'
# PDFJS = 'file:///usr/share/pdf.js/web/viewer.html'
PDF = 'file:///C:/Users/se/Desktop/4444.pdf'
class Window(QtWebEngineWidgets.QWebEngineView):
def __init__(self):
super(Window, self).__init__()
self.load(QtCore.QUrl.fromUserInput('%s?file=%s' % (PDFJS, PDF)))
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Window()
window.setGeometry(600, 50, 800, 600)
window.show()
sys.exit(app.exec_())
可视化: