alonisser
alonisser

Reputation: 12068

printing to windows printer with python or shell command

I'm tryin to script an annoying task that involves fetching, handling and printing loads of scanned docs - jpeg or pdf. I don't succeed in accessing the printer from python or from windows shell (which I could script with python subproccess module). I succeeded in printing a text file from the command line with lpr command, but not jpg or pdf.

be glad for any clues about that, including a more extensive win shell reference for printing to printer, a suitable python library I missed in my google search stackoverflow search etc (just one unanswered question)

Upvotes: 2

Views: 13874

Answers (4)

edgarglzza
edgarglzza

Reputation: 1

My brohter showed me another way to print using cmd (on windows) but I guess it could work for any OS.

In this case it worked for me using VScode as environment:

  1. get the filepath.
import os

myfile = os.path.join(os.getcwd(),"Foldername","Filename.pdf")
    open_file = open(myfile, "rb")

  1. Identify the command of your OS to print from the command source (like cmd):
command = "Start-Process -FilePath " + '\"' + myfile +'\"' + " -Verb Print"
  1. Get the output method in python. I used import subprocess module method.
output = subprocess.check_output(["powershell", command], stderr=subprocess.STDOUT, universal_newlines=True)

This script will allow you to print making a connection from python to cmd and from cmd to python again. Also, I had to make a .bat file to execute the testing program because VScode do not execute with all permissions. the file contains the following command (works like if its the cmd)

python.exe filepath\myfile.py

just executing the bat file will execute the program correctly.

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 113940

with a default pdf viewer assigned to the system you can do

 import win32api
 fname="C:\\somePDF.pdf"
 win32api.ShellExecute(0, "print", fname, None,  ".",  0)

note that this will only work on windows and will not work with all pdf viewers but it should be good with acrobat and Foxit and several other major ones.

Upvotes: 1

f p
f p

Reputation: 3223

I used this for a rtf (just an idea) :

subprocess.call(['loffice', '-pt', 'LaserJet', file])

I am using LibreOffice. it can print in a batch mode.

Upvotes: 1

user1106551
user1106551

Reputation:

Well, after a little research I found some links that might help you:

1) To print images using Python Shell, this link below has some code using PIL that will, hopefully, do what you want: http://timgolden.me.uk/python/win32_how_do_i/print.html

2) To print PDF files, this link may have what you need: http://www.darkcoding.net/software/printing-word-and-pdf-files-from-python/

I never did any of those things, but with a quick look, I could find this links and they seem to make very much sense. Hope it helps :)

Upvotes: 2

Related Questions