python连接打印机实现打印文档、图片、pdf文件等功能


Posted in Python onFebruary 07, 2020

引言

python连接打印机进行打印,可能根据需求的不同,使用不同的函数模块。

  1. 如果你只是简单的想打印文档,比如office文档,你可以使用ShellExecute方法,对于微软office的文档、pdf、txt等有用,你可以尝试下;
  2. 如果你输入某些数据,文字信息,就想直接把它发送给打印机打印,那么可以尝试使用win32print;
  3. 如果你有一张图片,那么你可以结合python的Python Imaging Library(PIL)win32ui模块进行打印;

普通打印

ShellExecute

  • 首先确保你电脑中的应用可以打开你要打印的文件;
  • 是一些标准的文件类型
  • 不用管哪些打印机,也就是说和连接的打印机型号无关;
  • 你无控制设置打印属性的权限;
import tempfile
import win32api
import win32print

filename = tempfile.mktemp (".txt")
open (filename, "w").write ("This is a test")
win32api.ShellExecute (
 0,
 "print",
 filename,
 #
 # If this is None, the default printer will
 # be used anyway.
 #
 '/d:"%s"' % win32print.GetDefaultPrinter (),
 ".",
 0
)

另一个版本

import tempfile
import win32api
import win32print

filename = tempfile.mktemp (".txt")
open (filename, "w").write ("This is a test")
win32api.ShellExecute (
 0,
 "printto",
 filename,
 '"%s"' % win32print.GetDefaultPrinter (),
 ".",
 0
)

直接打印数据

win32print

  • 直接将数据扔给打印机;
  • 快速而且容易;
  • 而且可以定义选择哪个打印机打印;
  • 但是要打印的数据必须是可打印的,例如字符串等;
import os, sys
import win32print
printer_name = win32print.GetDefaultPrinter ()
#
# raw_data could equally be raw PCL/PS read from
# some print-to-file operation
#
if sys.version_info >= (3,):
 raw_data = bytes ("This is a test", "utf-8")
else:
 raw_data = "This is a test"

hPrinter = win32print.OpenPrinter (printer_name)
try:
 hJob = win32print.StartDocPrinter (hPrinter, 1, ("test of raw data", None, "RAW"))
 try:
  win32print.StartPagePrinter (hPrinter)
  win32print.WritePrinter (hPrinter, raw_data)
  win32print.EndPagePrinter (hPrinter)
 finally:
  win32print.EndDocPrinter (hPrinter)
finally:
 win32print.ClosePrinter (hPrinter)

打印图片

PIL win32ui

不使用额外的工具,在windows电脑上打印一张图片是相当的困难,至少需要3种不同的且相关的设备环境才可以。
还好,device-independent bitmap(DIB)和PIL可以帮助我们快速打印。下面的代码可以将图片发送至打印机打印尽可能大的尺寸且不失比例。

  • 还可以选择使用哪个打印机
  • 选择加载的图片的格式等
  • 但是如果你电脑不是windows,那可能不是最好的方法;
import win32print
import win32ui
from PIL import Image, ImageWin

#
# Constants for GetDeviceCaps
#
#
# HORZRES / VERTRES = printable area
#
HORZRES = 8
VERTRES = 10
#
# LOGPIXELS = dots per inch
#
LOGPIXELSX = 88
LOGPIXELSY = 90
#
# PHYSICALWIDTH/HEIGHT = total area
#
PHYSICALWIDTH = 110
PHYSICALHEIGHT = 111
#
# PHYSICALOFFSETX/Y = left / top margin
#
PHYSICALOFFSETX = 112
PHYSICALOFFSETY = 113

printer_name = win32print.GetDefaultPrinter ()
file_name = "test.jpg"

#
# You can only write a Device-independent bitmap
# directly to a Windows device context; therefore
# we need (for ease) to use the Python Imaging
# Library to manipulate the image.
#
# Create a device context from a named printer
# and assess the printable size of the paper.
#
hDC = win32ui.CreateDC ()
hDC.CreatePrinterDC (printer_name)
printable_area = hDC.GetDeviceCaps (HORZRES), hDC.GetDeviceCaps (VERTRES)
printer_size = hDC.GetDeviceCaps (PHYSICALWIDTH), hDC.GetDeviceCaps (PHYSICALHEIGHT)
printer_margins = hDC.GetDeviceCaps (PHYSICALOFFSETX), hDC.GetDeviceCaps (PHYSICALOFFSETY)

