- Printing(to a printer) — how to.
- Recommended Answers Collapse Answers
- All 8 Replies
- Print to Standard Printer from Python
- How to send print job to printer in python
- Is There a way to print pictures With a printer using python?
- setting default printer custom page size with python
- Printing a file and configure printer settings
- printing out a text file with default printer
- can you print a file from python?
- 3 Answers 3
Printing(to a printer) — how to.
Hi, Im relatively experienced with the Python language, but i have a smaller knowledge of its modules etc. Im familiar with Tkinter, basic sockets, basic threading, math ( i know the most about). Im looking for a way to print to a printer. I can read from files easily — but what i want to do is to have each file printed with line numbers ( with wordwrap), and to add the document name at the top, and «Page x of y» at the bottom. The page name I need to format ( it will contain the full path, minus a specified section whic i can store in a variable to display on each page). Visual example: ——————————————+
| /dir/file.txt
|1 code
|2 code
|3 code
|
|.
|
| page 1 of 5
+—————————————-+
well thats the idea. I dont know how to print to a printer — liek I can in Visual Basic ( thought I hevent figured out the line numbering etc in that either). Is ther a particular module/library I need to install to be able to print form python? I am using Windows XP, and Python 2.5.1. Thanks for any and all help in advance.
- 4 Contributors
- 8 Replies
- 6K Views
- 2 Days Discussion Span
- Latest Post 15 Years Ago Latest Post by PC_Nerd
Recommended Answers Collapse Answers
To print directly to the printer, you have to access the device driver. I’m on linux so can’t help you there. A more common method for simple files that do not have to be formatted is to write the output to a file and use os.system() or subprocess with a …
Some of the basics of sending a text string to the printer are in the Python code snippet at:
http://www.daniweb.com/code/snippet399.htmlIf you have a Python code file like this .
# days2xmas.py # calculate days till xmas of 2008 import datetime as dt now = dt.date.today() …
All 8 Replies
To print directly to the printer, you have to access the device driver. I’m on linux so can’t help you there. A more common method for simple files that do not have to be formatted is to write the output to a file and use os.system() or subprocess with a system call to print the file. In linux it is
os.system( «lpr filename»)
In the dark ages when I used to use Windows it was just «print full_path_filename» which if it works it all the time you have to spend on this. The print command (if there is one) may also have an option to add line numbers when you print. Google should help you find more if no one here can be of more help.
Some of the basics of sending a text string to the printer are in the Python code snippet at:
http://www.daniweb.com/code/snippet399.html If you have a Python code file like this .
# days2xmas.py # calculate days till xmas of 2008 import datetime as dt now = dt.date.today() # change the year for other years xmas = dt.date(2008, 12, 25) time2xmas = xmas - now print "There are %d days till xmas 2008!" % time2xmas.days
You can load the file and build up a string you can send to the printer prefixed with line numbers this way.
# add line numbers to a code string my_str = "" linecount = 1 # load your code file for line in file("days2xmas.py", "r"): line = "%3d %s" % (linecount, line) my_str += line linecount += 1 print my_str """ my output --> 1 # days2xmas.py 2 # calculate days till xmas of 2008 3 4 import datetime as dt 5 6 now = dt.date.today() 7 # change the year for other years 8 xmas = dt.date(2008, 12, 25) 9 time2xmas = xmas - now 10 print "There are %d days till xmas 2008!" % time2xmas.days """
Breaking a long code string into page strings with page number, title and wordwrap is just a matter of string handling. Lots of work and a good exercise.
hmmm ok. Ive printed off and i plan on going through that turoail’/ code on the link you provoded (thanks). Im still not sure about the line numbering. As im sure your all aware, its easy to loop through a file and then attach each line to a dictionary with the first characters being a line number(increment) and then a tab. Thats easy. My main thing is that it looks like i have to manually wordwrap my printing — which is the hard part. can anyone suggest a method for this? Thanks
def wrap(text, width): """ A word-wrap function that preserves existing line breaks and most spaces in the text. Expects that existing line breaks are linux style newlines (\n). """ def func(line, word): nextword = word.split("\n", 1)[0] n = len(line) - line.rfind('\n') - 1 + len(nextword) if n >= width: sep = "\n" else: sep = " " return '%s%s%s' % (line, sep, word) text = text.split(" ") while len(text) > 1: text[0] = func(text.pop(0), text[0]) return text[0] # 2 very long lines separated by a blank line msg = """Arthur: "The Lady of the Lake, her arm clad in the purest \ shimmering samite, held aloft Excalibur from the bosom of the water, \ signifying by Divine Providence that I, Arthur, was to carry \ Excalibur. That is why I am your king!" Smarty: "Listen. Strange women lying in ponds distributing swords is \ no basis for a system of government. Supreme executive power derives \ from a mandate from the masses, not from some farcical aquatic \ ceremony!\"""" # example: make it fit in 40 columns print wrap(msg,40) # result is below """ Arthur: "The Lady of the Lake, her arm clad in the purest shimmering samite, held aloft Excalibur from the bosom of the water, signifying by Divine Providence that I, Arthur, was to carry Excalibur. That is why I am your king!" Smarty: "Listen. Strange women lying in ponds distributing swords is no basis for a system of government. Supreme executive power derives from a mandate from the masses, not from some farcical aquatic ceremony!" """
In Linux, one can use popen to access the print spooler, which then takes care of scheduling and printing the job. Does anyone know if this works on Windows using the «print» command?
pr=os.popen(«lpr», «w»)
pr.write(«Write this line directly to the print spooler\n»)
pr.close()
Ok, Nowe I hate to have to ask, but is there a default width of column size that would fit A4 paper? If i know what my margins from side will be, how would I then implement that into the code? I assume that the correct wat to wordwrap would be to alter each lines left align/margin? If now is there another way. Sorry abot this, Im not sued to overly formatting my data, expecially for a printer.
Thanks for all your help, its absoutely fantastic.
There is generally 8, 10, or 12 characters printed per inch using «normal» fonts. If you want the columns to line up then you have to use a monospaced/fixed width font instead of a proportional font. With a proportional font you can align the columns by inserting tabs but how it prints depends on the default tab size. You will have to print a test line or two to see what the default font for your printer does. i.e. send something like
. 1. 2. 3. 4. 5. 6. 7. 8
the above is for characters available per line (including margins) so length=available-margins
ilili
mwmwm
Print to Standard Printer from Python
Unfortunately, there is no standard way to print using Python on all platforms. So you’ll need to write your own wrapper function to print.
You need to detect the OS your program is running on, then:
import subprocess
lpr = subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE)
lpr.stdin.write(your_data_here)
For Windows: http://timgolden.me.uk/python/win32_how_do_i/print.html
Print PDF document with python’s win32print module?
How do I print to the OS’s default printer in Python 3 (cross platform)?
How to send print job to printer in python
try this! It uses os module to start the file in the default printer!
import os
os.startfile("YourDocument", "print")
Is There a way to print pictures With a printer using python?
This will only work on windows (10 or 11):
import os
os.startfile("C:/Users/TestFile.txt", "print")
This will start the file, in its default opener, with the verb ‘print’, which will print to your default printer. Only requires the os module which comes with the standard library
setting default printer custom page size with python
ShellExecute is using the default printing parameters. If you need to use the reset DevMode for printing, you can use CreateDC .
If you use SetPrinter to modify the default DEVMODE structure for a
printer (globally setting the printer defaults), you must first call
the DocumentProperties function to validate the DEVMODE structure.
You can also directly use DocumentProperties to modify printer initialization information.
Then pass pDevModeObj to CreateDC , and use StartDoc and StartPage to print.
Similar case: Change printer tray with pywin32
Printing a file and configure printer settings
Look at the «How To Print» page on Tim Golden’s website. This page was the same in 2014 when you asked your question. There’s an example printing a JPG file that also manipulates the printer settings.
That’s not quite a perfect example for what you’re doing but it should get you on the right track.
DC_PAPERS is defined in win32con:
import win32con
x = win32con.DC_PAPERS
How you’re supposed to know that, I have no idea. Perhaps it’s «obvious» to those already familiar with the Win32API outside of Python.
printing out a text file with default printer
you don’t have to use StringIO for this. Just use the pipe feature of subprocess and write your data to p.stdin :
from subprocess import Popen
# call the system's lpr command
p = Popen(["lpr"], stdin=subprocess.PIPE, shell=True) # not sure you need shell=True for a simple command
p.stdin.write("test.txt")
output = p.communicate()[0]
as a bonus, this is Python 3 compliant ( StringIO has been renamed since :))
BUT: that would just print a big white page with one line: test.txt . lpr reads standard input and prints it (that’s still an interesting piece of code :))
To print the contents of your file you have to read it, and in that case it’s even simpler since pipe & files work right away together:
from subprocess import Popen
with open("test.txt") as f:
# call the system's lpr command
p = Popen(["lpr"], stdin=f, shell=True) # not sure you need shell=True for a simple command
output = p.communicate()[0]
can you print a file from python?
Is there some way of sending output to the printer instead of the screen in Python? Or is there a service routine that can be called from within python to print a file? Maybe there is a module I can import that allows me to do this?
There are really plenty of resources explaining that in Google — just ask for «python print to printer» and you’ll get many ideas for using lp or lpr on linux/unix/mac and/or windows modules which you could use. Proof — bytes.com/topic/python/answers/169648-print-printer and newcenturycomputers.net/projects/pythonicwindowsprinting.html
I wanted to print out a simple .txt file without any formatting requirements from a button on an interface. I was looking for a specific module name (64 bit windows machine) and function from the module.
3 Answers 3
Most platforms—including Windows—have special file objects that represent the printer, and let you print text by just writing that text to the file.
On Windows, the special file objects have names like LPT1: , LPT2: , COM1: , etc. You will need to know which one your printer is connected to (or ask the user in some way).
It’s possible that your printer is not connected to any such special file, in which case you’ll need to fire up the Control Panel and configure it properly. (For remote printers, this may even require setting up a «virtual port».)
At any rate, writing to LPT1: or COM1: is exactly the same as writing to any other file. For example:
with open('LPT1:', 'w') as lpt: lpt.write(mytext)
lpt = open('LPT1:', 'w') print >>lpt, mytext print >>lpt, moretext close(lpt)
If you’ve already got the text to print in a file, you can print it like this:
with open(path, 'r') as f, open('LPT1:', 'w') as lpt: while True: buf = f.read() if not buf: break lpt.write(buf)
Or, more simply (untested, because I don’t have a Windows box here), this should work:
import shutil with open(path, 'r') as f, open('LPT1:', 'w') as lpt: shutil.copyfileobj(f, lpt)
It’s possible that just shutil.copyfile(path, ‘LPT1:’) , but the documentation says «Special files such as character or block devices and pipes cannot be copied with this function», so I think it’s safer to use copyfileobj .