2 # -*- coding: ISO-8859-1 -*-
5 # Copyright (C) 2005 Jörg Lehmann <joergl@users.sourceforge.net>
6 # Copyright (C) 2005 André Wobst <wobsta@users.sourceforge.net>
8 # This file is part of PyX (http://pyx.sourceforge.net/).
10 # PyX is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 2 of the License, or
13 # (at your option) any later version.
15 # PyX is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License
21 # along with PyX; if not, write to the Free Software
22 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 import copy
, time
, math
25 import style
, version
, type1font
, unit
30 # fallback implementation for Python 2.2 and below
32 return zip(xrange(len(list)), list)
38 # in order to keep a consistent order of the registered resources we
39 # not only store them in a hash but also keep an ordered list (up to a
40 # possible merging of resources, in which case the first instance is
42 self
.resourceshash
= {}
43 self
.resourceslist
= []
45 def add(self
, resource
):
46 rkey
= (resource
.type, resource
.id)
47 if self
.resourceshash
.has_key(rkey
):
48 self
.resourceshash
[rkey
].merge(resource
)
50 self
.resourceshash
[rkey
] = resource
51 self
.resourceslist
.append(resource
)
53 def outputPS(self
, file, writer
):
54 """ write all PostScript code of the prolog resources """
55 for resource
in self
.resourceslist
:
56 resource
.outputPS(file, writer
, self
)
64 """ a PostScript resource """
66 def __init__(self
, type, id):
67 # Every PSresource has to have a type and a unique id.
68 # Resources with the same type and id will be merged
69 # when they are registered in the PSregistry
73 def merge(self
, other
):
74 """ merge self with other, which has to be a resource of the same type and with
78 def outputPS(self
, file, writer
, registry
):
79 raise NotImplementedError("outputPS not implemented for %s" % repr(self
))
82 # Different variants of prolog items
85 class PSdefinition(PSresource
):
87 """ PostScript function definition included in the prolog """
89 def __init__(self
, id, body
):
90 self
.type = "definition"
94 def outputPS(self
, file, writer
, registry
):
95 file.write("%%%%BeginRessource: %s\n" % self
.id)
96 file.write("%(body)s /%(id)s exch def\n" % self
.__dict
__)
97 file.write("%%EndRessource\n")
102 def __init__(self
, font
, chars
, registry
):
104 registry
.add(PSfontfile(font
.basefontname
,
109 registry
.add(_ReEncodeFont
)
110 registry
.add(PSfontencoding(font
.encoding
))
111 registry
.add(PSfontreencoding(font
.name
,
116 class PSfontfile(PSresource
):
118 """ PostScript font definition included in the prolog """
120 def __init__(self
, name
, filename
, encoding
, chars
):
121 """ include type 1 font defined by the following parameters
123 - name: name of the PostScript font
124 - filename: name (without path) of file containing the font definition
125 - encfilename: name (without path) of file containing used encoding of font
126 or None (if no encoding file used)
127 - chars: character list to fill usedchars
131 # Note that here we only need the encoding for selecting the used glyphs!
133 self
.type = "fontfile"
134 self
.id = self
.name
= name
135 self
.filename
= filename
137 self
.encodingfilename
= None
139 self
.encodingfilename
= encoding
.filename
142 self
.usedchars
[char
] = 1
144 def merge(self
, other
):
145 if self
.encodingfilename
== other
.encodingfilename
:
146 self
.usedchars
.update(other
.usedchars
)
148 self
.encodingfilename
= None # stripping of font not possible
150 def outputPS(self
, file, writer
, registry
):
151 # XXX: access to the encoding file
152 if self
.encodingfilename
:
153 encodingfile
= type1font
.encodingfile(self
.encodingfilename
, self
.encodingfilename
)
154 usedglyphs
= [encodingfile
.decode(char
)[1:] for char
in self
.usedchars
.keys()]
156 file.write("%%%%BeginFont: %s\n" % self
.name
)
157 # file.write("%%Included glyphs: %s\n" % " ".join(usedglyphs))
159 font
= font
.t1font
.T1pfbfont(self
.filename
)
160 if self
.encodingfilename
:
161 strippedfont
= font
.getstrippedfont(usedglyphs
)
164 strippedfont
.outputPS(file)
165 file.write("\n%%EndFont\n")
168 class PSfontencoding(PSresource
):
170 """ PostScript font encoding vector included in the prolog """
172 def __init__(self
, encoding
):
173 """ include font encoding vector specified by encoding """
175 self
.type = "fontencoding"
176 self
.id = encoding
.name
177 self
.encoding
= encoding
179 def outputPS(self
, file, writer
, registry
):
180 encodingfile
= type1font
.encodingfile(self
.encoding
.name
, self
.encoding
.filename
)
181 encodingfile
.outputPS(file, writer
, registry
)
184 class PSfontreencoding(PSresource
):
186 """ PostScript font re-encoding directive included in the prolog """
188 def __init__(self
, fontname
, basefontname
, encodingname
):
189 """ include font re-encoding directive specified by
191 - fontname: PostScript FontName of the new reencoded font
192 - basefontname: PostScript FontName of the original font
193 - encname: name of the encoding
194 - font: a reference to the font instance (temporarily added for pdf support)
196 Before being able to reencode a font, you have to include the
197 encoding via a fontencoding prolog item with name=encname
201 self
.type = "fontreencoding"
202 self
.id = self
.fontname
= fontname
203 self
.basefontname
= basefontname
204 self
.encodingname
= encodingname
206 def outputPS(self
, file, writer
, registry
):
207 file.write("%%%%BeginProcSet: %s\n" % self
.fontname
)
208 file.write("/%s /%s %s ReEncodeFont\n" % (self
.basefontname
, self
.fontname
, self
.encodingname
))
209 file.write("%%EndProcSet\n")
212 _ReEncodeFont
= PSdefinition("ReEncodeFont", """{
215 /newencoding exch def
216 /newfontname exch def
217 /basefontname exch def
218 /basefontdict basefontname findfont def
219 /newfontdict basefontdict maxlength dict def
221 exch dup dup /FID ne exch /Encoding ne and
222 { exch newfontdict 3 1 roll put }
226 newfontdict /FontName newfontname put
227 newfontdict /Encoding newencoding put
228 newfontname newfontdict definefont pop
235 def __init__(self
, document
, filename
):
236 if len(document
.pages
) != 1:
237 raise ValueError("EPS file can be construced out of a single page document only")
238 page
= document
.pages
[0]
241 if not filename
.endswith(".eps"):
242 filename
= filename
+ ".eps"
244 file = open(filename
, "w")
246 raise IOError("cannot open output file")
249 pagetrafo
= page
.pagetrafo(bbox
)
251 # if a page transformation is necessary, we have to adjust the bounding box
253 if pagetrafo
is not None:
254 bbox
.transform(pagetrafo
)
256 file.write("%!PS-Adobe-3.0 EPSF-3.0\n")
258 file.write("%%%%BoundingBox: %d %d %d %d\n" % bbox
.lowrestuple_pt())
259 file.write("%%%%HiResBoundingBox: %g %g %g %g\n" % bbox
.highrestuple_pt())
260 file.write("%%%%Creator: PyX %s\n" % version
.version
)
261 file.write("%%%%Title: %s\n" % filename
)
262 file.write("%%%%CreationDate: %s\n" %
263 time
.asctime(time
.localtime(time
.time())))
264 file.write("%%EndComments\n")
266 file.write("%%BeginProlog\n")
267 registry
= PSregistry()
268 canvas
.registerPS(registry
)
269 registry
.outputPS(file, self
)
270 file.write("%%EndProlog\n")
273 # apply a possible page transformation
275 pagetrafo
.outputPS(file, self
, acontext
)
277 style
.linewidth
.normal
.outputPS(file, self
, acontext
)
279 # here comes the canvas content
280 canvas
.outputPS(file, self
, acontext
)
282 file.write("showpage\n")
283 file.write("%%Trailer\n")
284 file.write("%%EOF\n")
289 def __init__(self
, document
, filename
, writebbox
=0):
290 if not filename
.endswith(".ps"):
291 filename
= filename
+ ".ps"
293 file = open(filename
, "w")
295 raise IOError("cannot open output file")
297 # calculated bounding boxes of separate pages and the bounding box of the whole document
299 for page
in document
.pages
:
301 page
._bbox
= page
.bbox()
302 page
._pagetrafo
= page
.pagetrafo(page
._bbox
)
303 # if a page transformation is necessary, we have to adjust the bounding box
306 page
._transformedbbox
= page
._bbox
.transformed(page
._pagetrafo
)
308 page
._transformedbbox
= page
._bbox
309 if page
._transformedbbox
:
311 documentbbox
+= page
._transformedbbox
313 documentbbox
= page
._transformedbbox
.enlarge(0) # make a copy
315 file.write("%!PS-Adobe-3.0\n")
316 if documentbbox
and writebbox
:
317 file.write("%%%%BoundingBox: %d %d %d %d\n" % documentbbox
.lowrestuple_pt())
318 file.write("%%%%HiResBoundingBox: %g %g %g %g\n" % documentbbox
.highrestuple_pt())
319 file.write("%%%%Creator: PyX %s\n" % version
.version
)
320 file.write("%%%%Title: %s\n" % filename
)
321 file.write("%%%%CreationDate: %s\n" %
322 time
.asctime(time
.localtime(time
.time())))
324 # required paper formats
326 for page
in document
.pages
:
328 paperformats
[page
.paperformat
] = page
.paperformat
331 for paperformat
in paperformats
.values():
333 file.write("%%DocumentMedia: ")
337 file.write("%s %d %d 75 white ()\n" % (paperformat
.name
,
338 unit
.topt(paperformat
.width
),
339 unit
.topt(paperformat
.height
)))
341 # file.write(%%DocumentNeededResources: ") # register not downloaded fonts here
343 file.write("%%%%Pages: %d\n" % len(document
.pages
))
344 file.write("%%PageOrder: Ascend\n")
345 file.write("%%EndComments\n")
347 # document defaults section
348 #file.write("%%BeginDefaults\n")
349 #file.write("%%EndDefaults\n")
351 # document prolog section
352 file.write("%%BeginProlog\n")
353 registry
= PSregistry()
354 for page
in document
.pages
:
355 page
.canvas
.registerPS(registry
)
356 registry
.outputPS(file, self
)
357 file.write("%%EndProlog\n")
359 # document setup section
360 #file.write("%%BeginSetup\n")
361 #file.write("%%EndSetup\n")
364 for nr
, page
in enumerate(document
.pages
):
365 file.write("%%%%Page: %s %d\n" % (page
.pagename
is None and str(nr
+1) or page
.pagename
, nr
+1))
367 file.write("%%%%PageMedia: %s\n" % page
.paperformat
.name
)
368 file.write("%%%%PageOrientation: %s\n" % (page
.rotated
and "Landscape" or "Portrait"))
369 if page
._transformedbbox
and writebbox
:
370 file.write("%%%%PageBoundingBox: %d %d %d %d\n" % page
._transformedbbox
.lowrestuple_pt())
373 file.write("%%BeginPageSetup\n")
374 file.write("/pgsave save def\n")
377 # apply a possible page transformation
378 if page
._pagetrafo
is not None:
379 page
._pagetrafo
.outputPS(file, self
, acontext
)
381 style
.linewidth
.normal
.outputPS(file, self
, acontext
)
382 file.write("%%EndPageSetup\n")
384 # here comes the actual content
385 page
.canvas
.outputPS(file, self
, acontext
)
386 file.write("pgsave restore\n")
387 file.write("showpage\n")
388 file.write("%%PageTrailer\n")
390 file.write("%%Trailer\n")
391 file.write("%%EOF\n")
396 self
.linewidth_pt
= None
397 self
.colorspace
= None
400 def __call__(self
, **kwargs
):
401 newcontext
= copy
.copy(self
)
402 for key
, value
in kwargs
.items():
403 setattr(newcontext
, key
, value
)