简体   繁体   中英

Print PDF file in duplex mode via Python

I have an script in Python that prints PDF files.
The script works using win32api.ShellExecute() and everything is fine, but now, I need to print PDF files that have double sided content, user manuals in concrete.
I have tried setting the duplex mode in win32print, but nothing works, the printer still print 2 pages on 2 sheets for my PDF instead of two pages on a double sided sheet. The printer works with this mode in other applications, but with the python script doesn't work well. This is part of the code I used to print:

name = win32print.GetDefaultPrinter()
printdefaults = {"DesiredAccess": win32print.PRINTER_ALL_ACCESS}
handle = win32print.OpenPrinter(name, printdefaults)
level = 2
attributes = win32print.GetPrinter(handle, level)
attributes['pDevMode'].Duplex
attributes['pDevMode'].Duplex = 1
win32print.SetPrinter(handle, level, attributes, 0)
win32print.GetPrinter(handle, level)['pDevMode'].Duplex
win32api.ShellExecute(0,'print','file.pdf','.','/route',0)

Any idea why this doesn't works? Thanks.

Try to run this code:

import win32api
import win32print

name = win32print.GetDefaultPrinter()

#printdefaults = {"DesiredAccess": win32print.PRINTER_ACCESS_ADMINISTER}
printdefaults = {"DesiredAccess": win32print.PRINTER_ACCESS_USE}
handle = win32print.OpenPrinter(name, printdefaults)

level = 2
attributes = win32print.GetPrinter(handle, level)

print "Old Duplex = %d" % attributes['pDevMode'].Duplex

#attributes['pDevMode'].Duplex = 1    # no flip
#attributes['pDevMode'].Duplex = 2    # flip up
attributes['pDevMode'].Duplex = 3    # flip over

## 'SetPrinter' fails because of 'Access is denied.'
## But the attribute 'Duplex' is set correctly
try:
    win32print.SetPrinter(handle, level, attributes, 0)
except:
    print "win32print.SetPrinter: set 'Duplex'"

res = win32api.ShellExecute(0, 'print', 'test.pdf', None, '.', 0)

win32print.ClosePrinter(handle)

It works on my computer: Windows 10, Python 2.7.14, pypiwin32-220

Notes:

  1. On my computer PRINTER_ACCESS_ADMINISTER causes 'Access is denied' in OpenPrinter.
  2. On my computer SetPrinter fails with 'Access is denied'. But 'Duplex' is set correctly..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM