0% found this document useful (0 votes)
993 views460 pages

Ghostscript

This documentation covers how to build, install, use and interface with the Ghostscript software. It includes sections on building Ghostscript from source code for various platforms, installing on Unix and Windows, using Ghostscript for different file types and interfaces, its API, and language bindings.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
993 views460 pages

Ghostscript

This documentation covers how to build, install, use and interface with the Ghostscript software. It includes sections on building Ghostscript from source code for various platforms, installing on Unix and Windows, using Ghostscript for different file types and interfaces, its API, and language bindings.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 460

Ghostscript Documentation

Release 10.01.0

Artifex

Mar 10, 2023


CONTENTS

1 Introduction 1
1.1 What is Ghostscript? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 Document roadmap by theme . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Presence on the World Wide Web . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

2 How to Build Ghostscript from Source Code 5


2.1 General overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2 Built libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.3 How to acquire the source code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.4 How to acquire the development source code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.5 How to unpack the source code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.6 How to check for post-release bug fixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.7 How to prepare the makefiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.8 How to build Ghostscript from source (PC version) . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.9 How to build Ghostscript from source (MacOS version) . . . . . . . . . . . . . . . . . . . . . . . . 16
2.10 How to build Ghostscript from source (Unix version) . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.11 Other environments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.12 How to build Ghostscript with UFST . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

3 How to Install Ghostscript 23


3.1 Overview of how to install Ghostscript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.2 Installing Ghostscript on Unix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.3 Installing Ghostscript on MS Windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.4 Installing Ghostscript on OpenVMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

4 Using Ghostscript 29
4.1 Invoking Ghostscript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.2 Selecting an output device . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.3 Interacting with pipes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
4.4 Using Ghostscript with PDF files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
4.5 Using Ghostscript with EPS files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
4.6 Using Ghostscript with overprinting and spot colors . . . . . . . . . . . . . . . . . . . . . . . . . . 39
4.7 How Ghostscript finds files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
4.8 Notes on specific platforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
4.9 Command line options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
4.10 Improving performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
4.11 Summary of environment variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
4.12 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
4.13 Appendix: Paper sizes known to Ghostscript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

i
5 API 89
5.1 What is the Ghostscript Interpreter API? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
5.2 Exported functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
5.3 Callouts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
5.4 Return codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
5.5 Example Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
5.6 Multiple Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
5.7 Standard Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
5.8 Display Device . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106

6 Language Bindings 115


6.1 The C API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
6.2 Licensing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
6.3 Demo code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
6.4 C# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
6.5 Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
6.6 Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169

7 Details of Ghostscript Output Devices 181


7.1 Notes on measurements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
7.2 Image file formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
7.3 Optical Character Recognition (OCR) devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
7.4 High level devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
7.5 Display devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
7.6 IJS - Inkjet and other raster devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
7.7 Rinkj - Resplendent inkjet driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
7.8 HP Deskjet official drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
7.9 Gimp-Print driver collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
7.10 MS Windows printers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
7.11 Sun SPARCprinter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
7.12 Apple dot matrix printer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
7.13 Special and Test devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203

8 High Level Devices 207


8.1 PCL-XL (PXL) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
8.2 Text output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
8.3 DOCX output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
8.4 XPS file output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
8.5 The family of PDF and PostScript output devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
8.6 Creating a PDF/X-3 document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
8.7 Creating a PDF/A document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
8.8 Ghostscript PDF Printer Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
8.9 pdfmark extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
8.10 Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227

9 The Interface between Ghostscript and Device Drivers 229


9.1 Adding a driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
9.2 Keeping things simple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
9.3 Driver structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
9.4 Coordinates and types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
9.5 Coding conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
9.6 Printer drivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
9.7 Printer drivers (Multi-threaded) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
9.8 Driver procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
9.9 Tray selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264

ii
10 Ghostscript and the PostScript Language 267
10.1 Ghostscript’s capabilities in relation to PostScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
10.2 Implementation limits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
10.3 Additional operators in Ghostscript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
10.4 Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
10.5 Device parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
10.6 User parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
10.7 Miscellaneous additions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
10.8 Scripting the PDF interpreter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287

11 The Ghostscript Library 291


11.1 PostScript operator API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
11.2 Visual Trace instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
11.3 A full example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298

12 Information for Ghostscript Developers 301


12.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
12.2 Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
12.3 Design principles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
12.4 File roadmap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
12.5 Memory management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
12.6 Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
12.7 Profiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337

13 Ghostscript C Coding Guidelines 339


13.1 C language do’s and don’ts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
13.2 Language extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
13.3 Stylistic conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
13.4 File structuring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
13.5 Ghostscript conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353

14 Ghostscript PostScript Coding Guidelines 357


14.1 Summary of the coding guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
14.2 Use of PostScript language features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
14.3 Commenting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
14.4 Formatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
14.5 Naming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
14.6 Miscellany . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362

15 Convert PostScript to Encapsulated PostScript Interchange Format 363


15.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
15.2 Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 363
15.3 Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
15.4 Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364

16 PostScript Files Distributed with Ghostscript 365


16.1 Generally used system files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
16.2 Configuration files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
16.3 More obscure system files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
16.4 PDF-specific system files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
16.5 Display PostScript-specific system files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
16.6 Art and examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
16.7 Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
16.8 Development tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
16.9 Odds and ends . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372

iii
17 Fonts and Font Facilities Supplied with Ghostscript 373
17.1 About Ghostscript fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
17.2 Ghostscript’s free fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
17.3 How Ghostscript gets fonts when it runs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
17.4 Adding your own fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
17.5 For developers only . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375

18 Ghostscript Color Management 381


18.1 Author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
18.2 Abstract . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
18.3 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
18.4 Overall Architecture and Typical Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
18.5 PDL Color Definitions and ICC Profiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
18.6 Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
18.7 Details of objects and methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391
18.8 ICC Color, the Display List and Multi-Threaded Rendering . . . . . . . . . . . . . . . . . . . . . . 397
18.9 PDF and PS CIE color space handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
18.10 DeviceN and Separation colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
18.11 PCL and XPS Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
18.12 Figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
18.13 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400

19 Setting Up a Unix lpr Filter for Ghostscript 407


19.1 What it can do . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
19.2 Setting it up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407

20 News 411

21 Guide to Ghostscript Source Code 413


21.1 Conceptual overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
21.2 PostScript interpreter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
21.3 PDF interpreter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414
21.4 Graphics library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414
21.5 Makefiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415

22 Third Party Libraries Used by Ghostscript and GhostPDL 417

23 Unsupported devices 419


23.1 H-P 8xx, 1100, and 1600 color inkjet printers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
23.2 H-P 812, 815, 832, 880, 882, 895, and 970 color inkjet printers . . . . . . . . . . . . . . . . . . . . 421
23.3 H-P color inkjet printers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
23.4 Canon BJC-8200 printer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
23.5 Other Canon BubbleJet (BJC) printers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
23.6 Epson Stylus color printer (see also uniprint) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
23.7 uniprint, a flexible unified printer driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445

iv
CHAPTER

ONE

INTRODUCTION

This document is a roadmap to the Ghostscript documentation. After looking through it, if you want to install
Ghostscript and not only use it, we recommend you read How to install Ghostscript, and How to compile Ghostscript
from source code (which is necessary before installing it on Unix and VMS systems).

1.1 What is Ghostscript?

There are various products in the Ghostscript family; this document describes what they are, and how they are related.

1.1.1 Ghostscript

Ghostscript is an interpreter for PostScript® and Portable Document Format (PDF) files.
Ghostscript consists of a PostScript interpreter layer, and a graphics library. The graphics library is shared with all the
other products in the Ghostscript family, so all of these technologies are sometimes referred to as Ghostscript, rather
than the more correct GhostPDL.
Binaries for Ghostscript and (see below) GhostPDF (included in the Ghostscript binaries) for various systems can be
downloaded from here. The source can be found in both the Ghostscript and GhostPDL downloads from the same site.

1.1.2 GhostPDF

Prior to release 9.55.0 GhostPDF was an interpreter for the PDF page description language built on top of Ghostscript,
and written in the PostScript programming language. From 9.55.0 onwards there is a new GhostPDF executable,
separate from Ghostscript and written in C rather than PostScript.
This new interpreter has also been integrated into Ghostscript itself, in order to preserve the PDF functionality of
that interpreter. For now, the old PostScript-based interpreter remains the default, but the new interpreter is built-in
alongside it.
The intention is that the new interpreter will replace the old one, which will be withdrawn.
It is possible to control which interpreter is used with the NEWPDF command-line switch. When this is false (the
current default) the old PostScript-based interpreter is used, when NEWPDF is true then the new C-based interpreter
is used.

1
Ghostscript Documentation, Release 10.01.0

1.1.3 GhostPDL

Historically, we’ve used GhostPDL as an umbrella term to encompass our entire line of products. We’ve now brought
all these disparate products together into a single package, called, appropriately enough, GhostPDL.
When running on a printer (or server) GhostPDL now automatically detects the type of data being fed to it and pro-
cesses it accordingly. The individual interpreters all plug into a top-level module that handles both automatic language
detection and Printer Job Language (PJL) based configuration.
The exact set of interpreters present in an installation can be tuned by the integrator for their specific product/use cases.
In addition to our existing PDL modules (PS, PDF, PCL, PXL, and XPS) we have now added new modules to handle
a range of common image formats. With these installed, GhostPDL will handle JPEGs (both JFIF and EXIF), PWGs,
TIFFs, PNGs, JBIG2s, and JPEG2000s.
GhostPDL is available both under the GNU Affero GPL license and for commercial licensing from Artifex.
The source code for GhostPDL can be found here.

1.1.4 GhostPCL

GhostPCL is an interpreter for PCL™ and PXL files. This consists of an PCL/PXL interpreter hooked up to the
Ghostscript graphics library.
GhostPCL is available both under the GNU Affero GPL license and for commercial licensing from Artifex.
Binaries for GhostPCL for various systems can be downloaded from here. The source can be found in the Ghost-
PCL/GhostPDL downloads from the same site.

1.1.5 GhostXPS

GhostXPS is an interpreter for XPS (XML Paper Specfication) files. This consists of an XPS interpreter hooked up to
the Ghostscript graphics library.
GhostXPS is available both under the GNU Affero GPL license and for commercial licensing from Artifex.
Binaries for GhostXPS for various systems can be downloaded from here. The source can be found in the
GhostXPS/GhostPDL downloads from the same site.

1.1.6 URW Font Information

The set of truetype fonts in the urwfonts directory are necessary for the PCL/XL interpreter to function properly but they
ARE NOT FREE SOFTWARE and are NOT distributed under the GNU GPL/AGPL. They can instead be redistributed
under the AFPL license which bars commercial use.
If your copy of GhostPDL includes these fonts, you should have received a copy of the Aladdin Free Public License,
usually in a file called COPYING.AFPL. If not, please contact Artifex Software, Inc. 1305 Grant Avenue - Suite 200,
Novato, CA 94945 USA, or visit Artifex

2 Chapter 1. Introduction
Ghostscript Documentation, Release 10.01.0

1.2 Document roadmap by theme

1.2.1 What should I read if I’m a new user?

• How to use Ghostscript. This includes both a quickstart introduction to the command line version and more
extensive reference material.
• detailed information about specific devices that Ghostscript can use for output.
• more detailed information about how to use Ghostscript under Unix with lpr as a filter for printing.
• for information about known problems or to report a new one, please visit bugs.ghostscript.com but remember
that free versions of Ghostscript come with with NO WARRANTY and NO SUPPORT.

1.2.2 GPL and commercial Ghostscript

GPL Ghostscript, Artifex Ghostscript and AFPL Ghostscript are different releases.
• additional information about GPL Ghostscript releases that is not relevant to commercial versions.
If you run into any questions, or if you are going to be using Ghostscript extensively, you should at least skim, and
probably eventually read:
• about the fonts distributed with Ghostscript, including how to add or replace fonts.
• a description of the Ghostscript language, and its differences from the documented PostScript language.
• about the postscript files distributed with Ghostscript (other than fonts).

1.2.3 Before building Ghostscript

If you are going to compile Ghostscript from source, rather than just use an executable you got from somewhere, you
may want to read:
• How to build Ghostscript and install it.

1.2.4 What should I read if I’m not a new user?

If you have already used Ghostscript, when you receive a new release you should begin by reading this file, then:
• News, for incompatible changes and new features in the current release.

1.2.5 What if I’m a developer?

If you are going to do any development on or with Ghostscript at all, you should at least look at:
• the roadmap documentation for Ghostscript’s source files and architecture.
If you are going to write a new driver for Ghostscript, you should read:
• the guide to the Ghostscript source code.
• the interface between Ghostscript and device drivers.
If you are considering distributing GPL Ghostscript in conjunction with a commercial product, you should read the
license carefully, and you should also read:

1.2. Document roadmap by theme 3


Ghostscript Documentation, Release 10.01.0

• additional clarification of the circumstances under which Ghostscript can be distributed with a commercial prod-
uct.
If you intend to use Ghostscript in the form of a dynamic link library (DLL) under OS/2 or Microsoft Windows or in
the form of shared object under Linux, read:
• documentation on Ghostscript Interpreter API.
If you want to use Ghostscript as part of another program, as a callable PostScript language interpreter, and not as a
DLL or as a self-contained executable application, you should begin by reading:
• the source file imain.h, the documented API for Ghostscript not as a DLL.
or if you are going to use only the Ghostscript graphics library:
• about the structure of the Ghostscript library and its interfaces.

1.2.6 What if I’m writing documentation?

If you are editing or adding to Ghostscript’s existing documentation you should contact us on our Discord channel or
the gs-devel mailing list for guidance, links to those are on: www.ghostscript.com.

1.3 Presence on the World Wide Web

1.3.1 Ghostscript’s home page

Ghostscript has a home page on the World Wide Web with helpful information such as the FAQ (Frequently Asked
Questions):
www.ghostscript.com

1.3.2 Other material on the WWW

Much other material about Ghostscript is available on the World Wide Web, both as web pages and as archived Usenet
and mailing list discussions. Use the well-known search engines to find such material.

4 Chapter 1. Introduction
CHAPTER

TWO

HOW TO BUILD GHOSTSCRIPT FROM SOURCE CODE

2.1 General overview

This document describes how to build a Ghostscript executable from source code. There are four major steps to building
Ghostscript:
1. Acquire the compressed archive files of source code for Ghostscript.
2. Unpack the archive files into the Ghostscript directory.
3. Configure the build to match your system and desired configuration options.
4. Invoke “make” to build the software.
The remainder of this document describes each of these steps in detail. Note that some of this process is platform-
dependent. After building Ghostscript you must then install it; for that, see the installation instructions.
Long term users of Ghostscript may notice the instructions for a number of older systems have been removed from this
document. There is no value judgment implied in this, but recognition that the build system has changed considerably
in recent years, and several of these legacy systems are no longer easily available to the development team. We will
always consider contributions to continue support for legacy systems.

2.2 Built libraries

The following Ghostscript libraries will be built for these respective platforms:

Platform Ghostscript library files


Windows 32-bit gpdldll32.dll gsdll32.dll
Windows 64-bit gpdldll64.dll gsdll64.dll
MacOS libgpdl.dylib libgs.dylib
Linux / OpenBSD libgpdl.so libgs.so

Note: The actual filenames on MacOS will be appended with the version of Ghostscript with associated symlinks.

5
Ghostscript Documentation, Release 10.01.0

2.3 How to acquire the source code

Building Ghostscript requires the Ghostscript source code itself, and in some cases the source code for the third-party
libraries that Ghostscript uses.
Official releases can be found under the AGPL license at:
https://ghostscript.com/download/
Ghostscript source code is packaged in gzip-compressed tar archives (*.tar.gz), e.g.:
ghostscript-#.##.tar.gz
(“#.##” are version numbers.)
Software to decompress and extract both formats is available for almost every platform for which Ghostscript is available
– including Unix, Linux, MS Windows, and so on – but it’s up to you to locate that software. See the section on
unpacking the source code.

Note: Unlike earlier versions, Ghostscript packages are now one, complete archive, including font files and third party
library dependency sources.

2.4 How to acquire the development source code

The Ghostscript team use git for version control.


If you require a snapshot of the development code, the easiest way to get it is to visit the web interface to our git
repository: ghostpdl.git and click the “snapshot” link next to the specific commit in which you are interested. After a
short delay, that will download a complete source tree for the given commit in a gzipped tar archive.
If you require access to several commits, or wish to regularly access the latest development code, you are better to clone
the entire git repository, using:

git clone git://git.ghostscript.com/ghostpdl.git

which will create a local, read-only repository.


Both the “snapshot” and the git clone methods download the Ghostscript sources as part of the GhostPDL source tree,
which includes the PCL/PXL and XPS interpreters also built on top of the Ghostscript graphics library.
The configure script discussed later in the document is created as part of the Ghostscript release process, and as the
source tree retrieved from git is “pre-release” code, it does not include a pre-made configure script. See autogen.sh.

2.5 How to unpack the source code

Unfortunately, there are no generally accepted standards for how to package source code into archives, so the instructions
for unpacking Ghostscript are longer than they should be. We begin with a brief explanation of how to extract the two
kinds of archive files.

6 Chapter 2. How to Build Ghostscript from Source Code


Ghostscript Documentation, Release 10.01.0

2.5.1 How to unpack compressed tar files generally

Tar (.tar) files are the de facto standard for archiving files on Unix (every Unix-like system has the tar program),
and programs to extract their contents are also widely available for MS Windows, and most other environments. To
economize on space and downloading time, Ghostscript’s tar files are compressed with GNU gzip, which adds the
suffix “.gz” to the file name, giving “.tar.gz”.
To unpack a compressed tar file MyArchive.tar.gz you must both decompress it and extract the contents. You can
do this in two steps, one to decompress the file and another to unpack it:

gzip -d MyArchive.tar.gz
tar -xf MyArchive.tar

or in a pipeline:

gzip -d -c MyArchive.tar.gz | tar -xf -

or, if you have a program like GNU tar that can handle compressed tar files, with a single command:

tar -zxf MyArchive.tar.gz

The tar program automatically preserves directory structure in extracting files. The Ghostscript source archive puts
all files under a directory ghostscript-#.##, so using tar to unpack a compressed archive should always properly
create that directory, which we will call the “ghostscript directory”.
Some other programs – under MS Windows, for instance – can also unpack compressed tar files, but they may not
automatically preserve directory structure nor even extract files into the current directory. If you use one of these, you
must:
• set the program’s options to “Use folder names” (or the equivalent).
, and:
• check that it is extracting files into the right place.
As both tar and gzip formats are now well supported by several applications on MS Windows, we only supply the
tar.gz archive.
WinZip, 7-zip & Info-ZIP are respectively a commercial and two free applications which can decompress and extract
.tar.gz archives on MS Windows.

2.5.2 How to unpack Ghostscript itself

At this point you have acquired the source code and are ready to unpack it according to the preceding guidelines.
2-step:

gzip -d ghostscript-#.##.tar.gz
tar -xf ghostscript-#.##.tar

Pipe:

gzip -d -c ghostscript-#.##.tar.gz | tar -xf -

GNU tar:

tar -zxf ghostscript-#.##.tar.gz

All the Ghostscript source files are now in subdirectories of the ghostscript-#.## directory.

2.5. How to unpack the source code 7


Ghostscript Documentation, Release 10.01.0

2.5.3 Ghostscript Core Source subdirectories

Subdirectory Contents
arch/ Pre-defined architecture header files
base/ Graphics library C source code and makefiles
contrib/ Community contributed/supported output devices
devices/ The output devices supported by the Ghostscript
team
psi/ PS interpreter C source code and makefiles
Resource/ Postscript initialization, resource and font files
lib/ PostScript utilities and scripts used with
Ghostscript
doc/ Documentation
man/ Unix man pages
examples/ Sample PostScript files
iccprofiles/ Default set of ICC profiles
windows/ Visual Studio for Windows specific project and
solution files
toolbin/ Useful (non-Postscript) tools, mostly for devel-
oper use only

Optionally, if you downloaded the GhostPDL archive, you may also have:

2.5.4 Additional GhostPDL source subdirectories

Subdirectory Contents
pcl/ PCL/PXL interpreter C source code, makefiles,
fonts etc.
xps/ XPS interpreter C source code and makefiles

Supporting third party libraries will also be in their own sub-directories (e.g. jpeg, freetype and so on).

2.6 How to check for post-release bug fixes

Bug information and fixes are tracked on Ghostscript Bugzilla.

2.7 How to prepare the makefiles

The Ghostscript makefiles are very large and complex in order to deal with the diverse requirements of all the different
systems where they may be used.
Ghostscript has an automatic configuration script. If you’re on unix or a system that supports unix shell scripts, this is
the easiest option to use. Simply type:

./configure

8 Chapter 2. How to Build Ghostscript from Source Code


Ghostscript Documentation, Release 10.01.0

from the top level of the Ghostscript source directory. It should configure itself based on what’s available on your
system, warn you of any missing dependencies, and generate a Makefile. At this point you can skip to the section
invoking make below. Also, many common configuration options (like install location) can be set through options to
the configure script.
Type ./configure --help for a complete listing. Note that the configuration option is only available with the unix
.tar distributions of the source.

Note: If you’re building Ghostscript from development source out of a repository instead of from a released
source package, you should run ./autogen.sh instead of ./configure. This script takes all the same options that
configure does.

If your system doesn’t support the configure script or you don’t wish to use it, you can use the traditional Ghostscript
makefile system, editing the options by hand to match your system as described below. Fortunately, the only
makefiles you’re likely to want to change are relatively small ones containing platform-specific information.

2.7.1 Platform-specific makefiles

Makefile Used for


Makefile.in Template makefile for the autoconf build.
psi/msvc.mak MS Windows with Microsoft Visual Studio 2003 and
later.
base/unix-gcc.mak Unix with gcc.
base/unixansi.mak Unix with ANSI C compilers other than gcc.

A number of platform indepdent makefiles in each of the core Ghostscript source directories. Since these files can
change from one Ghostscript version to another, sometimes substantially, and since they all include documentation for
the various options, here we don’t duplicate most of that documentation: we recommend strongly that you review the
entire makefile specific for your operating system and compiler before building Ghostscript.

2.7.2 Changes for your environment

Assuming you have opted not to use the configure script or the default Microsoft Visual Studio bulid, you must edit
the platform-specific makefile to change any of these:
• The name of the makefile itself (MAKEFILE macro).
• The locations to install Ghostscript files (prefix etc.).
• The default search paths for the initialization and font files (GS_LIB_DEFAULT macro).
• The debugging options (DEBUG and TDEBUG macros).
• Which optional features to include (FEATURE_DEVS).
• Which device drivers to include (DEVICE_DEVS and DEVICE_DEVS{1--20} macros).
• Default resolution parameters for some printer drivers (devs.mak or contrib.mak, whichever defines the
driver).
In general these will be set to commonly sensible values already, but may not be ideal for your specific case.
The platform-specific makefiles include comments describing all these except the DEVICE_DEVS options. These are
described in devs.mak and contrib.mak, even though the file that must be edited to select them is the platform-
specific makefile.

2.7. How to prepare the makefiles 9


Ghostscript Documentation, Release 10.01.0

Some platform-specific options are described in the sections for individual platforms. See the “Options” section near
the beginning of the relevant makefile for more information.

2.7.3 Selecting features and devices

You may build Ghostscript with any of a variety of features and with any subset of the available device drivers. The
complete list of features is in a comment at the beginning of gs.mak, and the complete list of drivers in comments at
the beginning of devs.mak and contrib.mak. To find what devices a platform-specific makefile selects to include
in the executable, look in it for all lines of the form:

FEATURE_DEVS={list of features}
DEVICE_DEVS*={list of devices}

For example, if the makefile has:

FEATURE_DEVS=$(PSD)level2.dev

indicating that only the PostScript Level 2 facilities should be included, you might make it:

FEATURE_DEVS=$(PSD)level2.dev $(PSD)pdf.dev

to add the ability to interpret PDF files. (In fact, FEATURE_DEVS in the current Unix makefiles already includes
$(PSD)pdf.dev.).
It is extremely important that FEATURE_DEVS is set correctly. Currently, the default builds will include a complete
feature set, and as such most of those building Ghostscript will have no need to change it. Only those working in
heavily resource constrained environment will want to experiment, and it is vital that the implications of such changes
be understood, otherwise Ghostscript may behave in unexpected or apparently incorrect ways, or may even fail to build.
The Unix makefile also defines:

DEVICE_DEVS=$(DD)x11.dev

indicating that the X Windows driver should be included, but since platform-specific makefiles as distributed nor-
mally include many of the possible features and drivers, you will probably rather remove from the makefile the features
and drivers you don’t want. It does no harm to include unneeded features and devices, but the resulting executable will
be larger than needed.
You may edit the FEATURE_DEVS line to select or omit any of the features listed near the beginning of gs.mak, and the
DEVICE_DEVS* lines to select or omit any of the device drivers listed near the beginning of devs.mak and contrib.
mak. GS_DEV_DEFAULT is a string containing whitespace separate device names, and give the devices Ghostscript
should attempt to use (and the order) if no device is specified on the command line; see the usage documentation for
how to select an output device at run time using the -sDEVICE= switch. If you can’t fit all the devices on a single line,
you may add lines defining:

DEVICE_DEVS1=$(DD){dev11}.dev ... $(DD){dev1n}.dev


DEVICE_DEVS2=$(DD){dev21}.dev ... $(DD){dev2n}.dev

etc., up to DEVICE_DEVS15. Don’t use continuation lines – on some platforms they don’t work.

Note: If you want to include a driver named xxx, you must put $(DD)xxx.dev in DEVICE_DEVS*. Similarly, if you
want to include a feature related to the PostScript or PDF language interpreters (PostScript level 1 .. 3, or other language
features such as the ability to read EPSF files or TrueType font files), you must represent it as $(PSD)xxx.dev.

10 Chapter 2. How to Build Ghostscript from Source Code


Ghostscript Documentation, Release 10.01.0

Precompiled run-time data

Ghostscript normally reads a number of external data files at run time: initialization files containing PostScript code,
fonts, and other resources such as halftones. By changing options in the top-level makefile for the platform, you can
cause some of these files to be compiled into the executable: this simplifies installation, improves security, may reduce
memory requirements, and may be essential if you are planning on putting Ghostscript into ROM. Compiling these
files into the executable also means the executable is (largely) self-contained, meaning initialization files, font files,
resource files and ICC profile files are certain to be available and accessible. In general, Ghostscript should initialize
more quickly, and files (especially PDF) files making heavy use of the built-in fonts will interpret more quickly.
For those distributing Ghostscript binaries, compiling those files into the executable has another implication, any site-
specific customizations (such as font and CIDFont substitutions) are slightly more complex to implement - see: How
Ghostscript finds files for how to influence where Ghostscript searches for files. Furthermore, if the files Ghostscript
uses are also required to be accessible by applications other than Ghostscript (the mostly case for this would be font files
and ICC profile files), having those files compiled into Ghostscript maybe suboptimal, essentially require two copies
of the file data to be distributed (one set built into Ghostscript, and the other as “normal” files accessible outside of
Ghostscript.
Compiling the initialization files (Resource/Init/gs_init.ps, etc.) into the executable is the default. To disable
this, change the 1 to a 0 in the line:

COMPILE_INITS=1

Or, if you use the configure based Unix-style build, you can disable COMPILE_INITS by adding the option
--disable-compile-inits to the invocation of configure
Files are now compiled into the executable as a %rom% file system that can be searched, opened, etc. as with the normal
(%os%) file system. The data is (mostly) compressed. Several of the initialisation files (those in Resource/Init) are
also converted to binary Postscript encoding, and “merged” into a single monolithic file - this is done for both size and
speed optimization. Files that are often customized for individual installations (such as Fontmap and cidfmap) are not
merged into the single file and thus installation specific versions can be used.
The set of files built into the %rom% file system is specified in the psi/psromfs.mak file. By default the set of files
built into the rom file system comprises all the resource files Ghostscript requires to run successfully (all the files under
Resource directory, and those under the iccprofiles directory). Refer to the file base/mkromfs.c for a description
of the parameters that control source and destination pathnames, file enumeration exclusion, compression, etc.
Fonts normally are compiled into the executable using mkromfs (above) from the Resource/Font/ directory.
Similarly, Halftone resources can be compiled into the executable using mkromfs, but also threshold-array halftones can
be compiled into the executable. See the “Compiled halftone” section of int.mak for a sample makefile fragment,
genht.c for the syntax of halftone data files, and lib/ht_ccsto.ps for a sample data file. Note that even though the
data files use PostScript syntax, compiled halftones do not require the PostScript interpreter and may be used with the
graphics library alone.

2.7.4 Setting up “makefile”

After going through the steps just described to unpack the sources, configure the build and make any desired changes
to the makefiles. As the final step in preparing to build Ghostscript you must usually associate the name “makefile”
with the correct makefile for your environment so the make command can find it. See the section on your particular
platform for how to do that if necessary.
On unix systems, ./configure (or if checked out of git, ./autogen.sh) should create a Makefile which works in
most scenarios. Manual tampering and editing should rarely be needed nor recommended.

2.7. How to prepare the makefiles 11


Ghostscript Documentation, Release 10.01.0

2.7.5 Invoking “make”

make
Builds Ghostscript without debugging options.
make debug
Builds Ghostscript with debugging options and additional internal error checks. The program will be somewhat
larger and slower, but it will behave no differently unless you actually turn on debugging options at execution
time with the -DDEBUG or -Z command line switches described in the usage documentation.
make pg
On Unix platforms, builds with the -pg compiler switch, creating an executable for time profiling.
make install
After building, installs the Ghostscript executables, support files, and documentation, but does not install fonts.
See the installation documentation.
make (debug)clean
Deletes all the files created by the build process (relocatables, executables, and miscellaneous temporary files).
If you’ve built an executable and want to save it, move it first to another place, because “make clean” deletes it.
make so
On some platforms (Linux, *BSD, Darwin/Mac OS X, SunOS), it is possible to build Ghostscript as a shared
object library. There is a corresponding make soclean for cleaning up.
make sanitize
Builds Ghostscript with AddressSanitizer. Output is placed in ./sanbin.
make libgs
Builds static library for Ghostscript.
make libgpcl6
Builds static library for GhostPCL. Requires the full ghostpdl source release.
make libgxps
Builds static library for GhostXPS. Requires the full ghostpdl source release.
make libgpdl
Builds static library for GhostPDL. Requires the full ghostpdl source release.

Note:
• On some platforms aspects of these simple instructions don’t quite work in one way or another. Read the section
on your specific platform.
• If you are attempting to build a statically linked executable, you will probably need to add libraries to the linker
options (libraries that are normally pulled-in automatically by the dynamic linker). These can be added at the
make command line using the EXTRALIBS= option. Unfortunately, the set of libraries that may be required varies
greatly depending on platform and configuration, so it is not practical to offer a list here.

12 Chapter 2. How to Build Ghostscript from Source Code


Ghostscript Documentation, Release 10.01.0

2.7.6 Cross-compiling

Cross-compiling is not fully supported by the configure script (such support is a work-in-progress).
You can either use base/unixansi.mak or unix-gcc.mak as the basis for a cross-compile makefile, or use config-
ure to create a basic Makefile as the basis. And modify to suit.
You can set the compiler to your cross-compiler for configure by doing:

./configure CC=<cross-compiler executable>

and configure will then run its checks (as best it can) with the cross-compiler.
If you do so, you should also give configure the option to set the target architecture endianness: --enable-big-endian
or --enable-little-endian.
It would also be wise to review the settings shown in the output of ./configure --help for any that would be
applicable to your target.
The Ghostscript build system uses several interim executables, built and run on the host, as such, even when cross-
compiling, a host native compiler is also required. You must edit your makefile to ensure that is available. Find the
line that starts:
CCAUX=
and set that to your host compiler.
If you did not use configure or did not set the CC variable for configure, you must also set the:
CC=
to your cross-compiler.
The Ghostscript build system uses a utility called genarch (see base/genarch.c for details) to interrogate the envi-
ronment and generate a header file describing the architecture for which Ghostscript is being built. As this is run on
the host it will generate header for the host architecture rather than that of the target.
For cross compiling, you must create (or modify) a header file (arch.h) which accurately describes the target
architecture. Then you must edit your makefile by finding the line:
TARGET_ARCH_FILE=
and set it to the path to, and file name of your custom arch.h file. With that setting, genarch will still be run, but
rather than interrogate the current environment, it will copy the contents of your custom arch.h to the build.

2.8 How to build Ghostscript from source (PC version)

All Ghostscript builds in PC (DOS and MS Windows) environments are 32- or 64-bit: 16-bit builds are not supported.
The relevant makefiles are:

Makefile Construction tools For environment


msvc.mak Microsoft Visual Studio .NET 2003 (or later) MS Windows 32/64-bit
Makefile.in Cygwin/gcc Cygwin (Use Unix configure)

Ghostscript requires at least MS Windows 95 (although we no longer actively test nor support Win95, we have not
deliberately done anything to break compatibility with it). We recommend at least MS Windows NT 4.0.
For building, Ghostscript requires at least Visual Studio .NET 2003, and we recommend at least Visual Studio 2005
(required for 64 bit Windows support).

2.8. How to build Ghostscript from source (PC version) 13


Ghostscript Documentation, Release 10.01.0

Note: The make program supplied with Visual Studio (and earlier Visual C++ versions) is actually called nmake. We
refer to this program generically as make everywhere else in this document.

You must have cmd.exe in your path to build Ghostscript (using the Visual Studio command prompt is ideal). After
making any changes required to choose features and devices to build into the executable, you can then invoke make to
build the executable.

2.8.1 Microsoft Visual Studio

Using Microsoft Visual Studio

To build the required DLLs, load /windows/ghostpdl.sln into Visual Studio, and select the required architecture
from the drop down - then right click on ‘ghostpdl’ in the solution explorer and choose “Build”.

Further details

The Ghostscript source distribution ships with project and solution files for Visual Studio 2005 and later. These
can be found in the windows directory. The project(s) are nmake projects which means that rather than Visual
Studio controlling the build directly, it delegates the build process to the nmake.
Beyond lacking support for parallel builds (nmake cannot support parallel builds), there should be little visible differ-
ence between a conventional VS project and an nmake project to the user of the VS graphical interface. The only
exception to that is if you have to make changes to build options beyond those available in the defined build configura-
tions. In that case, you need to find the Nmake tab in the project Property Pages and modify the appropriate entry:
Build Command Line, Rebuild All Command Line and/or Clean Command Line.
As mentioned above, nmake does not support parallel builds. If you have downloaded and are building the GhostPDL
source archive (which contains Ghostscript, GhostPCL, GhostXPS, and GhostPDL “products”), the GhostPDL.sln
contains individual projects for each product but, as a result of the limitations of nmake the products cannot be built in
parallel, because nmake's lack of parallel build awareness means it cannot manage the dependencies shared between
the products, and may fail as multiple builds attempt to access the same dependencies.
To build all the products in one action, use the All “pseudo-project”. The All project uses a single nmake invocation
to build all the supported products.

Note: Changing the Output property in the Nmake properties will not change the name of the executable - to do that
requires editing of the psi/msvc.mak makefile, or you can add: GS=myname.exe to the nmake command line.

Using the command line

Ghostscript can be made using the Windows command prompt or one of the various command line shells made for
Windows, as long as the command line syntax is compatible with the Windows CMD.exe. The Visual Studio command
prompt is ideal.
In order for the makefiles to work properly, two items may have to be changed. An attempt is made to select the correct
version of Microsoft Visual C++ based on the version of nmake. If this doesn’t work it will default to version 6.x. If the
auto-detection does not work, and you are not using version 6.x then before building, in psi\msvc.mak find the line
#MSVC_VERSION=6 and change it to MSVC_VERSION=4, MSVC_VERSION=5, MSVC_VERSION=7 or MSVC_VERSION=8
and so on.

14 Chapter 2. How to Build Ghostscript from Source Code


Ghostscript Documentation, Release 10.01.0

In some cases the location of the Microsoft Developer Studio, needs to be changed. The location of Microsoft Developer
Studio is defined by the value of DEVSTUDIO. There are several different definitions of DEVSTUDIO in psi\msvc.mak.
There is one for each of the currently supported versions of Microsoft Visual C++ (4, 5, 6, 7, 7.1 and 8).
The normal installation process for Microsoft Visual C++ includes setting the location of the Microsoft Visual C++
executables (cl.exe, link.exe, nmake.exe, rc.exe) in your PATH definition and the LIB and INCLUDE environment
variables are set to point to the Microsoft Visual C++ directories. If this is true then the value for DEVSTUDIO can be
changed to empty, i.e. DEVSTUDIO=
If PATH, LIB, and INCLUDE are not correctly set then the value for DEVSTUDIO needs to be defined. For example,
for version 6.0, the default definition for the location for the Microsoft Developer Studio is: DEVSTUDIO=C:\Program
Files\Microsoft Visual Studio If the path to Microsoft Developer Studio on your system differs from the default
then change the appropriate definition of DEVSTUDIO. (Remember that there is a separate definition of DEVSTUDIO for
each version of MSVC, so be sure to change the correct definition.)
To run the make program, give the command:

nmake -f psi\msvc.mak

Rather than changing psi/msvc.mak, these values can also be specified on the make command line, i.e.

nmake -f psi\msvc.mak MSVC_VERSION=6 DEVSTUDIO="C:\Program Files\Microsoft Visual Studio"


nmake -f psi\msvc.mak MSVC_VERSION=7 DEVSTUDIO="C:\Program Files\Microsoft Visual Studio␣
˓→.NET"

Note that double quotes have been added around the path for DEVSTUDIO due to the spaces in the path value.
This command line can also be put into a batch file.
You may get warning messages during compilation about various undefined and/or unsupported switches - this is
because the compiler switches are set in the makefiles, and are applied when building with all versions of Visual
Studio, but not all options are supported (or required) by all versions of Visual Studio. These warnings are benign and
can be ignored.

2.8.2 Microsoft Environment for 64-bit

Building Ghostscript for 64-bit Windows (AMD64 processor) requires Microsoft Visual Studio .NET 2005 or Microsoft
Visual Studio 2008 or later on 64-bit Windows. Cross compiling on 32-bit Windows is possible.
Compiling for 64-bit is similar to the Microsoft Environment instructions above, but with the addition of a WIN64
define.
To make Ghostscript use:

nmake -f psi/msvc.mak WIN64=

Making self-extracting installers

You can build self-extracting Windows installers based on NSIS (Nullsoft Scriptable Install System). To do so, use the
nsis makefile target as well as any other options, for example:

nmake -f psi/msvc.mak WIN64= nsis

will create an nsis based installer for Ghostscript built for 64 bit Windows systems.

2.8. How to build Ghostscript from source (PC version) 15


Ghostscript Documentation, Release 10.01.0

2.8.3 Microsoft Environment for WinRT

Ghostscript can be built in the form of a win32 DLL for use within a Windows Runtime application or Windows
Runtime component. Building for WinRT requires use of Microsoft Visual Studio 2012. There is a solution file that
can be loaded into VS 2012, in the directory winrt.
The WinRT application or component should include iapi.h from gs/psi and link with gsdll32metro.lib from
gs/debugbin or gs/releasebin. Also any app using Ghostscript either directly or via a component should add
gsdll32metro.dll as “content”. This inclusion of the dll is necessary so that it will be packaged with the app. If
one wishes to be able to run the debugger on Ghostscript then gsdll32metro.pdb should also be added as content.

2.8.4 Cygwin32 gcc

It is possible to compile Ghostscript for MS Windows using the Cygwin32 gcc compiler, GNU make, using the “con-
figure” generated Makefile.
Information about this compiler and environment is at the Cygwin site.

MSys/Mingw

The configure build can be used to build Ghostscript on MSys/Mingw systems, but with a caveat. The msys-dvlpr
adds header files into the compiler’s header search paths which cause a clash, and the build will fail as a result. If you
have the msys-dvlpr package installed, and until a better solution is available you can work around this by temporarily
renaming the \mingw\msys\1.0\include directory so those headers are no longer found by the compiler.

2.9 How to build Ghostscript from source (MacOS version)

2.9.1 MacOS X

The unix source distribution (.tar.gz) builds fine on Darwin/MacOS X, albeit without a display device. You can
generally just use the Makefile generated by configure as your top-level makefile and get a reasonable default build.
This will allow you to use Ghostscript from the command line as a BSD-layer tool to rasterize postscript and pdf to
image files, and convert between the high-level formats supported by Ghostscript. See the instructions for the unix
build below for details of how to customize this build.

Note: If you have MacPorts installed, it can “confuse” the configure script because it includes some librares which
duplicate the “system” ones. This can cause missing symbol link errors. In order to resolve this, you can do:
LDFLAGS="-L/usr/lib" ./configure. That will force the linker to search the default directory first, and thus
pick up the system libraries first.

It is also possible to build “universal binaries” for MacOS X, containing i386 and x86_64 binaries in one file, using
the Makefile from configure. This can be achieved by using the following invocation of configure:

./configure CC="gcc -arch i386 -arch x86_64 -arch ppc" CPP="gcc -E"

You can choose the combination of valid architectures (i386/x86_64/ppc) that you require.
The separate options for CC and CPP are required because some of the features used by configure to explore the capa-
bilities of the preprocessor are not compatible with having multiple -arch options.
Building a shared library on MacOS X is the same as for other Unix-like systems, the “configure” step is done normally,
and the “so” target is given to the make invocation, thus:

16 Chapter 2. How to Build Ghostscript from Source Code


Ghostscript Documentation, Release 10.01.0

make so

The only difference compared to other Unix-like systems is that on OS X the resulting shared library is created with
the “.dylib” file name extension, instead of the more usual “.so”.

2.10 How to build Ghostscript from source (Unix version)

Ghostscript now ships with a build system for unix-like operating systems based on GNU Autoconf. In general the
following should work to configure and build Ghostscript:

./configure
make

or

./configure
make so

for building Ghostscript as a shared library.


Please report any problems with this method on your system as a bug.
On modern unix systems, ./configure should create a Makefile which works in most scenarios. Manual tempering
and editing should rarely be needed nor recommended.

Note: If you’re building Ghostscript from development source out of a repository instead of from a released
source package, you should run ./autogen.sh instead of ./configure. This script takes all the same options that
configure does.

(deprecated; see Autoconf-based method above) For the convenience of those already familiar with Ghostscript, the
old method based on hand-edited makefiles is still possible but no longer supported (and in many cases, simply do
not work without substantial expert manual-editing effort). It may also be helpful in getting Ghostscript to build on
very old platforms. The rest of this section deals exclusively with that older method and includes numerous pointers
regarding legacy systems.
(deprecated; see Autoconf-based method above) Before issuing the make command to build Ghostscript, you have to
make some choices, for instance:
• Which compiler to use.
• What features and devices to include.
• Whether to use system libraries for PNG and zlib.
• How to handle issues for your particular platform.
Be sure to check the sections on tool-, OS-, and hardware-specific issues for notes on your particular platform and
compiler. In fact, that is the first place to check if you build Ghostscript and it crashes or produces obviously incorrect
results.

2.10. How to build Ghostscript from source (Unix version) 17


Ghostscript Documentation, Release 10.01.0

2.10.1 make tools

You require a make tool which supports separate directories for the derived objects (such as object files, executables
and dynamically created header files) and the source files.
In general, GNU make is the recommended choice, and some features (such as the building of the Linux/Unix shared
library build (“make so”) are only available with GNU make.
Other make implementations are known to work, but are not guaranteed to do so.

GNU make

Current versions of GNU make have no problems building Ghostscript.

2.10.2 OS-specific issues

MacOS or Linux / OpenBSD

Running the autogen.sh script from the command line depends on having both autoconf and automake installed
on your system.
If this software is not already on your system (usually this can be found in the following location: usr/local/bin,
but it could be located elsewhere depending on your setup) then it can be installed from your OS’s package system.
Alternatively, it can be installed from GNU Software
Or, it can be installed via Brew by running:

brew install autoconf automake

Once built, these libraries can be found in your ghostpdl/sobin/ or ghostpdl/sodebugbin location depending on
your build command.

H-P RISC workstations

(see Autoconf-based method above)


• HP-UX versions before 11.0 do not support POSIX threads. Set SYNC=nosync in the makefile before building.
• Ghostscript builds on H-P machines with either GNU gcc or H-P’s ANSI-capable cc. The minimal, non-ANSI-
capable cc that shiped with some basic HPUX system does not work. If cc on your system doesn’t accept the
-Aa switch, then you need to get the full cc or gcc.
• If you use H-P’s compiler, be sure you have upgraded to a recent release. Many bizarre symptoms have been
reported trying to build Ghostscript with older, buggier compilers, for example:
– The link step fails with a message about “max” not being defined.
– The build succeeds, but the resulting executable fails to start up, with an error message like “Initializing. . .
Unrecoverable error: typecheck in .registerencoding”.
– The build succeeds, but the resulting executable produces a black background on the first page of output.
• It is reported that On HPUX 9.* you need at least compiler patch PHSS_5723 and dld.sl patch PHSS_5734
to build Ghostscript. (As of late 1997, those patches are long obsolete; the current patches are compiler
PHSS_10357 and dld.sl PHSS_11246. It is unknown whether current Ghostscript releases work with
compiler/dld.sl versions older than these).

18 Chapter 2. How to Build Ghostscript from Source Code


Ghostscript Documentation, Release 10.01.0

• On HPUX 10.*, we don’t know what combinations of compiler version and switches work. It is reported that On
HPUX 10.20, setting CC=c89 and CFLAGS=+O3 $(XCFLAGS) works, contradicting the information in the next
paragraph, but this may be dependent on the specific compiler version.
• In either HPUX version, you need to set CC=cc -Aa (or use -Ae if you prefer), and set
CFLAGS=-D_HPUX_SOURCE -O $(XCFLAGS). Higher levels of optimization than -O may work depend-
ing on your compiler revision; some users have reported success with +O3, some have not.
• Some users have reported needing -DNOSYSTIME and -D_POSIX_SOURCE in CFLAGS, but recent tests do not
show these to be necessary.
• If you use gcc, it’s a good idea to have a recent release – at the very least 2.7.2.1 or later. You may be able to get
a working executable with an older gcc by removing -O from CFLAGS.

IBM AIX

We recommend installing gcc and GNU make, and using the Autoconf-based method.
Other combinations are known to work, but are less well supported.
Recent veresions of Ghostscript can trigger a ‘TOC overflow’ error with some compilers on AIX. If this occurs, use
the linker flag -bbigtoc, which can either be added to your configure options:

configure LDFLAGS="-Wl,-bbigtoc"

Or on the make command line:

make XLDFLAGS="-Wl,-bbigtoc"

Silicon Graphics

(see Autoconf-based method above)


Users have had a lot of problems with the MIPSpro compilers on SGI systems. We recommend using gcc. If you do
choose to use the MIPSpro compiler, please read the following carefully.
• To make the optimizer allocate enough table space, set:
CFLAGS="-Olimit 2500" (for older compilers) CFLAGS="-OPT:Olimit=2500" (for newer com-
pilers)
• MIPSpro compiler version 3.19 is “older”, and 7.1 is “newer”; we aren’t sure at what point in between the latter
syntax was introduced.
• With the compiler shipped with Irix 5.2, use the -ansi option.
• The SGI C compiler may produce warnings about “Undefined the ANSI standard library defined macro
stdin/stdout/stderr”. To suppress these warnings, add -woff 608 to the definition of CFLAGS.
• The SGI C compiler shipped with Irix 6.1 and 6.2 will not compile zlib/deflate.c properly with optimization.
Compile this file separately without -O.
• With IRIX 6.5.x and the MIPSpro 7.x compilers there have been reports about incorrect output and binaries that
cause segmentation faults. Various solutions have been suggested and you may want to try them in this order,
until you get a working binary:
– Compile idict.c and isave.c separately without optimization after doing a normal compile; then re-
link.e.g.:

2.10. How to build Ghostscript from source (Unix version) 19


Ghostscript Documentation, Release 10.01.0

cc -OPT:Olimit=2500 -I. -I./obj -o ./obj/idict.o -c ./idict.c


cc -OPT:Olimit=2500 -I. -I./obj -o ./obj/isave.o -c ./isave.c

– Set CFLAGS= (no optimization).


– Use only -O2. Compiler produces incorrect output with -O3 or -Ofast=ip32 -show.
– Irix 6.5.1m with MIPSpro compiler 7.2.1.1m, Irix 6.5.3m with MIPSpro compiler 7.2.1, and probably other
6.5x / 7.2x combinations require compiling with the -o32 option. Compiling with the (default) -n32 option
produces non-working executables. -O2 is OK (possibly except for idict.c), but not -O3.

2.10.3 Oracle/Sun

(see Autoconf-based method above)


• The Sun unbundled C compiler (SC1.0) doesn’t compile Ghostscript properly with the -fast option: Ghostscript
core-dumps in build_gs_font. With that compiler use -g, or use gcc instead.
• The Sun version of dbx often gives up with an error message when trying to load Ghostscript. If this happens,
use GNU gdb instead. (gdb is more reliable than dbx in other ways as well).
• A bug in some versions of zlib results in an undefined symbol zmemcmp when compiling with Sun cc. Use gcc
instead.

2.10.4 Solaris

• Solaris 2.2 may require setting EXTRALIBS=-lsocket. Solaris 2.3 and later seem to require EXTRALIBS=-lnsl
-lsocket -lposix4.
• For Solaris 2.6 (and possibly some other versions), if you set SHARE_LIBPNG=1, SHARE_ZLIB=1, or
SHARE_JPEG=1, you may need to set XLDFLAGS=-R /usr/local/xxx/lib:/usr/local/lib using the full
path names of the relevant directories.
• Solaris 2.n uses /usr/openwin/share/include for the X11 libraries rather than /usr/local/X/include.
• Solaris 2.n typically has Type 1 fonts in /usr/openwin/lib/X11/fonts/Type1/outline.
• For Solaris 2.n in the makefile you must change the definition of INSTALL from install -c to /usr/ucb/
install -c.
• You may need to set XLIBDIR to the directory that holds the X11 libraries, as for other SVR4 systems. Set
-DSVR4 in CFLAGS.
• If you are using the SunPRO C compiler, don’t use optimization level -xO3. On SPARC platforms the compiler
hangs; on Intel platforms the generated code is incorrect. With this compiler on Intel, do not use the -native flag:
floating point computations become unacceptably inaccurate. You can use -xcg92 (SPARC V8) and -dalign
for better performance.
• One user reported compiling from source on a Linux NFS mounted volume failed. Compiling from a local
volume was the workaround.

20 Chapter 2. How to Build Ghostscript from Source Code


Ghostscript Documentation, Release 10.01.0

2.11 Other environments

2.11.1 Environments lacking multi-threading

All environments mentioned here by name have multi-threading capability. However, if your environment doesn’t, you
can remove all need for multi-threading by setting SYNC=nosync in the top-level makefile. Note that you will not be
able to use any so-called “async” drivers (drivers that overlap interpretation and rasterization) if you do this. No such
drivers are in the DEVICE_DEVS* lists of any makefile that we distribute.

2.11.2 Plan 9

Use unix-gcc.mak, editing it to define:

CC=cc GCFLAGS=-D_BSD_EXTENSION -DPlan9

You will also probably have to edit many path names.

2.12 How to build Ghostscript with UFST

Note: This section is only for customers who have a Monotype Imaging UFST license. Other users please skip this
section.

Ghostscript sources do not include UFST sources. You need to obtain them separately. The Ghostscript distributed
source include only some source modules that provide a bridge to UFST. You will also need an additional, UFST
specific makefile: contact Ghostscript support for more information.
If optioned in, the Ghostscript build system will build the UFST as part of the normal bulid process (previously, the
UFST was required to be built separately).
To build Ghostscript with UFST, specify additional options for “make”:
UFST_BRIDGE=1
Forces the UFST bridge to build.
UFST_ROOT=path
Specifies the path to UFST root directory or folder.
UFST_CFLAGS=options
Specifies C compiler options for UFST library. Refer to UFST manual for information about them.
UFST_LIB_EXT=extension
Sets the file name extension for object libraries. You must use the appropriate one for your platform and linker.
An example for Unix/GCC :

UFST_BRIDGE=1 UFST_ROOT=../ufst UFST_CFLAGS=-DGCCx86 UFST_LIB_EXT=.a

Starting with Ghostscript 9.x (Summer 2010), the above options are conveniently inserted in the Makefile with (this
also automatically disable the freetype bridge):

./configure --with-ufst=../ufst

2.11. Other environments 21


Ghostscript Documentation, Release 10.01.0

For Windows/MSVC you need only specify UFST_ROOT. msvc.mak sets the other options automatically.

22 Chapter 2. How to Build Ghostscript from Source Code


CHAPTER

THREE

HOW TO INSTALL GHOSTSCRIPT

3.1 Overview of how to install Ghostscript

You must have four things to run Ghostscript:


1. The Ghostscript executable file; on some operating systems, more than one file is required. These are entirely
platform-specific. See below for details.
2. Initialization files that Ghostscript reads in when it starts up; these are the same on all platforms.
3. • gs_*.ps unless Ghostscript was compiled using the “compiled initialization files” option. See the docu-
mentation of PostScript files distributed with Ghostscript.
• pdf_*.ps if Ghostscript was compiled with the ability to interpret Adobe Portable Document Format
(PDF) files, that is, pdf.dev was included in FEATURE_DEVS when Ghostscript was built.
• Fontmap and Fontmap.GS (or the appropriate Fontmap.xxx for your platform), unless you plan always
to invoke Ghostscript with the -dNOFONTMAP switch.
4. Fonts, for rendering text. These are platform-independent, but if you already have fonts of the right kind on your
platform, you may be able to use those. See below for details. Also see the documentation on fonts.
The usage documentation describes the search algorithms used to find initialization files and font files. The per-platform
descriptions that follow tell you where to install these files.

3.2 Installing Ghostscript on Unix

Ghostscript uses the common configure, build and install method common to many modern software packages.
In general the following with suffice to build Ghostscript:

./configure
make

and then it may be installed in the default location with:

make install

This last command may need to be performed with super user privileges.
You can set the installation directory by adding --prefix=path to the configure invocation in the first step. The
default prefix is /usr/local, which is to say the gs executable is installed as /usr/local/bin/gs.
A list of similar configuration options is available via ./configure --help.

23
Ghostscript Documentation, Release 10.01.0

For more detailed information on building Ghostscript see how to build Ghostscript on Unix in the documentation on
building Ghostscript, especially regarding information on using the older hand edited makefile approach. Whatever
configuration method you use, execute make install to install the executable and all the required and ancillary files
after the build is complete.

3.2.1 Fonts

The makefile installs all the files except fonts under the directory defined in the makefile as prefix. Fonts need to
be installed separately. The fonts should be installed in {prefix}/share/ghostscript/fonts. (That is, /usr/
local/share/ghostscript/fonts/ if you used the default configuration above.)
If you have Adobe Acrobat installed, you can use the Acrobat fonts in place of the ones distributed with with
Ghostscript by adding the Acrobat fonts directory to GS_FONTPATH and removing these fonts from
Fontmap.GS:
Courier, Courier-Bold, Courier-BoldOblique, Courier-Oblique, Helvetica, Helvetica-Bold,
Helvetica-BoldOblique, Helvetica-Oblique, Symbol, Times-Bold, Times-BoldItalic,
Times-Italic, Times-Roman, ZapfDingbats
Similarly, you can have Ghostscript use other fonts on your system by adding entries to the fontmap or adding the
directories to the GS_FONTMAP environment variable. See the usage documentation for more information.
For example, many linux distributions place fonts under /usr/share/fonts.

3.2.2 Ghostscript as a shared object

If you’ve built Ghostscript as a shared object, instead of make install, you must use make soinstall. See how to
build Ghostscript as a shared object for more details.

3.2.3 Additional notes on Linux

For Linux, you may be able to install or upgrade Ghostscript from precompiled RPM files using:

rpm -U ghostscript-N.NN-1.i386.rpm
rpm -U ghostscript-fonts-N.NN-1.noarch.rpm

However, please note that we do not create RPMs for Ghostscript, and we take no responsibility for RPMs created by
others.

3.3 Installing Ghostscript on MS Windows

We usually distribute Ghostscript releases for Windows as a binary installer, for the convenience of most users.

24 Chapter 3. How to Install Ghostscript


Ghostscript Documentation, Release 10.01.0

3.3.1 Windows 3.1 (16-bit)

The last version to run on 16-bit Windows 3.1 was Ghostscript 4.03.

3.3.2 Windows 95, 98, Me

The last version to be available as a binary for Windows 95/98/Me was 8.60. Although building from source with
Visual Studio 2003 should produce a working binary for those versions.

3.3.3 Windows NT4, 2000, XP, 2003 or Vista (32-bit)

The installer is normally named gs###w32.exe, where ### is the release number (e.g., 871 for Ghostscript 8.71, 910
for Ghostscript 9.10).

3.3.4 Windows XP x64 edition, 2003 or Vista (64-bit)

The x64 installer is normally named gs###w64.exe This is for 64-bit Windows operating systems based on the x64
instruction set. Do not use this on 64-bit processors running 32-bit Windows.

3.3.5 Installing

To install Ghostscript on Windows, you should run the installer executable.


The installer is NSIS-based and supports a few standard NSIS options: /NCRC disables the CRC check, /S runs the in-
staller or uninstaller silently, /D sets the default installation directory (It must be the last parameter used in the command
line and must not contain any quotes, even if the path contains spaces. Only absolute paths are supported).

3.3.6 General Windows configuration

The installer includes files in these subdirectories:


• gs#.##\bin
• gs#.##\examples
• gs#.##\lib
• gs#.##\doc
• gs#.##\Resource
• fonts
The actual executable files for the 32-bit Windows install, in the gs#.##\bin subdirectory, are:

GSWIN32C.EXE Ghostscript as a 32-bit Windows command line program. This is usually the preferred exe-
cutable.
GSWIN32.EXE 32-bit Ghostscript using its own window for commands.
GSDLL32.DLL 32-bit dynamic link library containing most of Ghostscript’s functionality.

For the 64-bit Windows install, also in the gs#.##\bin subdirectory, they are:

3.3. Installing Ghostscript on MS Windows 25


Ghostscript Documentation, Release 10.01.0

GSWIN64C.EXE Ghostscript as a 64-bit Windows command line program. This is usually the preferred exe-
cutable.
GSWIN64.EXE 64-bit Ghostscript using its own window for commands.
GSDLL64.DLL 64-bit dynamic link library containing most of Ghostscript’s functionality.

For printer devices, the default output is the default printer. This can be modified as follows:

-sOutputFile="%printer%printer name"

If your printer is named “HP DeskJet 500” then you would use -sOutputFile="%printer%HP DeskJet 500".
If Ghostscript fails to find an environment variable, it looks for a registry value of the same name under the key

HKEY_CURRENT_USER\Software\GPL Ghostscript\#.##

or if that fails, under the key:

HKEY_LOCAL_MACHINE\SOFTWARE\GPL Ghostscript\#.##

where #.## is the Ghostscript version number.


Ghostscript will attempt to load the Ghostscript dynamic link library GSDLL32.DLL in the following order:
• In the same directory as the Ghostscript executable.
• If the environment variable GS_DLL is defined, Ghostscript tries to load the Ghostscript dynamic link library
(DLL) with the name given.
• Using the standard Windows library search method: the directory from which the application loaded, the current
directory, the Windows system directory, the Windows directory and the directories listed in the PATH environ-
ment variable.
The Ghostscript installer will create registry values for the environment variables GS_LIB and GS_DLL.

3.3.7 Uninstalling Ghostscript on Windows

To uninstall Ghostscript, use the Control Panel, Add/Remove Programs and remove “Ghostscript #.##” and “Ghostscript
Fonts”. (The entries may be called “GPL Ghostscript” or “AFPL Ghostscript”, rather than just “Ghostscript”, depending
on what version of Ghostscript was installed).
Alternatively, an uninstall shortcut is also available in the Start Menu group.

3.4 Installing Ghostscript on OpenVMS

Support for OpenVMS has stagnated (and almost certainly bit-rotted), and as the core development team has no access
to an OpenVMS environment, we are unable to bring it up to date. We will consider patches from contributors if any
wish to take on the task of getting it working again. Given the very limited appeal of OpenVMS these days, however,
we are unlikely to consider patches with invasive code changes.
You need the file GS.EXE to run Ghostscript on OpenVMS, and installing Ghostscript on an OpenVMS system requires
building it first.
The following installation steps assume that the Ghostscript directory is DISK1:[DIR.GHOSTSCRIPT]. Yours will
almost certainly be in a different location so adjust the following commands accordingly.
• Download the fonts and unpack them into DISK1:[DIR.GHOSTSCRIPT.LIB].

26 Chapter 3. How to Install Ghostscript


Ghostscript Documentation, Release 10.01.0

• Enable access to the program and support files for all users with:

$ set file/prot=w:re DISK1:[DIR]GHOSTSCRIPT.dir


$ set file/prot=w:re DISK1:[DIR.GHOSTSCRIPT...]*.*

• Optionally, add the Ghostscript help instructions to your system wide help file:

$ lib/help sys$help:HELPLIB.HLB DISK1:[DIR.GHOSTSCRIPT.DOC]GS-VMS.HLP

• Lastly, add the following lines to the appropriate system wide or user specific login script.

$ define gs_exe DISK1:[DIR.GHOSTSCRIPT.BIN]


$ define gs_lib DISK1:[DIR.GHOSTSCRIPT.EXE]
$ gs :== $gs_exe:gs.exe

If you have DECWindows/Motif installed, you may wish to replace the FONTMAP.GS file with FONTMAP.VMS. Read the
comment at the beginning of the latter file for more information.

3.4. Installing Ghostscript on OpenVMS 27


Ghostscript Documentation, Release 10.01.0

28 Chapter 3. How to Install Ghostscript


CHAPTER

FOUR

USING 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.

4.1 Invoking Ghostscript

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

29
Ghostscript Documentation, Release 10.01.0

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 Command line options and Devices for a more complete listing.

4.1.1 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 gswin32.exe
gswin32c.exe
gswin64.exe
gswin64c.exe
OS/2 gsos2

On Windows, the two digit number indicates the word length of the system for which the binary was built (so gswin32.
exe is for x86 Windows systems, whilst gswin64.exe is for x86_64 Windows systems). And the “c” suffix indicates
a Windows console based binary (note that the “display device” window will still appear).

30 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

4.2 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

4.2.1 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.

4.2.2 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

4.2. Selecting an output device 31


Ghostscript Documentation, Release 10.01.0

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: On MS Windows systems, the % character also has a special meaning for the command processor (shell), so you
will have to double it, e.g.:

gs -sOutputFile=%%os%%%%abc

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
(continues on next page)

32 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

(continued from previous page)


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, eps2write, 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

4.2.3 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:
If the desired paper size is listed in the section on paper sizes known to Ghostscript below, you can select it as the
default paper size for a single invocation of Ghostscript by using the -sPAPERSIZE= switch, for instance:

-sPAPERSIZE=a4
-sPAPERSIZE=legal

Otherwise you can set the page size using the pair of switches:

-dDEVICEWIDTHPOINTS=w -dDEVICEHEIGHTPOINTS=h

Where w be the desired paper width and h be the desired paper height in points (units of 1/72 of an inch).
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.

4.2. Selecting an output device 33


Ghostscript Documentation, Release 10.01.0

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.
When the -dFIXEDMEDIA switch is given on the command line, the InputAttributes dictionary will only be pop-
ulated with the single page size. This allows the -dPSFitPage option to fit the page size requested in a PostScript file
to be rotated, scaled and centered for the best fit on the specified page.

4.2.4 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.

4.3 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:

34 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

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.

4.4 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.

4.4.1 Switches for PDF files

Here are some command line options specific to PDF:

-dPDFINFO

Starting with release 9.56.0 this new switch will work with the PDF interpreter (GhostPDF) and with the PDF interpreter
integrated into Ghostscript. When this switch is set the interpreter will emit information regarding the file, similar to
that produced by the old pdf_info.ps program in the ‘lib’ folder. The format is not entirely the same, and the search
for fonts and spot colours is ‘deeper’ than the old program; pdf_info.ps stops at the page level whereas the PDFINFO
switch will descend into objects such as Forms, Images, type 3 fonts and Patterns. In addition different instances of
fonts with the same name are now enumerated.
Unlike the pdf_info.ps program there is no need to add the input file to the list of permitted files for reading (using
–permit-file-read).

-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 have a variety of page sizes, for example thumbnail images.
This option is also set by the -dFitPage option.

4.4. Using Ghostscript with PDF files 35


Ghostscript Documentation, Release 10.01.0

-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.

-dUseBleedBox

Sets the page size to the BleedBox rather than the MediaBox. defines the region to which the contents of the page should
be clipped when output in a production environment. This may include any extra bleed area needed to accommodate
the physical limitations of cutting, folding, and trimming equipment. The actual printed page may 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 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.

-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 useful when one wants to crop the page as much as possible without 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 a defined meaning, it simply provides a rectangle to which the page contents will be clipped (cropped). By
convention, it is often, but not exclusively, used to aid the positioning of content on the (usually larger, in these cases)
media.

-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 annotations associated with the page Annots key. Annotations are shown by default.
In addition, finer control is available by defining an array /ShowAnnotTypes. Annotation types listed in this array will
be drawn, whilst those not listed will not be drawn.
To use this feature: -c "/ShowAnnotTypes [....] def" -f <input file>
Where the array can contain one or more of the following names: /Stamp, /Squiggly, /Underline, /Link, /Text,
/Highlight, /Ink, /FreeText, /StrikeOut and /stamp_dict.

36 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

For example, adding the follow to the command line: -c "/ShowAnnotTypes [/Text /UnderLine] def" -f
<input file> would draw only annotations with the subtypes “Text” and “UnderLine”.

-dShowAcroForm=false

Don’t show annotations from the Interactive Form Dictionary (AcroForm dictionary). By default, AcroForm processing
is now enabled because Adobe Acrobat does this. This option is provided to restore the previous behavior which
corresponded to older Acrobat.

-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.
These command line options are no longer specific to PDF, but have some specific differences with PDF files:

-dFirstPage=pagenumber

Begin on the designated page of the document. Pages of all documents in PDF collections are numbered sequentionally.

-dLastPage=pagenumber

Stop after the designated page of the document. Pages of all documents in PDF collections are numbered sequentionally.

Note: The PDF and XPS interpreters allow the use of a -dLastPage less than -dFirstPage. In this case the pages
will be processed backwards from LastPage to FirstPage.

-sPageList=pageranges

Page ranges are separated by a comma ‘,’. Each range of pages can consist of:
• (a) a single page number.
• (b) a range with a starting page number, followed by a dash ‘-’ followed by an ending page number.
• (c) a range with a starting page number, followed by a dash ‘-’ which ends at the last page.
• (d) the keyword “even” or “odd”, which optionally can be followed by a colon ‘:’ and a page range. If there is
no page range then all even or odd pages are processed in forward order.
• (e) a range with an initial dash ‘-’ followed by and ending page number which starts at the last page and ends
at the specified page (PDF and XPS only).

4.4. Using Ghostscript with PDF files 37


Ghostscript Documentation, Release 10.01.0

For example:

-sPageList=1,3,5 indicates that pages 1, 3 and 5 should be processed.


-sPageList=5-10 indicates that pages 5, 6, 7, 8, 9 and 10 should be processed.
-sPageList=1,5-10,12- indicates that pages 1, 5, 6, 7, 8, 9, 10 and 12 onwards should be␣
˓→processed.

-sPageList=odd:3-7,9-,-1,8 processes pages 3, 5, 7, 9, 10, 11, ..., last, last, last-1, .


˓→.., 1, 8

Note: Use of PageList overrides FirstPage and/or LastPage, if you set these as well as PageList they will be
ignored.

Be aware that using the %d syntax for -sOutputFile=... does not reflect the page number in the original document. If
you chose (for example) to process even pages by using -sPageList=even, then the output of -sOutputFile=out%d.
png would still be out1.png, out2.png, out3.png etc.
For PostScript or PCL input files, the list of pages must be given in increasing order, you cannot process pages out of
order or repeat pages and this will generate an error. PCL and PostScript require that all the pages must be interpreted,
however since only the requested pages are rendered, this can still lead to savings in time.
The PDF and XPS interpreters handle this in a slightly different way. Because these file types provide for random
access to individual pages in the document these inerpreters only need to process the required pages, and can do so in
any order.
Because the PostScript and PCL interpreters cannot determine when a document terminates, sending multple files
as input on the command line does not reset the PageList between each document, each page in the second and
subsequent documents is treated as following on directly from the last page in the first document. The PDF interpreter,
however, does not work this way. Since it knows about individual PDF files the PageList is applied to each PDF file
separately. So if you were to set -sPageList=1,2 and then send two PDF files, the result would be pages 1 and 2 from
the first file, and then pages 1 and 2 from the second file. The PostScript interpreter, by contrast, would only render
pages 1 and 2 from the first file. This means you must exercise caution when using this switch, and probably should
not use it at all when processing a mixture of PostScript and PDF files on the same command line.

4.4.2 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.

38 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

4.4.3 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.

4.5 Using Ghostscript with EPS files

Encapsulated PostScript (EPS) files are intended to be incorporated in other PostScript documents and may not dis-
play 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.

4.6 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

4.5. Using Ghostscript with EPS files 39


Ghostscript Documentation, Release 10.01.0

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.

Note: 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.

4.7 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.

4.7.1 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/ and
%rom%iccprofiles/ directories are 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.

40 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

4.7.2 Finding PostScript Level 2 resources

Adobe specifies that resources are installed in a single directory. Ghostscript instead maintains a list of resource direc-
tories, 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. 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 sys-
tem parameter GenericResourceDir is the string ../Resource/ (or its equivalent in the file path syntax of the
underlying platform), Ghostscript searches for ../Resource/CMap/Identity-H from all directories listed in How
Ghostscript finds files. So in this example, if the user on a Windows platform specifies the command line option
-I.;../gs/lib;c:/gs8.50/lib, Ghostscript searches for ../gs/Resource/CMap/Identity-H and then for c:/
gs8.50/Resource/CMap/Identity-H.
To get a proper platform dependent syntax Ghostscript inserts the value of the system parameter
GenericResourcePathSep (initially “/” on Unix and Windows, “:” on MacOS, “.” or “]” on OpenVMS).
The string ../Resource is replaced with a platform dependent equivalent.
In the case of multiple resource directories, the default ResourceFileName procedure retrieves either a path to the
first avaliable resource, or if the resource is not available it returns a path starting with GenericResourceDir. Con-
sequently Postscript installers of Postscript resources will 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 the next section, it concatenates together:
1. the value of the system parameter FontResourceDir (initially /Resource/Font/).
2. the name of the resource font (for instance, Times-Roman).

Note: Even although the system parameters are named “somethingDir”, they are not just plain directory names: they
have “/” on the end, so that they can be concatenated with the category name or font name.

4.7. How Ghostscript finds files 41


Ghostscript Documentation, Release 10.01.0

4.7.3 Font lookup

Ghostscript has a slightly different way to find the file containing a font with a given name. This rule uses not only the
search path defined by -I, GS_LIB, and GS_LIB_DEFAULT as described above, but also the directory that is the value
of the FontResourceDir system parameter, and an additional list of directories that is the value of the GS_FONTPATH
environment variable (or the value provided with the -sFONTPATH= switch, if present).
At startup time, Ghostscript reads in the Fontmap files in every directory on the search path (or in the list provided
with the -sFONTMAP= switch, if present): these files are catalogs of fonts and the files that contain them. (See the
documentation of fonts for details.) Then, when Ghostscript needs to find a font that isn’t already loaded into memory,
it goes through a series of steps.
1. First, it looks up the font name in the combined Fontmaps. If there is an entry for the desired font name, and the
file named in the entry can be found in some directory on the general search path (defined by -I, GS_LIB, and
GS_LIB_DEFAULT), and the file is loaded successfully, and loading it defines a font of the desired name, that is
the end of the process.
2. If this process fails at any step, Ghostscript looks for a file whose name is the concatenation of the value of the
FontResourceDir system parameter and the font name, with no extension. If such a file exists, can be loaded,
and defines a font of the desired name, that again is the end. The value of FontResourceDir is normally
the string /Resource/Font/, but it can be changed with the setsystemparams operator: see the PostScript
Language Reference Manual for details.
3. If that fails, Ghostscript then looks for a file on the general search path whose name is the desired font name,
with no extension. If such a file exists, can be loaded, and defines a font of the desired name, that again is the
end.
4. If that too fails, Ghostscript looks at the GS_FONTPATH environment variable (or the value provided with the
-sFONTPATH= switch, if present), which is also a list of directories. It goes to the first directory on the list, and
it’s descendants, looking for all files that appear to contain PostScript fonts (also Truetype fonts); it then adds all
those files and fonts to the combined Fontmaps, and starts over.
5. If scanning the first FONTPATH directory doesn’t produce a file that provides 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 is exhausted.
6. Finally, if all else fails, it will try to find a substitute for the font from among the standard 35 fonts.

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

42 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

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 Font-name-to-file-name mapping is implicit – the
files; FontName in the file is used.
aliases are possible, and there need not be any relation Aliases are not possible.
between the font name in the Fontmap and the FontName
in the file.
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 fea-
ture 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 to set the environment variable GS_FONTPATH to
the value indicated so that Ghostscript will automatically acquire all the installed Type 1 (and, if supported, TrueType)
fonts (but see below for notes 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 in place of Fontmap or Fontmap.GS, because otherwise the
entries in Fontmap will take precedence over the fonts in the FONTPATH directories.
** On Solaris systems simply setting GS_FONTPATH or using -sFONTPATH= may not work, because for some reason
some versions of Ghostscript can’t seem to find any of the Type1 fonts in /usr/openwin/lib/X11/fonts/Type1/
outline. (It says: “15 files, 15 scanned, 0 new fonts”. We think this problem has been fixed in Ghostscript version
6.0, but we aren’t sure because we’ve never been able to reproduce it.) See Fontmap.Sol instead. Also, on Solaris
2.x it’s probably not worth your while to add Sun’s fonts to your font path and 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 incorrect displays with Ghostscript.

4.7. How Ghostscript finds files 43


Ghostscript Documentation, Release 10.01.0

These paths may not be exactly right for your installation; if the indicated directory doesn’t contain files whose names
are familiar font names like Courier and Helvetica, you may wish to ask your system administrator where to find these
fonts.
Adobe Acrobat comes with a set of fourteen Type 1 fonts, on Unix typically in a directory called /Acrobat3/Fonts.
There is no particular reason to use these instead of the corresponding fonts in the Ghostscript distribution (which are
of just as good quality), except to save about a megabyte of disk space, but the installation documentation explains how
to do it on Unix.

4.7.4 CID fonts

CID fonts are PostScript resources containing a large 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, which defines specific codes for glyphs, before
it can be used as a font. This allows the reuse of a collection of glyphs with different encodings.
The simplest method to request a font composed of a CID font resource and a CMap resource in a PostScript document
is:

/CIDFont-CMap findfont

where CIDFont is a name of any CID font resource, and CMap is a name of a CMap resource designed for the same char-
acter collection. The interpreter will compose the 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 lookup on the search
path or font path.

4.7.5 CID font substitution

Automatic CIDFont Substitution

In general, it is highly recommended that CIDFonts used in the creation of PDF jobs should be embedded or available
to Ghostscript as CIDFont resources, this ensures that the character set, and typeface style are as intended by the author.
In cases where the original CIDFont is not available, the next best option is to provide Ghostscript with a mapping to
a suitable alternative CIDFont - see below for details on how this is achieved. However, Ghostscript does provide the
ability to use a “fall back” CIDFont substitute. As shipped, this uses the DroidSansFallback.ttf font. This font contains
a large number of glyphs covering several languages, but it is not comprehensive. There is, therefore, a chance that
glyphs may be wrong, or missing in the output when this fallback is used.
Internally, the font is referenced as CIDFont resource called CIDFallBack, thus a different fallback from
DroidSansFallback.ttf can be specified adding a mapping to your cidfmap file (see below for details) to map the
name “CIDFallBack” as you prefer. For CIDFallBack the mapping must be a TrueType font or TrueType collection,
it cannot be a Postscript CIDFont file.
As with any font containing large numbers of glyphs, DroidSansFallback.ttf is quite large (~3.5Mb at the of
writing). If this is space you cannot afford in your use of Ghostscript, you can simply delete the file from: Resource/
CIDFSubst/DroidSansFallback.ttf. The build system will cope with the file being removed, and the initialization
code will avoid adding the internal fall 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. As the name suggests, this will result in all the glyphs from a
missing CIDFont being replaced with a simple bullet point.

44 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

This type of generic fall back CIDFont substitution can be very useful for viewing and proofing jobs, but may not
be appropriate for a “production” workflow, where it is expected that only the original font should be used. For
this situation, you can supply Ghostscript with the command line option: -dPDFNOCIDFALLBACK. By combining
-dPDFNOCIDFALLBACK with -dPDFSTOPONERROR a production workflow can force a PDF with missing CIDFonts
to error, and avoid realising a CIDFont was missing only after printing.
The directory in which the fallback TrueType font or collection can be specified by the command line parameter
-sCIDFSubstPath="path/to/TTF", or with the environment variable CIDFSUBSTPATH. The file name of the substi-
tute TrueType font can be specified using the command line parameter -sCIDFSubstFont="TTF file name" or the
environment variable CIDFSUBSTFONT.

Explicit CIDFont Substitution

Substitution of CID font resources is controlled, by default, by the Ghostscript configuration file Resource/Init/
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 configure Ghostscript for a specific need. Note that the default Ghostscript build includes
such 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: rebuild the executable; use the “-I” command line option to add the
directory containing your modified file to Ghostscript’s search path; or, finally, build Ghostscript to use disk based
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 used by a document, and Original is a name of an available
CID font resource. Please pay attention that both them must be designed for same character collection. In other words,
you cannot substitute a Japanese CID font resource with a Korean CID font resource, etc. CMap resource names must
not appear in lib/cidfmap. The trailing semicolon and the space before it are 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.

4.7. How Ghostscript finds files 45


Ghostscript Documentation, Release 10.01.0

Key Type Description


/Path string A 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.
/FileType name Must be /TrueType.
/SubfontID integer (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.
/CSI array of 2 or 3 (required) Information for building CIDSystemInfo.
elements 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 char-
acters to cover an Adobe 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 used by a document, and path/to/cid/font/file is the path
to the Postscript CIDFont file, including the file name. NOTE: the CIDFont file, when executed by the Postscript
interpreter, must result in a CIDFont resource being defined 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 a CIDFont resource
called “PingHei-Bold”. To substitute a file based CIDFont for a differently named CIDFont, use formats 1 and 3 in
combination (the order of the entries is not important).
The trailing semicolon and the space before it are both required.

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] >> ;

46 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

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 update lib/cidfmap with the common CJK fonts provided by Microsoft products.
The script can 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 be represented 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 directly in a cidfmap file because the #xx notation in
names is a PDF-only encoding. Instead, try something like:

<82C68272835383568362834E>cvn << /Path (C:/WINDOWS/Fonts/msmincho.ttc) /FileType /


˓→TrueType /SubfontID 0 /CSI [(Japan1) 3] >> ;

Where <82C68272835383568362834E> is the same byte sequence converted to a hex string. This lets you specify a
name using any sequence of bytes through the encodings available for Postscript 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 truetype fonts. The 7.0x versions of Ghostscript supported this by assuming a
Japanese character ordering. This is replaced in the 8.0x and later releases with the more general cidfmap mechanism.
The PDF specification requires CID font files to be embedded, however some documents omit them. As a workaround
the PDF interpreter applies an additional substitution method when a requested CID font resource is not embedded
and it is not available. It takes values of the keys Registry and Ordering from 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:

/Registry (Adobe) /Ordering (Identity)

there is no way to determine the language properly. If the CID font file is not embedded, the Adobe-Identity record
depends on the document and a correct record isn’t possible when a document refers to multiple Far East languages. In
the latter case add individual records for specific CID font names used in the document.

4.7. How Ghostscript finds files 47


Ghostscript Documentation, Release 10.01.0

Consequently, if you want to handle any PDF document with non-embedded CID fonts (which isn’t a correct PDF),
you need to create a suitable lib/cidfmap by hand, possibly a specific one for each document.

4.7.6 Using Unicode True Type fonts

Ghostscript can make use of Truetype fonts with a Unicode character set. To do so, you should generate a (NOTE: non-
standard!) Postscript or PDF job where the relevant text is encoded as UTF-16. Ghostscript may be used for converting
such jobs to other formats (Postscript, PDF, PXL etc). The resulting output will be compliant with the spec (unlike the
input).
To render an UTF-16 encoded text, one must do the following:
• Provide a True Type font with Unicode Encoding. It must have a cmap table with platformID equals to 3
(Windows), and SpecificID eqials to 1 (Unicode).
• Describe the font in Resource/Init/cidfmap with special values for the CSI key : [(Artifex) (Unicode)
0].
• In the PS or PDF job combine the font with one of CMap Identity-UTF16-H (for the horizontal writing
mode) or Identity-UTF16-V (for the vertical writing mode). Those CMaps are distributed with Ghostscript in
Resource/CMap.
Please note that /Registry (Adobe) /Ordering (Identity) won’t properly work for Unicode documents, espe-
cially for the searchability feature (see CID font substitution).

4.7.7 Temporary files

Where Ghostscript puts temporary files

Platform Filename Location


MS Windows and OpenVMS _temp_XX.XXX Current directory
OS/2 gsXXXXXX Current directory
Unix gs_XXXXX /tmp

You can change in which directory Ghostscript creates temporary files by setting the TMPDIR or TEMP environment
variable to the name of the directory you want used. Ghostscript currently doesn’t do a very good job of deleting
temporary files if it exits because of an error; you may have to delete them manually from time to time.

4.8 Notes on specific platforms

4.8.1 Word size (32 or 64 bits)

The original PostScript language specification, while not stating a specific word size, defines ‘typical’ limits which
make it clear that it was intended to run as a 32-bit environment. Ghostscript was originally coded that way, and the
heritage remains within the code base.
Because the Ghostscript PDF interpreter is currently written in PostScript, it proved necessary to add support for 64-bit
integers so that we could process PDF files which exceed 2GB in size. This is the only real purpose in adding support
for large integers, however since that time, we have made some efforts to allow for the use of 64-bit words; in particular
the use of integers, but also lifting the 64K limit on strings and arrays, among other areas.
However this is, obviously, dependent on the operating system and compiler support available. Not all builds of
Ghostscript will support 64-bit integers, though some 32-bit builds (eg Windows) will.

48 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

Even when the build supports 64-bit words, you should be aware that there are areas of Ghostscript which do not
support 64-bit values. Sometimes these are dependent on the build and other times they are inherent in the architecture
of Ghostscript (the graphics library does not support 64-bit co-ordinates in device space for example, and most likely
never will).

Note: The extended support for 64-bit word size can be disabled by executing ‘true .setcpsimode’, This is important
for checking the output of the Quality Logic test suite (and possibly other test suites) as the tests make assumptions
about the sizes of integers (amongst other things). You can run /ghostpdl/Resource/Init/gs_cet.ps to change
Ghostscript’s behaviour so that it matches the observed behaviour of Adobe CPSI interpreters.

4.8.2 Unix

The Ghostscript distribution includes some Unix shell scripts to use with Ghostscript in different environments. These
are all user-contributed code, so if you have questions, please contact the user identified in the file, not Artifex Software.

pv.sh

Preview a specified page of a dvi file in an X window

sysvlp.sh

System V 3.2 lp interface for parallel printer

pj-gs.sh

Printing on an H-P PaintJet under HP-UX

unix-lpr.sh

Queue filter for lpr under Unix; its documentation is intended for system administrators

lprsetup.sh

Setup for unix-lpr.sh

4.8.3 VMS

To be able to specify switches and file names when invoking the interpreter, define gs as a foreign command:

$ gs == "$disk:[directory]gs.exe"

where the “disk” and “directory” specify where the Ghostscript executable is located. For instance:

$ gs == "$dua1:[ghostscript]gs.exe"

On VMS systems, the last character of each “directory” name indicates what sort of entity the “directory” refers to. If
the “directory” name ends with a colon “:”, it is taken to refer to a logical device, for instance:

4.8. Notes on specific platforms 49


Ghostscript Documentation, Release 10.01.0

$ define ghostscript_device dua1:[ghostscript_510]

$ define gs_lib ghostscript_device:

If the “directory” name ends with a closing square bracket “]”, it is taken to refer to a real directory, for instance

$ define gs_lib dua1:[ghostscript]

Defining the logical GS_LIB:

$ define gs_lib disk:[directory]

allows Ghostscript to find its initialization files in the Ghostscript directory even if that’s not where the executable
resides.
Although VMS DCL itself converts unquoted parameters to upper case, C programs such as Ghostscript receive their
parameters through the C runtime library, which forces all unquoted command-line parameters to lower case. That is,
with the command:

$ gs -Isys$login:

Ghostscript sees the switch as -isys$login, which doesn’t work. To preserve the case of switches, quote them like
this:

$ gs "-Isys$login:"

If you write printer output to a file with -sOutputFile= and then want to print the file later, use "PRINT/PASSALL".
PDF files (or PostScript files that use the setfileposition operator) must be “stream LF” type files to work properly
on VMS systems. (Note: This definitely matters if Ghostscript was compiled with DEC C; we are not sure of the
situation if you use gcc.) Because of this, if you transfer files by FTP, you probably need to do one of these two things
after the transfer:
• If the FTP transfer was in text (ASCII) mode:

$ convert/fdl=streamlf.fdl input-file output-file

where the contents of the file STREAMLF.FDL are:


FILE
ORGANIZATION sequential
RECORD
BLOCK_SPAN yes
CARRIAGE_CONTROL carriage_return
FORMAT stream_lf
• If the FTP transfer was in binary mode:

$ set file/attribute=(rfm:stmlf)

50 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

Using X Windows on VMS

If you are using on an X Windows display, you can set it up with the node name and network transport, for instance:

$ set display/create/node="doof.city.com"/transport=tcpip

and then run Ghostscript by typing gs at the command line.

4.8.4 MS Windows

The name of the Ghostscript command line executable on MS Windows is gswin32c/gswin64c so use this instead of
the plain ‘gs’ in the quickstart examples.
To run the batch files in the Ghostscript lib directory, you must add gs\bin and gs\lib to the PATH, where gs is the
top-level Ghostscript directory.
When passing options to Ghostscript through a batch file wrapper such as ps2pdf.bat you need to substitute ‘#’ for
‘=’ as the separator between options and their arguments. For example:

ps2pdf -sPAPERSIZE#a4 file.ps file.pdf

Ghostscript treats ‘#’ the same internally, and the ‘=’ is mangled by the command shell.
There is also an older version for MS Windows called just gswin32 that provides its own window for the interactive
postscript prompt. The executable gswin32c/gswin64c is usually the better option since it uses the native command
prompt window.
For printer devices, the default output is the default printer. This can be modified as follows:

-sOutputFile="%printer%printer name"

Output to the named printer. If your printer is named “HP DeskJet 500” then you would use
-sOutputFile="%printer%HP DeskJet 500".

4.8.5 MS-DOS

Note: Ghostscript is no longer supported on MS-DOS.

Invoking Ghostscript from the command prompt in Windows is supported by the Windows executable described above.

4.8.6 X Windows

Ghostscript looks for the following resources under the program name ghostscript and class name Ghostscript;
the ones marked “**” are calculated from display metrics:

4.8. Notes on specific platforms 51


Ghostscript Documentation, Release 10.01.0

X Windows resources

Name Class Default


background Background white
foreground Foreground black
borderColor BorderColor black
borderWidth BorderWidth 1
geometry Geometry NULL
xResolution Resolution **
yResolution Resolution **
useExternalFonts UseExternalFonts true
useScalableFonts UseScalableFonts true
logExternalFonts LogExternalFonts false
externalFontTolerance ExternalFontTolerance 10.0
palette Palette Color
maxGrayRamp MaxGrayRamp 128
maxRGBRamp MaxRGBRamp 5
maxDynamicColors MaxDynamicColors 256
useBackingPixmap UseBackingPixmap true
useXPutImage UseXPutImage true
useXSetTile UseXSetTile true

X resources

To set X resources, put them in a file (such as ~/.Xdefaults on Unix) in a form like this:

Ghostscript*geometry: 595x842-0+0
Ghostscript*xResolution: 72
Ghostscript*yResolution: 72

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

xrdb -merge ~/.Xdefaults

• Ghostscript doesn’t look at the default system background and foreground colors; if you want to change the
background or foreground color, you must set them explicitly for Ghostscript. This is a deliberate choice, so that
PostScript documents will display correctly by default – with white as white and black as black – even if text
windows use other colors.
• The geometry resource affects only window placement.
• Resolution is expressed in pixels per inch (1 inch = 25.4mm).
• The font tolerance gives the largest acceptable difference in height of the screen font, expressed as a percentage
of the height of the desired font.
• The palette resource can be used to restrict Ghostscript to using a grayscale or monochrome palette.
maxRGBRamp and maxGrayRamp control the maximum number of colors that Ghostscript allocates ahead of time for
the dither cube (ramp). Ghostscript never preallocates more than half the cells in a colormap. maxDynamicColors
controls the maximum number of colors that Ghostscript will allocate dynamically in the colormap.

52 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

Working around bugs in X servers

The “use...” resources exist primarily to work around bugs in X servers.


• Old versions of DEC’s X server (DECwindows) have bugs that require setting useXPutImage or useXSetTile
to false.
• Some servers do not implement backing pixmaps properly, or do not have enough memory for them. If you get
strange behavior or “out of memory” messages, try setting useBackingPixmap to false.
• Some servers do not implement tiling properly. This appears as broad bands of color where dither patterns should
appear. If this happens, try setting useXSetTile to false.
• Some servers do not implement bitmap or pixmap displaying properly. This may appear as white or black rectan-
gles where characters should appear; or characters may appear in “inverse video” (for instance, white on a black
rectangle rather than black on white). If this happens, try setting useXPutImage to false.

X device parameters

In addition to the device parameters recognized by all devices, Ghostscript’s X driver provides parameters
to adjust its performance. Users will rarely need to modify these. Note that these are parameters to be set
with the -d switch in the command line (e.g., -dMaxBitmap=10000000), not resources to be defined in
the ~/.Xdefaults file.

AlwaysUpdate <boolean>

If true, the driver updates the screen after each primitive drawing operation; if false (the default), the
driver uses an intelligent buffered updating algorithm.

MaxBitmap <integer>

If the amount of memory required to hold the pixmap for the window is no more than the value of
MaxBitmap, the driver will draw to a pixmap in Ghostscript’s address space (called a “client-side pixmap”)
and will copy it to the screen from time to time; if the amount of memory required for the pixmap exceeds
the value of MaxBitmap, the driver will draw to a server pixmap. Using a client-side pixmap usually pro-
vides better performance – for bitmap images, possibly much better performance – but since it may require
quite a lot of RAM (e.g., about 2.2 Mb for a 24-bit 1024x768 window), the default value of MaxBitmap
is 0.

MaxTempPixmap, MaxTempImage <integer>

These control various aspects of the driver’s buffering behavior. For details, please consult the source file
gdevx.h.

4.8. Notes on specific platforms 53


Ghostscript Documentation, Release 10.01.0

SCO Unix

Because of bugs in the SCO Unix kernel, Ghostscript will not work if you select direct screen output and also allow it
to write messages on the console. If you are using direct screen output, redirect Ghostscript’s terminal output to a file.

4.9 Command line options

Unless otherwise noted, these switches can be used on all platforms.

4.9.1 General switches

Input control

@filename

Causes Ghostscript to read filename and treat its contents the same as the command line. (This was in-
tended primarily for getting around DOS’s 128-character limit on the length of a command line.) Switches
or file names in the file may be separated by any amount of white space (space, tab, line break); there is
no limit on the size of the file.

– filename arg1 . . .

-+ 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.

-@ filename arg1 . . .

Does the same thing as – and -+, but expands @filename arguments.

-_

These are not really switches: they tell Ghostscript to read from standard input, which is coming from a
file or a pipe, with or without buffering. On some systems, Ghostscript may read the input one character
at a time, which is useful for programs such as ghostview that generate input for Ghostscript dynamically
and watch for some response, but can slow processing. If performance is significantly slower than with a
named file, try ‘-_’ which always reads the input in blocks. However, ‘-’ is equivalent on most systems.

54 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

-c token . . .

-c string . . .

Interprets arguments as PostScript code up to the next argument that begins with “-” followed by a non-
digit, or with “@”. For example, if the file quit.ps contains just the word “quit”, then -c quit on the
command line is equivalent to quit.ps there. Each argument must be valid PostScript, either individual
tokens as defined by the token operator, or a string containing valid PostScript.
Because Ghostscript must initialize the PostScript environment before executing the commands specified
by this option it should be specified after other setup options. Specifically this option ‘bind’s all operations
and sets the systemdict to readonly.

-f

Interprets following non-switch arguments as file names to be executed using the normal run command.
Since this is the default behavior, -f is useful only for terminating the list of tokens for the -c switch.

-f filename

Execute the given file, even if its name begins with a “-” or “@”.

File searching

Note that by “library files” here we mean all the files identified using the search rule under “How Ghostscript finds
files” above: Ghostscript’s own initialization files, fonts, and files named on the command line.

-I directories

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

-P

Makes Ghostscript look first in the current directory for library files.

-P-

Makes Ghostscript not look first in the current directory for library files (unless, of course, the first explicitly
supplied directory is “.”). This is now the default.

4.9. Command line options 55


Ghostscript Documentation, Release 10.01.0

Setting parameters

-D name, -d name

Define a name in systemdict with value=true.

-D name=token, -d name=token

Define a name in systemdict with the given value. The value must be a valid PostScript token (as defined
by the token operator). If the token is a non-literal name, it must be true, false, or null. It is recommeded
that this is used only for simple values – use -c (above) for complex values such as procedures, arrays or
dictionaries.
Note that these values are defined before other names in systemdict, so any name that that conflicts with
one usually in systemdict will be replaced by the normal definition during the interpreter initialization.

-S name=string, -s name=string

Define a name in systemdict with a given string as value. This is different from -d. For example, -dXYZ=35
on the command line is equivalent to the program fragment:

/XYZ 35 def

whereas -sXYZ=35 is equivalent to:

/XYZ (35) def

-p name=string

Define a name in systemdict with the parsed version of the given string as value. The string takes a pa-
rameter definition in (something very close to) postscript format. This allows more complex structures to
be passed in than is possible with -d or -s. For example:

-pFoo="<< /Bar[1 2 3]/Baz 0.1 /Whizz (string) /Bang <0123> >>"

This means that -p can do the job of both -d and -s. For example:

-dDownScaleFactor=3

can be equivalently performed by:

-pDownScaleFactor=3

and:

-sPAPERSIZE=letter

can be equivalently performed by:

-pPAPERSIZE="(letter)"

56 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

Note: There are some ‘special’ values that should be set using -s, not -p, such as DEVICE and DefaultGrayProfile.
Broadly, only use -p if you cannot set what you want using -s or -d.

Also, internally, after setting an parameter with -p we perform an initgraphics operation. This is required to allow
changes in parameters such as HWResolution to take effect. This means that attempting to use -p other than at the
start of a page is liable to give unexpected results.

-u name

Un-define a name, cancelling -d or -s.


Note that the initialization file gs_init.ps makes systemdict read-only, so the values of names defined with
-D, -d, -S, and -s cannot be changed – although, of course, they can be superseded by definitions in
userdict or other dictionaries. However, device parameters set this way (PageSize, Margins, etc.) are not
read-only, and can be changed by code in PostScript files.

-g number1 x number2

Equivalent to -dDEVICEWIDTH=number1 and -dDEVICEHEIGHT=number2, specifying the device width


and height in pixels for the benefit of devices such as X11 windows and VESA displays that require (or
allow) you to specify width and height. Note that this causes documents of other sizes to be clipped, not
scaled: see -dFIXEDMEDIA below.

-r number (same as -r number x number)

-r number1 x number2

Equivalent to -dDEVICEXRESOLUTION=number1 and -dDEVICEYRESOLUTION=number2, specifying the


device horizontal and vertical resolution in pixels per inch for the benefit of devices such as printers that
support multiple X and Y resolutions.

Suppress messages

-q

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

4.9.2 Parameter switches (-d and -s)

As noted above, -d and -s define initial values for PostScript names. Some of these names are parameters
that control the interpreter or the graphics engine. You can also use -d or -s to define a value for any
device parameter of the initial device (the one defined with -sDEVICE=, or the default device if this switch
is not used). For example, since the ppmraw device has a numeric GrayValues parameter that controls the
number of bits per component, -sDEVICE=ppmraw -dGrayValues=16 will make this the default device
and set the number of bits per component to 4 (log2(16)).

4.9. Command line options 57


Ghostscript Documentation, Release 10.01.0

Rendering parameters

-dCOLORSCREEN

-dCOLORSCREEN=0

-dCOLORSCREEN=false

On high-resolution devices (at least 150 dpi resolution, or -dDITHERPPI specified), -dCOLORSCREEN
forces the use of separate halftone screens with different angles for CMYK or RGB if halftones are needed
(this produces the best-quality output); -dCOLORSCREEN=0 uses separate screens with the same frequency
and angle; -dCOLORSCREEN=false forces the use of a single binary screen. The default if COLORSCREEN
is not specified is to use separate screens with different angles if the device has fewer than 5 bits per color,
and a single binary screen (which is never actually used under normal circumstances) on all other devices.

-dDITHERPPI= lpi

Forces all devices to be considered high-resolution, and forces use of a halftone screen or screens with lpi
lines per inch, disregarding the actual device resolution. Reasonable values for lpi are N/5 to N/20, where
N is the resolution in dots per inch.

-dInterpolateControl= control_value

This allows control of the image interpolation.


By default InterpolateControl is 1 and the image rendering for images that have /Interpolate true
are interpolated to the full device resolution. Otherwise, images are rendered using the nearest neighbour
scaling (Bresenham’s line algorithm through the image, plotting the closest texture coord at each pixel).
When downscaling this results in some source pixels not appearing at all in the destination. When upscal-
ing, each source pixels will cover at least one destination pixel.
When the control_value is 0 no interpolation is performed, whether or not the file has images with /
Interpolate true.
When the control_value is greater than 1 interpolation is performed for images with /Interpolate true
as long as the image scaling factor on either axis is larger than the control_value. Also, the interpolation
only produces images that have (device resolution / control_value) maximum resolution rather than full
device resolution. This allows for a performance vs. quality tradeoff since the number of pixels produced
by the interpolation will be a fraction of the interpolated pixels at full device resolution. Every source
pixel will contribute partially to the destination pixels.
When the InterpolateControl control_value is less than 0 interpolation is forced as if all images have
/Interpolate true, and the interpolation is controlled by the absolute value of the control_value as
described above. Thus, -dInterpolateControl=-1 forces all images to be interpolated at full device
resolution.
Computationally, image interpolation is much more demanding than without interpolation (lots of floating
point muliplies and adds for every output pixel vs simple integer additions, subtractions, and shifts).
In all but special cases image interpolation uses a Mitchell filter function to scale the contributions for
each output pixel. When upscaling, every output pixel ends up being the weighted sum of 16 input pixels,
When downscaling more source pixels will contribute to the interpolated pixels. Every source pixel has
some effect on the output pixels.

58 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

-dDOINTERPOLATE

This option still works, but is deprecated, and is the equivalent of -dInterpolateControl=-1.

-dNOINTERPOLATE

This option still works, but is deprecated and is the equivalent of -dInterpolateControl=0.
Turns off image interpolation, improving performance on interpolated images at the expense of image
quality. -dNOINTERPOLATE overrides -dDOINTERPOLATE.

-dTextAlphaBits= n

-dGraphicsAlphaBits= n

These options control the use of subsample antialiasing. Their use is highly recommended for producing
high quality rasterizations. The subsampling box size n should be 4 for optimum output, but smaller values
can be used for faster rendering. Antialiasing is enabled separately for text and graphics content. Allowed
values are 1, 2 or 4.

Note: Because of the way antialiasing blends the edges of shapes into the background when they are drawn
some files that rely on joining separate filled polygons together to cover an area may not render as expected with
GraphicsAlphaBits at 2 or 4. If you encounter strange lines within solid areas, try rendering that file again with
-dGraphicsAlphaBits=1.
Further note: because this feature relies upon rendering the input it is incompatible, and will generate an error on
attempted use, with any of the vector output devices.

-dAlignToPixels= n

Chooses glyph alignent to integral pixel boundaries (if set to the value 1) or to subpixels (value 0). Sub-
pixels are a smaller raster grid which is used internally for text antialiasing. The number of subpixels in a
pixel usually is 2^TextAlphaBits, but this may be automatically reduced for big characters to save space
in character cache.
The parameter has no effect if -dTextAlphaBits=1. Default value is 0.
Setting -dAlignToPixels=0 can improve rendering of poorly hinted fonts, but may impair the appearance
of well-hinted fonts.

-dGridFitTT= n

This specifies the initial value for the implementation specific user parameter GridFitTT . It controls grid
fitting of True Type fonts (Sometimes referred to as “hinting”, but strictly speaking the latter is a feature of
Type 1 fonts). Setting this to 2 enables automatic grid fitting for True Type glyphs. The value 0 disables grid
fitting. The default value is 2. For more information see the description of the user parameter GridFitTT .

4.9. Command line options 59


Ghostscript Documentation, Release 10.01.0

-dUseCIEColor

Set UseCIEColor in the page device dictionary, remapping device-dependent color values through a
Postscript defined CIE color space. Document DeviceGray, DeviceRGB and DeviceCMYK source col-
ors will be substituted respectively by Postscript CIEA, CIEABC and CIEDEFG color spaces. See the
document Ghostscript Color Management for details on how this option will interact with Ghostscript’s
ICC-based color workflow. If accurate colors are desired, it is recommended that an ICC workflow be
used.

-dNOCIE

Substitutes DeviceGray for CIEBasedA, DeviceRGB for CIEBasedABC and CIEBasedDEF spaces and
DeviceCMYK for CIEBasedDEFG color spaces. Useful only on very slow systems where color accuracy
is less important.

-dNOSUBSTDEVICECOLORS

This switch prevents the substitution of the ColorSpace resources (DefaultGray, DefaultRGB, and
DefaultCMYK) for the DeviceGray, DeviceRGB, and DeviceCMYK color spaces. This switch is primar-
ily useful for PDF creation using the pdfwrite device when retaining the color spaces from the original
document is important.

-dNOPSICC

Disables the automatic loading and use of an input color space that is contained in a PostScript file as DSC
comments starting with the %%BeginICCProfile: comment. ICC profiles are sometimes embedded by
applications to convey the exact input color space allowing better color fidelity. Since the embedded ICC
profiles often use multidimensional RenderTables, color conversion may be slower than using the Default
color conversion invoked when the -dUseCIEColor option is specified, therefore the -dNOPSICC option
may result in improved performance at slightly reduced color fidelity.

-dNOTRANSPARENCY

Turns off PDF 1.4 transparency, resulting in faster (but possibly incorrect) rendering of pages containing
PDF 1.4 transparency and blending.

-dALLOWPSTRANSPARENCY

Enables the use of the Ghostscript custom transparency operators (Transparency) from Postscript input.
Normally, these operators are not accessible from Postscript jobs, being primarily intended to be called
by the PDF interpreter. Using -dALLOWPSTRANSPARENCY leaves them available. It is important that these
operators are used correctly, especially the order in which they are called, otherwise unintended, even
undefined behavior may result.

60 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

-dNO_TN5044

Turns off the TN 5044 psuedo operators. These psuedo operators are not a part of the official Postscript
specification. However they are defined in Technical Note #5044 Color Separation Conventions for
PostScript Language Programs. These psuedo operators are required for some files from QuarkXPress.
However some files from Corel 9 and Illustrator 88 do not operate properly if these operators are present.

-dDOPS

Enables processing of Subtype /PS streams in PDF files and the DoPS operator. DoPS has in fact been
deprecated for some time. Also the “PS” operator that was removed from the 1.3 2nd edition specification
is also disabled by default, and enabled by -dDOPS. Use of this option is NOT recommended in security-
conscious applications, as it increases the scope for malicious code. -dDOPS has no effect on processing
of PostScript source files. Note: in releases 7.30 and earlier, processing of DoPS was always enabled.

-dBlackText

Forces text to be drawn with black. This occurs for text fill and text stroke operations. PDF output created
with this setting will be updated to be drawn with gray values of 0. Type 3 fonts, which are sometimes
used for graphics, are not affected by this parameter. Note, works only for fills with gray, rgb, and cmyk.
Pattern, separation, and deviceN fills will not be affected.

-dBlackVector

Forces vector stroke and fills to be drawn with black. PDF output created with this setting will be updated
to be drawn with gray values of 0. Note, works only for fills with gray, rgb, and cmyk. Pattern, separation,
and deviceN fills will not be affected.

-dBlackThresholdL= float

Sets the threshold for the luminance value (L*) at which that value and above will be mapped to white
when using the BlackText and BlackVector option. Default is 90. Pure white has a value of 100. Pure
black has a value of 0. This means that if you set BlackThresholdL=101, all colors will be mapped to
black. If you set BlackThresholdL=75, colors that are below an L* value of 75 will be mapped to black.
Colors at or above an L* of 75 will be mapped to white, depending upon the setting of BlackThresholdC
(see below).

-dBlackThresholdC= float

For colors that are at or above the value set by BlackThresholdL (or the default setting of 90), map colors
to white that are within a distance of BlackThresholdC from the CIELAB neutral axis in terms of the L1
norm on the a* and b* value. All others are mapped to black. This has the effect of forcing colors with high
luminance and high chrominance to black (e.g. pure yellow) while those with a lower luminance and less
chrominance to white (e.g. a light gray). Default value is 3. You can visualize the region that is mapped
to white as a cuboid that is centered on the CIELAB neutral axis with one end tied to the L*=100 value.
The cuboid cross sections across the neutral axis are squares whose size is set by BlackThresholdC. The
cuboid length is set by BlackThresholdL and is effectively 100-BlackThresholdL.

4.9. Command line options 61


Ghostscript Documentation, Release 10.01.0

Page parameters

-dFirstPage= pagenumber

Begin on the designated page of the document. Pages of all documents in PDF collections are numbered
sequentionally.

-dLastPage= pagenumber

Stop after the designated page of the document. Pages of all documents in PDF collections are numbered
sequentionally.

-sPageList= pagenumber

There are three possible values for this; even, odd or a list of pages to be processed. A list can include
single pages or ranges of pages. Ranges of pages use the minus sign ‘-’, individual pages and ranges of
pages are separated by commas ‘,’. A trailing minus ‘-’ means process all remaining pages. For example:
• -sPageList=1,3,5 indicates that pages 1, 3 and 5 should be processed.
• -sPageList=5-10 indicates that pages 5, 6, 7, 8, 9 and 10 should be processed.
• -sPageList=1, 5-10, 12 indicates that pages 1, 5, 6, 7, 8, 9, 10 and 12 onwards should be pro-
cessed.
The PDF interpreter and the other language interpreters handle these in slightly different ways. Because PDF files
enable random access to pages in the document the PDF inerpreter only interprets and renders the required pages. PCL
and PostScript cannot be handled in ths way, and so all the pages must be interpreted. However only the requested
pages are rendered, which can still lead to savings in time. Be aware that using the ‘%d’ syntax for OutputFile
does not reflect the page number in the original document. If you chose (for example) to process even pages by using
-sPageList=even, then the output of -sOutputFile=out%d.png would still be out0.png, out1.png, out2.png
etc.
Because the PostScript and PCL interpreters cannot determine when a document terminates, sending multple files
as input on the command line does not reset the PageList between each document, each page in the second and
subsequent documents is treated as following on directly from the last page in the first document. The PDF interpreter,
however, does not work this way. Since it knows about individual PDF files the PageList is applied to each PDF file
separately. So if you were to set -sPageList=1,2 and then send two PDF files, the result would be pages 1 and 2 from
the first file, and then pages 1 and 2 from the second file. The PostScript interpreter, by contrast, would only render
pages 1 and 2 from the first file. This means you must exercise caution when using this switch, and probably should
not use it at all when processing a mixture of PostScript and PDF files on the same command line.

-dFIXEDMEDIA

Causes the media size to be fixed after initialization, forcing pages of other sizes or orientations to be
clipped. This may be useful when printing documents on a printer that can handle their requested paper size
but whose default is some other size. Note that -g automatically sets -dFIXEDMEDIA, but -sPAPERSIZE=
does not.

62 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

-dFIXEDRESOLUTION

Causes the media resolution to be fixed similarly. -r automatically sets -dFIXEDRESOLUTION.

-dPSFitPage

The page size from the PostScript file setpagedevice operator, or one of the older statusdict page
size operators (such as letter or a4) will be rotated, scaled and centered on the “best fit” page size from
those availiable in the InputAttributes list. The -dPSFitPage is most easily used to fit pages when
used with the -dFIXEDMEDIA option.
This option is also set by the -dFitPage option.

-dORIENT1=true

-dORIENT1=false

Defines the meaning of the 0 and 1 orientation values for the setpage[params] compatibility operators.
The default value of ORIENT1 is true (set in gs_init.ps), which is the correct value for most files that
use setpage[params] at all, namely, files produced by badly designed applications that “know” that the
output will be printed on certain roll-media printers: these applications use 0 to mean landscape and 1
to mean portrait. -dORIENT1=false declares that 0 means portrait and 1 means landscape, which is the
convention used by a smaller number of files produced by properly written applications.

-dDEVICEWIDTHPOINTS= w

-dDEVICEHEIGHTPOINTS= h

Sets the initial page width to w or initial page height to h respectively, specified in 1/72” units.

-sDEFAULTPAPERSIZE= a4

This value will be used to replace the device default papersize ONLY if the default papersize for the device
is ‘letter’ or ‘a4’ serving to insulate users of A4 or 8.5x11 from particular device defaults (the collection
of contributed drivers in Ghostscript vary as to the default size).

-dFitPage

This is a “convenience” operator that sets the various options to perform page fitting for specific file types.
This option sets the -dEPSFitPage, -dPDFFitPage, and the -dFitPage options.

4.9. Command line options 63


Ghostscript Documentation, Release 10.01.0

-sNupControl= Nup_option_string

This option specifies the N-up nesting to be performed. The pages are scaled and arranged on the current
PageSize “master” page according the the option.
The only option strings are as follows:
-sNupControl=number1xnumber2
Will fit number1 nested pages across the master page, and number2 down the master page, from the
upper left, then to the right to fill the row, moving down to the leftmost place on the next row until the
nest is complete. A partially filled nest will be output when the -sNupControl= string is changed,
when Ghostscript exits, or when the page size changes.
Pages are scaled to fit the requested number horizontally and vertically, maintaining the aspect ratio. If the
scaling selected for fitting the nested pages leaves space horizontally on the master page, the blank area
will be added to the left and right of the entire row of nested pages. If the fit results in vertical space, the
blank area will be added above and below all of the rows.
-sNupControl=
An empty string will turn off nesting. If there are any nested pages on the master page, the partially
filled master page will be output. Printer devices typically reallocate their memory whenever the
transparency use of a page changes (from one page having transparency, to the next page not having
transparency, or vice versa). This would cause problems with Nup, possibly leading to lost or corrupt
pages in the output. To avoid this, the Nup device changes the parameters of the page to always set the
PageUsesTransparency flag. While this should be entirely transparent for the user and not cause
extra transparency blending operations during the standard rendering processes for most devices, it
may cause devices to use the clist rather than PageMode.

Font-related parameters

-dLOCALFONTS

Causes Type 1 fonts to be loaded into the current VM – normally local VM – instead of always being
loaded into global VM. Useful only for compatibility with Adobe printers for loading some obsolete fonts.

-dNOFONTMAP

Suppresses the normal loading of the Fontmap file. This may be useful in environments without a file
system.

-dNOFONTPATH

Suppresses consultation of GS_FONTPATH. This may be useful for debugging.

64 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

-dNOPLATFONTS

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

-dNONATIVEFONTMAP

Disables the use of font map and corresponding fonts supplied by the underlying platform. This may be
needed to ensure consistent rendering on the platforms with different fonts, for instance, during regression
testing.

-sFONTMAP= filename1;filename2;. . .

Specifies alternate name or names for the Fontmap file. Note that the names are separated by “:” on Unix
systems, by “;” on MS Windows systems, and by “,” on VMS systems, just as for search paths.

-sFONTPATH= dir1;dir2;. . .

Specifies a list of directories that will be scanned when looking for fonts not found on the search path,
overriding the environment variable GS_FONTPATH.
By implication, any paths specified by FONTPATH or GS_FONTPATH are automatically added to the permit
file read list (see “-dSAFER”).

-sSUBSTFONT= fontname

Causes the given font to be substituted for all unknown fonts, instead of using the normal intelligent sub-
stitution algorithm. Also, in this case, the font returned by findfont is the actual font named fontname, not
a copy of the font with its FontName changed to the requested one.

Note: THIS OPTION SHOULD NOT BE USED WITH HIGH LEVEL (VECTOR) DEVICES, such as pdfwrite,
because it prevents such devices from providing the original font names in the output document. The font specified
(fontname) will be embedded instead, limiting all future users of the document to the same approximate rendering.

Resource-related parameters

-sGenericResourceDir= path

Specifies a path to resource files. The value is platform dependent. It must end with a directory separator.
A note for Windows users, Artifex recommends the use of the forward slash delimiter due to the special
interpretation of \" by the Microsoft C startup code. See Parsing C Command-Line Arguments for more
information.
Adobe specifies GenericResourceDir to be an absolute path to a single resource directory. Ghostscript
instead maintains multiple resource directories and uses an extended method for finding resources, which
is explained in “Finding PostScript Level 2 resources”.
Due to the extended search method, Ghostscript uses GenericResourceDir only as a default direc-
tory for resources being not installed. Therefore GenericResourceDir may be considered as a place

4.9. Command line options 65


Ghostscript Documentation, Release 10.01.0

where new resources to be installed. The default implementation of the function ResourceFileName
uses GenericResourceDir when it is an absolute path, or when the resource file is absent.
The extended search method does not call ResourceFileName.
Default value is (./Resource/) for Unix, and an equivalent one on other platforms.

-sFontResourceDir= path

Specifies a path where font files are installed. It’s meaning is similar to GenericResourceDir.
Default value is (./Font/) for Unix, and an equivalent one on other platforms.

Interaction-related parameters

-dBATCH

Causes Ghostscript to exit after processing all files named on the command line, rather than going into an
interactive loop reading PostScript commands. Equivalent to putting -c quit at the end of the command
line.

-dNOPAGEPROMPT

Disables only the prompt, but not the pause, at the end of each page. This may be useful on PC displays
that get confused if a program attempts to write text to the console while the display is in a graphics mode.

-dNOPAUSE

Disables the prompt and pause at the end of each page. Normally one should use this (along with -dBATCH)
when producing output on a printer or to a file; it also may be desirable for applications where another
program is “driving” Ghostscript.

-dNOPROMPT

Disables the prompt printed by Ghostscript when it expects interactive input, as well as the end-of-page
prompt (-dNOPAGEPROMPT). This allows piping input directly into Ghostscript, as long as the data doesn’t
refer to currentfile.

-dQUIET

Suppresses routine information comments on standard output. This is currently necessary when redirecting
device output to standard output.

66 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

-dSHORTERRORS

Makes certain error and information messages more Adobe-compatible.

-sstdout= filename

Redirect PostScript %stdout to a file or stderr, to avoid it being mixed with device stdout. To redirect
stdout to stderr use -sstdout=%stderr. To cancel redirection of stdout use -sstdout=%stdout or
-sstdout=-.

Note: This redirects PostScript output to %stdout but does not change the destination FILE of device output as with
-sOutputFile=- or even -sOutputFile=%stdout since devices write directly using the stdout FILE * pointer with
C function calls such as fwrite or fputs.

-dTTYPAUSE

Causes Ghostscript to read a character from /dev/tty, rather than standard input, at the end of each page.
This may be useful if input is coming from a pipe.

Note: -dTTYPAUSE overrides -dNOPAUSE.

Device and output selection parameters

-dNODISPLAY

Initializes Ghostscript with a null device (a device that discards the output image) rather than the default
device or the device selected with -sDEVICE=. This is usually useful only when running PostScript code
whose purpose is to compute something rather than to produce an output image.

-sDEVICE= device

Selects an alternate initial output device.

-sOutputFile= filename

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

4.9. Command line options 67


Ghostscript Documentation, Release 10.01.0

-d.IgnoreNumCopies= true

Some devices implement support for “printing” multiple copies of the input document and some do not,
usually based on whether it makes sense for a particular output format. This switch instructs all devices to
ignore a request to print multiple copies, giving more consistent behaviour.

Deferred Page Rendering

Raster printers and image formats that can use the “command list” (clist) to store a representation of the page prior to
rendering can use the --saved-pages= string on the command line for deferred rendering of pages.
Pages that are saved instead of printed are retained until the list of saved pages is emptied by the flush command of the
saved-pages= command string.
Pages can be printed in reverse or normal order, or selected pages, including all even or all odd, and multiple collated
copies can be produced. Since pages are saved until the flush command, pages can be printed multiple times, in any
order.
Refer to the Using Saved Pages document for details.

EPS parameters

-dEPSCrop

Crop an EPS file to the bounding box. This is useful when converting an EPS file to a bitmap.

-dEPSFitPage

Resize an EPS file to fit the page. This is useful for shrinking or enlarging an EPS file to fit the paper size
when printing. This option is also set by the -dFitPage option.

-dNOEPS

Prevent special processing of EPS files. This is useful when EPS files have incorrect Document Structuring
Convention comments.

ICC color parameters

For details about the ICC controls see the document GS9 Color Management.

-sDefaultGrayProfile= filename

Set the ICC profile that will be associated with undefined device gray color spaces. If this is not set, the
profile file name “default_gray.icc” will be used as the default.

68 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

-sDefaultRGBProfile= filename

Set the ICC profile that will be associated with undefined device RGB color spaces. If this is not set, the
profile file name “default_rgb.icc” will be used as the default.

-sDefaultCMYKProfile= filename

Set the ICC profile that will be associated with undefined device CMYK color spaces. If this is not set,
the profile file name “default_cmyk.icc” will be used as the default.

-sDeviceNProfile= filename

Associate a devicen color space contained in a PS or PDF document with an ICC profile. Note that neither
PS nor PDF provide in-document ICC profile definitions for DeviceN color spaces. With this interface it is
possible to provide this definition. The colorants tag order in the ICC profile defines the lay-down order of
the inks associated with the profile. A windows-based tool for creating these source profiles is contained
in ./toolbin/color/icc_creator.

-sOutputICCProfile= filename

Set the ICC profile that will be associated with the output device. Care should be taken to ensure that the
number of colorants associated with the device is the same as the profile. If this is not set, an appropriate
profile (i.e. one with the proper number of colorants) will be selected from those in the directory specified
by ICCProfilesDir (see below). Note that if the output device is CMYK + spot colorants, a CMYK
profile can be used to provide color management for the CMYK colorants only. In this case, spot colors
will pass through unprocessed assuming the device supports those colorants. It is also possible for these
devices to specify NCLR ICC profiles for output.

-sICCOutputColors= “Cyan, Magenta, Yellow, Black, Orange, Violet”

For the psdcmyk and tiffsep separation devices, the device ICC profile can be an NCLR profile, which
means something that includes non-traditional inks like Orange, Violet, etc. In this case, the list of the
color names in the order that they exist in the profile must be provided with this command line option.
Note that if a color name that is specified for the profile occurs also within the document (e.g. “Orange”
above), then these color names will be associated with the same separation. Additional names beyond
those of the ICC profile component count can be included. In this case, those components will be installed
into the tiffsep or psdcmyk device list of colors, following the ICC profile colors. The number of spot
colors (those that go beyond the standard CMYK colors) allowed by tiffsep or psdcmyk can be set using
-dMaxSpots=#. The default value for this is currently set to 10 (GS_SOFT_MAX_SPOTS). As an example
consider the case where we wish to use a 6CLR ICC profile that includes Orange and Violet, but need the
device to include a specialty color component such as Varnish, which does not appear in the document and
is not handled by the 6CLR ICC profile.
In addition, we desire to allow one more spot color of the document to come through to our device.
For this case using -sICCOutputColors="Cyan, Magenta, Yellow, Black, Orange, Violet,
Varnish" -dMaxSpots=4 -sOutputICCProfile=My_6CLR_Profile.icc would provide the desired
outcome. Note that it is up to the device or through the use of -sNamedProfile (see below) to involve
the setting of any values in the Varnish channel. However, if an All color value is encountered in the
document, the Varnish component will have its value set as will the Orange and Violet values (Likewise
if a spot color named Varnish is encountered in the document the Varnish component will be used for the

4.9. Command line options 69


Ghostscript Documentation, Release 10.01.0

values). The All value is typically used for placing registration targets on separations. Finally, note that if
an NCLR ICC profile is specified and ICCOutputColors is not used, then a set of default names will be
used for the extra colorants (non-CMYK) in the profile. These names are given as ICC_COLOR_N for the
Nth non-CMYK channel.

-sProofProfile= filename

Enable the specificiation of a proofing profile that will make the color management system link multiple
profiles together to emulate the device defined by the proofing profile. See the document GS9 Color
Management for details about this option.

-sDeviceLinkProfile= filename

Define a device link profile. This profile is used following the output device profile. Care should be taken
to ensure that the output device process color model is the same as the output color space for the device
link profile. In addition, the color space of the OutputICCProfile should match the input color space of
the device link profile. For example, the following would be a valid specification -sDEVICE=tiff32nc
-sOutputICCProfile=srgb.icc -sDeviceLinkProfile=linkRGBtoCMYK.icc. In this case, the
output device’s color model is CMYK (tiff32nc) and the colors are mapped through sRGB and through a
devicelink profile that maps sRGB to CMYK values. See the document GS9 Color Management for details
about this option.

-sNamedProfile= filename

Define a structure that is to be used by the color management module (CMM) to provide color manage-
ment of named colors. While the ICC does define a named color format, this structure can in practice
be much more general. Many developers wish to use their own proprietary-based format for spot color
management. This command option is for developer use when an implementation for named color man-
agement is designed for the function gsicc_transform_named_color located in gsicccache.c . An example
implementation is currently contained in the code for the handling of both Separation and DeviceN colors.
For the general user this command option should really not be used.

-sBlendColorProfile= filename

With the PDF transparency imaging model, a color space can be specified within which the color blending
operations are to take place. Some files lack this specification, in which case the blending occurs in the
output device’s native color space. This dependency of blending color space on the device color model can
be avoided by using the above command to force a specific color space in which to perform the blending.

-dColorAccuracy= 0/1/2

Set the level of accuracy that should be used. A setting of 0 will result in less accurate color rendering
compared to a setting of 2. However, the creation of a transformation will be faster at a setting of 0
compared to a setting of 2. Default setting is 2.

70 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

-dRenderIntent= 0/1/2/3

Set the rendering intent that should be used with the profile specified above by -sOutputICCProfile.
The options 0, 1, 2, and 3 correspond to the ICC intents of Perceptual, Colorimetric, Saturation, and
Absolute Colorimetric.

-dBlackPtComp= 0/1

Specify if black point compensation should be used with the profile specified above by
-sOutputICCProfile.

-dKPreserve= 0/1/2

Specify if black preservation should be used when mapping from CMYK to CMYK. When using littleCMS
as the CMM, the code 0 corresponds to no preservation, 1 corresponds to the PRESERVE_K_ONLY approach
described in the littleCMS documentation and 2 corresponds to the PRESERVE_K_PLANE approach. This
is only valid when using littleCMS for color management.

-sVectorICCProfile= filename

Set the ICC profile that will be associated with the output device for vector-based graphics (e.g. Fill, Stroke
operations). Care should be taken to ensure that the number of colorants associated with the device is the
same as the profile. This can be used to obtain more saturated colors for graphics.

-dVectorIntent= 0/1/2/3

Set the rendering intent that should be used with vector-based graphic objects. The options are the same
as specified for -dRenderIntent.

-dVectorBlackPt= 0/1

Specify if black point compensation should be used for vector-based graphic objects.

-dVectorKPreserve= 0/1/2

Specify if black preservation should be used when mapping from CMYK to CMYK for vector-based
graphic objects. The options are the same as specified for -dKPreserve.

4.9. Command line options 71


Ghostscript Documentation, Release 10.01.0

-sImageICCProfile= filename

Set the ICC profile that will be associated with the output device for images. Care should be taken to
ensure that the number of colorants associated with the device is the same as the profile. This can be used
to obtain perceptually pleasing images.

-dImageIntent= 0/1/2/3

Set the rendering intent that should be used for images.

-dImageBlackPt= 0/1

Specify if black point compensation should be used with images.

-dImageKPreserve= 0/1/2

Specify if black preservation should be used when mapping from CMYK to CMYK for image objects.
The options are the same as specified for -dKPreserve.

-sTextICCProfile= filename

Set the ICC profile that will be associated with the output device for text. Care should be taken to ensure
that the number of colorants associated with the device is the same as the profile. This can be used ensure
K only text.

-dTextIntent= 0/1/2/3

Set the rendering intent that should be used text objects. The options are the same as specified for
-dRenderIntent.

-dTextBlackPt= 0/1

Specify if black point compensation should be used with text objects.

-dTextKPreserve= 0/1/2

Specify if black preservation should be used when mapping from CMYK to CMYK for text objects. The
options are the same as specified for -dKPreserve.

72 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

-dOverrideICC

Override any ICC profiles contained in the source document with the profiles specified by
sDefaultGrayProfile, sDefaultRGBProfile, sDefaultCMYKProfile. Note that if no profiles are
specified for the default Device color spaces, then the system default profiles will be used. For detailed
override control in the specification of source colors see -sSourceObjectICC.

-sSourceObjectICC= filename

This option provides an extreme level of override control to specify the source color spaces and render-
ing intents to use with vector-based graphics, images and text for both RGB and CMYK source objects.
The specification is made through a file that contains on a line a key name to specify the object type (e.g.
Image_CMYK) followed by an ICC profile file name, a rendering intent number (0 for perceptual, 1 for
colorimetric, 2 for saturation, 3 for absolute colorimetric) and information for black point compensation,
black preservation, and source ICC override. It is also possible to turn off color management for certain
object types, use device link profiles for object types and do custom color replacements. An example file
is given in ./gs/toolbin/color/src_color/objsrc_profiles_example.txt. Profiles to demon-
strate this method of specification are also included in this folder. Note that if objects are colorimetrically
specified through this mechanism other operations like -dImageIntent, -dOverrideICC, have no affect.
Also see below the interaction with the -dDeviceGrayToK option. See further details in the document
GS9 Color Management.

-dDeviceGrayToK= true/false

By default, Ghostscript will map DeviceGray color spaces to pure K when the output device is
CMYK based. This may not always be desired. In particular, it may be desired to map from the
gray ICC profile specified by -sDefaultGrayProfile to the output device profile. To achieve this,
one should specify -dDeviceGrayToK=false. Note that this option may not have any effect in cases
where SourceObjectICC settings are made for gray objects. In particular, if the gray objects in
SourceObjectICC are set to None, which implies that ICC color management is not to be applied to
these objects, then they are treated as DeviceGray and always mapped to K values in a CMYK target de-
vice, regardless of the settings of -dDeviceGrayToK (i.e. there is no color management). If instead, the
gray objects in SourceObjectICC are set to a specific ICC profile, then they are no longer DeviceGray
but are ICC colors. They will be color managed, regardless of the setting of -dDeviceGrayToK.

4.9. Command line options 73


Ghostscript Documentation, Release 10.01.0

-dUseFastColor= true/false

This is used to avoid the use of ICC profiles for source colors. This includes those that are defined by
DeviceGray, DeviceRGB and DeviceCMYK definitions as well as ICC-based color spaces in the source
document. With UseFastColor set to true, the traditional Postscript 255 minus operations are used to
convert between RGB and CMYK with black generation and undercolor removal mappings.

-dSimulateOverprint= true/false

This option has been replaced by -dOverprint=

-dOverprint= /enable | /disable | /simulate

This option provides control of overprinting. The default setting is /enable which allows devices such as
CMYK that can support overprint to leave planes unchanged under control of PostScript and PDF overprint
settings.
The /disable setting ignores all overprint (and overprint mode) from the input.
If /simulate is set, then pages with overprint (or overprint mode) set for CMYK or Separation colors will
be internally maintained and output to RGB or Gray devices.

Note: Not all spot color overprint cases can be accurately simulated with a CMYK only device. For example, a case
where you have a spot color overprinted with CMYK colors will be indistiguishable from a case where you have spot
color equivalent CMYK colorants overprinted with CMYK colors, even though they may need to show significantly
different overprint simulations. To obtain a full overprint simulation, use the /simulate setting or the psdcmyk or tiffsep
device, where the spot colors are kept in their own individual planes.

-dUsePDFX3Profile= int

This option enables rendering with an output intent defined in the PDF source file. If this option is included
in the command line, source device color values (e.g DeviceCMYK, DeviceRGB, or DeviceGray) that
match the color model of the output intent will be interpreted to be in the output intent color space. In
addition, if the output device color model matches the output intent color model, then the destination ICC
profile will be the output intent ICC profile. If there is a mismatch between the device color model and
the output intent, the output intent profile will be used as a proofing profile, since that is the intended
rendering. Note that a PDF document can have multiple rendering intents per the PDF specification. As
such, with the option -dUsePDFX3Profile the first output intent encountered will be used. It is possible
to specify a particular output intent where int is an integer (a value of 0 is the same as not specifying a
number). Probing of the output intents for a particular file is possible using extractICCprofiles.ps in ./
gs/toolbin. Finally, note that the ICC profile member entry is an option in the output intent dictionary.
In these cases, the output intent specifies a registry and a standard profile (e.g. Fogra39). Ghostscript will
not make use of these output intents. Instead, if desired, these standard profiles should be used with the
commands specified above (e.g. -sOutputICCProfile).

74 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

-sUseOutputIntent= string

Like -dUsePDFX3Profile above, this option enables rendering with an output intent defined in the PDF
source file. This option behaves the same way as the -dUsePDFX3Profile, but the selection criteria are
different. Because its possible (as of PDF 2.0) for each page to have a different array, its not sufficient just
to supply an array index, as the same profile might potentially be at different indices in each array.
Instead this option takes a string, which is first compared against the OutputConditionIdentifier in
each OutputIntent in the array. If the OutputConditionIdentifier is not a standard identifier then
it should be Custom and the UseOutputIntent string will be matched against the value of the Info key
instead. If the OutputConditionIdentifier or Info matches the value of UseOuttpuIntent, then
that OutputIntent is selected if the OutputIntent contains a DestOutputProfile key.

-sICCProfilesDir= path

Set a directory in which to search for the above profiles. The directory path must end with a file system
delimiter. If the user doesn’t use the -sICCProfilesDir= command line option, Ghostscript creates a
default value for it by looking on the directory paths explained in How Ghostscript finds files. If the current
directory is the first path a test is made for the iccprofiles directory. Next, the remaining paths with
the string Resource in it are tested. The prefix up to the path separator character preceding the string
Resource, concatenated with the string iccprofiles is used and if this exists, then this path will be used
for ICCProfilesDir.
Note that if the build is performed with COMPILE_INITS=1, then the profiles contained in gs/
iccprofiles will be placed in the ROM file system. If a directory is specified on the command line
using -sICCProfilesDir=, that directory is searched before the iccprofiles/ directory of the ROM
file system is searched.

Note: A note for Windows users, Artifex recommends the use of the forward slash delimiter due to the special
interpretation of \" by the Microsoft C startup code. See Parsing C Command-Line Arguments for more information.

Other parameters

-dFILTERIMAGE

If set, this will ignore all images in the input (in this context image means a bitmap), these will therefore
not be rendered.

-dFILTERTEXT

If set, this will ignore all text in the input (just because it looks like text doesn’t mean it is, it might be an
image), text will therefore not be rendered.

4.9. Command line options 75


Ghostscript Documentation, Release 10.01.0

-dFILTERVECTOR

If set, this will ignore anything which is neither text nor an image.

-dDELAYBIND

Causes bind to remember all its invocations, but not actually execute them until the .bindnow procedure
is called. Useful only for certain specialized packages like pstotext that redefine operators. See the docu-
mentation for .bindnow for more information on using this feature.

-dDOPDFMARKS

Causes pdfmark to be called for bookmarks, annotations, links and cropbox when processing PDF files.
Normally, pdfmark is only called for these types for PostScript files or when the output device requests it
(e.g. pdfwrite device).

-dJOBSERVER

Define \004 (^D) to start a new encapsulated job used for compatibility with Adobe PS Interpreters that
ordinarily run under a job server. The -dNOOUTERSAVE switch is ignored if -dJOBSERVER is specified
since job servers always execute the input PostScript under a save level, although the exitserver operator
can be used to escape from the encapsulated job and execute as if the -dNOOUTERSAVE was specified. This
also requires that the input be from stdin, otherwise an error will result (Error: /invalidrestore in
--restore--).
Example usage is:

gs ... -dJOBSERVER - < inputfile.ps

Or:

cat inputfile.ps | gs ... -dJOBSERVER -

Note: The ^D does not result in an end-of-file action on stdin as it may on some PostScript printers that rely on TBCP
(Tagged Binary Communication Protocol) to cause an out-of-band ^D to signal EOF in a stream input data. This means
that direct file actions on stdin such as flushfile and closefile will affect processing of data beyond the ^D in
the stream.

-dNOCACHE

Disables character caching. Useful only for debugging.

76 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

-dNOGC

Suppresses the initial automatic enabling of the garbage collector in Level 2 systems. (The vmreclaim
operator is not disabled.) Useful only for debugging.

-dNOOUTERSAVE

Suppresses the initial save that is used for compatibility with Adobe PS Interpreters that ordinarily run un-
der a job server. If a job server is going to be used to set up the outermost save level, then -dNOOUTERSAVE
should be used so that the restore between jobs will restore global VM as expected.

-dNOSAFER

Equivalent to -dDELAYSAFER.
This flag disables SAFER mode until the .setsafe procedure is run. This is intended for clients or
scripts that cannot operate in SAFER mode. If Ghostscript is started with -dNOSAFER or -dDELAYSAFER,
PostScript programs are allowed to read, write, rename or delete any files in the system that are not pro-
tected by operating system permissions.
This mode should be used with caution, and .setsafe should be run prior to running any PostScript file
with unknown contents.

-dSAFER

Important: Ghostscript now (as of 9.50) defaults to SAFER being active.

Enables access controls on files. Access controls fall into three categories, files from which Ghostscript
is permitted to read, ones to which it is permitted to write, and ones over which it has “control” (i.e.
delete/rename). These access controls apply to all files accessed via Ghostscript’s internal interface to the
C library file handling. Whilst we have taken considerable pains to ensure that all the code we maintain (as
well as the so called “contrib” devices, that are devices included in our release packages, but not strictly
maintained by the Ghostscript development team) uses this interface, we have no control over thirdparty
code.
This is an entirely new implementation of SAFER for Ghostscript versions 9.50 and later. Earlier versions
relied on storing the file permission lists in Postscript VM (Virtual Memory), and only applied file access
permissions to the Postscript file related operators. It relied on restricting the function of setpagedevice
to avoid the device code from being manipulated into opening arbitrary files. The application of the file
permissions was done within the internal context of the Postscript interpreter, and some other aspects of
the Postscript restrictions were applied in the Postscript environment. With so many of the feature’s ca-
pabilities relying on the Postscript context and environment, by using other (Ghostscript specific) features
maliciously, the restrictions could be overridden.
Whilst the path storage and application of the permissions is implemented entirely in C, it is still possible
for Postscript to add and remove paths from the permissions lists (see .addcontrolpath) until such time as
the access controls are enabled (see .activatepathcontrol), any call to .addcontrolpath after .activatepath-
control will result in a Fatal error causing the interpreter to immediately exit.
An incompatibility exists between the pre-9.50 and 9.50 and later SAFER. By removing storage and appli-
cation entirely from the Postscript language environment and internal context, SAFER is no longer affected
by Postscript save/restore operations. Previously, it was possible to do the equivalent of:

4.9. Command line options 77


Ghostscript Documentation, Release 10.01.0

save
.setsafe
Postscript ops
restore

In that sequence, the Postscript ops would run with SAFER protection but after the restore, SAFER would
no longer be in force. This is no longer the case. After the call to .setsafe the file controls are in
force until the interpreter exits. As the 9.50 and later implementation no longer restricts the operation of
setpagedevice, and because this capability is extremely rarely used, we feel the improvement in security
warrants the small reduction in flexibility.
Path matching is very simple: it is case sensitive, and we do not implement full featured “globbing” or
regular expression matching (such complexity would significantly and negatively impact performance).
Further, the string parameter(s) passed to the --permit-file-* option must exactly match the string(s)
used to reference the file(s): for example, you cannot use an absolute path to grant permission, and then
a relative path to reference the file (or vice versa) - the path match will fail. Similarly, you cannot grant
permission through one symlink, and then reference a file directly, or through an alternative symlink -
again, the matching will fail.
The following cases are handled:

"/path/to/file"

Permits access only to the file: “/path/to/file”

"/path/to/directory/"

Permits access to any file in, and only in, the directory: “/path/to/directory”

"/path/to/directory/*"

Permits access to any file in the directory: “/path/to/directory” and any child of that directory.

Important: Note for Windows Users


The file/path pattern matching is case sensitive, even on Windows. This is a change in behaviour compared
to the old code which, on Windows, was case insensitive. This is in recognition of changes in Windows
behaviour, in that it now supports (although does not enforce) case sensitivity.

Four command line parameters permit explicit control of the paths included in the access control lists:

--permit-file-read=pathlist

Adds a path, or list of paths, to the “permit read” list. A list of paths is a series of paths separated by the
appropriate path list separator for your platform (for example, on Unix-like systems it is “:” and on MS
Windows it is “;”).

--permit-file-write=pathlist

Adds a path, or list of paths, to the “permit write” list. A list of paths is a series of paths separated by the
appropriate path list separator for your platform (for example, on Unix-like systems it is “:” and on MS
Windows it is “;”).

--permit-file-control=pathlist

78 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

Adds a path, or list of paths, to the “permit control” list. A list of paths is a series of paths separated by
the appropriate path list separator for your platform (for example, on Unix-like systems it is “:” and on MS
Windows it is “;”).

--permit-file-all=pathlist

Adds a path, or list of paths, to the all the above lists. A list of paths is a series of paths separated by the
appropriate path list separator for your platform (for example, on Unix-like systems it is “:” and on MS
Windows it is “;”).
‘*’ may be used as a wildcard in the above paths to mean “any character other than the directory separator.
Do not use two or more *’s without intervening characters.
Finally, paths supplied on the command line (such as those in -I, -sFONTPATH parameters) are added to
the permitted reading list. Similarly, paths read during initialisation from Fontmap, cidfmap, and the
platform specific font file enumeration (e.g. fontconfig on Unix systems) are automatically added to the
permit read lists.

-dPreBandThreshold= true/false

If the target device is a halftone device, then images that are normally stored in the command list during
banded output will be halftoned during the command list writing phase, if the resulting image will result
in a smaller command list. The decision to halftone depends upon the output and source resolution as well
as the output and source color space.

-dWRITESYSTEMDICT

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

4.10 Improving performance

Ghostscript attempts to find an optimum balance between speed and memory consumption, but there are some cases
in which you may get a very large speedup by telling Ghostscript to use more memory.
Please note that this discussion relates to devices which produce a bitmap format as the output. These parameters have
no effect on the vector devices, such as pdfwrite.
• For raster printers and image format (jpeg*, tiff*, png* . . . ) devices, performance can be ‘tuned’ by adjusting
some of the parameters related to banding (clist) options (refer to: Banding Parameters).
• All devices may use a display list (“clist”) and use banding when rendering PDF 1.4 transparency. This prevents
allocation of excessively large amounts of memory for the transparency buffer stack. The -dMaxBitmap= option
is used to control when to use the display list, and the other banding parameters mentioned above control the
band size.
In general, page buffer mode is faster than banded/clist mode (a full page buffer is used when
-dMaxBitmap=# is large enough for the entire raster image) since there is no need to write, then
interpret the clist data.
On a multi-core system where multiple threads can be dispatched to individual processors/cores, band-
ing mode may provide higher performance since -dNumRenderingThreads=# can be used to take
advantage of more than one CPU core when rendering the clist. The number of threads should gen-
erally be set to the number of available processor cores for best throughput.

4.10. Improving performance 79


Ghostscript Documentation, Release 10.01.0

In general, larger -dBufferSpace=# values provide slightly higher performance since the per-band
overhead is reduced.
• If you are using X Windows, setting the -dMaxBitmap= parameter described in X device parameters may dra-
matically improve performance on files that have a lot of bitmap images.
• With some PDF files, or if you are using Chinese, Japanese, or other fonts with very large character sets, adding
the following sequence of switches before the first file name may dramatically improve performance at the cost of
an additional memory. For example, to allow use of 30Mb of extra RAM use: -c 30000000 setvmthreshold
-f.
This can also be useful in processing large documents when using a high-level (vector) output device
(like pdfwrite) that maintains significant internal state.
• For pattern tiles that are very large, Ghostscript uses an internal display list (memory based clist), but this can
slow things down. The current default threshold is 8Mb – pattern tiles larger than this will be cached as clist
rather than bitmap tiles. The parameter -dMaxPatternBitmap=# can be used to adjust this threshold, smaller
to reduce memory requirements and larger to avoid performance impacts due to clist based pattern handling.
For example, -dMaxPatternBitmap=200000 will use clist based patterns for pattern tiles larger than
200,000 bytes.

4.11 Summary of environment variables

4.11.1 GS, GSC (MS Windows only)

Specify the names of the Ghostscript executables. GS brings up a new typein window and possibly a
graphics window; GSC uses the DOS console. If these are not set, GS defaults to gswin32, and GSC
defaults to gswin32c.

4.11.2 GS_DEVICE

Defines the default output device. This overrides the compiled-in default, but is overridden by any com-
mand line setting.

4.11.3 GS_FONTPATH

Specifies a list of directories to scan for fonts if a font requested can’t be found anywhere on the search
path.

4.11.4 GS_LIB

Provides a search path for initialization files and fonts.

80 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

4.11.5 GS_OPTIONS

Defines a list of command-line arguments to be processed before the ones actually specified on the
command line. For example, setting GS_DEVICE to XYZ is equivalent to setting GS_OPTIONS to
-sDEVICE=XYZ. The contents of GS_OPTIONS are not limited to switches; they may include actual file
names or even “@file” arguments.

4.11.6 TEMP, TMPDIR

Defines a directory name for temporary files. If both TEMP and TMPDIR are defined, TMPDIR takes prece-
dence.

4.12 Debugging

The information here describing is probably interesting only to developers.

4.12.1 Debug switches

There are several debugging switches that are detected by the interpreter. These switches are available whether or not
Ghostscript was built with the DEBUG macro defined to the compiler (refer to building a debugging configuration).
Previous to 8.10, there was a single DEBUG flag, enabled with -dDEBUG on the command line. Now there are several de-
bugging flags to allow more selective debugging information to be printed containing only what is needed to investigate
particular areas. For backward compatibilty, the -dDEBUG option will set all of the subset switches.

-dCCFONTDEBUG Compiled Fonts


-dCFFDEBUG CFF Fonts
-dCMAPDEBUG CMAP
-dDOCIEDEBUG CIE color
-dEPSDEBUG EPS handling
-dFAPIDEBUG Font API
-dINITDEBUG Initialization
-dPDFDEBUG PDF Interpreter
-dPDFWRDEBUG PDF Writer
-dSETPDDEBUG setpagedevice
-dSTRESDEBUG Static Resources
-dTTFDEBUG TTF Fonts
-dVGIFDEBUG ViewGIF
-dVJPGDEBUG ViewJPEG

The PDF interpreter normally tries to repair, or ignore, all problems encountered in PDF files. Setting
-dPDFSTOPONERROR instead causes the interpreter to signal an error and stop processing the PDF file, instead of print-
ing a warning.
The -dPDFSTOPONWARNING switch behaves the same, but will stop if a condition which would normally merit a warning
(instead of an error) is encountered. Note that setting -dPDFSTOPONWARNING also sets -dPDFSTOPONERROR.
The -Z and -T switches apply only if the interpreter was built for a debugging configuration. In the table below, the
first column is a debugging switch, the second is an equivalent switch (if any) and the third is its usage.

4.12. Debugging 81
Ghostscript Documentation, Release 10.01.0

Switch Equivalent switch Usage


0 garbage collector, minimal detail
1 type 1 and type 42 font interpreter
2 curve subdivider/rasterizer
3 curve subdivider/rasterizer, detail
4 garbage collector (strings)
5 garbage collector (strings, detail)
6 garbage collector (clumps, roots)
7 garbage collector (objects)
8 garbage collector (refs)
9 garbage collector (pointers)
a allocator (large blocks only)
A allocator (all calls)
b bitmap image processor
B bitmap images, detail
c color/halftone mapper
d dictionary put/undef
D dictionary lookups
e external (OS-related) calls
f fill algorithm (summary)
F fill algorithm (detail)
g gsave/grestore[all]
h halftone renderer
H halftones, every pixel
i interpreter, just names
I interpreter, everything
j (Japanese) composite fonts
k character cache and xfonts
K character cache, every access
l command lists, bands
L command lists, everything
m makefont and font cache
n name lookup (new names only)
o outliner (stroke)
O stroke detail
p band list paths
P all paths
q clipping
r arc renderer
s streams
S scanner
t tiling algorithm
u undo saver (for save/restore), finalization
U undo saver, more detail
v compositors: alpha/transparency/overprint/rop
V compositors: alpha/transparency/overprint/rop, more detail
w compression encoder/decoder
x transformations
y Type 1 hints
Y Type 1 hints, every access
z trapezoid fill
continues on next page

82 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

Table 1 – continued from previous page


Switch Equivalent switch Usage
# operator error returns
% externally processed comments
* image and RasterOp parameters
: command list and allocator/time summary
~ math functions and Functions
' contexts, create/destroy
" contexts, every operation
^ reference counting
_ high-level (vector) output
! Postscript operator names (this option is available only
when Ghostscript is compiled with a predefined macro DE-
BUG_TRACE_PS_OPERATORS)
| (reserved for experimental code)

The following switch affects what is printed, but does not select specific items for printing:

Switch Equivalent switch Usage


/ include file name and line number on all trace output

These switches select debugging options other than what should be printed:

Switch Equivalent switch Usage


$ set unused parts of object references to identifiable garbage values
+ use minimum-size stack blocks
, don’t use path-based banding
don’t use high-level banded images

? validate pointers before, during and after garbage collection, also


before and after save and restore; also make other allocator validity
checks
@ fill newly allocated, garbage-collected, and freed storage with a
marker (a1, c1, and f1 respectively)
f the filling algorithm with characters
F the filling algorithm with non-character paths
h the Type 1 hinter
s the shading algorithm
S the stroking algorithm

4.12. Debugging 83
Ghostscript Documentation, Release 10.01.0

Switches used in debugging

Switch Description
-Bsize Run all subsequent files named on the command line (ex-
cept for -F) through the run_string interface, using a
buffer of size bytes.
-B- Turn off -B: run subsequent files (except for -F) directly
in the normal way.
-Ffile Execute the file with -B1 temporarily in effect
-Kn Limit the total amount of memory that the interpreter
can have allocated at any one time to nK bytes. n is a
positive decimal integer.
-Mn Force the interpreter’s allocator to acquire additional
memory in units of nK bytes, rather than the default 20K.
n is a positive decimal integer, on 16-bit systems no
greater than 63.
-Nn Allocate space for nK names, rather than the default
(normally 64K).
n may be greater than 64 only if EXTEND_NAMES was
defined (in inameidx.h) when the interpreter was com-
piled.
-Zxxx Turn debugging printout on (off). Each of the xxx char-
-Z-xxx acters selects an option.
Case is significant: “a” and “A” have different meanings.
-Txxx Turn Visual Trace on (off). Each of the xxx characters
-T-xxx selects an option.
Case is significant: “f” and “F” have different meanings.

In addition, calling Ghostscript with --debug will list all the currently defined (non visual trace) debugging flags, both
in their short form (as listed above for use with -Z) and in a long form, which can be used as in: --debug=tiling,
alloc. All the short form flags for -Z have an equivalent long form. Future flags may be added with a long form only
(due to all the short form flags being used already).

4.12.2 Visual Trace

Visual Trace allows to view internal Ghostscript data in a graphical form while execution of C code. Special instructions
to be inserted into C code for generating the output. Client application rasterizes it into a window.
Currently the rasterization is implemented for Windows only, in clients gswin32.exe and gswin32c.exe. They open
Visual Trace window when graphical debug output appears, -T switch is set, and Ghostscript was built with DEBUG
option.
There are two important incompletenesses of the implementation :
1. The graphical output uses a hardcoded scale. An advanced client would provide a scale option via user interface.
2. Breaks are not implemented in the client. If you need a step-by-step view, you should use an interactive C
debugger to delay execution at breakpoints.

84 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

4.13 Appendix: Paper sizes known to Ghostscript

The paper sizes known to Ghostscript are defined at the beginning of the initialization file gs_statd.ps; see the
comments there for more details about the definitions. The table here lists them by name and size. gs_statd.ps
defines their sizes exactly in points, and the dimensions in inches (at 72 points per inch) and centimeters shown in
the table are derived from those, rounded to the nearest 0.1 unit. A guide to international paper sizes can be found at
papersizes.org.

4.13.1 U.S. standard

Name Inches mm Points Notes


WxH WxH WxH
11 x 17 11.0 x 17.0 279 x 432 792 x 1224 11×17in portrait
ledger 17.0 x 11.0 432 x 279 1224 x 792 11×17in landscape
legal 8.5 x 14.0 216 x 356 612 x 1008
letter 8.5 x 11.0 216 x 279 612 x 792
letter small 8.5 x 11.0 216 x 279 612 x 792
archA 9.0 x 12.0 229 x 305 648 x 864
archB 12.0 x 18.0 305 x 457 864 x 1296
archC 18.0 x 24.0 457 x 610 1296 x 1728
archD 24.0 x 36.0 610 x 914 1728 x 2592
archE 36.0 x 48.0 914 x 1219 2592 x 3456

4.13. Appendix: Paper sizes known to Ghostscript 85


Ghostscript Documentation, Release 10.01.0

4.13.2 ISO standard

Name Inches mm Points Notes


WxH WxH WxH
a0 33.1 x 46.8 841 x 1189 2384 x 3370
a1 23.4 x 33.1 594 x 841 1684 x 2384
a2 16.5 x 23.4 420 x 594 1191 x 1684
a3 11.7 x 16.5 297 x 420 842 x 1191
a4 8.3 x 11.7 210 x 297 595 x 842
a4small 8.3 x 11.7 210 x 297 595 x 842
a5 5.8 x 8.3 148 x 210 420 x 595
a6 4.1 x 5.8 105 x 148 297 x 420
a7 2.9 x 4.1 74 x 105 210 x 297
a8 2.1 x 2.9 52 x 74 148 x 210
a9 1.5 x 2.1 37 x 52 105 x 148
a10 1.0 x 1.5 26 x 37 73 x 105
isob0 39.4 x 55.7 1000 x 1414 2835 x 4008
isob1 27.8 x 39.4 707 x 1000 2004 x 2835
isob2 19.7 x 27.8 500 x 707 1417 x 2004
isob3 13.9 x 19.7 353 x 500 1001 x 1417
isob4 9.8 x 13.9 250 x 353 709 x 1001
isob5 6.9 x 9.8 176 x 250 499 x 709
isob6 4.9 x 6.9 125 x 176 354 x 499
c0 36.1 x 51.1 917 x 1297 2599 x 3677
c1 25.5 x 36.1 648 x 917 1837 x 2599
c2 18.0 x 25.5 458 x 648 1298 x 1837
c3 12.8 x 18.0 324 x 458 918 x 1298
c4 9.0 x 12.8 229 x 324 649 x 918
c5 6.4 x 9.0 162 x 229 459 x 649
c6 4.5 x 6.4 114 x 162 323 x 459

4.13.3 JIS standard

Name mm Notes
WxH
jisb0 1030 x 1456
jisb1 728 x 1030
jisb2 515 x 728
jisb 364 x 515
jisb4 257 x 364
jisb5 182 x 257
jisb6 128 x 182

86 Chapter 4. Using Ghostscript


Ghostscript Documentation, Release 10.01.0

4.13.4 ISO/JIS switchable

Name
b0
b1
b2
b3
b4
b5

Note: Initially the B paper sizes are the ISO sizes, e.g., b0 is the same as isob0. Running the file lib/jispaper.ps
makes the B paper sizes be the JIS sizes, e.g., b0 becomes the same as jisb0.

4.13.5 Other

Name Inches mm Points Notes


WxH WxH WxH
flsa 8.5 x 13.0 216 x 330 612 x 936 U.S. foolscap
flse 8.5 x 13.0 216 x 330 612 x 936 European foolscap
halfletter 5.5 x 8.5 140 x 216 396 x 612
hagaki 3.9 x 5.8 100 x 148 283 x 420 Japanese postcard

4.13. Appendix: Paper sizes known to Ghostscript 87


Ghostscript Documentation, Release 10.01.0

88 Chapter 4. Using Ghostscript


CHAPTER

FIVE

API

5.1 What is the Ghostscript Interpreter API?

The Ghostscript interpreter can be built as a dynamic link library (DLL) on Microsoft Windows, as a shared object
on the Linux, Unix and MacOS X platforms. With some changes, it could be built as a static library. This document
describes the Application Programming Interface (API) for the Ghostscript interpreter library. This should not be
confused with the Ghostscript library which provides a graphics library but not the interpreter.
This supercedes the old DLL interface.
To provide the interface described in the usage documentation, a smaller independent executable loads the DLL/shared
object. This executable must provide all the interaction with the windowing system, including image windows and, if
necessary, a text window.
The Ghostscript interpreter library’s name and characteristics differ for each platform:
• The Win32 DLL gsdll32.dll can be used by multiple programs simultaneously, but only once within each
process.
• The OS/2 DLL gsdll2.dll has MULTIPLE NONSHARED data segments and can be called by multiple pro-
grams simultaneously.
• The Linux shared object libgs.so can be used by multiple programs simultaneously.
The source for the executable is in dw*.* (Windows), dp*.* (OS/2) and dx*.* (Linux/Unix). See these source files
for examples of how to use the DLL.
The source file dxmainc.c can also serve as an example of how to use the shared library component on MacOS X,
providing the same command-line tool it does on any linux, bsd or similar operating system.
At this stage, Ghostscript does not support multiple instances of the interpreter within a single process.

5.2 Exported functions

The functions exported by the DLL/shared object are described in the header file iapi.h and are summarised below.
Omitted from the summary are the calling convention (e.g. __stdcall), details of return values and error handling.
• int gsapi_revision (gsapi_revision_t *pr, int len); details
• int gsapi_new_instance (void **pinstance, void *caller_handle); details
• void gsapi_delete_instance (void *instance); details

89
Ghostscript Documentation, Release 10.01.0

• int gsapi_set_stdio_with_handle (void *instance, int(*stdin_fn)(void *caller_handle,


char *buf, int len), int(*stdout_fn)(void *caller_handle, const char *str,
int len), int(*stderr_fn)(void *caller_handle, const char *str, int len), void
*caller_handle); details
• int gsapi_set_stdio (void *instance, int(*stdin_fn)(void *caller_handle, char
*buf, int len), int(*stdout_fn)(void *caller_handle, const char *str, int len),
int(*stderr_fn)(void *caller_handle, const char *str, int len)); details
• int gsapi_set_poll_with_handle (void *instance, int(*poll_fn)(void *caller_handle),
void *caller_handle); details
• int gsapi_set_poll (void *instance, int(*poll_fn)(void *caller_handle)); details
• int gsapi_set_display_callback (void *instance, display_callback *callback); details
• int gsapi_register_callout (void *instance, gs_callout callout, void
*callout_handle); details
• void gsapi_deregister_callout (void *instance, gs_callout callout, void
*callout_handle); details
• int gsapi_set_arg_encoding (void *instance, int encoding); details
• int gsapi_get_default_device_list(void *instance, char **list, int *listlen); details
• int gsapi_set_default_device_list(void *instance, const char *list, int listlen); de-
tails
• int gsapi_run_string_begin (void *instance, int user_errors, int *pexit_code); details
• int gsapi_run_string_continue (void *instance, const char *str, unsigned int length,
int user_errors, int *pexit_code); details
• int gsapi_run_string_end (void *instance, int user_errors, int *pexit_code); details
• int gsapi_run_string_with_length (void *instance, const char *str, unsigned int
length, int user_errors, int *pexit_code); details
• int gsapi_run_string (void *instance, const char *str, int user_errors, int
*pexit_code); details
• int gsapi_run_file (void *instance, const char *file_name, int user_errors, int
*pexit_code); details
• int gsapi_init_with_args (void *instance, int argc, char **argv); details
• int gsapi_exit (void *instance); details
• int gsapi_set_param(void *instance, const char *param, const void *value,
gs_set_param_type type); details
• int gsapi_get_param(void *instance, const char *param, void *value,
gs_set_param_type type); details
• int gsapi_enumerate_params(void *instance, void **iter, const char **key,
gs_set_param_type *type); details
• int gsapi_add_control_path(void *instance, int type, const char *path); details
• int gsapi_remove_control_path(void *instance, int type, const char *path); details
• void gsapi_purge_control_paths(void *instance, int type); details
• void gsapi_activate_path_control(void *instance, int enable); details

90 Chapter 5. API
Ghostscript Documentation, Release 10.01.0

• int gsapi_is_path_control_active(void *instance); details


• int gsapi_add_fs (void *instance, gsapi_fs_t *fs, void *secret); details
• void gsapi_remove_fs (void *instance, gsapi_fs_t *fs, void *secret); details

5.2.1 gsapi_revision()

This function returns the revision numbers and strings of the Ghostscript interpreter library; you should call it before
any other interpreter library functions to make sure that the correct version of the Ghostscript interpreter has been
loaded.

typedef struct gsapi_revision_s {


const char *product;
const char *copyright;
long revision;
long revisiondate;
} gsapi_revision_t;
gsapi_revision_t r;

if (gsapi_revision(&r, sizeof(r)) == 0) {
if (r.revision < 650)
printf("Need at least Ghostscript 6.50");
}
else {
printf("revision structure size is incorrect");
}

5.2.2 gsapi_new_instance()

Create a new instance of Ghostscript. This instance is passed to most other gsapi functions. The caller_handle is the
default value that will be provided to callback functions. On some platforms (those that do not support threading),
only one instance of Ghostscript is supported at a time; any attempt to create more than one at a time would result in
gsapi_new_instance returning an error.
While the core Ghostscript devices are believed to be thread safe now, a handful of devices are known not to be (at
least the x11 devices, uniprint, and the open printing devices). A new mechanism has been implemented that allows
devices to check for concurrent use and to refuse to start up. The devices shipped with Ghostscript known to use global
variables have had these calls added to them. Any authors of non-standard Ghostscript devices that use global variables
should consider adding the same calls to their own code.
The first parameter, is a pointer to an opaque pointer (void **). The opaque pointer (void *) must be initialised to
NULL before the call to gsapi_new_instance(). See Example 1.

5.2. Exported functions 91


Ghostscript Documentation, Release 10.01.0

5.2.3 gsapi_delete_instance()

Destroy an instance of Ghostscript. Before you call this, Ghostscript must have finished. If Ghostscript has been
initialised, you must call gsapi_exit before gsapi_delete_instance.

5.2.4 gsapi_set_stdio_with_handle()

Set the callback functions for stdio, together with the handle to use in the callback functions. The stdin callback function
should return the number of characters read, 0 for EOF, or -1 for error. The stdout and stderr callback functions should
return the number of characters written.
NOTE: These callbacks do not affect output device I/O when using “%stdout” as the output file. In that case, device
output will still be directed to the process “stdout” file descriptor, not to the stdio callback.

5.2.5 gsapi_set_stdio()

Set the callback functions for stdio. The handle used in the callbacks will be taken from the value passed to
gsapi_new_instance. Otherwise the behaviour of this function matches gsapi_set_stdio_with_handle.

5.2.6 gsapi_set_poll_with_handle()

Set the callback function for polling, together with the handle to pass to the callback function. This function will only
be called if the Ghostscript interpreter was compiled with CHECK_INTERRUPTS as described in gpcheck.h.
The polling function should return zero if all is well, and return negative if it wants Ghostscript to abort. This is often
used for checking for a user cancel. This can also be used for handling window events or cooperative multitasking.
The polling function is called very frequently during interpretation and rendering so it must be fast. If the function
is slow, then using a counter to return 0 immediately some number of times can be used to reduce the performance
impact.

5.2.7 gsapi_set_poll()

Set the callback function for polling. The handle passed to the callback function will be taken from the handle passed
to gsapi_new_instance. Otherwise the behaviour of this function matches gsapi_set_poll_with_handle.

5.2.8 gsapi_set_display_callback()

This call is deprecated; please use gsapi_register_callout to register a callout handler for the display device in prefer-
ence. Set the callback structure for the display device. The handle passed in the callback functions is taken from the
DisplayHandle parameter (or NULL if there is no such parameter). If the display device is used, this must be called
after gsapi_new_instance() and before gsapi_init_with_args(). See gdevdsp.h for more details.

92 Chapter 5. API
Ghostscript Documentation, Release 10.01.0

5.2.9 gsapi_register_callout()

This call registers a callout handler.

5.2.10 gsapi_deregister_callout()

This call deregisters a callout handler previously registered with gsapi_register_callout. All three arguments must
match exactly for the callout handler to be deregistered.

5.2.11 gsapi_set_arg_encoding()

Set the encoding used for the interpretation of all subsequent args supplied via the gsapi interface on this instance. By
default we expect args to be in encoding 0 (the ‘local’ encoding for this OS). On Windows this means “the currently
selected codepage”. On Linux this typically means utf8. This means that omitting to call this function will leave
Ghostscript running exactly as it always has. Please note that use of the ‘local’ encoding is now deprecated and should
be avoided in new code. This must be called after gsapi_new_instance() and before gsapi_init_with_args().

5.2.12 gsapi_set_default_device_list()

Set the string containing the list of default device names, for example “display x11alpha x11 bbox”. Allows the calling
application to influence which device(s) gs will try, in order, in it’s selection of the default device. This must be called
after gsapi_new_instance() and before gsapi_init_with_args().

5.2.13 gsapi_get_default_device_list()

Returns a pointer to the current default device string. This must be called after gsapi_new_instance() and before
gsapi_init_with_args().

5.2.14 gsapi_init_with_args()

Initialise the interpreter. This calls gs_main_init_with_args() in imainarg.c . See below for return codes. The
arguments are the same as the “C” main function: argv[0] is ignored and the user supplied arguments are argv[1]
to argv[argc-1].

5.2.15 gsapi_run_*()

The gsapi_run_* functions are like gs_main_run_* except that the error_object is omitted. If these functions re-
turn <= -100, either quit or a fatal error has occured. You must call gsapi_exit() next. The only exception is
gsapi_run_string_continue() which will return gs_error_NeedInput if all is well. See below for return codes.
The address passed in pexit_code will be used to return the exit code for the interpreter in case of a quit or fatal
error. The user_errors argument is normally set to zero to indicate that errors should be handled through the normal
mechanisms within the interpreted code. If set to a negative value, the functions will return an error code directly
to the caller, bypassing the interpreted language. The interpreted language’s error handler is bypassed, regardless of
user_errors parameter, for the gs_error_interrupt generated when the polling callback returns a negative value.
A positive user_errors is treated the same as zero.
There is a 64 KB length limit on any buffer submitted to a gsapi_run_* function for processing. If you
have more than 65535 bytes of input then you must split it into smaller pieces and submit each in a separate
gsapi_run_string_continue() call.

5.2. Exported functions 93


Ghostscript Documentation, Release 10.01.0

5.2.16 gsapi_exit()

Exit the interpreter. This must be called on shutdown if gsapi_init_with_args() has been called, and just before
gsapi_delete_instance().

5.2.17 gsapi_set_param()

Set a parameter. Broadly, this is equivalent to setting a parameter using -d, -s or -p on the command line. This call can-
not be made during a run_string operation. Parameters in this context are not the same as ‘arguments’ as processed
by gsapi_init_with_args, but often the same thing can be achieved. For example, with gsapi_init_with_args,
we can pass “-r200” to change the resolution. Broadly the same thing can be achieved by using gsapi_set_param to
set a parsed value of “<</HWResolution [ 200.0 200.0 ]>>”.
Note, that internally, when we set a parameter, we perform an initgraphics operation. This means that using
set_param other than at the start of a page is likely to give unexpected results.
Further, note that attempting to set a parameter that the device does not recognise will be silently ignored, and that
parameter will not be found in subsequent gsapi_get_param calls.
The type argument dictates the kind of object that value points to:

typedef enum {
gs_spt_invalid = -1,
gs_spt_null = 0, /* void * is NULL */
gs_spt_bool = 1, /* void * is a pointer to an int (0 false,
* non-zero true). */
gs_spt_int = 2, /* void * is a pointer to an int */
gs_spt_float = 3, /* void * is a float * */
gs_spt_name = 4, /* void * is a char * */
gs_spt_string = 5, /* void * is a char * */
gs_spt_long = 6, /* void * is a long * */
gs_spt_i64 = 7, /* void * is an int64_t * */
gs_spt_size_t = 8, /* void * is a size_t * */
gs_spt_parsed = 9, /* void * is a pointer to a char * to be parsed */

/* Setting a typed param causes it to be instantly fed to to the


* device. This can cause the device to reinitialise itself. Hence,
* setting a sequence of typed params can cause the device to reset
* itself several times. Accordingly, if you OR the type with
* gs_spt_more_to_come, the param will held ready to be passed into
* the device, and will only actually be sent when the next typed
* param is set without this flag (or on device init). Not valid
* for get_typed_param. */
gs_spt_more_to_come = 1<<31
} gs_set_param_type;

Combining a type value by ORRing it with the gs_spt_more_to_come flag will cause the set_param operation to be
queued internally, but not actually be sent to the device. Thus a series of set_param operations can be queued, for
example as below:

int code = gsapi_set_param(instance,


"HWResolution",
"[300 300]",
gs_spt_parsed | gs_spt_more_to_come);
(continues on next page)

94 Chapter 5. API
Ghostscript Documentation, Release 10.01.0

(continued from previous page)


if (code >= 0) {
int i = 1;
code = gsapi_set_param(instance,
"FirstPage",
&i,
gs_spt_int | gs_spt_more_to_come);
}
if (code >= 0) {
int i = 3;
code = gsapi_set_param(instance,
"DownScaleFactor",
&i,
gs_spt_int);
}

This enables a series of set operations to be performed ‘atomically’. This can be useful for performance, in that any
reconfigurations to the device (such as page size changes or memory reallocations) will only happen when all the
parameters are sent, rather than potentially each time each one is sent.

5.2.18 gsapi_get_param()

Get a parameter. Retrieve the current value of a parameter.


If an error occurs, the return value is negative. Otherwise the return value is the number of bytes required for storage
of the value. Call once with value = NULL to get the number of bytes required, then call again with value pointing
to at least the required number of bytes where the value will be copied out. Note that the caller is required to know
the type of value in order to get it. For all types other than string, name, and parsed knowing the type means you
already know the size required.
This call retrieves parameters/values that have made it to the device. Thus, any values set using the
gs_spt_more_to_come without a following call without that flag will not be retrieved. Similarly, attempting to get
a parameter before gsapi_init_with_args has been called will not list any, even if gsapi_set_param has been
used.
Attempting to read a parameter that is not set will return gs_error_undefined (-21). Note that calling
gsapi_set_param followed by gsapi_get_param may not find the value, if the device did not recognise the key
as being one of its configuration keys.

5.2.19 gsapi_enumerate_params()

Enumerate the current parameters. Call repeatedly to list out the current parameters.
The first call should have *iter = NULL. Subsequent calls should pass the same pointer in so the iterator can be
updated. Negative return codes indicate error, 0 success, and 1 indicates that there are no more keys to read. On
success, key will be updated to point to a null terminated string with the key name that is guaranteed to be valid until
the next call to gsapi_enumerate_params. If type is non NULL then *type will be updated to have the type of the
parameter.
Note that only one enumeration can happen at a time. Starting a second enumeration will reset the first.
The enumeration only returns parameters/values that have made it to the device. Thus, any values set using the
gs_spt_more_to_come without a following call without that flag will not be retrieved. Similarly, attempting to enu-
merate parameters before gsapi_init_with_args has been called will not list any, even if gsapi_set_param has
been used.

5.2. Exported functions 95


Ghostscript Documentation, Release 10.01.0

5.2.20 gsapi_add_control_path()

Add a (case sensitive) path to one of the lists of permitted paths for file access. See dSAFER for more information about
permitted paths.

5.2.21 gsapi_remove_control_path()

Remove a (case sensitive) path from one of the lists of permitted paths for file access. See dSAFER for more information
about permitted paths.

5.2.22 gsapi_purge_control_paths()

Clear all the paths from one of the lists of permitted paths for file access. See dSAFER for more information about
permitted paths.

5.2.23 gsapi_activate_path_control()

Enable/Disable path control (i.e. whether paths are checked against permitted paths before access is granted). See
dSAFER for more information about permitted paths.

5.2.24 gsapi_is_path_control_active()

Query whether path control is activated or not. See dSAFER for more information about permitted paths.

5.2.25 gsapi_add_fs

Adds a new ‘Filing System’ to the interpreter. This enables callers to implement their own filing systems. The system
starts with just the conventional ‘file’ handlers installed, to allow access to the local filing system. Whenever files are
to be opened from the interpreter, the file paths are offered around each registered filing system in turn (from most
recently registered to oldest), until either an error is given, or the file is opened successfully.
Details of the gsapi_fs_t are given below.

5.2.26 gsapi_remove_fs

Remove a previously registered ‘Filing System’ from the interpreter. Both the function pointers within the gs_fs_t
and the secret value must match exactly.

5.2.27 gsapi_fs_t

Each ‘filing system’ within gs is a structure of function pointers; each function pointer gives a handler from taking a
different named resource (a file, a pipe, a printer, a scratch file etc) and attempts to open it.

typedef struct
{
int (*open_file)(const gs_memory_t *mem,
void *secret,
const char *fname,
(continues on next page)

96 Chapter 5. API
Ghostscript Documentation, Release 10.01.0

(continued from previous page)


const char *mode,
gp_file **file);
int (*open_pipe)(const gs_memory_t *mem,
void *secret,
const char *fname,
char *rfname, /* 4096 bytes */
const char *mode,
gp_file **file);
int (*open_scratch)(const gs_memory_t *mem,
void *secret,
const char *prefix,
char *rfname, /* 4096 bytes */
const char *mode,
int rm,
gp_file **file);
int (*open_printer)(const gs_memory_t *mem,
void *secret,
char *fname, /* 4096 bytes */
int binary,
gp_file **file);
int (*open_handle)(const gs_memory_t *mem,
void *secret,
char *fname, /* 4096 bytes */
const char *mode,
gp_file **file);
} gsapi_fs_t;

If the filename (always given in utf-8 format) is recognised as being one that the filing system handles (perhaps by the
prefix used), then it should open the file, fill in the gp_file pointer and return 0.
If the filename is not-recognised as being one that the filing system handles, then returning 0 will cause the filename
to be offered to other registered filing systems.
If an error is returned (perhaps gs_error_invalidfileaccess), then no other filing system will be allowed to try to
open the file. This provides a mechanism whereby a caller to gsapi can completely control access to all files accessed
via gp_fopen at runtime.
Note, that while most file access within Ghostscript will be redirected via these functions, stdio will not; see the existing
mechanisms within Ghostscript for intercepting/replacing this.
• The open_file function pointer will be called when something (most often a call to gp_fopen) attempts to
open a file.
• The open_pipe function pointer will be called when something (most often a call to gp_popen) attempts to
open a pipe. rfname points to a 4K buffer in which the actual name of the opened pipe should be returned.
• The open_scratch function pointer will be called when something (most often a call to
gp_open_scratch_file or gp_open_scratch_file_rm) attempts to open a temporary file. rfname
points to a 4K buffer in which the actual name of the opened pipe should be returned. If rm is true, then the file
should be set to delete itself when all handles to it are closed.
• The open_printer function pointer will be called when something (most often a call to gp_open_printer)
attempts to open a stream to a printer. If binary is true, then the stream should be opened as binary; most
streams will be binary by default - this has historical meaning on OS/2.
• The open_handle function pointer will be called when something (most often a call via the postscript %handle%
IO device) attempts to open a Windows handle. This entry point will never be called on non-Windows builds.

5.2. Exported functions 97


Ghostscript Documentation, Release 10.01.0

Any of these which are left as NULL will never be called; a filing system with all of the entries left as NULL is therefore
pointless.
The most complex part of the implementation of these functions is the creation of a gp_file instance to return. There
are some helper functions for this, best explained by example.
Let us consider a hypothetical filing system that encrypts data as it is written, and decrypts it as it is read back. As
each file is read and written the encryption/decryption routines will need to use some state, carried between calls to the
filing system. We therefore might define a new type ‘derived’ from gp_file as follows:

typedef struct
{
gp_file base;
/* State private to the implementation of this file for encryption/decryption */
/* For example: */
int foo;
char *bar;
} gp_file_crypt;

An implementation of gs_fs_t for our ‘crypt’ filing system might then look like this:

gsapi_fs_t gs_fs_crypt =
{
crypt_open_file,
NULL, /* open_pipe */
NULL, /* open_scratch */
NULL, /* open_printer */
NULL /* open_handle */
};

In the above definition, we define a single handler, to cope with the opening of our input/output files. If we wanted to
encrypt/decrypt other files too (perhaps the temporary files we produce) we’d need to define additional handlers (such
as open_scratch).
Our handler might look as follows:

int crypt_open_file(const gs_memory_t *mem,


void *secret,
const char *filename,
const char *mode,
gp_file **file)
{
gp_file_crypt crypt;

/* Ignore any filename not starting with "crypt://" */


if (strncmp(filename, "crypt://", 8) != 0)
return 0;

/* Allocate us an instance (and fill in the non-crypt-specific


* internals) */
crypt = (gp_file_crypt *)gp_file_alloc(mem, &crypt_ops, sizeof(*crypt), "gp_file_
˓→crypt");

if (crypt == NULL)
return gs_error_VMerror; /* Allocation failed */

(continues on next page)

98 Chapter 5. API
Ghostscript Documentation, Release 10.01.0

(continued from previous page)


/* Setup the crypt-specific state */
crypt->foo = 1;
crypt->bar = gs_alloc_bytes(mem->non_gc_memory, 256, "bar");
/* If allocations fail, we need to clean up before exiting */
if (crypt->bar) {
gp_file_dealloc(crypt);
return gs_error_VMerror;
}

/* Return the new instance */


*file = &crypt.base;
return 0;
}

The crucial part of this function is the definition of crypt_ops, an instance of the gp_file_ops_t type; a table of
function pointers that implement the actual operations required.

typedef struct {
int (*close)(gp_file *);
int (*getc)(gp_file *);
int (*putc)(gp_file *, int);
int (*read)(gp_file *, size_t size, unsigned int count, void *buf);
int (*write)(gp_file *, size_t size, unsigned int count, const void *buf);
int (*seek)(gp_file *, gs_offset_t offset, int whence);
gs_offset_t (*tell)(gp_file *);
int (*eof)(gp_file *);
gp_file *(*dup)(gp_file *, const char *mode);
int (*seekable)(gp_file *);
int (*pread)(gp_file *, size_t count, gs_offset_t offset, void *buf);
int (*pwrite)(gp_file *, size_t count, gs_offset_t offset, const void *buf);
int (*is_char_buffered)(gp_file *file);
void (*fflush)(gp_file *file);
int (*ferror)(gp_file *file);
FILE *(*get_file)(gp_file *file);
void (*clearerr)(gp_file *file);
gp_file *(*reopen)(gp_file *f, const char *fname, const char *mode);
} gp_file_ops_t;

These functions generally follow the same patterns as the posix functions that match them, and so in many cases we
will describe these with references to such. Whenever these routines are called, they will be passed a gp_file pointer.
This pointer will have originated from the crypt_open_file call, and so can safely be cast back to a gp_file_crypt
pointer to allow private data to be accessed.
close(gp_file *)
• close the given file; free any storage in the crypt specific parts of gp_file_crypt, but not the
gp_file_crypt structure itself.
int getc(gp_file *)
• Get a single character from the file, returning it as an int (or -1 for EOF). Behaves like
fgetc(FILE *).
int putc(gp_file *, int)

5.2. Exported functions 99


Ghostscript Documentation, Release 10.01.0

• Put a single character to the file, returning the character on success, or EOF (and setting the error
indicator) on error. Behaves like fgetc(FILE *).
int read(gp_file *, size_t size, unsigned int count, void *buf)
• Reads count entries of size bytes the file into buf, returning the number of entries read. Behaves
like fread(FILE *, size, count, buf).
int write(gp_file *, size_t size, unsigned int count, const void *buf)
• Writes count entries of size bytes from buf into the file, returning the number of entries written.
Behaves like fwrite(FILE *, size, count, buf).
int seek(gp_file *, gs_offset_t offset, int whence)
• Seeks within the file. Behaves like fseek(FILE *, offset, whence).
gs_offset_t tell(gp_file *)
• Returns the current offset within the file. Behaves like ftell(FILE *).
int eof(gp_file *)
• Returns 1 if we are at the end of the file, 0 otherwise. Behaves like feof(FILE *).
gp_file * dup(gp_file *, const char *mode)
• Optional function, only used if clist files are to be stored in this filing system. Behaves like
fdup(FILE *). Leave NULL if not implemented.
int seekable(gp_file *)
• Returns 1 if the file is seekable, 0 otherwise. Certain output devices will only work with seekable
files.
int pread(gp_file *, size_t count, gs_offset_t offset, void *buf)
• Optional function, only used if clist files are to be stored in this filing system. Behaves like
an atomic fseek(FILE *, offset, 0) and fread(FILE *, 1, count, buf). Akin to
pread.
int pwrite(gp_file *, size_t count, gs_offset_t offset, const void *buf)
• Optional function, only used if clist files are to be stored in this filing system. Behaves like
an atomic fseek(FILE *, offset, 0) and fwrite(FILE *, 1, count, buf). Akin to
pwrite.
int is_char_buffered(gp_file *file)
• Returns 1 if the file is character buffered, 0 otherwise. Used for handling reading from terminals.
Very unlikely to be used, so returning 0 all the time should be safe. Leave NULL to indicate
“always 0”.
void fflush(gp_file *file)
• Ensures that any buffered data is written to the file. Behaves like fflush(FILE *). Leave NULL
to indicate that no flushing is ever required.
int ferror(gp_file *file)
• Returns non-zero if there has been an error, or 0 otherwise. Behaves like ferror(FILE *).
FILE * get_file(gp_file *file)
• Optional: Gets the FILE * pointer that backs this file. Required for a few devices that insist on
working with FILE *’s direct. Generally safe to leave this set to NULL, and those devices will
fail gracefully.

100 Chapter 5. API


Ghostscript Documentation, Release 10.01.0

void clearerr(gp_file *file)


• Clear the error and EOF values for a file. Behaves like clearerror(FILE *).
gp_file * reopen(gp_file *f, const char *fname, const char *mode)
• Optional function, only used if the gp_file came from an open_scratch call; can be left
as NULL if the open_scratch pointer is set to NULL. Reopen a stream with a different mode.
Behaves like freopen(fname, mode, FILE *).

5.3 Callouts

Callouts are a mechanism for the core code (specifically devices) to communicate with the user of gsapi. This com-
munication can take the form of passing information out vis-a-vis what devices are doing, or requesting configuration
from the caller to affect exactly how the device itself works.
This is deliberately an extensible system, so exact details of callouts should be documented with the device in question.
In general however a callout handler will be of the form:

typedef int (*gs_callout)(void *callout_handle,


const char *device_name,
int id,
int size,
void *data);

The callout_handle value passed to the callout will be the value passed in at registration. The device_name should
be a null-terminated string giving the name of the device (though care should be taken to cope with the case where
device_name is NULL for potential future uses). The id value will have a (device-specific) meaning; see the documen-
tation for the device in question for more details. The same id value may be used to mean different things in different
devices. Finally, size and data have callout specific meanings, but typically, data will be a pointer to data block (which
may either be uninitialised or wholly/partially initialised on entry, and may be updated on exit), and size will be the
size (in bytes) of the block pointed to by data.
A return value of -1 (gs_error_unknownerror) means the callout was not recognised by the handler, and should
be passed to more handlers. Other negative values are interpreted as standard Ghostscript error values, and stop the
propagation of the callout. Non-negative return codes mean the callout was handled and should not be passed to any
more registered callout handlers.

5.4 Return codes

The gsapi_init_with_args, gsapi_run_* and gsapi_exit functions return an integer code.

5.3. Callouts 101


Ghostscript Documentation, Release 10.01.0

5.4.1 Return Codes from gsapi_*()

CODE STATUS
0 No errors
gs_error_Quit “quit” has been executed. This is not an error.
gsapi_exit() must be called next.
gs_error_interrupt The polling callback function returned a negative value,
requesting Ghostscript to abort.
gs_error_NeedInput More input is needed by
gsapi_run_string_continue(). This is not an
error.
gs_error_Info “gs -h” has been executed. This is not an error.
gsapi_exit() must be called next.
<0 Error
<= gs_error_Fatal Fatal error. gsapi_exit() must be called next.

The gsapi_run_*() functions do not flush stdio. If you want to see output from Ghostscript you must do this explicitly
as shown in the example below.
When executing a string with gsapi_run_string_*(), currentfile is the input from the string. Reading from
%stdin uses the stdin callback.

5.5 Example Usage

To try out the following examples in a development environment like Microsoft’s developer tools or Metrowerks Code-
warrior, create a new project, save the example source code as a .c file and add it, along with the Ghostscript dll or
shared library. You will also need to make sure the Ghostscript headers are available, either by adding their location
(the src directory in the Ghostscript source distribution) to the project’s search path, or by copying ierrors.h and
iapi.h into the same directory as the example source.

5.5.1 Example 1

/* Example of using GS DLL as a ps2pdf converter. */

#if defined(_WIN32) && !defined(_Windows)


# define _Windows
#endif
#ifdef _Windows
/* add this source to a project with gsdll32.dll, or compile it directly with:
* cl -D_Windows -Isrc -Febin\ps2pdf.exe ps2pdf.c bin\gsdll32.lib
*/
# include <windows.h>
# define GSDLLEXPORT __declspec(dllimport)
#endif

#include "ierrors.h"
#include "iapi.h"

void *minst = NULL;

(continues on next page)

102 Chapter 5. API


Ghostscript Documentation, Release 10.01.0

(continued from previous page)


int main(int argc, char *argv[])
{
int code, code1;
const char * gsargv[7];
int gsargc;
gsargv[0] = "";
gsargv[1] = "-dNOPAUSE";
gsargv[2] = "-dBATCH";
gsargv[3] = "-dSAFER";
gsargv[4] = "-sDEVICE=pdfwrite";
gsargv[5] = "-sOutputFile=out.pdf";
gsargv[6] = "input.ps";
gsargc=7;

code = gsapi_new_instance(&minst, NULL);


if (code < 0)
return 1;
code = gsapi_set_arg_encoding(minst, GS_ARG_ENCODING_UTF8);
if (code == 0)
code = gsapi_init_with_args(minst, gsargc, gsargv);
code1 = gsapi_exit(minst);
if ((code == 0) || (code == gs_error_Quit))
code = code1;

gsapi_delete_instance(minst);

if ((code == 0) || (code == gs_error_Quit))


return 0;
return 1;
}

5.5.2 Example 2

/* Similar to command line gs */

#if defined(_WIN32) && !defined(_Windows)


# define _Windows
#endif
#ifdef _Windows
/* Compile directly with:
* cl -D_Windows -Isrc -Febin\gstest.exe gstest.c bin\gsdll32.lib
*/
# include <windows.h>
# define GSDLLEXPORT __declspec(dllimport)
#endif
#include <stdio.h>
#include "ierrors.h"
#include "iapi.h"

/* stdio functions */
(continues on next page)

5.5. Example Usage 103


Ghostscript Documentation, Release 10.01.0

(continued from previous page)


static int GSDLLCALL
gsdll_stdin(void *instance, char *buf, int len)
{
int ch;
int count = 0;
while (count < len) {
ch = fgetc(stdin);
if (ch == EOF)
return 0;
*buf++ = ch;
count++;
if (ch == '\n')
break;
}
return count;
}

static int GSDLLCALL


gsdll_stdout(void *instance, const char *str, int len)
{
fwrite(str, 1, len, stdout);
fflush(stdout);
return len;
}

static int GSDLLCALL


gsdll_stderr(void *instance, const char *str, int len)
{
fwrite(str, 1, len, stderr);
fflush(stderr);
return len;
}

void *minst = NULL;


const char start_string[] = "systemdict /start get exec\n";

int main(int argc, char *argv[])


{
int code, code1;
int exit_code;

code = gsapi_new_instance(&minst, NULL);


if (code < 0)
return 1;
gsapi_set_stdio(minst, gsdll_stdin, gsdll_stdout, gsdll_stderr);
code = gsapi_set_arg_encoding(minst, GS_ARG_ENCODING_UTF8);
if (code == 0)
code = gsapi_init_with_args(minst, argc, argv);
if (code == 0)
code = gsapi_run_string(minst, start_string, 0, &exit_code);
code1 = gsapi_exit(minst);
if ((code == 0) || (code == gs_error_Quit))
(continues on next page)

104 Chapter 5. API


Ghostscript Documentation, Release 10.01.0

(continued from previous page)


code = code1;

gsapi_delete_instance(minst);

if ((code == 0) || (code == gs_error_Quit))


return 0;
return 1;
}

5.5.3 Example 3

Replace main() in either of the above with the following code, showing how you can feed Ghostscript piecemeal:

const char *command = "1 2 add == flush\n";

int main(int argc, char *argv[])


{
int code, code1;
int exit_code;

code = gsapi_new_instance(&minst, NULL);


if (code < 0)
return 1;
code = gsapi_set_arg_encoding(minst, GS_ARG_ENCODING_UTF8);
if (code == 0)
code = gsapi_init_with_args(minst, argc, argv);

if (code == 0) {
gsapi_run_string_begin(minst, 0, &exit_code);
gsapi_run_string_continue(minst, command, strlen(command), 0, &exit_code);
gsapi_run_string_continue(minst, "qu", 2, 0, &exit_code);
gsapi_run_string_continue(minst, "it", 2, 0, &exit_code);
gsapi_run_string_end(minst, 0, &exit_code);
}

code1 = gsapi_exit(minst);
if ((code == 0) || (code == gs_error_Quit))
code = code1;

gsapi_delete_instance(minst);

if ((code == 0) || (code == gs_error_Quit))


return 0;
return 1;
}

5.5. Example Usage 105


Ghostscript Documentation, Release 10.01.0

5.5.4 Example 4

When feeding Ghostscript piecemeal buffers, one can use the normal operators to configure things and invoke library
routines. For example, to parse a PDF file one could say:

code = gsapi_run_string(minst, "(example.pdf) .runlibfile", 0, &exit_code);

and Ghostscript would open and process the file named “example.pdf” as if it had been passed as an argument to
gsapi_init_with_args().

5.6 Multiple Threads

The Ghostscript library should have been compiled with a thread safe run time library. Synchronisation of threads is
entirely up to the caller. The exported gsapi_*() functions must be called from one thread only.

5.7 Standard Input and Output

When using the Ghostscript interpreter library interface, you have a choice of two standard input/output methods.
• If you do nothing, the “C” stdio will be used.
• If you use gsapi_set_stdio(), all stdio will be redirected to the callback functions you provide. This would
be used in a graphical user interface environment where stdio is not available, or where you wish to process
Ghostscript input or output.
The callback functions are described in iapi.h.

5.8 Display Device

The display device is available for use with the Ghostscript interpreter library. While originally designed for allowing
screen display of rendered output from Ghostscript, this is now powerful enough to provide a simple mechanism for
getting rendered output suitable for use in all manner of output scenarios, including printing.
Details of the API and options are given in the file gdevdsp.h. This device provides you with access to the raster
output of Ghostscript. It is the callers responsibility to copy this raster to a display window or printer.
In order for this device to operate, it needs access to a structure containing a set of callback functions, and a callback
handle (an opaque void * that can be used by caller to locate its own state). There are 2 ways that the device can get
this information, a legacy method, and a modern method.

5.8.1 Legacy method

The address of the callback structure, is provided using gsapi_set_display_callback(). This must be called after
gsapi_new_instance() and before gsapi_init_with_args().
With this call, the callback handle is passed as NULL by default, but can be overridden by using a parameter. We actively
dislike this way of working, as we consider passing addresses via the command line distasteful. The handle can be set
using:

-sDisplayHandle=1234

106 Chapter 5. API


Ghostscript Documentation, Release 10.01.0

Where “1234” is a string. The API was changed to use a string rather than an integer/long value when support for 64
bit systems arrived. A display “handle” is often a pointer, and since these command line options have to survive being
processed by Postscript machinery, and Postscript only permits 32 bit number values, a different representation was
required. Hence changing the value to a string, so that 64 bit values can be supported. The string formats allowed are:

1234 implicit base 10


10#1234 explicit base 10
16#04d2 explicit base 16

The “number string” is parsed by the display device to retrieve the number value, and is then assigned to the void pointer
parameter “pHandle” in the display device structure. Thus, for a trivial example, passing -sDisplayHandle=0 will
result in the first parameter passed to your display device callbacks being: (void *)0.
The previous API, using a number value:

-dDisplayHandle=1234

is still supported on 32 bit systems, but will cause a “typecheck” error on 64 bit systems, and is considered deprecated.
It should not be used in new code.

5.8.2 Modern method

The preferred method is to register a callout handler using gsapi_register_callout. When this handler is called for
the “display” device, with id = 0 (= DISPLAY_CALLOUT_GET_CALLBACK), then data should point to an empty
gs_display_get_callback_t block, with size = sizeof(gs_display_get_callback_t).

typedef struct {
display_callback *callback;
void *caller_handle;
} gs_display_get_callback_t;

The handler should fill in the structure before returning, with a return code of 0.
Note, that the DisplayHandle value is only consulted for display device callbacks registered using the (legacy, now
deprecated) gsapi_set_display_callback API, not the preferred gsapi_register_callout based mechanism.
The device raster format can be configured using:

-dDisplayFormat=NNNN

Options include:
• native, gray, RGB, CMYK or separation color spaces.
• alpha byte (ignored).
• 1 to 16 bits/component.
• bigendian (RGB) or littleendian (BGR) order.
• top first or bottom first raster.
• 16 bits/pixel with 555 or 565 bitfields.
• Chunky, Planar and Planar interleaved formats.
• “Full screen” or “Rectangle Request” modes of operation.

5.8. Display Device 107


Ghostscript Documentation, Release 10.01.0

The operation of the device is best described with a walkthrough of some example code that uses it. For simplicity and
clarity, we have omitted the error handling code in this example; in production code, every place where we get a code
value returned we should check it for failure (a negative value) and clean up accordingly. First, we create an instance
of Ghostscript:

void *minst = NULL;


code = gsapi_new_instance(&minst, NULL);
code = gsapi_set_stdio(minst, gsdll_stdin, gsdll_stdout, gsdll_stderr);

Next, we have to give the display device the address of our callback structure. In old code, we would do so using
something like this:

code = gsapi_set_display_callback(minst, &display_callback);

We strongly recommend that you don’t do that, but instead use the more modern callout mechanism:

code = gsapi_register_callout(minst, my_callout_handler, state);

where state is any void * value you like, usually a pointer to help you reach any internal state you may need. Earlier
in your code you would have the definition of my_callout_handler that might look like this:

static int
my_callout_handler(void *instance,
void *callout_handle,
const char *device_name,
int id,
int size,
void *data)
{
/* On entry, callout_handle == the value of state passed in
* to gsapi_register_callout. */
/* We are only interested in callouts from the display device. */
if (device_name == NULL || strcmp(device_name, "display"))
return -1;

if (id == DISPLAY_CALLOUT_GET_CALLBACK)
{
/* Fill in the supplied block with the details of our callback
* handler, and the handle to use. In this instance, the handle
* is the pointer to our test structure. */
gs_display_get_callback_t *cb = (gs_display_get_callback_t *)data;
cb->callback = &display_callback;
cb->caller_handle = callout_handle;
return 0;
}
return -1;
}

As you can see, this callout handler only responds to callouts for the display device, and then only for one particular
function (id). It returns the same display_callback structure as the deprecated, legacy mechanism passed in using
gsapi_set_display_callback, with the added benefit that the caller_handle value can be passed in too. In this
example we pass in the same value as was used for callout_handle, but implementations are free to use any value
they want.
Returning to our example, we now set up a set of arguments to setup Ghostscript:

108 Chapter 5. API


Ghostscript Documentation, Release 10.01.0

int argc = 0;
/* Allow for up to 32 args of up to 64 chars each. */
char argv[32][64];
sprintf(argc[argc++], "gs");
sprintf(argv[argc++], "-sDEVICE=display");

The zeroth arg is a dummy argument to match the standard C mechanism for passing arguments to a program. Tradi-
tionally this is the name of the program being invoked. Next, we tell Ghostscript to use the display device.

sprintf(argv[argc++], "-sDEVICE=display");

Next we tell the display device what output format to use. The format is flexible enough to support common Windows,
OS/2, Linux and Mac raster formats.
The format values are described in gdevdsp.h. To select the display device with a Windows 24-bit RGB raster:

sprintf(argv[argc++], "-dDisplayFormat=%d",
DISPLAY_COLORS_RGB | DISPLAY_ALPHA_NONE | DISPLAY_DEPTH_8 |
DISPLAY_LITTLEENDIAN | DISPLAY_BOTTOMFIRST);

If (and only if) you used the legacy mechanism described above, you will need another argument to pass in the
caller_handle value to be parroted back to the functions listed within display_callback:

sprintf(arg2, "-dDisplayHandle=%d", callout_handle);

Any other arguments that you want can be added to the end of the command line, typically including a file to run. Then
we pass that all to Ghostscript:

code = gsapi_init_with_args(minst, argc, argv);

At this point you should start to see your display callback functions being called. Exactly which callback functions are
provided, and how they respond will determine exactly how the display device operates. The primary choice will be
whether the device runs in “full page” or “rectangle request” mode. Details of these are given below.
Once we have finished processing the file, we can process other files using gsapi_run_file, or feed in data using
gsapi_run_string. Once you have finished, you can shut the interpreter down and exit, using:

code = gsapi_exit(minst);
gsapi_delete_instance(minst);

A full list of the display callback functions can be found in gdevdsp.h. There are several different versions of the
callback, corresponding to different “generations” of the device. In general you should use the latest one. The size field
of the structure should be initialised to the size of the structure in bytes.

5.8.3 display_open()

int (*display_open)(void *handle, void *device);

This function will be called when the display device is opened. The device may be opened and closed many times,
sometimes without any output being produced.

5.8. Display Device 109


Ghostscript Documentation, Release 10.01.0

5.8.4 display_preclose()

int (*display_preclose)(void *handle, void *device);

This function will be called when the display device is about to be closed. The device will not actually be closed until
this function returns.

5.8.5 display_close()

int (*display_close)(void *handle, void *device);

This function will be called once the display device has been closed. There will be no more events from the device
unless/until it is reopened.

5.8.6 display_presize()

int (*display_presize)(void *handle, void *device,


int width, int height, int raster, unsigned int format);

This function will be called when the display device is about to be resized. The device will only be resized if this
function returns 0.

5.8.7 display_size()

int (*display_size)(void *handle, void *device, int width, int height,


int raster, unsigned int format, unsigned char *pimage);

This function will be called when the display device is has been resized. The pointer to the raster image is pimage.

5.8.8 display_sync()

int (*display_sync)(void *handle, void *device);

This function may be called periodically during display to flush the page to the display.

5.8.9 display_page()

int (*display_page)(void *handle, void *device, int copies, int flush);

This function is called on a “showpage” operation (i.e. at the end of every page). Operation will continue as soon as
this function returns.

110 Chapter 5. API


Ghostscript Documentation, Release 10.01.0

5.8.10 display_update()

int (*display_update)(void *handle, void *device,


int x, int y, int w, int h);

This function may get called repeatedly during rendering to indicate that an area of the output has been updated. Certain
types of rendering will not see this function called back at all (in particular files using transparency).

5.8.11 display_memalloc()

int (*display_memalloc)(void *handle, void *device,


size_t long size);

Note: In older versions of this API, size is an unsigned long rather than a size_t.
If this function pointer is sent as NULL, then the display device will handle all the memory allocations internally, and
will always work in full page rendering mode.
Otherwise, this function will be called to allocate the storage for the page to be rendered into. If a non-NULL value
is returned, then the device will proceed to render the full page into it. If NULL is returned, then the device will
check a) whether we are using a V2 or greater display callback structure and b) whether that structure specifies a
rectangle_request function pointer.
If both of those conditions are true, then the device will continue in rectangle request mode. Otherwise it will fail with
an out of memory error.

5.8.12 display_memfree()

int (*display_memfree)(void *handle, void *device, void *ptr);

This function should be NULL if and only if display_memalloc is NULL. Any memory allocated using
display_memalloc will be freed via this function.

5.8.13 display_separation()

int (*display_separation)(void *handle, void *device,


int component, const char *component_name,
unsigned short c, unsigned short m,
unsigned short y, unsigned short k);

When using DISPLAY_COLORS_SEPARATION, this function will be called once for every separation component - first
“Cyan”, “Magenta”, “Yellow” and “Black”, then any spot colors used. The supplied c, m, y and k values give the
equivalent color for each spot. Each colorant value ranges from 0 (for none) to 65535 (full).
In separation color mode you are expected to count the number of calls you get to this function after each display_size
to know how many colors you are dealing with.

5.8. Display Device 111


Ghostscript Documentation, Release 10.01.0

5.8.14 display_adjust_band_height()

int (*display_adjust_band_height)(void *handle, void *device,


int bandheight);

When running in “rectangle request mode” the device first renders the page to a display list internally. It can then be
played back repeatedly so that different regions (rectangles) of the page can be extracted in sequence. A common use of
this is to support “banded” operation, where the page is divided into multiple non-overlapping bands of a fixed height.
The display device itself will pick an appropriate band height for it to use. If this function pointer is left as NULL then
this value will be used unchanged. Otherwise, the proposed value will be offered to this function. This function can
override the choice of bandheight, by returning the value that it would like to be used in preference.
In general, this figure should (as much as possible) only be adjusted downwards. For example, a device targeting an
inkjet printer with 200 nozzles in the print head might like to extract bands that are a multiple of 200 lines high. So the
function might return max(200, 200*(bandheight/200)). If the function returns 0, then the existing value will
be used unchanged.
Any size rectangle can be chosen with any size bandheight, so ultimately the value chosen here will not matter much.
It may make some small difference in speed in some cases.

5.8.15 display_rectangle_request()

int (*display_rectangle_request)(void *handle, void *device,


void **memory, int *ox, int *oy,
int *raster, int *plane_raster,
int *x, int *y, int *w, int *h);

If the display device chooses to use rectangle request mode, this function will be called repeatedly to request a rectangle
to render. Ghostscript will render the rectangle, and call this function again. The implementer is expected to handle
the rectangle that has just been rendered, and to return the details of another rectangle to render. This will continue
until a rectangle with zero height or width is returned, whereupon Ghostscript will continue operation.
On entry, *raster and *plane_raster are set to the values expected by the format in use. All the other pointers
point to uninitialised values.
On exit, the values should be updated appropriately. The implementor is expected to store the values returned so that
the rendered output given can be correctly interpreted when control returns to this function.
memory should be updated to point to a block of memory to use for the rendered output. Pixel (*ox, *oy) is the first
pixel represented in that block.
*raster is the number of bytes difference between the address of component 0 of Pixel(*ox, *oy) and the address of
component 0 of Pixel(*ox, 1 + *oy).
*plane_raster is the number of bytes difference between the address of component 0 of Pixel(*ox, *oy) and the
address of component 1 of Pixel(*ox, *oy), if in planar mode, 0 otherwise. *x, *y, *w and *h give the rectangle
requested within that memory block.
Any set of rectangles can be rendered with this method, so this can be used to drive Ghostscript in various ways. Firstly,
it is simple to request a set of non-overlapping “bands” that cover the page, to drive a printer. Alternatively, rectangles
can be chosen to fill a given block of memory to implement a window panning around a larger page. Either the whole
image could be redrawn each time, or smaller rectangles around the edge of the panned area could be requested. The
choice is down to the caller.
Some examples of driving this code in full page mode are in dwmain.c (Windows), dpmain.c (OS/2) and dxmain.c
(X11/Linux), and dmmain.c (MacOS Classic or Carbon).

112 Chapter 5. API


Ghostscript Documentation, Release 10.01.0

Alternatively an example that drives this code in both full page and rectangle request mode can be found in api_test.
c.
On some platforms, the calling convention for the display device callbacks in gdevdsp.h is not the same as the exported
gsapi_*() functions in iapi.h.

5.8. Display Device 113


Ghostscript Documentation, Release 10.01.0

114 Chapter 5. API


CHAPTER

SIX

LANGUAGE BINDINGS

The core of Ghostscript is written in C, but also supports language bindings for the following programming languages:
• C#
• Java
• Python
All of the above languages have equivalent methods as defined in the C API. Java and C# provide additional helper
methods to make the use of the API easier for certain applications. These languages also provide example viewers that
make use of these methods.
This developer documentation is organized by programming language type and includes API reference and sample
code.
Before using the language bindings first ensure that Ghostscript is built for your platform before proceeding. See:
• Building with Visual Studio
• Building with MacOS
• Building with Unix

6.1 The C API

Ghostscript has been in development for over thirty years and is written in C. The API has evolved over time and is
continually being developed. The language bindings into Ghostscript will attempt to mirror this evolution and match
the current C API as much as possible.

6.2 Licensing

Before using Ghostscript, please make sure that you have a valid license to do so. There are two available licenses;
make sure you pick the one whose terms you can comply with.

115
Ghostscript Documentation, Release 10.01.0

6.2.1 Open Source license

If your software is open source, you may use Ghostscript under the terms of the GNU Affero General Public License.
This means that all of the source code for your complete app must be released under a compatible open source license!
It also means that you may not use any proprietary closed source libraries or components in your app.
Please read the full text of the AGPL license agreement from the FSF web site
If you cannot or do not want to comply with these restrictions, you must acquire a commercial license instead.

6.2.2 Commercial license

If your project does not meet the requirements of the AGPL, please contact our sales team to discuss a commercial
license. Each Artifex commercial license is crafted based on your individual use case.

6.3 Demo code

Please locate the demos folder in your ghostpdl source code download from the GhostPDL repository to find sample
code demonstrating the language bindings in action.

6.4 C#

6.4.1 Introduction

In the GhostPDL repository a sample C# project can be found in /demos/csharp.


Within this project the following namespaces and corresponding C# files are of relevance:
• GhostAPI ghostapi.cs
• GhostNET ghostnet.cs
• GhostMono ghostmono.cs

6.4.2 Platform & setup

Ghostscript should be built as a shared library for your platform.


See Building Ghostscript.

6.4.3 GhostAPI

GhostAPI is the main wrapper responsible for bridging over to the C library and ensuring that the correct DLLs are
imported.
GhostAPI contains the ghostapi class which does not need to be instantiated as it provides public static methods.
These methods, which mirror their C counterparts, are as follows:

116 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

Method Description
gsapi_revision Returns the revision numbers and strings of the Ghostscript interpreter library.
gsapi_new_instance Create a new instance of Ghostscript.
gsapi_delete_instance Destroy an instance of Ghostscript.
gsapi_set_stdio_with_handle Set the callback functions for stdio, together with the handle to use in the callback
functions.
gsapi_set_stdio Set the callback functions for stdio.
gsapi_set_poll_with_handle Set the callback function for polling, together with the handle to pass to the callback
function.
gsapi_set_poll Set the callback function for polling.
gsapi_set_display_callback deprecated
gsapi_register_callout This call registers a callout handler.
gsapi_deregister_callout This call deregisters a previously registered callout handler.
gsapi_set_arg_encoding Set the encoding used for the interpretation of all subsequent args supplied via the
gsapi interface on this instance.
gsapi_set_default_device_listSet the string containing the list of default device names.
gsapi_get_default_device_listReturns a pointer to the current default device string.
gsapi_init_with_args Initialise the interpreter.
gsapi_run_* (Wildcard for various “run” methods).
gsapi_exit Exit the interpreter.
gsapi_set_param Set a parameter.
gsapi_get_param Get a parameter.
gsapi_enumerate_params Enumerate the current parameters.
gsapi_add_control_path Add a (case sensitive) path to one of the lists of permitted paths for file access.
gsapi_remove_control_path Remove a (case sensitive) path from one of the lists of permitted paths for file access.
gsapi_purge_control_paths Clear all the paths from one of the lists of permitted paths for file access.
gsapi_activate_path_control Enable/Disable path control.
gsapi_is_path_control_activeQuery whether path control is activated or not.

GhostAPI contains some essential structs & enums as well as a static class for some constants, finally it contains the
main GSAPI class which holds the key methods which interface with the C library.

Structs and Enums

gsapi_revision_t

This struct is used to contain information pertinent to the version of Ghostscript.

public struct gsapi_revision_t


{
public IntPtr product;
public IntPtr copyright;
public int revision;
public int revisiondate;
}

6.4. C# 117
Ghostscript Documentation, Release 10.01.0

gs_set_param_type

public enum gs_set_param_type


{
gs_spt_invalid = -1,
gs_spt_null = 0, /* void * is NULL */
gs_spt_bool = 1, /* void * is NULL (false) or non-NULL (true) */
gs_spt_int = 2, /* void * is a pointer to an int */
gs_spt_float = 3, /* void * is a float * */
gs_spt_name = 4, /* void * is a char * */
gs_spt_string = 5, /* void * is a char * */
gs_spt_long = 6, /* void * is a long * */
gs_spt_i64 = 7, /* void * is an int64_t * */
gs_spt_size_t = 8, /* void * is a size_t * */
gs_spt_parsed = 9, /* void * is a pointer to a char * to be parsed */
gs_spt_more_to_come = 1 << 31
};

gsEncoding

public enum gsEncoding


{
GS_ARG_ENCODING_LOCAL = 0,
GS_ARG_ENCODING_UTF8 = 1,
GS_ARG_ENCODING_UTF16LE = 2
};

Constants

Constants are stored in the static class gsConstants for direct referencing.

gsConstants

static class gsConstants


{
public const int E_QUIT = -101;
public const int GS_READ_BUFFER = 32768;
public const int DISPLAY_UNUSED_LAST = (1 << 7);
public const int DISPLAY_COLORS_RGB = (1 << 2);
public const int DISPLAY_DEPTH_8 = (1 << 11);
public const int DISPLAY_LITTLEENDIAN = (1 << 16);
public const int DISPLAY_BIGENDIAN = (0 << 16);
}

118 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

GSAPI

Methods contained within are explained below.


gsapi_run_* and gsapi_exit methods return an int code which can be interpreted as follows:

code status
0 no error
gsConstants.E_QUIT “quit” has been executed. This is not an error. gsapi_exit must be called next
<0 error

Note: For full details on these return codes please see The C API return codes.
All GSAPI methods aside from gsapi_revision and gsapi_new_instance should pass an instance of Ghostscript
as their first parameter with an IntPtr instance

gsapi_revision

This method returns the revision numbers and strings of the Ghostscript interpreter library; you should call it before any
other interpreter library functions to make sure that the correct version of the Ghostscript interpreter has been loaded.

public static extern int gsapi_revision(ref gsapi_revision_t vers, int size);

Note: The method should write to a reference variable which conforms to the struct gsapi_revision_t.

gsapi_new_instance

Creates a new instance of Ghostscript. This instance is passed to most other GSAPI methods. Unless Ghostscript has
been compiled with the GS_THREADSAFE define, only one instance at a time is supported.

public static extern int gsapi_new_instance(out IntPtr pinstance,


IntPtr caller_handle);

Note: The method returns a pointer which represents your instance of Ghostscript.

gsapi_delete_instance

Destroy an instance of Ghostscript. Before you call this, Ghostscript must have finished. If Ghostscript has been
initialised, you must call gsapi_exit beforehand.

public static extern void gsapi_delete_instance(IntPtr instance);

Sample code:

GSAPI.gsapi_delete_instance(gsInstance);
gsInstance = IntPtr.Zero;

6.4. C# 119
Ghostscript Documentation, Release 10.01.0

gsapi_set_stdio_with_handle

Set the callback functions for stdio, together with the handle to use in the callback functions. The stdin callback
function should return the number of characters read, 0 for EOF, or -1 for error. The stdout and stderr callback
functions should return the number of characters written.

Note: These callbacks do not affect output device I/O when using “%stdout” as the output file. In that case, device
output will still be directed to the process “stdout” file descriptor, not to the stdio callback.

public static extern int gsapi_set_stdio_with_handle(IntPtr instance,


gs_stdio_handler stdin,
gs_stdio_handler stdout,
gs_stdio_handler stderr,
IntPtr caller_handle);

gsapi_set_stdio

Set the callback functions for stdio. The handle used in the callbacks will be taken from the value passed to
gsapi_new_instance. Otherwise the behaviour of this function matches gsapi_set_stdio_with_handle.

public static extern int gsapi_set_stdio_with_handle(IntPtr instance,


gs_stdio_handler stdin,
gs_stdio_handler stdout,
gs_stdio_handler stderr);

gsapi_set_poll_with_handle

Set the callback function for polling, together with the handle to pass to the callback function. This function will only
be called if the Ghostscript interpreter was compiled with CHECK_INTERRUPTS as described in gpcheck.h.
The polling function should return zero if all is well, and return negative if it wants Ghostscript to abort. This is often
used for checking for a user cancel. This can also be used for handling window events or cooperative multitasking.
The polling function is called very frequently during interpretation and rendering so it must be fast. If the function
is slow, then using a counter to return 0 immediately some number of times can be used to reduce the performance
impact.

public static extern int gsapi_set_poll_with_handle(IntPtr instance,


gsPollHandler pollfn,
IntPtr caller_handle);

120 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

gsapi_set_poll

Set the callback function for polling. The handle passed to the callback function will be taken from the handle passed
to gsapi_new_instance. Otherwise the behaviour of this function matches gsapi_set_poll_with_handle.

public static extern int gsapi_set_poll(IntPtr instance,


gsPollHandler pollfn);

gsapi_set_display_callback

This call is deprecated; please use gsapi_register_callout to register a callout handler for the display device in prefer-
ence.

public static extern int gsapi_set_display_callback(IntPtr pinstance,


IntPtr caller_handle);

gsapi_register_callout

This call registers a callout handler.

public static extern int gsapi_register_callout(IntPtr instance,


gsCallOut callout,
IntPtr callout_handle);

gsapi_deregister_callout

This call deregisters a callout handler previously registered with gsapi_register_callout. All three arguments must
match exactly for the callout handler to be deregistered.

public static extern int gsapi_deregister_callout(IntPtr instance,


gsCallOut callout,
IntPtr callout_handle);

gsapi_set_arg_encoding

Set the encoding used for the interpretation of all subsequent arguments supplied via the GhostAPI interface on this
instance. By default we expect args to be in encoding 0 (the ‘local’ encoding for this OS). On Windows this means “the
currently selected codepage”. On Linux this typically means utf8. This means that omitting to call this function will
leave Ghostscript running exactly as it always has. Please note that use of the ‘local’ encoding is now deprecated and
should be avoided in new code. This must be called after gsapi_new_instance and before gsapi_init_with_args.

public static extern int gsapi_set_arg_encoding(IntPtr instance,


int encoding);

6.4. C# 121
Ghostscript Documentation, Release 10.01.0

gsapi_set_default_device_list

Set the string containing the list of default device names, for example “display x11alpha x11 bbox”. Allows the calling
application to influence which device(s) Ghostscript will try, in order, in its selection of the default device. This must
be called after gsapi_new_instance and before gsapi_init_with_args.

public static extern int gsapi_set_default_device_list(IntPtr instance,


IntPtr list,
ref int listlen);

gsapi_get_default_device_list

Returns a pointer to the current default device string. This must be called after gsapi_new_instance and before
gsapi_init_with_args.

public static extern int gsapi_get_default_device_list(IntPtr instance,


ref IntPtr list,
ref int listlen);

gsapi_init_with_args

To initialise the interpreter, pass your instance of Ghostscript, your argument count, argc and your argument vari-
ables, argv.

public static extern int gsapi_init_with_args(IntPtr instance,


int argc,
IntPtr argv);

gsapi_run_*

If these functions return <= -100, either quit or a fatal error has occured. You must call gsapi_exit next. The only
exception is gsapi_run_string_continue which will return gs_error_NeedInput if all is well.
There is a 64 KB length limit on any buffer submitted to a gsapi_run_* function for processing. If you have more than
65535 bytes of input then you must split it into smaller pieces and submit each in a separate gsapi_run_string_continue
call.

gsapi_run_string_begin

public static extern int gsapi_run_string_begin(IntPtr instance,


int usererr,
ref int exitcode);

122 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

gsapi_run_string_continue

public static extern int gsapi_run_string_continue(IntPtr instance,


IntPtr command,
int count,
int usererr,
ref int exitcode);

gsapi_run_string_with_length

public static extern int gsapi_run_string_with_length(IntPtr instance,


IntPtr command,
uint length,
int usererr,
ref int exitcode);

gsapi_run_string

public static extern int gsapi_run_string(IntPtr instance,


IntPtr command,
int usererr,
ref int exitcode);

gsapi_run_string_end

public static extern int gsapi_run_string_end(IntPtr instance,


int usererr,
ref int exitcode);

6.4. C# 123
Ghostscript Documentation, Release 10.01.0

gsapi_run_file

public static extern int gsapi_run_file(IntPtr instance,


IntPtr filename,
int usererr,
ref int exitcode);

gsapi_exit

Exit the interpreter. This must be called on shutdown if gsapi_init_with_args has been called, and just before
gsapi_delete_instance.

public static extern int gsapi_exit(IntPtr instance);

gsapi_set_param

Sets a parameter.
Broadly, this is equivalent to setting a parameter using -d, -s or -p on the command line. This call cannot be made
during a gsapi_run_string operation.
Parameters in this context are not the same as ‘arguments’ as processed by gsapi_init_with_args, but often the same
thing can be achieved. For example, with gsapi_init_with_args, we can pass “-r200” to change the resolution. Broadly
the same thing can be achieved by using gsapi_set_param to set a parsed value of “<</HWResolution [ 200.0 200.0
]>>”.
Internally, when we set a parameter, we perform an initgraphics operation. This means that using gsapi_set_param
other than at the start of a page is likely to give unexpected results.
Attempting to set a parameter that the device does not recognise will be silently ignored, and that parameter will not
be found in subsequent gsapi_get_param calls.

public static extern int gsapi_set_param(IntPtr instance,


IntPtr param,
IntPtr value,
gs_set_param_type type);

Note: The type argument, as a gs_set_param_type, dictates the kind of object that the value argument points to.
For more on the C implementation of parameters see: Ghostscript parameters in C.

gsapi_get_param

Retrieve the current value of a parameter.


If an error occurs, the return value is negative. Otherwise the return value is the number of bytes required for storage
of the value. Call once with value NULL to get the number of bytes required, then call again with value pointing to at
least the required number of bytes where the value will be copied out. Note that the caller is required to know the type
of value in order to get it. For all types other than gs_spt_string, gs_spt_name, and gs_spt_parsed knowing the
type means you already know the size required.

124 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

This call retrieves parameters/values that have made it to the device. Thus, any values set using gs_spt_more_to_come
without a following call omitting that flag will not be retrieved. Similarly, attempting to get a parameter before
gsapi_init_with_args has been called will not list any, even if gsapi_set_param has been used.
Attempting to read a parameter that is not set will return gs_error_undefined (-21). Note that calling
gsapi_set_param followed by gsapi_get_param may not find the value, if the device did not recognise the key as being
one of its configuration keys.
For further documentation please refer to the C API.

public static extern int gsapi_get_param(IntPtr instance,


IntPtr param,
IntPtr value,
gs_set_param_type type);

gsapi_enumerate_params

Enumerate the current parameters. Call repeatedly to list out the current parameters.
The first call should have iter = NULL. Subsequent calls should pass the same pointer in so the iterator can be updated.
Negative return codes indicate error, 0 success, and 1 indicates that there are no more keys to read. On success, key
will be updated to point to a null terminated string with the key name that is guaranteed to be valid until the next call to
gsapi_enumerate_params. If type is non NULL then the pointer type will be updated to have the type of the parameter.

Note: Only one enumeration can happen at a time. Starting a second enumeration will reset the first.

The enumeration only returns parameters/values that have made it to the device. Thus, any values set using the
gs_spt_more_to_come without a following call omitting that flag will not be retrieved. Similarly, attempting to
enumerate parameters before gsapi_init_with_args has been called will not list any, even if gsapi_set_param has been
used.

public static extern int gsapi_enumerate_params(IntPtr instance,


out IntPtr iter,
out IntPtr key,
IntPtr type);

gsapi_add_control_path

Add a (case sensitive) path to one of the lists of permitted paths for file access.

public static extern int gsapi_add_control_path(IntPtr instance,


int type,
IntPtr path);

6.4. C# 125
Ghostscript Documentation, Release 10.01.0

gsapi_remove_control_path

Remove a (case sensitive) path from one of the lists of permitted paths for file access.

public static extern int gsapi_remove_control_path(IntPtr instance,


int type,
IntPtr path);

gsapi_purge_control_paths

Clear all the paths from one of the lists of permitted paths for file access.

public static extern void gsapi_purge_control_paths(IntPtr instance,


int type);

gsapi_activate_path_control

Enable/Disable path control (i.e. whether paths are checked against permitted paths before access is granted).

public static extern void gsapi_activate_path_control(IntPtr instance,


int enable);

gsapi_is_path_control_active

Query whether path control is activated or not.

public static extern int gsapi_is_path_control_active(IntPtr instance);

Callback and Callout prototypes

GSAPI also defines some prototype pointers which are defined as follows.

gs_stdio_handler

/* Callback proto for stdio */


public delegate int gs_stdio_handler(IntPtr caller_handle,
IntPtr buffer,
int len);

126 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

gsPollHandler

/* Callback proto for poll function */


public delegate int gsPollHandler(IntPtr caller_handle);

gsCallOut

/* Callout proto */
public delegate int gsCallOut(IntPtr callout_handle,
IntPtr device_name,
int id,
int size,
IntPtr data);

6.4.4 GhostNET

GhostNET is the .NET interface into GhostAPI. It exemplifies how to do more complex operations involving multiple
API calls and sequences. See the table below for the main methods:

Method Description Notes


GetVersion Returns the version of Ghostscript.
DisplayDeviceOpen Sets up the display device ahead of time.
DisplayDevice- Closes the display device and deletes the instance.
Close
GetPageCount Returns the page count for the document.
CreateXPS Launches a thread to create an XPS document for Windows printing. asyn-
chronous
DistillPS Launches a thread rendering all the pages of a supplied PostScript file to a PDF. asyn-
chronous
DisplayDeviceRun- Launches a thread to run a file with the display device. asyn-
File chronous
DisplayDeviceRen- Launches a thread rendering all the pages with the display device to collect thumbnail asyn-
derThumbs images. chronous
DisplayDeviceRen- Launches a thread rendering a set of pages with the display device. asyn-
derPages chronous
GetStatus Returns the current status of Ghostscript.
Cancel Cancels asynchronous operations.
GhostscriptExcep- An application developer can log any exceptions in this public class.
tion

In demos/csharp/windows/ghostnet.sln there is a sample C# demo project.


This project can be opened in Visual Studio and used to test the Ghostscript API alongside a UI which handles opening
PostScript and PDF files. The sample application here allows for file browsing and Ghostscript file viewing.
Below is a screenshot of the sample application with a PDF open:

6.4. C# 127
Ghostscript Documentation, Release 10.01.0

Enums

Tasks

The Ghostscript task type enum is used to inform GhostAPI of the type of operation which is being requested.

Task Description
PS_DISTILL Task associated with converting a PostScript stream to a PDF document.
CREATE_XPS Task associated with outputting a copy of a document to XPS.
SAVE_RESULT Task associated with saving documents.
GET_PAGE_COUNT Task associated with getting the page count of a document.
GENERIC Generic task identifier.
DISPLAY_DEV_THUMBSDisplay Device task associated with rendering thumbnails.
Display Device task associated with non-PDF or non-XPS rendering (see: Ghostscript &
DISPLAY_DEV_NON_PDF
Page Description Languages).
DISPLAY_DEV_PDF Display Device task associated with PDF & XPS rendering (see: Ghostscript & Page De-
scription Languages).
Display Device task associated with running files.
DISPLAY_DEV_RUN_FILE

Task types are defined as GS_Task_t.

public enum GS_Task_t


{
PS_DISTILL,
CREATE_XPS,
SAVE_RESULT,
GET_PAGE_COUNT,
GENERIC,
DISPLAY_DEV_THUMBS,
DISPLAY_DEV_NON_PDF,
DISPLAY_DEV_PDF,
DISPLAY_DEV_RUN_FILE
}

Results

Result types are defined as GS_Result_t.

public enum GS_Result_t


{
gsOK,
gsFAILED,
gsCANCELLED
}

128 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

Status

Status types are defined as gsStatus.

public enum gsStatus


{
GS_READY,
GS_BUSY,
GS_ERROR
}

The Parameter Struct

The parameter struct gsParamState_t allows for bundles of information to be processed by Ghostscript to complete
overall requests.

public struct gsParamState_t


{
public String outputfile;
public String inputfile;
public GS_Task_t task;
public GS_Result_t result;
public int num_pages;
public List<int> pages;
public int firstpage;
public int lastpage;
public int currpage;
public List<String> args;
public int return_code;
public double zoom;
public bool aa;
public bool is_valid;
};

Parameters explained

Setting up your parameters (with any dedicated bespoke method(s) which your application requires) is needed when
communicating directly with GhostAPI.
When requesting Ghostscript to process an operation an application developer should send a parameter payload which
defines the details for the operation.
For example in GhostNET we can see the public method as follows:

public gsStatus DistillPS(String fileName, int resolution)


{
gsParamState_t gsparams = new gsParamState_t();
gsparams.args = new List<string>();

gsparams.inputfile = fileName;
gsparams.args.Add("gs");
gsparams.args.Add("-sDEVICE=pdfwrite");
(continues on next page)

6.4. C# 129
Ghostscript Documentation, Release 10.01.0

(continued from previous page)


gsparams.outputfile = Path.GetTempFileName();
gsparams.args.Add("-o" + gsparams.outputfile);
gsparams.task = GS_Task_t.PS_DISTILL;

return RunGhostscriptAsync(gsparams);
}

Here we can see a parameter payload being setup before being passed on to the asynchronous method
RunGhostscriptAsync which sets up a worker thread to run according to the task type in the payload.
GhostNET handles many common operations on an application developer’s behalf, however if you require to write your
own methods to interface with GhostAPI then referring to the public methods in GhostNET is a good starting point.
For full documentation on parameters refer to Ghostscript parameters.

The Event class

GhostNET contains a public class gsEventArgs which is an extension of the C# class EventArgs. This class is used
to set and get events as they occur. GhostNET will create these payloads and deliver them back to the application layer’s
ProgressCallBack method asynchronously.

public class gsEventArgs : EventArgs


{
private bool m_completed;
private int m_progress;
private gsParamState_t m_param;
public bool Completed
{
get { return m_completed; }
}
public gsParamState_t Params
{
get { return m_param; }
}
public int Progress
{
get { return m_progress; }
}
public gsEventArgs(bool completed, int progress, gsParamState_t param)
{
m_completed = completed;
m_progress = progress;
m_param = param;
}
}

130 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

GSNET

This class should be instantiated as a member variable in your application with callback definitions setup as required.
Handlers for asynchronous operations can injected by providing your own bespoke callback methods to your instance’s
ProgressCallBack function.

Sample code

/* Set up ghostscript with callbacks for system updates */


m_ghostscript = new GSNET();
m_ghostscript.ProgressCallBack += new GSNET.Progress(gsProgress);
m_ghostscript.StdIOCallBack += new GSNET.StdIO(gsIO);
m_ghostscript.DLLProblemCallBack += new GSNET.DLLProblem(gsDLL);
m_ghostscript.PageRenderedCallBack += new GSNET.PageRendered(gsPageRendered);
m_ghostscript.DisplayDeviceOpen();

/* example callback stubs for asynchronous operations */


private void gsProgress(gsEventArgs asyncInformation)
{
Console.WriteLine($"gsProgress().progress:{asyncInformation.Progress}");

if (asyncInformation.Completed) // task complete


{
// what was the task?
switch (asyncInformation.Params.task)
{
case GS_Task_t.CREATE_XPS:
Console.WriteLine($"CREATE_XPS.outputfile:");
Console.WriteLine($"{asyncInformation.Params.result.outputfile}");
break;

case GS_Task_t.PS_DISTILL:
Console.WriteLine($"PS_DISTILL.outputfile:");
Console.WriteLine($"{asyncInformation.Params.result.outputfile}");
break;

case GS_Task_t.SAVE_RESULT:

break;

case GS_Task_t.DISPLAY_DEV_THUMBS:

break;

case GS_Task_t.DISPLAY_DEV_RUN_FILE:

break;

case GS_Task_t.DISPLAY_DEV_PDF:

break;
(continues on next page)

6.4. C# 131
Ghostscript Documentation, Release 10.01.0

(continued from previous page)

case GS_Task_t.DISPLAY_DEV_NON_PDF:

break;

default:

break;
}

// task failed
if (asyncInformation.Params.result == GS_Result_t.gsFAILED)
{
switch (asyncInformation.Params.task)
{
case GS_Task_t.CREATE_XPS:

break;

case GS_Task_t.PS_DISTILL:

break;

case GS_Task_t.SAVE_RESULT:

break;

default:

break;
}
return;
}

// task cancelled
if (asyncInformation.Params.result == GS_Result_t.gsCANCELLED)
{

}
}
else // task is still running
{
switch (asyncInformation.Params.task)
{
case GS_Task_t.CREATE_XPS:

break;

case GS_Task_t.PS_DISTILL:

break;

(continues on next page)

132 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

(continued from previous page)


case GS_Task_t.SAVE_RESULT:

break;
}
}
}

private void gsIO(String message, int len)


{
Console.WriteLine($"gsIO().message:{message}, length:{len}");
}

private void gsDLL(String message)


{
Console.WriteLine($"gsDLL().message:{message}");
}

private void gsPageRendered(int width,


int height,
int raster,
IntPtr data,
gsParamState_t state)
{

};

Note: Once a Ghostscript operation is in progress any defined callback functions will be called as the operation runs
up unto completion. These callback methods are essential for your application to interpret activity events and react
accordingly.

An explanation of callbacks and the available public methods within GSNET are explained below.

Delegates

To handle asynchronous events GhostNET has four delegates which define callback methods that an application can
assign to.

Callback Description
DLLProblemCallBack Occurs if there is some issue with the Ghostscript DLL.
StdIOCallBack Occurs if Ghostscript outputs something to stderr or stdout.
ProgressCallBack Occurs as Ghostscript makes its way through a file.
PageRenderedCallBack Occurs when a page has been rendered and the data from the display device is ready.

6.4. C# 133
Ghostscript Documentation, Release 10.01.0

DLLProblemCallBack

internal delegate void DLLProblem(String mess);


internal event DLLProblem DLLProblemCallBack;

StdIOCallBack

internal delegate void StdIO(String mess,


int len);
internal event StdIO StdIOCallBack;

ProgressCallBack

internal delegate void Progress(gsEventArgs info);


internal event Progress ProgressCallBack;

PageRenderedCallBack

internal delegate void PageRendered(int width,


int height,
int raster,
IntPtr data,
gsParamState_t state);
internal event PageRendered PageRenderedCallBack;

GetVersion

Use this method to get Ghostscript version info as a String.

public String GetVersion()

Sample code:

String gs_vers = m_ghostscript.GetVersion();

Note: An exception will be thrown if there is any issue with the Ghostscript DLL.

134 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

DisplayDeviceOpen

Sets up the display device ahead of time.

public gsParamState_t DisplayDeviceOpen()

Sample code:

m_ghostscript.DisplayDeviceOpen();

Note: Calling this method instantiates Ghostscript and configures the encoding and the callbacks for the display device.

DisplayDeviceClose

Closes the display device and deletes the instance.

public gsParamState_t DisplayDeviceClose()

Sample code:

m_ghostscript.DisplayDeviceClose();

Note: Calling this method deletes Ghostscript.

GetPageCount

Use this method to get the number of pages in a supplied document.

public int GetPageCount(String fileName)

Sample code:

int page_number = m_ghostscript.GetPageCount("my_document.pdf");

Note: If Ghostscript is unable to determine the page count then this method will return -1.

CreateXPS

Launches a thread to create an XPS document for Windows printing. This method is asynchronous and logic should
be hooked into your application upon GSNET instantiation to interpret progress.

public gsStatus CreateXPS(String fileName,


int resolution,
int num_pages,
double width,
(continues on next page)

6.4. C# 135
Ghostscript Documentation, Release 10.01.0

(continued from previous page)


double height,
bool fit_page,
int firstpage,
int lastpage)

Sample code:

m_ghostscript.CreateXPS("my_document.pdf",
300,
10,
1000,
1000,
true,
0,
9);

DistillPS

Launches a thread rendering all the pages of a supplied PostScript file to a PDF.

public gsStatus DistillPS(String fileName, int resolution)

Sample code:

m_ghostscript.DistillPS("my_postscript_document.ps", 300);

DisplayDeviceRunFile

Launches a thread to run a file with the display device.

public gsStatus DisplayDeviceRunFile(String fileName,


double zoom,
bool aa, // anti-aliasing value
int firstpage,
int lastpage)

Sample code:

m_ghostscript.DisplayDeviceRunFile("my_document.pdf",
1.0,
true,
0,
9);

136 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

DisplayDeviceRenderThumbs

Launches a thread rendering all the pages with the display device to collect thumbnail images.
Recommended zoom level for thumbnails is between 0.05 and 0.2, additionally anti-aliasing is probably not required.

public gsStatus DisplayDeviceRenderThumbs(String fileName,


double zoom,
bool aa)

Sample code:

m_ghostscript.DisplayDeviceRenderThumbs("my_document.pdf",
0.1,
false);

DisplayDeviceRenderPages

Launches a thread rendering a set of pages with the display device. For use with languages that can be indexed via
pages which include PDF and XPS. (see: Ghostscript & Page Description Languages)

public gsStatus DisplayDeviceRenderPages(String fileName,


int first_page,
int last_page,
double zoom)

Sample code:

m_ghostscript.DisplayDeviceRenderPages("my_document.pdf",
0,
9,
1.0);

GetStatus

Returns the current status of Ghostscript.

public gsStatus GetStatus()

Sample code:

gsStatus status = m_ghostscript.GetStatus();

6.4. C# 137
Ghostscript Documentation, Release 10.01.0

Cancel

Cancels asynchronous operations.

public void Cancel()

Sample code:

m_ghostscript.Cancel();

GhostscriptException

An application developer can log any exceptions in this public class as required by editing the constructor.

public class GhostscriptException : Exception


{
public GhostscriptException(string message) : base(message)
{
// Report exceptions as required
}
}

6.4.5 GhostMono

GhostMono is the C# interface into the GhostAPI library and is developed for Linux systems.
As such GhostMono is the Mono equivalent of GhostNET with no dependency on a Windows environment.

Enums

Tasks

The Ghostscript task type enum is used to inform GhostAPI of the type of operation which is being requested.

Task Description
PS_DISTILL Task associated with converting a PostScript stream to a PDF document.
CREATE_XPS Task associated with outputting a copy of a document to XPS.
SAVE_RESULT Task associated with saving documents.
GET_PAGE_COUNT Task associated with getting the page count of a document.
GENERIC Generic task identifier.
DISPLAY_DEV_THUMBSDisplay Device task associated with rendering thumbnails.
Display Device task associated with non-PDF or non-XPS rendering (see: Ghostscript &
DISPLAY_DEV_NON_PDF
Page Description Languages).
DISPLAY_DEV_PDF Display Device task associated with PDF & XPS rendering (see: Ghostscript & Page De-
scription Languages).
Display Device task associated with running files.
DISPLAY_DEV_RUN_FILE

Task types are defined as GS_Task_t.

138 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

public enum GS_Task_t


{
PS_DISTILL,
CREATE_XPS,
SAVE_RESULT,
GET_PAGE_COUNT,
GENERIC,
DISPLAY_DEV_THUMBS,
DISPLAY_DEV_NON_PDF,
DISPLAY_DEV_PDF,
DISPLAY_DEV_RUN_FILE
}

Results

Result types are defined as GS_Result_t.

public enum GS_Result_t


{
gsOK,
gsFAILED,
gsCANCELLED
}

Status

Status types are defined as gsStatus.

public enum gsStatus


{
GS_READY,
GS_BUSY,
GS_ERROR
}

The Parameter Struct

The parameter struct gsParamState_t allows for bundles of information to be processed by Ghostscript to complete
overall requests.

public struct gsParamState_t


{
public String outputfile;
public String inputfile;
public GS_Task_t task;
public GS_Result_t result;
public int num_pages;
public List<int> pages;
public int firstpage;
(continues on next page)

6.4. C# 139
Ghostscript Documentation, Release 10.01.0

(continued from previous page)


public int lastpage;
public int currpage;
public List<String> args;
public int return_code;
public double zoom;
};

Parameters explained

Setting up your parameters (with any dedicated bespoke method(s) which your application requires) is needed when
communicating directly with GhostAPI.
When requesting Ghostscript to process an operation an application developer should send a parameter payload which
defines the details for the operation.
For example in GhostMono we can see the public method as follows:

public gsStatus DistillPS(String fileName, int resolution)


{
gsParamState_t gsparams = new gsParamState_t();
gsparams.args = new List<string>();

gsparams.inputfile = fileName;
gsparams.args.Add("gs");
gsparams.args.Add("-dNOPAUSE");
gsparams.args.Add("-dBATCH");
gsparams.args.Add("-I%rom%Resource/Init/");
gsparams.args.Add("-dSAFER");
gsparams.args.Add("-sDEVICE=pdfwrite");
gsparams.outputfile = Path.GetTempFileName();
gsparams.args.Add("-o" + gsparams.outputfile);
gsparams.task = GS_Task_t.PS_DISTILL;

return RunGhostscriptAsync(gsparams);
}

Here we can see a parameter payload being setup before being passed on to the asynchronous method
RunGhostscriptAsync which sets up a worker thread to run according to the task type in the payload.
GhostMono handles many common operations on an application developer’s behalf, however if you require to write
your own methods to interface with GhostAPI then referring to the public methods in GhostMono is a good starting
point.
For full documentation on parameters refer to Ghostscript parameters in C.

140 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

The Event class

GhostMono contains a public class gsThreadCallBack. This class is used to set and get callback information as they
occur. GhostMono will create these payloads and deliver them back to the application layer’s ProgressCallBack
method asynchronously.

public class gsThreadCallBack


{
private bool m_completed;
private int m_progress;
private gsParamState_t m_param;
public bool Completed
{
get { return m_completed; }
}
public gsParamState_t Params
{
get { return m_param; }
}
public int Progress
{
get { return m_progress; }
}
public gsThreadCallBack(bool completed, int progress, gsParamState_t param)
{
m_completed = completed;
m_progress = progress;
m_param = param;
}
}

GSMONO

This class should be instantiated as a member variable in your application with callback definitions setup as required.
Handlers for asynchronous operations can injected by providing your own bespoke callback methods to your instance’s
ProgressCallBack function.

/* Set up Ghostscript with callbacks for system updates */


m_ghostscript = new GSMONO();
m_ghostscript.ProgressCallBack += new GSMONO.Progress(gsProgress);
m_ghostscript.StdIOCallBack += new GSMONO.StdIO(gsIO);
m_ghostscript.DLLProblemCallBack += new GSMONO.DLLProblem(gsDLL);
m_ghostscript.PageRenderedCallBack += new GSMONO.PageRendered(gsPageRendered);
m_ghostscript.DisplayDeviceOpen();

/* example callback stubs for asynchronous operations */


private void gsProgress(gsThreadCallBack asyncInformation)
{
Console.WriteLine($"gsProgress().progress:{asyncInformation.Progress}");

if (asyncInformation.Completed) // task complete


{
(continues on next page)

6.4. C# 141
Ghostscript Documentation, Release 10.01.0

(continued from previous page)


// what was the task?
switch (asyncInformation.Params.task)
{
case GS_Task_t.CREATE_XPS:
Console.WriteLine($"CREATE_XPS.outputfile:");
Console.WriteLine($"{asyncInformation.Params.result.outputfile}");
break;

case GS_Task_t.PS_DISTILL:
Console.WriteLine($"PS_DISTILL.outputfile:");
Console.WriteLine($"{asyncInformation.Params.result.outputfile}");
break;

case GS_Task_t.SAVE_RESULT:

break;

case GS_Task_t.DISPLAY_DEV_THUMBS:

break;

case GS_Task_t.DISPLAY_DEV_RUN_FILE:

break;

case GS_Task_t.DISPLAY_DEV_PDF:

break;

case GS_Task_t.DISPLAY_DEV_NON_PDF:

break;

default:

break;
}

// task failed
if (asyncInformation.Params.result == GS_Result_t.gsFAILED)
{
switch (asyncInformation.Params.task)
{
case GS_Task_t.CREATE_XPS:

break;

case GS_Task_t.PS_DISTILL:

break;

case GS_Task_t.SAVE_RESULT:
(continues on next page)

142 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

(continued from previous page)

break;

default:

break;
}
return;
}

// task cancelled
if (asyncInformation.Params.result == GS_Result_t.gsCANCELLED)
{

}
}
else // task is still running
{
switch (asyncInformation.Params.task)
{
case GS_Task_t.CREATE_XPS:

break;

case GS_Task_t.PS_DISTILL:

break;

case GS_Task_t.SAVE_RESULT:

break;
}
}
}

private void gsIO(String message, int len)


{
Console.WriteLine($"gsIO().message:{message}, length:{len}");
}

private void gsDLL(String message)


{
Console.WriteLine($"gsDLL().message:{message}");
}

private void gsPageRendered(int width,


int height,
int raster,
IntPtr data,
gsParamState_t state)
{

(continues on next page)

6.4. C# 143
Ghostscript Documentation, Release 10.01.0

(continued from previous page)


};

Note: Once a Ghostscript operation is in progress any defined callback functions will be called as the operation runs
up unto completion. These callback methods are essential for your application to interpret activity events and react
accordingly.

An explanation of callbacks and the available public methods within GSMONO are explained below.

Delegates

To handle asynchronous events GhostMONO has four delegates which define callback methods that an application can
assign to.

Callback Description
DLLProblemCallBack Occurs if there is some issue with the Ghostscript Shared Object (libgpdl.so)
StdIOCallBack Occurs if Ghostscript outputs something to stderr or stdout.
ProgressCallBack Occurs as Ghostscript makes its way through a file.
PageRenderedCallBack Occurs when a page has been rendered and the data from the display device is ready.

DLLProblemCallBack

internal delegate void DLLProblem(String mess);


internal event DLLProblem DLLProblemCallBack;

StdIOCallBack

internal delegate void StdIO(String mess,


int len);
internal event StdIO StdIOCallBack;

ProgressCallBack

internal delegate void Progress(gsEventArgs info);


internal event Progress ProgressCallBack;

144 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

PageRenderedCallBack

internal delegate void PageRendered(int width,


int height,
int raster,
IntPtr data,
gsParamState_t state);
internal event PageRendered PageRenderedCallBack;

GetVersion

Use this method to get Ghostscript version info as a String.

public String GetVersion()

Sample code:

String gs_vers = m_ghostscript.GetVersion();

Note: An exception will be thrown if there is any issue with the Ghostscript DLL.

DisplayDeviceOpen

Sets up the display device ahead of time.

public gsParamState_t DisplayDeviceOpen()

Sample code:

m_ghostscript.DisplayDeviceOpen();

Note: Calling this method instantiates Ghostscript and configures the encoding and the callbacks for the display device.

DisplayDeviceClose

Closes the display device and deletes the instance.

public gsParamState_t DisplayDeviceClose()

Sample code:

m_ghostscript.DisplayDeviceClose();

Note: Calling this method deletes Ghostscript.

6.4. C# 145
Ghostscript Documentation, Release 10.01.0

GetPageCount

Use this method to get the number of pages in a supplied document.

public int GetPageCount(String fileName)

Sample code:

int page_number = m_ghostscript.GetPageCount("my_document.pdf");

Note: If Ghostscript is unable to determine the page count then this method will return -1.

DistillPS

Launches a thread rendering all the pages of a supplied PostScript file to a PDF.

public gsStatus DistillPS(String fileName, int resolution)

Sample code:

m_ghostscript.DistillPS("my_postscript_document.ps", 300);

DisplayDeviceRenderAll

Launches a thread rendering all the document pages with the display device. For use with languages that can be indexed
via pages which include PDF and XPS. (see: Ghostscript & Page Description Languages)

public gsStatus DisplayDeviceRenderAll(String fileName, double zoom, bool aa, GS_Task_t␣


˓→task)

Sample code:

m_ghostscript.DisplayDeviceRenderAll("my_document.pdf",
0.1,
false,
GS_Task_t.DISPLAY_DEV_THUMBS_NON_PDF);

DisplayDeviceRenderThumbs

Launches a thread rendering all the pages with the display device to collect thumbnail images.
Recommended zoom level for thumbnails is between 0.05 and 0.2, additionally anti-aliasing is probably not required.

public gsStatus DisplayDeviceRenderThumbs(String fileName,


double zoom,
bool aa)

Sample code:

146 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

m_ghostscript.DisplayDeviceRenderThumbs("my_document.pdf",
0.1,
false);

DisplayDeviceRenderPages

Launches a thread rendering a set of pages with the display device. For use with languages that can be indexed via
pages which include PDF and XPS. (see: Ghostscript & Page Description Languages)

public gsStatus DisplayDeviceRenderPages(String fileName,


int first_page,
int last_page,
double zoom)

Sample code:

m_ghostscript.DisplayDeviceRenderPages("my_document.pdf",
0,
9,
1.0);

GetStatus

Returns the current status of Ghostscript.

public gsStatus GetStatus()

Sample code:

gsStatus status = m_ghostscript.GetStatus();

GhostscriptException

An application developer can log any exceptions in this public class as required by editing the constructor.

public class GhostscriptException : Exception


{
public GhostscriptException(string message) : base(message)
{
// Report exceptions as required
}
}

Note: Ghostscript & Page Description Languages


Ghostscript handles the following PDLs: PCL PDF PS XPS.
PCL and PS do not allow random access, meaning that, to print page 2 in a 100 page document, Ghostscript has to read
the entire document stream of 100 pages.

6.4. C# 147
Ghostscript Documentation, Release 10.01.0

On the other hand, PDF and XPS allow for going directly to page 2 and then only dealing with that content. The
tasks DISPLAY_DEV_NON_PDF and DISPLAY_DEV_PDF keep track of what sort of input Ghostscript is dealing with and
enables the application to direct progress or completion callbacks accordingly.

6.5 Java

6.5.1 Introduction

In the GhostPDL repository sample Java projects can be found in /demos/java.


Within this location the following folders are of relevance:
• jni jni
• gsjava gsjava
• gstest gstest
• gsviewer gsviewer

6.5.2 Platform & setup

Ghostscript should be built as a shared library for your platform.


See Building Ghostscript.

jni: Building the Java Native Interface

Before building the JNI ensure that Ghostscript has already been built for your platform and that you have JDK installed.
The JNI is for use in the Java interface, this object must be placed somewhere on your Java PATH. On Windows, the
DLL can be placed in the working directory, next to gsjava.jar.

Platform JNI file


Windows gs_jni.dll
MacOS gs_jni.dylib
Linux / OpenBSD gs_jni.so

Preparing your include folder

The build scripts require the header jni.h, which defines all JNI functions, and jni_md.h, which defines all system-
specific integer types. The build scripts expect an include folder relative to their location which contain these header
files from your system.
These headers are typically found in the following directories:

148 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

Plat- jni.h jni_md.h


form
Win- C:Program FilesJava<JDK Install>includejni.h C:Program FilesJava<JDK In-
dows stall>includewin32jni_md.h
Ma- /Library/Java/JavaVirtualMachines/<JDK In- /Library/Java/JavaVirtualMachines/<JDK In-
cOS stall>/Contents/Home/include/jni.h stall>/Contents/Home/include/darwin/jni_md.h
Linux /lib/jvm/<JDK Install>/include/jni.h /lib/jvm/<JDK Install>/include/linux/jni_md.h

Once your include folder has been located folder you can copy it and place it in your ghostpdl/demos/java/jni/
gs_jni folder.
Your build scripts should now be ready to run as they will be able to find the required JNI header files in their own
relative include folder.

Building on Windows

The jni folder contains a Visual Studio Solution file /jni/gs_jni/gs_jni.sln which you should use to build the
required JNI gs_jni.dll library file.
With the project open in Visual Studio, select the required architecture from the drop down - then right click on ‘gs_jni’
in the solution explorer and choose “Build”.

Building on MacOS

On your command line, navigate to ghostpdl/demos/java/jni/gs_jni and ensure that the build script is executable
and then run it, with:

chmod +x build_darwin.sh
./build_darwin.sh

Building on Linux

On your command line, navigate to ghostpdl/demos/java/jni/gs_jni and ensure that the build script is executable
and then run it, with:

chmod +x build_linux.sh
./build_linux.sh

gsjava: Building the JAR

gsjava.jar is the Java library which contains classes and interfaces which enable API calls required to use
Ghostscript.
Assuming that the JAR for your project has been built and properly linked with your own project then the Ghostscript
API should be available by importing the required classes within your project’s .java files.

6.5. Java 149


Ghostscript Documentation, Release 10.01.0

Building with the command line

Navigate to ghostpdl/demos/java/gsjava and use the following:

Platform Run file


Windows build_win32.bat
MacOS build_darwin.sh
Linux build_linux.sh

Note: gsjava has a dependency on jni, please ensure that gs_jni is able to be built beforehand.

Building with Eclipse

Alternatively you can use Eclipse to build the JAR file.


Using Eclipse import the source folder gsjava as a project and select Export > Java > JAR File as shown in the
screenshot example below:

Linking the JAR

The built JAR should be properly linked within your project Java Build Path as follows:

6.5.3 Demo projects

gstest

Use this to quickly test Ghostscript methods.


This project can be opened in Eclipse and used to test the Ghostscript API. The sample here simply sets up an instance
of Ghostscript and then sets and gets some parameters accordingly.

gsviewer

A handy file viewer.


This project can be used to test the Ghostscript API alongside a UI which handles opening PostScript and PDF files.
The sample application here allows for file browsing and Ghostscript file viewing.
Below is a screenshot of the sample application with a PDF open:
To run the project navigate to the demos/java/gsviewer location and ensure that the required libraries are in the
directory:

150 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

Platform Ghostscript library file JNI library


file
Windows gpdldll64.dll gs_jni.dll
MacOS libgpdl.dylib gs_jni.
dylib
Linux / libgpdl.so (this may have been built as libgs.so, gs_jni.so
OpenBSD so it should be copied into this directory and
renamed to libgpdl.so)

Building on Windows

Run the build_win32.bat script.

Running on Windows

To run, open gsviewer.jar either through File Explorer or in the command line through the following command:

java -jar gsviewer.jar

Building on MacOS

On your command line, navigate to ghostpdl/demos/java/gsviewer and ensure that the build script is executable
and then run it, with:

chmod +x build_darwin.sh
./build_darwin.sh

This will automatically build gs_jni.dylib (in the ghostpdl/demos/java/jni/gs_jni/ location) and
gsjava.jar gsviewer.jar in the gsviewer directory.

Running on MacOS

Ensure that the Ghostscript library exists in the gsviewer directory. (Copy and move the built library from ghostpdl/
sobin as required).
Ensure that the run script is executable and then run it, with:

chmod +x start_darwin.sh
./start_darwin.sh

6.5. Java 151


Ghostscript Documentation, Release 10.01.0

Building on Linux

On your command line, navigate to ghostpdl/demos/java/gsviewer and ensure that the build script is executable
and then run it, with:

chmod +x build_linux.sh
./build_linux.sh

This will automatically build gs_jni.so (in the ghostpdl/demos/java/jni/gs_jni/ location) and gsjava.jar
gsviewer.jar in the gsviewer directory.

Note: On Linux, when using OpenJDK, the property “assistive_technologies” may need to be modified for the Java
code to build. It can be modified by editing the “accessibility.properties” file. This is located at:
/etc/java-8-openjdk/accessibility.properties

Running on Linux

Ensure that the Ghostscript library exists in the gsviewer directory. (Copy and move the built library from ghostpdl/
sobin as required).
Ensure that the run script is executable and then run it, with:

chmod +x start_linux.sh
./start_linux.sh

6.5.4 Using the Java library

gsjava

There are two main classes within the gsjava.jar library to consider:

GSAPI & GSInstance

GSAPI is the main Ghostscript API class which bridges into the Ghostscript C library.
GSInstance is a wrapper class for GSAPI which encapsulates an instance of Ghostscript and allows for simpler API
calls.
Sample code:

// to use GSAPI
import static com.artifex.gsjava.GSAPI.*;

// to use GSInstance
import com.artifex.gsjava.GSInstance;

152 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

GSAPI

gsapi_revision

This method returns the revision numbers and strings of the Ghostscript interpreter library; you should call it before any
other interpreter library functions to make sure that the correct version of the Ghostscript interpreter has been loaded.

public static native int gsapi_revision(GSAPI.Revision revision,


int len);

Note: The method should write to a reference variable which conforms to the class GSAPI.Revision.

GSAPI.Revision

This class is used to store information about Ghostscript and provides handy getters for the product and the copyright
information.

public static class Revision {


public volatile byte[] product;
public volatile byte[] copyright;
public volatile long revision;
public volatile long revisionDate;

public Revision() {
this.product = null;
this.copyright = null;
this.revision = 0L;
this.revisionDate = 0L;
}

/**
* Returns the product information as a String.
*
* @return The product information.
*/
public String getProduct() {
return new String(product);
}

/**
* Returns the copyright information as a String.
*
* @return The copyright information.
*/
public String getCopyright() {
return new String(copyright);
}
}

6.5. Java 153


Ghostscript Documentation, Release 10.01.0

gsapi_new_instance

Creates a new instance of Ghostscript. This instance is passed to most other GSAPI methods. Unless Ghostscript has
been compiled with the GS_THREADSAFE define, only one instance at a time is supported.

public static native int gsapi_new_instance(Reference<Long> instance,


long callerHandle);

Note: The method returns a reference which represents your instance of Ghostscript.

gsapi_delete_instance

Destroy an instance of Ghostscript. Before you call this, Ghostscript must have finished. If Ghostscript has been
initialised, you should call gsapi_exit beforehand.

public static native void gsapi_delete_instance(long instance);

gsapi_set_stdio_with_handle

Set the callback functions for stdio, together with the handle to use in the callback functions. The stdin callback
function should return the number of characters read, 0 for EOF, or -1 for error. The stdout and stderr callback
functions should return the number of characters written.

public static native int gsapi_set_stdio_with_handle(long instance,


IStdInFunction stdin,
IStdOutFunction stdout,
IStdErrFunction stderr,
long callerHandle);

gsapi_set_stdio

Set the callback functions for stdio. The handle used in the callbacks will be taken from the value passed to
gsapi_new_instance. Otherwise the behaviour of this function matches gsapi_set_stdio_with_handle.

public static native int gsapi_set_stdio(long instance,


IStdInFunction stdin,
IStdOutFunction stdout,
IStdErrFunction stderr);

154 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

gsapi_set_poll_with_handle

Set the callback function for polling, together with the handle to pass to the callback function. This function will only
be called if the Ghostscript interpreter was compiled with CHECK_INTERRUPTS as described in gpcheck.h.
The polling function should return zero if all is well, and return negative if it wants Ghostscript to abort. This is often
used for checking for a user cancel. This can also be used for handling window events or cooperative multitasking.
The polling function is called very frequently during interpretation and rendering so it must be fast. If the function is
slow, then using a counter to return 0 immediately some number of times can be used to reduce the performance
impact.

public static native int gsapi_set_poll_with_handle(long instance,


IPollFunction pollfun,
long callerHandle);

gsapi_set_poll

Set the callback function for polling. The handle passed to the callback function will be taken from the handle passed
to gsapi_new_instance. Otherwise the behaviour of this function matches gsapi_set_poll_with_handle.

public static native int gsapi_set_poll(long instance,


IPollFunction pollfun);

gsapi_set_display_callback

This call is deprecated; please use gsapi_register_callout to register a callout handler for the display device in prefer-
ence.

public static native int gsapi_set_display_callback(long instance,


DisplayCallback displayCallback);

gsapi_register_callout

This call registers a callout handler.

public static native int gsapi_register_callout(long instance,


ICalloutFunction callout,
long calloutHandle);

gsapi_deregister_callout

This call deregisters a callout handler previously registered with gsapi_register_callout. All three arguments must
match exactly for the callout handler to be deregistered.

public static native void gsapi_deregister_callout(long instance,


ICalloutFunction callout,
long calloutHandle);

6.5. Java 155


Ghostscript Documentation, Release 10.01.0

gsapi_set_arg_encoding

Set the encoding used for the interpretation of all subsequent arguments supplied via the GSAPI interface on this
instance. By default we expect args to be in encoding 0 (the ‘local’ encoding for this OS). On Windows this means “the
currently selected codepage”. This means that omitting to call this function will leave Ghostscript running exactly as
it always has. Please note that use of the ‘local’ encoding is now deprecated and should be avoided in new code. This
must be called after gsapi_new_instance and before gsapi_init_with_args.
public static native int gsapi_set_arg_encoding(long instance,
int encoding);

gsapi_set_default_device_list

Set the string containing the list of default device names, for example “display x11alpha x11 bbox”. Allows the calling
application to influence which device(s) Ghostscript will try, in order, in its selection of the default device. This must
be called after gsapi_new_instance and before gsapi_init_with_args.
public static native int gsapi_set_default_device_list(long instance,
byte[] list,
int listlen);

gsapi_get_default_device_list

Returns a pointer to the current default device string. This must be called after gsapi_new_instance and before
gsapi_init_with_args.
public static native int gsapi_get_default_device_list(long instance,
Reference<byte[]> list,
Reference<Integer> listlen);

gsapi_init_with_args

To initialise the interpreter, pass your instance of Ghostscript, your argument count: argc, and your argument vari-
ables: argv.
public static native int gsapi_init_with_args(long instance,
int argc,
byte[][] argv);

Note: There are also simpler utility methods which eliminates the need to send through your argument count and
allows for simpler String passing for your argument array.
Utility methods:
public static int gsapi_init_with_args(long instance,
String[] argv);

public static int gsapi_init_with_args(long instance,


List<String> argv);

156 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

gsapi_run_*

If these functions return <= -100, either quit or a fatal error has occured. You must call java gsapi_exit next. The only
exception is gsapi_run_string_continue which will return gs_error_NeedInput if all is well.
There is a 64 KB length limit on any buffer submitted to a gsapi_run_* function for processing. If you have more than
65535 bytes of input then you must split it into smaller pieces and submit each in a separate gsapi_run_string_continue
call.

gsapi_run_string_begin

public static native int gsapi_run_string_begin(long instance,


int userErrors,
Reference<Integer> pExitCode);

gsapi_run_string_continue

public static native int gsapi_run_string_continue(long instance,


byte[] str,
int length,
int userErrors,
Reference<Integer> pExitCode);

Note: There is a simpler utility method which allows for simpler String passing for the str argument.
Utility method:

public static int gsapi_run_string_continue(long instance,


String str,
int length,
int userErrors,
Reference<Integer> pExitCode);

gsapi_run_string_with_length

public static native int gsapi_run_string_with_length(long instance,


byte[] str,
int length,
int userErrors,
Reference<Integer> pExitCode);

Note: There is a simpler utility method which allows for simpler String passing for the str argument.
Utility method:

6.5. Java 157


Ghostscript Documentation, Release 10.01.0

public static int gsapi_run_string_with_length(long instance,


String str,
int length,
int userErrors,
Reference<Integer> pExitCode);

gsapi_run_string

public static native int gsapi_run_string(long instance,


byte[] str,
int userErrors,
Reference<Integer> pExitCode);

Note: There is a simpler utility method which allows for simpler String passing for the str argument.
Utility method:

public static int gsapi_run_string(long instance,


String str,
int userErrors,
Reference<Integer> pExitCode);

gsapi_run_string_end

public static native int gsapi_run_string_end(long instance,


int userErrors,
Reference<Integer> pExitCode);

gsapi_run_file

public static native int gsapi_run_file(long instance,


byte[] fileName,
int userErrors,
Reference<Integer> pExitCode);

Note: There is a simpler utility method which allows for simpler String passing for the fileName argument.
Utility method:

public static int gsapi_run_file(long instance,


String fileName,
int userErrors,
Reference<Integer> pExitCode);

158 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

gsapi_exit

Exit the interpreter. This must be called on shutdown if gsapi_init_with_args has been called, and just before
gsapi_delete_instance.

public static native int gsapi_exit(long instance);

gsapi_set_param

Sets a parameter. Broadly, this is equivalent to setting a parameter using -d, -s or -p on the command line. This call
cannot be made during a gsapi_run_string operation.
Parameters in this context are not the same as ‘arguments’ as processed by gsapi_init_with_args, but often the same
thing can be achieved. For example, with gsapi_init_with_args, we can pass “-r200” to change the resolution. Broadly
the same thing can be achieved by using gsapi_set_param to set a parsed value of “<</HWResolution [ 200.0 200.0
]>>”.
Internally, when we set a parameter, we perform an initgraphics operation. This means that using gsapi_set_param
other than at the start of a page is likely to give unexpected results.
Attempting to set a parameter that the device does not recognise will be silently ignored, and that parameter will not
be found in subsequent gsapi_get_param calls.

public static native int gsapi_set_param(long instance,


byte[] param,
Object value,
int paramType);

Note: For more on the C implementation of parameters see: Ghostscript parameters in C.


There are also simpler utility methods which allows for simpler String passing for your arguments.
Utility methods:

public static int gsapi_set_param(long instance,


String param,
String value,
int paramType);

public static int gsapi_set_param(long instance,


String param,
Object value,
int paramType);

6.5. Java 159


Ghostscript Documentation, Release 10.01.0

gsapi_get_param

Retrieve the current value of a parameter.


If an error occurs, the return value is negative. Otherwise the return value is the number of bytes required for storage
of the value. Call once with value NULL to get the number of bytes required, then call again with value pointing to at
least the required number of bytes where the value will be copied out. Note that the caller is required to know the type
of value in order to get it. For all types other than gs_spt_string, gs_spt_name, and gs_spt_parsed knowing the
type means you already know the size required.
This call retrieves parameters/values that have made it to the device. Thus, any values set using gs_spt_more_to_come
without a following call omitting that flag will not be retrieved. Similarly, attempting to get a parameter before
gsapi_init_with_args has been called will not list any, even if gsapi_set_param has been used.
Attempting to read a parameter that is not set will return gs_error_undefined (-21). Note that calling
gsapi_set_param followed by gsapi_get_param may not find the value, if the device did not recognise the key as being
one of its configuration keys.
For further documentation please refer to the C API.

public static native int gsapi_get_param(long instance,


byte[] param,
long value,
int paramType);

Note: There is a simpler utility method which allows for simpler String passing for the param argument.
Utility method:

public static int gsapi_get_param(long instance,


String param,
long value,
int paramType);

gsapi_enumerate_params

Enumerate the current parameters. Call repeatedly to list out the current parameters.
The first call should have iter = NULL. Subsequent calls should pass the same pointer in so the iterator can be updated.
Negative return codes indicate error, 0 success, and 1 indicates that there are no more keys to read. On success, key
will be updated to point to a null terminated string with the key name that is guaranteed to be valid until the next call to
gsapi_enumerate_params. If type is non NULL then the pointer type will be updated to have the type of the parameter.

Note: Only one enumeration can happen at a time. Starting a second enumeration will reset the first.

The enumeration only returns parameters/values that have made it to the device. Thus, any values set using the
gs_spt_more_to_come without a following call omitting that flag will not be retrieved. Similarly, attempting to
enumerate parameters before gsapi_init_with_args has been called will not list any, even if gsapi_set_param has been
used.

public static native int gsapi_enumerate_params(long instance,


Reference<Long> iter,
(continues on next page)

160 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

(continued from previous page)


Reference<byte[]> key,
Reference<Integer> paramType);

gsapi_add_control_path

Add a (case sensitive) path to one of the lists of permitted paths for file access.

public static native int gsapi_add_control_path(long instance,


int type,
byte[] path);

Note: There is a simpler utility method which allows for simpler String passing for the path argument.
Utility method:

public static int gsapi_add_control_path(long instance,


int type,
String path);

gsapi_remove_control_path

Remove a (case sensitive) path from one of the lists of permitted paths for file access.

public static native int gsapi_remove_control_path(long instance,


int type,
byte[] path);

Note: There is a simpler utility method which allows for simpler String passing for the path argument.
Utility method:

public static int gsapi_remove_control_path(long instance,


int type,
String path);

gsapi_purge_control_paths

Clear all the paths from one of the lists of permitted paths for file access.

public static native void gsapi_purge_control_paths(long instance,


int type);

6.5. Java 161


Ghostscript Documentation, Release 10.01.0

gsapi_activate_path_control

Enable/Disable path control (i.e. whether paths are checked against permitted paths before access is granted).

public static native void gsapi_activate_path_control(long instance,


boolean enable);

gsapi_is_path_control_active

Query whether path control is activated or not.

public static native boolean gsapi_is_path_control_active(long instance);

Callback & Callout interfaces

gsjava.jar also defines some functional interfaces for callbacks & callouts with package com.artifex.gsjava.
callback which are defined as follows.

IStdInFunction

public interface IStdInFunction {


/**
* @param callerHandle The caller handle.
* @param buf A string represented by a byte array.
* @param len The number of bytes to read.
* @return The number of bytes read, must be <code>len</code>/
*/
public int onStdIn(long callerHandle,
byte[] buf,
int len);
}

IStdOutFunction

public interface IStdOutFunction {


/**
* Called when something should be written to the standard
* output stream.
*
* @param callerHandle The caller handle.
* @param str The string represented by a byte array to write.
* @param len The number of bytes to write.
* @return The number of bytes written, must be <code>len</code>.
*/
public int onStdOut(long callerHandle,
byte[] str,
int len);
}

162 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

IStdErrFunction

public interface IStdErrFunction {


/**
* Called when something should be written to the standard error stream.
*
* @param callerHandle The caller handle.
* @param str The string represented by a byte array to write.
* @param len The length of bytes to be written.
* @return The amount of bytes written, must be <code>len</code>.
*/
public int onStdErr(long callerHandle,
byte[] str,
int len);
}

IPollFunction

public interface IPollFunction {


public int onPoll(long callerHandle);
}

ICalloutFunction

public interface ICalloutFunction {


public int onCallout(long instance,
long calloutHandle,
byte[] deviceName,
int id,
int size,
long data);
}

GSInstance

This is a utility class which makes Ghostscript calls easier by storing a Ghostscript instance and, optionally, a caller
handle. Essentially the class acts as a handy wrapper for the standard GSAPI methods.

Constructors

public GSInstance() throws IllegalStateException;


public GSInstance(long callerHandle) throws IllegalStateException;

6.5. Java 163


Ghostscript Documentation, Release 10.01.0

delete_instance

Wraps gsapi_delete_instance.

public void delete_instance();

set_stdio

Wraps gsapi_set_stdio.

public int set_stdio(IStdInFunction stdin,


IStdOutFunction stdout,
IStdErrFunction stderr);

set_poll

Wraps gsapi_set_poll.

public int set_poll(IPollFunction pollfun);

set_display_callback

Wraps gsapi_set_display_callback.

public int set_display_callback(DisplayCallback displaycallback);

register_callout

Wraps gsapi_register_callout.

public int register_callout(ICalloutFunction callout);

deregister_callout

Wraps gsapi_deregister_callout.

public void deregister_callout(ICalloutFunction callout);

164 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

set_arg_encoding

Wraps gsapi_set_arg_encoding.

public int set_arg_encoding(int encoding);

set_default_device_list

Wraps gsapi_set_default_device_list.

public int set_default_device_list(byte[] list,


int listlen);

get_default_device_list

Wraps gsapi_get_default_device_list.

public int get_default_device_list(Reference<byte[]> list,


Reference<Integer> listlen);

init_with_args

Wraps gsapi_init_with_args.

public int init_with_args(int argc,


byte[][] argv);

public int init_with_args(String[] argv);

public int init_with_args(List<String> argv);

run_string_begin

Wraps gsapi_run_string_begin.

public int run_string_begin(int userErrors,


Reference<Integer> pExitCode);

run_string_continue

Wraps gsapi_run_string_continue.

public int run_string_continue(byte[] str,


int length,
int userErrors,
Reference<Integer> pExitCode);

(continues on next page)

6.5. Java 165


Ghostscript Documentation, Release 10.01.0

(continued from previous page)


public int run_string_continue(String str,
int length,
int userErrors,
Reference<Integer> pExitCode);

run_string

Wraps gsapi_run_string.

public int run_string(byte[] str,


int userErrors,
Reference<Integer> pExitCode);

public int run_string(String str,


int userErrors,
Reference<Integer> pExitCode);

run_file

Wraps gsapi_run_file.

public int run_file(byte[] fileName,


int userErrors,
Reference<Integer> pExitCode);

public int run_file(String filename,


int userErrors,
Reference<Integer> pExitCode);

exit

Wraps gsapi_exit.

public int exit();

set_param

Wraps gsapi_set_param.

public int set_param(byte[] param,


Object value,
int paramType);

public int set_param(String param,


String value,
int paramType);

(continues on next page)

166 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

(continued from previous page)


public int set_param(String param,
Object value,
int paramType);

get_param

Wraps gsapi_get_param.

public int get_param(byte[] param,


long value,
int paramType);

public int get_param(String param,


long value,
int paramType);

enumerate_params

Wraps gsapi_enumerate_params.

public int enumerate_params(Reference<Long> iter,


Reference<byte[]> key,
Reference<Integer> paramType);

add_control_path

Wraps gsapi_add_control_path.

public int add_control_path(int type,


byte[] path);

public int add_control_path(int type,


String path);

remove_control_path

Wraps gsapi_remove_control_path.

public int remove_control_path(int type,


byte[] path);

public int remove_control_path(int type,


String path);

6.5. Java 167


Ghostscript Documentation, Release 10.01.0

purge_control_paths

Wraps gsapi_purge_control_paths.

public void purge_control_paths(int type);

activate_path_control

Wraps gsapi_activate_path_control.

public void activate_path_control(boolean enable);

is_path_control_active

Wraps gsapi_is_path_control_active.

public boolean is_path_control_active();

Utility classes

The com.artifex.gsjava.util package contains a set of classes and interfaces which are used throughout the API.

com.artifex.gsjava.util.Reference

Reference<T> is used in many of the Ghostscript calls, it stores a reference to a generic value of type T. This class
exists to emulate pointers being passed to a native function. Its value can be fetched with getValue() and set with
setValue(T value).

public class Reference<T> {

private volatile T value;

public Reference() {
this(null);
}

public Reference(T value) {


this.value = value;
}

public void setValue(T value) {


this.value = value;
}

public T getValue() {
return value;
}
...
}

168 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

6.6 Python

6.6.1 Introduction

The Python API is provided by the file gsapi.py - this is the binding to the Ghostscript C library.
In the GhostPDL repository sample Python examples can be found in /demos/python/examples.py.

6.6.2 Platform & setup

Ghostscript should be built as a shared library for your platform.


See Building Ghostscript.

Specifying the Ghostscript shared library

Two environmental variables can be used to specify where to find the Ghostscript shared library.
GSAPI_LIB sets the exact path of the Ghostscript shared library, otherwise, GSAPI_LIBDIR sets the directory containing
the Ghostscript shared library.
If neither is defined we will use the OS’s default location(s) for shared libraries.
If GSAPI_LIB is not defined, the leafname of the shared library is inferred from the OS type:

Platform Shared library file


Windows gsdll64.dll
MacOS libgs.dylib
Linux / OpenBSD libgs.so

API test

The gsapi.py file that provides the Python bindings can also be used to test the bindings, by running it directly.
Assuming that your Ghostscript library has successfully been created, then from the root of your ghostpdl repository
checkout do the following:
Windows
Run gsapi.py as a test script in a cmd.exe window:
set GSAPI_LIBDIR=debugbin&& python ./demos/python/gsapi.py

Run gsapi.py as a test script in a PowerShell window:


cmd /C "set GSAPI_LIBDIR=debugbin&& python ./demos/python/gsapi.py"

Linux/OpenBSD/MacOS
Run gsapi.py as a test script:
GSAPI_LIBDIR=sodebugbin ./demos/python/gsapi.py

Note: If there are no errors then this will have validated that the Ghostscript library is present & operational.

6.6. Python 169


Ghostscript Documentation, Release 10.01.0

6.6.3 The gsapi Python module

Assuming that the above platform & setup has been completed, then gsapi should be imported into your own Python
scripts for API usage.
• Implemented using Python’s ctypes module.
• All functions have the same name as the C function that they wrap.
• Functions raise a GSError exception if the underlying function returned a negative error code.
• Functions that don’t have out-params return None. Out-params are returned directly (using tuples if there are
more than one).

gsapi_revision()

Returns a gsapi_revision_t.
This method returns the revision numbers and strings of the Ghostscript interpreter library; you should call it before any
other interpreter library functions to make sure that the correct version of the Ghostscript interpreter has been loaded.
Sample code:

version_info = gsapi.gsapi_revision()
print(version_info)

C code reference: gsapi_revision

gsapi_new_instance(caller_handle)

Returns a new instance of Ghostscript to be used with other gsapi_*() functions.


Parameters:
caller_handle
Typically unused, but is passed to callbacks e.g. via gsapi_set_stdio(). Must be convertible to a C void*, so
None or an integer is ok but other types such as strings will fail.
Sample code:

instance = gsapi.gsapi_new_instance(1)

C code reference: gsapi_new_instance

gsapi_delete_instance(instance)

Destroy an instance of Ghostscript. Before you call this, Ghostscript should ensure to have finished any processes.
Parameters:
instance
Your instance of Ghostscript.
Sample code:

gsapi.gsapi_delete_instance(instance)

C code reference: gsapi_delete_instance

170 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

gsapi_set_stdio(instance, stdin_fn, stdout_fn, stderr_fn)

Set the callback functions for stdio, together with the handle to use in the callback functions.
Parameters:
instance
Your instance of Ghostscript.
stdin_fn
If not None, will be called with:
• (caller_handle, text, len_):
– caller_handle: As passed originally to gsapi_new_instance().
– text: A ctypes.LP_c_char of length len_.
stdout_fn , stderr_fn
If not None, called with:
• (caller_handle, text):
– caller_handle: As passed originally to gsapi_new_instance().
– text: A Python bytes object.
Should return the number of bytes of text that they handled; for convenience None is converted to len(text).
Sample code:

def stdout_fn(caller_handle, bytes_):


sys.stdout.write(bytes_.decode('latin-1'))

gsapi.gsapi_set_stdio(instance, None, stdout_fn, None)


print('gsapi_set_stdio() ok.')

C code reference: gsapi_set_stdio

gsapi_set_poll(instance, poll_fn)

Set the callback function for polling.


Parameters:
instance
Your instance of Ghostscript.
poll_fn
Will be called with caller_handle as passed to gsapi_new_instance.
Sample code:

def poll_fn(caller_handle, bytes_):


sys.stdout.write(bytes_.decode('latin-1'))

gsapi.gsapi_set_poll(instance, poll_fn)
print('gsapi_set_poll() ok.')

C code reference: gsapi_set_poll

6.6. Python 171


Ghostscript Documentation, Release 10.01.0

gsapi_set_display_callback(instance, callback)

Sets the display callback.


Parameters:
instance
Your instance of Ghostscript.
callback
Must be a display_callback instance.
Sample code:

d = display_callback()
gsapi.gsapi_set_display_callback(instance, d)
print('gsapi_set_display_callback() ok.')

C code reference: gsapi_set_display_callback

gsapi_set_arg_encoding(instance, encoding)

Set the encoding used for the interpretation of all subsequent arguments supplied via the GhostAPI interface on this
instance. By default we expect args to be in encoding 0 (the ‘local’ encoding for this OS). On Windows this means
“the currently selected codepage”. On Linux this typically means utf8. This means that omitting to call this function
will leave Ghostscript running exactly as it always has.
This must be called after gsapi_new_instance and before gsapi_init_with_args.
Parameters:
instance
Your instance of Ghostscript.
encoding
Encoding must be one of:

Encoding enum Value


GS_ARG_ENCODING_LOCAL 0
GS_ARG_ENCODING_UTF8 1
GS_ARG_ENCODING_UTF16LE 2

Sample code:

gsapi.gsapi_set_arg_encoding(instance, gsapi.GS_ARG_ENCODING_UTF8)

Note: Please note that use of the ‘local’ encoding (GS_ARG_ENCODING_LOCAL) is now deprecated and should be
avoided in new code.

C code reference: gsapi_set_arg_encoding

172 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

gsapi_set_default_device_list(instance, list_)

Set the string containing the list of default device names, for example “display x11alpha x11 bbox”. Allows the calling
application to influence which device(s) Ghostscript will try, in order, in its selection of the default device. This must
be called after gsapi_new_instance and before gsapi_init_with_args.
Parameters:
instance
Your instance of Ghostscript.
list_
A string of device names.
Sample code:

gsapi.gsapi_set_default_device_list(instance, 'bmp256 bmp32b bmpgray cdeskjet cdj1600␣


˓→cdj500')

C code reference: gsapi_set_default_device_list

gsapi_get_default_device_list(instance)

Returns a string containing the list of default device names. This must be called after gsapi_new_instance and before
gsapi_init_with_args.
Parameters:
instance
Your instance of Ghostscript.
Sample code:

device_list = gsapi.gsapi_get_default_device_list(instance)
print(device_list)

C code reference: gsapi_get_default_device_list

gsapi_init_with_args(instance, args)

To initialise the interpreter, pass your instance of Ghostscript and your argument variables with args.
Parameters:
instance
Your instance of Ghostscript.
args
A list/tuple of strings.
Sample code:

in_filename = 'tiger.eps'
out_filename = 'tiger.pdf'
params = ['gs', '-dNOPAUSE', '-dBATCH', '-sDEVICE=pdfwrite',
'-o', out_filename, '-f', in_filename]
gsapi.gsapi_init_with_args(instance, params)

C code reference: gsapi_init_with_args

6.6. Python 173


Ghostscript Documentation, Release 10.01.0

gsapi_run_*

There is a 64 KB length limit on any buffer submitted to a gsapi_run_* function for processing. If you have more than
65535 bytes of input then you must split it into smaller pieces and submit each in a separate gsapi_run_string_continue
call.
On success (underlying C function’s return value is >=0), these functions return the underlying C function’s exit_code
out-parameter (and the return value is discarded). Otherwise they raise a GSError in the usual way (and the underlying
exit_code out-parameter is discarded).
For full details on these return codes please see The C API return codes.

Note: User errors parameter explained


The user_errors argument is normally set to zero to indicate that errors should be handled through the normal
mechanisms within the interpreted code. If set to a negative value, the functions will return an error code directly
to the caller, bypassing the interpreted language. The interpreted language’s error handler is bypassed, regardless of
user_errors parameter, for the gs_error_interrupt generated when the polling callback returns a negative value.
A positive user_errors is treated the same as zero.

C code reference: gsapi_run_*

gsapi_run_string_begin(instance, user_errors)

Starts a run_string_ operation.


Parameters:
instance
Your instance of Ghostscript.
user_errors
An int, for more see: User errors parameter explained.
Sample code:

exitcode = gsapi.gsapi_run_string_begin(instance, 0)

C code reference: gsapi_run_*

gsapi_run_string_continue(instance, str_, user_errors)

Processes file byte data (str_) to feed as chunks into Ghostscript. This method should typically be called within a
buffer context.

Note: An exception is not raised for the gs_error_NeedInput return code.

Parameters:
instance
Your instance of Ghostscript.
str_
Should be either a Python string or a bytes object. If the former, it is converted into a bytes object using utf-8
encoding.

174 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

user_errors
An int, for more see: User errors parameter explained.
Sample code:

exitcode = gsapi.gsapi_run_string_continue(instance, data, 0)

Note: For the return code, we don’t raise an exception for gs_error_NeedInput.

C code reference: gsapi_run_*

gsapi_run_string_with_length(instance, str_, length, user_errors)

Processes file byte data (str_) to feed into Ghostscript when the length is known and the file byte data is immediately
available.
Parameters:
instance
Your instance of Ghostscript.
str_
Should be either a Python string or a bytes object. If the former, it is converted into a bytes object using utf-8
encoding.
length
An int representing the length of str_.
user_errors
An int, for more see: User errors parameter explained.
Sample code:

gsapi.gsapi_run_string_with_length(instance,"hello",5,0)

Note: If using this method then ensure that the file byte data will fit into a single (<64k) buffer.

C code reference: gsapi_run_*

gsapi_run_string(instance, str_, user_errors)

Processes file byte data (str_) to feed into Ghostscript.


Parameters:
instance
Your instance of Ghostscript.
str_
Should be either a Python string or a bytes object. If the former, it is converted into a bytes object using utf-8
encoding.
user_errors
An int, for more see: User errors parameter explained.
Sample code:

6.6. Python 175


Ghostscript Documentation, Release 10.01.0

gsapi.gsapi_run_string(instance,"hello",0)

Note: This method can only work on a standard, null terminated C string.

C code reference: gsapi_run_*

gsapi_run_string_end(instance, user_errors)

Ends a run_string_ operation.


Parameters:
instance
Your instance of Ghostscript.
user_errors
An int, for more see: User errors parameter explained.
Sample code:

exitcode = gsapi.gsapi_run_string_end(instance, 0)

C code reference: gsapi_run_*

gsapi_run_file(instance, filename, user_errors)

Runs a file through Ghostscript.


Parameters:
instance
Your instance of Ghostscript.
filename
String representing file name.
user_errors
An int, for more see: User errors parameter explained.
Sample code:

in_filename = 'tiger.eps'
gsapi.gsapi_run_file(instance, in_filename, 0)

Note: This will process the supplied input file with any previously supplied argument parameters.

C code reference: gsapi_run_*

176 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

gsapi_exit(instance)

Returns a successful exit code 0, or raises a GSError exception on error.


Exit the interpreter. This must be called on shutdown if gsapi_init_with_args has been called, and just before
gsapi_delete_instance.
Parameters:
instance
Your instance of Ghostscript.
Sample code:

gsapi.gsapi_exit(instance)

C code reference: gsapi_exit

gsapi_set_param(instance, param, value, type_=None)

Sets a parameter.
We behave much like the underlying gsapi_set_param() C function, except that we also support automatic inference
of type type_ arg by looking at the type of value.
Parameters:
instance
Your instance of Ghostscript.
param
Name of parameter, either a bytes or a str; if str it is encoded using latin-1.
value
A bool, int, float, bytes or str. If str, it is encoded into a bytes using utf-8.
type_
If type_ is not None, value must be convertible to the Python type implied by type_:

type_ Python type(s)


gs_spt_null [Ignored]
gs_spt_bool bool
gs_spt_int int
gs_spt_float float
gs_spt_name [Error]
gs_spt_string (bytes, str)
gs_spt_long int
gs_spt_i64 int
gs_spt_size_t int
gs_spt_parsed (bytes, str)
gs_spt_more_to_come (bytes, str)

An exception is raised if type_ is an integer type and value is outside its range.
If type_ is None, we choose something suitable for type of value:

6.6. Python 177


Ghostscript Documentation, Release 10.01.0

Python type of value type_


bool gs_spt_bool
int gs_spt_i64
float gs_spt_float
bytes gs_spt_parsed
str gs_spt_parsed (encoded with utf-8)

If value is None, we use gs_spt_null.


Otherwise type_ must be a gs_spt_* except for gs_spt_invalid and gs_spt_name (we don’t allow
psapi_spt_name because the underlying C does not copy the string, so cannot be safely used from Python).
Sample code:

set_margins = gsapi.gsapi_set_param(instance, "Margins", "[10 10]")

C code reference: gsapi_set_param

gsapi_get_param(instance, param, type_=None, encoding=None)

Returns value of specified parameter, or None if parameter type is gs_spt_null.


Parameters:
instance
Your instance of Ghostscript.
param
Name of parameter, either a bytes or str; if a str it is encoded using latin-1.
type_
A gs_spt_* constant or None. If None we try each gs_spt_* until one succeeds; if none succeeds we raise the
last error.
encoding
Only affects string values. If None we return a bytes object, otherwise it should be the encoding to use to decode
into a string, e.g. ‘utf-8’.
Sample code:

get_margins = gsapi.gsapi_get_param(instance, "Margins")

C code reference: gsapi_get_param

gsapi_enumerate_params(instance)

Enumerate the current parameters on the instance of Ghostscript.


Yields (key, value) for each param. key is decoded as latin-1.
Parameters:
instance
Your instance of Ghostscript.
Sample code:

178 Chapter 6. Language Bindings


Ghostscript Documentation, Release 10.01.0

for param, type_ in gsapi.gsapi_enumerate_params(instance):


val = gsapi.gsapi_get_param(instance,param, encoding='utf-8')
print('%-24s : %s' % (param, val))

C code reference: gsapi_enumerate_params

gsapi_add_control_path(instance, type_, path)

Add a (case sensitive) path to one of the lists of permitted paths for file access.
Parameters:
instance
Your instance of Ghostscript.
type_
An int which must be one of:

Enum Value
GS_PERMIT_FILE_READING 0
GS_PERMIT_FILE_WRITING 1
GS_PERMIT_FILE_CONTROL 2

path
A string representing the file path.
Sample code:

gsapi.gsapi_add_control_path(instance, gsapi.GS_PERMIT_FILE_READING, "/docs/secure/")

C code reference: gsapi_add_control_path

gsapi_remove_control_path(instance, type_, path)

Remove a (case sensitive) path from one of the lists of permitted paths for file access.
Parameters:
instance
Your instance of Ghostscript.
type_
An int representing the permission type.
path
A string representing the file path.
Sample code:

gsapi.gsapi_remove_control_path(instance, gsapi.GS_PERMIT_FILE_READING, "/docs/secure/")

C code reference: gsapi_remove_control_path

6.6. Python 179


Ghostscript Documentation, Release 10.01.0

gsapi_purge_control_paths(instance, type_)

Clear all the paths from one of the lists of permitted paths for file access.
Parameters:
instance
Your instance of Ghostscript.
type_
An int representing the permission type.
Sample code:

gsapi.gsapi_purge_control_paths(instance, gsapi.GS_PERMIT_FILE_READING)

C code reference: gsapi_purge_control_paths

gsapi_activate_path_control(instance, enable)

Enable/Disable path control (i.e. whether paths are checked against permitted paths before access is granted).
Parameters:
instance
Your instance of Ghostscript.
enable
bool to enable/disable path control.
Sample code:

gsapi.gsapi_activate_path_control(instance, true)

C code reference: gsapi_activate_path_control

gsapi_is_path_control_active(instance)

Query whether path control is activated or not.


Parameters:
instance
Your instance of Ghostscript.
Sample code:

isActive = gsapi.gsapi_is_path_control_active(instance)

C code reference: gsapi_is_path_control_active

180 Chapter 6. Language Bindings


CHAPTER

SEVEN

DETAILS OF GHOSTSCRIPT OUTPUT DEVICES

For other information, see the Ghostscript overview. You may also be interested in how to build Ghostscript and install
it, as well as the description of the driver interface.
Documentation for some older, superceded devices has been moved to unsupported devices. In general such devices
are deprecated and will be removed in future versions of Ghostscript. In general all older printer drivers can be replaced
by the ijs interface and one of the available 3rd party raster driver collections. We recommend moving to the ijs device
for all such printing.
Documentation for device subclassing can be found on the Device Subclassing page.

7.1 Notes on measurements

Several different important kinds of measures appear throughout this document: inches, centimeters and millimeters,
points, dots per inch and bits per pixel.

7.1.1 Inches

1 inch equals 2.54 centimeters. The inch measure is sometimes represented by in or a quotation mark
(”) to the right of a measure, like 8.5in or 8.5”. U.S. “letter” paper is exactly 8.5in×11in, approximately
21.6cm×27.9cm. (See in the usage documentation all the paper sizes predefined in Ghostscript.)

7.1.2 Centimeters and millimeters

ISO standard paper sizes such as A4 and A3 are commonly represented in the SI units of centimeters and
millimeters. Centimeters are abbreviated cm, millimeters mm. ISO A4 paper is quite close to 210×297
millimeters (approximately 8.3×11.7 inches).

7.1.3 Points

Points are a measure traditionally used in the printing trade and now in PostScript, which specifies exactly
72 points per inch (approximately 28.35 per centimeter). The paper sizes known to Ghostscript are defined
in the initialization file gs_statd.ps in terms of points.

181
Ghostscript Documentation, Release 10.01.0

7.1.4 Dots per inch

Dots per inch or “dpi” is the common measure of printing resolution in the US.

7.1.5 Bits per pixel

Commonly abbreviated “bpp” this is the number of digital bits used to represent the color of each pixel.
This is also referred to as ‘bit depth’ or ‘pixel depth’.

7.2 Image file formats

Ghostscript supports output to a variety of image file formats and is widely used for rasterizing postscript and pdf files.
A collection of such formats (‘output devices’ in Ghostscript terminology) are described in this section.
Here are some commonly useful driver options that apply to all raster drivers. Options specific to particular file formats
are described in their respective sections below.

-sOutputFile=filename

This is a general option telling Ghostscript what to name the output. It can either be a single filename ‘tiger.png’ or a
template ‘figure-%03d.jpg’ where the %03d is replaced by the page number.

-rres
-rxresxyres

This option sets the resolution of the output file in dots per inch. The default value if you don’t specify this options is
usually 72 dpi.

-dTextAlphaBits=n
-dGraphicsAlphaBits=n

These options control the use of subsample antialiasing. Their use is highly recommended for producing high quality
rasterizations of the input files. The size of the subsampling box n should be 4 for optimum output, but smaller values
can be used for faster rendering. Antialiasing is enabled separately for text and graphics content.
Because this feature relies upon rendering the input it is incompatible, and will generate an error on attempted use,
with any of the vector output devices.
It is also conventional to call Ghostscript with the -dSAFER -dBATCH -dNOPAUSE trio of options when rasterizing to
a file. These suppress interactive prompts and enable some security checks on the file to be run. Please see the Using
Ghostscript section for further details.

7.2.1 PNG file format

PNG (pronounced ‘ping’) stands for Portable Network Graphics, and is the recommended format for high-quality
images. It supports full quality color and transparency, offers excellent lossless compression of the image data, and is
widely supported. Please see the PNG website for a complete description of the format.
Ghostscript provides a variety of devices for PNG output varying by bit depth. For normal use we recommend png16m
for 24-bit RGB color, or pnggray for grayscale. The png256, png16 and pngmono devices respectively provide 8-bit
color, 4-bit color and black-and-white for special needs. The pngmonod device is also a black-and-white device, but the
output is formed from an internal 8 bit grayscale rendering which is then error diffused and converted down to 1bpp.

182 Chapter 7. Details of Ghostscript Output Devices


Ghostscript Documentation, Release 10.01.0

The png16malpha and pngalpha devices are 32-bit RGBA color with transparency indicating pixel coverage. The back-
ground is transparent unless it has been explicitly filled. PDF 1.4 transparent files do not give a transparent background
with this device. The devices differ, in that the pngalpha device enables Text and graphics anti-aliasing by default. We
now recommend that people use the png16malpha device in preference, and achieve any required antialiasing via the
DownScaleFactor parameter, as this gives better results in many cases.

Options

The pngmonod, png16m, pnggray, png16malpha and pngalpha devices all respond to the following:

-dDownScaleFactor=integer

This causes the internal rendering to be scaled down by the given (integer <= 8) factor before being output. For example,
the following will produce a 200dpi output png from a 600dpi internal rendering:

gs -sDEVICE=png16m -r600 -dDownScaleFactor=3 -o tiger.png\


examples/tiger.eps

The pngmonod device responds to the following option:

-dMinFeatureSize=state (0 to 4; default = 1)

This option allows a minimum feature size to be set; if any output pixel appears on its own, or as part of a group of
pixels smaller than MinFeatureSize x MinFeatureSize, it will be expanded to ensure that it does. This is useful for
output devices that are high resolution, but that have trouble rendering isolated pixels.
While this parameter will accept values from 0 to 4, not all are fully implemented. 0 and 1 cause no change to the
output (as expected). 2 works as specified. Values of 3 and 4 are accepted for compatibility, but behave as for 2.
The png16malpha and pngalpha devices respond to the following option:

-dBackgroundColor=16#RRGGBB (RGB color, default white = 16#ffffff)

For the png16malpha and pngalpha devices only, set the suggested background color in the PNG bKGD chunk. When
a program reading a PNG file does not support alpha transparency, the PNG library converts the image using either
a background color if supplied by the program or the bKGD chunk. One common web browser has this problem, so
when using <body bgcolor="CCCC00"> on a web page you would need to use -dBackgroundColor=16#CCCC00
when creating alpha transparent PNG images for use on the page.

Examples

Examples of how to use Ghostscript to convert postscript to PNG image files:

gs -dSAFER -dBATCH -dNOPAUSE -sDEVICE=png16m -dGraphicsAlphaBits=4 \


-sOutputFile=tiger.png examples/tiger.png
gs -dSAFER -dBATCH -dNOPAUSE -r150 -sDEVICE=pnggray -dTextAlphaBits=4 \
-sOutputFile=doc-%02d.png doc.pdf

In commercial builds, the png16m device will accept a -dDeskew option to automatically detect/correct skew when
generating output bitmaps.

7.2. Image file formats 183


Ghostscript Documentation, Release 10.01.0

7.2.2 JPEG file format (JFIF)

Ghostscript includes output drivers that can produce jpeg files from postscript or pdf images. These are the jpeg and
jpeggray devices.
Technically these produce Independent JPEG Group JFIF (JPEG File Interchange Format) files, the common sort found
on the web.
Please note that JPEG is a compression method specifically intended for continuous-tone images such as photographs,
not for graphics, and it is therefore quite unsuitable for the vast majority of page images produced with PostScript. For
anything other than pages containing simple images the lossy compression of the jpeg format will result in poor quality
output regardless of the input. To learn more about the distinction, consult a reference about uses and abuses of JPEG,
such as the JPEG FAQ.

Options

The JPEG devices support several special parameters to control the JPEG “quality setting” (DCT quantization level).

-dJPEGQ=N (integer from 0 to 100, default 75)

Set the quality level N according to the widely used IJG quality scale, which balances the extent of compression against
the fidelity of the image when reconstituted. Lower values drop more information from the image to achieve higher
compression, and therefore have lower quality when reconstituted.

-dQFactor=M (float from 0.0 to 1.0)

Adobe’s QFactor quality scale, which you may use in place of JPEGQ above. The QFactor scale is used by PostScript’s
DCTEncode filter but is nearly unheard-of elsewhere.
At this writing the default JPEG quality level of 75 is equivalent to -dQFactor=0.5, but the JPEG default might change
in the future. There is currently no support for any additional JPEG compression options, such as the other DCTEncode
filter parameters.

Examples

You can use the JPEG output drivers – jpeg to produce color JPEG files and jpeggray for grayscale JPEGs – the same
as other file-format drivers: by specifying the device name and an output file name, for example

gs -sDEVICE=jpeg -sOutputFile=foo.jpg foo.ps

7.2.3 PNM

The PNM (portable network map) family of formats are very simple uncompressed image formats commonly used on
unix-like systems. They are particularly useful for testing or as input to an external conversion utility.
A wide variety of data formats and depths is supported. Devices include pbm pbmraw pgm pgmraw pgnm pgnmraw
pnm pnmraw ppm ppmraw pkm pkmraw pksm pksmraw.

184 Chapter 7. Details of Ghostscript Output Devices


Ghostscript Documentation, Release 10.01.0

7.2.4 TIFF file formats

TIFF is a loose collection of formats, now largely superceded by PNG except in applications where backward compat-
ibility or special compression is required. The TIFF file format is described in the TIFF 6.0 Specification published by
Adobe Systems Incorporated.

Note: Due to the structure of the TIFF format, writing TIFF output requires that the target file be seekable. Writing
to stdout, pipes or other similar stream is not supported. Attempting to do so will generate an error.

There are two unrelated sets of TIFF drivers. There are five color TIFF drivers that produce uncompressed output:
tiffgray
Produces 8-bit gray output.
tiff12nc
Produces 12-bit RGB output (4 bits per component).
tiff24nc
Produces 24-bit RGB output (8 bits per component).
tiff48nc
Produces 48-bit RGB output (16 bits per component).
tiff32nc
Produces 32-bit CMYK output (8 bits per component).
tiff64nc
Produces 64-bit CMYK output (16 bits per component).
tiffsep
The tiffsep device creates multiple output files: a single 32 bit composite CMYK file and multiple tiffgray files,
one for each separation (unless -dNoSeparationFiles is specified). If separation files are being produced
and more than one page is being generated, the output file specification must include a format specifier (e.g -o
outfile-%d.tif) so that each page can have a uniquely named set of separation files.
The default compression is lzw but this may be overridden by the -sCompression= option.
The file specified via the OutputFile command line parameter will contain CMYK data. This data is based
upon the CMYK data within the file plus an equivalent CMYK color for each spot color. The equivalent CMYK
color for each spot color is determined using the alternate tint transform function specified in the Separation
and devicen color spaces. Since this file is created based upon having color planes for each colorant, the file will
correctly represent the appearance of overprinting with spot colors.
File names for the separations for the CMYK colorants are created by appending ‘.Cyan.tif’, ‘.Magenta.tif’ ‘.Yel-
low.tif’ or ‘.Black.tif’ to the end of the file name specified via the OutputFile parameter. File names for the
spot color separation files are created by appending the Spot color name in ‘(’ and ‘).tif’ to the filename.
Note that, while the name of the ink is case-sensitive, the filename may not be (depending on the Operating
System), so if a spot name matches one of the process ink names, it will have the spot number included as part
of the name (e.g. YELLOW0).
If desired the file names for the spot color separation files can be created by appending ‘.sn.tif’ (where n is the spot
color number, see below) to the end of the file name specified via the OutputFile parameter. This change is a
compile time edit. To obtain this type of output the function create_separation_file_name in gdevtsep.c
should be called with a true value for its use_sep_name parameter.
The tiffsep device will automatically recognize spot colors. In this case their order is determined by when they
are found in the input file. The names of spot colors may be specified via the SeparationColorNames device
parameters.

7.2. Image file formats 185


Ghostscript Documentation, Release 10.01.0

Internally each spot color is assigned a spot color number. These numbers start with 0 for the first spot color. The
spot color numbers are assigned in the same order as the names are printed to stderr (see below). This order also
matches the ordering in the SeparationColorNames list, if this parameter is specified. The spot color numbers
are not affected by the SeparationOrder parameter.
If only a subset of the colorants for a file is desired, then the separations to be output can be selected via the
SeparationOrder device parameter. When colorants are selected via the SeparationOrder parameter, the
composite CMYK output contains the equivalent CMYK data only for the selected colorants.

Note: The composite CMYK output, because it uses the tint transformed colour equivalents for any spot colours
(see Postscript Language Reference “Separation Color Spaces” and “DeviceN Color Spaces”), may not produce
an accurate preview, if the job uses overprinting.

The tiffsep device also prints the names of any spot colors detected within a document to stderr, (stderr is also
used for the output from the bbox device). For each spot color, the name of the color is printed preceded by
‘%%SeparationName: ‘. This provides a simple mechanism for users and external applications to be informed
about the names of spot colors within a document.
Generally Ghostscript will support a maximum of 64 process and spot colors. The tiffsep device the psdcmyk
device and the psdcmyk16 devices maintain rendered data in a planar form with a maximum of 64 planes set
by the definition of GS_CLIENT_COLOR_MAX_COMPONENTS in the code. That is there can be up to 64 colorants
accurately handled with overprint on a single page. If more than 64 colorants are encountered, those beyond 64
will be mapped to CMYK using the alternate tint transform.
When rendering a PDF document, Ghostscript can deteremine prior to rendering how many colorants occur on a
particular page. With Postscript, this is not possible in general. To optimize for this, when rendering Postscript,
it is possible to specify at run-time the number of spot colorants you wish to have the device capable of handling
using the -dMaxSpots=N command option, where N is the number of spot colorants that you wish to be able
to handle and must be no more than the 64 minus the number of process colors. For example, 60 or less for a
CMYK device such as tiffsep. If you specify more than is needed, the document will render more slowly. The
ideal case is to use the same number as the maximum number of spot colorants that occur on a single page of
the document. If more spot colorants are encountered than is specified by -dMaxSpots, then a warning will be
printed indicating that some spot colorants will be mapped to CMYK using the alternate tint transform.
The tiffsep device accepts a -dBitsPerComponent= option, which may be set to 8 (the default) or 1. In 1bpp
mode, the device renders each component internally in 8 bits, but then converts down to 1bpp with error diffusion
before output as described below in the tiffscaled device. No composite file is produced in 1bpp mode, only
individual separations.
The device also accepts the -dDownScaleFactor= -dTrapX= -dTrapy= and -sPostRenderProfile= pa-
rameters as described below in the tiffscaled device, and -dMinFeatureSize= in 1bpp mode.
When -dDownScaleFactor= is used in 8 bit mode with the tiffsep (and psdcmyk/psdrgb/psdcmyk16/psdrgb16)
device(s) 2 additional “special” ratios are available, 32 and 34. 32 provides a 3:2 downscale (so from 300 to 200
dpi, say). 34 produces a 3:4 upscale (so from 300 to 400 dpi, say).
In commercial builds, with 8 bit per component output, the -dDeskew option can be used to automatically
detect/correct skew when generating output bitmaps.
The tiffscaled and tiffscaled4 devices can optionally use Even Toned Screening, rather than simple Floyd Stein-
berg error diffusion. This patented technique gives better quality at the expense of some speed. While the
code used has many quality tuning options, none of these are currently exposed. Any device author inter-
ested in trying these options should contact Artifex for more information. Currently ETS can be enabled using
-dDownScaleETS=1.
tiffsep1
The tiffsep1 device creates multiple output files, one for each component or separation color. The device creates

186 Chapter 7. Details of Ghostscript Output Devices


Ghostscript Documentation, Release 10.01.0

multiple tiffg4 files (the compression can be set using -sCompression= described below). The 1 bit per com-
ponent output is halftoned using the current screening set by ‘setcolorscreen’ or ‘sethalftone’ which allows for
ordered dither or stochastic threshold array dither to be used. This is faster than error diffusion.
The file specified via the OutputFile command line parameter will not be created (it is opened, but deleted
prior to finishing each page).
File names for the separations for the CMYK colorants are created by appending ‘(Cyan).tif’, ‘(Magenta).tif’
‘(Yellow).tif’ or ‘(Black).tif’ to the to the end of the file name specified via the OutputFile parameter. File
names for the spot color separation files are created by appending the Spot color name in ‘(’ and ‘).tif’ to the
filename. If the file name specified via the OutputFile parameter ends with the suffix ‘.tif’, then the suffix is
removed prior to adding the component name in ‘(’ and ‘).tif’.
tiffscaled
The tiffscaled device renders internally at the specified resolution to an 8 bit greyscale image. This is then scaled
down by an integer scale factor (set by -dDownScaleFactor= described below) and then error diffused to give
1bpp output. The compression can be set using -sCompression= as described below.
tiffscaled4
The tiffscaled4 device renders internally at the specified resolution to an 8 bit cmyk image. This is then scaled
down by an integer scale factor (set by -dDownScaleFactor= described below) and then error diffused to give
4bpp cmyk output. The compression can be set using -sCompression= as described below.
tiffscaled8
The tiffscaled8 device renders internally at the specified resolution to an 8 bit greyscale image. This is then scaled
down by an integer scale factor (set by -dDownScaleFactor= described below). The compression can be set
using -sCompression= as described below.
tiffscaled24
The tiffscaled24 device renders internally at the specified resolution to a 24 bit rgb image. This is then scaled
down by an integer scale factor (set by -dDownScaleFactor= described below). The compression can be set
using -sCompression= as described below.
In commercial builds, the -dDeskew option can be used to automatically detect/correct skew when generating
output bitmaps.
tiffscaled32
The tiffscaled32 device renders internally at the specified resolution to a 32 bit cmyk image. This is then scaled
down by an integer scale factor (set by -dDownScaleFactor= described below). The compression can be set
using -sCompression= as described below.
In commercial builds, the -dDeskew option can be used to automatically detect/correct skew when generating
output bitmaps.
The remaining TIFF drivers all produce black-and-white output with different compression modes:
tiffcrle
G3 fax encoding with no EOLs.
tiffg3
G3 fax encoding with EOLs.
tiffg32d
2-D G3 fax encoding.
tiffg4
G4 fax encoding.
tifflzw
LZW-compatible (tag = 5) compression.

7.2. Image file formats 187


Ghostscript Documentation, Release 10.01.0

tiffpack
PackBits (tag = 32773) compression.
See the AdjustWidth option documentation below for important information about these devices.

Options

All TIFF drivers support creation of files that are comprised of more than a single strip. Multi-strip files reduce the
memory requirement on the reader, since readers need only store and process one strip at a time. The MaxStripSize
parameter controls the strip size:

-dMaxStripSize=N

Where N is a non-negative integer; default = 8192, 0 on Fax devices. Set the maximum (uncompressed) size of a strip.
The TIFF 6.0 specification, Section 7, page 27, recommends that the size of each strip be about 8 Kbytes.
If the value of the MaxStripSize parameter is smaller than a single image row, then no error will be generated, and
the TIFF file will be generated correctly using one row per strip. Note that smaller strip sizes increase the size of the
file by increasing the size of the StripOffsets and StripByteCounts tables, and by reducing the effectiveness of
the compression which must start over for each strip.
If the value of MaxStripSize is 0, then the entire image will be a single strip.
Since v. 8.51 the logical order of bits within a byte, FillOrder, tag = 266 is controlled by a parameter:

-dFillOrder=1 | 2 (default = 1)

If this option set to 2 then pixels are arranged within a byte such that pixels with lower column values are stored in the
lower-order bits of the byte; otherwise pixels are arranged in reverse order.
Earlier versions of Ghostscript always generated TIFF files with FillOrder = 2. According to the TIFF 6.0 specifi-
cation, Section 8, page 32, support of FillOrder = 2 is not required in a Baseline TIFF compliant reader
The writing of BigTIFF format output files is controlled with the -dUseBigTIFF parameter.
Unfortunately, due the unpredictable size of compressed output, we cannot automate the selection of BigTIFF, using
it only when the output file grows large enough to warrant it.

-dUseBigTIFF(=false/true) (boolean, default: false)

Forces use (or not) of BigTIFF format in output from TIFF devices.
The writing of the DateTime TAG can be controlled using the -dTIFFDateTime parameter.

-dTIFFDateTime(=true/false) (boolean, default: true)

Write or otherwise the DateTime TAG to the TIFF output file. Thus to disable writing the TAG, use:
-dTIFFDateTime=false.
The compression scheme that is used for the image data can be set for all tiff devices with:

-sCompression=none | crle | g3 | g4 | lzw | pack

Change the compression scheme of the tiff device. crle, g3, and g4 may only be used with 1 bit devices (including
tiffsep1).
For the tiffsep device, it changes the compression scheme of the separation files and composite cmyk file (which is lzw
by default). It defaults to g4 for the tiffsep1 device.

188 Chapter 7. Details of Ghostscript Output Devices


Ghostscript Documentation, Release 10.01.0

The black-and-white TIFF devices also provide the following parameters:

-dAdjustWidth=state (0, 1, or value; default = 1)

If this option is 1 then if the requested page width is in the range of either 1680..1736 or 2000..2056 columns, set the
page width to A4 (1728 columns) or B4 (2048 columns) respectively. If this option is set to a value >1 then the width
is unconditionally adjusted to this value.
This behavior is the default for all the fax based devices (i.e. all the black and white devices except tifflzw, tiffpack and
tiffscaled). Pass -dAdjustWidth=0 to force this behaviour off.
When using this option with tiffscaled it is the downsampled size that triggers the adjustment.

-dMinFeatureSize=state (0 to 4; default = 1)

This option allows a minimum feature size to be set; if any output pixel appears on its own, or as part of a group of
pixels smaller than MinFeatureSize x MinFeatureSize, it will be expanded to ensure that it does. This is useful for
output devices that are high resolution, but that have trouble rendering isolated pixels.
While this parameter will accept values from 0 to 4, not all are fully implemented. 0 and 1 cause no change to the
output (as expected). 2 works as specified. 3 and 4 currently expand pixels correctly horizontally, but only expand
vertically to the 2 pixel size.
The mechanism by which MinFeatureSize is implemented for tiffscaled is different, in that it is done as part of the
error diffusion. Values of 0 to 2 work as expected, but values 3 and 4 (while accepted for compatibility) will behave as
for 2.
The tiffscaled, tiffscaled4, tiffscaled8, tiffscaled24 and tiffscaled32 TIFF drivers also provide the following two param-
eters:

-dDownScaleFactor=factor (integer <= 8; default = 1)

If this option set then the page is downscaled by the given factor on both axes before error diffusion takes place. For
example rendering with -r600 and then specifying -dDownScaleFactor=3 will produce a 200dpi image.

-sPostRenderProfile=path (path to an ICC profile)

If this option set then the page will be color transformed using that profile after downscaling.
This is useful when the file uses overprint to separately paint to some subset of the C, M, Y, and K colorants, but the
final CMYK is to be color corrected for printing or display.
The tiffsep TIFF device also provide this parameter:

-dPrintSpotCMYK=boolean defaults to false.

When set to true the device will print (to stdout) the name of each ink used on the page, and the CMYK values which
are equivalent to 100% of that ink. The values are 16-bits ranging from 0 to 32760.
The tiffsep device (along with the tiffscaled32 and psdcmyk devices) can perform rudimentary automatic bitmap ‘trap-
ping’ on the final rendered bitmap. This code is disabled by default; see the note below as to why.
Trapping is a process whereby the output is adjusted to minimise the visual impact of offsets between each printed
plane. Typically this involves slightly extending abutting regions that are rendered in different inks. The intent of this
is to avoid the unsightly gaps that might be otherwise be revealed in the final printout if the different color plates do
not exactly line up.
This trapping is controlled by 3 device parameters. Firstly the maximum X and Y offsets are specified using -dTrapX=N
and -dTrapY=N (where N is a figure in pixels, before the downscaler is applied).

7.2. Image file formats 189


Ghostscript Documentation, Release 10.01.0

The final control is to inform the trapping process in what order inks should be processed, from darkest to lightest. For
a typical CMYK device this order would be [ 3 1 0 2 ] (K darker than M darker than C darker than Y). This is the
default. In the case where CMYK + spots are used, the code defaults to assuming that the spots are lighter than the
standard colours and are sent darkest first (thus [ 3 1 0 2 4 5 6 . . . ]).
To override these defaults, the TrapOrder parameter can be used, for example:

gs -sDEVICE=psdcmyk -dTrapX=2 -dTrapY=2 -o out.psd -c "<< /TrapOrder [ 4 5 3 1 0 2 ] >>␣


˓→setpagedevice" -f examples\tiger.eps

Note: Trapping patents. Trapping is an technology area encumbered by many patents. We believe that the last of
these has now lapsed, and so have enabled the code by default.

7.2.5 FAX

Ghostscript supports a variety of fax encodings, both encapsulated in TIFF (see above) and as raw files. The later case
is described here.
The fax devices are faxg3, faxg32d and faxg4.
The fax devices support the MinFeatureSize parameter as defined in the TIFF device section.
It appears from this commit: 0abc209b8460396cdece8fc824c053a2662c4cbf that some (many ?) fax readers
cannot cope with multiple strip TIFF files. The commit noted above works around this by assuming no fax output will
exceed 1MB. Unfrotunately it also altered all the TIFF devices’ default strip size which we now think was inadvisable.
The fax devices now use a MaxStripSize of 0 so that the file only contains a single strip. This can still be overridden
by specifying MaxStripSize on the command line.

7.2.6 BMP

BMP is a simple uncompressed image format commonly used on MS Windows.


It is supported by the bmpmono bmpgray bmpsep1 bmpsep8 bmp16 bmp256 bmp16m bmp32b series of devices.

7.2.7 PCX

PCX is an image format sometimes used on MS Windows. It has some support for image compression and alternate
color spaces, and so can be a useful way to output CMYK.
It is supported by the pcxmono pcxgray pcx16 pcx256 pcx24b pcxcmyk series of devices.

7.2.8 PSD

PSD is the image format used by Adobe Photoshop.


It is supported by the psdcmyk psdrgb psdcmyk16 psdrgb16 series of devices.
Of special interest with the psdcmyk and psdcmyk16 devices is that they support spot colors. See the comments under
the tiffsep and tiffsep1 device about the maximum number of spot colors supported by Ghostscript.
The psdcmyk16 and psdrgb16 devices are essentially the same as the psdcmyk and psdrgb devices except they provide
16 bit output.

190 Chapter 7. Details of Ghostscript Output Devices


Ghostscript Documentation, Release 10.01.0

The psdcmykog device produces PSD files with 6 components: Cyan, Magenta, Yellow, blacK, Orange, and Green.
This device does not support the -dDownScaleFactor= option (see below), instead it always scales down by a factor
of two.
These devices support the same -dDownScaleFactor= ratios as tiffsep. The psdcmyk device supports the same trap-
ping options as tiffsep (but see this note).

Note: The PSD format is a single image per file format, so you must use the “%d” format for the OutputFile (or
“-o”) file name parameter (see One page per file for details). An attempt to output multiple pages to a single PSD file
(i.e. without the “%d” format) will result in an ioerror Postscript error.

In commercial builds, for the psdcmyk and psdrgb devices, the -dDeskew option can be used to automatically de-
tect/correct skew when generating output bitmaps.

7.2.9 PDF

These devices render input to a bitmap (or in the case of PCLm multiple bitmaps) then wraps the bitmap(s) up as the
content of a PDF file. For PCLm there are some additional rules regarding headers, extra content and the order in which
the content is written in the PDF file.
The aim is to support the PCLm mobile printing standard, and to permit production of PDF files from input where the
graphics model differs significantly from PDF (eg PCL and RasterOPs).
There are five devices named pdfimage8, pdfimage24, pdfimage32, pclm and pclm8. These produce valid PDF files
with a colour depth of 8 (Gray), 24 (RGB) or 32 (CMYK), the pclm device only supports 24-bit RGB and the pclm8
device only supports 8-bit gray. These are all implemented as ‘downscale’ devices, which means they can implement
page level anti-aliasing using the -dDownScaleFactor switch.

-dDownScaleFactor=integer

This causes the internal rendering to be scaled down by the given (integer <= 8) factor before being output. For example,
the following will produce a PDF containing a 200dpi output from a 600dpi internal rendering:

gs -sDEVICE=pdfimage8 -r600 -dDownScaleFactor=3 -o tiger.pdf\


examples/tiger.eps

In commercial builds, the -dDeskew option can be used to automatically detect/correct skew when generating the
output file.
The type of compression used for the image data can also be selected using the -sCompression switch. Valid com-
pression types are None, LZW, Flate, jpeg and RLE.

Note: LZW is not supported on pclm (not valid) and None is only supported on pclm for debugging purposes.

For JPEG compression the devices support both the JPEGQ and QFactor switches as documented for the JPEG file
format device.
In addition, the PCLm device supports some other parameters. Firstly, the -dStripHeight switch to set the vertical
height of the strips of image content, as required by the specification.
Secondly, the standard postscript -dDuplex and -dTumbleswitches are supported, in that if both are set to true, every
verso page (i.e. all even pages) will be rotated by 180 degrees.

7.2. Image file formats 191


Ghostscript Documentation, Release 10.01.0

As an extension to this, a -dTumble2 parameter is also supported that will add an additional X-axis flip for every verso
page. Thus -dDuplex=true -dTumble=false -dTumble2=true will result in verso pages being flipped horizon-
tally, and -dDuplex=true -dTumble=true -dTumble2=true will result in verso pages being flipped vertically.

Note: In addition to raster image files, Ghostscript supports output in a number of ‘high-level’ formats. These allow
Ghostscript to preserve (as much as possible) the drawing elements of the input file maintaining flexibility, resolution
independence, and editability.

7.3 Optical Character Recognition (OCR) devices

7.3.1 OCR text output

These devices render internally in 8 bit greyscale, and then feed the resultant image into an OCR engine. Currently,
we are using the Tesseract engine. Not only is this both free and open source, it gives very good results, and supports
a huge number of languages/scripts.
The Tesseract engine relies on files to encapsulate each language and/or script. These “traineddata” files are available
in different forms, including fast and best variants. Alternatively, people can train their own data using the standard
Tesseract tools.
These files are looked for from a variety of places.
1. Files will be searched for in the directory given by the environment variable TESSDATA_PREFIX.
2. Then they will be searched for within the ROM filing system. Any files placed in “tessdata” will be included
within the ROM filing system in the binary for any standard (COMPILE_INITS=1) build.
3. Then files will be searched for in the configured ‘tessdata’ path. On Unix, this can be specified at the configure
stage using ‘–with-tessdata=<path>’ (where <path> is a list of directories to search, separated by ‘:’ (on Unix)
or ‘;’ (on Windows)).
4. Finally, we resort to searching the current directory.
Please note, this pattern of directory searching differs from the original release of the OCR devices.
By default, the OCR process defaults to looking for English text, using “eng.traineddata”. This can be changed by
using the -sOCRLanguage= switch:

-sOCRLanguage=language

This sets the trained data sets to use within the Tesseract OCR engine.
For example, the following will use English and Arabic:

gs -sDEVICE=ocr -r200 -sOCRLanguage="eng+ara" -o out.txt\


zlib/zlib.3.pdf

The first device is named ocr. It extracts data as unicode codepoints and outputs them to the device as a stream of
UTF-8 bytes.
The second device is named hocr. This extracts the data in hOCR format.
These devices are implemented as downscaling devices, so the standard parameters can be used to control this process.
It may seem strange to use downscaling on an image that is not actually going to be output, but there are actually good
reasons for this. Firstly, the higher the resolution, the slower the OCR process. Secondly, the way the Tesseract OCR
engine works means that anti-aliased images perform broadly as well as the super-sampled image from which it came.

192 Chapter 7. Details of Ghostscript Output Devices


Ghostscript Documentation, Release 10.01.0

7.3.2 PDF image output (with OCR text)

These devices do the same render to bitmap and wrap as a PDF process as the PDFimage devices above, but with the
addition of an OCR step at the end. The OCR’d text is overlaid “invisibly” over the images, so searching and cut/paste
should still work.
The OCR engine being used is Tesseract. For information on this including how to control what language data is used,
see the OCR devices section above.
There are three devices named pdfocr8, pdfocr24 and pdfocr32. These produce valid PDF files with a colour depth of
8 (Gray), 24 (RGB) or 32 (CMYK).
These devices accept all the same flags as the PDFimage devices described above.

7.3.3 Vector PDF output (with OCR Unicode CMaps)

The pdfwrite device has been augmented to use the OCR engine to analyse text (not images!) in the input stream, and
derive Unicode code points for it. That information can then be used to create ToUnicode CMaps which are attached
to the Font (or CIDFont) objects embedded in the PDF file.
Fonts which have ToUnicode CMaps can be reliably (limited by the accuracy of the CMap) used in search and copy/paste
functions, as well as text extraction from PDF files. Note that OCR is not a 100% perfect process; it is possible that
some text might be misidentified.
OCR is a slow operation! In addition it can (for Latin text at least) sometimes be preferable not to add ToUnicode
information which may be incorrect, but instead to use the existing font Encoding. For English text this may give
better results.
For these reasons the OCR functionality of pdfwrite can be controlled by using a new parameter -sUseOCR. This has
three possible values:

-sUseOCR=string

string values as follows:


Never
Default - don’t use OCR at all even if support is built-in.
AsNeeded
If there is no existing ToUnicode information, use OCR.
Always
Ignore any existing information and always use OCR.

7.4 High level devices

Please refer to High Level Devices for documentation on the device options for these devices.

7.4. High level devices 193


Ghostscript Documentation, Release 10.01.0

7.4.1 PDF writer

The pdfwrite device outputs PDF.

7.4.2 PS2 writer

The ps2write device outputs postscript language level 2. It is recommnded that this device is used for PostScript output.
There is no longer any support for creating PostScript level 1 output.

7.4.3 EPS writer

The eps2write device outputs encapsulated postscript.

7.4.4 PXL

The pxlmono and pxlcolor devices output HP PCL-XL, a graphic language understood by many recent laser printers.

7.4.5 Text output

The txtwrite device will output the text contained in the original document as Unicode.

7.5 Display devices

Ghostscript is often used for screen display of postscript and pdf documents. In many cases, a client or ‘viewer’
application calls the Ghostscript engine to do the rasterization and handles the display of the resulting image itself, but
it is also possible to invoke Ghostscript directly and select an output device which directly handles displaying the image
on screen.
This section describes the various display-oriented devices that are available in Ghostscript.

7.5.1 X Window System

Perhaps the most common use of of a display device is with the X Window System on unix-like systems. It is the
default device on the command line client on such systems, and is used more creatively by the gv client application.
The available devices are:
x11
This is the default device, handling display on X11R6.
x11alpha
This is the x11 device, but with antialiasing. It is equivalent to invoking the x11 device with the options
-dGraphicsAlphaBits=4 -dTextAlphaBits=4 -dMaxBitmap=50000000.
x11cmyk
This device rasterizes the image in the CMYK color space, then flattens it to RGB for display. It’s intended for
testing only.
x11mono
This is a strict black-and-white device for 1-bit monochrome displays.

194 Chapter 7. Details of Ghostscript Output Devices


Ghostscript Documentation, Release 10.01.0

x11gray2
This is a device for 2 bpp (4-level) monochrome displays.
x11gray4
This is a device for 4 bpp (16-level) monochrome displays.
On Mac OS X as of 10.6, the X server (XQuartz) only supports color depth 15 and 24. Depth 15 isn’t well-tested, and
it may be desirable, for serious use, to switch to depth 24 with:

defaults write org.x.X11 depth 24

7.5.2 Display device (MS Windows, OS/2, gtk+)

The display device is used by the MS Windows, OS/2 and the gtk+ versions of Ghostscript.

Options

The display device has several user settable options.


-dDisplayFormat=N (integer bit-field)
Some common values are 16#30804 for Windows RGB, 16#804 for gtk+ RGB, 16#20101 for Windows
monochrome, 16#102 for gtk+ monochrome, 16#20802 grayscale, 16#20808 for CMYK, 16#a0800 for
separations.
The bit fields are:
• native (1), gray (2), RGB (4), CMYK (8), or separation (80000) color spaces.
• unused first byte (40) or last byte (80).
• 1 (100), 4 (400), or 8 (800) bits/component.
• bigendian (00000 = RGB) or littleendian (10000 = BGR) order.
• top first (20000) or bottom first (00000) raster.
• 16 bits/pixel with 555 (00000) or 565 (40000) bitfields.
• For more details, see the Ghostscript Interpreter API.
-dDisplayResolution=DPI
Set the initial resolution resolution for the display device. This is used by the Windows clients to set the
display device resolution to the Windows display logical resolution. This can be overriden by the command
line option -rDPI.
When using the separation color space, the following options may be set using setpagedevice, as described in the
PostScript Language Reference:
SeparationColorNames
An array giving the names of the spot colors.
SeparationOrder
An array giving the names and order of the colorants to be output.

7.5. Display devices 195


Ghostscript Documentation, Release 10.01.0

7.6 IJS - Inkjet and other raster devices

IJS is a relatively new initiative to improve the quality and ease of use of inkjet printing with Ghostscript. Using IJS,
you can add new drivers, or upgrade existing ones, without recompiling Ghostscript. All driver authors are encouraged
to adapt their drivers for IJS, and if there is an IJS driver available for your printer, it should be your first choice.
Please see the IJS web page for more information about IJS, including a listing of IJS-compatible drivers.
A typical command line for IJS is:

gs -dSAFER -sDEVICE=ijs -sIjsServer=hpijs -sDeviceManufacturer=HEWLETT-PACKARD -


˓→sDeviceModel='DESKJET 990' -dIjsUseOutputFD -sOutputFile=/dev/usb/lp1 -dNOPAUSE --␣

˓→examples/tiger.eps

Individual IJS command line parameters are as follows:


-sIjsServer={path}
Sets the pathname for the IJS server (ie printer driver). Ghostscript will spawn a new process for this driver,
and communicate with it using the IJS protocol. The pathname need not be absolute, as the PATH environment
variable is searched, but it’s probably a good idea for robustness and security. Note also that if -dSAFER is not
specified, it’s possible for PostScript code to set this parameter, so it can cause arbitrary code to be executed. See
the section on Security for more information.
-sDeviceManufacturer={name} -sDeviceModel={name}
These parameters select the device according to IEEE-1284 standard device ID strings. In general, consult the
documentation for the driver to find the appropriate settings. Note that, if the value contains a space, you’ll want
to quote the value in your shell, as in the example above.
-sIjsParams={params}
This parameter allows you to set arbitrary IJS parameters on the IJS driver. The format is a comma-separated list
of key=value pairs. If it is necessary to send a value containing a comma or backslash, it can be escaped with a
backslash. Thus, -sIjsParams=Foo=bar,Baz=a\,b sets the parameter Foo to “bar”, and Baz to “a,b”.
-dIjsUseOutputFD
This flag indicates that Ghostscript should open the output file and pass a file descriptor to the server. If
not set, Ghostscript simply passes the filename set in OutputFile to the server. In most cases, this flag won’t
matter, but if you have a driver which works only with OutputFD (such as hpijs 1.0.2), or if you’re using the
-sOutputFile="|cmd" syntax, you’ll need to set it.
-dBitsPerSample=N
This parameter controls the number of bits per sample. The default value of 8 should be appropriate for most
work. For monochrome images, use -dBitsPerSample=1.
Generic Ghostscript options that are particularly relevant for IJS are summarized below:
-rnumber -rnumber1xnumber2
Sets the resolution, in dpi. If the resolution is not specified, Ghostscript queries the IJS server to determine the
preferred resolution. When the resolution is specified, it overrides the value (if any) preferred by the IJS server.
-dDuplex -dTumble
These flags enable duplex (two-sided) printing. Tumble controls the orientation. When Tumble is false, the
pages are oriented suitably at the left or right. When Tumble is true, the pages are oriented suitably for binding
at the top or bottom.
-sProcessColorModel={name}
Use this flag to select the process color model. Suitable values include DeviceGray, DeviceRGB, and
DeviceCMYK.

196 Chapter 7. Details of Ghostscript Output Devices


Ghostscript Documentation, Release 10.01.0

7.6.1 Building IJS

IJS is included by default on Unix gcc builds, and also in autoconf’ed builds. Others may need some makefile
tweaking. Firstly, make sure the IJS device is selected:
DEVICE_DEVS2=$(DD)ijs.dev
Next, make sure that the path and execution type are set in the top level makefile. The values for Unix are as
follows:
IJSSRCDIR=ijs IJSEXECTYPE=unix
At present, “unix” and “win” are the only supported values for IJSEXECTYPE. If neither sounds appropriate for
your system, it’s possible that more porting work is needed.
Lastly, make sure that ijs.mak is included in the top level makefile. It should be present right after the include of
icclib.mak.
IJS is not inherently platform-specific. We’re very much interested in taking patches from people who have ported it
to non-mainstream platforms. And once it’s built, you won’t have to recompile Ghostscript to support new drivers!

7.7 Rinkj - Resplendent inkjet driver

The Rinkj driver is an experimental new driver, capable of driving some Epson printers at a very high level of quality.
It is not currently recommended for the faint of heart.
You will need to add the following line to your makefile:
DEVICE_DEVS2=$(DD)rinkj.dev
Most of the configuration parameters, including resolution, choice of printer model, and linearization curves, are
in a separate setup file. In addition, we rely heavily on an ICC profile for mapping document colors to actual
device colors.
A typical command line invocation is:

gs -r1440x720 -sDEVICE=rinkj -sOutputFile=/dev/usb/lp0 -sSetupFile=lib/rinkj-2200-setup -


˓→sProfileOut=2200-cmyk.icm -dNOPAUSE -dBATCH file.ps

Individual Rinkj command line parameters are as follows:


-sSetupFile={path}
Specifies the path for the setup file.
-sProfileOut={path}
Specifies the path for the output ICC profile. This profile should be a link profile, mapping the
ProcessColorModel (DeviceCMYK by default) to the device color space.
For 6- and 7-color devices, the target color space for the output profile is currently a 4-component space. The conversion
from this into the 6- or 7-color space (the “ink split”) is done by lookup tables in the setup file.
Setup files are in a simple “Key: value” text format. Relevant keys are:
Manufacturer:{name} Model:{name}
The manufacturer and model of the individual device, using the same syntax as IEEE printer identification strings.
Currently, the only supported manufacturer string is “EPSON”, and the only supported model strings are “Stylus
Photo 2200” and “Stylus Photo 7600”.
Resolution:{x-dpi}x{y-dpi}
The resolution in dpi. Usually, this should match the Ghostscript resolution set with the -r switch. Otherwise,
the page image will be scaled.

7.7. Rinkj - Resplendent inkjet driver 197


Ghostscript Documentation, Release 10.01.0

Dither:{int}
Selects among variant dither options. Currently, the choices are 1 for one-bit dither, and 2, for a 2-bit variable
dot dither.
Aspect:{int}
Controls the aspect ratio for highlight dot placement. Valid values are 1, 2, and 4. For best results, choose a value
near the x resolution divided by the y resolution. For example, if resolution is 1440x720, aspect should be 2.
Microdot:{int}
Chooses a microdot size. On EPSON devices, this value is passed directly through to the “ESC ( e” command.
See EPSON documentation for further details (see, I told you this wasn’t for the faint of heart).
Unidirectional:{int}
Enables (1) or disables (0) unidirectional printing, which is slower but possibly higher quality.
AddLut:{plane}
Adds a linearization look-up table. The plane is one of “CcMmYKk”. The lookup table data follows. The line
immediately following AddLut is the number of data points. Then, for each data point is a line consisting of two
space-separated floats - the output value and the input value. If more than one LUT is specified for a single plane,
they are applied in sequence.
A typical setup file is supplied in lib/rinkj-2200-setup. It is configured for the 2200, but can be adapted to the
7600 just by changing the “Model” line.
A known issue with this driver is poor support for margins and page size. In some cases, this will cause an addi-
tional page to be ejected at the end of a job. You may be able to work around this by supplying a cut-down value for
-dDEVICEHEIGHTPOINTS, for example 755 for an 8.5x11 inch page on the EPSON 2200.

7.8 HP Deskjet official drivers

HP provides official drivers for many of their Deskjet printer models. In order to use these drivers, you will need the
HP Inkjet Server as well as Ghostscript, available from HP Linux Imaging and Printing. This version of Ghostscript
includes the patch from version 0.97 of the hpijs software. If you are installing hpijs from an RPM, you will only
need the hpijs RPM, not the Ghostscript-hpijs one, as the code needed to work with hpijs is already included.
Note that newer version of the hpijs drivers support the IJS protocol. If you can, you should consider using the ijs
driver instead. Among other things, the hpijs Ghostscript driver is Unix-only, and is untested on older Unix platforms.
As of the 0.97 version, hpijs supports the following printer models:
e-Series: e-20
DeskJet 350C Series: 350C
DeskJet 600C Series: 600C, 660C, 670/672C, 670TV, 680/682C
DeskJet 600C Series Photo: 610/612C, 640/648C, 690/692/693/694/695/697C
DeskJet 630C Series: 630/632C
DeskJet 800C Series: 810/812C, 830/832C, 840/842/843C, 880/882C, 895C
DeskJet 900C Series, PhotoSmart: 930/932C, 950/952C, 970C, PhotoSmart 1000/1100
DeskJet 990C, PhotoSmart: 960C, 980C, 990C, PhotoSmart 1215/1218
You will need to add the following line to your makefile:

DEVICE_DEVS2=$(DD)DJ630.dev $(DD)DJ6xx.dev $(DD)DJ6xxP.dev $(DD)DJ8xx.dev $(DD)DJ9xx.dev


˓→$(DD)DJ9xxVIP.dev $(DD)AP21xx.dev

198 Chapter 7. Details of Ghostscript Output Devices


Ghostscript Documentation, Release 10.01.0

Please see HP Linux Imaging and Printing for more information about this driver. Thanks to the folks at HP, especially
David Suffield for making this driver available and working to integrate it with Ghostscript.

7.9 Gimp-Print driver collection

The Gimp-Print project provides a large collection of printer drivers with an IJS interface. Please see Gimp print for
details.

7.10 MS Windows printers

This section was written by Russell Lang, the author of Ghostscript’s MS Windows-specific printer driver, and updated
by Pierre Arnaud.
The mswinpr2 device uses MS Windows printer drivers, and thus should work with any printer with device-independent
bitmap (DIB) raster capabilities. The printer resolution cannot be selected directly using PostScript commands from
Ghostscript: use the printer setup in the Control Panel instead. It is however possible to specify a maximum resolution
for the printed document (see below).
If no Windows printer name is specified in -sOutputFile, Ghostscript prompts for a Windows printer using the stan-
dard Print Setup dialog box. You must set the orientation to Portrait and the page size to that expected by Ghostscript;
otherwise the image will be clipped. Ghostscript sets the physical device size to that of the Windows printer driver, but
it does not update the PostScript clipping path.
If a Windows printer name is specified in -sOutputFile using the format “%printer%printer_name”, for instance:

gs ... -sOutputFile="%printer%Apple LaserWriter II NT"

Then Ghostscript attempts to open the Windows printer without prompting (except, of course, if the printer is con-
nected to FILE:). Ghostscript attempts to set the Windows printer page size and orientation to match that expected by
Ghostscript, but doesn’t always succeed. It uses this algorithm:
1. If the requested page size matches one of the Windows standard page sizes +/- 2mm, request that standard size.
2. Otherwise if the requested page size matches one of the Windows standard page sizes in landscape mode, ask
for that standard size in landscape.
3. Otherwise ask for the page size by specifying only its dimensions.
4. Merge the requests above with the defaults. If the printer driver ignores the requested paper size, no error is
generated: it will print on the wrong paper size.
5. Open the Windows printer with the merged orientation and size.
The Ghostscript physical device size is updated to match the Windows printer physical device.

7.9. Gimp-Print driver collection 199


Ghostscript Documentation, Release 10.01.0

7.10.1 Supported command-line parameters

The mswinpr2 device supports a limited number of command-line parameters (e.g. it does not support setting the
printer resolution). The recognized parameters are the following:
-sDEVICE=mswinpr2
Selects the MS Windows printer device. If Ghostscript was not compiled with this device as the default output
device, you have to specify it on the command line.
-dNoCancel
Hides the progress dialog, which shows the percent of the document page already processed and also provides
a cancel button. This option is useful if GS is intended to print pages in the background, without any user
intervention.
-sOutputFile="%printer%printer_name"
Specifies which printer should be used. The printer_name should be typed exactly as it appears in the Printers
control panel, including spaces.

7.10.2 Supported options (device properties)

Several extra options exist which cannot be set through the command-line, but only by executing the appropriate
PostScript setup code. These options can be set through the inclusion of a setup file on the command-line:

gs ... setup.ps ...

The setup.ps file is responsible for the device selection, therefore you should not specify the -sDEVICE=mswinpr2
option on the command-line if you are using such a setup file. Here is an example of such a setup file:

mark
/NoCancel true % don't show the cancel dialog
/BitsPerPixel 4 % force 4 bits/pixel
/UserSettings
<<
/DocumentName (Ghostscript document) % name for the Windows spooler
/MaxResolution 360 % maximum document resolution
>>
(mswinpr2) finddevice % select the Windows device driver
putdeviceprops
setdevice

This example disables the progress dialog (same as the -dNoCancel option), forces a 4 bits/pixel output resolution
and specifies additional user settings, such as the document name (which will be displayed by the Windows spooler
for the queued document) and the maximum resolution (here 360 dpi). It then finds and selects an instance of the MS
Windows device printer and activates it. This will show the standard printer dialog, since no /OutputFile property
was specified.
The following options are available:
/NoCancel boolean
Disables (hides) the progress dialog when set to true or show the progress dialog if not set or set to false.
/OutputFile string
Specifies which printer should be used. The string should be of the form %printer%printer_name, where the
printer_name should be typed exactly as it appears in the Printers control panel, including spaces.

200 Chapter 7. Details of Ghostscript Output Devices


Ghostscript Documentation, Release 10.01.0

/QueryUser integer
Shows the standard printer dialog (1 or any other value), shows the printer setup dialog (2) or selects the default
Windows printer without any user interaction (3).
/BitsPerPixel integer
Sets the device depth to the specified bits per pixel. Currently supported values are 1 (monochrome), 4 (CMYK
with screening handled by Ghostscript) and 24 (True Color, dithering handled by the Windows printer driver;
this option can produce huge print jobs).
/UserSettings dict
Sets additional options, defined in a dictionary. The following properties can be set:
/DocumentName string
Defines the user friendly document name which will be displayed by the Windows spooler.
/DocumentRange [n1 n2]
Defines the range of pages contained in the document. This information can be used by the printer dialog,
in conjunction with the following property.
/SelectedRange [n1 n2]
Defines the selected range of pages. This information will be displayed in the printer dialog and will be
updated after the user interaction. A PostScript program could check these values and print only the selected
page range.
/MaxResolution dpi
Specifies the maximum tolerated output resolution. If the selected printer has a higher resolution than dpi,
then Ghostscript will render the document with a submultiple of the printer resolution. For example, if
MaxResolution is set to 360 and the output printer supports up to 1200 dpi, then Ghostscript renders the
document with an internal resolution of 1200/4=300 dpi. This can be very useful to reduce the memory
requirements when printing in True Color on some high resolution ink-jet color printers.
These properties can be queried through the currentpagedevice operator. The following PostScript code snippet shows
how to do it for some of the properties:

currentpagedevice /BitsPerPixel get == % displays the selected depth

currentpagedevice /UserSettings get % get the additional options..


/us exch def % ..and assign them to a variable

us /DocumentName get == % displays the document name


us /SelectedRange get == % displays the selected page range

% other misc. information (don't rely on them)

us /Color get == % 1 => monochrome output, 2 => color output


us /PrintCopies get == % displays the number of copies requested

There are a few undocumented parameters stored in the UserSettings dictionary. You should not rely on them. Their
use is still experimental and they could be removed in a future version.

7.10. MS Windows printers 201


Ghostscript Documentation, Release 10.01.0

7.10.3 Duplex printing

If the Windows printer supports the duplex printing feature, then it will also be available through the mswinpr2 device.
You can query for this support through the /Duplex property of the currentpagedevice. If it returns null, then the
feature is not supported by the selected printer. Otherwise, true means that the printer is currently set up to print on
both faces of the paper and false that it is not, but that it can.
The following example shows how to print on both faces of the paper (using the long side of the paper as the reference):

<< /Duplex true /Tumble false >> setpagedevice

7.11 Sun SPARCprinter

This section was contributed by Martin Schulte.


With a SPARCprinter you always buy software that enables you to do PostScript printing on it. A page image is
composed on the host, which sends a bitmap to the SPARCprinter through a special SBUS video interface. So the need
for a Ghostscript interface to the SPARCprinter seems low, but on the other hand, Sun’s software prints some PostScript
drawings incorrectly: some pages contain a thin vertical line of rubbish, and on some Mathematica drawings the text at
the axes isn’t rotated. Ghostscript, however, gives the correct results. Moreover, replacing proprietary software should
never be a bad idea.
The problem is that there has yet been no effort to make the SPARCPrinter driver behave like a BSD output filter. I
made my tests using the script shown here.

7.11.1 Installation

Add sparc.dev to DEVICE_DEVS and compile Ghostscript as described in the documentation on how to build
Ghostscript. Afterwards you can use the following script as an example for printing after modifying it with the right
pathnames – including for {GSPATH} the full pathname of the Ghostscript executable:

outcmd1='/vol/local/lib/troff2/psxlate -r'
outcmd2='{GSPATH} -sDEVICE=sparc -sOUTPUTFILE=/dev/lpvi0 -'

if [ $# -eq 0 ]
then
$outcmd1 | $outcmd2
else
cat $* | $outcmd1 | $outcmd2
fi

7.11.2 Problems

Since /dev/lpi can be opened only for exclusive use, if another job has it open (engine_ctl_sparc or another
Ghostscript are the most likely candidates), Ghostscript stops with “Error: /invalidfileaccess in –.outputpage–”
In case of common printer problems like being out of paper, a warning describing the reason is printed to stdout. The
driver tries access again each five seconds. Due to a problem with the device driver (in the kernel) the reason for printer
failure isn’t always reported correctly to the program. This is the case, for instance, if you open the top cover (error
E5 on the printer’s display). Look at the display on the printer itself if a “Printer problem with unknown reason” is
reported. Fatal errors cause the print job to be terminated.

202 Chapter 7. Details of Ghostscript Output Devices


Ghostscript Documentation, Release 10.01.0

Note: There is some confusion whether the resolution setting should be the integers 300 and 400, or the symbolic
constants DPI300 and DPI400 (defined in lpviio.h). Ghostscript releases have had it both ways. It is currently the
latter. However, INOUE Namihiko reports (in bug #215256) that the former works better for him. If anyone has a
definitive answer, please let us know.

7.12 Apple dot matrix printer

This section was contributed by Mark Wedel.


The Apple Dot Matrix Printer (DMP) was a parallel predecessor to the Imagewriter printer. As far as I know, Im-
agewriter commands are a superset of the Dot Matrix printer’s, so the driver should generate output that can be printed
on Imagewriters.
To print images, the driver sets the printer for unidirectional printing and 15 characters per inch (cpi), or 120dpi. It
sets the line feed to 1/9 inch. When finished, it sets the printer to bidirectional printing, 1/8-inch line feeds, and 12 cpi.
There appears to be no way to reset the printer to initial values.
This code does not set for 8-bit characters (which is required). It also assumes that carriage return-newline is needed,
and not just carriage return. These are all switch settings on the DMP, and I have configured them for 8-bit data and
carriage return exclusively. Ensure that the Unix printer daemon handles 8-bit (binary) data properly; in my SunOS
4.1.1 printcap file the string “ms=pass8,-opost” works fine for this.
Finally, you can search devdemp.c for “Init” and “Reset” to find the strings that initialize the printer and reset things
when finished, and change them to meet your needs.

7.13 Special and Test devices

The devices in this section are intended primarily for testing. They may be interesting as code examples, as well.

7.13.1 Raw ‘bit’ devices

There are a collection of ‘bit’ devices that don’t do any special formatting but output ‘raw’ binary data for the page
images. These are used for benchmarking but can also be useful when you want to directly access the raster data.
The raw devices are bit bitrgb bitcmyk.

7.13.2 Bounding box output

There is a special bbox “device” that just prints the bounding box of each page. You select it in the usual way:

gs -dSAFER -dNOPAUSE -dBATCH -sDEVICE=bbox

It prints the output in a format like this:

%%BoundingBox: 14 37 570 719


%%HiResBoundingBox: 14.3ep08066 37.547999 569.495061 718.319158

Currently, it always prints the bounding box on stderr; eventually, it should also recognize -sOutputFile=.
By default, white objects don’t contribute to the bounding box because many files fill the whole page with white before
drawing other objects. This can be changed by:

7.12. Apple dot matrix printer 203


Ghostscript Documentation, Release 10.01.0

<< /WhiteIsOpaque true >> setpagedevice

Note that this device, like other devices, has a resolution and a (maximum) page size. As for other devices, the prod-
uct (resolution x page size) is limited to approximately 500K pixels. By default, the resolution is 4000 DPI and the
maximum page size is approximately 125”, or approximately 9000 default (1/72”) user coordinate units. If you need
to measure larger pages than this, you must reset both the resolution and the page size in pixels, e.g.,

gs -dNOPAUSE -dBATCH -sDEVICE=bbox -r100 -g500000x500000

Note: The box returned by the bbox device is just sufficient to contain the pixels which would be rendered by
Ghostscript at the selected resolution. The language rendering rules can mean this differs by up to two pixels from
the ‘theoretical’ area covered, and the precise area covered by curves and line joins is also, to some extent, related to
the resolution. Finally the actual pixel position needs to be converted back to PostScript points, and that can be affected
by mathematical precision, which can cause rounding errors. As a result the bounding box returned may differ very
slightly from that which was expected.

7.13.3 Ink coverage output

There are two special inkcov devices that print the ink coverage of each page; the inkcov device and the ink_cov device.
They are selected like this:

gs -dSAFER -dNOPAUSE -dBATCH -o- -sDEVICE=inkcov Y.pdf


gs -dSAFER -dNOPAUSE -dBATCH -o- -sDEVICE=ink_cov Y.pdf

These commands also work as expected:

gs -o X_inkcov.txt -sDEVICE=inkcov Y.pdf


gs -o X_inkcov_page%03d.txt -sDEVICE=inkcov Y.pdf

The devices print their output in a format like this:

Page 1
0.10022 0.09563 0.10071 0.06259 CMYK OK
Page 2
0.06108 0.05000 0.05834 0.04727 CMYK OK

The difference between the two devices is that the inkcov device considers each rendered pixel and whether it marks
the C, M, Y or K channels. So the percentages are a measure of how many device pixels contain that ink. The ink_cov
device gives the more traditional use of ink coverage, it also considers the amount of each colourant at each rendered
pixel, so the percentages in this case are what percentage of the ink is used on the page.
As an example, If we take a page which is covered by a pure 100% cyan fill both devices would give the same result
1.00 0.00 0.00 0.00; each pixel is marked by the cyan ink and each pixel contains 100% cyan. If however we use a 50%
cyan fill the inkcov device will still give 1.00 0.00 0.00 0.00 as 100% of the pixels contain cyan. The ink_cov device,
however, would give a result of 0.50 0.00 0.00 0.00.

204 Chapter 7. Details of Ghostscript Output Devices


Ghostscript Documentation, Release 10.01.0

7.13.4 Permutation (DeviceN color model)

With no additional parameters, the device named “permute” looks to Ghostscript like a standard CMYK contone device,
and outputs a PPM file, using a simple CMYK->RGB transform. This should be the baseline for regression testing.
With the addition of -dPermute=1, the internal behavior changes somewhat, but in most cases the resulting rendered
file should be the same. In this mode, the color model becomes “DeviceN” rather than “DeviceCMYK”, the number of
components goes to six, and the color model is considered to be the (yellow, cyan, cyan, magenta, 0, black) tuple. This
is what’s rendered into the memory buffer. Finally, on conversion to RGB for output, the colors are permuted back.
As such, this code should check that all imaging code paths are 64-bit clean. Additionally, it should find incorrect code
that assumes that the color model is one of DeviceGray, DeviceRGB, or DeviceCMYK.
Currently, the code has the limitation of 8-bit continuous tone rendering only. An enhancement to do halftones is
planned as well. Note, however, that when testing permuted halftones for consistency, it is important to permute the
planes of the default halftone accordingly, and that any file which sets halftones explicitly will fail a consistency check.

7.13.5 spotcmyk (DeviceN color model)

The spotcmyk device was created for debugging and testing of the devicen extensions to Ghostscript that were released
in version 8.0. There are also another device (devicen) in the same source file. It were created for testing however it
are not actually useful except as example code.
The spotcmyk device was also designed to provide example code for a device which supports spot colors. Spot colors
need to be specified prior to opening the first page. This can be done via adding the following to the command line: -c
"<< /SeparationColorNames [ /Name1 /Name2 ] >> setpagedevice" -f.
The spotcmyk device produces a binary data file (similar to the bitcmyk device) for the CMYK data. This data file has
the name specified by the “OutputFile” parameter. The device also produces a binary data file (similar to the bitmono
device) for each spot color plane. These data files have the name specified by the “OutputFile” parameter with “sn”
appended to the end (where “n” is the spot color number 0 to 12)”.
After the spotcmyk device produces the binary data files, the files are read and PCX format versions of these files are
created with “.pcx” appended to the binary source file name.
If the spotcmyk is being used with three spot colors and the “OutputFile” parameter is xxx then the following files
would be created by the device:

xxx binary CMYK data


xxxs0 binary data for first spot color
xxxs1 binary data for second spot color
xxxs2 binary data for third spot color
xxx.pcx CMYK data in PCX format
xxxs0.pcx first spot color in PCX format
xxxs1.pcx second spot color in PCX format
xxxs2.pcx third spot color in PCX format

The spotcmyk device has the creation of the binary data files separated from the creation of the PCX files since the
source file is intended as example code and many people may not be interested in the PCX format. The PCX format
was chosen because it was simple to implement from pre-existing code and viewers are available. The PCX format
does have the dis-advantage that most of those viewers are on Windows.

7.13. Special and Test devices 205


Ghostscript Documentation, Release 10.01.0

7.13.6 XCF (DeviceN color model)

The XCF file format is the native image format for the GIMP program. This format is currently supported by two
devices: xcfrgb and xcfcmyk.
We have been warned by the people supporting the GIMP program that they reserve the right to change the XCF format
at anytime and thus these devices may become invalid. They are being included in the documentation because we have
received some questions about what these devices do.
The XCF devices were created for testing of the devicen extensions to Ghostscript which were released in version 8.0.
The xcfrgb device uses a DeviceRGB process color model and creates a normal XCF file.
The xcfcmyk device was created as a means of viewing spot colors for those users that do not have access to either
Photoshop (see the PSD devices) or a PCX viewer (see the spotcmyk device).
The xcfcmyk device starts by using a DeviceCMYK process color model. The DeviceCMYK process color model allows
the xcfcmyk device to also support spot colors. Spot colors need to be specified prior to opening the first page. This
can be done via adding the following to the command line:

-c "<< /SeparationColorNames [ /Name1 /Name2 ] >> setpagedevice" -f

After a page is complete, the xcfcmyk converts the CMYK image data into RGB for storing in the XCF output file. The
XCF format does not currently support CMYK data directly. The spot color planes are converted into alpha channel
planes. This is done because the XCF format does not currently support spot colors.

206 Chapter 7. Details of Ghostscript Output Devices


CHAPTER

EIGHT

HIGH LEVEL DEVICES

High level devices are Ghostscript output devices which do not render to a raster, in general they produce ‘vector’ as
opposed to bitmap output. Such devices currently include: pdfwrite, ps2write, eps2write, txtwrite, xpswrite, pxlmono,
pxlcolor and docxwrite.
Although these devices produce output which is not a raster, they still work in the same general fashion as all Ghostscript
devices. The input (PostScript, PDF, XPS, PCL or PXL) is handled by an appropriate interpreter, the interpreter
processes the input and produces from it a sequence of drawing ‘primitives’ which are handed to the device. The
device decides whether to handle the primitive itself, or call upon the graphics library to render the primitive to the
final raster.
Primitives are quite low level graphics operations; as an example consider the PDF sequence '0 0 100 100 re f'.
This constructs a rectangle with the bottom left corner at 0,0 which is 100 units wide by 100 units high, and fills it with
the current color. A lower level implementation using only primitives would first move the current point to 0,0, then
construct a line to 0,100, then a line to 100,100, a line to 100, 0 and finally a line back to 0,0. It would then fill the
result.
Obviously that’s a simple example but it serves to demonstrate the point.
Now the raster devices all call the graphics library to process primitives (though they may choose to take some action
first) and render the result to a bitmap. The high level devices instead reassemble the primitives back into high level
page description and write the result to a file. This means that the output, while it should be visually the same as the
input (because it makes the same marks), is not the same as the original input, even if the output Page Description
Language is the same as the input one was (eg PDF to PDF).
Why is this important? Firstly because the description of the page won’t be the same, if your workflow relies upon (for
example) finding rectangles in the description then it might not work after it has been processed by a high level device,
as the rectangles may all have turned into lengthy path descriptions.
In addition, any part of the original input which does not actually make marks on the page (such as hyperlinks, book-
marks, comments etc) will normally not be present in the output, even if the output is the same format. In general the
PDF interpreter and the PDF output device (pdfwrite) try to preserve the non-marking information from the input, but
some ki