Python implements sending pictures to the printer for printing

foreword

environment

OS: win10
python: 3.8.16

rely

pip install openpyxl qrcode pillow pypiwin32 reportlab

Function

python printer.pyAfter running, it will retrieve the printer device connected to the machine, and then select the printer according to the need, and then pass in the image path to send the printing task to the printer (the image will be converted to a vector image during the process).
You can batch automate the image input part, and then you can print in batches.

renderings

insert image description here

source code

direct print version

import win32print
import win32ui
from PIL import Image, ImageWin

# 列出所有打印机
printers = [printer[2] for printer in win32print.EnumPrinters(2)]
for i, printer in enumerate(printers):
    print(f"{
      
      i+1}: {
      
      printer}")

# 选择打印机
choice = int(input("选择要使用的打印机 (输入对应的序号): ")) - 1
printer_name = printers[choice]

# 加载图片
image_path = input("输入要打印的图片的路径: ")
image = Image.open(image_path)

# 创建设备描述表
hDC = win32ui.CreateDC()
hDC.CreatePrinterDC(printer_name)

# 开始文档
hDC.StartDoc(image_path)

# 开始页面
hDC.StartPage()

# 绘制位图
dib = ImageWin.Dib(image)
dib.draw(hDC.GetHandleOutput(), (0, 0, image.width, image.height))

# 结束页面
hDC.EndPage()

# 结束文档
hDC.EndDoc()

# 删除设备描述表对象
del hDC

print("打印成功!")

The version that opens edge for printing

Will run edge and let you manually print 0.0

import subprocess
import win32print
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter, landscape
from PIL import Image

# 列出所有打印机
printers = [printer[2] for printer in win32print.EnumPrinters(2)]
for i, printer in enumerate(printers):
    print(f"{
      
      i+1}: {
      
      printer}")

# 选择打印机
choice = int(input("选择要使用的打印机 (输入对应的序号): ")) - 1
printer_name = printers[choice]

# 加载图片
image_path = input("输入要打印的图片的路径: ")
image = Image.open(image_path)

# 转换图片为PDF
pdf_path = image_path.rsplit('.', 1)[0] + '.pdf'
c = canvas.Canvas(pdf_path, pagesize=landscape(letter))
width, height = landscape(letter)
c.drawImage(image_path, 0, 0, width, height)
c.showPage()
c.save()

# 打印PDF
edge_path = r'C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe' # 默认的Edge路径
cmd = [edge_path, '--kiosk-printing', pdf_path]
subprocess.run(cmd)

print("打印成功!")

Guess you like

Origin blog.csdn.net/Ikaros_521/article/details/130965339