All formats

python-ghostscript

LanguagePython 3.6+
LicenseGPL-3.0-or-later (Ghostscript itself is AGPL-3.0)
Repositorygitlab.com/pdftools/python-ghostscript
DocumentationPyPI page, Ghostscript command-line options
Depends onGhostscript shared library (libgs, gsdll64.dll)
Read / writeyes / 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#

Shell
pip install ghostscript

The Ghostscript library must be installed too:

Shell
# 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#

Python
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#

Python
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:

Python
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#

Python
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#