How to use Ghostscript

Table of contents

For other information, see the Ghostscript overview and, if necessary, how to install Ghostscript.


Invoking Ghostscript

This document describes how to use the command line Ghostscript client. Ghostscript is also used as a general engine inside other applications (for viewing files for example). Please refer to the documentation for those applications for using Ghostscript in other contexts.

The command line to invoke Ghostscript is essentially the same on all systems, although the name of the executable program itself may differ among systems. For instance, to invoke Ghostscript on unix-like systems type:

gs [options] {filename 1} ... [options] {filename N} ...

Here are some basic examples. The details of how these work are described below.

To view a file:

gs -dSAFER -dBATCH document.pdf
You'll be prompted to press return between pages.

To convert a figure to an image file:

gs -dSAFER -dBATCH -dNOPAUSE -sDEVICE=png16m -dGraphicsAlphaBits=4 \
    -sOutputFile=tiger.png tiger.eps

To render the same image at 300 dpi:

gs -dSAFER -dBATCH -dNOPAUSE -sDEVICE=png16m -r300 \
                -sOutputFile=tiger_300.png tiger.eps

To render a figure in grayscale:

gs -dSAFER -dBATCH -dNOPAUSE -sDEVICE=pnggray -sOutputFile=figure.png figure.pdf

To rasterize a whole document:

gs -dSAFER -dBATCH -dNOPAUSE -sDEVICE=pgmraw -r150 \
                -dTextAlphaBits=4 -sOutputFile='paper-%00d.pgm' paper.ps

There are also a number of utility scripts for common to convert a PostScript document to PDF:

ps2pdf file.ps
The output is saved as file.pdf.

There are other utility scripts besides ps2pdf, including pdf2ps, ps2epsi, pdf2dsc, ps2ascii, ps2ps and ps2ps2. These just call Ghostscript with the appropriate (if complicated) set of options. You can use the 'ps2' set with eps files.

Ghostscript is capable of interpreting PostScript, encapsulated PostScript (EPS), DOS EPS (EPSF), and Adobe Portable Document Format (PDF). The interpreter reads and executes the files in sequence, using the method described under "File searching" to find them.

The interpreter runs in interactive mode by default. After processing the files given on the command line (if any) it reads further lines of PostScript language commands from the primary input stream, normally the keyboard, interpreting each line separately. To quit the interpreter, type "quit". The -dBATCH -dNOPAUSE options in the examples above disable the interactive prompting. The interpreter also quits gracefully if it encounters end-of-file or control-C.

The interpreter recognizes many options. An option may appear anywhere in the command line, and applies to all files named after it on the line. Many of them include "=" followed by a parameter. The most important are described in detail here. Please see the reference sections on options and devices for a more complete listing.

Help at the command line: gs -h

You can get a brief help message by invoking Ghostscript with the -h or -? switch, like this:

gs -h
gs -?

The message shows for that version of the Ghostscript executable:

On other systems the executable may have a different name:

System    invocation name
Unix  gs
VMS  gs
MS Windows 95 and later  gswin32c
OS/2  gsos2

Selecting an output device

Ghostscript has a notion of 'output devices' which handle saving or displaying the results in a particular format. Ghostscript comes with a diverse variety of such devices supporting vector and raster file output, screen display, driving various printers and communicating with other applications.

The command line option '-sDEVICE=device' selects which output device Ghostscript should use. If this option isn't given the default device (usually a display device) is used. Ghostscript's built-in help message (gs -h) lists the available output devices. For complete description of the devices distributed with Ghostscript and their options, please see the devices section of the documentation.

Note that this switch must precede the name of the first input file, and only its first use has any effect. For example, for printer output in a configuration that includes an Epson printer driver, instead of just 'gs myfile.ps' you might use

gs -sDEVICE=epson myfile.ps

The output device can also be set through the GS_DEVICE environment variable.

Once you invoke Ghostscript you can also find out what devices are available by typing 'devicenames ==' at the interactive prompt. You can set the output device and process a file from the interactive prompt as well:

(epson) selectdevice
(myfile.ps) run
All output then goes to the Epson printer instead of the display until you do something to change devices. You can switch devices at any time by using the selectdevice procedure, for instance like one of these:
(x11alpha) selectdevice
(epson) selectdevice

Output resolution

Some printers can print at several different resolutions, letting you balance resolution against printing speed. To select the resolution on such a printer, use the -r switch:

gs -sDEVICE=printer -rXRESxYRES
where XRES and YRES are the requested number of dots (or pixels) per inch. Where the two resolutions are same, as is the common case, you can simply use -rres.

