我正在尝试使用 Python 打印 PDF,而不打开 PDF 查看器应用程序(Adobe、Foxit 等)。我还需要知道打印何时完成(以删除文件)。
在这里我找到了这个实现:
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
你可以用我用的这个方法; 但您需要安装两个文件并将它们放在主应用程序的目录中: 幽灵脚本 GSPRINT 该参数是为了提高打印质量,因此如果您愿意,可以更改它们
def print_pdf(self, word_path_org, printer_name):
try:
# Initialize COM
pythoncom.CoInitialize()
# Get the full path of the Word document
word_path = os.path.abspath(word_path_org)
# Get the base name without extension
base_name, _ = os.path.splitext(os.path.basename(word_path_org))
# Construct the full path of the PDF file
pdf_path = os.path.abspath(f"{base_name}.pdf")
self.convert_to_pdf(word_path,pdf_path )
try:
GHOSTSCRIPT_PATH = "GHOSTSCRIPT\\bin\\gswin32.exe"
GSPRINT_PATH = "GSPRINT\\gsprint.exe"
# Check if the PDF file exists
if not os.path.exists(pdf_path):
raise FileNotFoundError(f"PDF file not found: {pdf_path}")
command = f'-ghostscript "{GHOSTSCRIPT_PATH}" -printer "{printer_name}" -color -r600 -dColorDepth=24 -dJPEGQ=95 -dGraphicsAlphaBits=4 -dTextAlphaBits=4 -sOutputICCProfile=sRGB.icc "{pdf_path}"'
win32api.ShellExecute(0, 'open', GSPRINT_PATH, command, '.', 0)
except Exception as e:
print(f"Error during printing: {e}")
finally:
# Uninitialize COM
pythoncom.CoUninitialize()
time.sleep(2)
except Exception as e:
print(f"Error: {e}")