Python中PDF的无声打印
我想用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
2 个回答
0
你可以使用我用的方法;
但是你需要安装两个文件,并把它们放到主应用的目录下:
- GHOSTSCRIPT
- 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}")
21
我建议你安装 GSView 和 GSPrint,然后使用 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 文件了。