2010-12-21 48 views
11

我試圖用Python打印PDF,無需打開PDF查看器應用程序(Adobe,Foxit等)。我還需要知道何時完成打印(刪除文件)。在Python中靜默打印PDF

Here我發現這個實現

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() 

但它在ConnectTo行拋出此異常:

dde.error: ConnectTo failed 

有人知道如何解決呢?或者有一個不同的解決方案用於無聲打印?或在列表中可以鏈接到一個參考ConnectTo?在網上找不到任何關於它的信息。

與合作:Python 2.7版,Windows 7中,使用Acrobat Reader 10.0

回答

17

我建議你安裝GSViewGSPrint並掏出來gsprint.exe打印的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 

我已經在一個工業標籤打印解決方案中使用過,效果很好。

gsprint.exe程序退出時(即在撥打communicate後),您可以刪除pdf文件。

+1

GREAT !!我解決了這個在幾天內折磨我的問題。我補充說,它需要安裝GhostScript(「後端」,可從http://pages.cs.wisc.edu/~ghost/下載)和GSView(「前端」,包括GSView和GSPrint,可下載從codeape的第一個鏈接) – bluish 2010-12-21 13:54:41

+1

是的 - Ghostscript工具鏈是去這裏的方式。值得注意的是,現在幾乎所有Linux和其他Unix的打印解決方案都以某種方式使用GS程序。 – jsbueno 2010-12-21 13:54:47

+0

謝謝。我用esc序列將我的txt文件打印到pcl製作的打印機中,將其轉換爲pdf並用ghostscript無聲打印到非PCL打印機:) – 2017-06-19 13:10:04