python-ghostscript
| Language | Python 3.6+ |
|---|---|
| License | GPL-3.0-or-later (Ghostscript itself is AGPL-3.0) |
| Repository | gitlab.com/pdftools/python-ghostscript |
| Documentation | PyPI page, Ghostscript command-line options |
| Depends on | Ghostscript shared library (libgs, gsdll64.dll) |
| Read / write | yes / yes (anything Ghostscript does) |
The ghostscript package loads the Ghostscript shared library with ctypes and runs it inside the Python process. The high-level ghostscript.Ghostscript(*args) takes the same arguments as the gs command line. There’s also a low-level module, ghostscript._gsprint, with the raw gsapi_* functions.
It’s a thin binding: you choose the work with Ghostscript devices and switches (pdfwrite, png16m, txtwrite, bbox). The author tests it on Linux; on Windows it finds gsdll64.dll from the Ghostscript installation. If you don’t need in-process calls, running gs with subprocess does the same.
Installation#
pip install ghostscript
The Ghostscript library must be installed too:
# Debian / Ubuntu
sudo apt install libgs10 # or ghostscript
# macOS
brew install ghostscript
On Windows install Ghostscript from ghostscript.com with the same bitness as Python.
Basic usage: convert PostScript to PDF#
import ghostscript
args = [
"ps2pdf", # argv[0], ignored
"-dNOPAUSE", "-dBATCH", "-dSAFER", "-dQUIET",
"-sDEVICE=pdfwrite",
"-sOutputFile=out.pdf",
"-f", "in.ps",
]
try:
ghostscript.Ghostscript(*args)
except ghostscript.GhostscriptError as e:
print("conversion failed:", e)
How to render PostScript pages to PNG#
import ghostscript
ghostscript.Ghostscript(
"gs", "-dNOPAUSE", "-dBATCH", "-dSAFER", "-dQUIET",
"-sDEVICE=png16m", "-r150",
"-dTextAlphaBits=4", "-dGraphicsAlphaBits=4",
"-sOutputFile=page-%03d.png",
"-f", "in.ps",
)
%03d becomes the page number. Use pngalpha for a transparent background or pnggray for grayscale.
How to run PostScript code from a string#
Documents passed to run_string must be bytes:
import ghostscript
doc = b"""%!
/Helvetica findfont 24 scalefont setfont
72 720 moveto (Hello, PostScript) show
showpage
"""
args = ["gs", "-dNOPAUSE", "-dBATCH", "-dSAFER",
"-sDEVICE=pdfwrite", "-sOutputFile=hello.pdf"]
with ghostscript.Ghostscript(*args) as gs:
gs.run_string(doc)
How to extract text from a PostScript file#
import ghostscript
ghostscript.Ghostscript(
"gs", "-dNOPAUSE", "-dBATCH", "-dSAFER", "-dQUIET",
"-sDEVICE=txtwrite", "-sOutputFile=out.txt",
"-f", "in.ps",
)
print(open("out.txt", encoding="utf-8").read())
Tips#
- Pass
-dFirstPage=N -dLastPage=Mto process only some pages. - Ghostscript keeps global state per process. Run one conversion at a time per process, or use
multiprocessingfor parallel jobs. - Keep
-dSAFER(the default since Ghostscript 9.50) for files from other people.