The -r option is also useful for controlling the density of pixels when rasterizing to an image file. It is used this way in the examples at the beginning of this document.

Output to files

Ghostscript also allows you to control where it sends its output. With a display device this isn't necessary as the device handles presenting the output on screen internally. Some specialized printer drivers operate this way as well, but most devices are general and need to be directed to a particular file or printer.

To send the output to a file, use the -sOutputFile= switch or the -o switch (below). For instance, to direct all output into the file ABC.xyz, use

gs -sOutputFile=ABC.xyz

When printing on MS Windows systems, output normally goes directly to the printer, PRN. On Unix and VMS systems it normally goes to a temporary file which is sent to the printer in a separate step. When using Ghostscript as a file rasterizer (converting PostScript or PDF to a raster image format) you will of course want to specify an appropriately named file for the output.

Ghostscript also accepts the special filename '-' which indicates the output should be written to standard output (the command shell).

Be aware that filenames beginning with the character % have a special meaning in PostScript. If you need to specify a file name that actually begins with %, you must prepend the %os% filedevice explicitly. For example to output to a file named %abc, you need to specify

gs -sOutputFile=%os%%abc
Please see Ghostscript and the PostScript Language and the PostScript Language Reference Manual for more details on % and filedevices.

Note that on MS Windows systems, the % character also has a special meaning for the command processor (shell), so you will have to double it.

gs -sOutputFile=%%os%%%%abc (on MS Windows)

Note, some devices (e.g. pdfwrite, ps2write, ...) only write the output file upon exit, but changing the OutputFile device parameter will cause these devices to emit the pages received up to that point and then open the new file name given by OutputFile.

For example, in order to create two PDF files from a single invocation of ghostscript the following can be used:

gs -sDEVICE=pdfwrite -o tiger.pdf examples/tiger.eps -c "<< /OutputFile (colorcir.pdf) >> setpagedevice" -f examples/colorcir.ps

One page per file

Specifying a single output file works fine for printing and rasterizing figures, but sometimes you want images of each page of a multi-page document. You can tell Ghostscript to put each page of output in a series of similarly named files. To do this place a template '%d' in the filename which Ghostscript will replace with the page number.

Note: Since the % character is used to precede the page number format specification, in order to represent a file name that contains a %, double % characters must be used. For example for the file my%foo the OutputFile string needs to be my%%foo.

The format can in fact be more involved than a simple '%d'. The format specifier is of a form similar to the C printf format. The general form supported is:

            %[flags][width][.precision][l]type

    where:  flags    is one of:  #+-
            type     is one of:  diuoxX
For more information, please refer to documentation on the C printf format specifications. Some examples are:
-sOutputFile=ABC-%d.png
produces 'ABC-1.png', ... , 'ABC-10.png', ...

-sOutputFile=ABC-%03d.pgm
produces 'ABC-001.pgm', ... , 'ABC-010.pgm', ...

-sOutputFile=ABC_p%04d.tiff
produces 'ABC_p0001.tiff', ... , 'ABC_p0510.tiff', ... , 'ABC_p5238.tiff'

Note, however that the one page per file feature may not supported by all devices. Also, since some devices write output files when opened, there may be an extra blank page written (pdfwrite, ps2write, pswrite, pxlmono, pxlcolor, ...).

As noted above, when using MS Windows console (command.com or cmd.exe), you will have to double the % character since the % is used by that shell to prefix variables for substitution, e.g.,

gswin32c -sOutputFile=ABC%%03d.xyz

-o option:

As a convenient shorthand you can use the -o option followed by the output file specification as discussed above. The -o option also sets the -dBATCH and -dNOPAUSE options. This is intended to be a quick way to invoke ghostscript to convert one or more input files. For instance, to convert somefile.ps to JPEG image files, one per page, use:

gs -sDEVICE=jpeg -o out-%d.jpg somefile.ps
is equivalent to:
gs -sDEVICE=jpeg -sOutputFile=out-%d.jpg -dBATCH -dNOPAUSE somefile.ps

Choosing paper size

Ghostscript is distributed configured to use U.S. letter paper as its default page size. There are two ways to select other paper sizes from the command line:

Individual documents can (and often do) specify a paper size, which takes precedence over the default size. To force a specific paper size and ignore the paper size specified in the document, select a paper size as just described, and also include the -dFIXEDMEDIA switch on the command line.

