Python静默打印PDF到特定prin

2024-09-28 22:25:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个PDF文档,我想用python应用程序打印出来。

我已经在here (Print PDF document with python's win32print module?)中尝试过解决方案,但是当我安装Ghostscript 9.15(实际版本)时,它没有gsprint.exe

我使用它的方式是使用命令os.startfile('PDFfile.pdf', "print"),但它打开默认查看器(我的是Adobe Reader),打印后它仍然打开,试图用os.system("TASKKILL /F /IM AcroRD32.exe")终止进程会杀死其他打开的窗口,我不需要它。

使用下一个命令,它也可以打印,但它也可以让Adobe Reader打开

currentprinter = win32print.GetDefaultPrinter()
win32api.ShellExecute(0, "print", 'PDFfile.pdf', '/d:"%s"' % currentprinter, ".", 0)

我也见过this answer,但他们建议再次使用gsprint.exe

有人有gsprint.exe文件或其他解决方案吗?。

注意:当我使用另一个默认程序打开诸如Chrome或Windows Reader之类的PDF文件时,在使用'(31, 'ShellExecute', 'A device attached to the system is not functioning.')'[Error 1155] No application is associated with the specified file for this operation: 'PDFfile.pdf'命令执行上面的命令时,总会出现异常


Tags: 命令pdfoswith解决方案exesystemreader
3条回答

经过数小时的查找,我终于找到了我的问题的答案。

您可以在HERE中下载GSPRINT

您可以在HERE中下载Ghostscript GPL

使用PC(Windows)中提取的文件,您可以使用此命令打印PDF

GHOSTSCRIPT_PATH = "C:\\path\\to\\GHOSTSCRIPT\\bin\\gswin32.exe"
GSPRINT_PATH = "C:\\path\\to\\GSPRINT\\gsprint.exe"

# YOU CAN PUT HERE THE NAME OF YOUR SPECIFIC PRINTER INSTEAD OF DEFAULT
currentprinter = win32print.GetDefaultPrinter()

win32api.ShellExecute(0, 'open', GSPRINT_PATH, '-ghostscript "'+GHOSTSCRIPT_PATH+'" -printer "'+currentprinter+'" "PDFFile.pdf"', '.', 0)

鬼脚本也可以在官方页面HERE中找到

我找到了64位的gsprint.exe HERE

我希望这能有帮助。

如果要打印特定页和某些其他参数,应在gsprint的参数中指定它们,如下所示:

import win32print
import win32api

GHOSTSCRIPT_PATH = "C:\\path\\to\\GHOSTSCRIPT\\bin\\gswin32.exe"
GSPRINT_PATH = "C:\\path\\to\\GSPRINT\\gsprint.exe"

params = '-ghostscript "'+ GHOSTSCRIPT_PATH  +'" -printer "'+currentprinter+'" -from 1 -to 3 -landscape -copies 1 "1.pdf "'
print(params)

win32api.ShellExecute(0, 'open', GSPRINT_PATH, params, '.',0)

这里有一种方法可以在与python脚本相同的目录中无需gsprint也无需win32api就可以无提示地打印pdf。它允许更多的鬼脚本定制,如选择宽度/高度等

import os
import subprocess
import sys

if sys.platform == 'win32':
    args = '"C:\\\\Program Files\\\\gs\\\\gs9.23\\\\bin\\\\gswin64c" ' \
           '-sDEVICE=mswinpr2 ' \
           '-dBATCH ' \
           '-dNOPAUSE ' \
           '-dFitPage ' \
           '-sOutputFile="%printer%myPrinterName" '
    ghostscript = args + os.path.join(os.getcwd(), 'myFile.pdf').replace('\\', '\\\\')
    subprocess.call(ghostscript, shell=True)

如果您使用的是32位版本的GhostScript,那么您将使用gswin32c

相关问题 更多 >