use width 0 for unused glyphs in the width array of the pdffont object
[PyX/mjg.git] / pyx / pswriter.py
blob1fda418d74b6f9dd0fa72dd7abe79e0ad084ac6e
1 # -*- coding: ISO-8859-1 -*-
4 # Copyright (C) 2005-2006 Jörg Lehmann <joergl@users.sourceforge.net>
5 # Copyright (C) 2005-2006 André Wobst <wobsta@users.sourceforge.net>
7 # This file is part of PyX (http://pyx.sourceforge.net/).
9 # PyX is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 2 of the License, or
12 # (at your option) any later version.
14 # PyX is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License
20 # along with PyX; if not, write to the Free Software
21 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 import cStringIO, copy, time, math
24 import bbox, config, style, version, unit, trafo
27 class PSregistry:
29 def __init__(self):
30 # in order to keep a consistent order of the registered resources we
31 # not only store them in a hash but also keep an ordered list (up to a
32 # possible merging of resources, in which case the first instance is
33 # kept)
34 self.resourceshash = {}
35 self.resourceslist = []
37 def add(self, resource):
38 rkey = (resource.type, resource.id)
39 if self.resourceshash.has_key(rkey):
40 self.resourceshash[rkey].merge(resource)
41 else:
42 self.resourceshash[rkey] = resource
43 self.resourceslist.append(resource)
45 def mergeregistry(self, registry):
46 for resource in registry.resources:
47 self.add(resource)
49 def output(self, file, writer):
50 """ write all PostScript code of the prolog resources """
51 for resource in self.resourceslist:
52 resource.output(file, writer, self)
55 # Abstract base class
58 class PSresource:
60 """ a PostScript resource """
62 def __init__(self, type, id):
63 # Every PSresource has to have a type and a unique id.
64 # Resources with the same type and id will be merged
65 # when they are registered in the PSregistry
66 self.type = type
67 self.id = id
69 def merge(self, other):
70 """ merge self with other, which has to be a resource of the same type and with
71 the same id"""
72 pass
74 def output(self, file, writer, registry):
75 raise NotImplementedError("output not implemented for %s" % repr(self))
77 class PSdefinition(PSresource):
79 """ PostScript function definition included in the prolog """
81 def __init__(self, id, body):
82 self.type = "definition"
83 self.id = id
84 self.body = body
86 def output(self, file, writer, registry):
87 file.write("%%%%BeginRessource: %s\n" % self.id)
88 file.write("%(body)s /%(id)s exch def\n" % self.__dict__)
89 file.write("%%EndRessource\n")
92 # Writers
95 class _PSwriter:
97 def __init__(self, title=None, stripfonts=True, textaspath=False):
98 self._fontmap = None
99 self.title = title
100 self.stripfonts = stripfonts
101 self.textaspath = textaspath
103 # dictionary mapping font names to dictionaries mapping encoding names to encodings
104 # encodings themselves are mappings from glyphnames to codepoints
105 self.encodings = {}
107 def writeinfo(self, file):
108 file.write("%%%%Creator: PyX %s\n" % version.version)
109 if self.title is not None:
110 file.write("%%%%Title: %s\n" % self.title)
111 file.write("%%%%CreationDate: %s\n" %
112 time.asctime(time.localtime(time.time())))
114 def getfontmap(self):
115 if self._fontmap is None:
116 # late import due to cyclic dependency
117 from pyx.dvi import mapfile
118 fontmapfiles = config.get("text", "psfontmaps", "psfonts.map")
119 separator = config.get("general", "separator", "|")
120 self._fontmap = mapfile.readfontmap(fontmapfiles.split(separator))
121 return self._fontmap
124 class EPSwriter(_PSwriter):
126 def __init__(self, document, file, **kwargs):
127 _PSwriter.__init__(self, **kwargs)
129 if len(document.pages) != 1:
130 raise ValueError("EPS file can be constructed out of a single page document only")
131 page = document.pages[0]
132 canvas = page.canvas
134 pagefile = cStringIO.StringIO()
135 registry = PSregistry()
136 acontext = context()
137 pagebbox = bbox.empty()
139 page.processPS(pagefile, self, acontext, registry, pagebbox)
141 file.write("%!PS-Adobe-3.0 EPSF-3.0\n")
142 if pagebbox:
143 file.write("%%%%BoundingBox: %d %d %d %d\n" % pagebbox.lowrestuple_pt())
144 file.write("%%%%HiResBoundingBox: %g %g %g %g\n" % pagebbox.highrestuple_pt())
145 self.writeinfo(file)
146 file.write("%%EndComments\n")
148 file.write("%%BeginProlog\n")
149 registry.output(file, self)
150 file.write("%%EndProlog\n")
152 file.write(pagefile.getvalue())
153 pagefile.close()
155 file.write("showpage\n")
156 file.write("%%Trailer\n")
157 file.write("%%EOF\n")
160 class PSwriter(_PSwriter):
162 def __init__(self, document, file, writebbox=0, **kwargs):
163 _PSwriter.__init__(self, **kwargs)
165 # We first have to process the content of the pages, writing them into the stream pagesfile
166 # Doing so, we fill the registry and also calculate the page bounding boxes, which are
167 # stored in page._bbox for every page
168 pagesfile = cStringIO.StringIO()
169 registry = PSregistry()
171 # calculated bounding boxes of the whole document
172 documentbbox = bbox.empty()
174 for nr, page in enumerate(document.pages):
175 # process contents of page
176 pagefile = cStringIO.StringIO()
177 acontext = context()
178 pagebbox = bbox.empty()
179 page.processPS(pagefile, self, acontext, registry, pagebbox)
181 documentbbox += pagebbox
183 pagesfile.write("%%%%Page: %s %d\n" % (page.pagename is None and str(nr+1) or page.pagename, nr+1))
184 if page.paperformat:
185 pagesfile.write("%%%%PageMedia: %s\n" % page.paperformat.name)
186 pagesfile.write("%%%%PageOrientation: %s\n" % (page.rotated and "Landscape" or "Portrait"))
187 if pagebbox and writebbox:
188 pagesfile.write("%%%%PageBoundingBox: %d %d %d %d\n" % pagebbox.lowrestuple_pt())
190 # page setup section
191 pagesfile.write("%%BeginPageSetup\n")
192 pagesfile.write("/pgsave save def\n")
194 pagesfile.write("%%EndPageSetup\n")
195 pagesfile.write(pagefile.getvalue())
196 pagefile.close()
197 pagesfile.write("pgsave restore\n")
198 pagesfile.write("showpage\n")
199 pagesfile.write("%%PageTrailer\n")
201 file.write("%!PS-Adobe-3.0\n")
202 if documentbbox and writebbox:
203 file.write("%%%%BoundingBox: %d %d %d %d\n" % documentbbox.lowrestuple_pt())
204 file.write("%%%%HiResBoundingBox: %g %g %g %g\n" % documentbbox.highrestuple_pt())
205 self.writeinfo(file)
207 # required paper formats
208 paperformats = {}
209 for page in document.pages:
210 if page.paperformat:
211 paperformats[page.paperformat] = page.paperformat
213 first = 1
214 for paperformat in paperformats.values():
215 if first:
216 file.write("%%DocumentMedia: ")
217 first = 0
218 else:
219 file.write("%%+ ")
220 file.write("%s %d %d 75 white ()\n" % (paperformat.name,
221 unit.topt(paperformat.width),
222 unit.topt(paperformat.height)))
224 # file.write(%%DocumentNeededResources: ") # register not downloaded fonts here
226 file.write("%%%%Pages: %d\n" % len(document.pages))
227 file.write("%%PageOrder: Ascend\n")
228 file.write("%%EndComments\n")
230 # document defaults section
231 #file.write("%%BeginDefaults\n")
232 #file.write("%%EndDefaults\n")
234 # document prolog section
235 file.write("%%BeginProlog\n")
236 registry.output(file, self)
237 file.write("%%EndProlog\n")
239 # document setup section
240 #file.write("%%BeginSetup\n")
241 #file.write("%%EndSetup\n")
243 file.write(pagesfile.getvalue())
244 pagesfile.close()
246 file.write("%%Trailer\n")
247 file.write("%%EOF\n")
250 class context:
252 def __init__(self):
253 self.linewidth_pt = None
254 self.colorspace = None
255 self.selectedfont = None
257 def __call__(self, **kwargs):
258 newcontext = copy.copy(self)
259 for key, value in kwargs.items():
260 setattr(newcontext, key, value)
261 return newcontext