Ale*_*dor 12 python printing pdf
我有一个PDF文档,我想用我的python应用程序打印它.
我在这里尝试了解决方案(使用python的win32print模块打印PDF文档?)但是当我安装实际版本的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)
Run Code Online (Sandbox Code Playgroud)
我也看到了这个答案,但他们建议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'使用startfile命令时遇到异常
Ale*_*dor 13
最后,经过几个小时的搜索正确的文件后,我找到了问题的答案.
您可以在这里下载GSPRINT
您可以在这里下载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)
Run Code Online (Sandbox Code Playgroud)
Ghostscript的也可以在官方网页上找到这里
我在这里找到了64位的gsprint.exe
我希望这有帮助.
我知道这是一个老问题,但如果有人在这里寻找它,我是如何修复它的。
我在 Windows 10 64 位上使用 python 3.8 和 gs9.52 以及 python3-ghostscript 库,您可以使用它进行安装pip install python3-ghostscript我还使用 pypiwin32 来获取默认打印机名称,您可以使用 pip 安装它pip install pypiwin32
这是工作脚本
import tempfile
import win32print
import locale
import ghostscript
import render_to_pdf
pdf = render_to_pdf('print/slip.html', context)
temp1 = tempfile.mktemp('.pdf')
f1 = open(temp1, 'ab')
f1.write(pdf)
f1.close()
args = [
"-dPrinted", "-dBATCH", "-dNOSAFER", "-dNOPAUSE", "-dNOPROMPT"
"-q",
"-dNumCopies#1",
"-sDEVICE#mswinpr2",
f'-sOutputFile#"%printer%{win32print.GetDefaultPrinter()}"',
f'"{temp1}"'
]
encoding = locale.getpreferredencoding()
args = [a.encode(encoding) for a in args]
ghostscript.Ghostscript(*args)
Run Code Online (Sandbox Code Playgroud)
这里需要注意的事情很少,我使用“#”而不是“=”,因为由于某种原因它不能与“=”一起使用。
如果这对您不起作用,请尝试将 -sDEVICE 开关更改为您的打印机类型,例如,当我使用HP LaserJet时,它会给我提示,因此我将 -sDEVICE 更改为 Laserjet 并且它起作用了,您可以通过运行获取设备列表gs -h在终端