{"id":7259,"library":"ghostscript","title":"Ghostscript Python Interface","description":"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.","status":"active","version":"0.8.1","language":"en","source_language":"en","source_url":"https://gitlab.com/pdftools/python-ghostscript","tags":["pdf","postscript","ctypes","document processing","conversion"],"install":[{"cmd":"pip install ghostscript","lang":"bash","label":"Install from PyPI"}],"dependencies":[{"reason":"The Python library is a wrapper around the Ghostscript C library, which must be installed separately on the system. Version 9.0.8 or higher is generally recommended for recent Python wrapper versions.","package":"Ghostscript (C library)","optional":false},{"reason":"Required for installation, typically handled by pip.","package":"setuptools","optional":true}],"imports":[{"symbol":"ghostscript","correct":"import ghostscript"},{"note":"This is the high-level interface class.","symbol":"Ghostscript","correct":"from ghostscript import Ghostscript"},{"note":"Used for the low-level C-API bindings, often found in the Ghostscript C library's own Python demos.","symbol":"gsapi","correct":"import gsapi"}],"quickstart":{"code":"import sys\nimport locale\nimport ghostscript\n\n# Example 1: Convert a PostScript file to PDF using the high-level interface\n# This assumes 'input.ps' exists and you want 'output.pdf'\n# Ensure Ghostscript C library is installed and in PATH.\n# For Windows, you might need to specify the GS DLL path via GSAPI_LIB or GSAPI_LIBDIR env var.\n\n# Simulate command-line arguments for Ghostscript\nargs_ps2pdf = [\n    \"ps2pdf\", # actual value doesn't matter for the python wrapper, but typically 'gs'\n    \"-dNOPAUSE\",\n    \"-dBATCH\",\n    \"-dSAFER\",\n    \"-sDEVICE=pdfwrite\",\n    \"-sOutputFile=output.pdf\",\n    \"-f\",\n    \"input.ps\"\n]\n\ntry:\n    # Ghostscript expects arguments to be byte strings in some contexts\n    # For the high-level interface, strings are often handled, but explicit encoding can be safer\n    encoded_args = [arg.encode(locale.getpreferredencoding()) for arg in args_ps2pdf]\n    ghostscript.Ghostscript(*encoded_args)\n    print(\"Converted input.ps to output.pdf\")\nexcept ghostscript.GhostscriptError as e:\n    print(f\"Ghostscript error: {e}\")\nexcept Exception as e:\n    print(f\"An unexpected error occurred: {e}\")\n\n# Example 2: Process a string document directly\n# Documents passed to ghostscript need to be bytes\ndoc_content = b\"\"\"%!PS\n/Helvetica findfont 20 scalefont setfont\n50 50 moveto (Hello World from Python) show\nshowpage quit\n\"\"\"\n\nargs_string_to_pdf = (\n    \"-dNOPAUSE\",\n    \"-dBATCH\",\n    \"-dSAFER\",\n    \"-sDEVICE=pdfwrite\",\n    \"-sOutputFile=hello_world.pdf\",\n    \"-\" # '-' indicates input from stdin\n)\n\ntry:\n    with ghostscript.Ghostscript(*args_string_to_pdf) as gs:\n        gs.run_string(doc_content)\n    print(\"Generated hello_world.pdf from string content\")\nexcept ghostscript.GhostscriptError as e:\n    print(f\"Ghostscript error: {e}\")\nexcept Exception as e:\n    print(f\"An unexpected error occurred: {e}\")","lang":"python","description":"This quickstart demonstrates two common uses of the `ghostscript` library: converting an existing PostScript file to PDF, and processing a PostScript string directly into a PDF. It utilizes the high-level `Ghostscript` class to manage the Ghostscript interpreter instance and pass arguments. Note that the Ghostscript C library must be installed and accessible by the Python wrapper for these examples to run."},"warnings":[{"fix":"Review your `Ghostscript()` calls and remove any unrecognised keyword arguments. Pass Ghostscript-specific options as positional arguments in a list, as done in command-line usage.","message":"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.","severity":"breaking","affected_versions":"0.7.x and later"},{"fix":"Upgrade your Python environment to version 3.6 or higher.","message":"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.","severity":"breaking","affected_versions":"0.7.x and later"},{"fix":"Download and install Ghostscript from its official website (ghostscript.com/download.html) for your operating system. Ensure the installation directory's `bin` and `lib` folders are added to your system's PATH, or set `GSAPI_LIB` to the exact path of the Ghostscript shared library or `GSAPI_LIBDIR` to its directory.","message":"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).","severity":"gotcha","affected_versions":"All versions"},{"fix":"Explicitly encode Python strings to bytes using a suitable encoding (e.g., `text.encode('utf-8')` or `locale.getpreferredencoding()`) before passing them to Ghostscript functions that expect binary data.","message":"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.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Always use raw strings or forward slashes for paths. For multi-page output, ensure the output filename contains `%d` to generate sequential files for each page. Avoid double-quoting output file parameters, as this can break Ghostscript processing.","message":"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`).","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Run `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.","cause":"The Python `ghostscript` package has not been installed in the current environment.","error":"ModuleNotFoundError: No module named 'ghostscript'"},{"fix":"1. 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.","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.","error":"RuntimeError: Can not find Ghostscript library (libgs)"},{"fix":"1. 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.","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.","error":"subprocess.CalledProcessError: Command '['gs', ...]` or 'No such file or directory: 'gs''"},{"fix":"Ensure 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 + '\"'`.","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.","error":"Ghostscript error: **** Could not open the file '\"/path/to/output.pdf\"'."}]}