Ghostscript Python Interface

0.8.1 · active · verified Thu Apr 16

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

Warnings

Install

Imports

Quickstart

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.

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}")

view raw JSON →