国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > web前端 > htmlcss > GhostScript命令参数详解

GhostScript命令参数详解

来源:程序员人生   发布时间:2015-01-19 09:04:42 阅读次数:14117次

本文列出几个经常使用参数,然后下面附上官方的参数详解:

1、经常使用参数解释

这是1个测试的命令:gs -dQUIET -dNOSAFER -r300 -dBATCH -sDEVICE=pngalpha -dNOPAUSE -dNOPROMPT -sOutputFile=/opt/shanhy/testpng/%d.png /opt/shanhy/test.pdf

相干参数以下说明:

    "-dQUIET",    安静的意思,指代履行进程中尽量少的输出日志等信息。(也能够简写为“-q”)
    "-dNOSAFER",    通过命令行运行
    "-dBATCH",    履行到最后1页后退出
    "-dNOPAUSE",    每页转换之间没有停顿
    "-dNOPROMPT",    没有相干提示                       
    "-dFirstPage=1",    从第几页开始
    "-dLastPage=5",     到第几页结束  
    "-sDEVICE=pngalpha",    转换输出的文件类型装置,默许值为x11alpha
    "-g720x1280",    图片像素(-g<width>x<height>),1般不指定,使用默许输出
    "-r300",    图片分辨率,默许值好像是72(未测试证实)
    "-sOutputFile=/opt/shanhy/error1png/%d.png",    图片输前途径,使用%d或%ld输出页数

输出装备以下:

Default output device: x11alpha
Available devices:
   alc1900 alc2000 alc4000 alc4100 alc8500 alc8600 alc9100 ap3250 appledmp
   atx23 atx24 atx38 bbox bit bitcmyk bitrgb bitrgbtags bj10e bj10v bj10vh
   bj200 bjc600 bjc800 bjc880j bjccmyk bjccolor bjcgray bjcmono bmp16 bmp16m
   bmp256 bmp32b bmpgray bmpmono bmpsep1 bmpsep8 ccr cdeskjet cdj1600 cdj500
   cdj550 cdj670 cdj850 cdj880 cdj890 cdj970 cdjcolor cdjmono cdnj500 cfax
   chp2200 cif cljet5 cljet5c cljet5pr coslw2p coslwxl cp50 declj250 deskjet
   devicen dfaxhigh dfaxlow dj505j djet500 djet500c dl2100 dnj650c epl2050
   epl2050p epl2120 epl2500 epl2750 epl5800 epl5900 epl6100 epl6200 eplcolor
   eplmono eps2write eps9high eps9mid epson epsonc escp escpage faxg3
   faxg32d faxg4 fmlbp fmpr fpng fs600 gdi hl1240 hl1250 hl7x0 hpdj1120c
   hpdj310 hpdj320 hpdj340 hpdj400 hpdj500 hpdj500c hpdj510 hpdj520 hpdj540
   hpdj550c hpdj560c hpdj600 hpdj660c hpdj670c hpdj680c hpdj690c hpdj850c
   hpdj855c hpdj870c hpdj890c hpdjplus hpdjportable ibmpro ijs imagen
   inferno ink_cov inkcov itk24i itk38 iwhi iwlo iwlq jetp3852 jj100 jpeg
   jpegcmyk jpeggray la50 la70 la75 la75plus laserjet lbp310 lbp320 lbp8
   lex2050 lex3200 lex5700 lex7000 lips2p lips3 lips4 lips4v lj250 lj3100sw
   lj4dith lj4dithp lj5gray lj5mono ljet2p ljet3 ljet3d ljet4 ljet4d
   ljet4pjl ljetplus ln03 lp1800 lp1900 lp2000 lp2200 lp2400 lp2500 lp2563
   lp3000c lp7500 lp7700 lp7900 lp8000 lp8000c lp8100 lp8200c lp8300c
   lp8300f lp8400f lp8500c lp8600 lp8600f lp8700 lp8800c lp8900 lp9000b
   lp9000c lp9100 lp9200b lp9200c lp9300 lp9400 lp9500c lp9600 lp9600s
   lp9800c lps4500 lps6500 lq850 lxm3200 lxm5700m m8510 mag16 mag256
   md1xMono md2k md50Eco md50Mono md5k mgr4 mgr8 mgrgray2 mgrgray4 mgrgray8
   mgrmono miff24 mj500c mj6000c mj700v2c mj8000c ml600 necp6 npdl nullpage
   oce9050 oki182 oki4w okiibm oprp opvp paintjet pam pamcmyk32 pamcmyk4 pbm
   pbmraw pcl3 pcx16 pcx24b pcx256 pcx2up pcxcmyk pcxgray pcxmono pdfwrite
   pgm pgmraw pgnm pgnmraw photoex picty180 pj pjetxl pjxl pjxl300 pkm
   pkmraw pksm pksmraw plan plan9bm planc plang plank planm png16 png16m
   png256 png48 pngalpha pnggray pngmono pnm pnmraw ppm ppmraw pr1000
   pr1000_4 pr150 pr201 ps2write psdcmyk psdcmykog psdrgb pxlcolor pxlmono
   r4081 rinkj rpdl samsunggdi sgirgb sj48 spotcmyk st800 stcolor sunhmono
   t4693d2 t4693d4 t4693d8 tek4696 tiff12nc tiff24nc tiff32nc tiff48nc
   tiff64nc tiffcrle tiffg3 tiffg32d tiffg4 tiffgray tifflzw tiffpack
   tiffscaled tiffsep tiffsep1 txtwrite uniprint x11 x11alpha x11cmyk
   x11cmyk2 x11cmyk4 x11cmyk8 x11gray2 x11gray4 x11mono x11rg16x x11rg32x
   xcf xes xpswrite


