14

I'm trying to print a PDF with Python, without opening the PDF viewer application (Adobe, Foxit etc.). I need also to know when printing has finished (to delete the file).

Here I found this implementation:

import win32ui, dde, os.path, time
from win32api import FindExecutable
from os import spawnl, P_NOWAIT
...
pd = "C:\\temp\\test.pdf"
pdbits = os.path.split(pd)
readerexe = FindExecutable(pdbits[1],pdbits[0])

spawnl(P_NOWAIT,readerexe[1],"DUMMY") #I added "DUMMY" to avoid a weird error

time.sleep(2)

s = dde.CreateServer()
s.Create('')
c = dde.CreateConversation(s)
c.ConnectTo('acroview', 'control')

c.Exec('[FilePrintSilent("%s")]' % (pd,))

s.Destroy()

But it throws this exception at the ConnectTo line:

dde.error: ConnectTo failed

Someone knows how to solve it? Or has a different solution for silent printing? Or at list can give a link to a reference for ConnectTo? Could find nothing on the web about it.

Working with: Python 2.7, Windows 7, Acrobat Reader 10.0

bluish
  • 26,356
  • 27
  • 122
  • 180

1 Answers1

21

I suggest you install GSView and GSPrint and shell out to gsprint.exe to print the pdf.

p = subprocess.Popen([r"p:\ath\to\gsprint.exe", "test.pdf"], 
                     stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
print stdout
print stderr

I have used this in a industrial label printing solution, works great.

When the gsprint.exe program exits (i.e. after the call to communicate), you can delete the pdf file.

codeape
  • 97,830
  • 24
  • 159
  • 188
  • 1
    GREAT!! I solved this issue that tormented me during days. I add that it's required to install both GhostScript ("back-end", downloadable from http://pages.cs.wisc.edu/~ghost/) and GSView ("front-end", which includes GSView and GSPrint, downloadable from codeape's first link) – bluish Dec 21 '10 at 13:54
  • 1
    Yes - the Ghostscript toolchain is the way to go here. It is worth noting that almost all printing solutions for Linux and other Unixes nowadays use GS programas one way or another. – jsbueno Dec 21 '10 at 13:54
  • Thank for this. I printed my txt file with esc sequences into pcl made printer, converted it to pdf and printed silently with ghostscript to a non-PCL printer :) – Hrvoje T Jun 19 '17 at 13:10
  • Shall I use gsprint in a commerical software? – Jisson Oct 04 '19 at 11:51
  • what is the solution to print microsoft's DOC/DOCX silently? – oyster Jan 19 '21 at 03:43
  • and how to set print on the both sides of paper without setting this as the default for printer – oyster Jan 19 '21 at 03:45
  • Options to gsprint.exe are documented in gsprint.html inside the installed files. The options for both side printing are `-duplex_vertical` and `-duplex_horizontal` I believe. – codeape Jan 19 '21 at 12:36
  • As for doc/docx I guess there is no simple solution. – codeape Jan 19 '21 at 12:38