xph
xph

Reputation: 997

Printing a file and configure printer settings

I'm trying to code a printer automation using Python on Windows, but can't get it done.

I'm not really understanding the topic and i'm a little surprised - a "simple" way to get this done doesn't seem to exist..? There are so many APIs that allow to access common things in a nice and easy way, but printing seems to be something "special"..?

 

Here is what i have and what i want to do:

 

To me, that doesn't seem to be a very "complex" task to do. Doing that "by hand" is very easy and straightforward - select the document, start printing, select the printer, select the paper size - and print.

Doing this by code seems to be rather difficult. Here is what i've come across until now.

 

And when using this win32print module, i can't get it to work correctly. Here is an exmple snippet i tried to use:

from win32print import *
printer = GetDefaultPrinterW()
handle = OpenPrinter(printer)
info = GetPrinter(handle, 2)
cap = DeviceCapabilities(info['pPrinterName'], info['pPortName'], DC_PAPERS)
ClosePrinter(handle)

...as described here:

http://timgolden.me.uk/pywin32-docs/win32print__DeviceCapabilities_meth.html

But that just returns:

NameError: name 'DC_PAPERS' is not defined

That happens whenever i'm trying to use a function that needs such constants passed. Not a single constant is defined on my system and i don't know why.

But i don't know if i could use this API even when working correctly, all the usage examples are just showing how to send a text-string to a printer. That's not what i need, that's not what i want to know.

 

Is there any working solution to print a file and to set the printing size in a simple and straightforward way?

Ideas and hints are welcome!

Upvotes: 8

Views: 13885

Answers (2)

Srinath Kamath
Srinath Kamath

Reputation: 558

The problem is you are using from win32print import * The latest python 3+ package for win32print does not store sub-modules under win32print module.

import win32print
import win32con
printer = win32print.GetDefaultPrinterW()
handle = win32print.OpenPrinter(printer)
info = win32print.GetPrinter(handle, 2)
cap = win32print.DeviceCapabilities(
    info['pPrinterName'], info['pPortName'], win32con.DC_PAPERNAMES)
print(cap)
win32print.ClosePrinter(handle)

Upvotes: 2

bobpaul
bobpaul

Reputation: 390

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...

Upvotes: 3

Related Questions