2、官方参数详解

How to use Ghostscript

Table of contents

  • Invoking Ghostscript
    • Help at the command line: gs -h
  • Selecting an output device
    • Output resolution
    • Output to files
      • One page per file
    • Choosing paper size
    • Changing the installed default paper size
  • Interacting with pipes
  • Using Ghostscript with PDF files
    • Switches for PDF files
    • Problems interpreting a PDF file
    • PDF files from standard input
  • Using Ghostscript with EPS files
  • Using Ghostscript with overprinting and spot colors
  • How Ghostscript finds files
    • Finding PostScript Level 2 resources
    • Font lookup
    • CID fonts
    • CID font substitution
    • Using Unicode True Type fonts
    • Temporary files
  • Notes on specific platforms
    • Unix
    • VMS
      • Using X Windows on VMS
    • MS Windows
    • X Windows
      • X resources
      • Working around bugs in X servers
      • X fonts
      • Using Ghostscript fonts on X displays
      • X device parameters
    • SCO Unix
  • Command line options
    • General switches
      • Input control
      • File searching
      • Setting parameters
      • Suppress messages
    • Parameter switches (-d and -s)
      • Rendering parameters
      • Page parameters
      • Font-related parameters
      • Resource-related parameters
      • Interaction-related parameters
      • Device and output selection parameters
      • EPS parameters
      • Deferred Page Rendering
      • ICC color parameters
      • Other parameters
  • Improving performance
  • Summary of environment variables
  • Debugging
    • Debug Switches
    • Visual Trace
  • Appendix: Paper sizes known to Ghostscript
  • Appendix: X default font mappings
    • Standard X servers
      • Regular fonts
      • Symbol fonts
      • Dingbat fonts
    • Sun OpenWindows
  • Appendix: Running Ghostscript with third-partyfont renderers

For other information, see the Ghostscriptoverview and, if necessary, how toinstall 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 isessentially the same on all systems, although the name of the executableprogram itself may differ among systems. For instance, to invokeGhostscript 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 commonto 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:

  • the version and release information
  • the general format of the command line
  • a few of the most useful options
  • the formats it can interpret
  • the available output devices
  • the search path
  • the bug report address

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) liststhe 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, andonly its first use has any effect. For example, for printer output in aconfiguration 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 Ghostscriptyou 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 youdo something to change devices. You can switch devices at any time byusing the selectdevice procedure, forinstance like one of these:
(x11alpha) selectdevice
(epson) selectdevice

Output resolution

Some printers can print at several different resolutions, letting youbalance resolution against printing speed. To select the resolution onsuch 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 actuallybegins 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 fileupon exit, but changing the OutputFile device parameter will cause thesedevices to emit the pages received up to that point and then open the newfile name given by OutputFile.

For example, in order to create two PDF files from a single invocation ofghostscript 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 rasterizingfigures, but sometimes you want images of each page of a multi-pagedocument. You can tell Ghostscript to put each page of output in aseries of similarly named files. To do this place a template'%d' in the filename which Ghostscript will replace with thepage number.

Note: Since the % character is used to precede the page numberformat specification, in order to represent a file name that contains a %,double % characters must be used. For example for the file my%foothe 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 formatspecifications. Some examples are:
-sOutputFile=ABC-%d.png
produces 'ABC⑴.png', ... , 'ABC⑴0.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 extrablank page written (pdfwrite, ps2write, eps2write, pxlmono, pxlcolor, ...).

