Is there a reasonably standard and cross platform way to print text (or even PS/PDF) to the system defined printer?
Assuming CPython here, not something clever like using Jython and the Java printing API.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
This has only been tested on Windows:
You can do the following:
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
Method 2
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:
For Linux –
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
More resources:
Print PDF document with python’s win32print module?
How do I print to the OS’s default printer in Python 3 (cross platform)?
Method 3
To print to any printer on the network you can send a PJL/PCL print job directly to a network printer on port 9100.
Please have a look at the below link that should give a good start:
http://frank.zinepal.com/printing-directly-to-a-network-printer
Also, If there is a way to call Windows cmd you can use FTP put to print your page on 9100. Below link should give you details, I have used this method for HP printers but I believe it will work for other printers.
http://h20000.www2.hp.com/bizsupport/TechSupport/Document.jsp?objectID=bpj06165
Method 4
You can try wx library. It’s a cross platform UI library. Here you can find the printing tutorial:
https://web.archive.org/web/20160619163747/http://wiki.wxpython.org/Printing
Method 5
I find this to be the superior solution, at least when dealing with web applications. The idea is this: convert the HTML page to a PDF document and send that to a printer via gsprint.
Even though gsprint is no longer in development, it works really, really well. You can choose the printer and the page orientation and size among several other options.
I convert the web page to PDF using Puppeteer, Chrome’s headless browser. But you need to pass in the session cookie to maintain credentials.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0