fix multipage PS output
[PyX.git] / pyx / pswriter.py
blob57418bba787173385320d715b5c9cb4f719f0f69
1 #!/usr/bin/env python
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 import time, math
25 import style, version, type1font, unit
28 class PSregistry:
30 def __init__(self):
31 # in order to keep a consistent order of the registered resources we
32 # not only store them in a hash but also keep an ordered list (up to a
33 # possible merging of resources, in which case the first instance is
34 # kept)
35 self.resourceshash = {}
36 self.resourceslist = []
38 def add(self, resource):
39 rkey = (resource.type, resource.id)
40 if self.resourceshash.has_key(rkey):
41 self.resourceshash[rkey].merge(resource)
42 else:
43 self.resourceshash[rkey] = resource
44 self.resourceslist.append(resource)
46 def outputPS(self, file):
47 """ write all PostScript code of the prolog resources """
48 for resource in self.resourceslist:
49 resource.outputPS(file)
52 # Abstract base class
55 class PSresource:
57 """ a PostScript resource """
59 def __init__(self, type, id):
60 # Every PSresource has to have a type and a unique id.
61 # Resources with the same type and id will be merged
62 # when they are registered in the PSregistry
63 self.type = type
64 self.id = id
66 def merge(self, other):
67 """ merge self with other, which has to be a resource of the same type and with
68 the same id"""
69 pass
71 def outputPS(self, file):
72 raise NotImplementedError("outputPS not implemented for %s" % repr(self))
75 # Different variants of prolog items
78 class PSdefinition(PSresource):
80 """ PostScript function definition included in the prolog """
82 def __init__(self, id, body):
83 self.type = "definition"
84 self.id = id
85 self.body = body
87 def outputPS(self, file):
88 file.write("%%%%BeginRessource: %s\n" % self.id)
89 file.write("%(body)s /%(id)s exch def\n" % self.__dict__)
90 file.write("%%EndRessource\n")
93 class PSfont:
95 def __init__(self, font, chars, registry):
96 if font.filename:
97 registry.add(PSfontfile(font.basefontname,
98 font.filename,
99 font.encoding,
100 chars))
101 if font.encoding:
102 registry.add(_ReEncodeFont)
103 registry.add(PSfontencoding(font.encoding))
104 registry.add(PSfontreencoding(font.name,
105 font.basefontname,
106 font.encoding.name))
109 class PSfontfile(PSresource):
111 """ PostScript font definition included in the prolog """
113 def __init__(self, name, filename, encoding, chars):
114 """ include type 1 font defined by the following parameters
116 - name: name of the PostScript font
117 - filename: name (without path) of file containing the font definition
118 - encfilename: name (without path) of file containing used encoding of font
119 or None (if no encoding file used)
120 - chars: character list to fill usedchars
124 # Note that here we only need the encoding for selecting the used glyphs!
126 self.type = "fontfile"
127 self.id = self.name = name
128 self.filename = filename
129 if encoding is None:
130 self.encodingfilename = None
131 else:
132 self.encodingfilename = encoding.filename
133 self.usedchars = {}
134 for char in chars:
135 self.usedchars[char] = 1
137 def merge(self, other):
138 if self.encodingfilename == other.encodingfilename:
139 self.usedchars.update(other.usedchars)
140 else:
141 self.usedchars = None # stripping of font not possible
143 def outputPS(self, file):
144 fontfile = type1font.fontfile(self.name, self.filename, self.usedchars, self.encodingfilename)
145 fontfile.outputPS(file)
148 class PSfontencoding(PSresource):
150 """ PostScript font encoding vector included in the prolog """
152 def __init__(self, encoding):
153 """ include font encoding vector specified by encoding """
155 self.type = "fontencoding"
156 self.id = encoding.name
157 self.encoding = encoding
159 def outputPS(self, file):
160 encodingfile = type1font.encodingfile(self.encoding.name, self.encoding.filename)
161 encodingfile.outputPS(file)
164 class PSfontreencoding(PSresource):
166 """ PostScript font re-encoding directive included in the prolog """
168 def __init__(self, fontname, basefontname, encodingname):
169 """ include font re-encoding directive specified by
171 - fontname: PostScript FontName of the new reencoded font
172 - basefontname: PostScript FontName of the original font
173 - encname: name of the encoding
174 - font: a reference to the font instance (temporarily added for pdf support)
176 Before being able to reencode a font, you have to include the
177 encoding via a fontencoding prolog item with name=encname
181 self.type = "fontreencoding"
182 self.id = self.fontname = fontname
183 self.basefontname = basefontname
184 self.encodingname = encodingname
186 def outputPS(self, file):
187 file.write("%%%%BeginProcSet: %s\n" % self.fontname)
188 file.write("/%s /%s %s ReEncodeFont\n" % (self.basefontname, self.fontname, self.encodingname))
189 file.write("%%EndProcSet\n")
192 _ReEncodeFont = PSdefinition("ReEncodeFont", """{
193 5 dict
194 begin
195 /newencoding exch def
196 /newfontname exch def
197 /basefontname exch def
198 /basefontdict basefontname findfont def
199 /newfontdict basefontdict maxlength dict def
200 basefontdict {
201 exch dup dup /FID ne exch /Encoding ne and
202 { exch newfontdict 3 1 roll put }
203 { pop pop }
204 ifelse
205 } forall
206 newfontdict /FontName newfontname put
207 newfontdict /Encoding newencoding put
208 newfontname newfontdict definefont pop
210 }""")
213 class epswriter:
215 def __init__(self, document, filename):
216 if len(document.pages) != 1:
217 raise ValueError("EPS file can be construced out of a single page document only")
218 page = document.pages[0]
219 canvas = page.canvas
221 if filename[-4:] != ".eps":
222 filename = filename + ".eps"
223 try:
224 file = open(filename, "w")
225 except IOError:
226 raise IOError("cannot open output file")
228 bbox = canvas.bbox()
229 bbox.enlarge(page.bboxenlarge)
230 pagetrafo = page.pagetrafo(bbox)
232 # if a page transformation is necessary, we have to adjust the bounding box
233 # accordingly
234 if pagetrafo is not None:
235 bbox.transform(pagetrafo)
237 file.write("%!PS-Adobe-3.0 EPSF-3.0\n")
238 bbox.outputPS(file)
239 file.write("%%%%Creator: PyX %s\n" % version.version)
240 file.write("%%%%Title: %s\n" % filename)
241 file.write("%%%%CreationDate: %s\n" %
242 time.asctime(time.localtime(time.time())))
243 file.write("%%EndComments\n")
245 file.write("%%BeginProlog\n")
246 registry = PSregistry()
247 canvas.registerPS(registry)
248 registry.outputPS(file)
249 file.write("%%EndProlog\n")
251 # apply a possible page transformation
252 if pagetrafo is not None:
253 pagetrafo.outputPS(file)
255 style.linewidth.normal.outputPS(file)
257 # here comes the canvas content
258 canvas.outputPS(file)
260 file.write("showpage\n")
261 file.write("%%Trailer\n")
262 file.write("%%EOF\n")
265 class pswriter:
267 def __init__(self, document, filename):
268 if filename[-4:] != ".ps":
269 filename = filename + ".ps"
270 try:
271 file = open(filename, "w")
272 except IOError:
273 raise IOError("cannot open output file")
275 # calculated bounding boxes of separate pages and the bounding box of the whole document
276 documentbbox = None
277 for page in document.pages:
278 canvas = page.canvas
279 page.bbox = canvas.bbox()
280 page.bbox.enlarge(page.bboxenlarge)
281 page._pagetrafo = page.pagetrafo(page.bbox)
282 # if a page transformation is necessary, we have to adjust the bounding box
283 # accordingly
284 if page._pagetrafo is not None and page.bbox is not None:
285 page.bbox.transform(page._pagetrafo)
286 if documentbbox is None:
287 documentbbox = page.bbox
288 elif page.bbox is not None:
289 documentbbox += page.bbox
291 file.write("%!PS-Adobe-3.0\n")
292 documentbbox.outputPS(file)
293 file.write("%%%%Creator: PyX %s\n" % version.version)
294 file.write("%%%%Title: %s\n" % filename)
295 file.write("%%%%CreationDate: %s\n" %
296 time.asctime(time.localtime(time.time())))
298 # required paper formats
299 paperformats = {}
300 for page in document.pages:
301 paperformats[page.paperformat] = page.paperformat
303 first = 1
304 for paperformat in paperformats.values():
305 if first:
306 file.write("%%DocumentMedia: ")
307 first = 0
308 else:
309 file.write("%%+ ")
310 file.write("%s %d %d 75 white ()\n" % (paperformat.name,
311 unit.topt(paperformat.width),
312 unit.topt(paperformat.height)))
314 # file.write(%%DocumentNeededResources: ") # register not downloaded fonts here
316 file.write("%%%%Pages: %d\n" % len(document.pages))
317 file.write("%%PageOrder: Ascend\n")
318 file.write("%%EndComments\n")
320 # document defaults section
321 #file.write("%%BeginDefaults\n")
322 #file.write("%%EndDefaults\n")
324 # document prolog section
325 file.write("%%BeginProlog\n")
326 registry = PSregistry()
327 for page in document.pages:
328 page.canvas.registerPS(registry)
329 registry.outputPS(file)
330 file.write("%%EndProlog\n")
332 # document setup section
333 #file.write("%%BeginSetup\n")
334 #file.write("%%EndSetup\n")
336 # pages section
337 for nr, page in enumerate(document.pages):
338 file.write("%%%%Page: %s %d\n" % (page.pagename is None and str(nr+1) or page.pagename, nr+1))
339 file.write("%%%%PageMedia: %s\n" % page.paperformat)
340 file.write("%%%%PageOrientation: %s\n" % (page.rotated and "Landscape" or "Portrait"))
341 file.write("%%%%PageBoundingBox: %d %d %d %d\n" % (math.floor(page.bbox.llx_pt), math.floor(page.bbox.lly_pt),
342 math.ceil(page.bbox.urx_pt), math.ceil(page.bbox.ury_pt)))
344 # page setup section
345 file.write("%%BeginPageSetup\n")
346 file.write("/pgsave save def\n")
347 # apply a possible page transformation
348 if page._pagetrafo is not None:
349 page._pagetrafo.outputPS(file)
351 style.linewidth.normal.outputPS(file)
352 file.write("%%EndPageSetup\n")
354 # here comes the actual content
355 page.canvas.outputPS(file)
356 file.write("pgsave restore\n")
357 file.write("showpage\n")
358 file.write("%%PageTrailer\n")
360 file.write("%%Trailer\n")
361 file.write("%%EOF\n")