As noted above, when using MS Windows console (command.com or cmd.exe), youwill have to double the % character since the % is used bythat 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 outputfile 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 moreinput 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 itsdefault page size. There are two ways to select other paper sizes from thecommand line:

  • If the desired paper size is listed in the section on paper sizes known to Ghostscript below, youcan select it as the default paper size for a single invocation ofGhostscript by using the -sPAPERSIZE= switch, for instance
    -sPAPERSIZE=a4
    -sPAPERSIZE=legal
  • Otherwise you can set the page size using thepair of switches
    -dDEVICEWIDTHPOINTS=w-dDEVICEHEIGHTPOINTS=h
    Where w be the desired paper width and h be thedesired paper height in points (units of 1/72 of an inch).

Individual documents can (and often do) specify a paper size, which takesprecedence over the default size. To force a specific paper size andignore the paper size specified in the document, select a paper size asjust described, and also include the-dFIXEDMEDIA switch on thecommand line.

The default set of paper sizes will be included in the currentpagedevicein the InputAttributes dictionary with each paper size asone of the entries. The last entry in the dictionary (which has numeric keys)is a non-standard (Ghostscript extension) type of PageSize where the arrayhas four elements rather than the standard two elements. This four elementarray represents a page size range where the first two elements are the lowerbound of the range and the second two are the upper bound. By default theseare [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 sepcificationfor non-printer file formats such as JPEG, PNG, TIFF, EPS, ...
For actual printers, either the entire InputAttributes dictionaryshould be replaced or the range type entry should not be included. To simplifyusing the default page sizes in the InputAttributes dictionary,the command line option -dNORANGEPAGESIZE can be used. Usingthis option will result in automatic rotation of the document page if the requestedpage size matches one of the default page sizes.

When the -dFIXEDMEDIA switch is given on thecommand line, the InputAttributes dictionary will only be populatedwith the single page size. This allows the -dPSFitPage option to fitthe page size requested in a PostScript file to be rotated, scaled and centeredfor the best fit on the specified page.

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 changethis to

/DEFAULTPAPERSIZE (a4) def

For a4 you can substitute anypaper 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 beselected to be a4 or letter dependingon the locale.

Interacting with pipes

As noted above, input files are normally specified on the commandline. However, one can also "pipe" input into Ghostscript from anotherprogram 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 thangoing 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 -qswitch to prevent Ghostscript from writing messages to standard outputwhich become mixed with the intended output stream.

Also, using the -sstdout=%stderr option is useful, particularly withinput 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, thepdf2ps 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.Pages of all documents in PDF collections are numbered sequentionally.
-dLastPage=pagenumber
Stops interpreting after the designated page of the document.Pages of all documents in PDF collections are numbered sequentionally.
-dPDFFitPage
Rather than selecting a PageSize given by the PDF MediaBox, BleedBox (see -dUseBleedBox),TrimBox (see -dUseTrimBox), ArtBox (see -dUseArtBox), 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 for creating fixed size images of PDF files that may havea variety of page sizes, for example thumbnail images.

This option is also set by the -dFitPage option.

-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 thefile's "screen" options. If neither of these is specified, the output willuse the screen options for any output device that doesn't have anOutputFile parameter, and the printer options fordevices that do have this parameter.
-dUseBleedBox
Sets the page size to the BleedBox rather than the MediaBox.defines the region to which the contents of the page should beclipped when output in a production environment. This may includeany extra bleed area needed to accommodate the physical limitationsof cutting, folding, and trimming equipment. The actual printed pagemay include printing marks that fall outside the bleed box.
-dUseTrimBox
Sets the page size to the TrimBox rather than the MediaBox.The trim box defines the intended dimensions of the finished pageafter trimming. Some files have a TrimBox that is smaller than theMediaBox and may include white space, registration or cutting marksoutside the CropBox. Using this option simulates appearance of thefinished printed page.
-dUseArtBox
Sets the page size to the ArtBox rather than the MediaBox.The art box defines the extent of the page's meaningful content(including potential white space) as intended by the page's creator.The art box is likely to be the smallest box. It can be usefulwhen one wants to crop the page as much as possiblewithout losing the content.
-dUseCropBox
Sets the page size to the CropBox rather than the MediaBox.Unlike the other "page boundary" boxes, CropBox does not have adefined meaning, it simply provides a rectangle to which thepage contents will be clipped (cropped). By convention, it isoften, but not exclusively, used to aid the positioning of contenton the (usually larger, in these cases) media.
-sPDFPassword=password
Sets the user or owner password to be used in decoding encryptedPDF files. For files created with encryption method 4 or earlier, thepassword is an arbitrary string of bytes; with encryption method 5 orlater, it should be text in either UTF⑻ or your locale's characterset (Ghostscript tries both).
-dShowAnnots=false
Don't enumerate anntoations associated with the page objects throughAnnots 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 filesthat don't associate all annotations with the page objects.
-dNoUserUnit
Ignore UserUnit parameter. This may be useful for backwardcompatibility with old versions of Ghostscript and Adobe Acrobat,or for processing files with large values of UserUnitthat otherwise exceed implementation limits.
-dRENDERTTNOTDEF
If a glyph is not present in a font the normal behaviour is to use the /.notdefglyph instead. On TrueType fonts, this is often a hollow sqaure. Under someconditions Acrobat does not do this, instead leaving a gap equivalent to thewidth of the missing glyph, or the width of the /.notdef glyph if no /Widthsarray is present. Ghostscript now attempts to mimic this undocumented featureusing a user parameter RenderTTNotdef. The PDF interpreter sets thisuser 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 thatGhostscript doesn't recognize as PDF, even though the same filecan be opened and interpreted by an Adobe Acrobat viewer.In many cases, this is because of incorrectly generated PDF. Acrobattends to be very forgiving of invalid PDF files. Ghostscript tends toexpect files to conform to the standard. For example, even thoughvalid PDF files must begin with %PDF, Acrobat willscan the first 1000 bytes or so for this string, and ignore any precedinggarbage.

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

PDF files from standard input

The PDF language, unlike the PostScript language, inherently requiresrandom access to the file.If you provide PDF to standard input using thespecial 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 incorporatedin other PostScript documents and may not display or print on theirown. An EPS file must conform to the Document Structuring Conventions,must include a %%BoundingBox line to indicate therectangle in which it will draw, must not use PostScript commandswhich 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 requiresthat 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, pleaserefer to the Adobe documentation in their tech note #5002. Itis 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 ofoverprinting and spot colors depends upon theprocess color model of the output device. Devicesthat 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 colorscaused by the differences in the color model of the output device are part of thePostScript and PDF specifications. They are not due to a limitation in theimplementation of Ghostscript or its output devices.

With devices which use a subtractive process color model, both PostScriptand PDF allow the drawing of objects using colorants (inks) for one or more planeswithout affecting the data for the remaining colorants. Thus the inks for oneobject may overprint the inks for another object. In some casesthis produces a transparency like effect. (The effects of overprinting shouldnot be confused with the PDF 1.4 blending operations which are supported forall output devices.) Overprinting is not allowed for devices with an additiveprocess color model. With files that use overprinting, the appearance of theresulting image can differ between devices which produce RGB output versus deviceswhich 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 appearanceof the output from the tiff24nc and tiff32nc deviceswhich use an RGB and a CMYK process color models.

Most of the Ghostscript output devices do not havefile formats which support spot colors. Instead spot colors are converted usingthe tint transform function contained within the color space definition.. Howeverthere are several devices which have support for spot colors. The PSD format(Adobe Photoshop) produced by the psdcmyk devicecontains 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 displaydevice (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 equivalentCMYK color to simulate the appearance of the spot color. Thetiffsepdevice creates output files for each separation (CMYK and any spot colorspresent). It also creates a composite CMYK file using an equivalent CMYK colorto simulate the appearance of spot colors. Thexcfcmyk devicecreates output files with spot colors placed in separate alpha channels. (TheXCF file format does not currently directly support spot colors.)

Overprinting with spot colors is not allowed if the tint transform functionis 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 resultwould be obtained with a CMYK only device and another would be obtained witha CMYK plus spot color device. In a worst case situation where a file has overprintingwith both process (CMYK) and spot colors, it is possible to get three differentappearances for the same input file using thetiff24nc (RGB),tiff32nc (CMYK), andtiffsep (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 availablein the free Acrobat Reader. The free Acrobat Reader also uses the tint transformfunctions 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 thefile 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 fileusing 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 -Iswitches in the command line, if any;
  3. The directories specified by the GS_LIBenvironment 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 builtinto 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 singledirectory or a list of directories separated by a character appropriate forthe operating system (":" on Unix systems,"," on VMS systems, and";" on MS Windows systems).By default, Ghostscript no longer searches the current directory firstbut provides -P switch for a degreeof backward compatibility.

Note that Ghostscript does not use this file searching algorithm for therun or file operators: for these operators, itsimply opens the file with the name given. To run a file using the searchingalgorithm, 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 whetherthe value of the system parameter GenericResourceDirspecifies an absolute path. The user may set it as explained inResource-related parameters.

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

If the value of the system parameter GenericResourceDiris 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 GenericResourceDiris not an absolute path,Ghostscript assumes multiple resource directories.In this case it concatenates :

  1. A directory listed in the sectionHow 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. The name of the resource instance (for instance, Identity-H)
Due to possible variety of the part 1, the first successful combination is used.For example, if the value of the system parameter GenericResourceDiris the string ../Resource/(or its equivalent in the file path syntax of the underlying platform),Ghostscript searches for ../Resource/CMap/Identity-Hfrom all directories listed inHow Ghostscript finds files.So in this example, if the user on a Windows platform specifiesthe command line option -I.;../gs/lib;c:/gs8.50/lib,Ghostscript searches for ../gs/Resource/CMap/Identity-H andthen for c:/gs8.50/Resource/CMap/Identity-H.

To get a proper platform dependent syntax Ghostscript insertsthe value of the system parameterGenericResourcePathSep (initially"/" on Unix and Windows, ":" on MacOS,"." or "]" on OpenVMS).The string ../Resource is replaced with aplatform dependent equivalent.

In the case of multiple resource directories,the default ResourceFileName procedure retrieves either a pathto the first avaliable resource, or if the resource is not available itreturns a path starting with GenericResourceDir.Consequently Postscript installers of Postscript resourceswill overwrite an existing resource or add a new one to the first resource directory.

To look up fonts, after exhausting the search method described in thenext section, it concatenates together

  1. the value of the system parameterFontResourceDir (initially/Resource/Font/)
  2. the name of the resource font (for instance, Times-Roman)

Note that even although the system parameters are named "somethingDir", theyare not just plain directory names: they have "/" on theend, so that they can be concatenated with the category name or font name.

Font lookup

Ghostscript has a slightly different way to find the file containing a fontwith a given name. This rule uses not only the search path defined by-I, GS_LIB, andGS_LIB_DEFAULT as describedabove, but also the directory that is the value of theFontResourceDir system parameter, and an additional list ofdirectories that is the value of the GS_FONTPATH environmentvariable (or the value provided with the -sFONTPATH= switch,if present).

At startup time, Ghostscript reads in the Fontmap files inevery directory on the search path (or in the list provided with the-sFONTMAP= switch, if present): these files are catalogs offonts and the files that contain them. (See thedocumentation of fonts for details.) Then, when Ghostscript needs tofind a font that isn't already loaded into memory, it goes through a seriesof steps.

  • First, it looks up the font name in the combined Fontmaps. If there is anentry for the desired font name, and the file named in the entry can befound in some directory on the general search path (defined by-I, GS_LIB, andGS_LIB_DEFAULT), and the file is loaded successfully, andloading it defines a font of the desired name, that is the end of theprocess.
  • If this process fails at any step, Ghostscript looks for a file whose nameis the concatenation of the value of the FontResourceDirsystem parameter and the font name, with no extension. If such a fileexists, can be loaded, and defines a font of the desired name, that again isthe end. The value of FontResourceDir is normally thestring /Resource/Font/, but it can be changed with thesetsystemparams operator: see the PostScript LanguageReference Manual for details.
  • If that fails, Ghostscript then looks for a file on the general search pathwhose name is the desired font name, with no extension. If such a fileexists, can be loaded, and defines a font of the desired name, that again isthe end.
  • If that too fails, Ghostscript looks at the GS_FONTPATHenvironment variable (or the value provided with the-sFONTPATH= switch, if present), which is also a list ofdirectories. It goes to the first directory on the list, looking for allfiles that appear to contain PostScript fonts; it then adds all those filesand fonts to the combined Fontmaps, and starts over.
  • If scanning the first FONTPATH directory doesn't produce a file thatprovides the desired font, it adds the next directory on the FONTPATH list,and so on until either the font is defined successfully or the list isexhausted.
  • Finally, if all else fails, it will try to find a substitute for the fontfrom among the standard 35 fonts.

CID fonts (e.g. Chinese, Japanese and Korean)are found using a different method.


Differences between search path and font path
Search path Font path

-I switch -sFONTPATH= switch
 
GS_LIB and GS_LIB_DEFAULT environment variables GS_FONTPATH environment variable
 
Consulted first Consulted only if search path and FontResourceDir don't provide the file.
 
Font-name-to-file-name mapping given in Fontmap files; aliases are possible, and there need not be any relation between the font name in the Fontmap and the FontName in the file. Font-name-to-file-name mapping is implicit -- the FontName in the file is used. Aliases are not possible.
 
Only fonts and files named in Fontmap are used. Every Type 1 font file in each directory is available; if TrueType fonts are supported (the ttfont.dev feature was included when the executable was built), they are also available.

If you are using one of the following types of computer, you may wish toset the environment variable GS_FONTPATH tothe value indicated so that Ghostscript will automatically acquire all theinstalled Type 1 (and, if supported, TrueType) fonts (but see below fornotes on systems marked with "*"):


Suggested GS_FONTPATH for different systems
  System type GS_FONTPATH

  Digital Unix /usr/lib/X11/fonts/Type1Adobe
  Ultrix /usr/lib/DPS/outline/decwin
  HP-UX 9 /usr/lib/X11/fonts/type1.st/typefaces
  IBM AIX /usr/lpp/DPS/fonts/outlines
/usr/lpp/X11/lib/X11/fonts/Type1
/usr/lpp/X11/lib/X11/fonts/Type1/DPS
  NeXT /NextLibrary/Fonts/outline
* SGI IRIX /usr/lib/DPS/outline/base
/usr/lib/X11/fonts/Type1
  SunOS 4.x
(NeWSprint only)
 newsprint_2.5/SUNWsteNP/reloc/$BASEDIR/NeWSprint/
    small_openwin/lib/fonts
** SunOS 4.x /usr/openwin/lib/X11/fonts/Type1/outline
** Solaris 2.x /usr/openwin/lib/X11/fonts/Type1/outline
  VMS SYS$COMMON:[SYSFONT.XDPS.OUTLINE]

* On SGI IRIX systems, you must use Fontmap.SGI inplace of Fontmap or Fontmap.GS, becauseotherwise the entries in Fontmap will take precedence overthe fonts in the FONTPATH directories.

** On Solaris systems simply setting GS_FONTPATH orusing -sFONTPATH= may not work, because for some reason someversions of Ghostscript can't seem to find any of the Type1 fonts in/usr/openwin/lib/X11/fonts/Type1/outline. (It says: "15files, 15 scanned, 0 new fonts". We think this problem has been fixed inGhostscript version 6.0, but we aren't sure because we've never been able toreproduce it.) See Fontmap.Sol instead. Also, on Solaris2.x it's probably not worth your while to add Sun's fonts to your font pathand Fontmap. The fonts Sun distributes on Solaris 2.x in the directories

/usr/openwin/lib/X11/fonts/Type1
/usr/openwin/lib/X11/fonts/Type1/outline

are already represented among the ones distributed as part of Ghostscript;and on some test files, Sun's fonts have been shown to cause incorrectdisplays with Ghostscript.

These paths may not be exactly right for your installation; if the indicateddirectory doesn't contain files whose names are familiar font names likeCourier and Helvetica, you may wish to ask your system administrator whereto find these fonts.

Adobe Acrobat comes with a set of fourteen Type 1 fonts, on Unix typicallyin a directory called .../Acrobat3/Fonts. There is noparticular reason to use these instead of the corresponding fonts in theGhostscript distribution (which are of just as good quality), except to saveabout a megabyte of disk space, but the installation documentation explainshow to do it on Unix.

CID fonts

CID fonts are PostScript resources containing alarge number of glyphs (e.g. glyphs for Far East languages,Chinese, Japanese and Korean).Please refer to the PostScript Language Reference,third edition, for details.

CID font resources are a different kind of PostScript resource from fonts.In particular, they cannot be used as regular fonts.CID font resources must first be combined with a CMap resource, whichdefines specific codes for glyphs, before it can be used as a font. Thisallows the reuse of a collection of glyphs with different encodings.

The simplest method to request a font composed of a CID font resourceand a CMap resource in a PostScript document is

/CIDFont-CMap findfont
where CIDFont is a name of anyCID font resource, and CMap is a name of a CMap resourcedesigned for the same character collection. The interpreter will composethe font automatically from the specified CID font and CMap resources.Another method is possible using the composefont operator.

CID fonts must be placed in the /Resource/CIDFont/ directory.They are not found using Font lookupon the search path or font path.

CID font substitution

Automatic CIDFont Substitution

In general, it is highly recommended that CIDFonts used in the creation of PDFjobs should be embedded or available to Ghostscript as CIDFont resources, thisensures that the character set, and typeface style are as intended by theauthor.

In cases where the original CIDFont is not available, the next best option isto provide Ghostscript with a mapping to a suitable alternative CIDFont - seebelow for details on how this is achieved. However, Ghostscript does provide theability to use a "fall back" CIDFont substitute. As shipped, this uses theDroidSansFallback.ttf font. This font contains a large number of glyphs coveringseveral languages, but it is not comprehensive. There is, therefore, a chancethat glyphs may be wrong, or missing in the output when this fallback is used.

Internally, the font is referenced as CIDFont resource called CIDFallBack, thusa different fallback from DroidSansFallback.ttf can be specified adding amapping to your cidfmap file (see below for details) to map the name "CIDFallBack"as you prefer. For CIDFallBack the mapping must be a TrueTypefont or TrueType collection, it cannot be a Postscript CIDFont file.

As with any font containing large numbers of glyphs, DroidSansFallback.ttf isquite large (~3.5Mb at the of writing). If this is space you cannot afford inyour use of Ghostscript, you can simply delete the file from:Resource/CIDFSubst/DroidSansFallback.ttf. The build system will cope with thefile being removed, and the initialization code will avoid adding the internalfall back mapping if the file is missing.

If DroidSansFallback.ttf is removed, and no other CIDFallBack mapping is supplied,the final "fall back" is to use a "dumb" bullet CIDFont, called ArtifexBullet. Asthe name suggests, this will result in all the glyphs from a missing CIDFont being replaced witha simple bullet point.

This type of generic fall back CIDFont substitution can be very useful forviewing and proofing jobs, but may not be appropriate for a "production"workflow, where it is expected that only the original font should beused. For this situation, you can supply Ghostscript with the command line option:-dPDFNOCIDFALLBACK. By combining -dPDFNOCIDFALLBACK with -dPDFSTOPONERRORa production workflow can force a PDF with missing CIDFonts to error, and avoidrealising a CIDFont was missing only after printing.

The directory in which the fallback TrueType font or collection can be specified by thecommand line parameter -sCIDFSubstPath="path/to/TTF", or with the environmentvariable CIDFSUBSTPATH. The file name of the substitute TrueType font can bespecified using the command line parameter -sCIDFSubstFont="TTF file name" orthe environment variable CIDFSUBSTFONT.

Explicit CIDFont Substitution

Substitution of CID font resources is controlled by the Ghostscriptconfiguration file lib/cidfmap, which defines a CID font resource map.

The file forms a table of records, each of which should use one of three formats,explained below. Users may modify Resource/Init/cidfmap to configureGhostscript for a specific need. Note that the default Ghostscript build includessuch configuration and resource files in a rom file system built into the executable.So, to ensure your changes have an effect, you should do one of the following: rebuildthe executable; use the "-I" command line option to add the directory containing yourmodified file to Ghostscript's search path; or, finally, build Ghostscript to use diskbased resources.

Format 1

To substitute a CID font resource with another CID font resource, add a record like this :

/Substituted /Original ;
where Substituted is a name of CID font resource being usedby a document, and Original is a name of an availableCID font resource. Please pay attention that both them must bedesigned for same character collection. In other words, youcannot substitute a Japanese CID font resource with a Korean CID font resource,etc. CMap resource names must not appear inlib/cidfmap. The trailing semicolon and the space before itare both required.

Format 2

To substitute (emulate) a CID font resource with a TrueType font file, add a record like this :

/Substituted << keys&values >> ;
Where keys&values are explained in the table below.
KeyTypeDescription
/PathstringA path to a TrueType font file. This must be an absolute path. If using -dSAFER, the directory containing the font file must be on one of the permitted paths.
/FileTypenameMust be /TrueType.
/SubfontIDinteger(optional) Index of the font in font collection, such as TTC. This is ignored if Path doesn't specify a collection. The first font in a collection is 0. Default value is 0.
/CSIarray of 2 or 3 elements(required) Information for building CIDSystemInfo.

If the array consists of 2 elements, the first element is a string, which specifies Ordering; the second element is a number, which specifies Supplement.

If the array consists of 3 elements, the first element is a string, which specifies Registry; the second element is a string, which specifies Ordering; the third element is a number, which specifies Supplement.

Currently only CIDFontType 2 can be emulated with a TrueType font.The TrueType font must contain enough characters to cover anAdobe character collection, which is specified in Ordering and used in documents.

Format 3

To point Ghostscript at a specific CIDFont file outside it's "normal" resource search path :

/CIDName (path/to/cid/font/file) ;
where CIDName is a name of CID font resource being usedby a document, and "path/to/cid/font/file" is the path to thePostscript CIDFont file, including the file name. NOTE: the CIDFont file, whenexecuted by the Postscript interpreter, must result in a CIDFont resource beingdefined whose CIDFontName matches the "CIDName" key for the current record.I.E. an entry with the key /PingHei-Bold must reference a file which creates aCIDFont resource called "PingHei-Bold". To substitute a file based CIDFont fora differently named CIDFont, use formats 1 and 3 in combination (the order of theentries is not important).The trailing semicolon and the space before it are both required.

NOTE: Environment Variables

It is also possible to influence the path using standard, or your own environment variables, usingthe custom Postscript operator getenv. Said operator takes a string parameter on the stackwhich is the environment variable to interrogate, and returns either a string, containing the value ofthe environment variable, and boolean true to indicate success, or just a booleanfalse to indicate failure. See below for an example of its use.

Examples :

Format 1:
/Ryumin-Medium /ShinGo-Bold ;
/Ryumin-Light /MS-Mincho ;
Format 2:
/Batang << /FileType /TrueType /Path (C:/WINDOWS/fonts/batang.ttc) /SubfontID 0 /CSI [(Korea1) 3] >> ;
/Gulim << /FileType /TrueType /Path (C:/WINDOWS/fonts/gulim.ttc) /SubfontID 0 /CSI [(Korea1) 3] >> ;
/Dotum << /FileType /TrueType /Path (C:/WINDOWS/fonts/gulim.ttc) /SubfontID 2 /CSI [(Korea1) 3] >> ;

Format 2 & environment variable:
/SimHei << /FileType /TrueType /Path (windir) getenv not {(c:/windows)}if (/fonts/simhei.ttf) concatstrings /SubfontID 0 /CSI [(GB1) 2] >> ;
Format 1 & 2
/SimSun << /FileType /TrueType /Path (C:/WINDOWS/fonts/simsun.ttc) /SubfontID 0 /CSI [(GB1) 2] >> ;
/SimHei << /FileType /TrueType /Path (C:/WINDOWS/fonts/simhei.ttf) /SubfontID 0 /CSI [(GB1) 2] >> ;
/STSong-Light /SimSun ;
/STHeiti-Regular /SimHei ;
Format 3:
/PMingLiU (/usr/local/share/font/cidfont/PMingLiU.cid) ;
Format 1 & 3
/Ryumin-Light /PMingLiU ;
/PMingLiU (/usr/local/share/font/cidfont/PMingLiU.cid) ;

The win32 installer of recent version of ghostscript has a checkbox for"Use Windows TrueType fonts for Chinese, Japanese and Korean" to optionally updatelib/cidfmap with the common CJK fonts provided by Microsoft products. The scriptcan also be run separately (e.g. against a network drive with windows CJK fonts):

gswin32c -q -dBATCH -sFONTDIR=c:/windows/fonts -sCIDFMAP=lib/cidfmap lib/mkcidfm.ps

Note that the font file path uses Postscript syntax.Because of this, backslashes in the paths must berepresented as a double backslash.

This can complicate substitutions for fonts with non-Roman names.For example, if a PDF file asks for a font with the name/#82l#82r#83S#83V#83b#83N. This cannot be used directlyin a cidfmap file because the #xx notation in names is a PDF-onlyencoding. Instead, try something like:

<82C68272835383568362834E>cvn << /Path(C:/WINDOWS/Fonts/msmincho.ttc) /FileType /TrueType /SubfontID 0 /CSI[(Japan1) 3] >> ;
Where <82C68272835383568362834E> is the same bytesequence converted to a hex string. This lets you specify a nameusing any sequence of bytes through the encodings available forPostscript strings.

Note that loading truetype fonts directly from/Resources/CIDFont is no longer supported.There is no reliable way to generate a character ordering for truetypefonts. The 7.0x versions of Ghostscript supported this by assuming a Japanesecharacter ordering. This is replaced in the 8.0x and later releases withthe more general cidfmap mechanism.

The PDF specification requires CID font files to be embedded,however some documents omit them. As a workaroundthe PDF interpreter applies an additional substitution method whena requested CID font resource is not embedded and it is not available.It takes values of the keys Registry and Orderingfrom the CIDFontSystem dictionary,and concatenates them with a dash inserted.For example, if a PDF CID font resource specifies

/CIDSystemInfo << /Registry (Adobe) /Ordering (CNS1) /Supplement 1 >>
the generated subsitituite name is Adobe-CNS1.The latter may look some confusing for a font name,but we keep it for compatibility with older Ghostscript versions,which do so due to a historical reason.Add a proper record to lib/cidfmap to provide it.

Please note that when a PDF font resource specifies

/Regi
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生