#
# Open the image, rotate it if it's wider than
# it is high, and work out how much to multiply
# each pixel by to get it as big as possible on
# the page without distorting.
#
bmp = Image.open (file_name)
if bmp.size[0] > bmp.size[1]:
 bmp = bmp.rotate (90)

ratios = [1.0 * printable_area[0] / bmp.size[0], 1.0 * printable_area[1] / bmp.size[1]]
scale = min (ratios)

#
# Start the print job, and draw the bitmap to
# the printer device at the scaled size.
#
hDC.StartDoc (file_name)
hDC.StartPage ()

dib = ImageWin.Dib (bmp)
scaled_width, scaled_height = [int (scale * i) for i in bmp.size]
x1 = int ((printer_size[0] - scaled_width) / 2)
y1 = int ((printer_size[1] - scaled_height) / 2)
x2 = x1 + scaled_width
y2 = y1 + scaled_height
dib.draw (hDC.GetHandleOutput (), (x1, y1, x2, y2))

hDC.EndPage ()
hDC.EndDoc ()
hDC.DeleteDC ()

实践

从前台传来要打印的字符,后端生成二维码,并作出相应处理后,连接打印机打印图片。

# 打印二维码
def print_barcode(request):
  import pyqrcode
  import random,string
  from PIL import Image,ImageDraw,ImageFont
  import numpy as np
  if request.is_ajax() and request.method == 'POST':
    result = {}
    bar_string = 'NaN'
    type = request.POST['type']

    if type == 'box':
      # 生成箱子码
      # 格式:P190823-K91 [P][日期][-][A-Z][0-9][0-9]
      bar_string = 'P'+datetime.date.today().strftime('%y%m%d')+'-'+str(random.choice('ABCDEFGHIGKLMNOPQRSTUVWXYZ'))\
             + str(random.choice(range(10)))+ str(random.choice(range(10)))
    elif type == 'kuwei':
      # 生成库位码
      bar_string = request.POST['string']
    else:
      pass

    try:
      big_code = pyqrcode.create(bar_string, error='L', version=2 , mode='binary')
      big_code.png('./code.png', scale=8)
      img_code = Image.open('code.png')

      size = img_code.size
      img_final = Image.new('RGB', (size[0], size[1]+35), color=(255, 255, 255))
      img_final.paste(img_code, (0, 0, size[0], size[1]))

      draw = ImageDraw.Draw(img_final)
      font = ImageFont.truetype('AdobeGothicStd-Bold.otf', size=35)
      width, height = draw.textsize(bar_string,font=font)
      draw.text(((size[0]-width)/2, size[1]-15), bar_string , fill=(0, 0, 0), font=font)
      img_final.save('./code.png')

      # 然后连接打印机将其打印出来即可
      is_ok =[]
      if type == 'box':
        for i in range(4):
          temp = print_img('./code.png')
          is_ok.append(temp)
      else:
        temp = print_img('./code.png')
        is_ok.append(temp)
      # is_ok = True
      result['done'] = 'ok' if np.all(is_ok) else '连接打印机失败'
    except Exception as e:
      result['done'] = e

    return JsonResponse(result)
 
 def print_img(img):
  import win32print
  import win32ui
  from PIL import Image, ImageWin
  # 参考 http://timgolden.me.uk/python/win32_how_do_i/print.html#win32print
  try:
    printer_name = win32print.GetDefaultPrinter()
    hDC = win32ui.CreateDC()
    hDC.CreatePrinterDC(printer_name)

    #printable_area = (300, 270) # 打印纸尺寸
    #printer_size = (300, 270)

    # 打开图片并缩放
    bmp = Image.open(img)
    if bmp.size[0] < bmp.size[1]:
      bmp = bmp.rotate(90)

    # ratios = [1.0 * printable_area[0] / bmp.size[1], 1.0 * printable_area[1] / bmp.size[0]]
    # scale = min(ratios)
    scale = 1

    hDC.StartDoc(img)
    hDC.StartPage()

    dib = ImageWin.Dib(bmp)
    scaled_width, scaled_height = [int(scale * i) for i in bmp.size]

    x1 = 20 # 控制位置
    y1 = -30
    x2 = x1 + scaled_width
    y2 = y1 + scaled_height
    dib.draw(hDC.GetHandleOutput(), (x1, y1, x2, y2))

    hDC.EndPage()
    hDC.EndDoc()
    hDC.DeleteDC()

    return True
  except:
    return False

