- 将帖子标记为未读
- 将此主题添加到书签
- 订阅此主题
- 禁止
- 订阅此主题的 RSS 提要
- 高亮显示此贴
- 打印此贴
- 标记帖子
如何使用 Python 的 Socket 连接网络打印机直接打印内容?
发布时间 2023-10-10 10:09:48
产品名称: HP LaserJet Professional M1132 MFP
import socket
def text_to_pcl(text):
pcl_data = b'\x1B%-12345X' # 进入 PCL 模式
# 设置页面大小(默认为A4)
pcl_data += b'\x1B&l26A'
# 设置字体(默认字体)
pcl_data += b'\x1B(s0p10h12v0s1b4099T'
# 打印文本
pcl_data += text.encode('utf-8')
pcl_data += b'\x1B&l0H' # 退出 PCL 模式
return pcl_data
if __name__ == "__main__":
mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "10.77.77.199"
port = 9100
try:
# 要打印的文本
text_to_print = "Hello, World!\nThis is a test print."
pcl_data = text_to_pcl(text_to_print)
mysocket.connect((host, port)) # connecting to host
mysocket.sendall(pcl_data) # sending data to printer
# 是否发送成功
print(mysocket)
# print(mysocket.recv(1024)) # receiving data from host
print("Printing Successful")
mysocket.close() # closing connection
except:
print("Error with the connection")
1 条回复1