blob: 1cf2eea48765bd354a20b6e2081428b1901bcc14 [file] [log] [blame]
//========================================================================
//
// PSOutputDev.cc
//
// Copyright 1996-2003 Glyph & Cog, LLC
//
//========================================================================
//========================================================================
//
// Modified under the Poppler project - http://poppler.freedesktop.org
//
// All changes made under the Poppler project to this file are licensed
// under GPL version 2 or later
//
// Copyright (C) 2005 Martin Kretzschmar <martink@gnome.org>
// Copyright (C) 2005, 2006 Kristian Høgsberg <krh@redhat.com>
// Copyright (C) 2006-2009 Albert Astals Cid <aacid@kde.org>
// Copyright (C) 2006 Jeff Muizelaar <jeff@infidigm.net>
// Copyright (C) 2007, 2008 Brad Hards <bradh@kde.org>
// Copyright (C) 2008, 2009 Koji Otani <sho@bbr.jp>
// Copyright (C) 2008 Hib Eris <hib@hiberis.nl>
// Copyright (C) 2009 Thomas Freitag <Thomas.Freitag@alfa.de>
// Copyright (C) 2009 Till Kamppeter <till.kamppeter@gmail.com>
// Copyright (C) 2009 Carlos Garcia Campos <carlosgc@gnome.org>
// Copyright (C) 2009 William Bader <williambader@hotmail.com>
// Copyright (C) 2009 Kovid Goyal <kovid@kovidgoyal.net>
//
// To see a description of the changes please see the Changelog file that
// came with your tarball or type make ChangeLog if you are building from git
//
//========================================================================
#include <config.h>
#ifdef USE_GCC_PRAGMAS
#pragma implementation
#endif
#include <stdio.h>
#include <stddef.h>
#include <stdarg.h>
#include <signal.h>
#include <math.h>
#include <limits.h>
#include "goo/GooString.h"
#include "goo/GooList.h"
#include "poppler-config.h"
#include "GlobalParams.h"
#include "Object.h"
#include "Error.h"
#include "Function.h"
#include "Gfx.h"
#include "GfxState.h"
#include "GfxFont.h"
#include "UnicodeMap.h"
#include <fofi/FoFiType1C.h>
#include <fofi/FoFiTrueType.h>
#include "Catalog.h"
#include "Page.h"
#include "Stream.h"
#include "Annot.h"
#include "XRef.h"
#include "PreScanOutputDev.h"
#include "FileSpec.h"
#if HAVE_SPLASH
# include "splash/Splash.h"
# include "splash/SplashBitmap.h"
# include "SplashOutputDev.h"
#endif
#include "PSOutputDev.h"
#ifdef MACOS
// needed for setting type/creator of MacOS files
#include "ICSupport.h"
#endif
// the MSVC math.h doesn't define this
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
//------------------------------------------------------------------------
// Resolution at which pages with transparency will be rasterized.
#define splashDPI 300
//------------------------------------------------------------------------
// PostScript prolog and setup
//------------------------------------------------------------------------
// The '~' escapes mark prolog code that is emitted only in certain
// levels:
//
// ~[123][sn]
// ^ ^----- s=psLevel*Sep, n=psLevel*
// +----- 1=psLevel1*, 2=psLevel2*, 3=psLevel3*
static char *prolog[] = {
"/xpdf 75 dict def xpdf begin",
"% PDF special state",
"/pdfDictSize 15 def",
"~1sn",
"/pdfStates 64 array def",
" 0 1 63 {",
" pdfStates exch pdfDictSize dict",
" dup /pdfStateIdx 3 index put",
" put",
" } for",
"~123sn",
"/pdfSetup {",
" 3 1 roll 2 array astore",
" /setpagedevice where {",
" pop 3 dict begin",
" /PageSize exch def",
" /ImagingBBox null def",
" /Policies 1 dict dup begin /PageSize 3 def end def",
" { /Duplex true def } if",
" currentdict end setpagedevice",
" } {",
" pop pop",
" } ifelse",
"} def",
"~1sn",
"/pdfOpNames [",
" /pdfFill /pdfStroke /pdfLastFill /pdfLastStroke",
" /pdfTextMat /pdfFontSize /pdfCharSpacing /pdfTextRender",
" /pdfTextRise /pdfWordSpacing /pdfHorizScaling /pdfTextClipPath",
"] def",
"~123sn",
"/pdfStartPage {",
"~1sn",
" pdfStates 0 get begin",
"~23sn",
" pdfDictSize dict begin",
"~23n",
" /pdfFillCS [] def",
" /pdfFillXform {} def",
" /pdfStrokeCS [] def",
" /pdfStrokeXform {} def",
"~1n",
" /pdfFill 0 def",
" /pdfStroke 0 def",
"~1s",
" /pdfFill [0 0 0 1] def",
" /pdfStroke [0 0 0 1] def",
"~23sn",
" /pdfFill [0] def",
" /pdfStroke [0] def",
" /pdfFillOP false def",
" /pdfStrokeOP false def",
"~123sn",
" /pdfLastFill false def",
" /pdfLastStroke false def",
" /pdfTextMat [1 0 0 1 0 0] def",
" /pdfFontSize 0 def",
" /pdfCharSpacing 0 def",
" /pdfTextRender 0 def",
" /pdfTextRise 0 def",
" /pdfWordSpacing 0 def",
" /pdfHorizScaling 1 def",
" /pdfTextClipPath [] def",
"} def",
"/pdfEndPage { end } def",
"~23s",
"% separation convention operators",
"/findcmykcustomcolor where {",
" pop",
"}{",
" /findcmykcustomcolor { 5 array astore } def",
"} ifelse",
"/setcustomcolor where {",
" pop",
"}{",
" /setcustomcolor {",
" exch",
" [ exch /Separation exch dup 4 get exch /DeviceCMYK exch",
" 0 4 getinterval cvx",
" [ exch /dup load exch { mul exch dup } /forall load",
" /pop load dup ] cvx",
" ] setcolorspace setcolor",
" } def",
"} ifelse",
"/customcolorimage where {",
" pop",
"}{",
" /customcolorimage {",
" gsave",
" [ exch /Separation exch dup 4 get exch /DeviceCMYK exch",
" 0 4 getinterval",
" [ exch /dup load exch { mul exch dup } /forall load",
" /pop load dup ] cvx",
" ] setcolorspace",
" 10 dict begin",
" /ImageType 1 def",
" /DataSource exch def",
" /ImageMatrix exch def",
" /BitsPerComponent exch def",
" /Height exch def",
" /Width exch def",
" /Decode [1 0] def",
" currentdict end",
" image",
" grestore",
" } def",
"} ifelse",
"~123sn",
"% PDF color state",
"~1n",
"/g { dup /pdfFill exch def setgray",
" /pdfLastFill true def /pdfLastStroke false def } def",
"/G { dup /pdfStroke exch def setgray",
" /pdfLastStroke true def /pdfLastFill false def } def",
"/fCol {",
" pdfLastFill not {",
" pdfFill setgray",
" /pdfLastFill true def /pdfLastStroke false def",
" } if",
"} def",
"/sCol {",
" pdfLastStroke not {",
" pdfStroke setgray",
" /pdfLastStroke true def /pdfLastFill false def",
" } if",
"} def",
"~1s",
"/k { 4 copy 4 array astore /pdfFill exch def setcmykcolor",
" /pdfLastFill true def /pdfLastStroke false def } def",
"/K { 4 copy 4 array astore /pdfStroke exch def setcmykcolor",
" /pdfLastStroke true def /pdfLastFill false def } def",
"/fCol {",
" pdfLastFill not {",
" pdfFill aload pop setcmykcolor",
" /pdfLastFill true def /pdfLastStroke false def",
" } if",
"} def",
"/sCol {",
" pdfLastStroke not {",
" pdfStroke aload pop setcmykcolor",
" /pdfLastStroke true def /pdfLastFill false def",
" } if",
"} def",
"~23n",
"/cs { /pdfFillXform exch def dup /pdfFillCS exch def",
" setcolorspace } def",
"/CS { /pdfStrokeXform exch def dup /pdfStrokeCS exch def",
" setcolorspace } def",
"/sc { pdfLastFill not { pdfFillCS setcolorspace } if",
" dup /pdfFill exch def aload pop pdfFillXform setcolor",
" /pdfLastFill true def /pdfLastStroke false def } def",
"/SC { pdfLastStroke not { pdfStrokeCS setcolorspace } if",
" dup /pdfStroke exch def aload pop pdfStrokeXform setcolor",
" /pdfLastStroke true def /pdfLastFill false def } def",
"/op { /pdfFillOP exch def",
" pdfLastFill { pdfFillOP setoverprint } if } def",
"/OP { /pdfStrokeOP exch def",
" pdfLastStroke { pdfStrokeOP setoverprint } if } def",
"/fCol {",
" pdfLastFill not {",
" pdfFillCS setcolorspace",
" pdfFill aload pop pdfFillXform setcolor",
" pdfFillOP setoverprint",
" /pdfLastFill true def /pdfLastStroke false def",
" } if",
"} def",
"/sCol {",
" pdfLastStroke not {",
" pdfStrokeCS setcolorspace",
" pdfStroke aload pop pdfStrokeXform setcolor",
" pdfStrokeOP setoverprint",
" /pdfLastStroke true def /pdfLastFill false def",
" } if",
"} def",
"~23s",
"/k { 4 copy 4 array astore /pdfFill exch def setcmykcolor",
" /pdfLastFill true def /pdfLastStroke false def } def",
"/K { 4 copy 4 array astore /pdfStroke exch def setcmykcolor",
" /pdfLastStroke true def /pdfLastFill false def } def",
"/ck { 6 copy 6 array astore /pdfFill exch def",
" findcmykcustomcolor exch setcustomcolor",
" /pdfLastFill true def /pdfLastStroke false def } def",
"/CK { 6 copy 6 array astore /pdfStroke exch def",
" findcmykcustomcolor exch setcustomcolor",
" /pdfLastStroke true def /pdfLastFill false def } def",
"/op { /pdfFillOP exch def",
" pdfLastFill { pdfFillOP setoverprint } if } def",
"/OP { /pdfStrokeOP exch def",
" pdfLastStroke { pdfStrokeOP setoverprint } if } def",
"/fCol {",
" pdfLastFill not {",
" pdfFill aload length 4 eq {",
" setcmykcolor",
" }{",
" findcmykcustomcolor exch setcustomcolor",
" } ifelse",
" pdfFillOP setoverprint",
" /pdfLastFill true def /pdfLastStroke false def",
" } if",
"} def",
"/sCol {",
" pdfLastStroke not {",
" pdfStroke aload length 4 eq {",
" setcmykcolor",
" }{",
" findcmykcustomcolor exch setcustomcolor",
" } ifelse",
" pdfStrokeOP setoverprint",
" /pdfLastStroke true def /pdfLastFill false def",
" } if",
"} def",
"~123sn",
"% build a font",
"/pdfMakeFont {",
" 4 3 roll findfont",
" 4 2 roll matrix scale makefont",
" dup length dict begin",
" { 1 index /FID ne { def } { pop pop } ifelse } forall",
" /Encoding exch def",
" currentdict",
" end",
" definefont pop",
"} def",
"/pdfMakeFont16 {",
" exch findfont",
" dup length dict begin",
" { 1 index /FID ne { def } { pop pop } ifelse } forall",
" /WMode exch def",
" currentdict",
" end",
" definefont pop",
"} def",
"~3sn",
"/pdfMakeFont16L3 {",
" 1 index /CIDFont resourcestatus {",
" pop pop 1 index /CIDFont findresource /CIDFontType known",
" } {",
" false",
" } ifelse",
" {",
" 0 eq { /Identity-H } { /Identity-V } ifelse",
" exch 1 array astore composefont pop",
" } {",
" pdfMakeFont16",
" } ifelse",
"} def",
"~123sn",
"% graphics state operators",
"~1sn",
"/q {",
" gsave",
" pdfOpNames length 1 sub -1 0 { pdfOpNames exch get load } for",
" pdfStates pdfStateIdx 1 add get begin",
" pdfOpNames { exch def } forall",
"} def",
"/Q { end grestore } def",
"~23sn",
"/q { gsave pdfDictSize dict begin } def",
"/Q {",
" end grestore",
" /pdfLastFill where {",
" pop",
" pdfLastFill {",
" pdfFillOP setoverprint",
" } {",
" pdfStrokeOP setoverprint",
" } ifelse",
" } if",
"} def",
"~123sn",
"/cm { concat } def",
"/d { setdash } def",
"/i { setflat } def",
"/j { setlinejoin } def",
"/J { setlinecap } def",
"/M { setmiterlimit } def",
"/w { setlinewidth } def",
"% path segment operators",
"/m { moveto } def",
"/l { lineto } def",
"/c { curveto } def",
"/re { 4 2 roll moveto 1 index 0 rlineto 0 exch rlineto",
" neg 0 rlineto closepath } def",
"/h { closepath } def",
"% path painting operators",
"/S { sCol stroke } def",
"/Sf { fCol stroke } def",
"/f { fCol fill } def",
"/f* { fCol eofill } def",
"% clipping operators",
"/W { clip newpath } def",
"/W* { eoclip newpath } def",
"/Ws { strokepath clip newpath } def",
"% text state operators",
"/Tc { /pdfCharSpacing exch def } def",
"/Tf { dup /pdfFontSize exch def",
" dup pdfHorizScaling mul exch matrix scale",
" pdfTextMat matrix concatmatrix dup 4 0 put dup 5 0 put",
" exch findfont exch makefont setfont } def",
"/Tr { /pdfTextRender exch def } def",
"/Ts { /pdfTextRise exch def } def",
"/Tw { /pdfWordSpacing exch def } def",
"/Tz { /pdfHorizScaling exch def } def",
"% text positioning operators",
"/Td { pdfTextMat transform moveto } def",
"/Tm { /pdfTextMat exch def } def",
"% text string operators",
"/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 {",
" false charpath",
" 5 index 5 index rmoveto",
" 6 index eq { 7 index 7 index rmoveto } if",
" } exch cshow2",
" 6 {pop} repeat",
"} 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",
"/Tclip { pdfTextClipPath cvx exec clip newpath",
" /pdfTextClipPath [] def } def",
"/Tclip* { pdfTextClipPath cvx exec eoclip newpath",
" /pdfTextClipPath [] def } def",
"~1ns",
"% Level 1 image operators",
"~1n",
"/pdfIm1 {",
" /pdfImBuf1 4 index string def",
" { currentfile pdfImBuf1 readhexstring pop } image",
"} def",
"~1s",
"/pdfIm1Sep {",
" /pdfImBuf1 4 index string def",
" /pdfImBuf2 4 index string def",
" /pdfImBuf3 4 index string def",
" /pdfImBuf4 4 index string def",
" { currentfile pdfImBuf1 readhexstring pop }",
" { currentfile pdfImBuf2 readhexstring pop }",
" { currentfile pdfImBuf3 readhexstring pop }",
" { currentfile pdfImBuf4 readhexstring pop }",
" true 4 colorimage",
"} def",
"~1ns",
"/pdfImM1 {",
" fCol /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",
"~23sn",
"% Level 2 image operators",
"/pdfImBuf 100 string def",
"/pdfIm {",
" image",
" { currentfile pdfImBuf readline",
" not { pop exit } if",
" (%-EOD-) eq { exit } if } loop",
"} def",
"~23s",
"/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 {",
" 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",
" not { pop exit } if",
" (%-EOD-) eq { exit } if } loop",
"} def",
"~23sn",
"/pdfImM {",
" fCol imagemask",
" { currentfile pdfImBuf readline",
" not { pop exit } if",
" (%-EOD-) eq { exit } if } loop",
"} def",
"/pr { 2 index 2 index 3 2 roll putinterval 4 add } def",
"/pdfImClip {",
" gsave",
" 0 2 4 index length 1 sub {",
" dup 4 index exch 2 copy",
" get 5 index div put",
" 1 add 3 index exch 2 copy",
" get 3 index div put",
" } for",
" pop pop rectclip",
"} def",
"/pdfImClipEnd { grestore } def",
"~23sn",
"% shading operators",
"/colordelta {",
" false 0 1 3 index length 1 sub {",
" dup 4 index exch get 3 index 3 2 roll get sub abs 0.004 gt {",
" pop true",
" } if",
" } for",
" exch pop exch pop",
"} def",
"/funcCol { func n array astore } def",
"/funcSH {",
" dup 0 eq {",
" true",
" } {",
" dup 6 eq {",
" false",
" } {",
" 4 index 4 index funcCol dup",
" 6 index 4 index funcCol dup",
" 3 1 roll colordelta 3 1 roll",
" 5 index 5 index funcCol dup",
" 3 1 roll colordelta 3 1 roll",
" 6 index 8 index funcCol dup",
" 3 1 roll colordelta 3 1 roll",
" colordelta or or or",
" } ifelse",
" } ifelse",
" {",
" 1 add",
" 4 index 3 index add 0.5 mul exch 4 index 3 index add 0.5 mul exch",
" 6 index 6 index 4 index 4 index 4 index funcSH",
" 2 index 6 index 6 index 4 index 4 index funcSH",
" 6 index 2 index 4 index 6 index 4 index funcSH",
" 5 3 roll 3 2 roll funcSH pop pop",
" } {",
" pop 3 index 2 index add 0.5 mul 3 index 2 index add 0.5 mul",
"~23n",
" funcCol sc",
"~23s",
" funcCol aload pop k",
"~23sn",
" dup 4 index exch mat transform m",
" 3 index 3 index mat transform l",
" 1 index 3 index mat transform l",
" mat transform l pop pop h f*",
" } ifelse",
"} def",
"/axialCol {",
" dup 0 lt {",
" pop t0",
" } {",
" dup 1 gt {",
" pop t1",
" } {",
" dt mul t0 add",
" } ifelse",
" } ifelse",
" func n array astore",
"} def",
"/axialSH {",
" dup 0 eq {",
" true",
" } {",
" dup 8 eq {",
" false",
" } {",
" 2 index axialCol 2 index axialCol colordelta",
" } ifelse",
" } ifelse",
" {",
" 1 add 3 1 roll 2 copy add 0.5 mul",
" dup 4 3 roll exch 4 index axialSH",
" exch 3 2 roll axialSH",
" } {",
" pop 2 copy add 0.5 mul",
"~23n",
" axialCol sc",
"~23s",
" axialCol aload pop k",
"~23sn",
" exch dup dx mul x0 add exch dy mul y0 add",
" 3 2 roll dup dx mul x0 add exch dy mul y0 add",
" dx abs dy abs ge {",
" 2 copy yMin sub dy mul dx div add yMin m",
" yMax sub dy mul dx div add yMax l",
" 2 copy yMax sub dy mul dx div add yMax l",
" yMin sub dy mul dx div add yMin l",
" h f*",
" } {",
" exch 2 copy xMin sub dx mul dy div add xMin exch m",
" xMax sub dx mul dy div add xMax exch l",
" exch 2 copy xMax sub dx mul dy div add xMax exch l",
" xMin sub dx mul dy div add xMin exch l",
" h f*",
" } ifelse",
" } ifelse",
"} def",
"/radialCol {",
" dup t0 lt {",
" pop t0",
" } {",
" dup t1 gt {",
" pop t1",
" } if",
" } ifelse",
" func n array astore",
"} def",
"/radialSH {",
" dup 0 eq {",
" true",
" } {",
" dup 8 eq {",
" false",
" } {",
" 2 index dt mul t0 add radialCol",
" 2 index dt mul t0 add radialCol colordelta",
" } ifelse",
" } ifelse",
" {",
" 1 add 3 1 roll 2 copy add 0.5 mul",
" dup 4 3 roll exch 4 index radialSH",
" exch 3 2 roll radialSH",
" } {",
" pop 2 copy add 0.5 mul dt mul t0 add",
"~23n",
" radialCol sc",
"~23s",
" radialCol aload pop k",
"~23sn",
" encl {",
" exch dup dx mul x0 add exch dup dy mul y0 add exch dr mul r0 add",
" 0 360 arc h",
" dup dx mul x0 add exch dup dy mul y0 add exch dr mul r0 add",
" 360 0 arcn h f",
" } {",
" 2 copy",
" dup dx mul x0 add exch dup dy mul y0 add exch dr mul r0 add",
" a1 a2 arcn",
" dup dx mul x0 add exch dup dy mul y0 add exch dr mul r0 add",
" a2 a1 arcn h",
" dup dx mul x0 add exch dup dy mul y0 add exch dr mul r0 add",
" a1 a2 arc",
" dup dx mul x0 add exch dup dy mul y0 add exch dr mul r0 add",
" a2 a1 arc h f",
" } ifelse",
" } ifelse",
"} def",
"~123sn",
"end",
NULL
};
static char *cmapProlog[] = {
"/CIDInit /ProcSet findresource begin",
"10 dict begin",
" begincmap",
" /CMapType 1 def",
" /CMapName /Identity-H def",
" /CIDSystemInfo 3 dict dup begin",
" /Registry (Adobe) def",
" /Ordering (Identity) def",
" /Supplement 0 def",
" end def",
" 1 begincodespacerange",
" <0000> <ffff>",
" endcodespacerange",
" 0 usefont",
" 1 begincidrange",
" <0000> <ffff> 0",
" endcidrange",
" endcmap",
" currentdict CMapName exch /CMap defineresource pop",
"end",
"10 dict begin",
" begincmap",
" /CMapType 1 def",
" /CMapName /Identity-V def",
" /CIDSystemInfo 3 dict dup begin",
" /Registry (Adobe) def",
" /Ordering (Identity) def",
" /Supplement 0 def",
" end def",
" /WMode 1 def",
" 1 begincodespacerange",
" <0000> <ffff>",
" endcodespacerange",
" 0 usefont",
" 1 begincidrange",
" <0000> <ffff> 0",
" endcidrange",
" endcmap",
" currentdict CMapName exch /CMap defineresource pop",
"end",
"end",
NULL
};
//------------------------------------------------------------------------
// Fonts
//------------------------------------------------------------------------
struct PSSubstFont {
char *psName; // PostScript name
double mWidth; // width of 'm' character
};
static const char *psFonts[] = {
"Courier",
"Courier-Bold",
"Courier-Oblique",
"Courier-BoldOblique",
"Helvetica",
"Helvetica-Bold",
"Helvetica-Oblique",
"Helvetica-BoldOblique",
"Symbol",
"Times-Roman",
"Times-Bold",
"Times-Italic",
"Times-BoldItalic",
"ZapfDingbats",
NULL
};
static const PSSubstFont psSubstFonts[] = {
{"Helvetica", 0.833},
{"Helvetica-Oblique", 0.833},
{"Helvetica-Bold", 0.889},
{"Helvetica-BoldOblique", 0.889},
{"Times-Roman", 0.788},
{"Times-Italic", 0.722},
{"Times-Bold", 0.833},
{"Times-BoldItalic", 0.778},
{"Courier", 0.600},
{"Courier-Oblique", 0.600},
{"Courier-Bold", 0.600},
{"Courier-BoldOblique", 0.600}
};
// Info for 8-bit fonts
struct PSFont8Info {
Ref fontID;
Gushort *codeToGID; // code-to-GID mapping for TrueType fonts
};
// Encoding info for substitute 16-bit font
struct PSFont16Enc {
Ref fontID;
GooString *enc;
};
//------------------------------------------------------------------------
// process colors
//------------------------------------------------------------------------
#define psProcessCyan 1
#define psProcessMagenta 2
#define psProcessYellow 4
#define psProcessBlack 8
#define psProcessCMYK 15
//------------------------------------------------------------------------
// PSOutCustomColor
//------------------------------------------------------------------------
class PSOutCustomColor {
public:
PSOutCustomColor(double cA, double mA,
double yA, double kA, GooString *nameA);
~PSOutCustomColor();
double c, m, y, k;
GooString *name;
PSOutCustomColor *next;
};
PSOutCustomColor::PSOutCustomColor(double cA, double mA,
double yA, double kA, GooString *nameA) {
c = cA;
m = mA;
y = yA;
k = kA;
name = nameA;
next = NULL;
}
PSOutCustomColor::~PSOutCustomColor() {
delete name;
}
//------------------------------------------------------------------------
struct PSOutImgClipRect {
int x0, x1, y0, y1;
};
//------------------------------------------------------------------------
// 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 GooString *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 x[gfxColorMaxComps], y[gfxColorMaxComps];
int i;
if (pixelIdx >= width * height) {
return gFalse;
}
imgStr->getPixel(pixBuf);
colorMap->getColor(pixBuf, &color);
for (i = 0;
i < ((GfxDeviceNColorSpace *)colorMap->getColorSpace())->getNComps();
++i) {
x[i] = colToDbl(color.c[i]);
}
func->transform(x, y);
for (i = 0; i < bufSize; ++i) {
buf[i] = (int)(y[i] * 255 + 0.5);
}
bufIdx = 0;
++pixelIdx;
return gTrue;
}
//------------------------------------------------------------------------
// PSOutputDev
//------------------------------------------------------------------------
extern "C" {
typedef void (*SignalFunc)(int);
}
static void outputToFile(void *stream, char *data, int len) {
fwrite(data, 1, len, (FILE *)stream);
}
PSOutputDev::PSOutputDev(const char *fileName, XRef *xrefA, Catalog *catalog,
char *psTitle,
int firstPage, int lastPage, PSOutMode modeA,
int paperWidthA, int paperHeightA, GBool duplexA,
int imgLLXA, int imgLLYA, int imgURXA, int imgURYA,
GBool forceRasterizeA,
GBool manualCtrlA) {
FILE *f;
PSFileType fileTypeA;
underlayCbk = NULL;
underlayCbkData = NULL;
overlayCbk = NULL;
overlayCbkData = NULL;
fontIDs = NULL;
fontFileIDs = NULL;
fontFileNames = NULL;
font8Info = NULL;
font16Enc = NULL;
imgIDs = NULL;
formIDs = NULL;
xobjStack = NULL;
embFontList = NULL;
customColors = NULL;
haveTextClip = gFalse;
haveCSPattern = gFalse;
t3String = NULL;
forceRasterize = forceRasterizeA;
// open file or pipe
if (!strcmp(fileName, "-")) {
fileTypeA = psStdout;
f = stdout;
} else if (fileName[0] == '|') {
fileTypeA = psPipe;
#ifdef HAVE_POPEN
#ifndef _WIN32
signal(SIGPIPE, (SignalFunc)SIG_IGN);
#endif
if (!(f = popen(fileName + 1, "w"))) {
error(-1, "Couldn't run print command '%s'", fileName);
ok = gFalse;
return;
}
#else
error(-1, "Print commands are not supported ('%s')", fileName);
ok = gFalse;
return;
#endif
} else {
fileTypeA = psFile;
if (!(f = fopen(fileName, "w"))) {
error(-1, "Couldn't open PostScript file '%s'", fileName);
ok = gFalse;
return;
}
}
init(outputToFile, f, fileTypeA, psTitle,
xrefA, catalog, firstPage, lastPage, modeA,
imgLLXA, imgLLYA, imgURXA, imgURYA, manualCtrlA,
paperWidthA, paperHeightA, duplexA);
}
PSOutputDev::PSOutputDev(PSOutputFunc outputFuncA, void *outputStreamA,
char *psTitle,
XRef *xrefA, Catalog *catalog,
int firstPage, int lastPage, PSOutMode modeA,
int paperWidthA, int paperHeightA, GBool duplexA,
int imgLLXA, int imgLLYA, int imgURXA, int imgURYA,
GBool forceRasterizeA,
GBool manualCtrlA) {
underlayCbk = NULL;
underlayCbkData = NULL;
overlayCbk = NULL;
overlayCbkData = NULL;
fontIDs = NULL;
fontFileIDs = NULL;
fontFileNames = NULL;
font8Info = NULL;
font16Enc = NULL;
imgIDs = NULL;
formIDs = NULL;
xobjStack = NULL;
embFontList = NULL;
customColors = NULL;
haveTextClip = gFalse;
haveCSPattern = gFalse;
t3String = NULL;
forceRasterize = forceRasterizeA;
init(outputFuncA, outputStreamA, psGeneric, psTitle,
xrefA, catalog, firstPage, lastPage, modeA,
imgLLXA, imgLLYA, imgURXA, imgURYA, manualCtrlA,
paperWidthA, paperHeightA, duplexA);
}
void PSOutputDev::init(PSOutputFunc outputFuncA, void *outputStreamA,
PSFileType fileTypeA, char *pstitle, XRef *xrefA, Catalog *catalog,
int firstPage, int lastPage, PSOutMode modeA,
int imgLLXA, int imgLLYA, int imgURXA, int imgURYA,
GBool manualCtrlA, int paperWidthA, int paperHeightA,
GBool duplexA) {
Page *page;
PDFRectangle *box;
// initialize
displayText = gTrue;
ok = gTrue;
outputFunc = outputFuncA;
outputStream = outputStreamA;
fileType = fileTypeA;
m_catalog = catalog;
xref = xrefA;
level = globalParams->getPSLevel();
mode = modeA;
paperWidth = paperWidthA;
paperHeight = paperHeightA;
imgLLX = imgLLXA;
imgLLY = imgLLYA;
imgURX = imgURXA;
imgURY = imgURYA;
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)ceil(page->getMediaWidth());
paperHeight = (int)ceil(page->getMediaHeight());
} else {
paperWidth = 1;
paperHeight = 1;
}
}
substFonts = globalParams->getPSSubstFonts();
preload = globalParams->getPSPreload();
if (imgLLX == 0 && imgURX == 0 && imgLLY == 0 && imgURY == 0) {
imgLLX = imgLLY = 0;
imgURX = paperWidth;
imgURY = paperHeight;
}
if (imgLLX == 0 && imgURX == 0 && imgLLY == 0 && imgURY == 0) {
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 = -1;
xScale0 = yScale0 = 0;
rotate0 = -1;
clipLLX0 = clipLLY0 = 0;
clipURX0 = clipURY0 = -1;
// initialize fontIDs, fontFileIDs, and fontFileNames lists
fontIDSize = 64;
fontIDLen = 0;
fontIDs = (Ref *)gmallocn(fontIDSize, sizeof(Ref));
fontFileIDSize = 64;
fontFileIDLen = 0;
fontFileIDs = (Ref *)gmallocn(fontFileIDSize, sizeof(Ref));
fontFileNameSize = 64;
fontFileNameLen = 0;
fontFileNames = (GooString **)gmallocn(fontFileNameSize, sizeof(GooString *));
psFileNames = (GooString **)gmallocn(fontFileNameSize, sizeof(GooString *));
nextTrueTypeNum = 0;
font8InfoLen = 0;
font8InfoSize = 0;
font16EncLen = 0;
font16EncSize = 0;
imgIDLen = 0;
imgIDSize = 0;
formIDLen = 0;
formIDSize = 0;
xobjStack = new GooList();
numSaves = 0;
numTilingPatterns = 0;
nextFunc = 0;
// initialize embedded font resource comment list
embFontList = new GooString();
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)->getMediaBox(),
catalog->getPage(firstPage)->getCropBox(),
catalog->getPage(firstPage)->getRotate(),
pstitle);
} else {
box = new PDFRectangle(0, 0, 1, 1);
writeHeader(firstPage, lastPage, box, box, 0, pstitle);
delete box;
}
if (mode != psModeForm) {
writePS("%%BeginProlog\n");
}
writeXpdfProcset();
if (mode != psModeForm) {
writePS("%%EndProlog\n");
writePS("%%BeginSetup\n");
}
writeDocSetup(catalog, firstPage, lastPage, duplexA);
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 (font8Info) {
for (i = 0; i < font8InfoLen; ++i) {
gfree(font8Info[i].codeToGID);
}
gfree(font8Info);
}
if (psFileNames) {
for (i = 0; i < fontFileNameLen; ++i) {
if (psFileNames[i])
delete psFileNames[i];
}
gfree(psFileNames);
}
if (font16Enc) {
for (i = 0; i < font16EncLen; ++i) {
delete font16Enc[i].enc;
}
gfree(font16Enc);
}
gfree(imgIDs);
gfree(formIDs);
if (xobjStack) {
delete xobjStack;
}
while (customColors) {
cc = customColors;
customColors = cc->next;
delete cc;
}
}
void PSOutputDev::writeHeader(int firstPage, int lastPage,
PDFRectangle *mediaBox, PDFRectangle *cropBox,
int pageRotate, char *psTitle) {
double x1, y1, x2, y2;
Object info, obj1;
switch (mode) {
case psModePSOrigPageSizes:
case psModePS:
writePS("%!PS-Adobe-3.0\n");
break;
case psModeEPS:
writePS("%!PS-Adobe-3.0 EPSF-3.0\n");
break;
case psModeForm:
writePS("%!PS-Adobe-3.0 Resource-Form\n");
break;
}
xref->getDocInfo(&info);
if (info.isDict() && info.dictLookup("Creator", &obj1)->isString()) {
writePS("%%Creator: ");
writePSTextLine(obj1.getString());
}
obj1.free();
info.free();
if(psTitle) {
writePSFmt("%%Title: {0:s}\n", psTitle);
}
writePSFmt("%%LanguageLevel: {0:d}\n",
(level == psLevel1 || level == psLevel1Sep) ? 1 :
(level == psLevel2 || level == psLevel2Sep) ? 2 : 3);
if (level == psLevel1Sep || level == psLevel2Sep || level == psLevel3Sep) {
writePS("%%DocumentProcessColors: (atend)\n");
writePS("%%DocumentCustomColors: (atend)\n");
}
writePS("%%DocumentSuppliedResources: (atend)\n");
switch (mode) {
case psModePSOrigPageSizes:
prevWidth = 0;
prevHeight = 0;
case psModePS:
writePSFmt("%%DocumentMedia: plain {0:d} {1:d} 0 () ()\n",
paperWidth, paperHeight);
writePSFmt("%%BoundingBox: 0 0 {0:d} {1:d}\n", paperWidth, paperHeight);
writePSFmt("%%Pages: {0:d}\n", lastPage - firstPage + 1);
writePS("%%EndComments\n");
writePS("%%BeginDefaults\n");
writePS("%%PageMedia: plain\n");
writePS("%%EndDefaults\n");
break;
case psModeEPS:
epsX1 = cropBox->x1;
epsY1 = cropBox->y1;
epsX2 = cropBox->x2;
epsY2 = cropBox->y2;
if (pageRotate == 0 || pageRotate == 180) {
x1 = epsX1;
y1 = epsY1;
x2 = epsX2;
y2 = epsY2;
} else { // pageRotate == 90 || pageRotate == 270
x1 = 0;
y1 = 0;
x2 = epsY2 - epsY1;
y2 = epsX2 - epsX1;
}
writePSFmt("%%BoundingBox: {0:d} {1:d} {2:d} {3:d}\n",
(int)floor(x1), (int)floor(y1), (int)ceil(x2), (int)ceil(y2));
if (floor(x1) != ceil(x1) || floor(y1) != ceil(y1) ||
floor(x2) != ceil(x2) || floor(y2) != ceil(y2)) {
writePSFmt("%%HiResBoundingBox: {0:.4g} {1:.4g} {2:.4g} {3:.4g}\n",
x1, y1, x2, y2);
}
writePS("%%DocumentSuppliedResources: (atend)\n");
writePS("%%EndComments\n");
break;
case psModeForm:
writePS("%%EndComments\n");
writePS("32 dict dup begin\n");
writePSFmt("/BBox [{0:d} {1:d} {2:d} {3: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;
}
}
void PSOutputDev::writeXpdfProcset() {
GBool lev1, lev2, lev3, sep, nonSep;
char **p;
char *q;
writePSFmt("%%BeginResource: procset xpdf {0:s} 0\n", "3.00");
writePSFmt("%%Copyright: {0:s}\n", xpdfCopyright);
lev1 = lev2 = lev3 = sep = nonSep = gTrue;
for (p = prolog; *p; ++p) {
if ((*p)[0] == '~') {
lev1 = lev2 = lev3 = sep = nonSep = gFalse;
for (q = *p + 1; *q; ++q) {
switch (*q) {
case '1': lev1 = gTrue; break;
case '2': lev2 = gTrue; break;
case '3': lev3 = gTrue; break;
case 's': sep = gTrue; break;
case 'n': nonSep = gTrue; break;
}
}
} else if ((level == psLevel1 && lev1 && nonSep) ||
(level == psLevel1Sep && lev1 && sep) ||
(level == psLevel2 && lev2 && nonSep) ||
(level == psLevel2Sep && lev2 && sep) ||
(level == psLevel3 && lev3 && nonSep) ||
(level == psLevel3Sep && lev3 && sep)) {
writePSFmt("{0:s}\n", *p);
}
}
writePS("%%EndResource\n");
if (level >= psLevel3) {
for (p = cmapProlog; *p; ++p) {
writePSFmt("{0:s}\n", *p);
}
}
}
void PSOutputDev::writeDocSetup(Catalog *catalog,
int firstPage, int lastPage,
GBool duplexA) {
Page *page;
Dict *resDict;
Annots *annots;
Object obj1, obj2;
int pg, i;
if (mode == psModeForm) {
// swap the form and xpdf dicts
writePS("xpdf end begin dup begin\n");
} else {
writePS("xpdf begin\n");
}
for (pg = firstPage; pg <= lastPage; ++pg) {
page = catalog->getPage(pg);
if ((resDict = page->getResourceDict())) {
setupResources(resDict);
}
annots = new Annots(xref, catalog, page->getAnnots(&obj1));
obj1.free();
for (i = 0; i < annots->getNumAnnots(); ++i) {
if (annots->getAnnot(i)->getAppearance(&obj1)->isStream()) {
obj1.streamGetDict()->lookup("Resources", &obj2);
if (obj2.isDict()) {
setupResources(obj2.getDict());
}
obj2.free();
}
obj1.free();
}
delete annots;
}
if (mode != psModeForm) {
if (mode != psModeEPS && !manualCtrl) {
writePSFmt("{0:d} {1:d} {2:s} pdfSetup\n",
paperWidth, paperHeight, duplexA ? "true" : "false");
}
#if OPI_SUPPORT
if (globalParams->getPSOPI()) {
writePS("/opiMatrix matrix currentmatrix def\n");
}
#endif
}
}
void PSOutputDev::writePageTrailer() {
if (mode != psModeForm) {
writePS("pdfEndPage\n");
}
}
void PSOutputDev::writeTrailer() {
PSOutCustomColor *cc;
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");
}
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(" ({0:s})", cc->name->getCString());
}
writePS("\n");
writePS("%%CMYKCustomColor:\n");
for (cc = customColors; cc; cc = cc->next) {
writePSFmt("%%+ {0:.4g} {1:.4g} {2:.4g} {3:.4g} ({4:t})\n",
cc->c, cc->m, cc->y, cc->k, cc->name);
}
}
}
}
void PSOutputDev::setupResources(Dict *resDict) {
Object xObjDict, xObjRef, xObj, patDict, patRef, pat, resObj;
Ref ref0, ref1;
GBool skip;
int i, j;
setupFonts(resDict);
setupImages(resDict);
setupForms(resDict);
//----- recursively scan XObjects
resDict->lookup("XObject", &xObjDict);
if (xObjDict.isDict()) {
for (i = 0; i < xObjDict.dictGetLength(); ++i) {
// 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);
}
}
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();
//----- recursively scan Patterns
resDict->lookup("Pattern", &patDict);
if (patDict.isDict()) {
inType3Char = gTrue;
for (i = 0; i < patDict.dictGetLength(); ++i) {
// avoid infinite recursion on Patterns
skip = gFalse;
if ((patDict.dictGetValNF(i, &patRef)->isRef())) {
ref0 = patRef.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);
}
}
if (!skip) {
// process the Pattern's resource dictionary
patDict.dictGetVal(i, &pat);
if (pat.isStream()) {
pat.streamGetDict()->lookup("Resources", &resObj);
if (resObj.isDict()) {
setupResources(resObj.getDict());
}
resObj.free();
}
pat.free();
}
if (patRef.isRef() && !skip) {
xobjStack->del(xobjStack->getLength() - 1);
}
patRef.free();
}
inType3Char = gFalse;
}
patDict.free();
}
void PSOutputDev::setupFonts(Dict *resDict) {
Object obj1, obj2;
Ref r;
GfxFontDict *gfxFontDict;
GfxFont *font;
int i;
if (forceRasterize) return;
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) {
if ((font = gfxFontDict->getFont(i))) {
setupFont(font, resDict);
}
}
delete gfxFontDict;
}
obj1.free();
}
void PSOutputDev::setupFont(GfxFont *font, Dict *parentResDict) {
Ref fontFileID;
GooString *name;
PSFontParam *fontParam;
GooString *psName;
char buf[16];
GBool subst;
UnicodeMap *uMap;
char *charName;
double xs, ys;
int code;
double w1, w2;
double *fm;
int i, j;
DisplayFontParam *dfp;
// check if font is already set up
for (i = 0; i < fontIDLen; ++i) {
if (fontIDs[i].num == font->getID()->num &&
fontIDs[i].gen == font->getID()->gen) {
return;
}
}
// add entry to fontIDs list
if (fontIDLen >= fontIDSize) {
fontIDSize += 64;
fontIDs = (Ref *)greallocn(fontIDs, fontIDSize, sizeof(Ref));
}
fontIDs[fontIDLen++] = *font->getID();
xs = ys = 1;
subst = gFalse;
// check for resident 8-bit font
if (font->getName() &&
(fontParam = globalParams->getPSFont(font->getName()))) {
psName = new GooString(fontParam->psFontName->getCString());
// check for embedded Type 1 font
} else if (globalParams->getPSEmbedType1() &&
font->getType() == fontType1 &&
font->getEmbeddedFontID(&fontFileID) &&
font->getEmbeddedFontName()) {
psName = font->getEmbeddedFontName()->sanitizedName(gTrue /* ps mode */);
setupEmbeddedType1Font(&fontFileID, psName);
// check for embedded Type 1C font
} else if (globalParams->getPSEmbedType1() &&
font->getType() == fontType1C &&
font->getEmbeddedFontID(&fontFileID) &&
font->getOrigName()) {
// use the PDF font name because the embedded font name might
// not include the subset prefix
psName = font->getOrigName()->sanitizedName(gTrue /* ps mode */);
setupEmbeddedType1CFont(font, &fontFileID, psName);
// check for embedded OpenType - Type 1C font
} else if (globalParams->getPSEmbedType1() &&
font->getType() == fontType1COT &&
font->getEmbeddedFontID(&fontFileID) &&
font->getOrigName()) {
// use the PDF font name because the embedded font name might
// not include the subset prefix
psName = font->getOrigName()->sanitizedName(gTrue /* ps mode */);
setupEmbeddedOpenTypeT1CFont(font, &fontFileID, psName);
// check for external Type 1 font file
} else if (globalParams->getPSEmbedType1() &&
font->getType() == fontType1 &&
font->getExtFontFile() &&
font->getName()) {
// this assumes that the PS font name matches the PDF font name
psName = font->getName()->copy();
setupExternalType1Font(font->getExtFontFile(), psName);
// check for embedded TrueType font
} else if (globalParams->getPSEmbedTrueType() &&
(font->getType() == fontTrueType ||
font->getType() == fontTrueTypeOT) &&
font->getEmbeddedFontID(&fontFileID) &&
font->getEmbeddedFontName()) {
psName = font->getEmbeddedFontName()->sanitizedName(gTrue /* ps mode */);
setupEmbeddedTrueTypeFont(font, &fontFileID, psName);
// check for external TrueType font file
} else if (globalParams->getPSEmbedTrueType() &&
font->getType() == fontTrueType &&
font->getExtFontFile()) {
psName = setupExternalTrueTypeFont(font);
// check for embedded CID PostScript font
} else if (globalParams->getPSEmbedCIDPostScript() &&
font->getType() == fontCIDType0C &&
font->getEmbeddedFontID(&fontFileID) &&
font->getEmbeddedFontName()) {
psName = font->getEmbeddedFontName()->sanitizedName(gTrue /* ps mode */);
setupEmbeddedCIDType0Font(font, &fontFileID, psName);
// check for embedded CID TrueType font
} else if (globalParams->getPSEmbedCIDTrueType() &&
(font->getType() == fontCIDType2 ||
font->getType() == fontCIDType2OT) &&
font->getEmbeddedFontID(&fontFileID) &&
font->getEmbeddedFontName()) {
psName = font->getEmbeddedFontName()->sanitizedName(gTrue /* ps mode */);
setupEmbeddedCIDTrueTypeFont(font, &fontFileID, psName, gTrue);
// check for embedded OpenType - CID CFF font
} else if (globalParams->getPSEmbedCIDPostScript() &&
font->getType() == fontCIDType0COT &&
font->getEmbeddedFontID(&fontFileID) &&
font->getEmbeddedFontName()) {
psName = font->getEmbeddedFontName()->sanitizedName(gTrue /* ps mode */);
setupEmbeddedOpenTypeCFFFont(font, &fontFileID, psName);
// check for Type 3 font
} else if (font->getType() == fontType3) {
psName = GooString::format("T3_{0:d}_{1:d}",
font->getID()->num, font->getID()->gen);
setupType3Font(font, psName, parentResDict);
// check for external CID TrueType font file
} else if (globalParams->getPSEmbedCIDTrueType() &&
font->getType() == fontCIDType2 &&
font->getExtFontFile()) {
psName = setupExternalCIDTrueTypeFont(font, font->getExtFontFile());
// 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) {
psName = new GooString(psFonts[i]);
break;
}
}
}
if (!psName) {
if (substFonts) {
if (font->isFixedWidth()) {
i = 8;
} else if (font->isSerif()) {
i = 4;
} else {
i = 0;
}
if (font->isBold()) {
i += 2;
}
if (font->isItalic()) {
i += 1;
}
psName = new GooString(psSubstFonts[i].psName);
for (code = 0; code < 256; ++code) {
if ((charName = ((Gfx8BitFont *)font)->getCharName(code)) &&
charName[0] == 'm' && charName[1] == '\0') {
break;
}
}
if (code < 256) {
w1 = ((Gfx8BitFont *)font)->getWidth(code);
} else {
w1 = 0;
}
w2 = psSubstFonts[i].mWidth;
xs = w1 / w2;
if (xs < 0.1) {
xs = 1;
}
} else {
psName = new GooString(name);
xs = 1;
}
if (font->getType() == fontType3) {
// This is a hack which makes it possible to substitute for some
// Type 3 fonts. The problem is that it's impossible to know what
// the base coordinate system used in the font is without actually
// rendering the font.
ys = xs;
fm = font->getFontMatrix();
if (fm[0] != 0) {
ys *= fm[3] / fm[0];
}
} else {
ys = 1;
}
}
// do 16-bit font substitution
} else if ((fontParam = globalParams->
getPSFont16(font->getName(),
((GfxCIDFont *)font)->getCollection(),
font->getWMode()))) {
subst = gTrue;
psName = fontParam->psFontName->copy();
if (font16EncLen >= font16EncSize) {
font16EncSize += 16;
font16Enc = (PSFont16Enc *)greallocn(font16Enc,
font16EncSize, sizeof(PSFont16Enc));
}
font16Enc[font16EncLen].fontID = *font->getID();
font16Enc[font16EncLen].enc = fontParam->encoding->copy();
if ((uMap = globalParams->getUnicodeMap(font16Enc[font16EncLen].enc))) {
uMap->decRefCnt();
++font16EncLen;
} else {
error(-1, "Couldn't find Unicode map for 16-bit font encoding '%s'",
font16Enc[font16EncLen].enc->getCString());
}
// try the display font for embedding
} else if (globalParams->getPSEmbedCIDTrueType() &&
((GfxCIDFont *)font)->getCollection() &&
(dfp = globalParams->
getDisplayFont(font)) &&
dfp->kind == displayFontTT) {
psName = setupExternalCIDTrueTypeFont(font, dfp->tt.fileName, dfp->tt.faceIndex);
// give up - can't do anything with this font
} else {
error(-1, "Couldn't find a font to substitute for '%s' ('%s' character collection)",
font->getName() ? font->getName()->getCString() : "(unnamed)",
((GfxCIDFont *)font)->getCollection()
? ((GfxCIDFont *)font)->getCollection()->getCString()
: "(unknown)");
return;
}
// generate PostScript code to set up the font
if (font->isCIDFont()) {
if (level == psLevel3 || level == psLevel3Sep) {
writePSFmt("/F{0:d}_{1:d} /{2:t} {3:d} pdfMakeFont16L3\n",
font->getID()->num, font->getID()->gen, psName,
font->getWMode());
} else {
writePSFmt("/F{0:d}_{1:d} /{2:t} {3:d} pdfMakeFont16\n",
font->getID()->num, font->getID()->gen, psName,
font->getWMode());
}
} else {
writePSFmt("/F{0:d}_{1:d} /{2:t} {3:.4g} {4:.4g}\n",
font->getID()->num, font->getID()->gen, psName, xs, ys);
for (i = 0; i < 256; i += 8) {
writePS((char *)((i == 0) ? "[ " : " "));
for (j = 0; j < 8; ++j) {
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("/");
writePSName(charName ? charName : (char *)".notdef");
// the empty name is legal in PDF and PostScript, but PostScript
// uses a double-slash (//...) for "immediately evaluated names",
// so we need to add a space character here
if (charName && !charName[0]) {
writePS(" ");
}
}
writePS((i == 256-8) ? (char *)"]\n" : (char *)"\n");
}
writePS("pdfMakeFont\n");
}
delete psName;
}
void PSOutputDev::setupEmbeddedType1Font(Ref *id, GooString *psName) {
static const char hexChar[17] = "0123456789abcdef";
Object refObj, strObj, obj1, obj2, obj3;
Dict *dict;
int length1, length2, length3;
int c;
int start[4];
GBool binMode;
GBool writePadding = gTrue;
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;
}
// add entry to fontFileIDs list
if (fontFileIDLen >= fontFileIDSize) {
fontFileIDSize += 64;
fontFileIDs = (Ref *)greallocn(fontFileIDs, fontFileIDSize, sizeof(Ref));
}
fontFileIDs[fontFileIDLen++] = *id;
// get the font stream and info
refObj.initRef(id->num, id->gen);
refObj.fetch(xref, &strObj);
refObj.free();
if (!strObj.isStream()) {
error(-1, "Embedded font file object is not a stream");
goto err1;
}
if (!(dict = strObj.streamGetDict())) {
error(-1, "Embedded font stream is missing its dictionary");
goto err1;
}
dict->lookup("Length1", &obj1);
dict->lookup("Length2", &obj2);
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();
obj3.free();
goto err1;
}
length1 = obj1.getInt();
length2 = obj2.getInt();
length3 = obj3.getInt();
obj1.free();
obj2.free();
obj3.free();
// beginning comment
writePSFmt("%%BeginResource: font {0:t}\n", psName);
embFontList->append("%%+ font ");
embFontList->append(psName->getCString());
embFontList->append("\n");
// copy ASCII portion of font
strObj.streamReset();
for (i = 0; i < length1 && (c = strObj.streamGetChar()) != EOF; ++i) {
writePSChar(c);
}
// figure out if encrypted portion is binary or ASCII
binMode = gFalse;
for (i = 0; i < 4; ++i) {
start[i] = strObj.streamGetChar();
if (start[i] == EOF) {
error(-1, "Unexpected end of file in embedded font stream");
goto err1;
}
if (!((start[i] >= '0' && start[i] <= '9') ||
(start[i] >= 'A' && start[i] <= 'F') ||
(start[i] >= 'a' && start[i] <= 'f')))
binMode = gTrue;
}
if (length2 == 0)
{
// length2 == 0 is an error
// trying to solve it by just piping all
// the stream data
error(-1, "Font has length2 as 0, trying to overcome the problem reading the stream until the end");
length2 = INT_MAX;
writePadding = gFalse;
}
// convert binary data to ASCII
if (binMode) {
for (i = 0; i < 4; ++i) {
writePSChar(hexChar[(start[i] >> 4) & 0x0f]);
writePSChar(hexChar[start[i] & 0x0f]);
}
#if 0 // this causes trouble for various PostScript printers
// 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;
#endif
while (i < length2) {
if ((c = strObj.streamGetChar()) == EOF) {
break;
}
writePSChar(hexChar[(c >> 4) & 0x0f]);
writePSChar(hexChar[c & 0x0f]);
if (++i % 32 == 0) {
writePSChar('\n');
}
}
if (i % 32 > 0) {
writePSChar('\n');
}
// already in ASCII format -- just copy it
} else {
for (i = 0; i < 4; ++i) {
writePSChar(start[i]);
}
for (i = 4; i < length2; ++i) {
if ((c = strObj.streamGetChar()) == EOF) {
break;
}
writePSChar(c);
}
}
if (writePadding)
{
// write padding and "cleartomark"
for (i = 0; i < 8; ++i) {
writePS("00000000000000000000000000000000"
"00000000000000000000000000000000\n");
}
writePS("cleartomark\n");
}
// ending comment
writePS("%%EndResource\n");
err1:
strObj.streamClose();
strObj.free();
}
//~ This doesn't handle .pfb files or binary eexec data (which only
//~ happens in pfb files?).
void PSOutputDev::setupExternalType1Font(GooString *fileName, GooString *psName) {
FILE *fontFile;
int c;
int i;
// check if font is already embedded
for (i = 0; i < fontFileNameLen; ++i) {
if (!fontFileNames[i]->cmp(fileName)) {
return;
}
}
// add entry to fontFileNames list
if (fontFileNameLen >= fontFileNameSize) {
fontFileNameSize += 64;
fontFileNames = (GooString **)greallocn(fontFileNames,
fontFileNameSize, sizeof(GooString *));
psFileNames = (GooString **)greallocn(psFileNames,
fontFileNameSize, sizeof(GooString *));
}
fontFileNames[fontFileNameLen] = fileName->copy();
psFileNames[fontFileNameLen] = psName->copy();
fontFileNameLen++;
// beginning comment
writePSFmt("%%BeginResource: font {0:t}\n", psName);
embFontList->append("%%+ font ");
embFontList->append(psName->getCString());
embFontList->append("\n");
// copy the font file
if (!(fontFile = fopen(fileName->getCString(), "rb"))) {
error(-1, "Couldn't open external font file");
return;
}
while ((c = fgetc(fontFile)) != EOF) {
writePSChar(c);
}
fclose(fontFile);
// ending comment
writePS("%%EndResource\n");
}
void PSOutputDev::setupEmbeddedType1CFont(GfxFont *font, Ref *id,
GooString *psName) {
char *fontBuf;
int fontLen;
FoFiType1C *ffT1C;
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;
}
// add entry to fontFileIDs list
if (fontFileIDLen >= fontFileIDSize) {
fontFileIDSize += 64;
fontFileIDs = (Ref *)greallocn(fontFileIDs, fontFileIDSize, sizeof(Ref));
}
fontFileIDs[fontFileIDLen++] = *id;
// beginning comment
writePSFmt("%%BeginResource: font {0:t}\n", psName);
embFontList->append("%%+ font ");
embFontList->append(psName->getCString());
embFontList->append("\n");
// convert it to a Type 1 font
fontBuf = font->readEmbFontFile(xref, &fontLen);
if ((ffT1C = FoFiType1C::make(fontBuf, fontLen))) {
ffT1C->convertToType1(psName->getCString(), NULL, gTrue,
outputFunc, outputStream);
delete ffT1C;
}
gfree(fontBuf);
// ending comment
writePS("%%EndResource\n");
}
void PSOutputDev::setupEmbeddedOpenTypeT1CFont(GfxFont *font, Ref *id,
GooString *psName) {
char *fontBuf;
int fontLen;
FoFiTrueType *ffTT;
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;
}
// add entry to fontFileIDs list
if (fontFileIDLen >= fontFileIDSize) {
fontFileIDSize += 64;
fontFileIDs = (Ref *)greallocn(fontFileIDs, fontFileIDSize, sizeof(Ref));
}
fontFileIDs[fontFileIDLen++] = *id;
// beginning comment
writePSFmt("%%BeginResource: font {0:t}\n", psName);
embFontList->append("%%+ font ");
embFontList->append(psName->getCString());
embFontList->append("\n");
// convert it to a Type 1 font
fontBuf = font->readEmbFontFile(xref, &fontLen);
if ((ffTT = FoFiTrueType::make(fontBuf, fontLen))) {
if (ffTT->isOpenTypeCFF()) {
ffTT->convertToType1(psName->getCString(), NULL, gTrue,
outputFunc, outputStream);
}
delete ffTT;
}
gfree(fontBuf);
// ending comment
writePS("%%EndResource\n");
}
void PSOutputDev::setupEmbeddedTrueTypeFont(GfxFont *font, Ref *id,
GooString *psName) {
char *fontBuf;
int fontLen;
FoFiTrueType *ffTT;
Gushort *codeToGID;
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) {
psName->appendf("_{0:d}", nextTrueTypeNum++);
break;
}
}
// add entry to fontFileIDs list
if (i == fontFileIDLen) {
if (fontFileIDLen >= fontFileIDSize) {
fontFileIDSize += 64;
fontFileIDs = (Ref *)greallocn(fontFileIDs, fontFileIDSize, sizeof(Ref));
}
fontFileIDs[fontFileIDLen++] = *id;
}
// beginning comment
writePSFmt("%%BeginResource: font {0:t}\n", psName);
embFontList->append("%%+ font ");
embFontList->append(psName->getCString());
embFontList->append("\n");
// convert it to a Type 42 font
fontBuf = font->readEmbFontFile(xref, &fontLen);
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);
if (codeToGID) {
if (font8InfoLen >= font8InfoSize) {
font8InfoSize += 16;
font8Info = (PSFont8Info *)greallocn(font8Info,
font8InfoSize,
sizeof(PSFont8Info));
}
font8Info[font8InfoLen].fontID = *font->getID();
font8Info[font8InfoLen].codeToGID = codeToGID;
++font8InfoLen;
}
delete ffTT;
}
gfree(fontBuf);
// ending comment
writePS("%%EndResource\n");
}
GooString *PSOutputDev::setupExternalTrueTypeFont(GfxFont *font) {
GooString *fileName;
char *fontBuf;
int fontLen;
FoFiTrueType *ffTT;
Gushort *codeToGID;
GooString *psName;
int i;
// check if font is already embedded
fileName = font->getExtFontFile();
for (i = 0; i < fontFileNameLen; ++i) {
if (!fontFileNames[i]->cmp(fileName)) {
return psFileNames[i]->copy();
}
}
psName = font->getName()->sanitizedName(gTrue /* ps mode */);
// add entry to fontFileNames list
if (i == fontFileNameLen) {
if (fontFileNameLen >= fontFileNameSize) {
fontFileNameSize += 64;
fontFileNames =
(GooString **)greallocn(fontFileNames,
fontFileNameSize, sizeof(GooString *));
psFileNames =
(GooString **)greallocn(psFileNames,
fontFileNameSize, sizeof(GooString *));
}
fontFileNames[fontFileNameLen] = fileName->copy();
psFileNames[fontFileNameLen] = psName->copy();
fontFileNameLen++;
}
// beginning comment
writePSFmt("%%BeginResource: font {0:t}\n", psName);
embFontList->append("%%+ font ");
embFontList->append(psName->getCString());
embFontList->append("\n");
// convert it to a Type 42 font
fontBuf = font->readExtFontFile(&fontLen);
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);
if (codeToGID) {
if (font8InfoLen >= font8InfoSize) {
font8InfoSize += 16;
font8Info = (PSFont8Info *)greallocn(font8Info,
font8InfoSize,
sizeof(PSFont8Info));
}
font8Info[font8InfoLen].fontID = *font->getID();
font8Info[font8InfoLen].codeToGID = codeToGID;
++font8InfoLen;
}
delete ffTT;
}
gfree(fontBuf);
// ending comment
writePS("%%EndResource\n");
return psName;
}
GooString *PSOutputDev::setupExternalCIDTrueTypeFont(GfxFont *font, GooString *fileName, int faceIndex) {
FoFiTrueType *ffTT;
Gushort *codeToGID;
GooString *psName;
int i;
GooString *myFileName;
myFileName = fileName->copy();
if (faceIndex > 0) {
char tmp[32];
sprintf(tmp, ",%d", faceIndex);
myFileName->append(tmp);
}
// check if font is already embedded
for (i = 0; i < fontFileNameLen; ++i) {
if (!fontFileNames[i]->cmp(myFileName)) {
delete myFileName;
return psFileNames[i]->copy();
}
}
psName = font->getName()->sanitizedName(gTrue /* ps mode */);
// add entry to fontFileNames list
if (i == fontFileNameLen) {
if (fontFileNameLen >= fontFileNameSize) {
fontFileNameSize += 64;
fontFileNames =
(GooString **)grealloc(fontFileNames,
fontFileNameSize * sizeof(GooString *));
psFileNames =
(GooString **)grealloc(psFileNames,
fontFileNameSize * sizeof(GooString *));
}
}
fontFileNames[fontFileNameLen] = myFileName;
psFileNames[fontFileNameLen] = psName->copy();
fontFileNameLen++;
// beginning comment
writePSFmt("%%BeginResource: font {0:t}\n", psName);
embFontList->append("%%+ font ");
embFontList->append(psName->getCString());
embFontList->append("\n");
// convert it to a CID type2 font
if ((ffTT = FoFiTrueType::load(fileName->getCString(), faceIndex))) {
int n = ((GfxCIDFont *)font)->getCIDToGIDLen();
if (n) {
codeToGID = (Gushort *)gmallocn(n, sizeof(Gushort));
memcpy(codeToGID, ((GfxCIDFont *)font)->getCIDToGID(), n * sizeof(Gushort));
} else {
codeToGID = ((GfxCIDFont *)font)->getCodeToGIDMap(ffTT, &n);
}
if (globalParams->getPSLevel() >= psLevel3) {
// Level 3: use a CID font
ffTT->convertToCIDType2(psName->getCString(),
codeToGID, n, gTrue,
outputFunc, outputStream);
} else {
// otherwise: use a non-CID composite font
ffTT->convertToType0(psName->getCString(),
codeToGID, n, gTrue,
outputFunc, outputStream);
}
gfree(codeToGID);
delete ffTT;
}
// ending comment
writePS("%%EndResource\n");
return psName;
}
void PSOutputDev::setupEmbeddedCIDType0Font(GfxFont *font, Ref *id,
GooString *psName) {
char *fontBuf;
int fontLen;
FoFiType1C *ffT1C;
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;
}
// add entry to fontFileIDs list
if (fontFileIDLen >= fontFileIDSize) {
fontFileIDSize += 64;
fontFileIDs = (Ref *)greallocn(fontFileIDs, fontFileIDSize, sizeof(Ref));
}
fontFileIDs[fontFileIDLen++] = *id;
// beginning comment
writePSFmt("%%BeginResource: font {0:t}\n", psName);
embFontList->append("%%+ font ");
embFontList->append(psName->getCString());
embFontList->append("\n");
// convert it to a Type 0 font
fontBuf = font->readEmbFontFile(xref, &fontLen);
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;
}
gfree(fontBuf);
// ending comment
writePS("%%EndResource\n");
}
void PSOutputDev::setupEmbeddedCIDTrueTypeFont(GfxFont *font, Ref *id,
GooString *psName,
GBool needVerticalMetrics) {
char *fontBuf;
int fontLen;
FoFiTrueType *ffTT;
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) {
psName->appendf("_{0:d}", nextTrueTypeNum++);
break;
}
}
// add entry to fontFileIDs list
if (fontFileIDLen >= fontFileIDSize) {
fontFileIDSize += 64;
fontFileIDs = (Ref *)greallocn(fontFileIDs, fontFileIDSize, sizeof(Ref));
}
fontFileIDs[fontFileIDLen++] = *id;
// beginning comment
writePSFmt("%%BeginResource: font {0:t}\n", psName);
embFontList->append("%%+ font ");
embFontList->append(psName->getCString());
embFontList->append("\n");
// convert it to a Type 0 font
fontBuf = font->readEmbFontFile(xref, &fontLen);
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)->getCIDToGIDLen(),
needVerticalMetrics,
outputFunc, outputStream);
} else {
// otherwise: use a non-CID composite font
ffTT->convertToType0(psName->getCString(),
((GfxCIDFont *)font)->getCIDToGID(),
((GfxCIDFont *)font)->getCIDToGIDLen(),
needVerticalMetrics,
outputFunc, outputStream);
}
delete ffTT;
}
gfree(fontBuf);
// ending comment
writePS("%%EndResource\n");
}
void PSOutputDev::setupEmbeddedOpenTypeCFFFont(GfxFont *font, Ref *id,
GooString *psName) {
char *fontBuf;
int fontLen;
FoFiTrueType *ffTT;
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;
}
// add entry to fontFileIDs list
if (fontFileIDLen >= fontFileIDSize) {
fontFileIDSize += 64;
fontFileIDs = (Ref *)greallocn(fontFileIDs, fontFileIDSize, sizeof(Ref));
}
fontFileIDs[fontFileIDLen++] = *id;
// beginning comment
writePSFmt("%%BeginResource: font {0:t}\n", psName);
embFontList->append("%%+ font ");
embFontList->append(psName->getCString());
embFontList->append("\n");
// convert it to a Type 0 font
fontBuf = font->readEmbFontFile(xref, &fontLen);
if ((ffTT = FoFiTrueType::make(fontBuf, fontLen))) {
if (ffTT->isOpenTypeCFF()) {
if (globalParams->getPSLevel() >= psLevel3) {
// Level 3: use a CID font
ffTT->convertToCIDType0(psName->getCString(),
outputFunc, outputStream);
} else {
// otherwise: use a non-CID composite font
ffTT->convertToType0(psName->getCString(), outputFunc, outputStream);
}
}
delete ffTT;
}
gfree(fontBuf);
// ending comment
writePS("%%EndResource\n");
}
void PSOutputDev::setupType3Font(GfxFont *font, GooString *psName,
Dict *parentResDict) {
Dict *resDict;
Dict *charProcs;
Object charProc;
Gfx *gfx;
PDFRectangle box;
double *m;
GooString *buf;
int i;
// set up resources used by font
if ((resDict = ((Gfx8BitFont *)font)->getResources())) {
inType3Char = gTrue;
setupResources(resDict);
inType3Char = gFalse;
} else {
resDict = parentResDict;
}
// beginning comment
writePSFmt("%%BeginResource: font {0:t}\n", psName);
embFontList->append("%%+ font ");
embFontList->append(psName->getCString());
embFontList->append("\n");
// font dictionary
writePS("8 dict begin\n");
writePS("/FontType 3 def\n");
m = font->getFontMatrix();
writePSFmt("/FontMatrix [{0:.4g} {1:.4g} {2:.4g} {3:.4g} {4:.4g} {5:.4g}] def\n",
m[0], m[1], m[2], m[3], m[4], m[5]);
m = font->getFontBBox();
writePSFmt("/FontBBox [{0:.4g} {1:.4g} {2:.4g} {3:.4g}] 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(" exch /CharProcs get exch\n");
writePS(" 2 copy known not { pop /.notdef } if\n");
writePS(" get exec\n");
writePS("} bind def\n");
writePS("/BuildChar {\n");
writePS(" 1 index /Encoding get exch get\n");
writePS(" 1 index /BuildGlyph get exec\n");
writePS("} bind def\n");
if ((charProcs = ((Gfx8BitFont *)font)->getCharProcs())) {
writePSFmt("/CharProcs {0:d} dict def\n", charProcs->getLength());
writePS("CharProcs begin\n");
box.x1 = m[0];
box.y1 = m[1];
box.x2 = m[2];
box.y2 = m[3];
gfx = new Gfx(xref, this, resDict, m_catalog, &box, NULL);
inType3Char = gTrue;
for (i = 0; i < charProcs->getLength(); ++i) {
t3Cacheable = gFalse;
t3NeedsRestore = gFalse;
writePS("/");
writePSName(charProcs->getKey(i));
writePS(" {\n");
gfx->display(charProcs->getVal(i, &charProc));
charProc.free();
if (t3String) {
if (t3Cacheable) {
buf = GooString::format("{0:.4g} {1:.4g} {2:.4g} {3:.4g} {4:.4g} {5:.4g} setcachedevice\n",
t3WX, t3WY, t3LLX, t3LLY, t3URX, t3URY);
} else {
buf = GooString::format("{0:.4g} {1:.4g} setcharwidth\n", t3WX, t3WY);
}
(*outputFunc)(outputStream, buf->getCString(), buf->getLength());
delete buf;
(*outputFunc)(outputStream, t3String->getCString(),
t3String->getLength());
delete t3String;
t3String = NULL;
}
if (t3NeedsRestore) {
(*outputFunc)(outputStream, "Q\n", 2);
}
writePS("} def\n");
}
inType3Char = gFalse;
delete gfx;
writePS("end\n");
}
writePS("currentdict end\n");
writePSFmt("/{0:t} exch definefont pop\n", psName);
// ending comment
writePS("%%EndResource\n");
}
void PSOutputDev::setupImages(Dict *resDict) {
Object xObjDict, xObj, xObjRef, subtypeObj;
int i;
if (!(mode == psModeForm || inType3Char || preload)) {
return;
}
//----- recursively scan XObjects
resDict->lookup("XObject", &xObjDict);
if (xObjDict.isDict()) {
for (i = 0; i < xObjDict.dictGetLength(); ++i) {
xObjDict.dictGetValNF(i, &xObjRef);
xObjDict.dictGetVal(i, &xObj);
if (xObj.isStream()) {
xObj.streamGetDict()->lookup("Subtype", &subtypeObj);
if (subtypeObj.isName("Image")) {
if (xObjRef.isRef()) {
setupImage(xObjRef.getRef(), xObj.getStream());
} else {
error(-1, "Image in resource dict is not an indirect reference");
}
}
subtypeObj.free();
}
xObj.free();
xObjRef.free();
}
}
xObjDict.free();
}
void PSOutputDev::setupImage(Ref id, Stream *str) {
GBool useRLE, useCompressed, useASCIIHex;
GooString *s;
int c;
int size, line, col, i;
int outerSize, outer;
// check if image is already setup
for (i = 0; i < imgIDLen; ++i) {
if (imgIDs[i].num == id.num && imgIDs[i].gen == id.gen) {
return;
}
}
// add entry to imgIDs list
if (imgIDLen >= imgIDSize) {
if (imgIDSize == 0) {
imgIDSize = 64;
} else {
imgIDSize *= 2;
}
imgIDs = (Ref *)greallocn(imgIDs, imgIDSize, sizeof(Ref));
}
imgIDs[imgIDLen++] = id;
// filters
//~ this does not correctly handle the DeviceN color space
//~ -- need to use DeviceNRecoder
if (level < psLevel2) {
useRLE = gFalse;
useCompressed = gFalse;
useASCIIHex = gTrue;
} else {
s = str->getPSFilter(level < psLevel3 ? 2 : 3, "");
if (s) {
useRLE = gFalse;
useCompressed = gTrue;
delete s;
} else {
useRLE = gTrue;
useCompressed = gFalse;
}
useASCIIHex = level == psLevel1 || level == psLevel1Sep ||
globalParams->getPSASCIIHex();
}
if (useCompressed) {
str = str->getUndecodedStream();
}
if (useRLE) {