Linux Commands Examples

A great documentation place for Linux commands

ghostscript

Ghostscript (PostScript and PDF language interpreter and previewer)

Synopsis

gs [ options ] [ files ] ... (Unix, VMS)
gswin32c
[ options ] [ files ] ... (MS Windows)
gswin32
[ options ] [ files ] ... (MS Windows 3.1)
gsos2
[ options ] [ files ] ... (OS/2)


add an example, a script, a trick and tips

: email address (won't be displayed)
: name

Step 2

Thanks for this example ! - It will be moderated and published shortly.

Feel free to post other examples
Oops ! There is a tiny cockup. A damn 404 cockup. Please contact the loosy team who maintains and develops this wonderful site by clicking in the mighty feedback button on the side of the page. Say what happened. Thanks!

examples

0
source
            
ensure_ghostscript () {
if ! brewed "ghostscript" ; then
echo "Unable to Ghostscript, installing .."
g_exec "InstallGhostscript", "brew install ghostscript"
echo " DONE"
fi
}
0
source
            
/usr/bin/ghostscript -dTextAlphaBits=4 -dGraphicsAlphaBits=4 $*
0
source

Linux-based tool to chop PDFs into multiple pages

So, after a lot more searching (it seems that "PDF cut pages" is a far better search), I found a little script called unpnup which uses poster, PDF/PS conversion, and pdftk to do exactly what I need. It's a bit of a long way around, but it's far superior to the other methods I found (such as using imagemagick) because it doesn't rasterise the pages before spitting them out.

Just in case mobileread goes away for some reason, the core of the script (licenced under the GPLv2 or later by Harald Hackenberg <hackenberggmx.at>) is as follows:

pdftk "$1" burst
for file in pg*.pdf;
do
    pdftops -eps $file
    poster -v -pA4 -mA5 -c0% `basename $file .pdf`.eps > `basename $file .pdf`.tps
    epstopdf `basename $file .pdf`.tps
done
pdftk pg*.pdf cat output ../`basename $1 .pdf`_unpnuped.pdf
0
source

Using Ghostscript to convert multi-page PDF into single JPG?

Yes, you'll have to convert each PDF page into a single JPG file (Ghostscript can do that).

Then stitch together the resulting JPG files using another program (ImageMagick or GraphicsMagic can do that using their montage sub-commands).

I'm not aware of any software which can do that in one go.

PDF-to-JPG conversion (with Ghostscript): You'll want to make sure that you get the best possible result. So make sure you tweak the commandline options so they work for you. I'd start with this:

gswin32c.exe ^
    -dBATCH ^
    -dNOPAUSE ^
    -dSAFER ^
    -sDEVICE=jpeg ^
    -dJPEGQ=95 ^
    -r600x600 ^
    -sOutputFile=c:/path/to/jpeg-dir/pdffile-%03d.jpeg ^
    c:/path/to/pdffile.pdf

This will create JPGs called pdffile-001.jpeg, pdffile-002.jpg etc. The parameter *-dJPEGQ=95" sets "JPEG Quality" to 95%. It uses a resolution of "600x600 dpi". You may need to additionally control the pagesize of the resulting JPGs in case your Ghostscript's default doesn't fit your needs:

gswin32c.exe ^
    -dBATCH ^
    -dNOPAUSE ^
    -dSAFER ^
    -sDEVICE=jpeg ^
    -dJPEGQ=95 ^
    -r600x600 ^
    -dPDFFitPage ^
    -dFIXEDMEDIA ^
    -dDEVICEWIDTHPOINTS=800 ^
    -dDEVICEHEIGHTPOINTS=600 ^
    -sOutputFile=c:/path/to/jpeg-dir/pdffile-%03d.jpeg ^
    c:/path/to/pdffile.pdf

or

gswin32c.exe ^
    -dBATCH ^
    -dNOPAUSE ^
    -dSAFER ^
    -sDEVICE=jpeg ^
    -dJPEGQ=95 ^
    -r600x600 ^
    -dPDFFitPage ^
    -dFIXEDMEDIA ^
    -sDEFAULTPAPERSIZE=a4 ^
    -sOutputFile=c:/path/to/jpeg-dir/pdffile-%03d.jpeg ^
    c:/path/to/pdffile.pdf

multiple-to-single-JPG-stitching with montage (ImageMagick or GraphicsMagick): The montage command (used in this example is ImageMagick) allows you to control the tiling pattern. If you use e.g. -tile 4x3 you'd get this imposition layout:

1  2  3  4    
5  6  7  8    
9 10 11 12    

You could use this command to stitch together 12 individual JPGs into one:

montage ^
    -border 0  ^
    -tile 4x3  ^
    c:/path/to/jpeg-dir/pdffile-*.jpeg  ^
    c:/path/to/final.jpg

Of course, montage has many dozen of additional parameters which allow you to determine background, spacing, offsets, decoration, labels, rotation, cropping, caption etc. for the input and the resulting JPG.


EDIT: (I had wanted to give this hint already in my original answer, but forgot.) montage by default will use tile sizes of 120x120 pixels. If you want to keep the original page sizes for each tile, you have to add -geometry to the commandline. Assuming you had A4 (=595x852 pt) pages in your PDF, and you want to keep this, but also add a spacing of 11pt to the horizontal and 22 pt to the vertical direction of the tiling (plus 4pt strong gray border/frame lines around each tile), do this:

montage ^
    -border 4 ^
    -tile 4x3 ^
    -geometry 595x842+11+22 ^
    c:/path/to/jpeg-dir/pdffile-*.jpeg ^
    c:/path/to/final.jpg

EDIT 2: (Missed still another important hint.) If you do not want to lose the good image quality during the stitching/montage process, which your PDF-to-JPG conversion had created, then also add the -quality 100 parameter to your commandline like this:

montage ^
    -border 4 ^
    -tile 4x3 ^
    -geometry 595x842+11+22 ^
    -quality 100 ^
    c:/path/to/jpeg-dir/pdffile-*.jpeg ^
    c:/path/to/final.jpg
0
source

Converting a PDF to black & white with ghostscript

I am not sure if the following suggestion will work... but it may be worth to try out:

  1. convert the PDF to PostScript using the simple pdf2ps utility
  2. convert that PostScript back to PDF while using a re-defined /setrgbcolor PostScript operator

These are the commands:

First

  pdf2ps color.pdf color.ps

This gives you color.ps as output.

Second

gs \
-o bw-from-color.pdf \
-sDEVICE=pdfwrite \
-c "/setrgbcolor{0 mul 3 1 roll 0 mul 3 1 roll 0 mul 3 1 roll 0 mul add add setgray}def" \
-f color.ps
0
source

GhostScript "Unrecoverable error, exit code 1" when using embeded fonts in .pdf

My suggestion would be to use a version of Ghostscript which isn't quite so elderly. That version is 4 years old now, the current version is 9.07.

If current code fails in a similar fashion, then you can open a bug report at http://bugs.ghostscript.com. If you do open a bug, remember to attach the specimen file and a command line to reproduce the problem.

0
source

merge pdf files a4 and letter linux

Do you want all pages in the resulting document to have the same paper size? For that, you would need to resize the page of one of the two documents. This question deals with resizing one PDF using ghostscript.

Otherwise, just leave out the -sPAPERSIZE switch, so your command will look like:

gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=output.pdf file1.pdf file2.pdf file3.pdf lastfile.pdf

description

The gs (gswin32c, gswin32, gsos2) command invokes Ghostscript, an interpreter of Adobe Systems’ PostScript(tm) and Portable Document Format (PDF) languages. gs reads "files" in sequence and executes them as Ghostscript programs. After doing this, it reads further input from the standard input stream (normally the keyboard), interpreting each line separately and output to an output device (may be a file or an X11 window preview, see below). The interpreter exits gracefully when it encounters the "quit" command (either in a file or from the keyboard), at end-of-file, or at an interrupt signal (such as Control-C at the keyboard).

The interpreter recognizes many option switches, some of which are described below. Please see the usage documentation for complete information. Switches may appear anywhere in the command line and apply to all files thereafter. Invoking Ghostscript with the -h or -? switch produces a message which shows several useful switches, all the devices known to that executable, and the search path for fonts; on Unix it also shows the location of detailed documentation.

Ghostscript may be built to use many different output devices. To see which devices your executable includes, run "gs -h".

Unless you specify a particular device, Ghostscript normally opens the first one of those and directs output to it.

If built with X11 support, often the default device is an X11 window (previewer), else ghostscript will typically use the bbox device and print on stdout the dimension of the postscript file.

So if the first one in the list is the one you want to use, just issue the command

gs myfile.ps

You can also check the set of available devices from within Ghostscript: invoke Ghostscript and type

devicenames ==

but the first device on the resulting list may not be the default device you determine with "gs -h". To specify "AbcXyz" as the initial output device, include the switch

-sDEVICE=AbcXyz

For example, for output to an Epson printer you might use the command

gs -sDEVICE=epson myfile.ps

The "-sDEVICE=" switch must precede the first mention of a file to print, and only the switch’s first use has any effect.

Finally, you can specify a default device in the environment variable GS_DEVICE. The order of precedence for these alternatives from highest to lowest (Ghostscript uses the device defined highest in the list) is:

Some devices can support different resolutions (densities). To specify the resolution on such a printer, use the "-r" switch:

gs -sDEVICE=<device> -r<xres>x<yres>

For example, on a 9-pin Epson-compatible printer, you get the lowest-density (fastest) mode with

gs -sDEVICE=epson -r60x72

and the highest-density (best output quality) mode with

gs -sDEVICE=epson -r240x72.

If you select a printer as the output device, Ghostscript also allows you to choose where Ghostscript sends the output -- on Unix systems, usually to a temporary file. To send the output to a file "foo.xyz", use the switch

-sOutputFile=foo.xyz

You might want to print each page separately. To do this, send the output to a series of files "foo1.xyz, foo2.xyz, ..." using the "-sOutputFile=" switch with "%d" in a filename template:

-sOutputFile=foo%d.xyz

Each resulting file receives one page of output, and the files are numbered in sequence. "%d" is a printf format specification; you can also use a variant like "%02d".

On Unix and MS Windows systems you can also send output to a pipe. For example, to pipe output to the "lpr" command (which, on many Unix systems, directs it to a printer), use the option

-sOutputFile=%pipe%lpr

Note that the ’%’ characters need to be doubled on MS Windows to avoid mangling by the command interpreter.

You can also send output to standard output:

-sOutputFile=-

or

-sOutputFile=%stdout%

In this case you must also use the -q switch, to prevent Ghostscript from writing messages to standard output.

To select a specific paper size, use the command line switch

-sPAPERSIZE=<paper_size>

for instance

-sPAPERSIZE=a4

or

-sPAPERSIZE=legal

Most ISO and US paper sizes are recognized. See the usage documentation for a full list, or the definitions in the initialization file "gs_statd.ps".

Ghostscript can do many things other than print or view PostScript and PDF files. For example, if you want to know the bounding box of a PostScript (or EPS) file, Ghostscript provides a special "device" that just prints out this information.

For example, using one of the example files distributed with Ghostscript,

gs -sDEVICE=bbox golfer.ps

prints out

%%BoundingBox: 0 25 583 732

%%HiResBoundingBox: 0.808497 25.009496 582.994503 731.809445

options

-- filename arg1 ...

Takes the next argument as a file name as usual, but takes all remaining arguments (even if they have the syntactic form of switches) and defines the name "ARGUMENTS" in "userdict" (not "systemdict") as an array of those strings, before running the file. When Ghostscript finishes executing the file, it exits back to the shell.

-Dname=token
-d
name=token

Define a name in "systemdict" with the given definition. The token must be exactly one token (as defined by the "token" operator) and may contain no whitespace.

-Dname

-dname

Define a name in "systemdict" with value=null.

-Sname=string
-s
name=string

Define a name in "systemdict" with a given string as value. This is different from -d. For example, -dname=35 is equivalent to the program fragment
/name 35 def
whereas -sname=35 is equivalent to
/name (35) def

-P

Makes Ghostscript to look first in the current directory for library files. By default, Ghostscript no longer looks in the current directory, unless, of course, the first explicitly supplied directory is "." in -I. See also the INITIALIZATION FILES section below, and bundled Use.htm for detailed discussion on search paths and how Ghostcript finds files.

-q

Quiet startup: suppress normal startup messages, and also do the equivalent of -dQUIET.

-gnumber1xnumber2

Equivalent to -dDEVICEWIDTH=number1 and -dDEVICEHEIGHT=number2. This is for the benefit of devices (such as X11 windows) that require (or allow) width and height to be specified.

-rnumber
-r
number1xnumber2

Equivalent to -dDEVICEXRESOLUTION=number1 and -dDEVICEYRESOLUTION=number2. This is for the benefit of devices such as printers that support multiple X and Y resolutions. If only one number is given, it is used for both X and Y resolutions.

-Idirectories

Adds the designated list of directories at the head of the search path for library files.

-

This is not really a switch, but indicates to Ghostscript that standard input is coming from a file or a pipe and not interactively from the command line. Ghostscript reads from standard input until it reaches end-of-file, executing it like any other file, and then continues with processing the command line. When the command line has been entirely processed, Ghostscript exits rather than going into its interactive mode.

Note that the normal initialization file "gs_init.ps" makes "systemdict" read-only, so the values of names defined with -D, -d, -S, or -s cannot be changed (although, of course, they can be superseded by definitions in "userdict" or other dictionaries.)

environment

GS_OPTIONS

String of options to be processed before the command line options

GS_DEVICE

Used to specify an output device

GS_FONTPATH

Path names used to search for fonts

GS_LIB

Path names for initialization files and fonts

TEMP

Where temporary files are made

files

The locations of many Ghostscript run-time files are compiled into the executable when it is built. On Unix these are typically based in /usr/local, but this may be different on your system. Under DOS they are typically based in C:\GS, but may be elsewhere, especially if you install Ghostscript with GSview. Run "gs -h" to find the location of Ghostscript documentation on your system, from which you can get more details. On a Debian system they are in /usr.
/usr/share/gs-gpl/#.##/*/*

Startup files, utilities, and basic font definitions

/usr/share/fonts/type1/gsfonts/*

More font definitions from the gsfonts package

/usr/share/doc/gs-gpl/examples/*

Ghostscript demonstration files

/usr/share/doc/gs-gpl/*

Diverse document files

initialization files

When looking for the initialization files "gs_*.ps", the files related to fonts, or the file for the "run" operator, Ghostscript first tries to open the file with the name as given, using the current working directory if no directory is specified. If this fails, and the file name doesn’t specify an explicit directory or drive (for instance, doesn’t contain "/" on Unix systems or "\" on MS Windows systems), Ghostscript tries directories in this order:

1.

the directories specified by the -I switches in the command line (see below), if any;

2.

the directories specified by the GS_LIB environment variable, if any;

3.

the directories specified by the GS_LIB_DEFAULT macro in the Ghostscript makefile when the executable was built. When gs is built on Unix, GS_LIB_DEFAULT is usually "/usr/local/share/ghostscript/#.##:/usr/local/share/ghostscript/fonts" where "#.##" represents the Ghostscript version number. They are "/usr/share/gs-gpl/#.## on a Debian system".

Each of these (GS_LIB_DEFAULT, GS_LIB, and -I parameter) may be either a single directory or a list of directories separated by ":".

safer mode

The -dSAFER option disables the "deletefile" and "renamefile" operators and prohibits opening piped commands ("%pipe%cmd"). Only "%stdout" and "%stderr" can be opened for writing. It also disables reading from files, except for "%stdin", files given as a command line argument, and files contained in paths given by LIBPATH and FONTPATH or specified by the system params /FontResourceDir and /GenericResourceDir.

This mode also sets the .LockSafetyParams parameter of the initial output device to protect against programs that attempt to write to files using the OutputFile device parameter. Since the device parameters specified on the command line, including OutputFile, are set prior to SAFER mode, use of "-sOutputFile=..." on the command line is unrestricted.

SAFER mode prevents changing the /GenericResourceDir, /FontResourceDir, /SystemParamsPassword, and /StartJobPassword.

While SAFER mode is not the default, it is the default for many wrapper scripts such as ps2pdf and may be the default in a subsequent release of Ghostscript. Thus when running programs that need to open files or set restricted parameters you should pass the -dNOSAFER command line option or its synonym -dDELAYSAFER.

When running with -dNOSAFER it is possible to perform a "save" followed by ".setsafe", execute a file or procedure in SAFER mode, and then use "restore" to return to NOSAFER mode. In order to prevent the save object from being restored by the foreign file or procedure, the ".runandhide" operator should be used to hide the save object from the restricted procedure.

special names

-dDISKFONTS

Causes individual character outlines to be loaded from the disk the first time they are encountered. (Normally Ghostscript loads all the character outlines when it loads a font.) This may allow loading more fonts into RAM, at the expense of slower rendering.

-dNOCACHE

Disables character caching. Useful only for debugging.

-dNOBIND

Disables the "bind" operator. Useful only for debugging.

-dNODISPLAY

Suppresses the normal initialization of the output device. This may be useful when debugging.

-dNOPAUSE

Disables the prompt and pause at the end of each page. This may be desirable for applications where another program is driving Ghostscript.

-dNOPLATFONTS

Disables the use of fonts supplied by the underlying platform (for instance X Windows). This may be needed if the platform fonts look undesirably different from the scalable fonts.

-dSAFER

Restricts file operations the job can perform. Strongly recommended for spoolers, conversion scripts or other sensitive environments where a badly written or malicious PostScript program code must be prevented from changing important files.

-dWRITESYSTEMDICT

Leaves "systemdict" writable. This is necessary when running special utility programs such as font2c and pcharstr, which must bypass normal PostScript access protection.

-sDEVICE=device

Selects an alternate initial output device, as described above.

-sOutputFile=filename

Selects an alternate output file (or pipe) for the initial output device, as described above.

version

This document was last revised for Ghostscript version 9.07.

x resources

Ghostscript, or more properly the X11 display device, looks for the following resources under the program name "Ghostscript":
borderWidth

The border width in pixels (default = 1).

borderColor

The name of the border color (default = black).

geometry

The window size and placement, WxH+X+Y (default is NULL).

xResolution

The number of x pixels per inch (default is computed from WidthOfScreen and WidthMMOfScreen).

yResolution

The number of y pixels per inch (default is computed from HeightOfScreen and HeightMMOfScreen).

useBackingPixmap

Determines whether backing store is to be used for saving display window (default = true).

See the usage document for a more complete list of resources. To set these resources on Unix, put them in a file such as "~/.Xresources" in the following form:

Ghostscript*geometry: 612x792-0+0

Ghostscript*xResolution: 72

Ghostscript*yResolution: 72

Then merge these resources into the X server’s resource database:

% xrdb -merge ~/.Xresources


bugs

See http://bugs.ghostscript.com/ and the Usenet news group comp.lang.postscript.


see also

The various Ghostscript document files (above), especially Use.htm.


author

Artifex Software, Inc. are the primary maintainers of Ghostscript. Russell J. Lang, gsview at ghostgum.com.au, is the author of most of the MS Windows code in Ghostscript.

How can this site be more helpful to YOU ?


give  feedback