python调用小票打印机_PyQt5中使用Qprinter打印热敏小票

在《PyQt5中使用QWebChannel和内嵌网页进行js交互》一文中,我记录了如何使用QWebchannel与内嵌网页进行js交互,其根本目标在于使用Qt5调起打印机服务。在这篇文章中我将介绍一下具体使用Qprinter打印超市热敏小票的过程。

PyQt5中使用Qprinter打印热敏小票

参考内容:

Qt5官方文档

《pyqt5的 QPrinter 使用模板》 by 一心狮

本文包含以下内容:

1.使用html进行热敏打印的方法

2.分析存在的问题

3.提出另一种打印方法来解决问题

使用html进行热敏打印

python端代码

# -*- coding:utf-8 -*-

# webprint.py

from PyQt5.QtWidgets import QApplication

from PyQt5.QtCore import QObject, pyqtSlot, QUrl, QSizeF

from PyQt5.QtWebChannel import QWebChannel

from PyQt5.QtWebEngineWidgets import QWebEngineView

from PyQt5.QtPrintSupport import QPrinter, QPrinterInfo

from PyQt5.QtGui import QTextDocument

import sys

class Printer:

def __init__(self):

self.p = QPrinterInfo.defaultPrinter() # 获取默认打印机

self.print_device = QPrinter(self.p) # 指定打印所使用的装置

def print(self, content):

# 设置打印内容的宽度,否则打印内容会变形

self.print_device.setPageSizeMM(QSizeF(110, 250))

d = QTextDocument() # 使用QTextDcument对html进行解析

d.setDocumentMargin(0) # 将打印的边距设为0

# 设置全局生效的默认样式

d.setDefaultStyleSheet('''

* {padding:0;margin: 0;}

h1 {font-size: 20px;}

h3 {font-size: 16px;}

.left {float: left;}

.right {float:right;}

.clearfix {clear: both;}

ul {list-style: none;}

.print_container {width: 250px;}

.section2 label {display: block;}

.section3 label {display: block;}

.section4 .total label {display: block;}

.section4 {border-bottom: 1px solid #DADADA;}

.section5 label {display: block;}

''')

d.setHtml(content) # 注入html内容

d.print(self.print_device) # 调用打印机进行打印

class Print(QObject):

def __init__(self):

super().__init__()

self.printer = Printer()

@pyqtSlot(str, result=str)

def print(self, content):

self.printer.print(content)

return

if __name__ == '__main__':

app = QApplication(sys.argv)

browser = QWebEngineView()

browser.setWindowTitle('使用PyQt5打印热敏小票')

browser.resize(900, 600)

channel = QWebChannel()

printer = Print()

channel.registerObject('printer', printer)

browser.page().setWebChannel(channel)

url_string = "file:///python/print/webprint.html" # 内置的网页地址

browser.load(QUrl(url_string))

browser.show()

sys.exit(app.exec_())

网页端代码

使用PyQt5打印热敏小票

* {padding:0;margin: 0;}

h1 {font-size: 20px;}

h3 {font-size: 16px;}

.left {float: left;}

.right {float:right;}

.clearfix {clear: both;}

ul {list-style: none;}

.print_container {width: 250px;}

.section2 label {displ

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值