<li id="jut4n"></li>
  • 系統城裝機大師 - 唯一官網:www.ship-models.net!

    當前位置:首頁 > 腳本中心 > python > 詳細頁面

    python連接打印機實現打印文檔、圖片、pdf文件等功能

    時間:2020-02-09來源:系統城作者:電腦系統城

    引言

    python連接打印機進行打印,可能根據需求的不同,使用不同的函數模塊。

    1. 如果你只是簡單的想打印文檔,比如office文檔,你可以使用ShellExecute方法,對于微軟office的文檔、pdf、txt等有用,你可以嘗試下;
    2. 如果你輸入某些數據,文字信息,就想直接把它發送給打印機打印,那么可以嘗試使用win32print;
    3. 如果你有一張圖片,那么你可以結合python的Python Imaging Library(PIL)win32ui模塊進行打??;

    普通打印

    ShellExecute

    • 首先確保你電腦中的應用可以打開你要打印的文件;
    • 是一些標準的文件類型
    • 不用管哪些打印機,也就是說和連接的打印機型號無關;
    • 你無控制設置打印屬性的權限;
    
     
    1. import tempfile
    2. import win32api
    3. import win32print
    4.  
    5. filename = tempfile.mktemp (".txt")
    6. open (filename, "w").write ("This is a test")
    7. win32api.ShellExecute (
    8. 0,
    9. "print",
    10. filename,
    11. #
    12. # If this is None, the default printer will
    13. # be used anyway.
    14. #
    15. '/d:"%s"' % win32print.GetDefaultPrinter (),
    16. ".",
    17. 0
    18. )

    另一個版本

    
     
    1. import tempfile
    2. import win32api
    3. import win32print
    4.  
    5. filename = tempfile.mktemp (".txt")
    6. open (filename, "w").write ("This is a test")
    7. win32api.ShellExecute (
    8. 0,
    9. "printto",
    10. filename,
    11. '"%s"' % win32print.GetDefaultPrinter (),
    12. ".",
    13. 0
    14. )

    直接打印數據

    win32print

    • 直接將數據扔給打印機;
    • 快速而且容易;
    • 而且可以定義選擇哪個打印機打??;
    • 但是要打印的數據必須是可打印的,例如字符串等;
    
     
    1. import os, sys
    2. import win32print
    3. printer_name = win32print.GetDefaultPrinter ()
    4. #
    5. # raw_data could equally be raw PCL/PS read from
    6. # some print-to-file operation
    7. #
    8. if sys.version_info >= (3,):
    9. raw_data = bytes ("This is a test", "utf-8")
    10. else:
    11. raw_data = "This is a test"
    12.  
    13. hPrinter = win32print.OpenPrinter (printer_name)
    14. try:
    15. hJob = win32print.StartDocPrinter (hPrinter, 1, ("test of raw data", None, "RAW"))
    16. try:
    17. win32print.StartPagePrinter (hPrinter)
    18. win32print.WritePrinter (hPrinter, raw_data)
    19. win32print.EndPagePrinter (hPrinter)
    20. finally:
    21. win32print.EndDocPrinter (hPrinter)
    22. finally:
    23. win32print.ClosePrinter (hPrinter)

    打印圖片

    PIL win32ui

    不使用額外的工具,在windows電腦上打印一張圖片是相當的困難,至少需要3種不同的且相關的設備環境才可以。
    還好,device-independent bitmap(DIB)和PIL可以幫助我們快速打印。下面的代碼可以將圖片發送至打印機打印盡可能大的尺寸且不失比例。

    • 還可以選擇使用哪個打印機
    • 選擇加載的圖片的格式等
    • 但是如果你電腦不是windows,那可能不是最好的方法;
    
     
    1. import win32print
    2. import win32ui
    3. from PIL import Image, ImageWin
    4.  
    5. #
    6. # Constants for GetDeviceCaps
    7. #
    8. #
    9. # HORZRES / VERTRES = printable area
    10. #
    11. HORZRES = 8
    12. VERTRES = 10
    13. #
    14. # LOGPIXELS = dots per inch
    15. #
    16. LOGPIXELSX = 88
    17. LOGPIXELSY = 90
    18. #
    19. # PHYSICALWIDTH/HEIGHT = total area
    20. #
    21. PHYSICALWIDTH = 110
    22. PHYSICALHEIGHT = 111
    23. #
    24. # PHYSICALOFFSETX/Y = left / top margin
    25. #
    26. PHYSICALOFFSETX = 112
    27. PHYSICALOFFSETY = 113
    28.  
    29. printer_name = win32print.GetDefaultPrinter ()
    30. file_name = "test.jpg"
    31.  
    32. #
    33. # You can only write a Device-independent bitmap
    34. # directly to a Windows device context; therefore
    35. # we need (for ease) to use the Python Imaging
    36. # Library to manipulate the image.
    37. #
    38. # Create a device context from a named printer
    39. # and assess the printable size of the paper.
    40. #
    41. hDC = win32ui.CreateDC ()
    42. hDC.CreatePrinterDC (printer_name)
    43. printable_area = hDC.GetDeviceCaps (HORZRES), hDC.GetDeviceCaps (VERTRES)
    44. printer_size = hDC.GetDeviceCaps (PHYSICALWIDTH), hDC.GetDeviceCaps(PHYSICALHEIGHT)
    45. printer_margins = hDC.GetDeviceCaps (PHYSICALOFFSETX), hDC.GetDeviceCaps(PHYSICALOFFSETY)
    46.  
    47. #
    48. # Open the image, rotate it if it's wider than
    49. # it is high, and work out how much to multiply
    50. # each pixel by to get it as big as possible on
    51. # the page without distorting.
    52. #
    53. bmp = Image.open (file_name)
    54. if bmp.size[0] > bmp.size[1]:
    55. bmp = bmp.rotate (90)
    56.  
    57. ratios = [1.0 * printable_area[0] / bmp.size[0], 1.0 * printable_area[1] / bmp.size[1]]
    58. scale = min (ratios)
    59.  
    60. #
    61. # Start the print job, and draw the bitmap to
    62. # the printer device at the scaled size.
    63. #
    64. hDC.StartDoc (file_name)
    65. hDC.StartPage ()
    66.  
    67. dib = ImageWin.Dib (bmp)
    68. scaled_width, scaled_height = [int (scale * i) for i in bmp.size]
    69. x1 = int ((printer_size[0] - scaled_width) / 2)
    70. y1 = int ((printer_size[1] - scaled_height) / 2)
    71. x2 = x1 + scaled_width
    72. y2 = y1 + scaled_height
    73. dib.draw (hDC.GetHandleOutput (), (x1, y1, x2, y2))
    74.  
    75. hDC.EndPage ()
    76. hDC.EndDoc ()
    77. hDC.DeleteDC ()

    實踐

    從前臺傳來要打印的字符,后端生成二維碼,并作出相應處理后,連接打印機打印圖片。

    
     
    1. # 打印二維碼
    2. def print_barcode(request):
    3. import pyqrcode
    4. import random,string
    5. from PIL import Image,ImageDraw,ImageFont
    6. import numpy as np
    7. if request.is_ajax() and request.method == 'POST':
    8. result = {}
    9. bar_string = 'NaN'
    10. type = request.POST['type']
    11.  
    12. if type == 'box':
    13. # 生成箱子碼
    14. # 格式:P190823-K91 [P][日期][-][A-Z][0-9][0-9]
    15. bar_string = 'P'+datetime.date.today().strftime('%y%m%d')+'-'+str(random.choice('ABCDEFGHIGKLMNOPQRSTUVWXYZ'))\
    16. + str(random.choice(range(10)))+ str(random.choice(range(10)))
    17. elif type == 'kuwei':
    18. # 生成庫位碼
    19. bar_string = request.POST['string']
    20. else:
    21. pass
    22.  
    23. try:
    24. big_code = pyqrcode.create(bar_string, error='L', version=2 , mode='binary')
    25. big_code.png('./code.png', scale=8)
    26. img_code = Image.open('code.png')
    27.  
    28. size = img_code.size
    29. img_final = Image.new('RGB', (size[0], size[1]+35), color=(255, 255, 255))
    30. img_final.paste(img_code, (0, 0, size[0], size[1]))
    31.  
    32. draw = ImageDraw.Draw(img_final)
    33. font = ImageFont.truetype('AdobeGothicStd-Bold.otf', size=35)
    34. width, height = draw.textsize(bar_string,font=font)
    35. draw.text(((size[0]-width)/2, size[1]-15), bar_string , fill=(0, 0, 0), font=font)
    36. img_final.save('./code.png')
    37.  
    38. # 然后連接打印機將其打印出來即可
    39. is_ok =[]
    40. if type == 'box':
    41. for i in range(4):
    42. temp = print_img('./code.png')
    43. is_ok.append(temp)
    44. else:
    45. temp = print_img('./code.png')
    46. is_ok.append(temp)
    47. # is_ok = True
    48. result['done'] = 'ok' if np.all(is_ok) else '連接打印機失敗'
    49. except Exception as e:
    50. result['done'] = e
    51.  
    52. return JsonResponse(result)
    53.  
    54. def print_img(img):
    55. import win32print
    56. import win32ui
    57. from PIL import Image, ImageWin
    58. # 參考 http://timgolden.me.uk/python/win32_how_do_i/print.html#win32print
    59. try:
    60. printer_name = win32print.GetDefaultPrinter()
    61. hDC = win32ui.CreateDC()
    62. hDC.CreatePrinterDC(printer_name)
    63.  
    64. #printable_area = (300, 270) # 打印紙尺寸
    65. #printer_size = (300, 270)
    66.  
    67. # 打開圖片并縮放
    68. bmp = Image.open(img)
    69. if bmp.size[0] < bmp.size[1]:
    70. bmp = bmp.rotate(90)
    71.  
    72. # ratios = [1.0 * printable_area[0] / bmp.size[1], 1.0 * printable_area[1] / bmp.size[0]]
    73. # scale = min(ratios)
    74. scale = 1
    75.  
    76. hDC.StartDoc(img)
    77. hDC.StartPage()
    78.  
    79. dib = ImageWin.Dib(bmp)
    80. scaled_width, scaled_height = [int(scale * i) for i in bmp.size]
    81.  
    82. x1 = 20 # 控制位置
    83. y1 = -30
    84. x2 = x1 + scaled_width
    85. y2 = y1 + scaled_height
    86. dib.draw(hDC.GetHandleOutput(), (x1, y1, x2, y2))
    87.  
    88. hDC.EndPage()
    89. hDC.EndDoc()
    90. hDC.DeleteDC()
    91.  
    92. return True
    93. except:
    94. return False

    打印效果:

    python連接打印機實現打印文檔、圖片、pdf文件等功能

    以上內容為二賽君整理發布,轉載請注明出處,謝謝。

    參考

    分享到:

    相關信息

    系統教程欄目

    欄目熱門教程

    人氣教程排行

    站長推薦

    熱門系統下載

    淑芬两腿间又痒了