]> www.fi.muni.cz Git - evince.git/blobdiff - pdf/xpdf/PSOutputDev.cc
Add «nb» to ALL_LINGUAS too.
[evince.git] / pdf / xpdf / PSOutputDev.cc
index 18359119617a158c28ea0a0b0245d0df0aadeac1..28811a8320593679d91553dc4aa227c648d94eee 100644 (file)
@@ -2,22 +2,24 @@
 //
 // PSOutputDev.cc
 //
 //
 // PSOutputDev.cc
 //
-// Copyright 1996-2002 Glyph & Cog, LLC
+// Copyright 1996-2003 Glyph & Cog, LLC
 //
 //========================================================================
 
 //
 //========================================================================
 
-#ifdef __GNUC__
+#include <aconf.h>
+
+#ifdef USE_GCC_PRAGMAS
 #pragma implementation
 #endif
 
 #pragma implementation
 #endif
 
-#include <aconf.h>
 #include <stdio.h>
 #include <stddef.h>
 #include <stdarg.h>
 #include <signal.h>
 #include <math.h>
 #include "GString.h"
 #include <stdio.h>
 #include <stddef.h>
 #include <stdarg.h>
 #include <signal.h>
 #include <math.h>
 #include "GString.h"
-#include "config.h"
+#include "GList.h"
+#include "xpdfconfig.h"
 #include "GlobalParams.h"
 #include "Object.h"
 #include "Error.h"
 #include "GlobalParams.h"
 #include "Object.h"
 #include "Error.h"
@@ -25,9 +27,9 @@
 #include "Gfx.h"
 #include "GfxState.h"
 #include "GfxFont.h"
 #include "Gfx.h"
 #include "GfxState.h"
 #include "GfxFont.h"
-#include "CharCodeToUnicode.h"
 #include "UnicodeMap.h"
 #include "UnicodeMap.h"
