一、pdf显示逻辑
import sys
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgetsPDFJS = 'file:///pdfjs-1.9.426-dist/web/viewer.html'
# PDFJS = 'file:///usr/share/pdf.js/web/viewer.html'
PDF = 'file:///D:/Code/report.pdf'class Window(QtWebEngineWidgets.QWebEngineView):def __init__(self):super().__init__()print('%s?file=%s' % (PDFJS, PDF))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_())
必要条件: 下载PDFJS1.9.426(版本太高可能不支持pyqt5显示),调用web文件夹下的 view.html
文件。
注意: view.html
和.pdf
文件的路径前需要加上file:///
字符串,不然无法显示。原理可能涉及到前端技术,不过可以解释的是,当你用浏览器打开本地pdf文件时,路径前的确加了file:///
。之前一直不知道是什么东西没有加一直显示不出来,无意间看到浏览器下本地pdf的路径豁然开朗。
二、完整代码
主界面
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from pdfui import Ui_Form
import sys
import time
from tools import print_interfaceimport os
Pdf_path = ''
class ui_main(QMainWindow, Ui_Form):def __init__(self):super(ui_main, self).__init__()self.setupUi(self)self.pdf_view_btn.clicked.connect(self.show_report)#查看报表self.print_report_btn.clicked.connect(self.printpdf)#打印报表self.PDFJS = 'file:///pdfjs-1.9.426-dist/web/viewer.html' #已将不可用按钮设置为无法点击 button的disable属性def printpdf(self):if Pdf_path == '':passelse:printobject = print_interface.BridgeClass(Pdf_path)printobject.print_pdf()def show_report(self):self.name, _ = QFileDialog.getOpenFileName(self, 'Open File', './report_pdf', 'Image files (*.pdf)')print(self.name)self.load_pdf_in_qwebengineview(self.name)def load_pdf_in_qwebengineview(self,pdf_path):global Pdf_pathPdf_path = pdf_pathif pdf_path:file_path = 'file:///'+pdf_pathself.webEngineView.load(QUrl.fromUserInput('%s?file=%s' % (self.PDFJS, file_path)))def showMessage(self, message):result = QMessageBox.question(self, '提示', message, QMessageBox.Ok)if __name__ == '__main__':app = QApplication(sys.argv)window = ui_main()window.show()sys.exit(app.exec_())
UI
# -*- coding: utf-8 -*-# Form implementation generated from reading ui file 'pdfui.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.from PyQt5 import QtCore, QtGui, QtWidgetsclass Ui_Form(object):def setupUi(self, Form):Form.setObjectName("Form")Form.resize(851, 703)self.pdf_view_btn = QtWidgets.QPushButton(Form)self.pdf_view_btn.setGeometry(QtCore.QRect(320, 10, 75, 23))self.pdf_view_btn.setObjectName("pdf_view_btn")self.print_report_btn = QtWidgets.QPushButton(Form)self.print_report_btn.setGeometry(QtCore.QRect(440, 10, 75, 23))self.print_report_btn.setObjectName("print_report_btn")self.webEngineView = QtWebEngineWidgets.QWebEngineView(Form)self.webEngineView.setGeometry(QtCore.QRect(40, 40, 781, 651))self.webEngineView.setUrl(QtCore.QUrl("about:blank"))self.webEngineView.setObjectName("webEngineView")self.retranslateUi(Form)QtCore.QMetaObject.connectSlotsByName(Form)def retranslateUi(self, Form):_translate = QtCore.QCoreApplication.translateForm.setWindowTitle(_translate("Form", "Form"))self.pdf_view_btn.setText(_translate("Form", "查看报表"))self.print_report_btn.setText(_translate("Form", "打印报表"))
from PyQt5 import QtWebEngineWidgets
打印程序
# -*- coding:utf-8 -*-
import osimport win32print
import win32ui
from PIL import Image, ImageWin
import fitz # fitz就是pip install PyMuPDF
import shutilclass BridgeClass():def __init__(self, Pdf_path):self.Pdf_path = Pdf_pathself.imagePath = 'image_temporary'def print_pdf(self):# 获取打印机信息https://blog.51cto.com/u_16213318/7916941print('...................')printer_name = win32print.GetDefaultPrinter()print(printer_name)num = self.pyMuPDF_fitz(self.Pdf_path, self.imagePath)for i in range(1):self.img_print(self.imagePath, printer_name, num)self.del_files(self.imagePath)def pyMuPDF_fitz(self,pdfPath, imagePath):# print(333)pdfDoc = fitz.open(pdfPath)for pg in range(pdfDoc.page_count):page = pdfDoc[pg]rotate = int(0)zoom_x = 2.6 # (1.33333333-->1056x816) (2-->1584x1224)zoom_y = 2.6mat = fitz.Matrix(zoom_x, zoom_y).prerotate(rotate)pix = page.get_pixmap(matrix=mat, alpha=False)if not os.path.exists(self.imagePath):os.makedirs(self.imagePath)pix._writeIMG(self.imagePath + '/' + 'images_%s.png' % pg, format=1, jpg_quality=95)return pdfDoc.page_countdef img_print(self,imagePath, printer_name, num):for i in range(num):hDC = win32ui.CreateDC()hDC.CreatePrinterDC(printer_name)# 打开图片bmp = Image.open(imagePath + '/' + 'images_%s.png' % i)w, h = bmp.sizehDC.StartDoc(imagePath + '/' + 'images_%s.png' % i)hDC.StartPage()dib = ImageWin.Dib(bmp)# (10,10,1024,768)前面的两个数字是坐标,后面两个数字是打印纸张的大小# dib.draw(hDC.GetHandleOutput(), (0, 0, 4958, 7016))dib.draw(hDC.GetHandleOutput(), (0, 0, 4658, 6592))hDC.EndPage()hDC.EndDoc()hDC.DeleteDC()def del_files(self,dir_path):shutil.rmtree(dir_path)
三、整体资源下载(包括pdfjs、不用积分)
完成代码下载链接
四、参考资源
1.python - 如何在 PyQt 中使用 pdf.js 查看器呈现 PDF?