pyqt5+QWebEngineView+pdfjs+win32print实现pdf文件的预览、打印

2023-12-13 13:29:03

一、pdf显示逻辑

import sys
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets

PDFJS = '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_interface

import 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 == '':
            pass
        else:
            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_path
        Pdf_path = pdf_path

        if pdf_path:
            file_path = 'file:///'+pdf_path
            self.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, QtWidgets


class 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.translate
        Form.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 os

import win32print
import win32ui
from PIL import Image, ImageWin
import fitz  # fitz就是pip install PyMuPDF
import shutil


class BridgeClass():
    def __init__(self, Pdf_path):
        self.Pdf_path = Pdf_path
        self.imagePath = 'image_temporary'

    def print_pdf(self):
        # 获取打印机信息https://blog.51cto.com/u_16213318/7916941
        print('...................')
        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.6

            mat = 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_count

    def 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.size
            hDC.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?

文章来源:https://blog.csdn.net/weixin_42632271/article/details/134830232
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。