The default set of paper sizes will be included in the currentpagedevice in the InputAttributes dictionary with each paper size as one of the entries. The last entry in the dictionary (which has numeric keys) is a non-standard (Ghostscript extension) type of PageSize where the array has four elements rather than the standard two elements. This four element array represents a page size range where the first two elements are the lower bound of the range and the second two are the upper bound. By default these are [0, 0] for the lower bound and [16#fffff, 16#fffff] for the upper bound.
The range type of PageSize is intended to allow flexible page size sepcification for non-printer file formats such as JPEG, PNG, TIFF, EPS, ...
For actual printers, either the entire InputAttributes dictionary should be replaced or the range type entry should not be included. To simplify using the default page sizes in the InputAttributes dictionary, the command line option -dNORANGEPAGESIZE can be used. Using this option will result in automatic rotation of the document page if the requested page size matches one of the default page sizes.

Changing the installed default paper size

You can change the installed default paper size on an installed version of Ghostscript, by editing the initialization file gs_init.ps. This file is usually in the Resource/Init directory somewhere in the search path. See the section on finding files for details.

Find the line

% /DEFAULTPAPERSIZE (a4) def

Then to make A4 the default paper size, uncomment the line to change this to

/DEFAULTPAPERSIZE (a4) def

For a4 you can substitute any paper size Ghostscript knows.

This supecedes the previous method of uncommenting the line % (a4) ....

Sometimes the initialization files are compiled into Ghostscript and cannot be changed.

On Windows and some Linux builds, the default paper size will be selected to be a4 or letter depending on the locale.

Interacting with pipes

As noted above, input files are normally specified on the command line. However, one can also "pipe" input into Ghostscript from another program by using the special file name '-' which is interpreted as standard input. Examples:

{some program producing ps} | gs [options] -
zcat paper.ps.gz | gs -

When Ghostscript finishes reading from the pipe, it quits rather than going into interactive mode. Because of this, options and files after the '-' in the command line will be ignored.

On Unix and MS Windows systems you can send output to a pipe in the same way. For example, to pipe the output to lpr, use the command

gs -q -sOutputFile=- | lpr

In this case you must also use the -q switch to prevent Ghostscript from writing messages to standard output which become mixed with the intended output stream.

Also, using the -sstdout=%stderr option is useful, particularly with input from PostScript files that may print to stdout.

Similar results can be obtained with the %stdout and %pipe% filedevices. The example above would become

gs -sOutputFile=%stdout -q | lpr
or
gs -sOutputFile=%pipe%lpr
(again, doubling the % character on MS Windows systems.)

In the last case, -q isn't necessary since Ghostscript handles the pipe itself and messages sent to stdout will be printed as normal.

Using Ghostscript with PDF files

Ghostscript is normally built to interpret both PostScript and PDF files, examining each file to determine automatically whether its contents are PDF or PostScript. All the normal switches and procedures for interpreting PostScript files also apply to PDF files, with a few exceptions. In addition, the pdf2ps utility uses Ghostscript to convert PDF to (Level 2) PostScript.

Switches for PDF files

Here are some command line options specific to PDF

-dFirstPage=pagenumber
Begins interpreting on the designated page of the document.
-dLastPage=pagenumber
Stops interpreting after the designated page of the document.
-dPDFFitPage
Rather than selecting a PageSize given by the PDF MediaBox, TrimBox (see -dUseTrimBox), or CropBox (see -dUseCropBox), the PDF file will be scaled to fit the current device page size (usually the default page size).

This is useful to avoid clipping information on a PDF document when sending to a printer that may have unprintable areas at the edge of the media larger than allowed for in the document.

This is also useful for creating fixed size images of PDF files that may have a variety of page sizes, for example thumbnail images.

-dPrinted
-dPrinted=false
Determines whether the file should be displayed or printed using the "screen" or "printer" options for annotations and images. With -dPrinted, the output will use the file's "print" options; with -dPrinted=false, the output will use the file's "screen" options. If neither of these is specified, the output will use the screen options for any output device that doesn't have an OutputFile parameter, and the printer options for devices that do have this parameter.
-dUseCropBox
Sets the page size to the CropBox rather than the MediaBox. Some files have a CropBox that is smaller than the MediaBox and may include white space, registration or cutting marks outside the CropBox. Using this option will set the page size appropriately for a viewer.
-dUseTrimBox
Sets the page size to the TrimBox rather than the MediaBox. The trim box defines the intended dimensions of the finished page after trimming. Some files have a TrimBox that is smaller than the MediaBox and may include white space, registration or cutting marks outside the CropBox. Using this option simulates appearance of the finished printed page.
-sPDFPassword=password
Sets the user or owner password to be used in decoding encrypted PDF files. For files created with encryption method 4 or earlier, the password is an arbitrary string of bytes; with encryption method 5 or later, it should be text in either UTF-8 or your locale's character set (Ghostscript tries both).
-dShowAnnots=false
Don't enumerate anntoations associated with the page objects through Annots attribute. Annotations are shown by default.
-dShowAcroForm
Show annotations referred from the Interactive Form Dictionary (AcroForm dictionary). By default, AcroForm is not enumerated because Adobe Acrobat doesn't do this. This option may be useful for debugging or recovery of incorrect PDF files that don't associate all annotations with the page objects.
-dNoUserUnit
Ignore UserUnit parameter. This may be useful for backward compatibility with old versions of Ghostscript and Adobe Acrobat, or for processing files with large values of UserUnit that otherwise exceed implementation limits.
-dRENDERTTNOTDEF
If a glyph is not present in a font the normal behaviour is to use the /.notdef glyph instead. On TrueType fonts, this is often a hollow sqaure. Under some conditions Acrobat does not do this, instead leaving a gap equivalent to the width of the missing glyph, or the width of the /.notdef glyph if no /Widths array is present. Ghostscript now attempts to mimic this undocumented feature using a user parameter RenderTTNotdef. The PDF interpreter sets this user parameter to the value of RENDERTTNOTDEF in systemdict, when rendering PDF files. To restore rendering of /.notdef glyphs from TrueType fonts in PDF files, set this parameter to true.

Problems interpreting a PDF file

Occasionally you may try to read or print a 'PDF' file that Ghostscript doesn't recognize as PDF, even though the same file can be opened and interpreted by an Adobe Acrobat viewer. In many cases, this is because of incorrectly generated PDF. Acrobat tends to be very forgiving of invalid PDF files. Ghostscript tends to expect files to conform to the standard. For example, even though valid PDF files must begin with %PDF, Acrobat will scan the first 1000 bytes or so for this string, and ignore any preceding garbage.

In the past, Ghostscript's policy has been to simply fail with an error message when confronted with these files. This policy has, no doubt, encouraged PDF generators to be more careful. However, we now recognize that this behavior is not very friendly for people who just want to use Ghostscript to view or print PDF files. Our new policy is to try to render broken PDF's, and also to print a warning, so that Ghostscript is still useful as a sanity-check for invalid files.

PDF files from standard input

The PDF language, unlike the PostScript language, inherently requires random access to the file. If you provide PDF to standard input using the special filename '-', Ghostscript will copy it to a temporary file before interpreting the PDF.

Using Ghostscript with EPS files

Encapsulated PostScript (EPS) files are intended to be incorporated in other PostScript documents and may not display or print on their own. An EPS file must conform to the Document Structuring Conventions, must include a %%BoundingBox line to indicate the rectangle in which it will draw, must not use PostScript commands which will interfere with the document importing the EPS, and can have either zero pages or one page. Ghostscript has support for handling EPS files, but requires that the %%BoundingBox be in the header, not the trailer. To customize EPS handling, see EPS parameters.

For the official description of the EPS file format, please refer to the Adobe documentation in their tech note #5002. It is available from: http://partners.adobe.com/public/developer/ps/index_specs.html

Using Ghostscript with overprinting and spot colors

In general with PostScript and PDF interpreters, the handling of overprinting and spot colors depends upon the process color model of the output device. Devices that produce gray or RGB output have an additive process color model. Devices which produce CMYK output have a subtractive process color model. Devices may, or may not, have support for spot colors.

Note: The differences in appearance of files with overprinting and spot colors caused by the differences in the color model of the output device are part of the PostScript and PDF specifications. They are not due to a limitation in the implementation of Ghostscript or its output devices.

With devices which use a subtractive process color model, both PostScript and PDF allow the drawing of objects using colorants (inks) for one or more planes without affecting the data for the remaining colorants. Thus the inks for one object may overprint the inks for another object. In some cases this produces a transparency like effect. (The effects of overprinting should not be confused with the PDF 1.4 blending operations which are supported for all output devices.) Overprinting is not allowed for devices with an additive process color model. With files that use overprinting, the appearance of the resulting image can differ between devices which produce RGB output versus devices which produce CMYK output. Ghostscript automatically overprints (if needed) when the output device uses a subtractive process color model. For example, if the file is using overprinting, differences can be seen in the appearance of the output from the tiff24nc and tiff32nc devices which use an RGB and a CMYK process color models.

Most of the Ghostscript output devices do not have file formats which support spot colors. Instead spot colors are converted using the tint transform function contained within the color space definition.. However there are several devices which have support for spot colors. The PSD format (Adobe Photoshop) produced by the psdcmyk device contains both the raster data plus an equivalent CMYK color for each spot color. This allows Photoshop to simulate the appearance of the spot colors. The display device (MS Windows, OS/2, gtk+) can be used with different color models: Gray, RGB, CMYK only, or CMYK plus spot colors (separation). The display device, when using its CMYK plus spot color (separation) mode, also uses an equivalent CMYK color to simulate the appearance of the spot color. The tiffsep device creates output files for each separation (CMYK and any spot colors present). It also creates a composite CMYK file using an equivalent CMYK color to simulate the appearance of spot colors. The xcfcmyk device creates output files with spot colors placed in separate alpha channels. (The XCF file format does not currently directly support spot colors.)

Overprinting with spot colors is not allowed if the tint transform function is being used to convert spot colors. Thus if spot colors are used with overprinting, then the appearance of the result can differ between output devices. One result would be obtained with a CMYK only device and another would be obtained with a CMYK plus spot color device. In a worst case situation where a file has overprinting with both process (CMYK) and spot colors, it is possible to get three different appearances for the same input file using the tiff24nc (RGB), tiff32nc (CMYK), and tiffsep (CMYK plus spot colors) devices.

In Adobe Acrobat, viewing of the effects of overprinting is enabled by the 'Overprint Preview' item in the 'Advanced' menu. This feature is not available in the free Acrobat Reader. The free Acrobat Reader also uses the tint transform functions to convert spot colors to the appropriate alternate color space.

How Ghostscript finds files

When looking for initialization files (gs_*.ps, pdf_*.ps), font files, the Fontmap file, files named on the command line, and resource files, Ghostscript first tests whether the file name specifies an absolute path.


Testing a file name for an absolute path
System    Does the name ...

Unix   Begin with / ?
MS Windows   Have : as its second character, or begin with /, \, or //servername/share/ ?
VMS   Contain a node, device, or root specification?

If the test succeeds, Ghostscript tries to open the file using the name given. Otherwise it tries directories in this order:

  1. The current directory if enabled by the -P switch;
  2. The directories specified by -I switches in the command line, if any;
  3. The directories specified by the GS_LIB environment variable, if any;
  4. If built with COMPILE_INITS=1 (currently the default build) the files in the %rom%Resource/Init/ and %rom%lib/ file system built into the executable ;
  5. The directories specified by the GS_LIB_DEFAULT macro (if any) in the makefile when this executable was built.

GS_LIB_DEFAULT, GS_LIB, and the -I parameter may specify either a single directory or a list of directories separated by a character appropriate for the operating system (":" on Unix systems, "," on VMS systems, and ";" on MS Windows systems). By default, Ghostscript no longer searches the current directory first but provides -P switch for a degree of backward compatibility.

Note that Ghostscript does not use this file searching algorithm for the run or file operators: for these operators, it simply opens the file with the name given. To run a file using the searching algorithm, use runlibfile instead of run.

Finding PostScript Level 2 resources

Adobe specifies that resources are installed in a single directory. Ghostscript instead maintains a list of resource directories, and uses an extended method for finding resource files.

The search for a resource file depends on whether the value of the system parameter GenericResourceDir specifies an absolute path. The user may set it as explained in Resource-related parameters.

If the user doesn't set the system parameter GenericResourceDir, or use the -sGenericResourceDir= command line option, Ghostscript creates a default value for it by looking on the directory paths explained in How Ghostscript finds files, excluding the current directory. The first path with Resource in it is used, including any prefix up to the path separator character following the string Resource. For example, when COMPILE_INITS=1 (the current default build), if the first path is %rom%Resource/Init/, then the GenericResourceDir systemparam will be set to %rom%Resource/ by default.

If the value of the system parameter GenericResourceDir is an absolute path (the default), Ghostscript assumes a single resource directory. It concatenates :

  1. The value of the system parameter GenericResourceDir;
  2. The name of the resource category (for instance, CMap);
  3. The name of the resource instance (for instance, Identity-H).

If the value of the system parameter GenericResourceDir is not an absolute path, Ghostscript assumes multiple resource directories. In this case it concatenates :

  1. A directory listed in the section How Ghostscript finds files, except the current directory;
  2. The value of the system parameter GenericResourceDir;
  3. The name of the resource category (for instance, CMap);
  4. T