Я занимаюсь исследованием того, как печатать данные на локальном принтере из Python в Windows.
Если у вас есть документ и его путь, я нашел простой способ:
import os
os.startfile("C:/Users/Jdash/Desktop/TestFile.txt", "print")
Однако я хочу напрямую отправить текстовую строку, не создавая документ.
Этот код печати Windows через Python , похоже, выполняет то, что я хочу:
# create a dc (Device Context) object (actually a PyCDC)
dc = win32ui.CreateDC()
# convert the dc into a "printer dc"
# get default printer
printername = win32print.GetDefaultPrinter ()
# leave out the printername to get the default printer automatically
dc.CreatePrinterDC(printername)
# you need to set the map mode mainly so you know how
# to scale your output. I do everything in points, so setting
# the map mode as "twips" works for me.
dc.SetMapMode(win32con.MM_TWIPS) # 1440 per inch
# here's that scaling I mentioned:
scale_factor = 20 # i.e. 20 twips to the point
# start the document. the description variable is a string
# which will appear in the print queue to identify the job.
dc.StartDoc('Win32print test')
# to draw anything (other than text) you need a pen.
# the variables are pen style, pen width and pen color.
pen = win32ui.CreatePen(0, int(scale_factor), 0)
# SelectObject is used to apply a pen or font object to a dc.
dc.SelectObject(pen)
# how about a font? Lucida Console 10 point.
# I'm unsure how to tell if this failed.
font = win32ui.CreateFont({
"name": "Lucida Console",
"height": int(scale_factor * 10),
"weight": 400,
})
# again with the SelectObject call.
dc.SelectObject(font)
# okay, now let's print something.
# TextOut takes x, y, and text values.
# the map mode determines whether y increases in an
# upward or downward direction; in MM_TWIPS mode, it
# advances up, so negative numbers are required to
# go down the page. If anyone knows why this is a
# "good idea" please email me; as far as I'm concerned
# it's garbage.
dc.TextOut(scale_factor * 72,
-1 * scale_factor * 72,
"Testing...")
# must not forget to tell Windows we're done.
dc.EndDoc()
Мой вопрос в том, какие еще существуют способы печати из Python в Windows, которые позволяют отправлять текстовую строку напрямую?
Или, может быть, я слишком усложняю себе задачу, и создание документа проходит незаметно?
Один из способов печатать напрямую — использовать
win32print
. Вот несколько примеров, в которых также показаны другие способы печати текста, файлов PDF, изображений и т. д. из Python в Windows. Но то, что вы ищете, кажется, следующее:Вот еще один пример, который кажется более универсальным. Проверено на двух разных принтерах. (Тот, что выше, работал только на одном)
ссылка на код