打印效果:

python连接打印机实现打印文档、图片、pdf文件等功能

以上内容为二赛君整理发布,转载请注明出处,谢谢。

参考

http://timgolden.me.uk/python/win32_how_do_i/print.htm

Python 相关文章推荐
sqlalchemy对象转dict的示例
Apr 22 Python
优化Python代码使其加快作用域内的查找
Mar 30 Python
详细解读Python中解析XML数据的方法
Oct 15 Python
Python之Web框架Django项目搭建全过程
May 02 Python
python3实现基于用户的协同过滤
May 31 Python
对python 匹配字符串开头和结尾的方法详解
Oct 27 Python
django实现支付宝支付实例讲解
Oct 17 Python
python 实现绘制整齐的表格
Nov 18 Python
Python使用进程Process模块管理资源
Mar 05 Python
Python内置异常类型全面汇总
May 28 Python
Keras: model实现固定部分layer,训练部分layer操作
Jun 28 Python
编译 pycaffe时报错:fatal error: numpy/arrayobject.h没有那个文件或目录
Nov 29 Python
解决Keras 与 Tensorflow 版本之间的兼容性问题
Feb 07 #Python
tensorflow2.0与tensorflow1.0的性能区别介绍
Feb 07 #Python
python第三方库学习笔记
Feb 07 #Python
Python字典添加,删除,查询等相关操作方法详解
Feb 07 #Python
tensorflow之自定义神经网络层实例
Feb 07 #Python
在tensorflow中设置使用某一块GPU、多GPU、CPU的操作
Feb 07 #Python
谈一谈数组拼接tf.concat()和np.concatenate()的区别
Feb 07 #Python
You might like
安装PHP可能遇到的问题“无法载入mysql扩展” 的解决方法
2007/04/16 PHP
php error_log 函数的使用
2009/04/13 PHP
php绘图中显示不出图片的原因及解决
2014/03/05 PHP
模仿JQuery sortable效果 代码有错但值得看看
2009/11/05 Javascript
利用javaScript实现点击输入框弹出窗体选择信息
2013/12/11 Javascript
JavaScript对IE操作的经典代码(推荐)
2014/03/10 Javascript
JavaScript避免代码的重复执行经验技巧分享
2014/04/17 Javascript
如何实现双向绑定mvvm的原理实现
2019/05/28 Javascript
jquery实现直播弹幕效果
2019/11/28 jQuery
vue实现前端列表多条件筛选
2020/10/26 Javascript
python实现的解析crontab配置文件代码
2014/06/30 Python
python使用sorted函数对列表进行排序的方法
2015/04/04 Python
用Python的Django框架编写从Google Adsense中获得报表的应用
2015/04/17 Python
在Python的Django框架下使用django-tagging的教程
2015/05/30 Python
python模块之sys模块和序列化模块(实例讲解)
2017/09/13 Python
python密码错误三次锁定(实例讲解)
2017/11/14 Python
python3.7简单的爬虫实例详解
2019/07/08 Python
Python3 合并二叉树的实现
2019/09/30 Python
pytorch AvgPool2d函数使用详解
2020/01/03 Python
Python集成开发工具Pycharm的安装和使用详解
2020/03/18 Python
django 外键创建注意事项说明
2020/05/20 Python
python3.8.1+selenium实现登录滑块验证功能
2020/05/22 Python
python中remove函数的踩坑记录
2021/01/04 Python
纯CSS3单页切换导航菜单界面设计的简单实现
2016/08/16 HTML / CSS
师范生教师实习自我鉴定
2013/09/27 职场文书
工业设计专业个人求职信范文
2013/12/28 职场文书
大学生村官事迹材料
2014/01/21 职场文书
节能环保标语
2014/06/12 职场文书
房屋出租协议书范本(标准版)
2014/09/24 职场文书
公司离职证明标准范本
2014/10/05 职场文书
个人专业技术总结
2015/03/05 职场文书
公司财务部岗位职责
2015/04/14 职场文书
公司借条范本
2015/05/25 职场文书
盘点2020年适合农村地区创业的项目
2019/10/16 职场文书
Python进程池与进程锁之语法学习
2022/04/11 Python
微软Win11 全新照片应用面向 Dev预览版推出 新版本上手体验图集
2022/09/23 数码科技