Ghostscript Python Interface
The `ghostscript` Python library (version 0.8.1) provides both high-level and low-level interfaces to the Ghostscript C-API, leveraging `ctypes`. It allows Python applications to interpret PostScript and PDF files, enabling tasks like conversion, rendering, and manipulation. While its release cadence is infrequent, the project is actively maintained. It is primarily tested on GNU/Linux, and users on other operating systems are encouraged to report compatibility.
Common errors
-
ModuleNotFoundError: No module named 'ghostscript'
cause The Python `ghostscript` package has not been installed in the current environment.fixRun `pip install ghostscript` in your activated Python environment. If using Anaconda, you might also consider `conda install -c conda-forge ghostscript` followed by `pip install ghostscript` to ensure proper linkage to the C library. -
RuntimeError: Can not find Ghostscript library (libgs)
cause The Python `ghostscript` wrapper cannot locate the underlying Ghostscript C library on your system. This often happens if the C library is not installed, or its installation path is not included in the system's PATH environment variable, or if the 32-bit/64-bit architecture mismatch.fix1. Ensure the Ghostscript C library is installed for your OS (e.g., from ghostscript.com). 2. Add the Ghostscript `bin` and `lib` directories to your system's PATH environment variable. 3. On Windows, ensure you've installed the correct 32-bit or 64-bit version of Ghostscript matching your Python installation. 4. You can explicitly set the `GSAPI_LIB` or `GSAPI_LIBDIR` environment variables to point to the Ghostscript shared library. -
subprocess.CalledProcessError: Command '['gs', ...]` or 'No such file or directory: 'gs''
cause This error, often seen when using the Python `subprocess` module to call Ghostscript, indicates that the `gs` executable (or `gswin64c.exe`/`gswin32c.exe` on Windows) is not found in the system's PATH, or the arguments passed to it are incorrect.fix1. Verify that the Ghostscript executable (`gs` or `gswin*c.exe`) is in your system's PATH. 2. Double-check the arguments passed to the Ghostscript command for typos or incorrect syntax. 3. Consider using the `ghostscript` Python package's high-level API directly to abstract away subprocess management. -
Ghostscript error: **** Could not open the file '"/path/to/output.pdf"'.
cause This specific error often arises when the output file path passed to Ghostscript arguments is incorrectly quoted, resulting in Ghostscript trying to open a filename that includes literal quotation marks.fixEnsure that your Python script does not add extra quotes around the output file path when constructing the argument list for Ghostscript. For example, use `'-sOutputFile=' + output_path` instead of `'-sOutputFile="' + output_path + '"'`.
Warnings
- breaking The `Ghostscript()` constructor in version 0.7 and later no longer accepts arbitrary keyword arguments. Only specific, documented arguments like `stdin`, `stdout`, `stderr` are allowed.
- breaking As of `python-ghostscript` version 0.7, support for Python 2.7, 3.4, and 3.5 has been dropped. The minimum required Python version is now 3.6.
- gotcha The Python `ghostscript` package is a wrapper for the external Ghostscript C library. You must install the actual Ghostscript program separately on your system, and its executable/libraries must be discoverable via your system's PATH environment variable (or `GSAPI_LIB`/`GSAPI_LIBDIR` environment variables for direct library path specification).
- gotcha When passing document content or arguments to Ghostscript, especially for `run_string`, ensure that `bytes` objects are used. Passing Python `str` objects may lead to encoding issues or unexpected behavior, particularly for non-ASCII characters, although the high-level interface attempts to handle string encoding.
- gotcha When specifying output file paths in Ghostscript arguments, particularly on Windows, use raw strings (e.g., `r'C:\path\file.pdf'`) or forward slashes (`'C:/path/file.pdf'`) to avoid issues with backslash escape sequences. Additionally, if generating multiple output files (e.g., pages to images), include `%d` in the output filename (e.g., `-sOutputFile=page_%d.png`).
Install
-
pip install ghostscript
Imports
- ghostscript
import ghostscript
- Ghostscript
from ghostscript import Ghostscript
- gsapi
import gsapi
Quickstart
import sys
import locale
import ghostscript
# Example 1: Convert a PostScript file to PDF using the high-level interface
# This assumes 'input.ps' exists and you want 'output.pdf'
# Ensure Ghostscript C library is installed and in PATH.
# For Windows, you might need to specify the GS DLL path via GSAPI_LIB or GSAPI_LIBDIR env var.
# Simulate command-line arguments for Ghostscript
args_ps2pdf = [
"ps2pdf", # actual value doesn't matter for the python wrapper, but typically 'gs'
"-dNOPAUSE",
"-dBATCH",
"-dSAFER",
"-sDEVICE=pdfwrite",
"-sOutputFile=output.pdf",
"-f",
"input.ps"
]
try:
# Ghostscript expects arguments to be byte strings in some contexts
# For the high-level interface, strings are often handled, but explicit encoding can be safer
encoded_args = [arg.encode(locale.getpreferredencoding()) for arg in args_ps2pdf]
ghostscript.Ghostscript(*encoded_args)
print("Converted input.ps to output.pdf")
except ghostscript.GhostscriptError as e:
print(f"Ghostscript error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
# Example 2: Process a string document directly
# Documents passed to ghostscript need to be bytes
doc_content = b"""%!PS
/Helvetica findfont 20 scalefont setfont
50 50 moveto (Hello World from Python) show
showpage quit
"""
args_string_to_pdf = (
"-dNOPAUSE",
"-dBATCH",
"-dSAFER",
"-sDEVICE=pdfwrite",
"-sOutputFile=hello_world.pdf",
"-" # '-' indicates input from stdin
)
try:
with ghostscript.Ghostscript(*args_string_to_pdf) as gs:
gs.run_string(doc_content)
print("Generated hello_world.pdf from string content")
except ghostscript.GhostscriptError as e:
print(f"Ghostscript error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")