-#include "FontFile.h"
+#include "FoFiType1C.h"
+#include "FoFiTrueType.h"
 #include "Catalog.h"
 #include "Page.h"
 #include "Stream.h"
 #include "Catalog.h"
 #include "Page.h"
 #include "Stream.h"
 static char *prolog[] = {
   "/xpdf 75 dict def xpdf begin",
   "% PDF special state",
 static char *prolog[] = {
   "/xpdf 75 dict def xpdf begin",
   "% PDF special state",
-  "/pdfDictSize 14 def",
+  "/pdfDictSize 15 def",
+  "~1",
+  "/pdfStates 64 array def",
+  "  0 1 63 {",
+  "    pdfStates exch pdfDictSize dict",
+  "    dup /pdfStateIdx 3 index put",
+  "    put",
+  "  } for",
+  "~a",
   "/pdfSetup {",
   "  3 1 roll 2 array astore",
   "  /setpagedevice where {",
   "/pdfSetup {",
   "  3 1 roll 2 array astore",
   "  /setpagedevice where {",
@@ -54,14 +64,25 @@ static char *prolog[] = {
   "      /PageSize exch def",
   "      /ImagingBBox null def",
   "      /Policies 1 dict dup begin /PageSize 3 def end def",
   "      /PageSize exch def",
   "      /ImagingBBox null def",
   "      /Policies 1 dict dup begin /PageSize 3 def end def",
-  "      /Duplex exch def",
+  "      { /Duplex true def } if",
   "    currentdict end setpagedevice",
   "  } {",
   "    pop pop",
   "  } ifelse",
   "} def",
   "    currentdict end setpagedevice",
   "  } {",
   "    pop pop",
   "  } ifelse",
   "} def",
+  "~1",
+  "/pdfOpNames [",
+  "  /pdfFill /pdfStroke /pdfLastFill /pdfLastStroke",
+  "  /pdfTextMat /pdfFontSize /pdfCharSpacing /pdfTextRender",
+  "  /pdfTextRise /pdfWordSpacing /pdfHorizScaling /pdfTextClipPath",
+  "] def",
+  "~a",
   "/pdfStartPage {",
   "/pdfStartPage {",
+  "~1",
+  "  pdfStates 0 get begin",
+  "~2",
   "  pdfDictSize dict begin",
   "  pdfDictSize dict begin",
+  "~a",
   "  /pdfFill [0] def",
   "  /pdfStroke [0] def",
   "  /pdfLastFill false def",
   "  /pdfFill [0] def",
   "  /pdfStroke [0] def",
   "  /pdfLastFill false def",
@@ -73,6 +94,7 @@ static char *prolog[] = {
   "  /pdfTextRise 0 def",
   "  /pdfWordSpacing 0 def",
   "  /pdfHorizScaling 1 def",
   "  /pdfTextRise 0 def",
   "  /pdfWordSpacing 0 def",
   "  /pdfHorizScaling 1 def",
+  "  /pdfTextClipPath [] def",
   "} def",
   "/pdfEndPage { end } def",
   "% separation convention operators",
   "} def",
   "/pdfEndPage { end } def",
   "% separation convention operators",
@@ -99,7 +121,7 @@ static char *prolog[] = {
   "  /customcolorimage {",
   "    gsave",
   "    [ exch /Separation exch dup 4 get exch /DeviceCMYK exch",
   "  /customcolorimage {",
   "    gsave",
   "    [ exch /Separation exch dup 4 get exch /DeviceCMYK exch",
-  "      0 4 getinterval cvx",
+  "      0 4 getinterval",
   "      [ exch /dup load exch { mul exch dup } /forall load",
   "        /pop load dup ] cvx",
   "    ] setcolorspace",
   "      [ exch /dup load exch { mul exch dup } /forall load",
   "        /pop load dup ] cvx",
   "    ] setcolorspace",
@@ -189,7 +211,16 @@ static char *prolog[] = {
   "  } ifelse",
   "} def",
   "% graphics state operators",
   "  } ifelse",
   "} def",
   "% graphics state operators",
+  "~1",
+  "/q {",
+  "  gsave",
+  "  pdfOpNames length 1 sub -1 0 { pdfOpNames exch get load } for",
+  "  pdfStates pdfStateIdx 1 add get begin",
+  "  pdfOpNames { exch def } forall",
+  "} def",
+  "~2",
   "/q { gsave pdfDictSize dict begin } def",
   "/q { gsave pdfDictSize dict begin } def",
+  "~a",
   "/Q { end grestore } def",
   "/cm { concat } def",
   "/d { setdash } def",
   "/Q { end grestore } def",
   "/cm { concat } def",
   "/d { setdash } def",
@@ -246,55 +277,101 @@ static char *prolog[] = {
   "/Td { pdfTextMat transform moveto } def",
   "/Tm { /pdfTextMat exch def } def",
   "% text string operators",
   "/Td { pdfTextMat transform moveto } def",
   "/Tm { /pdfTextMat exch def } def",
   "% text string operators",
-  "/awcp { % awidthcharpath",
+  "/cshow where {",
+  "  pop",
+  "  /cshow2 {",
+  "    dup {",
+  "      pop pop",
+  "      1 string dup 0 3 index put 3 index exec",
+  "    } exch cshow",
+  "    pop pop",
+  "  } def",
+  "}{",
+  "  /cshow2 {",
+  "    currentfont /FontType get 0 eq {",
+  "      0 2 2 index length 1 sub {",
+  "        2 copy get exch 1 add 2 index exch get",
+  "        2 copy exch 256 mul add",
+  "        2 string dup 0 6 5 roll put dup 1 5 4 roll put",
+  "        3 index exec",
+  "      } for",
+  "    } {",
+  "      dup {",
+  "        1 string dup 0 3 index put 3 index exec",
+  "      } forall",
+  "    } ifelse",
+  "    pop pop",
+  "  } def",
+  "} ifelse",
+  "/awcp {", // awidthcharpath
   "  exch {",
   "  exch {",
-  "    1 string dup 0 3 index put 2 index charpath",
-  "    3 index 3 index rmoveto",
-  "    4 index eq { 5 index 5 index rmoveto } if",
-  "  } forall",
+  "    false charpath",
+  "    5 index 5 index rmoveto",
+  "    6 index eq { 7 index 7 index rmoveto } if",
+  "  } exch cshow2",
   "  6 {pop} repeat",
   "} def",
   "  6 {pop} repeat",
   "} def",
-  "/Tj { fCol",  // because stringwidth has to draw Type 3 chars
-  "      0 pdfTextRise pdfTextMat dtransform rmoveto",
-  "      1 index stringwidth pdfTextMat idtransform pop",
-  "      sub 1 index length dup 0 ne { div } { pop pop 0 } ifelse",
-  "      pdfWordSpacing pdfHorizScaling mul 0 pdfTextMat dtransform 32",
-  "      4 3 roll pdfCharSpacing pdfHorizScaling mul add 0",
-  "      pdfTextMat dtransform",
-  "      6 5 roll",
-  "      currentpoint 8 2 roll",
-  "      pdfTextRender 1 and 0 eq {",
-  "        6 copy awidthshow",
-  "      } if",
-  "      pdfTextRender 3 and dup 1 eq exch 2 eq or {",
-  "        8 6 roll moveto",
-  "        sCol false awcp currentpoint stroke moveto",
-  "      } {",
-  "        8 {pop} repeat",
-  "      } ifelse",
-  "      0 pdfTextRise neg pdfTextMat dtransform rmoveto } def",
-  "/Tj16 { pdfTextRender 1 and 0 eq { fCol } { sCol } ifelse",
-  "        0 pdfTextRise pdfTextMat dtransform rmoveto",
-  "        2 index stringwidth pdfTextMat idtransform pop",
-  "        sub exch div",
-  "        pdfWordSpacing pdfHorizScaling mul 0 pdfTextMat dtransform 32",
-  "        4 3 roll pdfCharSpacing pdfHorizScaling mul add 0",
-  "        pdfTextMat dtransform",
-  "        6 5 roll awidthshow",
-  "        0 pdfTextRise neg pdfTextMat dtransform rmoveto } def",
-  "/Tj16V { pdfTextRender 1 and 0 eq { fCol } { sCol } ifelse",
-  "         0 pdfTextRise pdfTextMat dtransform rmoveto",
-  "         2 index stringwidth pdfTextMat idtransform exch pop",
-  "         sub exch div",
-  "         0 pdfWordSpacing pdfTextMat dtransform 32",
-  "         4 3 roll pdfCharSpacing add 0 exch",
-  "         pdfTextMat dtransform",
-  "         6 5 roll awidthshow",
-  "         0 pdfTextRise neg pdfTextMat dtransform rmoveto } def",
+  "/Tj {",
+  "  fCol",  // because stringwidth has to draw Type 3 chars
+  "  1 index stringwidth pdfTextMat idtransform pop",
+  "  sub 1 index length dup 0 ne { div } { pop pop 0 } ifelse",
+  "  pdfWordSpacing pdfHorizScaling mul 0 pdfTextMat dtransform 32",
+  "  4 3 roll pdfCharSpacing pdfHorizScaling mul add 0",
+  "  pdfTextMat dtransform",
+  "  6 5 roll Tj1",
+  "} def",
+  "/Tj16 {",
+  "  fCol",  // because stringwidth has to draw Type 3 chars
+  "  2 index stringwidth pdfTextMat idtransform pop",
+  "  sub exch div",
+  "  pdfWordSpacing pdfHorizScaling mul 0 pdfTextMat dtransform 32",
+  "  4 3 roll pdfCharSpacing pdfHorizScaling mul add 0",
+  "  pdfTextMat dtransform",
+  "  6 5 roll Tj1",
+  "} def",
+  "/Tj16V {",
+  "  fCol",  // because stringwidth has to draw Type 3 chars
+  "  2 index stringwidth pdfTextMat idtransform exch pop",
+  "  sub exch div",
+  "  0 pdfWordSpacing pdfTextMat dtransform 32",
+  "  4 3 roll pdfCharSpacing add 0 exch",
+  "  pdfTextMat dtransform",
+  "  6 5 roll Tj1",
+  "} def",
+  "/Tj1 {",
+  "  0 pdfTextRise pdfTextMat dtransform rmoveto",
+  "  currentpoint 8 2 roll",
+  "  pdfTextRender 1 and 0 eq {",
+  "    6 copy awidthshow",
+  "  } if",
+  "  pdfTextRender 3 and dup 1 eq exch 2 eq or {",
+  "    7 index 7 index moveto",
+  "    6 copy",
+  "    currentfont /FontType get 3 eq { fCol } { sCol } ifelse",
+  "    false awcp currentpoint stroke moveto",
+  "  } if",
+  "  pdfTextRender 4 and 0 ne {",
+  "    8 6 roll moveto",
+  "    false awcp",
+  "    /pdfTextClipPath [ pdfTextClipPath aload pop",
+  "      {/moveto cvx}",
+  "      {/lineto cvx}",
+  "      {/curveto cvx}",
+  "      {/closepath cvx}",
+  "    pathforall ] def",
+  "    currentpoint newpath moveto",
+  "  } {",
+  "    8 {pop} repeat",
+  "  } ifelse",
+  "  0 pdfTextRise neg pdfTextMat dtransform rmoveto",
+  "} def",
   "/TJm { pdfFontSize 0.001 mul mul neg 0",
   "       pdfTextMat dtransform rmoveto } def",
   "/TJmV { pdfFontSize 0.001 mul mul neg 0 exch",
   "        pdfTextMat dtransform rmoveto } def",
   "/TJm { pdfFontSize 0.001 mul mul neg 0",
   "       pdfTextMat dtransform rmoveto } def",
   "/TJmV { pdfFontSize 0.001 mul mul neg 0 exch",
   "        pdfTextMat dtransform rmoveto } def",
+  "/Tclip { pdfTextClipPath cvx exec clip newpath",
+  "         /pdfTextClipPath [] def } def",
+  "~1",
   "% Level 1 image operators",
   "/pdfIm1 {",
   "  /pdfImBuf1 4 index string def",
   "% Level 1 image operators",
   "/pdfIm1 {",
   "  /pdfImBuf1 4 index string def",
@@ -315,6 +392,11 @@ static char *prolog[] = {
   "  /pdfImBuf1 4 index 7 add 8 idiv string def",
   "  { currentfile pdfImBuf1 readhexstring pop } imagemask",
   "} def",
   "  /pdfImBuf1 4 index 7 add 8 idiv string def",
   "  { currentfile pdfImBuf1 readhexstring pop } imagemask",
   "} def",
+  "/pdfImM1a {",
+  "  { 2 copy get exch 1 add exch } imagemask",
+  "  pop pop",
+  "} def",
+  "~2",
   "% Level 2 image operators",
   "/pdfImBuf 100 string def",
   "/pdfIm {",
   "% Level 2 image operators",
   "/pdfImBuf 100 string def",
   "/pdfIm {",
@@ -326,11 +408,15 @@ static char *prolog[] = {
   "/pdfImSep {",
   "  findcmykcustomcolor exch",
   "  dup /Width get /pdfImBuf1 exch string def",
   "/pdfImSep {",
   "  findcmykcustomcolor exch",
   "  dup /Width get /pdfImBuf1 exch string def",
+  "  dup /Decode get aload pop 1 index sub /pdfImDecodeRange exch def",
+  "  /pdfImDecodeLow exch def",
   "  begin Width Height BitsPerComponent ImageMatrix DataSource end",
   "  /pdfImData exch def",
   "  { pdfImData pdfImBuf1 readstring pop",
   "    0 1 2 index length 1 sub {",
   "  begin Width Height BitsPerComponent ImageMatrix DataSource end",
   "  /pdfImData exch def",
   "  { pdfImData pdfImBuf1 readstring pop",
   "    0 1 2 index length 1 sub {",
-  "      1 index exch 2 copy get 255 exch sub put",
+  "      1 index exch 2 copy get",
+  "      pdfImDecodeRange mul 255 div pdfImDecodeLow add round cvi",
+  "      255 exch sub put",
   "    } for }",
   "  6 5 roll customcolorimage",
   "  { currentfile pdfImBuf readline",
   "    } for }",
   "  6 5 roll customcolorimage",
   "  { currentfile pdfImBuf readline",
@@ -343,6 +429,7 @@ static char *prolog[] = {
   "    not { pop exit } if",
   "    (%-EOD-) eq { exit } if } loop",
   "} def",
   "    not { pop exit } if",
   "    (%-EOD-) eq { exit } if } loop",
   "} def",
+  "~a",
   "end",
   NULL
 };
   "end",
   NULL
 };
@@ -480,6 +567,87 @@ PSOutCustomColor::~PSOutCustomColor() {
   delete name;
 }
 
   delete name;
 }
 
+//------------------------------------------------------------------------
+// DeviceNRecoder
+//------------------------------------------------------------------------
+
+class DeviceNRecoder: public FilterStream {
+public:
+
+  DeviceNRecoder(Stream *strA, int widthA, int heightA,
+                GfxImageColorMap *colorMapA);
+  virtual ~DeviceNRecoder();
+  virtual StreamKind getKind() { return strWeird; }
+  virtual void reset();
+  virtual int getChar()
+    { return (bufIdx >= bufSize && !fillBuf()) ? EOF : buf[bufIdx++]; }
+  virtual int lookChar()
+    { return (bufIdx >= bufSize && !fillBuf()) ? EOF : buf[bufIdx]; }
+  virtual GString *getPSFilter(int psLevel, char *indent) { return NULL; }
+  virtual GBool isBinary(GBool last = gTrue) { return gTrue; }
+  virtual GBool isEncoder() { return gTrue; }
+
+private:
+
+  GBool fillBuf();
+
+  int width, height;
+  GfxImageColorMap *colorMap;
+  Function *func;
+  ImageStream *imgStr;
+  int buf[gfxColorMaxComps];
+  int pixelIdx;
+  int bufIdx;
+  int bufSize;
+};
+
+DeviceNRecoder::DeviceNRecoder(Stream *strA, int widthA, int heightA,
+                              GfxImageColorMap *colorMapA):
+    FilterStream(strA) {
+  width = widthA;
+  height = heightA;
+  colorMap = colorMapA;
+  imgStr = NULL;
+  pixelIdx = 0;
+  bufIdx = gfxColorMaxComps;
+  bufSize = ((GfxDeviceNColorSpace *)colorMap->getColorSpace())->
+              getAlt()->getNComps();
+  func = ((GfxDeviceNColorSpace *)colorMap->getColorSpace())->
+           getTintTransformFunc();
+}
+
+DeviceNRecoder::~DeviceNRecoder() {
+  if (imgStr) {
+    delete imgStr;
+  }
+}
+
+void DeviceNRecoder::reset() {
+  imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(),
+                          colorMap->getBits());
+  imgStr->reset();
+}
+
+GBool DeviceNRecoder::fillBuf() {
+  Guchar pixBuf[gfxColorMaxComps];
+  GfxColor color;
+  double y[gfxColorMaxComps];
+  int i;
+
+  if (pixelIdx >= width * height) {
+    return gFalse;
+  }
+  imgStr->getPixel(pixBuf);
+  colorMap->getColor(pixBuf, &color);
+  func->transform(color.c, y);
+  for (i = 0; i < bufSize; ++i) {
+    buf[i] = (int)(y[i] * 255 + 0.5);
+  }
+  bufIdx = 0;
+  ++pixelIdx;
+  return gTrue;
+}
+
 //------------------------------------------------------------------------
 // PSOutputDev
 //------------------------------------------------------------------------
 //------------------------------------------------------------------------
 // PSOutputDev
 //------------------------------------------------------------------------
@@ -488,50 +656,38 @@ extern "C" {
 typedef void (*SignalFunc)(int);
 }
 
 typedef void (*SignalFunc)(int);
 }
 
+static void outputToFile(void *stream, char *data, int len) {
+  fwrite(data, 1, len, (FILE *)stream);
+}
+
 PSOutputDev::PSOutputDev(char *fileName, XRef *xrefA, Catalog *catalog,
 PSOutputDev::PSOutputDev(char *fileName, XRef *xrefA, Catalog *catalog,
-                        int firstPage, int lastPage, PSOutMode modeA) {
-  Page *page;
-  PDFRectangle *box;
-  Dict *resDict;
-  Annots *annots;
-  char **p;
-  int pg;
-  Object obj1, obj2;
-  int i;
+                        int firstPage, int lastPage, PSOutMode modeA,
+                        int imgLLXA, int imgLLYA, int imgURXA, int imgURYA,
+                        GBool manualCtrlA) {
+  FILE *f;
+  PSFileType fileTypeA;
+
+  underlayCbk = NULL;
+  underlayCbkData = NULL;
+  overlayCbk = NULL;
+  overlayCbkData = NULL;
 
 
-  // initialize
-  xref = xrefA;
-  level = globalParams->getPSLevel();
-  mode = modeA;
-  paperWidth = globalParams->getPSPaperWidth();
-  paperHeight = globalParams->getPSPaperHeight();
   fontIDs = NULL;
   fontFileIDs = NULL;
   fontFileNames = NULL;
   font16Enc = NULL;
   fontIDs = NULL;
   fontFileIDs = NULL;
   fontFileNames = NULL;
   font16Enc = NULL;
+  xobjStack = NULL;
   embFontList = NULL;
   embFontList = NULL;
-  f = NULL;
-  if (mode == psModeForm) {
-    lastPage = firstPage;
-  }
-  processColors = 0;
   customColors = NULL;
   customColors = NULL;
-  inType3Char = gFalse;
+  haveTextClip = gFalse;
   t3String = NULL;
 
   t3String = NULL;
 
-#if OPI_SUPPORT
-  // initialize OPI nesting levels
-  opi13Nest = 0;
-  opi20Nest = 0;
-#endif
-
   // open file or pipe
   // open file or pipe
-  ok = gTrue;
   if (!strcmp(fileName, "-")) {
   if (!strcmp(fileName, "-")) {
-    fileType = psStdout;
+    fileTypeA = psStdout;
     f = stdout;
   } else if (fileName[0] == '|') {
     f = stdout;
   } else if (fileName[0] == '|') {
-    fileType = psPipe;
+    fileTypeA = psPipe;
 #ifdef HAVE_POPEN
 #ifndef WIN32
     signal(SIGPIPE, (SignalFunc)SIG_IGN);
 #ifdef HAVE_POPEN
 #ifndef WIN32
     signal(SIGPIPE, (SignalFunc)SIG_IGN);
@@ -547,7 +703,7 @@ PSOutputDev::PSOutputDev(char *fileName, XRef *xrefA, Catalog *catalog,
     return;
 #endif
   } else {
     return;
 #endif
   } else {
-    fileType = psFile;
+    fileTypeA = psFile;
     if (!(f = fopen(fileName, "w"))) {
       error(-1, "Couldn't open PostScript file '%s'", fileName);
       ok = gFalse;
     if (!(f = fopen(fileName, "w"))) {
       error(-1, "Couldn't open PostScript file '%s'", fileName);
       ok = gFalse;
@@ -555,6 +711,94 @@ PSOutputDev::PSOutputDev(char *fileName, XRef *xrefA, Catalog *catalog,
     }
   }
 
     }
   }
 
+  init(outputToFile, f, fileTypeA,
+       xrefA, catalog, firstPage, lastPage, modeA,
+       imgLLXA, imgLLYA, imgURXA, imgURYA, manualCtrlA);
+}
+
+PSOutputDev::PSOutputDev(PSOutputFunc outputFuncA, void *outputStreamA,
+                        XRef *xrefA, Catalog *catalog,
+                        int firstPage, int lastPage, PSOutMode modeA,
+                        int imgLLXA, int imgLLYA, int imgURXA, int imgURYA,
+                        GBool manualCtrlA) {
+  underlayCbk = NULL;
+  underlayCbkData = NULL;
+  overlayCbk = NULL;
+  overlayCbkData = NULL;
+
+  fontIDs = NULL;
+  fontFileIDs = NULL;
+  fontFileNames = NULL;
+  font16Enc = NULL;
+  xobjStack = NULL;
+  embFontList = NULL;
+  customColors = NULL;
+  haveTextClip = gFalse;
+  t3String = NULL;
+
+  init(outputFuncA, outputStreamA, psGeneric,
+       xrefA, catalog, firstPage, lastPage, modeA,
+       imgLLXA, imgLLYA, imgURXA, imgURYA, manualCtrlA);
+}
+
+void PSOutputDev::init(PSOutputFunc outputFuncA, void *outputStreamA,
+                      PSFileType fileTypeA, XRef *xrefA, Catalog *catalog,
+                      int firstPage, int lastPage, PSOutMode modeA,
+                      int imgLLXA, int imgLLYA, int imgURXA, int imgURYA,
+                      GBool manualCtrlA) {
+  Page *page;
+  PDFRectangle *box;
+
+  // initialize
+  ok = gTrue;
+  outputFunc = outputFuncA;
+  outputStream = outputStreamA;
+  fileType = fileTypeA;
+  xref = xrefA;
+  level = globalParams->getPSLevel();
+  mode = modeA;
+  paperWidth = globalParams->getPSPaperWidth();
+  paperHeight = globalParams->getPSPaperHeight();
+  imgLLX = imgLLXA;
+  imgLLY = imgLLYA;
+  imgURX = imgURXA;
+  imgURY = imgURYA;
+  if (imgLLX == 0 && imgURX == 0 && imgLLY == 0 && imgURY == 0) {
+    globalParams->getPSImageableArea(&imgLLX, &imgLLY, &imgURX, &imgURY);
+  }
+  if (paperWidth < 0 || paperHeight < 0) {
+    // this check is needed in case the document has zero pages
+    if (firstPage > 0 && firstPage <= catalog->getNumPages()) {
+      page = catalog->getPage(firstPage);
+      paperWidth = (int)(page->getWidth() + 0.5);
+      paperHeight = (int)(page->getHeight() + 0.5);
+    } else {
+      paperWidth = 1;
+      paperHeight = 1;
+    }
+    imgLLX = imgLLY = 0;
+    imgURX = paperWidth;
+    imgURY = paperHeight;
+  }
+  manualCtrl = manualCtrlA;
+  if (mode == psModeForm) {
+    lastPage = firstPage;
+  }
+  processColors = 0;
+  inType3Char = gFalse;
+
+#if OPI_SUPPORT
+  // initialize OPI nesting levels
+  opi13Nest = 0;
+  opi20Nest = 0;
+#endif
+
+  tx0 = ty0 = 0;
+  xScale0 = yScale0 = 1;
+  rotate0 = 0;
+  clipLLX0 = clipLLY0 = 0;
+  clipURX0 = clipURY0 = -1;
+
   // initialize fontIDs, fontFileIDs, and fontFileNames lists
   fontIDSize = 64;
   fontIDLen = 0;
   // initialize fontIDs, fontFileIDs, and fontFileNames lists
   fontIDSize = 64;
   fontIDLen = 0;
@@ -565,104 +809,211 @@ PSOutputDev::PSOutputDev(char *fileName, XRef *xrefA, Catalog *catalog,
   fontFileNameSize = 64;
   fontFileNameLen = 0;
   fontFileNames = (GString **)gmalloc(fontFileNameSize * sizeof(GString *));
   fontFileNameSize = 64;
   fontFileNameLen = 0;
   fontFileNames = (GString **)gmalloc(fontFileNameSize * sizeof(GString *));
+  nextTrueTypeNum = 0;
   font16EncLen = 0;
   font16EncSize = 0;
 
   font16EncLen = 0;
   font16EncSize = 0;
 
+  xobjStack = new GList();
+  numSaves = 0;
+
   // initialize embedded font resource comment list
   embFontList = new GString();
 
   // initialize embedded font resource comment list
   embFontList = new GString();
 
-  // write header
+  if (!manualCtrl) {
+    // this check is needed in case the document has zero pages
+    if (firstPage > 0 && firstPage <= catalog->getNumPages()) {
+      writeHeader(firstPage, lastPage,
+                 catalog->getPage(firstPage)->getBox(),
+                 catalog->getPage(firstPage)->getCropBox());
+    } else {
+      box = new PDFRectangle(0, 0, 1, 1);
+      writeHeader(firstPage, lastPage, box, box);
+      delete box;
+    }
+    if (mode != psModeForm) {
+      writePS("%%BeginProlog\n");
+    }
+    writeXpdfProcset();
+    if (mode != psModeForm) {
+      writePS("%%EndProlog\n");
+      writePS("%%BeginSetup\n");
+    }
+    writeDocSetup(catalog, firstPage, lastPage);
+    if (mode != psModeForm) {
+      writePS("%%EndSetup\n");
+    }
+  }
+
+  // initialize sequential page number
+  seqPage = 1;
+}
+
+PSOutputDev::~PSOutputDev() {
+  PSOutCustomColor *cc;
+  int i;
+
+  if (ok) {
+    if (!manualCtrl) {
+      writePS("%%Trailer\n");
+      writeTrailer();
+      if (mode != psModeForm) {
+       writePS("%%EOF\n");
+      }
+    }
+    if (fileType == psFile) {
+#ifdef MACOS
+      ICS_MapRefNumAndAssign((short)((FILE *)outputStream)->handle);
+#endif
+      fclose((FILE *)outputStream);
+    }
+#ifdef HAVE_POPEN
+    else if (fileType == psPipe) {
+      pclose((FILE *)outputStream);
+#ifndef WIN32
+      signal(SIGPIPE, (SignalFunc)SIG_DFL);
+#endif
+    }
+#endif
+  }
+  if (embFontList) {
+    delete embFontList;
+  }
+  if (fontIDs) {
+    gfree(fontIDs);
+  }
+  if (fontFileIDs) {
+    gfree(fontFileIDs);
+  }
+  if (fontFileNames) {
+    for (i = 0; i < fontFileNameLen; ++i) {
+      delete fontFileNames[i];
+    }
+    gfree(fontFileNames);
+  }
+  if (font16Enc) {
+    for (i = 0; i < font16EncLen; ++i) {
+      delete font16Enc[i].enc;
+    }
+    gfree(font16Enc);
+  }
+  if (xobjStack) {
+    delete xobjStack;
+  }
+  while (customColors) {
+    cc = customColors;
+    customColors = cc->next;
+    delete cc;
+  }
+}
+
+void PSOutputDev::writeHeader(int firstPage, int lastPage,
+                             PDFRectangle *mediaBox, PDFRectangle *cropBox) {
   switch (mode) {
   case psModePS:
   switch (mode) {
   case psModePS:
-    writePS("%%!PS-Adobe-3.0\n");
-    writePS("%%%%Creator: xpdf/pdftops %s\n", xpdfVersion);
-    writePS("%%%%LanguageLevel: %d\n",
-           (level == psLevel1 || level == psLevel1Sep) ? 1 :
-           (level == psLevel2 || level == psLevel2Sep) ? 2 : 3);
+    writePS("%!PS-Adobe-3.0\n");
+    writePSFmt("%%%%Creator: xpdf/pdftops %s\n", xpdfVersion);
+    writePSFmt("%%%%LanguageLevel: %d\n",
+              (level == psLevel1 || level == psLevel1Sep) ? 1 :
+              (level == psLevel2 || level == psLevel2Sep) ? 2 : 3);
     if (level == psLevel1Sep || level == psLevel2Sep || level == psLevel3Sep) {
     if (level == psLevel1Sep || level == psLevel2Sep || level == psLevel3Sep) {
-      writePS("%%%%DocumentProcessColors: (atend)\n");
-      writePS("%%%%DocumentCustomColors: (atend)\n");
-    }
-    writePS("%%%%DocumentSuppliedResources: (atend)\n");
-    writePS("%%%%DocumentMedia: plain %d %d 0 () ()\n",
-           paperWidth, paperHeight);
-    writePS("%%%%Pages: %d\n", lastPage - firstPage + 1);
-    writePS("%%%%EndComments\n");
-    writePS("%%%%BeginDefaults\n");
-    writePS("%%%%PageMedia: plain\n");
-    writePS("%%%%EndDefaults\n");
+      writePS("%%DocumentProcessColors: (atend)\n");
+      writePS("%%DocumentCustomColors: (atend)\n");
+    }
+    writePS("%%DocumentSuppliedResources: (atend)\n");
+    writePSFmt("%%%%DocumentMedia: plain %d %d 0 () ()\n",
+              paperWidth, paperHeight);
+    writePSFmt("%%%%BoundingBox: 0 0 %d %d\n", paperWidth, paperHeight);
+    writePSFmt("%%%%Pages: %d\n", lastPage - firstPage + 1);
+    writePS("%%EndComments\n");
+    writePS("%%BeginDefaults\n");
+    writePS("%%PageMedia: plain\n");
+    writePS("%%EndDefaults\n");
     break;
   case psModeEPS:
     break;
   case psModeEPS:
-    writePS("%%!PS-Adobe-3.0 EPSF-3.0\n");
-    writePS("%%%%Creator: xpdf/pdftops %s\n", xpdfVersion);
-    writePS("%%%%LanguageLevel: %d\n",
-           (level == psLevel1 || level == psLevel1Sep) ? 1 :
-           (level == psLevel2 || level == psLevel2Sep) ? 2 : 3);
+    writePS("%!PS-Adobe-3.0 EPSF-3.0\n");
+    writePSFmt("%%%%Creator: xpdf/pdftops %s\n", xpdfVersion);
+    writePSFmt("%%%%LanguageLevel: %d\n",
+              (level == psLevel1 || level == psLevel1Sep) ? 1 :
+              (level == psLevel2 || level == psLevel2Sep) ? 2 : 3);
     if (level == psLevel1Sep || level == psLevel2Sep || level == psLevel3Sep) {
     if (level == psLevel1Sep || level == psLevel2Sep || level == psLevel3Sep) {
-      writePS("%%%%DocumentProcessColors: (atend)\n");
-      writePS("%%%%DocumentCustomColors: (atend)\n");
-    }
-    page = catalog->getPage(firstPage);
-    box = page->getBox();
-    writePS("%%%%BoundingBox: %d %d %d %d\n",
-           (int)floor(box->x1), (int)floor(box->y1),
-           (int)ceil(box->x2), (int)ceil(box->y2));
-    if (floor(box->x1) != ceil(box->x1) ||
-       floor(box->y1) != ceil(box->y1) ||
-       floor(box->x2) != ceil(box->x2) ||
-       floor(box->y2) != ceil(box->y2)) {
-      writePS("%%%%HiResBoundingBox: %g %g %g %g\n",
-             box->x1, box->y1, box->x2, box->y2);
-    }
-    writePS("%%%%DocumentSuppliedResources: (atend)\n");
-    writePS("%%%%EndComments\n");
+      writePS("%%DocumentProcessColors: (atend)\n");
+      writePS("%%DocumentCustomColors: (atend)\n");
+    }
+    writePSFmt("%%%%BoundingBox: %d %d %d %d\n",
+              (int)floor(cropBox->x1), (int)floor(cropBox->y1),
+              (int)ceil(cropBox->x2), (int)ceil(cropBox->y2));
+    if (floor(cropBox->x1) != ceil(cropBox->x1) ||
+       floor(cropBox->y1) != ceil(cropBox->y1) ||
+       floor(cropBox->x2) != ceil(cropBox->x2) ||
+       floor(cropBox->y2) != ceil(cropBox->y2)) {
+      writePSFmt("%%%%HiResBoundingBox: %g %g %g %g\n",
+                cropBox->x1, cropBox->y1, cropBox->x2, cropBox->y2);
+    }
+    writePS("%%DocumentSuppliedResources: (atend)\n");
+    writePS("%%EndComments\n");
     break;
   case psModeForm:
     break;
   case psModeForm:
-    writePS("%%!PS-Adobe-3.0 Resource-Form\n");
-    writePS("%%%%Creator: xpdf/pdftops %s\n", xpdfVersion);
-    writePS("%%%%LanguageLevel: %d\n",
-           (level == psLevel1 || level == psLevel1Sep) ? 1 :
-           (level == psLevel2 || level == psLevel2Sep) ? 2 : 3);
+    writePS("%!PS-Adobe-3.0 Resource-Form\n");
+    writePSFmt("%%%%Creator: xpdf/pdftops %s\n", xpdfVersion);
+    writePSFmt("%%%%LanguageLevel: %d\n",
+              (level == psLevel1 || level == psLevel1Sep) ? 1 :
+              (level == psLevel2 || level == psLevel2Sep) ? 2 : 3);
     if (level == psLevel1Sep || level == psLevel2Sep || level == psLevel3Sep) {
     if (level == psLevel1Sep || level == psLevel2Sep || level == psLevel3Sep) {
-      writePS("%%%%DocumentProcessColors: (atend)\n");
-      writePS("%%%%DocumentCustomColors: (atend)\n");
+      writePS("%%DocumentProcessColors: (atend)\n");
+      writePS("%%DocumentCustomColors: (atend)\n");
     }
     }
-    writePS("%%%%DocumentSuppliedResources: (atend)\n");
-    writePS("%%%%EndComments\n");
-    page = catalog->getPage(firstPage);
-    box = page->getBox();
+    writePS("%%DocumentSuppliedResources: (atend)\n");
+    writePS("%%EndComments\n");
     writePS("32 dict dup begin\n");
     writePS("32 dict dup begin\n");
-    writePS("/BBox [%d %d %d %d] def\n",
-           (int)box->x1, (int)box->y1, (int)box->x2, (int)box->y2);
+    writePSFmt("/BBox [%d %d %d %d] def\n",
+              (int)floor(mediaBox->x1), (int)floor(mediaBox->y1),
+              (int)ceil(mediaBox->x2), (int)ceil(mediaBox->y2));
     writePS("/FormType 1 def\n");
     writePS("/Matrix [1 0 0 1 0 0] def\n");
     break;
   }
     writePS("/FormType 1 def\n");
     writePS("/Matrix [1 0 0 1 0 0] def\n");
     break;
   }
+}
 
 
-  // write prolog
-  if (mode != psModeForm) {
-    writePS("%%%%BeginProlog\n");
-  }
-  writePS("%%%%BeginResource: procset xpdf %s 0\n", xpdfVersion);
+void PSOutputDev::writeXpdfProcset() {
+  char prologLevel;
+  char **p;
+
+  writePSFmt("%%%%BeginResource: procset xpdf %s 0\n", xpdfVersion);
+  prologLevel = 'a';
   for (p = prolog; *p; ++p) {
   for (p = prolog; *p; ++p) {
-    writePS("%s\n", *p);
+    if ((*p)[0] == '~' && (*p)[1] == '1') {
+      prologLevel = '1';
+    } else if ((*p)[0] == '~' && (*p)[1] == '2') {
+      prologLevel = '2';
+    } else if ((*p)[0] == '~' && (*p)[1] == 'a') {
+      prologLevel = 'a';
+    } else if (prologLevel == 'a' ||
+              (prologLevel == '1' && level < psLevel2) ||
+              (prologLevel == '2' && level >= psLevel2)) {
+      writePSFmt("%s\n", *p);
+    }
   }
   }
-  writePS("%%%%EndResource\n");
+  writePS("%%EndResource\n");
+
   if (level >= psLevel3) {
     for (p = cmapProlog; *p; ++p) {
   if (level >= psLevel3) {
     for (p = cmapProlog; *p; ++p) {
-      writePS("%s\n", *p);
+      writePSFmt("%s\n", *p);
     }
   }
     }
   }
-  if (mode != psModeForm) {
-    writePS("%%%%EndProlog\n");
-  }
+}
+
+void PSOutputDev::writeDocSetup(Catalog *catalog,
+                               int firstPage, int lastPage) {
+  Page *page;
+  Dict *resDict;
+  Annots *annots;
+  Object obj1, obj2;
+  int pg, i;
 
 
-  // set up fonts and images
   if (mode == psModeForm) {
     // swap the form and xpdf dicts
     writePS("xpdf end begin dup begin\n");
   } else {
   if (mode == psModeForm) {
     // swap the form and xpdf dicts
     writePS("xpdf end begin dup begin\n");
   } else {
-    writePS("%%%%BeginSetup\n");
     writePS("xpdf begin\n");
   }
   for (pg = firstPage; pg <= lastPage; ++pg) {
     writePS("xpdf begin\n");
   }
   for (pg = firstPage; pg <= lastPage; ++pg) {
@@ -685,110 +1036,69 @@ PSOutputDev::PSOutputDev(char *fileName, XRef *xrefA, Catalog *catalog,
     delete annots;
   }
   if (mode != psModeForm) {
     delete annots;
   }
   if (mode != psModeForm) {
-    if (mode != psModeEPS) {
-      writePS("%d %d %s pdfSetup\n",
-             paperWidth, paperHeight,
-             globalParams->getPSDuplex() ? "true" : "false");
+    if (mode != psModeEPS && !manualCtrl) {
+      writePSFmt("%d %d %s pdfSetup\n",
+                paperWidth, paperHeight,
+                globalParams->getPSDuplex() ? "true" : "false");
     }
 #if OPI_SUPPORT
     if (globalParams->getPSOPI()) {
       writePS("/opiMatrix matrix currentmatrix def\n");
     }
 #endif
     }
 #if OPI_SUPPORT
     if (globalParams->getPSOPI()) {
       writePS("/opiMatrix matrix currentmatrix def\n");
     }
 #endif
-    writePS("%%%%EndSetup\n");
   }
   }
+}
 
 
-  // initialize sequential page number
-  seqPage = 1;
+void PSOutputDev::writePageTrailer() {
+  if (mode != psModeForm) {
+    writePS("pdfEndPage\n");
+  }
 }
 
 }
 
-PSOutputDev::~PSOutputDev() {
+void PSOutputDev::writeTrailer() {
   PSOutCustomColor *cc;
   PSOutCustomColor *cc;
-  int i;
 
 
-  if (f) {
-    if (mode == psModeForm) {
-      writePS("/Foo exch /Form defineresource pop\n");
-    } else {
-      writePS("%%%%Trailer\n");
-      writePS("end\n");
-      writePS("%%%%DocumentSuppliedResources:\n");
-      writePS("%s", embFontList->getCString());
-      if (level == psLevel1Sep || level == psLevel2Sep ||
-         level == psLevel3Sep) {
-         writePS("%%%%DocumentProcessColors:");
-         if (processColors & psProcessCyan) {
-          writePS(" Cyan");
-        }
-         if (processColors & psProcessMagenta) {
-          writePS(" Magenta");
-        }
-         if (processColors & psProcessYellow) {
-          writePS(" Yellow");
-        }
-         if (processColors & psProcessBlack) {
-          writePS(" Black");
-        }
-         writePS("\n");
-         writePS("%%%%DocumentCustomColors:");
-        for (cc = customColors; cc; cc = cc->next) {
-          writePS(" (%s)", cc->name->getCString());
+  if (mode == psModeForm) {
+    writePS("/Foo exch /Form defineresource pop\n");
+  } else {
+    writePS("end\n");
+    writePS("%%DocumentSuppliedResources:\n");
+    writePS(embFontList->getCString());
+    if (level == psLevel1Sep || level == psLevel2Sep ||
+       level == psLevel3Sep) {
+      writePS("%%DocumentProcessColors:");
+      if (processColors & psProcessCyan) {
+       writePS(" Cyan");
         }
         }
-         writePS("\n");
-         writePS("%%%%CMYKCustomColor:\n");
-        for (cc = customColors; cc; cc = cc->next) {
-          writePS("%%%%+ %g %g %g %g (%s)\n",
+      if (processColors & psProcessMagenta) {
+       writePS(" Magenta");
+      }
+      if (processColors & psProcessYellow) {
+       writePS(" Yellow");
+      }
+      if (processColors & psProcessBlack) {
+       writePS(" Black");
+      }
+      writePS("\n");
+      writePS("%%DocumentCustomColors:");
+      for (cc = customColors; cc; cc = cc->next) {
+       writePSFmt(" (%s)", cc->name->getCString());
+      }
+      writePS("\n");
+      writePS("%%CMYKCustomColor:\n");
+      for (cc = customColors; cc; cc = cc->next) {
+       writePSFmt("%%%%+ %g %g %g %g (%s)\n",
                   cc->c, cc->m, cc->y, cc->k, cc->name->getCString());
                   cc->c, cc->m, cc->y, cc->k, cc->name->getCString());
-        }
       }
       }
-      writePS("%%%%EOF\n");
     }
     }
-    if (fileType == psFile) {
-#ifdef MACOS
-      ICS_MapRefNumAndAssign((short)f->handle);
-#endif
-      fclose(f);
-    }
-#ifdef HAVE_POPEN
-    else if (fileType == psPipe) {
-      pclose(f);
-#ifndef WIN32
-      signal(SIGPIPE, (SignalFunc)SIG_DFL);
-#endif
-    }
-#endif
-  }
-  if (embFontList) {
-    delete embFontList;
-  }
-  if (fontIDs) {
-    gfree(fontIDs);
-  }
-  if (fontFileIDs) {
-    gfree(fontFileIDs);
-  }
-  if (fontFileNames) {
-    for (i = 0; i < fontFileNameLen; ++i) {
-      delete fontFileNames[i];
-    }
-    gfree(fontFileNames);
-  }
-  if (font16Enc) {
-    for (i = 0; i < font16EncLen; ++i) {
-      delete font16Enc[i].enc;
-    }
-    gfree(font16Enc);
-  }
-  while (customColors) {
-    cc = customColors;
-    customColors = cc->next;
-    delete cc;
   }
 }
 
 void PSOutputDev::setupResources(Dict *resDict) {
   }
 }
 
 void PSOutputDev::setupResources(Dict *resDict) {
-  Object xObjDict, xObj, resObj;
-  int i;
+  Object xObjDict, xObjRef, xObj, resObj;
+  Ref ref0, ref1;
+  GBool skip;
+  int i, j;
 
   setupFonts(resDict);
   setupImages(resDict);
 
   setupFonts(resDict);
   setupImages(resDict);
@@ -796,45 +1106,82 @@ void PSOutputDev::setupResources(Dict *resDict) {
   resDict->lookup("XObject", &xObjDict);
   if (xObjDict.isDict()) {
     for (i = 0; i < xObjDict.dictGetLength(); ++i) {
   resDict->lookup("XObject", &xObjDict);
   if (xObjDict.isDict()) {
     for (i = 0; i < xObjDict.dictGetLength(); ++i) {
-      xObjDict.dictGetVal(i, &xObj);
-      if (xObj.isStream()) {
-       xObj.streamGetDict()->lookup("Resources", &resObj);
-       if (resObj.isDict()) {
-         setupResources(resObj.getDict());
+
+      // avoid infinite recursion on XObjects
+      skip = gFalse;
+      if ((xObjDict.dictGetValNF(i, &xObjRef)->isRef())) {
+       ref0 = xObjRef.getRef();
+       for (j = 0; j < xobjStack->getLength(); ++j) {
+         ref1 = *(Ref *)xobjStack->get(j);
+         if (ref1.num == ref0.num && ref1.gen == ref0.gen) {
+           skip = gTrue;
+           break;
+         }
+       }
+       if (!skip) {
+         xobjStack->append(&ref0);
        }
        }
-       resObj.free();
       }
       }
-      xObj.free();
+      if (!skip) {
+
+       // process the XObject's resource dictionary
+       xObjDict.dictGetVal(i, &xObj);
+       if (xObj.isStream()) {
+         xObj.streamGetDict()->lookup("Resources", &resObj);
+         if (resObj.isDict()) {
+           setupResources(resObj.getDict());
+         }
+         resObj.free();
+       }
+       xObj.free();
+      }
+
+      if (xObjRef.isRef() && !skip) {
+       xobjStack->del(xobjStack->getLength() - 1);
+      }
+      xObjRef.free();
     }
   }
   xObjDict.free();
 }
 
 void PSOutputDev::setupFonts(Dict *resDict) {
     }
   }
   xObjDict.free();
 }
 
 void PSOutputDev::setupFonts(Dict *resDict) {
-  Object fontDict;
+  Object obj1, obj2;
+  Ref r;
   GfxFontDict *gfxFontDict;
   GfxFont *font;
   int i;
 
   GfxFontDict *gfxFontDict;
   GfxFont *font;
   int i;
 
-  resDict->lookup("Font", &fontDict);
-  if (fontDict.isDict()) {
-    gfxFontDict = new GfxFontDict(xref, fontDict.getDict());
+  gfxFontDict = NULL;
+  resDict->lookupNF("Font", &obj1);
+  if (obj1.isRef()) {
+    obj1.fetch(xref, &obj2);
+    if (obj2.isDict()) {
+      r = obj1.getRef();
+      gfxFontDict = new GfxFontDict(xref, &r, obj2.getDict());
+    }
+    obj2.free();
+  } else if (obj1.isDict()) {
+    gfxFontDict = new GfxFontDict(xref, NULL, obj1.getDict());
+  }
+  if (gfxFontDict) {
     for (i = 0; i < gfxFontDict->getNumFonts(); ++i) {
     for (i = 0; i < gfxFontDict->getNumFonts(); ++i) {
-      font = gfxFontDict->getFont(i);
-      setupFont(font, resDict);
+      if ((font = gfxFontDict->getFont(i))) {
+       setupFont(font, resDict);
+      }
     }
     delete gfxFontDict;
   }
     }
     delete gfxFontDict;
   }
-  fontDict.free();
+  obj1.free();
 }
 
 void PSOutputDev::setupFont(GfxFont *font, Dict *parentResDict) {
   Ref fontFileID;
   GString *name;
   PSFontParam *fontParam;
 }
 
 void PSOutputDev::setupFont(GfxFont *font, Dict *parentResDict) {
   Ref fontFileID;
   GString *name;
   PSFontParam *fontParam;
-  GString *psNameStr;
-  char *psName;
-  char type3Name[64];
+  GString *psName;
+  char type3Name[64], buf[16];
+  GBool subst;
   UnicodeMap *uMap;
   char *charName;
   double xs, ys;
   UnicodeMap *uMap;
   char *charName;
   double xs, ys;
@@ -859,27 +1206,25 @@ void PSOutputDev::setupFont(GfxFont *font, Dict *parentResDict) {
   fontIDs[fontIDLen++] = *font->getID();
 
   xs = ys = 1;
   fontIDs[fontIDLen++] = *font->getID();
 
   xs = ys = 1;
-  psNameStr = NULL;
+  subst = gFalse;
 
   // check for resident 8-bit font
   if (font->getName() &&
       (fontParam = globalParams->getPSFont(font->getName()))) {
 
   // check for resident 8-bit font
   if (font->getName() &&
       (fontParam = globalParams->getPSFont(font->getName()))) {
-    psName = fontParam->psFontName->getCString();
+    psName = new GString(fontParam->psFontName->getCString());
 
   // check for embedded Type 1 font
   } else if (globalParams->getPSEmbedType1() &&
             font->getType() == fontType1 &&
             font->getEmbeddedFontID(&fontFileID)) {
 
   // check for embedded Type 1 font
   } else if (globalParams->getPSEmbedType1() &&
             font->getType() == fontType1 &&
             font->getEmbeddedFontID(&fontFileID)) {
-    psNameStr = filterPSName(font->getEmbeddedFontName());
-    psName = psNameStr->getCString();
+    psName = filterPSName(font->getEmbeddedFontName());
     setupEmbeddedType1Font(&fontFileID, psName);
 
   // check for embedded Type 1C font
   } else if (globalParams->getPSEmbedType1() &&
             font->getType() == fontType1C &&
             font->getEmbeddedFontID(&fontFileID)) {
     setupEmbeddedType1Font(&fontFileID, psName);
 
   // check for embedded Type 1C font
   } else if (globalParams->getPSEmbedType1() &&
             font->getType() == fontType1C &&
             font->getEmbeddedFontID(&fontFileID)) {
-    psNameStr = filterPSName(font->getEmbeddedFontName());
-    psName = psNameStr->getCString();
+    psName = filterPSName(font->getEmbeddedFontName());
     setupEmbeddedType1CFont(font, &fontFileID, psName);
 
   // check for external Type 1 font file
     setupEmbeddedType1CFont(font, &fontFileID, psName);
 
   // check for external Type 1 font file
@@ -887,55 +1232,52 @@ void PSOutputDev::setupFont(GfxFont *font, Dict *parentResDict) {
             font->getType() == fontType1 &&
             font->getExtFontFile()) {
     // this assumes that the PS font name matches the PDF font name
             font->getType() == fontType1 &&
             font->getExtFontFile()) {
     // this assumes that the PS font name matches the PDF font name
-    psName = font->getName()->getCString();
+    psName = font->getName()->copy();
     setupExternalType1Font(font->getExtFontFile(), psName);
 
   // check for embedded TrueType font
   } else if (globalParams->getPSEmbedTrueType() &&
             font->getType() == fontTrueType &&
             font->getEmbeddedFontID(&fontFileID)) {
     setupExternalType1Font(font->getExtFontFile(), psName);
 
   // check for embedded TrueType font
   } else if (globalParams->getPSEmbedTrueType() &&
             font->getType() == fontTrueType &&
             font->getEmbeddedFontID(&fontFileID)) {
-    psNameStr = filterPSName(font->getEmbeddedFontName());
-    psName = psNameStr->getCString();
+    psName = filterPSName(font->getEmbeddedFontName());
     setupEmbeddedTrueTypeFont(font, &fontFileID, psName);
 
   // check for external TrueType font file
   } else if (globalParams->getPSEmbedTrueType() &&
             font->getType() == fontTrueType &&
             font->getExtFontFile()) {
     setupEmbeddedTrueTypeFont(font, &fontFileID, psName);
 
   // check for external TrueType font file
   } else if (globalParams->getPSEmbedTrueType() &&
             font->getType() == fontTrueType &&
             font->getExtFontFile()) {
-    psNameStr = filterPSName(font->getName());
-    psName = psNameStr->getCString();
+    psName = filterPSName(font->getName());
     setupExternalTrueTypeFont(font, psName);
 
   // check for embedded CID PostScript font
   } else if (globalParams->getPSEmbedCIDPostScript() &&
             font->getType() == fontCIDType0C &&
             font->getEmbeddedFontID(&fontFileID)) {
     setupExternalTrueTypeFont(font, psName);
 
   // check for embedded CID PostScript font
   } else if (globalParams->getPSEmbedCIDPostScript() &&
             font->getType() == fontCIDType0C &&
             font->getEmbeddedFontID(&fontFileID)) {
-    psNameStr = filterPSName(font->getEmbeddedFontName());
-    psName = psNameStr->getCString();
+    psName = filterPSName(font->getEmbeddedFontName());
     setupEmbeddedCIDType0Font(font, &fontFileID, psName);
 
   // check for embedded CID TrueType font
   } else if (globalParams->getPSEmbedCIDTrueType() &&
             font->getType() == fontCIDType2 &&
             font->getEmbeddedFontID(&fontFileID)) {
     setupEmbeddedCIDType0Font(font, &fontFileID, psName);
 
   // check for embedded CID TrueType font
   } else if (globalParams->getPSEmbedCIDTrueType() &&
             font->getType() == fontCIDType2 &&
             font->getEmbeddedFontID(&fontFileID)) {
-    psNameStr = filterPSName(font->getEmbeddedFontName());
-    psName = psNameStr->getCString();
+    psName = filterPSName(font->getEmbeddedFontName());
     setupEmbeddedCIDTrueTypeFont(font, &fontFileID, psName);
 
   } else if (font->getType() == fontType3) {
     sprintf(type3Name, "T3_%d_%d",
            font->getID()->num, font->getID()->gen);
     setupEmbeddedCIDTrueTypeFont(font, &fontFileID, psName);
 
   } else if (font->getType() == fontType3) {
     sprintf(type3Name, "T3_%d_%d",
            font->getID()->num, font->getID()->gen);
-    psName = type3Name;
+    psName = new GString(type3Name);
     setupType3Font(font, psName, parentResDict);
 
   // do 8-bit font substitution
   } else if (!font->isCIDFont()) {
     setupType3Font(font, psName, parentResDict);
 
   // do 8-bit font substitution
   } else if (!font->isCIDFont()) {
+    subst = gTrue;
     name = font->getName();
     psName = NULL;
     if (name) {
       for (i = 0; psFonts[i]; ++i) {
        if (name->cmp(psFonts[i]) == 0) {
     name = font->getName();
     psName = NULL;
     if (name) {
       for (i = 0; psFonts[i]; ++i) {
        if (name->cmp(psFonts[i]) == 0) {
-         psName = psFonts[i];
+         psName = new GString(psFonts[i]);
          break;
        }
       }
          break;
        }
       }
@@ -954,7 +1296,7 @@ void PSOutputDev::setupFont(GfxFont *font, Dict *parentResDict) {
       if (font->isItalic()) {
        i += 1;
       }
       if (font->isItalic()) {
        i += 1;
       }
-      psName = psSubstFonts[i].psName;
+      psName = new GString(psSubstFonts[i].psName);
       for (code = 0; code < 256; ++code) {
        if ((charName = ((Gfx8BitFont *)font)->getCharName(code)) &&
            charName[0] == 'm' && charName[1] == '\0') {
       for (code = 0; code < 256; ++code) {
        if ((charName = ((Gfx8BitFont *)font)->getCharName(code)) &&
            charName[0] == 'm' && charName[1] == '\0') {
@@ -991,7 +1333,8 @@ void PSOutputDev::setupFont(GfxFont *font, Dict *parentResDict) {
                getPSFont16(font->getName(),
                            ((GfxCIDFont *)font)->getCollection(),
                            font->getWMode()))) {
                getPSFont16(font->getName(),
                            ((GfxCIDFont *)font)->getCollection(),
                            font->getWMode()))) {
-    psName = fontParam->psFontName->getCString();
+    subst = gTrue;
+    psName = fontParam->psFontName->copy();
     if (font16EncLen >= font16EncSize) {
       font16EncSize += 16;
       font16Enc = (PSFont16Enc *)grealloc(font16Enc,
     if (font16EncLen >= font16EncSize) {
       font16EncSize += 16;
       font16Enc = (PSFont16Enc *)grealloc(font16Enc,
@@ -1020,43 +1363,50 @@ void PSOutputDev::setupFont(GfxFont *font, Dict *parentResDict) {
   // generate PostScript code to set up the font
   if (font->isCIDFont()) {
     if (level == psLevel3 || level == psLevel3Sep) {
   // generate PostScript code to set up the font
   if (font->isCIDFont()) {
     if (level == psLevel3 || level == psLevel3Sep) {
-      writePS("/F%d_%d /%s %d pdfMakeFont16L3\n",
-             font->getID()->num, font->getID()->gen, psName,
-             font->getWMode());
+      writePSFmt("/F%d_%d /%s %d pdfMakeFont16L3\n",
+                font->getID()->num, font->getID()->gen, psName->getCString(),
+                font->getWMode());
     } else {
     } else {
-      writePS("/F%d_%d /%s %d pdfMakeFont16\n",
-             font->getID()->num, font->getID()->gen, psName,
-             font->getWMode());
+      writePSFmt("/F%d_%d /%s %d pdfMakeFont16\n",
+                font->getID()->num, font->getID()->gen, psName->getCString(),
+                font->getWMode());
     }
   } else {
     }
   } else {
-    writePS("/F%d_%d /%s %g %g\n",
-           font->getID()->num, font->getID()->gen, psName, xs, ys);
+    writePSFmt("/F%d_%d /%s %g %g\n",
+              font->getID()->num, font->getID()->gen, psName->getCString(),
+              xs, ys);
     for (i = 0; i < 256; i += 8) {
     for (i = 0; i < 256; i += 8) {
-      writePS((i == 0) ? "[ " : "  ");
+      writePSFmt((i == 0) ? "[ " : "  ");
       for (j = 0; j < 8; ++j) {
       for (j = 0; j < 8; ++j) {
-       charName = ((Gfx8BitFont *)font)->getCharName(i+j);
-       // this is a kludge for broken PDF files that encode char 32
-       // as .notdef
-       if (i+j == 32 && charName && !strcmp(charName, ".notdef")) {
-         charName = "space";
+       if (font->getType() == fontTrueType &&
+           !subst &&
+           !((Gfx8BitFont *)font)->getHasEncoding()) {
+         sprintf(buf, "c%02x", i+j);
+         charName = buf;
+       } else {
+         charName = ((Gfx8BitFont *)font)->getCharName(i+j);
+         // this is a kludge for broken PDF files that encode char 32
+         // as .notdef
+         if (i+j == 32 && charName && !strcmp(charName, ".notdef")) {
+           charName = "space";
+         }
        }
        }
-       writePS("/%s", charName ? charName : ".notdef");
+       writePS("/");
+       writePSName(charName ? charName : (char *)".notdef");
       }
       }
-      writePS((i == 256-8) ? "]\n" : "\n");
+      writePS((i == 256-8) ? (char *)"]\n" : (char *)"\n");
     }
     writePS("pdfMakeFont\n");
   }
 
     }
     writePS("pdfMakeFont\n");
   }
 
-  if (psNameStr) {
-    delete psNameStr;
-  }
+  delete psName;
 }
 
 }
 
-void PSOutputDev::setupEmbeddedType1Font(Ref *id, char *psName) {
+void PSOutputDev::setupEmbeddedType1Font(Ref *id, GString *psName) {
   static char hexChar[17] = "0123456789abcdef";
   static char hexChar[17] = "0123456789abcdef";
-  Object refObj, strObj, obj1, obj2;
+  Object refObj, strObj, obj1, obj2, obj3;
   Dict *dict;
   Dict *dict;
-  int length1, length2;
+  int length1, length2, length3;
   int c;
   int start[4];
   GBool binMode;
   int c;
   int start[4];
   GBool binMode;
@@ -1090,21 +1440,25 @@ void PSOutputDev::setupEmbeddedType1Font(Ref *id, char *psName) {
   }
   dict->lookup("Length1", &obj1);
   dict->lookup("Length2", &obj2);
   }
   dict->lookup("Length1", &obj1);
   dict->lookup("Length2", &obj2);
-  if (!obj1.isInt() || !obj2.isInt()) {
+  dict->lookup("Length3", &obj3);
+  if (!obj1.isInt() || !obj2.isInt() || !obj3.isInt()) {
     error(-1, "Missing length fields in embedded font stream dictionary");
     obj1.free();
     obj2.free();
     error(-1, "Missing length fields in embedded font stream dictionary");
     obj1.free();
     obj2.free();
+    obj3.free();
     goto err1;
   }
   length1 = obj1.getInt();
   length2 = obj2.getInt();
     goto err1;
   }
   length1 = obj1.getInt();
   length2 = obj2.getInt();
+  length3 = obj3.getInt();
   obj1.free();
   obj2.free();
   obj1.free();
   obj2.free();
+  obj3.free();
 
   // beginning comment
 
   // beginning comment
-  writePS("%%%%BeginResource: font %s\n", psName);
+  writePSFmt("%%%%BeginResource: font %s\n", psName->getCString());
   embFontList->append("%%+ font ");
   embFontList->append("%%+ font ");
-  embFontList->append(psName);
+  embFontList->append(psName->getCString());
   embFontList->append("\n");
 
   // copy ASCII portion of font
   embFontList->append("\n");
 
   // copy ASCII portion of font
@@ -1133,6 +1487,9 @@ void PSOutputDev::setupEmbeddedType1Font(Ref *id, char *psName) {
       writePSChar(hexChar[(start[i] >> 4) & 0x0f]);
       writePSChar(hexChar[start[i] & 0x0f]);
     }
       writePSChar(hexChar[(start[i] >> 4) & 0x0f]);
       writePSChar(hexChar[start[i] & 0x0f]);
     }
+    // if Length2 is incorrect (too small), font data gets chopped, so
+    // we take a few extra characters from the trailer just in case
+    length2 += length3 >= 8 ? 8 : length3;
     while (i < length2) {
       if ((c = strObj.streamGetChar()) == EOF) {
        break;
     while (i < length2) {
       if ((c = strObj.streamGetChar()) == EOF) {
        break;
@@ -1168,7 +1525,7 @@ void PSOutputDev::setupEmbeddedType1Font(Ref *id, char *psName) {
   writePS("cleartomark\n");
 
   // ending comment
   writePS("cleartomark\n");
 
   // ending comment
-  writePS("%%%%EndResource\n");
+  writePS("%%EndResource\n");
 
  err1:
   strObj.streamClose();
 
  err1:
   strObj.streamClose();
@@ -1177,7 +1534,7 @@ void PSOutputDev::setupEmbeddedType1Font(Ref *id, char *psName) {
 
 //~ This doesn't handle .pfb files or binary eexec data (which only
 //~ happens in pfb files?).
 
 //~ This doesn't handle .pfb files or binary eexec data (which only
 //~ happens in pfb files?).
-void PSOutputDev::setupExternalType1Font(GString *fileName, char *psName) {
+void PSOutputDev::setupExternalType1Font(GString *fileName, GString *psName) {
   FILE *fontFile;
   int c;
   int i;
   FILE *fontFile;
   int c;
   int i;
@@ -1198,9 +1555,9 @@ void PSOutputDev::setupExternalType1Font(GString *fileName, char *psName) {
   fontFileNames[fontFileNameLen++] = fileName->copy();
 
   // beginning comment
   fontFileNames[fontFileNameLen++] = fileName->copy();
 
   // beginning comment
-  writePS("%%%%BeginResource: font %s\n", psName);
+  writePSFmt("%%%%BeginResource: font %s\n", psName->getCString());
   embFontList->append("%%+ font ");
   embFontList->append("%%+ font ");
-  embFontList->append(psName);
+  embFontList->append(psName->getCString());
   embFontList->append("\n");
 
   // copy the font file
   embFontList->append("\n");
 
   // copy the font file
@@ -1214,14 +1571,14 @@ void PSOutputDev::setupExternalType1Font(GString *fileName, char *psName) {
   fclose(fontFile);
 
   // ending comment
   fclose(fontFile);
 
   // ending comment
-  writePS("%%%%EndResource\n");
+  writePS("%%EndResource\n");
 }
 
 void PSOutputDev::setupEmbeddedType1CFont(GfxFont *font, Ref *id,
 }
 
 void PSOutputDev::setupEmbeddedType1CFont(GfxFont *font, Ref *id,
-                                         char *psName) {
+                                         GString *psName) {
   char *fontBuf;
   int fontLen;
   char *fontBuf;
   int fontLen;
-  Type1CFontFile *t1cFile;
+  FoFiType1C *ffT1C;
   int i;
 
   // check if font is already embedded
   int i;
 
   // check if font is already embedded
@@ -1239,113 +1596,133 @@ void PSOutputDev::setupEmbeddedType1CFont(GfxFont *font, Ref *id,
   fontFileIDs[fontFileIDLen++] = *id;
 
   // beginning comment
   fontFileIDs[fontFileIDLen++] = *id;
 
   // beginning comment
-  writePS("%%%%BeginResource: font %s\n", psName);
+  writePSFmt("%%%%BeginResource: font %s\n", psName->getCString());
   embFontList->append("%%+ font ");
   embFontList->append("%%+ font ");
-  embFontList->append(psName);
+  embFontList->append(psName->getCString());
   embFontList->append("\n");
 
   // convert it to a Type 1 font
   fontBuf = font->readEmbFontFile(xref, &fontLen);
   embFontList->append("\n");
 
   // convert it to a Type 1 font
   fontBuf = font->readEmbFontFile(xref, &fontLen);
-  t1cFile = new Type1CFontFile(fontBuf, fontLen);
-  t1cFile->convertToType1(f);
-  delete t1cFile;
+  if ((ffT1C = FoFiType1C::make(fontBuf, fontLen))) {
+    ffT1C->convertToType1(NULL, gTrue, outputFunc, outputStream);
+    delete ffT1C;
+  }
   gfree(fontBuf);
 
   // ending comment
   gfree(fontBuf);
 
   // ending comment
-  writePS("%%%%EndResource\n");
+  writePS("%%EndResource\n");
 }
 
 void PSOutputDev::setupEmbeddedTrueTypeFont(GfxFont *font, Ref *id,
 }
 
 void PSOutputDev::setupEmbeddedTrueTypeFont(GfxFont *font, Ref *id,
-                                           char *psName) {
+                                           GString *psName) {
+  char unique[32];
   char *fontBuf;
   int fontLen;
   char *fontBuf;
   int fontLen;
-  TrueTypeFontFile *ttFile;
-  CharCodeToUnicode *ctu;
+  FoFiTrueType *ffTT;
+  Gushort *codeToGID;
   int i;
 
   // check if font is already embedded
   for (i = 0; i < fontFileIDLen; ++i) {
     if (fontFileIDs[i].num == id->num &&
   int i;
 
   // check if font is already embedded
   for (i = 0; i < fontFileIDLen; ++i) {
     if (fontFileIDs[i].num == id->num &&
-       fontFileIDs[i].gen == id->gen)
-      return;
+       fontFileIDs[i].gen == id->gen) {
+      sprintf(unique, "_%d", nextTrueTypeNum++);
+      psName->append(unique);
+      break;
+    }
   }
 
   // add entry to fontFileIDs list
   }
 
   // add entry to fontFileIDs list
-  if (fontFileIDLen >= fontFileIDSize) {
-    fontFileIDSize += 64;
-    fontFileIDs = (Ref *)grealloc(fontFileIDs, fontFileIDSize * sizeof(Ref));
+  if (i == fontFileIDLen) {
+    if (fontFileIDLen >= fontFileIDSize) {
+      fontFileIDSize += 64;
+      fontFileIDs = (Ref *)grealloc(fontFileIDs, fontFileIDSize * sizeof(Ref));
+    }
+    fontFileIDs[fontFileIDLen++] = *id;
   }
   }
-  fontFileIDs[fontFileIDLen++] = *id;
 
   // beginning comment
 
   // beginning comment
-  writePS("%%%%BeginResource: font %s\n", psName);
+  writePSFmt("%%%%BeginResource: font %s\n", psName->getCString());
   embFontList->append("%%+ font ");
   embFontList->append("%%+ font ");
-  embFontList->append(psName);
+  embFontList->append(psName->getCString());
   embFontList->append("\n");
 
   // convert it to a Type 42 font
   fontBuf = font->readEmbFontFile(xref, &fontLen);
   embFontList->append("\n");
 
   // convert it to a Type 42 font
   fontBuf = font->readEmbFontFile(xref, &fontLen);
-  ttFile = new TrueTypeFontFile(fontBuf, fontLen);
-  ctu = ((Gfx8BitFont *)font)->getToUnicode();
-  ttFile->convertToType42(psName, ((Gfx8BitFont *)font)->getEncoding(),
-                         ctu, ((Gfx8BitFont *)font)->getHasEncoding(), f);
-  ctu->decRefCnt();
-  delete ttFile;
+  if ((ffTT = FoFiTrueType::make(fontBuf, fontLen))) {
+    codeToGID = ((Gfx8BitFont *)font)->getCodeToGIDMap(ffTT);
+    ffTT->convertToType42(psName->getCString(),
+                         ((Gfx8BitFont *)font)->getHasEncoding()
+                           ? ((Gfx8BitFont *)font)->getEncoding()
+                           : (char **)NULL,
+                         codeToGID, outputFunc, outputStream);
+    gfree(codeToGID);
+    delete ffTT;
+  }
   gfree(fontBuf);
 
   // ending comment
   gfree(fontBuf);
 
   // ending comment
-  writePS("%%%%EndResource\n");
+  writePS("%%EndResource\n");
 }
 
 }
 
-void PSOutputDev::setupExternalTrueTypeFont(GfxFont *font, char *psName) {
+void PSOutputDev::setupExternalTrueTypeFont(GfxFont *font, GString *psName) {
+  char unique[32];
   GString *fileName;
   char *fontBuf;
   int fontLen;
   GString *fileName;
   char *fontBuf;
   int fontLen;
-  TrueTypeFontFile *ttFile;
-  CharCodeToUnicode *ctu;
+  FoFiTrueType *ffTT;
+  Gushort *codeToGID;
   int i;
 
   // check if font is already embedded
   fileName = font->getExtFontFile();
   for (i = 0; i < fontFileNameLen; ++i) {
     if (!fontFileNames[i]->cmp(fileName)) {
   int i;
 
   // check if font is already embedded
   fileName = font->getExtFontFile();
   for (i = 0; i < fontFileNameLen; ++i) {
     if (!fontFileNames[i]->cmp(fileName)) {
-      return;
+      sprintf(unique, "_%d", nextTrueTypeNum++);
+      psName->append(unique);
+      break;
     }
   }
 
   // add entry to fontFileNames list
     }
   }
 
   // add entry to fontFileNames list
-  if (fontFileNameLen >= fontFileNameSize) {
-    fontFileNameSize += 64;
-    fontFileNames = (GString **)grealloc(fontFileNames,
-                                        fontFileNameSize * sizeof(GString *));
+  if (i == fontFileNameLen) {
+    if (fontFileNameLen >= fontFileNameSize) {
+      fontFileNameSize += 64;
+      fontFileNames =
+       (GString **)grealloc(fontFileNames,
+                            fontFileNameSize * sizeof(GString *));
+    }
   }
   fontFileNames[fontFileNameLen++] = fileName->copy();
 
   // beginning comment
   }
   fontFileNames[fontFileNameLen++] = fileName->copy();
 
   // beginning comment
-  writePS("%%%%BeginResource: font %s\n", psName);
+  writePSFmt("%%%%BeginResource: font %s\n", psName->getCString());
   embFontList->append("%%+ font ");
   embFontList->append("%%+ font ");
-  embFontList->append(psName);
+  embFontList->append(psName->getCString());
   embFontList->append("\n");
 
   // convert it to a Type 42 font
   fontBuf = font->readExtFontFile(&fontLen);
   embFontList->append("\n");
 
   // convert it to a Type 42 font
   fontBuf = font->readExtFontFile(&fontLen);
-  ttFile = new TrueTypeFontFile(fontBuf, fontLen);
-  ctu = ((Gfx8BitFont *)font)->getToUnicode();
-  ttFile->convertToType42(psName, ((Gfx8BitFont *)font)->getEncoding(),
-                         ctu, ((Gfx8BitFont *)font)->getHasEncoding(), f);
-  ctu->decRefCnt();
-  delete ttFile;
+  if ((ffTT = FoFiTrueType::make(fontBuf, fontLen))) {
+    codeToGID = ((Gfx8BitFont *)font)->getCodeToGIDMap(ffTT);
+    ffTT->convertToType42(psName->getCString(),
+                         ((Gfx8BitFont *)font)->getHasEncoding()
+                           ? ((Gfx8BitFont *)font)->getEncoding()
+                           : (char **)NULL,
+                         codeToGID, outputFunc, outputStream);
+    delete ffTT;
+  }
   gfree(fontBuf);
 
   // ending comment
   gfree(fontBuf);
 
   // ending comment
-  writePS("%%%%EndResource\n");
+  writePS("%%EndResource\n");
 }
 
 void PSOutputDev::setupEmbeddedCIDType0Font(GfxFont *font, Ref *id,
 }
 
 void PSOutputDev::setupEmbeddedCIDType0Font(GfxFont *font, Ref *id,
-                                           char *psName) {
+                                           GString *psName) {
   char *fontBuf;
   int fontLen;
   char *fontBuf;
   int fontLen;
-  Type1CFontFile *t1cFile;
+  FoFiType1C *ffT1C;
   int i;
 
   // check if font is already embedded
   int i;
 
   // check if font is already embedded
@@ -1363,33 +1740,34 @@ void PSOutputDev::setupEmbeddedCIDType0Font(GfxFont *font, Ref *id,
   fontFileIDs[fontFileIDLen++] = *id;
 
   // beginning comment
   fontFileIDs[fontFileIDLen++] = *id;
 
   // beginning comment
-  writePS("%%%%BeginResource: font %s\n", psName);
+  writePSFmt("%%%%BeginResource: font %s\n", psName->getCString());
   embFontList->append("%%+ font ");
   embFontList->append("%%+ font ");
-  embFontList->append(psName);
+  embFontList->append(psName->getCString());
   embFontList->append("\n");
 
   // convert it to a Type 0 font
   fontBuf = font->readEmbFontFile(xref, &fontLen);
   embFontList->append("\n");
 
   // convert it to a Type 0 font
   fontBuf = font->readEmbFontFile(xref, &fontLen);
-  t1cFile = new Type1CFontFile(fontBuf, fontLen);
-  if (globalParams->getPSLevel() >= psLevel3) {
-    // Level 3: use a CID font
-    t1cFile->convertToCIDType0(psName, f);
-  } else {
-    // otherwise: use a non-CID composite font
-    t1cFile->convertToType0(psName, f);
+  if ((ffT1C = FoFiType1C::make(fontBuf, fontLen))) {
+    if (globalParams->getPSLevel() >= psLevel3) {
+      // Level 3: use a CID font
+      ffT1C->convertToCIDType0(psName->getCString(), outputFunc, outputStream);
+    } else {
+      // otherwise: use a non-CID composite font
+      ffT1C->convertToType0(psName->getCString(), outputFunc, outputStream);
+    }
+    delete ffT1C;
   }
   }
-  delete t1cFile;
   gfree(fontBuf);
 
   // ending comment
   gfree(fontBuf);
 
   // ending comment
-  writePS("%%%%EndResource\n");
+  writePS("%%EndResource\n");
 }
 
 void PSOutputDev::setupEmbeddedCIDTrueTypeFont(GfxFont *font, Ref *id,
 }
 
 void PSOutputDev::setupEmbeddedCIDTrueTypeFont(GfxFont *font, Ref *id,
-                                              char *psName) {
+                                              GString *psName) {
   char *fontBuf;
   int fontLen;
   char *fontBuf;
   int fontLen;
-  TrueTypeFontFile *ttFile;
+  FoFiTrueType *ffTT;
   int i;
 
   // check if font is already embedded
   int i;
 
   // check if font is already embedded
@@ -1407,31 +1785,36 @@ void PSOutputDev::setupEmbeddedCIDTrueTypeFont(GfxFont *font, Ref *id,
   fontFileIDs[fontFileIDLen++] = *id;
 
   // beginning comment
   fontFileIDs[fontFileIDLen++] = *id;
 
   // beginning comment
-  writePS("%%%%BeginResource: font %s\n", psName);
+  writePSFmt("%%%%BeginResource: font %s\n", psName->getCString());
   embFontList->append("%%+ font ");
   embFontList->append("%%+ font ");
-  embFontList->append(psName);
+  embFontList->append(psName->getCString());
   embFontList->append("\n");
 
   // convert it to a Type 0 font
   fontBuf = font->readEmbFontFile(xref, &fontLen);
   embFontList->append("\n");
 
   // convert it to a Type 0 font
   fontBuf = font->readEmbFontFile(xref, &fontLen);
-  ttFile = new TrueTypeFontFile(fontBuf, fontLen);
-  if (globalParams->getPSLevel() >= psLevel3) {
-    ttFile->convertToCIDType2(psName,
+  if ((ffTT = FoFiTrueType::make(fontBuf, fontLen))) {
+    if (globalParams->getPSLevel() >= psLevel3) {
+      // Level 3: use a CID font
+      ffTT->convertToCIDType2(psName->getCString(),
                              ((GfxCIDFont *)font)->getCIDToGID(),
                              ((GfxCIDFont *)font)->getCIDToGID(),
-                             ((GfxCIDFont *)font)->getCIDToGIDLen(), f);
-  } else {
-    // otherwise: use a non-CID composite font
-    ttFile->convertToType0(psName, ((GfxCIDFont *)font)->getCIDToGID(),
-                          ((GfxCIDFont *)font)->getCIDToGIDLen(), f);
+                             ((GfxCIDFont *)font)->getCIDToGIDLen(),
+                             outputFunc, outputStream);
+    } else {
+      // otherwise: use a non-CID composite font
+      ffTT->convertToType0(psName->getCString(),
+                          ((GfxCIDFont *)font)->getCIDToGID(),
+                          ((GfxCIDFont *)font)->getCIDToGIDLen(),
+                          outputFunc, outputStream);
+    }
+    delete ffTT;
   }
   }
-  delete ttFile;
   gfree(fontBuf);
 
   // ending comment
   gfree(fontBuf);
 
   // ending comment
-  writePS("%%%%EndResource\n");
+  writePS("%%EndResource\n");
 }
 
 }
 
-void PSOutputDev::setupType3Font(GfxFont *font, char *psName,
+void PSOutputDev::setupType3Font(GfxFont *font, GString *psName,
                                 Dict *parentResDict) {
   Dict *resDict;
   Dict *charProcs;
                                 Dict *parentResDict) {
   Dict *resDict;
   Dict *charProcs;
@@ -1439,30 +1822,33 @@ void PSOutputDev::setupType3Font(GfxFont *font, char *psName,
   Gfx *gfx;
   PDFRectangle box;
   double *m;
   Gfx *gfx;
   PDFRectangle box;
   double *m;
+  char buf[256];
   int i;
 
   // set up resources used by font
   if ((resDict = ((Gfx8BitFont *)font)->getResources())) {
   int i;
 
   // set up resources used by font
   if ((resDict = ((Gfx8BitFont *)font)->getResources())) {
+    inType3Char = gTrue;
     setupResources(resDict);
     setupResources(resDict);
+    inType3Char = gFalse;
   } else {
     resDict = parentResDict;
   }
 
   // beginning comment
   } else {
     resDict = parentResDict;
   }
 
   // beginning comment
-  writePS("%%%%BeginResource: font %s\n", psName);
+  writePSFmt("%%%%BeginResource: font %s\n", psName->getCString());
   embFontList->append("%%+ font ");
   embFontList->append("%%+ font ");
-  embFontList->append(psName);
+  embFontList->append(psName->getCString());
   embFontList->append("\n");
 
   // font dictionary
   embFontList->append("\n");
 
   // font dictionary
-  writePS("7 dict begin\n");
+  writePS("8 dict begin\n");
   writePS("/FontType 3 def\n");
   m = font->getFontMatrix();
   writePS("/FontType 3 def\n");
   m = font->getFontMatrix();
-  writePS("/FontMatrix [%g %g %g %g %g %g] def\n",
-         m[0], m[1], m[2], m[3], m[4], m[5]);
+  writePSFmt("/FontMatrix [%g %g %g %g %g %g] def\n",
+            m[0], m[1], m[2], m[3], m[4], m[5]);
   m = font->getFontBBox();
   m = font->getFontBBox();
-  writePS("/FontBBox [%g %g %g %g] def\n",
-         m[0], m[1], m[2], m[3]);
+  writePSFmt("/FontBBox [%g %g %g %g] def\n",
+            m[0], m[1], m[2], m[3]);
   writePS("/Encoding 256 array def\n");
   writePS("  0 1 255 { Encoding exch /.notdef put } for\n");
   writePS("/BuildGlyph {\n");
   writePS("/Encoding 256 array def\n");
   writePS("  0 1 255 { Encoding exch /.notdef put } for\n");
   writePS("/BuildGlyph {\n");
@@ -1475,7 +1861,7 @@ void PSOutputDev::setupType3Font(GfxFont *font, char *psName,
   writePS("  1 index /BuildGlyph get exec\n");
   writePS("} bind def\n");
   if ((charProcs = ((Gfx8BitFont *)font)->getCharProcs())) {
   writePS("  1 index /BuildGlyph get exec\n");
   writePS("} bind def\n");
   if ((charProcs = ((Gfx8BitFont *)font)->getCharProcs())) {
-    writePS("/CharProcs %d dict def\n", charProcs->getLength());
+    writePSFmt("/CharProcs %d dict def\n", charProcs->getLength());
     writePS("CharProcs begin\n");
     box.x1 = m[0];
     box.y1 = m[1];
     writePS("CharProcs begin\n");
     box.x1 = m[0];
     box.y1 = m[1];
@@ -1483,22 +1869,27 @@ void PSOutputDev::setupType3Font(GfxFont *font, char *psName,
     box.y2 = m[3];
     gfx = new Gfx(xref, this, resDict, &box, gFalse, NULL);
     inType3Char = gTrue;
     box.y2 = m[3];
     gfx = new Gfx(xref, this, resDict, &box, gFalse, NULL);
     inType3Char = gTrue;
+    t3Cacheable = gFalse;
     for (i = 0; i < charProcs->getLength(); ++i) {
     for (i = 0; i < charProcs->getLength(); ++i) {
-      writePS("/%s {\n", charProcs->getKey(i));
+      writePS("/");
+      writePSName(charProcs->getKey(i));
+      writePS(" {\n");
       gfx->display(charProcs->getVal(i, &charProc));
       charProc.free();
       if (t3String) {
        if (t3Cacheable) {
       gfx->display(charProcs->getVal(i, &charProc));
       charProc.free();
       if (t3String) {
        if (t3Cacheable) {
-         fprintf(f, "%g %g %g %g %g %g setcachedevice\n",
+         sprintf(buf, "%g %g %g %g %g %g setcachedevice\n",
                  t3WX, t3WY, t3LLX, t3LLY, t3URX, t3URY);
        } else {
                  t3WX, t3WY, t3LLX, t3LLY, t3URX, t3URY);
        } else {
-         fprintf(f, "%g %g setcharwidth\n", t3WX, t3WY);
+         sprintf(buf, "%g %g setcharwidth\n", t3WX, t3WY);
        }
        }
-       fputs(t3String->getCString(), f);
+       (*outputFunc)(outputStream, buf, strlen(buf));
+       (*outputFunc)(outputStream, t3String->getCString(),
+                     t3String->getLength());
        delete t3String;
        t3String = NULL;
       }
        delete t3String;
        t3String = NULL;
       }
-      fputs("Q\n", f);
+      (*outputFunc)(outputStream, "Q\n", 2);
       writePS("} def\n");
     }
     inType3Char = gFalse;
       writePS("} def\n");
     }
     inType3Char = gFalse;
@@ -1506,17 +1897,17 @@ void PSOutputDev::setupType3Font(GfxFont *font, char *psName,
     writePS("end\n");
   }
   writePS("currentdict end\n");
     writePS("end\n");
   }
   writePS("currentdict end\n");
-  writePS("/%s exch definefont pop\n", psName);
+  writePSFmt("/%s exch definefont pop\n", psName->getCString());
 
   // ending comment
 
   // ending comment
-  writePS("%%%%EndResource\n");
+  writePS("%%EndResource\n");
 }
 
 void PSOutputDev::setupImages(Dict *resDict) {
   Object xObjDict, xObj, xObjRef, subtypeObj;
   int i;
 
 }
 
 void PSOutputDev::setupImages(Dict *resDict) {
   Object xObjDict, xObj, xObjRef, subtypeObj;
   int i;
 
-  if (mode != psModeForm) {
+  if (!(mode == psModeForm || inType3Char)) {
     return;
   }
 
     return;
   }
 
@@ -1544,11 +1935,14 @@ void PSOutputDev::setupImages(Dict *resDict) {
 }
 
 void PSOutputDev::setupImage(Ref id, Stream *str) {
 }
 
 void PSOutputDev::setupImage(Ref id, Stream *str) {
+  GBool useASCIIHex;
   int c;
   int size, line, col, i;
 
   // construct an encoder stream
   int c;
   int size, line, col, i;
 
   // construct an encoder stream
-  if (globalParams->getPSASCIIHex()) {
+  useASCIIHex = level == psLevel1 || level == psLevel1Sep ||
+                globalParams->getPSASCIIHex();
+  if (useASCIIHex) {
     str = new ASCIIHexEncoder(str);
   } else {
     str = new ASCII85Encoder(str);
     str = new ASCIIHexEncoder(str);
   } else {
     str = new ASCII85Encoder(str);
@@ -1561,18 +1955,18 @@ void PSOutputDev::setupImage(Ref id, Stream *str) {
     do {
       c = str->getChar();
     } while (c == '\n' || c == '\r');
     do {
       c = str->getChar();
     } while (c == '\n' || c == '\r');
-    if (c == '~' || c == EOF) {
+    if (c == (useASCIIHex ? '>' : '~') || c == EOF) {
       break;
     }
     if (c == 'z') {
       ++col;
     } else {
       ++col;
       break;
     }
     if (c == 'z') {
       ++col;
     } else {
       ++col;
-      for (i = 1; i <= 4; ++i) {
+      for (i = 1; i <= (useASCIIHex ? 1 : 4); ++i) {
        do {
          c = str->getChar();
        } while (c == '\n' || c == '\r');
        do {
          c = str->getChar();
        } while (c == '\n' || c == '\r');
-       if (c == '~' || c == EOF) {
+       if (c == (useASCIIHex ? '>' : '~') || c == EOF) {
          break;
        }
        ++col;
          break;
        }
        ++col;
@@ -1582,19 +1976,20 @@ void PSOutputDev::setupImage(Ref id, Stream *str) {
       ++size;
       col = 0;
     }
       ++size;
       col = 0;
     }
-  } while (c != '~' && c != EOF);
+  } while (c != (useASCIIHex ? '>' : '~') && c != EOF);
   ++size;
   ++size;
-  writePS("%d array dup /ImData_%d_%d exch def\n", size, id.num, id.gen);
+  writePSFmt("%d array dup /ImData_%d_%d exch def\n", size, id.num, id.gen);
+  str->close();
 
   // write the data into the array
   str->reset();
   line = col = 0;
 
   // write the data into the array
   str->reset();
   line = col = 0;
-  writePS("dup 0 <~");
+  writePS((char *)(useASCIIHex ? "dup 0 <" : "dup 0 <~"));
   do {
     do {
       c = str->getChar();
     } while (c == '\n' || c == '\r');
   do {
     do {
       c = str->getChar();
     } while (c == '\n' || c == '\r');
-    if (c == '~' || c == EOF) {
+    if (c == (useASCIIHex ? '>' : '~') || c == EOF) {
       break;
     }
     if (c == 'z') {
       break;
     }
     if (c == 'z') {
@@ -1603,11 +1998,11 @@ void PSOutputDev::setupImage(Ref id, Stream *str) {
     } else {
       writePSChar(c);
       ++col;
     } else {
       writePSChar(c);
       ++col;
-      for (i = 1; i <= 4; ++i) {
+      for (i = 1; i <= (useASCIIHex ? 1 : 4); ++i) {
        do {
          c = str->getChar();
        } while (c == '\n' || c == '\r');
        do {
          c = str->getChar();
        } while (c == '\n' || c == '\r');
-       if (c == '~' || c == EOF) {
+       if (c == (useASCIIHex ? '>' : '~') || c == EOF) {
          break;
        }
        writePSChar(c);
          break;
        }
        writePSChar(c);
@@ -1619,76 +2014,97 @@ void PSOutputDev::setupImage(Ref id, Stream *str) {
     // chunks are 1 or 4 bytes each, so we have to stop at 232
     // but make it 225 just to be safe
     if (col > 225) {
     // chunks are 1 or 4 bytes each, so we have to stop at 232
     // but make it 225 just to be safe
     if (col > 225) {
-      writePS("~> put\n");
+      writePS((char *)(useASCIIHex ? "> put\n" : "~> put\n"));
       ++line;
       ++line;
-      writePS("dup %d <~", line);
+      writePSFmt((char *)(useASCIIHex ? "dup %d <" : "dup %d <~"), line);
       col = 0;
     }
       col = 0;
     }
-  } while (c != '~' && c != EOF);
-  writePS("~> put\n");
+  } while (c != (useASCIIHex ? '>' : '~') && c != EOF);
+  writePS((char *)(useASCIIHex ? "> put\n" : "~> put\n"));
   writePS("pop\n");
   writePS("pop\n");
+  str->close();
 
   delete str;
 }
 
 void PSOutputDev::startPage(int pageNum, GfxState *state) {
 
   delete str;
 }
 
 void PSOutputDev::startPage(int pageNum, GfxState *state) {
-  int x1, y1, x2, y2, width, height, t;
+  int x1, y1, x2, y2, width, height;
+  int imgWidth, imgHeight, imgWidth2, imgHeight2;
+
 
   switch (mode) {
 
   case psModePS:
 
   switch (mode) {
 
   case psModePS:
-    writePS("%%%%Page: %d %d\n", pageNum, seqPage);
-    writePS("%%%%BeginPageSetup\n");
+    writePSFmt("%%%%Page: %d %d\n", pageNum, seqPage);
+    writePS("%%BeginPageSetup\n");
 
     // rotate, translate, and scale page
 
     // rotate, translate, and scale page
+    imgWidth = imgURX - imgLLX;
+    imgHeight = imgURY - imgLLY;
     x1 = (int)(state->getX1() + 0.5);
     y1 = (int)(state->getY1() + 0.5);
     x2 = (int)(state->getX2() + 0.5);
     y2 = (int)(state->getY2() + 0.5);
     width = x2 - x1;
     height = y2 - y1;
     x1 = (int)(state->getX1() + 0.5);
     y1 = (int)(state->getY1() + 0.5);
     x2 = (int)(state->getX2() + 0.5);
     y2 = (int)(state->getY2() + 0.5);
     width = x2 - x1;
     height = y2 - y1;
-    if (width > height && width > paperWidth) {
-      landscape = gTrue;
-      writePS("%%%%PageOrientation: %s\n",
-             state->getCTM()[0] ? "Landscape" : "Portrait");
+    tx = ty = 0;
+    // portrait or landscape
+    if (width > height && width > imgWidth) {
+      rotate = 90;
+      writePSFmt("%%%%PageOrientation: %s\n",
+                state->getCTM()[0] ? "Landscape" : "Portrait");
       writePS("pdfStartPage\n");
       writePS("90 rotate\n");
       writePS("pdfStartPage\n");
       writePS("90 rotate\n");
-      tx = -x1;
-      ty = -(y1 + paperWidth);
-      t = width;
-      width = height;
-      height = t;
+      ty = -imgWidth;
+      imgWidth2 = imgHeight;
+      imgHeight2 = imgWidth;
     } else {
     } else {
-      landscape = gFalse;
-      writePS("%%%%PageOrientation: %s\n",
-             state->getCTM()[0] ? "Portrait" : "Landscape");
+      rotate = 0;
+      writePSFmt("%%%%PageOrientation: %s\n",
+                state->getCTM()[0] ? "Portrait" : "Landscape");
       writePS("pdfStartPage\n");
       writePS("pdfStartPage\n");
-      tx = -x1;
-      ty = -y1;
-    }
-    if (width < paperWidth) {
-      tx += (paperWidth - width) / 2;
-    }
-    if (height < paperHeight) {
-      ty += (paperHeight - height) / 2;
-    }
-    if (tx != 0 || ty != 0) {
-      writePS("%g %g translate\n", tx, ty);
-    }
-    if (width > paperWidth || height > paperHeight) {
-      xScale = (double)paperWidth / (double)width;
-      yScale = (double)paperHeight / (double)height;
+      imgWidth2 = imgWidth;
+      imgHeight2 = imgHeight;
+    }
+    // shrink or expand
+    if ((globalParams->getPSShrinkLarger() &&
+        (width > imgWidth2 || height > imgHeight2)) ||
+       (globalParams->getPSExpandSmaller() &&
+        (width < imgWidth2 && height < imgHeight2))) {
+      xScale = (double)imgWidth2 / (double)width;
+      yScale = (double)imgHeight2 / (double)height;
       if (yScale < xScale) {
        xScale = yScale;
       } else {
        yScale = xScale;
       }
       if (yScale < xScale) {
        xScale = yScale;
       } else {
        yScale = xScale;
       }
-      writePS("%0.4f %0.4f scale\n", xScale, xScale);
     } else {
       xScale = yScale = 1;
     }
     } else {
       xScale = yScale = 1;
     }
+    // deal with odd bounding boxes
+    tx -= xScale * x1;
+    ty -= yScale * y1;
+    // center
+    if (globalParams->getPSCenter()) {
+      tx += (imgWidth2 - xScale * width) / 2;
+      ty += (imgHeight2 - yScale * height) / 2;
+    }
+    tx += imgLLX + tx0;
+    ty += imgLLY + ty0;
+    xScale *= xScale0;
+    yScale *= yScale0;
+    if (tx != 0 || ty != 0) {
+      writePSFmt("%g %g translate\n", tx, ty);
+    }
+    if (xScale != 1 || yScale != 1) {
+      writePSFmt("%0.4f %0.4f scale\n", xScale, xScale);
+    }
+    if (clipLLX0 < clipURX0 && clipLLY0 < clipURY0) {
+      writePSFmt("%g %g %g %g re W\n",
+                clipLLX0, clipLLY0, clipURX0 - clipLLX0, clipURY0 - clipLLY0);
+    }
 
 
-    writePS("%%%%EndPageSetup\n");
+    writePS("%%EndPageSetup\n");
     ++seqPage;
     break;
 
     ++seqPage;
     break;
 
@@ -1696,7 +2112,7 @@ void PSOutputDev::startPage(int pageNum, GfxState *state) {
     writePS("pdfStartPage\n");
     tx = ty = 0;
     xScale = yScale = 1;
     writePS("pdfStartPage\n");
     tx = ty = 0;
     xScale = yScale = 1;
-    landscape = gFalse;
+    rotate = 0;
     break;
 
   case psModeForm:
     break;
 
   case psModeForm:
@@ -1705,35 +2121,48 @@ void PSOutputDev::startPage(int pageNum, GfxState *state) {
     writePS("pdfStartPage\n");
     tx = ty = 0;
     xScale = yScale = 1;
     writePS("pdfStartPage\n");
     tx = ty = 0;
     xScale = yScale = 1;
-    landscape = gFalse;
+    rotate = 0;
     break;
   }
     break;
   }
+
+  if (underlayCbk) {
+    (*underlayCbk)(this, underlayCbkData);
+  }
 }
 
 void PSOutputDev::endPage() {
 }
 
 void PSOutputDev::endPage() {
+  if (overlayCbk) {
+    (*overlayCbk)(this, overlayCbkData);
+  }
+
+
   if (mode == psModeForm) {
     writePS("pdfEndPage\n");
     writePS("end end\n");
     writePS("} def\n");
     writePS("end end\n");
   } else {
   if (mode == psModeForm) {
     writePS("pdfEndPage\n");
     writePS("end end\n");
     writePS("} def\n");
     writePS("end end\n");
   } else {
-    writePS("showpage\n");
-    writePS("%%%%PageTrailer\n");
-    writePS("pdfEndPage\n");
+    if (!manualCtrl) {
+      writePS("showpage\n");
+      writePS("%%PageTrailer\n");
+      writePageTrailer();
+    }
   }
 }
 
 void PSOutputDev::saveState(GfxState *state) {
   writePS("q\n");
   }
 }
 
 void PSOutputDev::saveState(GfxState *state) {
   writePS("q\n");
+  ++numSaves;
 }
 
 void PSOutputDev::restoreState(GfxState *state) {
   writePS("Q\n");
 }
 
 void PSOutputDev::restoreState(GfxState *state) {
   writePS("Q\n");
+  --numSaves;
 }
 
 void PSOutputDev::updateCTM(GfxState *state, double m11, double m12,
                            double m21, double m22, double m31, double m32) {
 }
 
 void PSOutputDev::updateCTM(GfxState *state, double m11, double m12,
                            double m21, double m22, double m31, double m32) {
-  writePS("[%g %g %g %g %g %g] cm\n", m11, m12, m21, m22, m31, m32);
+  writePSFmt("[%g %g %g %g %g %g] cm\n", m11, m12, m21, m22, m31, m32);
 }
 
 void PSOutputDev::updateLineDash(GfxState *state) {
 }
 
 void PSOutputDev::updateLineDash(GfxState *state) {
@@ -1744,28 +2173,28 @@ void PSOutputDev::updateLineDash(GfxState *state) {
   state->getLineDash(&dash, &length, &start);
   writePS("[");
   for (i = 0; i < length; ++i)
   state->getLineDash(&dash, &length, &start);
   writePS("[");
   for (i = 0; i < length; ++i)
-    writePS("%g%s", dash[i], (i == length-1) ? "" : " ");
-  writePS("] %g d\n", start);
+    writePSFmt("%g%s", dash[i], (i == length-1) ? "" : " ");
+  writePSFmt("] %g d\n", start);
 }
 
 void PSOutputDev::updateFlatness(GfxState *state) {
 }
 
 void PSOutputDev::updateFlatness(GfxState *state) {
-  writePS("%d i\n", state->getFlatness());
+  writePSFmt("%d i\n", state->getFlatness());
 }
 
 void PSOutputDev::updateLineJoin(GfxState *state) {
 }
 
 void PSOutputDev::updateLineJoin(GfxState *state) {
-  writePS("%d j\n", state->getLineJoin());
+  writePSFmt("%d j\n", state->getLineJoin());
 }
 
 void PSOutputDev::updateLineCap(GfxState *state) {
 }
 
 void PSOutputDev::updateLineCap(GfxState *state) {
-  writePS("%d J\n", state->getLineCap());
+  writePSFmt("%d J\n", state->getLineCap());
 }
 
 void PSOutputDev::updateMiterLimit(GfxState *state) {
 }
 
 void PSOutputDev::updateMiterLimit(GfxState *state) {
-  writePS("%g M\n", state->getMiterLimit());
+  writePSFmt("%g M\n", state->getMiterLimit());
 }
 
 void PSOutputDev::updateLineWidth(GfxState *state) {
 }
 
 void PSOutputDev::updateLineWidth(GfxState *state) {
-  writePS("%g w\n", state->getLineWidth());
+  writePSFmt("%g w\n", state->getLineWidth());
 }
 
 void PSOutputDev::updateFillColor(GfxState *state) {
 }
 
 void PSOutputDev::updateFillColor(GfxState *state) {
@@ -1778,23 +2207,24 @@ void PSOutputDev::updateFillColor(GfxState *state) {
   switch (level) {
   case psLevel1:
     state->getFillGray(&gray);
   switch (level) {
   case psLevel1:
     state->getFillGray(&gray);
-    writePS("%g g\n", gray);
+    writePSFmt("%g g\n", gray);
     break;
   case psLevel1Sep:
     state->getFillCMYK(&cmyk);
     break;
   case psLevel1Sep:
     state->getFillCMYK(&cmyk);
-    writePS("%g %g %g %g k\n", cmyk.c, cmyk.m, cmyk.y, cmyk.k);
+    writePSFmt("%g %g %g %g k\n", cmyk.c, cmyk.m, cmyk.y, cmyk.k);
+    addProcessColor(cmyk.c, cmyk.m, cmyk.y, cmyk.k);
     break;
   case psLevel2:
   case psLevel3:
     if (state->getFillColorSpace()->getMode() == csDeviceCMYK) {
       state->getFillCMYK(&cmyk);
     break;
   case psLevel2:
   case psLevel3:
     if (state->getFillColorSpace()->getMode() == csDeviceCMYK) {
       state->getFillCMYK(&cmyk);
-      writePS("%g %g %g %g k\n", cmyk.c, cmyk.m, cmyk.y, cmyk.k);
+      writePSFmt("%g %g %g %g k\n", cmyk.c, cmyk.m, cmyk.y, cmyk.k);
     } else {
       state->getFillRGB(&rgb);
       if (rgb.r == rgb.g && rgb.g == rgb.b) {
     } else {
       state->getFillRGB(&rgb);
       if (rgb.r == rgb.g && rgb.g == rgb.b) {
-       writePS("%g g\n", rgb.r);
+       writePSFmt("%g g\n", rgb.r);
       } else {
       } else {
-       writePS("%g %g %g rg\n", rgb.r, rgb.g, rgb.b);
+       writePSFmt("%g %g %g rg\n", rgb.r, rgb.g, rgb.b);
       }
     }
     break;
       }
     }
     break;
@@ -1804,14 +2234,14 @@ void PSOutputDev::updateFillColor(GfxState *state) {
       sepCS = (GfxSeparationColorSpace *)state->getFillColorSpace();
       color.c[0] = 1;
       sepCS->getCMYK(&color, &cmyk);
       sepCS = (GfxSeparationColorSpace *)state->getFillColorSpace();
       color.c[0] = 1;
       sepCS->getCMYK(&color, &cmyk);
-      writePS("%g %g %g %g %g (%s) ck\n",
-             state->getFillColor()->c[0],
-             cmyk.c, cmyk.m, cmyk.y, cmyk.k,
-             sepCS->getName()->getCString());
+      writePSFmt("%g %g %g %g %g (%s) ck\n",
+                state->getFillColor()->c[0],
+                cmyk.c, cmyk.m, cmyk.y, cmyk.k,
+                sepCS->getName()->getCString());
       addCustomColor(sepCS);
     } else {
       state->getFillCMYK(&cmyk);
       addCustomColor(sepCS);
     } else {
       state->getFillCMYK(&cmyk);
-      writePS("%g %g %g %g k\n", cmyk.c, cmyk.m, cmyk.y, cmyk.k);
+      writePSFmt("%g %g %g %g k\n", cmyk.c, cmyk.m, cmyk.y, cmyk.k);
       addProcessColor(cmyk.c, cmyk.m, cmyk.y, cmyk.k);
     }
     break;
       addProcessColor(cmyk.c, cmyk.m, cmyk.y, cmyk.k);
     }
     break;
@@ -1829,23 +2259,24 @@ void PSOutputDev::updateStrokeColor(GfxState *state) {
   switch (level) {
   case psLevel1:
     state->getStrokeGray(&gray);
   switch (level) {
   case psLevel1:
     state->getStrokeGray(&gray);
-    writePS("%g G\n", gray);
+    writePSFmt("%g G\n", gray);
     break;
   case psLevel1Sep:
     state->getStrokeCMYK(&cmyk);
     break;
   case psLevel1Sep:
     state->getStrokeCMYK(&cmyk);
-    writePS("%g %g %g %g K\n", cmyk.c, cmyk.m, cmyk.y, cmyk.k);
+    writePSFmt("%g %g %g %g K\n", cmyk.c, cmyk.m, cmyk.y, cmyk.k);
+    addProcessColor(cmyk.c, cmyk.m, cmyk.y, cmyk.k);
     break;
   case psLevel2:
   case psLevel3:
     if (state->getStrokeColorSpace()->getMode() == csDeviceCMYK) {
       state->getStrokeCMYK(&cmyk);
     break;
   case psLevel2:
   case psLevel3:
     if (state->getStrokeColorSpace()->getMode() == csDeviceCMYK) {
       state->getStrokeCMYK(&cmyk);
-      writePS("%g %g %g %g K\n", cmyk.c, cmyk.m, cmyk.y, cmyk.k);
+      writePSFmt("%g %g %g %g K\n", cmyk.c, cmyk.m, cmyk.y, cmyk.k);
     } else {
       state->getStrokeRGB(&rgb);
       if (rgb.r == rgb.g && rgb.g == rgb.b) {
     } else {
       state->getStrokeRGB(&rgb);
       if (rgb.r == rgb.g && rgb.g == rgb.b) {
-       writePS("%g G\n", rgb.r);
+       writePSFmt("%g G\n", rgb.r);
       } else {
       } else {
-       writePS("%g %g %g RG\n", rgb.r, rgb.g, rgb.b);
+       writePSFmt("%g %g %g RG\n", rgb.r, rgb.g, rgb.b);
       }
     }
     break;
       }
     }
     break;
@@ -1855,14 +2286,14 @@ void PSOutputDev::updateStrokeColor(GfxState *state) {
       sepCS = (GfxSeparationColorSpace *)state->getStrokeColorSpace();
       color.c[0] = 1;
       sepCS->getCMYK(&color, &cmyk);
       sepCS = (GfxSeparationColorSpace *)state->getStrokeColorSpace();
       color.c[0] = 1;
       sepCS->getCMYK(&color, &cmyk);
-      writePS("%g %g %g %g %g (%s) CK\n",
-             state->getStrokeColor()->c[0],
-             cmyk.c, cmyk.m, cmyk.y, cmyk.k,
-             sepCS->getName()->getCString());
+      writePSFmt("%g %g %g %g %g (%s) CK\n",
+                state->getStrokeColor()->c[0],
+                cmyk.c, cmyk.m, cmyk.y, cmyk.k,
+                sepCS->getName()->getCString());
       addCustomColor(sepCS);
     } else {
       state->getStrokeCMYK(&cmyk);
       addCustomColor(sepCS);
     } else {
       state->getStrokeCMYK(&cmyk);
-      writePS("%g %g %g %g K\n", cmyk.c, cmyk.m, cmyk.y, cmyk.k);
+      writePSFmt("%g %g %g %g K\n", cmyk.c, cmyk.m, cmyk.y, cmyk.k);
       addProcessColor(cmyk.c, cmyk.m, cmyk.y, cmyk.k);
     }
     break;
       addProcessColor(cmyk.c, cmyk.m, cmyk.y, cmyk.k);
     }
     break;
@@ -1905,9 +2336,9 @@ void PSOutputDev::addCustomColor(GfxSeparationColorSpace *sepCS) {
 
 void PSOutputDev::updateFont(GfxState *state) {
   if (state->getFont()) {
 
 void PSOutputDev::updateFont(GfxState *state) {
   if (state->getFont()) {
-    writePS("/F%d_%d %g Tf\n",
-           state->getFont()->getID()->num, state->getFont()->getID()->gen,
-           state->getFontSize());
+    writePSFmt("/F%d_%d %g Tf\n",
+              state->getFont()->getID()->num, state->getFont()->getID()->gen,
+              state->getFontSize());
   }
 }
 
   }
 }
 
@@ -1915,19 +2346,19 @@ void PSOutputDev::updateTextMat(GfxState *state) {
   double *mat;
 
   mat = state->getTextMat();
   double *mat;
 
   mat = state->getTextMat();
-  writePS("[%g %g %g %g %g %g] Tm\n",
-         mat[0], mat[1], mat[2], mat[3], mat[4], mat[5]);
+  writePSFmt("[%g %g %g %g %g %g] Tm\n",
+            mat[0], mat[1], mat[2], mat[3], mat[4], mat[5]);
 }
 
 void PSOutputDev::updateCharSpace(GfxState *state) {
 }
 
 void PSOutputDev::updateCharSpace(GfxState *state) {
-  writePS("%g Tc\n", state->getCharSpace());
+  writePSFmt("%g Tc\n", state->getCharSpace());
 }
 
 void PSOutputDev::updateRender(GfxState *state) {
   int rm;
 
   rm = state->getRender();
 }
 
 void PSOutputDev::updateRender(GfxState *state) {
   int rm;
 
   rm = state->getRender();
-  writePS("%d Tr\n", rm);
+  writePSFmt("%d Tr\n", rm);
   rm &= 3;
   if (rm != 0 && rm != 3) {
     t3Cacheable = gFalse;
   rm &= 3;
   if (rm != 0 && rm != 3) {
     t3Cacheable = gFalse;
@@ -1935,26 +2366,31 @@ void PSOutputDev::updateRender(GfxState *state) {
 }
 
 void PSOutputDev::updateRise(GfxState *state) {
 }
 
 void PSOutputDev::updateRise(GfxState *state) {
-  writePS("%g Ts\n", state->getRise());
+  writePSFmt("%g Ts\n", state->getRise());
 }
 
 void PSOutputDev::updateWordSpace(GfxState *state) {
 }
 
 void PSOutputDev::updateWordSpace(GfxState *state) {
-  writePS("%g Tw\n", state->getWordSpace());
+  writePSFmt("%g Tw\n", state->getWordSpace());
 }
 
 void PSOutputDev::updateHorizScaling(GfxState *state) {
 }
 
 void PSOutputDev::updateHorizScaling(GfxState *state) {
-  writePS("%g Tz\n", state->getHorizScaling());
+  double h;
+
+  if ((h = state->getHorizScaling()) < 0.01) {
+    h = 0.01;
+  }
+  writePSFmt("%g Tz\n", h);
 }
 
 void PSOutputDev::updateTextPos(GfxState *state) {
 }
 
 void PSOutputDev::updateTextPos(GfxState *state) {
-  writePS("%g %g Td\n", state->getLineX(), state->getLineY());
+  writePSFmt("%g %g Td\n", state->getLineX(), state->getLineY());
 }
 
 void PSOutputDev::updateTextShift(GfxState *state, double shift) {
   if (state->getFont()->getWMode()) {
 }
 
 void PSOutputDev::updateTextShift(GfxState *state, double shift) {
   if (state->getFont()->getWMode()) {
-    writePS("%g TJmV\n", shift);
+    writePSFmt("%g TJmV\n", shift);
   } else {
   } else {
-    writePS("%g TJm\n", shift);
+    writePSFmt("%g TJm\n", shift);
   }
 }
 
   }
 }
 
@@ -2010,14 +2446,14 @@ void PSOutputDev::doPath(GfxPath *path) {
       x3 = subpath->getX(3);
       y3 = subpath->getY(3);
       if (x0 == x1 && x2 == x3 && y0 == y3 && y1 == y2) {
       x3 = subpath->getX(3);
       y3 = subpath->getY(3);
       if (x0 == x1 && x2 == x3 && y0 == y3 && y1 == y2) {
-       writePS("%g %g %g %g re\n",
-               x0 < x2 ? x0 : x2, y0 < y1 ? y0 : y1,
-               fabs(x2 - x0), fabs(y1 - y0));
+       writePSFmt("%g %g %g %g re\n",
+                  x0 < x2 ? x0 : x2, y0 < y1 ? y0 : y1,
+                  fabs(x2 - x0), fabs(y1 - y0));
        return;
       } else if (x0 == x3 && x1 == x2 && y0 == y1 && y2 == y3) {
        return;
       } else if (x0 == x3 && x1 == x2 && y0 == y1 && y2 == y3) {
-       writePS("%g %g %g %g re\n",
-               x0 < x1 ? x0 : x1, y0 < y2 ? y0 : y2,
-               fabs(x1 - x0), fabs(y2 - y0));
+       writePSFmt("%g %g %g %g re\n",
+                  x0 < x1 ? x0 : x1, y0 < y2 ? y0 : y2,
+                  fabs(x1 - x0), fabs(y2 - y0));
        return;
       }
     }
        return;
       }
     }
@@ -2026,16 +2462,16 @@ void PSOutputDev::doPath(GfxPath *path) {
   for (i = 0; i < n; ++i) {
     subpath = path->getSubpath(i);
     m = subpath->getNumPoints();
   for (i = 0; i < n; ++i) {
     subpath = path->getSubpath(i);
     m = subpath->getNumPoints();
-    writePS("%g %g m\n", subpath->getX(0), subpath->getY(0));
+    writePSFmt("%g %g m\n", subpath->getX(0), subpath->getY(0));
     j = 1;
     while (j < m) {
       if (subpath->getCurve(j)) {
     j = 1;
     while (j < m) {
       if (subpath->getCurve(j)) {
-       writePS("%g %g %g %g %g %g c\n", subpath->getX(j), subpath->getY(j),
-               subpath->getX(j+1), subpath->getY(j+1),
-               subpath->getX(j+2), subpath->getY(j+2));
+       writePSFmt("%g %g %g %g %g %g c\n", subpath->getX(j), subpath->getY(j),
+                  subpath->getX(j+1), subpath->getY(j+1),
+                  subpath->getX(j+2), subpath->getY(j+2));
        j += 3;
       } else {
        j += 3;
       } else {
-       writePS("%g %g l\n", subpath->getX(j), subpath->getY(j));
+       writePSFmt("%g %g l\n", subpath->getX(j), subpath->getY(j));
        ++j;
       }
     }
        ++j;
       }
     }
@@ -2058,7 +2494,7 @@ void PSOutputDev::drawString(GfxState *state, GString *s) {
   int len, nChars, uLen, n, m, i, j;
 
   // check for invisible text -- this is used by Acrobat Capture
   int len, nChars, uLen, n, m, i, j;
 
   // check for invisible text -- this is used by Acrobat Capture
-  if ((state->getRender() & 3) == 3) {
+  if (state->getRender() == 3) {
     return;
   }
 
     return;
   }
 
@@ -2134,17 +2570,28 @@ void PSOutputDev::drawString(GfxState *state, GString *s) {
     writePSString(s2);
     if (font->isCIDFont()) {
       if (wMode) {
     writePSString(s2);
     if (font->isCIDFont()) {
       if (wMode) {
-       writePS(" %d %g Tj16V\n", nChars, dy);
+       writePSFmt(" %d %g Tj16V\n", nChars, dy);
       } else {
       } else {
-       writePS(" %d %g Tj16\n", nChars, dx);
+       writePSFmt(" %d %g Tj16\n", nChars, dx);
       }
     } else {
       }
     } else {
-      writePS(" %g Tj\n", dx);
+      writePSFmt(" %g Tj\n", dx);
     }
   }
   if (font->isCIDFont()) {
     delete s2;
   }
     }
   }
   if (font->isCIDFont()) {
     delete s2;
   }
+
+  if (state->getRender() & 4) {
+    haveTextClip = gTrue;
+  }
+}
+
+void PSOutputDev::endTextObject(GfxState *state) {
+  if (haveTextClip) {
+    writePS("Tclip\n");
+    haveTextClip = gFalse;
+  }
 }
 
 void PSOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str,
 }
 
 void PSOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str,
@@ -2154,7 +2601,7 @@ void PSOutputDev::drawImageMask(GfxState *state, Object *ref, Stream *str,
 
   len = height * ((width + 7) / 8);
   if (level == psLevel1 || level == psLevel1Sep) {
 
   len = height * ((width + 7) / 8);
   if (level == psLevel1 || level == psLevel1Sep) {
-    doImageL1(NULL, invert, inlineImg, str, width, height, len);
+    doImageL1(ref, NULL, invert, inlineImg, str, width, height, len);
   } else {
     doImageL2(ref, NULL, invert, inlineImg, str, width, height, len);
   }
   } else {
     doImageL2(ref, NULL, invert, inlineImg, str, width, height, len);
   }
@@ -2169,7 +2616,7 @@ void PSOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
                   colorMap->getBits() + 7) / 8);
   switch (level) {
   case psLevel1:
                   colorMap->getBits() + 7) / 8);
   switch (level) {
   case psLevel1:
-    doImageL1(colorMap, gFalse, inlineImg, str, width, height, len);
+    doImageL1(ref, colorMap, gFalse, inlineImg, str, width, height, len);
     break;
   case psLevel1Sep:
     //~ handle indexed, separation, ... color spaces
     break;
   case psLevel1Sep:
     //~ handle indexed, separation, ... color spaces
@@ -2185,70 +2632,113 @@ void PSOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
   t3Cacheable = gFalse;
 }
 
   t3Cacheable = gFalse;
 }
 
-void PSOutputDev::doImageL1(GfxImageColorMap *colorMap,
+void PSOutputDev::doImageL1(Object *ref, GfxImageColorMap *colorMap,
                            GBool invert, GBool inlineImg,
                            Stream *str, int width, int height, int len) {
   ImageStream *imgStr;
   Guchar pixBuf[gfxColorMaxComps];
   double gray;
                            GBool invert, GBool inlineImg,
                            Stream *str, int width, int height, int len) {
   ImageStream *imgStr;
   Guchar pixBuf[gfxColorMaxComps];
   double gray;
-  int x, y, i;
+  int col, x, y, c, i;
 
 
-  // width, height, matrix, bits per component
-  if (colorMap) {
-    writePS("%d %d 8 [%d 0 0 %d 0 %d] pdfIm1\n",
-           width, height,
-           width, -height, height);
+  if (inType3Char && !colorMap) {
+    if (inlineImg) {
+      // create an array
+      str = new FixedLengthEncoder(str, len);
+      str = new ASCIIHexEncoder(str);
+      str->reset();
+      col = 0;
+      writePS("[<");
+      do {
+       do {
+         c = str->getChar();
+       } while (c == '\n' || c == '\r');
+       if (c == '>' || c == EOF) {
+         break;
+       }
+       writePSChar(c);
+       ++col;
+       // each line is: "<...data...><eol>"
+       // so max data length = 255 - 4 = 251
+       // but make it 240 just to be safe
+       // chunks are 2 bytes each, so we need to stop on an even col number
+       if (col == 240) {
+         writePS(">\n<");
+         col = 0;
+       }
+      } while (c != '>' && c != EOF);
+      writePS(">]\n");
+      writePS("0\n");
+      str->close();
+      delete str;
+    } else {
+      // set up to use the array already created by setupImages()
+      writePSFmt("ImData_%d_%d 0\n", ref->getRefNum(), ref->getRefGen());
+    }
+  }
+
+  // image/imagemask command
+  if (inType3Char && !colorMap) {
+    writePSFmt("%d %d %s [%d 0 0 %d 0 %d] pdfImM1a\n",
+              width, height, invert ? "true" : "false",
+              width, -height, height);
+  } else if (colorMap) {
+    writePSFmt("%d %d 8 [%d 0 0 %d 0 %d] pdfIm1\n",
+              width, height,
+              width, -height, height);
   } else {
   } else {
-    writePS("%d %d %s [%d 0 0 %d 0 %d] pdfImM1\n",
-           width, height, invert ? "true" : "false",
-           width, -height, height);
+    writePSFmt("%d %d %s [%d 0 0 %d 0 %d] pdfImM1\n",
+              width, height, invert ? "true" : "false",
+              width, -height, height);
   }
 
   }
 
-  // image
-  if (colorMap) {
+  // image data
+  if (!(inType3Char && !colorMap)) {
 
 
-    // set up to process the data stream
-    imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(),
-                            colorMap->getBits());
-    imgStr->reset();
+    if (colorMap) {
 
 
-    // process the data stream
-    i = 0;
-    for (y = 0; y < height; ++y) {
+      // set up to process the data stream
+      imgStr = new ImageStream(str, width, colorMap->getNumPixelComps(),
+                              colorMap->getBits());
+      imgStr->reset();
 
 
-      // write the line
-      for (x = 0; x < width; ++x) {
-       imgStr->getPixel(pixBuf);
-       colorMap->getGray(pixBuf, &gray);
-       writePS("%02x", (int)(gray * 255 + 0.5));
-       if (++i == 32) {
-         writePSChar('\n');
-         i = 0;
+      // process the data stream
+      i = 0;
+      for (y = 0; y < height; ++y) {
+
+       // write the line
+       for (x = 0; x < width; ++x) {
+         imgStr->getPixel(pixBuf);
+         colorMap->getGray(pixBuf, &gray);
+         writePSFmt("%02x", (int)(gray * 255 + 0.5));
+         if (++i == 32) {
+           writePSChar('\n');
+           i = 0;
+         }
        }
       }
        }
       }
-    }
-    if (i != 0) {
-      writePSChar('\n');
-    }
-    delete imgStr;
+      if (i != 0) {
+       writePSChar('\n');
+      }
+      delete imgStr;
 
 
-  // imagemask
-  } else {
-    str->reset();
-    i = 0;
-    for (y = 0; y < height; ++y) {
-      for (x = 0; x < width; x += 8) {
-       writePS("%02x", str->getChar() & 0xff);
-       if (++i == 32) {
-         writePSChar('\n');
-         i = 0;
+    // imagemask
+    } else {
+      str->reset();
+      i = 0;
+      for (y = 0; y < height; ++y) {
+       for (x = 0; x < width; x += 8) {
+         writePSFmt("%02x", str->getChar() & 0xff);
+         if (++i == 32) {
+           writePSChar('\n');
+           i = 0;
+         }
        }
       }
        }
       }
+      if (i != 0) {
+       writePSChar('\n');
+      }
+      str->close();
     }
     }
-    if (i != 0) {
-      writePSChar('\n');
-    }
-    str->close();
   }
 }
 
   }
 }
 
@@ -2262,9 +2752,9 @@ void PSOutputDev::doImageL1Sep(GfxImageColorMap *colorMap,
   int x, y, i, comp;
 
   // width, height, matrix, bits per component
   int x, y, i, comp;
 
   // width, height, matrix, bits per component
-  writePS("%d %d 8 [%d 0 0 %d 0 %d] pdfIm1Sep\n",
-           width, height,
-           width, -height, height);
+  writePSFmt("%d %d 8 [%d 0 0 %d 0 %d] pdfIm1Sep\n",
+            width, height,
+            width, -height, height);
 
   // allocate a line buffer
   lineBuf = (Guchar *)gmalloc(4 * width);
 
   // allocate a line buffer
   lineBuf = (Guchar *)gmalloc(4 * width);
@@ -2286,12 +2776,13 @@ void PSOutputDev::doImageL1Sep(GfxImageColorMap *colorMap,
       lineBuf[4*x+1] = (int)(255 * cmyk.m + 0.5);
       lineBuf[4*x+2] = (int)(255 * cmyk.y + 0.5);
       lineBuf[4*x+3] = (int)(255 * cmyk.k + 0.5);
       lineBuf[4*x+1] = (int)(255 * cmyk.m + 0.5);
       lineBuf[4*x+2] = (int)(255 * cmyk.y + 0.5);
       lineBuf[4*x+3] = (int)(255 * cmyk.k + 0.5);
+      addProcessColor(cmyk.c, cmyk.m, cmyk.y, cmyk.k);
     }
 
     // write one line of each color component
     for (comp = 0; comp < 4; ++comp) {
       for (x = 0; x < width; ++x) {
     }
 
     // write one line of each color component
     for (comp = 0; comp < 4; ++comp) {
       for (x = 0; x < width; ++x) {
-       writePS("%02x", lineBuf[4*x + comp]);
+       writePSFmt("%02x", lineBuf[4*x + comp]);
        if (++i == 32) {
          writePSChar('\n');
          i = 0;
        if (++i == 32) {
          writePSChar('\n');
          i = 0;
@@ -2313,12 +2804,12 @@ void PSOutputDev::doImageL2(Object *ref, GfxImageColorMap *colorMap,
                            Stream *str, int width, int height, int len) {
   GString *s;
   int n, numComps;
                            Stream *str, int width, int height, int len) {
   GString *s;
   int n, numComps;
-  GBool useRLE, useASCII, useCompressed;
+  GBool useRLE, useASCII, useASCIIHex, useCompressed;
   GfxSeparationColorSpace *sepCS;
   GfxColor color;
   GfxCMYK cmyk;
   int c;
   GfxSeparationColorSpace *sepCS;
   GfxColor color;
   GfxCMYK cmyk;
   int c;
-  int i;
+  int col, i;
 
   // color space
   if (colorMap) {
 
   // color space
   if (colorMap) {
@@ -2326,20 +2817,77 @@ void PSOutputDev::doImageL2(Object *ref, GfxImageColorMap *colorMap,
     writePS(" setcolorspace\n");
   }
 
     writePS(" setcolorspace\n");
   }
 
-  // set up to use the array created by setupImages()
-  if ((mode == psModeForm || inType3Char) && !inlineImg) {
-    writePS("ImData_%d_%d 0\n", ref->getRefNum(), ref->getRefGen());
+  useASCIIHex = globalParams->getPSASCIIHex();
+
+  // set up the image data
+  if (mode == psModeForm || inType3Char) {
+    if (inlineImg) {
+      // create an array
+      str = new FixedLengthEncoder(str, len);
+      if (useASCIIHex) {
+       str = new ASCIIHexEncoder(str);
+      } else {
+       str = new ASCII85Encoder(str);
+      }
+      str->reset();
+      col = 0;
+      writePS((char *)(useASCIIHex ? "[<" : "[<~"));
+      do {
+       do {
+         c = str->getChar();
+       } while (c == '\n' || c == '\r');
+       if (c == (useASCIIHex ? '>' : '~') || c == EOF) {
+         break;
+       }
+       if (c == 'z') {
+         writePSChar(c);
+         ++col;
+       } else {
+         writePSChar(c);
+         ++col;
+         for (i = 1; i <= (useASCIIHex ? 1 : 4); ++i) {
+           do {
+             c = str->getChar();
+           } while (c == '\n' || c == '\r');
+           if (c == (useASCIIHex ? '>' : '~') || c == EOF) {
+             break;
+           }
+           writePSChar(c);
+           ++col;
+         }
+       }
+       // each line is: "<~...data...~><eol>"
+       // so max data length = 255 - 6 = 249
+       // chunks are 1 or 5 bytes each, so we have to stop at 245
+       // but make it 240 just to be safe
+       if (col > 240) {
+         writePS((char *)(useASCIIHex ? ">\n<" : "~>\n<~"));
+         col = 0;
+       }
+      } while (c != (useASCIIHex ? '>' : '~') && c != EOF);
+      writePS((char *)(useASCIIHex ? ">]\n" : "~>]\n"));
+      writePS("0\n");
+      str->close();
+      delete str;
+    } else {
+      // set up to use the array already created by setupImages()
+      writePSFmt("ImData_%d_%d 0\n", ref->getRefNum(), ref->getRefGen());
+    }
   }
 
   // image dictionary
   writePS("<<\n  /ImageType 1\n");
 
   // width, height, matrix, bits per component
   }
 
   // image dictionary
   writePS("<<\n  /ImageType 1\n");
 
   // width, height, matrix, bits per component
-  writePS("  /Width %d\n", width);
-  writePS("  /Height %d\n", height);
-  writePS("  /ImageMatrix [%d 0 0 %d 0 %d]\n", width, -height, height);
-  writePS("  /BitsPerComponent %d\n",
-         colorMap ? colorMap->getBits() : 1);
+  writePSFmt("  /Width %d\n", width);
+  writePSFmt("  /Height %d\n", height);
+  writePSFmt("  /ImageMatrix [%d 0 0 %d 0 %d]\n", width, -height, height);
+  if (colorMap && colorMap->getColorSpace()->getMode() == csDeviceN) {
+    writePSFmt("  /BitsPerComponent 8\n");
+  } else {
+    writePSFmt("  /BitsPerComponent %d\n",
+              colorMap ? colorMap->getBits() : 1);
+  }
 
   // decode 
   if (colorMap) {
 
   // decode 
   if (colorMap) {
@@ -2347,62 +2895,52 @@ void PSOutputDev::doImageL2(Object *ref, GfxImageColorMap *colorMap,
     if (colorMap->getColorSpace()->getMode() == csSeparation) {
       //~ this is a kludge -- see comment in dumpColorSpaceL2
       n = (1 << colorMap->getBits()) - 1;
     if (colorMap->getColorSpace()->getMode() == csSeparation) {
       //~ this is a kludge -- see comment in dumpColorSpaceL2
       n = (1 << colorMap->getBits()) - 1;
-      writePS("%g %g", colorMap->getDecodeLow(0) * n,
-             colorMap->getDecodeHigh(0) * n);
+      writePSFmt("%g %g", colorMap->getDecodeLow(0) * n,
+                colorMap->getDecodeHigh(0) * n);
+    } else if (colorMap->getColorSpace()->getMode() == csDeviceN) {
+      numComps = ((GfxDeviceNColorSpace *)colorMap->getColorSpace())->
+                  getAlt()->getNComps();
+      for (i = 0; i < numComps; ++i) {
+       if (i > 0) {
+         writePS(" ");
+       }
+       writePSFmt("0 1", colorMap->getDecodeLow(i),
+                  colorMap->getDecodeHigh(i));
+      }
     } else {
       numComps = colorMap->getNumPixelComps();
       for (i = 0; i < numComps; ++i) {
        if (i > 0) {
          writePS(" ");
        }
     } else {
       numComps = colorMap->getNumPixelComps();
       for (i = 0; i < numComps; ++i) {
        if (i > 0) {
          writePS(" ");
        }
-       writePS("%g %g", colorMap->getDecodeLow(i),
-               colorMap->getDecodeHigh(i));
+       writePSFmt("%g %g", colorMap->getDecodeLow(i),
+                  colorMap->getDecodeHigh(i));
       }
     }
     writePS("]\n");
   } else {
       }
     }
     writePS("]\n");
   } else {
-    writePS("  /Decode [%d %d]\n", invert ? 1 : 0, invert ? 0 : 1);
+    writePSFmt("  /Decode [%d %d]\n", invert ? 1 : 0, invert ? 0 : 1);
   }
 
   if (mode == psModeForm || inType3Char) {
 
   }
 
   if (mode == psModeForm || inType3Char) {
 
-    if (inlineImg) {
-
-      // data source
-      writePS("  /DataSource <~\n");
-
-      // write image data stream, using ASCII85 encode filter
-      str = new FixedLengthEncoder(str, len);
-      if (globalParams->getPSASCIIHex()) {
-       str = new ASCIIHexEncoder(str);
-      } else {
-       str = new ASCII85Encoder(str);
-      }
-      str->reset();
-      while ((c = str->getChar()) != EOF) {
-       writePSChar(c);
-      }
-      writePSChar('\n');
-      delete str;
-
-    } else {
-      writePS("  /DataSource { 2 copy get exch 1 add exch }\n");
-    }
+    // data source
+    writePS("  /DataSource { 2 copy get exch 1 add exch }\n");
 
     // end of image dictionary
 
     // end of image dictionary
-    writePS(">>\n%s\n", colorMap ? "image" : "imagemask");
+    writePSFmt(">>\n%s\n", colorMap ? "image" : "imagemask");
 
     // get rid of the array and index
 
     // get rid of the array and index
-    if (!inlineImg) {
-      writePS("pop pop\n");
-    }
+    writePS("pop pop\n");
 
   } else {
 
     // data source
     writePS("  /DataSource currentfile\n");
 
   } else {
 
     // data source
     writePS("  /DataSource currentfile\n");
-    s = str->getPSFilter("    ");
-    if (inlineImg || !s) {
+    s = str->getPSFilter(level < psLevel2 ? 1 : level < psLevel3 ? 2 : 3,
+                        "    ");
+    if ((colorMap && colorMap->getColorSpace()->getMode() == csDeviceN) ||
+       inlineImg || !s) {
       useRLE = gTrue;
       useASCII = gTrue;
       useCompressed = gFalse;
       useRLE = gTrue;
       useASCII = gTrue;
       useCompressed = gFalse;
@@ -2412,14 +2950,14 @@ void PSOutputDev::doImageL2(Object *ref, GfxImageColorMap *colorMap,
       useCompressed = gTrue;
     }
     if (useASCII) {
       useCompressed = gTrue;
     }
     if (useASCII) {
-      writePS("    /ASCII%sDecode filter\n",
-             globalParams->getPSASCIIHex() ? "Hex" : "85");
+      writePSFmt("    /ASCII%sDecode filter\n",
+                useASCIIHex ? "Hex" : "85");
     }
     if (useRLE) {
       writePS("    /RunLengthDecode filter\n");
     }
     if (useCompressed) {
     }
     if (useRLE) {
       writePS("    /RunLengthDecode filter\n");
     }
     if (useCompressed) {
-      writePS("%s", s->getCString());
+      writePS(s->getCString());
     }
     if (s) {
       delete s;
     }
     if (s) {
       delete s;
@@ -2432,12 +2970,17 @@ void PSOutputDev::doImageL2(Object *ref, GfxImageColorMap *colorMap,
       str = str->getBaseStream();
     }
 
       str = str->getBaseStream();
     }
 
+    // recode DeviceN data
+    if (colorMap && colorMap->getColorSpace()->getMode() == csDeviceN) {
+      str = new DeviceNRecoder(str, width, height, colorMap);
+    }
+
     // add RunLengthEncode and ASCIIHex/85 encode filters
     if (useRLE) {
       str = new RunLengthEncoder(str);
     }
     if (useASCII) {
     // add RunLengthEncode and ASCIIHex/85 encode filters
     if (useRLE) {
       str = new RunLengthEncoder(str);
     }
     if (useASCII) {
-      if (globalParams->getPSASCIIHex()) {
+      if (useASCIIHex) {
        str = new ASCIIHexEncoder(str);
       } else {
        str = new ASCII85Encoder(str);
        str = new ASCIIHexEncoder(str);
       } else {
        str = new ASCII85Encoder(str);
@@ -2465,7 +3008,7 @@ void PSOutputDev::doImageL2(Object *ref, GfxImageColorMap *colorMap,
       // +6/7 for "pdfIm\n" / "pdfImM\n"
       // +8 for newline + trailer
       n += colorMap ? 14 : 15;
       // +6/7 for "pdfIm\n" / "pdfImM\n"
       // +8 for newline + trailer
       n += colorMap ? 14 : 15;
-      writePS("%%%%BeginData: %d Hex Bytes\n", n);
+      writePSFmt("%%%%BeginData: %d Hex Bytes\n", n);
     }
 #endif
     if ((level == psLevel2Sep || level == psLevel3Sep) && colorMap &&
     }
 #endif
     if ((level == psLevel2Sep || level == psLevel3Sep) && colorMap &&
@@ -2473,10 +3016,11 @@ void PSOutputDev::doImageL2(Object *ref, GfxImageColorMap *colorMap,
       color.c[0] = 1;
       sepCS = (GfxSeparationColorSpace *)colorMap->getColorSpace();
       sepCS->getCMYK(&color, &cmyk);
       color.c[0] = 1;
       sepCS = (GfxSeparationColorSpace *)colorMap->getColorSpace();
       sepCS->getCMYK(&color, &cmyk);
-      writePS("%g %g %g %g (%s) pdfImSep\n",
-             cmyk.c, cmyk.m, cmyk.y, cmyk.k, sepCS->getName()->getCString());
+      writePSFmt("%g %g %g %g (%s) pdfImSep\n",
+                cmyk.c, cmyk.m, cmyk.y, cmyk.k,
+                sepCS->getName()->getCString());
     } else {
     } else {
-      writePS("%s\n", colorMap ? "pdfIm" : "pdfImM");
+      writePSFmt("%s\n", colorMap ? "pdfIm" : "pdfImM");
     }
 
     // copy the stream data
     }
 
     // copy the stream data
@@ -2488,10 +3032,10 @@ void PSOutputDev::doImageL2(Object *ref, GfxImageColorMap *colorMap,
 
     // add newline and trailer to the end
     writePSChar('\n');
 
     // add newline and trailer to the end
     writePSChar('\n');
-    writePS("%%-EOD-\n");
+    writePS("%-EOD-\n");
 #if OPI_SUPPORT
     if (opi13Nest) {
 #if OPI_SUPPORT
     if (opi13Nest) {
-      writePS("%%%%EndData\n");
+      writePS("%%EndData\n");
     }
 #endif
 
     }
 #endif
 
@@ -2508,11 +3052,14 @@ void PSOutputDev::dumpColorSpaceL2(GfxColorSpace *colorSpace) {
   GfxLabColorSpace *labCS;
   GfxIndexedColorSpace *indexedCS;
   GfxSeparationColorSpace *separationCS;
   GfxLabColorSpace *labCS;
   GfxIndexedColorSpace *indexedCS;
   GfxSeparationColorSpace *separationCS;
-  Guchar *lookup;
+  GfxColorSpace *baseCS;
+  Guchar *lookup, *p;
   double x[gfxColorMaxComps], y[gfxColorMaxComps];
   GfxColor color;
   GfxCMYK cmyk;
   double x[gfxColorMaxComps], y[gfxColorMaxComps];
   GfxColor color;
   GfxCMYK cmyk;
-  int n, numComps;
+  Function *func;
+  int n, numComps, numAltComps;
+  int byte;
   int i, j, k;
 
   switch (colorSpace->getMode()) {
   int i, j, k;
 
   switch (colorSpace->getMode()) {
@@ -2525,16 +3072,16 @@ void PSOutputDev::dumpColorSpaceL2(GfxColorSpace *colorSpace) {
   case csCalGray:
     calGrayCS = (GfxCalGrayColorSpace *)colorSpace;
     writePS("[/CIEBasedA <<\n");
   case csCalGray:
     calGrayCS = (GfxCalGrayColorSpace *)colorSpace;
     writePS("[/CIEBasedA <<\n");
-    writePS(" /DecodeA {%g exp} bind\n", calGrayCS->getGamma());
-    writePS(" /MatrixA [%g %g %g]\n",
-           calGrayCS->getWhiteX(), calGrayCS->getWhiteY(),
-           calGrayCS->getWhiteZ());
-    writePS(" /WhitePoint [%g %g %g]\n",
-           calGrayCS->getWhiteX(), calGrayCS->getWhiteY(),
-           calGrayCS->getWhiteZ());
-    writePS(" /BlackPoint [%g %g %g]\n",
-           calGrayCS->getBlackX(), calGrayCS->getBlackY(),
-           calGrayCS->getBlackZ());
+    writePSFmt(" /DecodeA {%g exp} bind\n", calGrayCS->getGamma());
+    writePSFmt(" /MatrixA [%g %g %g]\n",
+              calGrayCS->getWhiteX(), calGrayCS->getWhiteY(),
+              calGrayCS->getWhiteZ());
+    writePSFmt(" /WhitePoint [%g %g %g]\n",
+              calGrayCS->getWhiteX(), calGrayCS->getWhiteY(),
+              calGrayCS->getWhiteZ());
+    writePSFmt(" /BlackPoint [%g %g %g]\n",
+              calGrayCS->getBlackX(), calGrayCS->getBlackY(),
+              calGrayCS->getBlackZ());
     writePS(">>]");
     processColors |= psProcessBlack;
     break;
     writePS(">>]");
     processColors |= psProcessBlack;
     break;
@@ -2547,21 +3094,21 @@ void PSOutputDev::dumpColorSpaceL2(GfxColorSpace *colorSpace) {
   case csCalRGB:
     calRGBCS = (GfxCalRGBColorSpace *)colorSpace;
     writePS("[/CIEBasedABC <<\n");
   case csCalRGB:
     calRGBCS = (GfxCalRGBColorSpace *)colorSpace;
     writePS("[/CIEBasedABC <<\n");
-    writePS(" /DecodeABC [{%g exp} bind {%g exp} bind {%g exp} bind]\n",
-           calRGBCS->getGammaR(), calRGBCS->getGammaG(),
-           calRGBCS->getGammaB());
-    writePS(" /MatrixABC [%g %g %g %g %g %g %g %g %g]\n",
-           calRGBCS->getMatrix()[0], calRGBCS->getMatrix()[1],
-           calRGBCS->getMatrix()[2], calRGBCS->getMatrix()[3],
-           calRGBCS->getMatrix()[4], calRGBCS->getMatrix()[5],
-           calRGBCS->getMatrix()[6], calRGBCS->getMatrix()[7],
-           calRGBCS->getMatrix()[8]);
-    writePS(" /WhitePoint [%g %g %g]\n",
-           calRGBCS->getWhiteX(), calRGBCS->getWhiteY(),
-           calRGBCS->getWhiteZ());
-    writePS(" /BlackPoint [%g %g %g]\n",
-           calRGBCS->getBlackX(), calRGBCS->getBlackY(),
-           calRGBCS->getBlackZ());
+    writePSFmt(" /DecodeABC [{%g exp} bind {%g exp} bind {%g exp} bind]\n",
+              calRGBCS->getGammaR(), calRGBCS->getGammaG(),
+              calRGBCS->getGammaB());
+    writePSFmt(" /MatrixABC [%g %g %g %g %g %g %g %g %g]\n",
+              calRGBCS->getMatrix()[0], calRGBCS->getMatrix()[1],
+              calRGBCS->getMatrix()[2], calRGBCS->getMatrix()[3],
+              calRGBCS->getMatrix()[4], calRGBCS->getMatrix()[5],
+              calRGBCS->getMatrix()[6], calRGBCS->getMatrix()[7],
+              calRGBCS->getMatrix()[8]);
+    writePSFmt(" /WhitePoint [%g %g %g]\n",
+              calRGBCS->getWhiteX(), calRGBCS->getWhiteY(),
+              calRGBCS->getWhiteZ());
+    writePSFmt(" /BlackPoint [%g %g %g]\n",
+              calRGBCS->getBlackX(), calRGBCS->getBlackY(),
+              calRGBCS->getBlackZ());
     writePS(">>]");
     processColors |= psProcessCMYK;
     break;
     writePS(">>]");
     processColors |= psProcessCMYK;
     break;
@@ -2574,52 +3121,83 @@ void PSOutputDev::dumpColorSpaceL2(GfxColorSpace *colorSpace) {
   case csLab:
     labCS = (GfxLabColorSpace *)colorSpace;
     writePS("[/CIEBasedABC <<\n");
   case csLab:
     labCS = (GfxLabColorSpace *)colorSpace;
     writePS("[/CIEBasedABC <<\n");
-    writePS(" /RangeABC [0 100 %g %g %g %g]\n",
-           labCS->getAMin(), labCS->getAMax(),
-           labCS->getBMin(), labCS->getBMax());
+    writePSFmt(" /RangeABC [0 100 %g %g %g %g]\n",
+              labCS->getAMin(), labCS->getAMax(),
+              labCS->getBMin(), labCS->getBMax());
     writePS(" /DecodeABC [{16 add 116 div} bind {500 div} bind {200 div} bind]\n");
     writePS(" /MatrixABC [1 1 1 1 0 0 0 0 -1]\n");
     writePS(" /DecodeLMN\n");
     writePS("   [{dup 6 29 div ge {dup dup mul mul}\n");
     writePS(" /DecodeABC [{16 add 116 div} bind {500 div} bind {200 div} bind]\n");
     writePS(" /MatrixABC [1 1 1 1 0 0 0 0 -1]\n");
     writePS(" /DecodeLMN\n");
     writePS("   [{dup 6 29 div ge {dup dup mul mul}\n");
-    writePS("     {4 29 div sub 108 841 div mul } ifelse %g mul} bind\n",
-           labCS->getWhiteX());
+    writePSFmt("     {4 29 div sub 108 841 div mul } ifelse %g mul} bind\n",
+              labCS->getWhiteX());
     writePS("    {dup 6 29 div ge {dup dup mul mul}\n");
     writePS("    {dup 6 29 div ge {dup dup mul mul}\n");
-    writePS("     {4 29 div sub 108 841 div mul } ifelse %g mul} bind\n",
-           labCS->getWhiteY());
+    writePSFmt("     {4 29 div sub 108 841 div mul } ifelse %g mul} bind\n",
+              labCS->getWhiteY());
     writePS("    {dup 6 29 div ge {dup dup mul mul}\n");
     writePS("    {dup 6 29 div ge {dup dup mul mul}\n");
-    writePS("     {4 29 div sub 108 841 div mul } ifelse %g mul} bind]\n",
-           labCS->getWhiteZ());
-    writePS(" /WhitePoint [%g %g %g]\n",
-           labCS->getWhiteX(), labCS->getWhiteY(), labCS->getWhiteZ());
-    writePS(" /BlackPoint [%g %g %g]\n",
-           labCS->getBlackX(), labCS->getBlackY(), labCS->getBlackZ());
+    writePSFmt("     {4 29 div sub 108 841 div mul } ifelse %g mul} bind]\n",
+              labCS->getWhiteZ());
+    writePSFmt(" /WhitePoint [%g %g %g]\n",
+              labCS->getWhiteX(), labCS->getWhiteY(), labCS->getWhiteZ());
+    writePSFmt(" /BlackPoint [%g %g %g]\n",
+              labCS->getBlackX(), labCS->getBlackY(), labCS->getBlackZ());
     writePS(">>]");
     processColors |= psProcessCMYK;
     break;
 
   case csICCBased:
     writePS(">>]");
     processColors |= psProcessCMYK;
     break;
 
   case csICCBased:
+    // there is no transform function to the alternate color space, so
+    // we can use it directly
     dumpColorSpaceL2(((GfxICCBasedColorSpace *)colorSpace)->getAlt());
     break;
 
   case csIndexed:
     indexedCS = (GfxIndexedColorSpace *)colorSpace;
     dumpColorSpaceL2(((GfxICCBasedColorSpace *)colorSpace)->getAlt());
     break;
 
   case csIndexed:
     indexedCS = (GfxIndexedColorSpace *)colorSpace;
+    baseCS = indexedCS->getBase();
     writePS("[/Indexed ");
     writePS("[/Indexed ");
-    dumpColorSpaceL2(indexedCS->getBase());
+    dumpColorSpaceL2(baseCS);
     n = indexedCS->getIndexHigh();
     n = indexedCS->getIndexHigh();
-    numComps = indexedCS->getBase()->getNComps();
+    numComps = baseCS->getNComps();
     lookup = indexedCS->getLookup();
     lookup = indexedCS->getLookup();
-    writePS(" %d <\n", n);
-    for (i = 0; i <= n; i += 8) {
-      writePS("  ");
-      for (j = i; j < i+8 && j <= n; ++j) {
-       for (k = 0; k < numComps; ++k) {
-         writePS("%02x", lookup[j * numComps + k]);
+    writePSFmt(" %d <\n", n);
+    if (baseCS->getMode() == csDeviceN) {
+      func = ((GfxDeviceNColorSpace *)baseCS)->getTintTransformFunc();
+      numAltComps = ((GfxDeviceNColorSpace *)baseCS)->getAlt()->getNComps();
+      p = lookup;
+      for (i = 0; i <= n; i += 8) {
+       writePS("  ");
+       for (j = i; j < i+8 && j <= n; ++j) {
+         for (k = 0; k < numComps; ++k) {
+           x[k] = *p++ / 255.0;
+         }
+         func->transform(x, y);
+         for (k = 0; k < numAltComps; ++k) {
+           byte = (int)(y[k] * 255 + 0.5);
+           if (byte < 0) {
+             byte = 0;
+           } else if (byte > 255) {
+             byte = 255;
+           }
+           writePSFmt("%02x", byte);
+         }
+         color.c[0] = j;
+         indexedCS->getCMYK(&color, &cmyk);
+         addProcessColor(cmyk.c, cmyk.m, cmyk.y, cmyk.k);
        }
        }
-       color.c[0] = j;
-       indexedCS->getCMYK(&color, &cmyk);
-       addProcessColor(cmyk.c, cmyk.m, cmyk.y, cmyk.k);
+       writePS("\n");
+      }
+    } else {
+      for (i = 0; i <= n; i += 8) {
+       writePS("  ");
+       for (j = i; j < i+8 && j <= n; ++j) {
+         for (k = 0; k < numComps; ++k) {
+           writePSFmt("%02x", lookup[j * numComps + k]);
+         }
+         color.c[0] = j;
+         indexedCS->getCMYK(&color, &cmyk);
+         addProcessColor(cmyk.c, cmyk.m, cmyk.y, cmyk.k);
+       }
+       writePS("\n");
       }
       }
-      writePS("\n");
     }
     writePS(">]");
     break;
     }
     writePS(">]");
     break;
@@ -2639,13 +3217,16 @@ void PSOutputDev::dumpColorSpaceL2(GfxColorSpace *colorSpace) {
        x[0] = (double)j / 255.0;
        separationCS->getFunc()->transform(x, y);
        for (k = 0; k < numComps; ++k) {
        x[0] = (double)j / 255.0;
        separationCS->getFunc()->transform(x, y);
        for (k = 0; k < numComps; ++k) {
-         writePS("%02x", (int)(255 * y[k] + 0.5));
+         writePSFmt("%02x", (int)(255 * y[k] + 0.5));
        }
       }
       writePS("\n");
     }
     writePS(">]");
        }
       }
       writePS("\n");
     }
     writePS(">]");
+#if 0 //~ this shouldn't be here since the PS file doesn't actually refer
+      //~ to this colorant (it's converted to CMYK instead)
     addCustomColor(separationCS);
     addCustomColor(separationCS);
+#endif
     break;
 
   case csDeviceN:
     break;
 
   case csDeviceN:
@@ -2686,20 +3267,20 @@ void PSOutputDev::opiBegin20(GfxState *state, Dict *dict) {
   int w, h;
   int i;
 
   int w, h;
   int i;
 
-  writePS("%%%%BeginOPI: 2.0\n");
-  writePS("%%%%Distilled\n");
+  writePS("%%BeginOPI: 2.0\n");
+  writePS("%%Distilled\n");
 
   dict->lookup("F", &obj1);
   if (getFileSpec(&obj1, &obj2)) {
 
   dict->lookup("F", &obj1);
   if (getFileSpec(&obj1, &obj2)) {
-    writePS("%%%%ImageFileName: %s\n",
-           obj2.getString()->getCString());
+    writePSFmt("%%%%ImageFileName: %s\n",
+              obj2.getString()->getCString());
     obj2.free();
   }
   obj1.free();
 
   dict->lookup("MainImage", &obj1);
   if (obj1.isString()) {
     obj2.free();
   }
   obj1.free();
 
   dict->lookup("MainImage", &obj1);
   if (obj1.isString()) {
-    writePS("%%%%MainImage: %s\n", obj1.getString()->getCString());
+    writePSFmt("%%%%MainImage: %s\n", obj1.getString()->getCString());
   }
   obj1.free();
 
   }
   obj1.free();
 
@@ -2714,7 +3295,7 @@ void PSOutputDev::opiBegin20(GfxState *state, Dict *dict) {
     obj1.arrayGet(1, &obj2);
     height = obj2.getNum();
     obj2.free();
     obj1.arrayGet(1, &obj2);
     height = obj2.getNum();
     obj2.free();
-    writePS("%%%%ImageDimensions: %g %g\n", width, height);
+    writePSFmt("%%%%ImageDimensions: %g %g\n", width, height);
   }
   obj1.free();
 
   }
   obj1.free();
 
@@ -2732,31 +3313,31 @@ void PSOutputDev::opiBegin20(GfxState *state, Dict *dict) {
     obj1.arrayGet(3, &obj2);
     bottom = obj2.getNum();
     obj2.free();
     obj1.arrayGet(3, &obj2);
     bottom = obj2.getNum();
     obj2.free();
-    writePS("%%%%ImageCropRect: %g %g %g %g\n", left, top, right, bottom);
+    writePSFmt("%%%%ImageCropRect: %g %g %g %g\n", left, top, right, bottom);
   }
   obj1.free();
 
   dict->lookup("Overprint", &obj1);
   if (obj1.isBool()) {
   }
   obj1.free();
 
   dict->lookup("Overprint", &obj1);
   if (obj1.isBool()) {
-    writePS("%%%%ImageOverprint: %s\n", obj1.getBool() ? "true" : "false");
+    writePSFmt("%%%%ImageOverprint: %s\n", obj1.getBool() ? "true" : "false");
   }
   obj1.free();
 
   dict->lookup("Inks", &obj1);
   if (obj1.isName()) {
   }
   obj1.free();
 
   dict->lookup("Inks", &obj1);
   if (obj1.isName()) {
-    writePS("%%%%ImageInks: %s\n", obj1.getName());
+    writePSFmt("%%%%ImageInks: %s\n", obj1.getName());
   } else if (obj1.isArray() && obj1.arrayGetLength() >= 1) {
     obj1.arrayGet(0, &obj2);
     if (obj2.isName()) {
   } else if (obj1.isArray() && obj1.arrayGetLength() >= 1) {
     obj1.arrayGet(0, &obj2);
     if (obj2.isName()) {
-      writePS("%%%%ImageInks: %s %d",
-             obj2.getName(), (obj1.arrayGetLength() - 1) / 2);
+      writePSFmt("%%%%ImageInks: %s %d",
+                obj2.getName(), (obj1.arrayGetLength() - 1) / 2);
       for (i = 1; i+1 < obj1.arrayGetLength(); i += 2) {
        obj1.arrayGet(i, &obj3);
        obj1.arrayGet(i+1, &obj4);
        if (obj3.isString() && obj4.isNum()) {
          writePS(" ");
          writePSString(obj3.getString());
       for (i = 1; i+1 < obj1.arrayGetLength(); i += 2) {
        obj1.arrayGet(i, &obj3);
        obj1.arrayGet(i+1, &obj4);
        if (obj3.isString() && obj4.isNum()) {
          writePS(" ");
          writePSString(obj3.getString());
-         writePS(" %g", obj4.getNum());
+         writePSFmt(" %g", obj4.getNum());
        }
        obj3.free();
        obj4.free();
        }
        obj3.free();
        obj4.free();
@@ -2769,7 +3350,7 @@ void PSOutputDev::opiBegin20(GfxState *state, Dict *dict) {
 
   writePS("gsave\n");
 
 
   writePS("gsave\n");
 
-  writePS("%%%%BeginIncludedImage\n");
+  writePS("%%BeginIncludedImage\n");
 
   dict->lookup("IncludedImageDimensions", &obj1);
   if (obj1.isArray() && obj1.arrayGetLength() == 2) {
 
   dict->lookup("IncludedImageDimensions", &obj1);
   if (obj1.isArray() && obj1.arrayGetLength() == 2) {
@@ -2779,13 +3360,13 @@ void PSOutputDev::opiBegin20(GfxState *state, Dict *dict) {
     obj1.arrayGet(1, &obj2);
     h = obj2.getInt();
     obj2.free();
     obj1.arrayGet(1, &obj2);
     h = obj2.getInt();
     obj2.free();
-    writePS("%%%%IncludedImageDimensions: %d %d\n", w, h);
+    writePSFmt("%%%%IncludedImageDimensions: %d %d\n", w, h);
   }
   obj1.free();
 
   dict->lookup("IncludedImageQuality", &obj1);
   if (obj1.isNum()) {
   }
   obj1.free();
 
   dict->lookup("IncludedImageQuality", &obj1);
   if (obj1.isNum()) {
-    writePS("%%%%IncludedImageQuality: %g\n", obj1.getNum());
+    writePSFmt("%%%%IncludedImageQuality: %g\n", obj1.getNum());
   }
   obj1.free();
 
   }
   obj1.free();
 
@@ -2807,8 +3388,8 @@ void PSOutputDev::opiBegin13(GfxState *state, Dict *dict) {
 
   dict->lookup("F", &obj1);
   if (getFileSpec(&obj1, &obj2)) {
 
   dict->lookup("F", &obj1);
   if (getFileSpec(&obj1, &obj2)) {
-    writePS("%%ALDImageFileName: %s\n",
-           obj2.getString()->getCString());
+    writePSFmt("%%ALDImageFileName: %s\n",
+              obj2.getString()->getCString());
     obj2.free();
   }
   obj1.free();
     obj2.free();
   }
   obj1.free();
@@ -2827,7 +3408,7 @@ void PSOutputDev::opiBegin13(GfxState *state, Dict *dict) {
     obj1.arrayGet(3, &obj2);
     bottom = obj2.getInt();
     obj2.free();
     obj1.arrayGet(3, &obj2);
     bottom = obj2.getInt();
     obj2.free();
-    writePS("%%ALDImageCropRect: %d %d %d %d\n", left, top, right, bottom);
+    writePSFmt("%%ALDImageCropRect: %d %d %d %d\n", left, top, right, bottom);
   }
   obj1.free();
 
   }
   obj1.free();
 
@@ -2847,7 +3428,7 @@ void PSOutputDev::opiBegin13(GfxState *state, Dict *dict) {
     obj2.free();
     obj1.arrayGet(4, &obj2);
     if (obj2.isString()) {
     obj2.free();
     obj1.arrayGet(4, &obj2);
     if (obj2.isString()) {
-      writePS("%%ALDImageColor: %g %g %g %g ", c, m, y, k);
+      writePSFmt("%%ALDImageColor: %g %g %g %g ", c, m, y, k);
       writePSString(obj2.getString());
       writePS("\n");
     }
       writePSString(obj2.getString());
       writePS("\n");
     }
@@ -2857,7 +3438,7 @@ void PSOutputDev::opiBegin13(GfxState *state, Dict *dict) {
 
   dict->lookup("ColorType", &obj1);
   if (obj1.isName()) {
 
   dict->lookup("ColorType", &obj1);
   if (obj1.isName()) {
-    writePS("%%ALDImageColorType: %s\n", obj1.getName());
+    writePSFmt("%%ALDImageColorType: %s\n", obj1.getName());
   }
   obj1.free();
 
   }
   obj1.free();
 
@@ -2878,20 +3459,20 @@ void PSOutputDev::opiBegin13(GfxState *state, Dict *dict) {
     obj1.arrayGet(3, &obj2);
     lry = obj2.getNum();
     obj2.free();
     obj1.arrayGet(3, &obj2);
     lry = obj2.getNum();
     obj2.free();
-    writePS("%%ALDImageCropFixed: %g %g %g %g\n", ulx, uly, lrx, lry);
+    writePSFmt("%%ALDImageCropFixed: %g %g %g %g\n", ulx, uly, lrx, lry);
   }
   obj1.free();
 
   dict->lookup("GrayMap", &obj1);
   if (obj1.isArray()) {
   }
   obj1.free();
 
   dict->lookup("GrayMap", &obj1);
   if (obj1.isArray()) {
-    writePS("%%ALDImageGrayMap:");
+    writePS("%ALDImageGrayMap:");
     for (i = 0; i < obj1.arrayGetLength(); i += 16) {
       if (i > 0) {
     for (i = 0; i < obj1.arrayGetLength(); i += 16) {
       if (i > 0) {
-       writePS("\n%%%%+");
+       writePS("\n%%+");
       }
       for (j = 0; j < 16 && i+j < obj1.arrayGetLength(); ++j) {
        obj1.arrayGet(i+j, &obj2);
       }
       for (j = 0; j < 16 && i+j < obj1.arrayGetLength(); ++j) {
        obj1.arrayGet(i+j, &obj2);
-       writePS(" %d", obj2.getInt());
+       writePSFmt(" %d", obj2.getInt());
        obj2.free();
       }
     }
        obj2.free();
       }
     }
@@ -2901,7 +3482,7 @@ void PSOutputDev::opiBegin13(GfxState *state, Dict *dict) {
 
   dict->lookup("ID", &obj1);
   if (obj1.isString()) {
 
   dict->lookup("ID", &obj1);
   if (obj1.isString()) {
-    writePS("%%ALDImageID: %s\n", obj1.getString()->getCString());
+    writePSFmt("%%ALDImageID: %s\n", obj1.getString()->getCString());
   }
   obj1.free();
 
   }
   obj1.free();
 
@@ -2913,13 +3494,13 @@ void PSOutputDev::opiBegin13(GfxState *state, Dict *dict) {
     obj1.arrayGet(1, &obj2);
     bits = obj2.getInt();
     obj2.free();
     obj1.arrayGet(1, &obj2);
     bits = obj2.getInt();
     obj2.free();
-    writePS("%%ALDImageType: %d %d\n", samples, bits);
+    writePSFmt("%%ALDImageType: %d %d\n", samples, bits);
   }
   obj1.free();
 
   dict->lookup("Overprint", &obj1);
   if (obj1.isBool()) {
   }
   obj1.free();
 
   dict->lookup("Overprint", &obj1);
   if (obj1.isBool()) {
-    writePS("%%ALDImageOverprint: %s\n", obj1.getBool() ? "true" : "false");
+    writePSFmt("%%ALDImageOverprint: %s\n", obj1.getBool() ? "true" : "false");
   }
   obj1.free();
 
   }
   obj1.free();
 
@@ -2953,8 +3534,8 @@ void PSOutputDev::opiBegin13(GfxState *state, Dict *dict) {
     opiTransform(state, ulx, uly, &tulx, &tuly);
     opiTransform(state, urx, ury, &turx, &tury);
     opiTransform(state, lrx, lry, &tlrx, &tlry);
     opiTransform(state, ulx, uly, &tulx, &tuly);
     opiTransform(state, urx, ury, &turx, &tury);
     opiTransform(state, lrx, lry, &tlrx, &tlry);
-    writePS("%%ALDImagePosition: %g %g %g %g %g %g %g %g\n",
-           tllx, tlly, tulx, tuly, turx, tury, tlrx, tlry);
+    writePSFmt("%%ALDImagePosition: %g %g %g %g %g %g %g %g\n",
+              tllx, tlly, tulx, tuly, turx, tury, tlrx, tlry);
     obj2.free();
   }
   obj1.free();
     obj2.free();
   }
   obj1.free();
@@ -2967,7 +3548,7 @@ void PSOutputDev::opiBegin13(GfxState *state, Dict *dict) {
     obj1.arrayGet(1, &obj2);
     vert = obj2.getNum();
     obj2.free();
     obj1.arrayGet(1, &obj2);
     vert = obj2.getNum();
     obj2.free();
-    writePS("%%ALDImageResoution: %g %g\n", horiz, vert);
+    writePSFmt("%%ALDImageResoution: %g %g\n", horiz, vert);
     obj2.free();
   }
   obj1.free();
     obj2.free();
   }
   obj1.free();
@@ -2980,7 +3561,7 @@ void PSOutputDev::opiBegin13(GfxState *state, Dict *dict) {
     obj1.arrayGet(1, &obj2);
     height = obj2.getInt();
     obj2.free();
     obj1.arrayGet(1, &obj2);
     height = obj2.getInt();
     obj2.free();
-    writePS("%%ALDImageDimensions: %d %d\n", width, height);
+    writePSFmt("%%ALDImageDimensions: %d %d\n", width, height);
   }
   obj1.free();
 
   }
   obj1.free();
 
@@ -2989,17 +3570,17 @@ void PSOutputDev::opiBegin13(GfxState *state, Dict *dict) {
 
   dict->lookup("Tint", &obj1);
   if (obj1.isNum()) {
 
   dict->lookup("Tint", &obj1);
   if (obj1.isNum()) {
-    writePS("%%ALDImageTint: %g\n", obj1.getNum());
+    writePSFmt("%%ALDImageTint: %g\n", obj1.getNum());
   }
   obj1.free();
 
   dict->lookup("Transparency", &obj1);
   if (obj1.isBool()) {
   }
   obj1.free();
 
   dict->lookup("Transparency", &obj1);
   if (obj1.isBool()) {
-    writePS("%%ALDImageTransparency: %s\n", obj1.getBool() ? "true" : "false");
+    writePSFmt("%%ALDImageTransparency: %s\n", obj1.getBool() ? "true" : "false");
   }
   obj1.free();
 
   }
   obj1.free();
 
-  writePS("%%%%BeginObject: image\n");
+  writePS("%%BeginObject: image\n");
   writePS("opiMatrix2 setmatrix\n");
   ++opi13Nest;
 }
   writePS("opiMatrix2 setmatrix\n");
   ++opi13Nest;
 }
@@ -3014,10 +3595,17 @@ void PSOutputDev::opiTransform(GfxState *state, double x0, double y0,
   state->transform(x0, y0, x1, y1);
   *x1 += tx;
   *y1 += ty;
   state->transform(x0, y0, x1, y1);
   *x1 += tx;
   *y1 += ty;
-  if (landscape) {
+  if (rotate == 90) {
     t = *x1;
     *x1 = -*y1;
     *y1 = t;
     t = *x1;
     *x1 = -*y1;
     *y1 = t;
+  } else if (rotate == 180) {
+    *x1 = -*x1;
+    *y1 = -*y1;
+  } else if (rotate == 270) {
+    t = *x1;
+    *x1 = *y1;
+    *y1 = -t;
   }
   *x1 *= xScale;
   *y1 *= yScale;
   }
   *x1 *= xScale;
   *y1 *= yScale;
@@ -3029,8 +3617,8 @@ void PSOutputDev::opiEnd(GfxState *state, Dict *opiDict) {
   if (globalParams->getPSOPI()) {
     opiDict->lookup("2.0", &dict);
     if (dict.isDict()) {
   if (globalParams->getPSOPI()) {
     opiDict->lookup("2.0", &dict);
     if (dict.isDict()) {
-      writePS("%%%%EndIncludedImage\n");
-      writePS("%%%%EndOPI\n");
+      writePS("%%EndIncludedImage\n");
+      writePS("%%EndOPI\n");
       writePS("grestore\n");
       --opi20Nest;
       dict.free();
       writePS("grestore\n");
       --opi20Nest;
       dict.free();
@@ -3038,7 +3626,7 @@ void PSOutputDev::opiEnd(GfxState *state, Dict *opiDict) {
       dict.free();
       opiDict->lookup("1.3", &dict);
       if (dict.isDict()) {
       dict.free();
       opiDict->lookup("1.3", &dict);
       if (dict.isDict()) {
-       writePS("%%%%EndObject\n");
+       writePS("%%EndObject\n");
        writePS("restore\n");
        --opi13Nest;
       }
        writePS("restore\n");
        --opi13Nest;
       }
@@ -3079,7 +3667,7 @@ GBool PSOutputDev::getFileSpec(Object *fileSpec, Object *fileName) {
 #endif // OPI_SUPPORT
 
 void PSOutputDev::type3D0(GfxState *state, double wx, double wy) {
 #endif // OPI_SUPPORT
 
 void PSOutputDev::type3D0(GfxState *state, double wx, double wy) {
-  writePS("%g %g setcharwidth\n", wx, wy);
+  writePSFmt("%g %g setcharwidth\n", wx, wy);
   writePS("q\n");
 }
 
   writePS("q\n");
 }
 
@@ -3112,18 +3700,34 @@ void PSOutputDev::psXObject(Stream *psStream, Stream *level1Stream) {
   str->close();
 }
 
   str->close();
 }
 
-void PSOutputDev::writePS(const char *fmt, ...) {
+void PSOutputDev::writePSChar(char c) {
+  if (t3String) {
+    t3String->append(c);
+  } else {
+    (*outputFunc)(outputStream, &c, 1);
+  }
+}
+
+void PSOutputDev::writePS(char *s) {
+  if (t3String) {
+    t3String->append(s);
+  } else {
+    (*outputFunc)(outputStream, s, strlen(s));
+  }
+}
+
+void PSOutputDev::writePSFmt(const char *fmt, ...) {
   va_list args;
   char buf[512];
 
   va_start(args, fmt);
   va_list args;
   char buf[512];
 
   va_start(args, fmt);
+  vsprintf(buf, fmt, args);
+  va_end(args);
   if (t3String) {
   if (t3String) {
-    vsprintf(buf, fmt, args);
     t3String->append(buf);
   } else {
     t3String->append(buf);
   } else {
-    vfprintf(f, fmt, args);
+    (*outputFunc)(outputStream, buf, strlen(buf));
   }
   }
-  va_end(args);
 }
 
 void PSOutputDev::writePSString(GString *s) {
 }
 
 void PSOutputDev::writePSString(GString *s) {
@@ -3137,11 +3741,11 @@ void PSOutputDev::writePSString(GString *s) {
       writePSChar('\\');
       writePSChar((char)*p);
     } else if (*p < 0x20 || *p >= 0x80) {
       writePSChar('\\');
       writePSChar((char)*p);
     } else if (*p < 0x20 || *p >= 0x80) {
+      sprintf(buf, "\\%03o", *p);
       if (t3String) {
       if (t3String) {
-       sprintf(buf, "\\%03o", *p);
        t3String->append(buf);
       } else {
        t3String->append(buf);
       } else {
-       fprintf(f, "\\%03o", *p);
+       (*outputFunc)(outputStream, buf, strlen(buf));
       }
     } else {
       writePSChar((char)*p);
       }
     } else {
       writePSChar((char)*p);
@@ -3150,11 +3754,20 @@ void PSOutputDev::writePSString(GString *s) {
   writePSChar(')');
 }
 
   writePSChar(')');
 }
 
-void PSOutputDev::writePSChar(char c) {
-  if (t3String) {
-    t3String->append(c);
-  } else {
-    fputc(c, f);
+void PSOutputDev::writePSName(char *s) {
+  char *p;
+  char c;
+
+  p = s;
+  while ((c = *p++)) {
+    if (c <= (char)0x20 || c >= (char)0x7f ||
+       c == '(' || c == ')' || c == '<' || c == '>' ||
+       c == '[' || c == ']' || c == '{' || c == '}' ||
+       c == '/' || c == '%') {
+      writePSFmt("#%02x", c & 0xff);
+    } else {
+      writePSChar(c);
+    }
   }
 }
 
   }
 }
 
@@ -3165,6 +3778,15 @@ GString *PSOutputDev::filterPSName(GString *name) {
   char c;
 
   name2 = new GString();
   char c;
 
   name2 = new GString();
+
+  // ghostscript chokes on names that begin with out-of-limits
+  // numbers, e.g., 1e4foo is handled correctly (as a name), but
+  // 1e999foo generates a limitcheck error
+  c = name->getChar(0);
+  if (c >= '0' && c <= '9') {
+    name2->append('f');
+  }
+
   for (i = 0; i < name->getLength(); ++i) {
     c = name->getChar(i);
     if (c <= (char)0x20 || c >= (char)0x7f ||
   for (i = 0; i < name->getLength(); ++i) {
     c = name->getChar(i);
     if (c <= (char)0x20 || c >= (char)0x7f ||