1 # -*- encoding: utf-8 -*-
4 # Copyright (C) 2005-2011 Jörg Lehmann <joergl@users.sourceforge.net>
5 # Copyright (C) 2007 Michael Schindler <m-schindler@users.sourceforge.net>
6 # Copyright (C) 2005-2011 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 io
, copy
, warnings
, time
31 from . import bbox
, config
, style
, unit
, version
, trafo
, writer
39 # we want to keep the order of the resources
42 self
.procsets
= {"PDF": 1}
45 def add(self
, object):
46 """ register object, merging it with an already registered object of the same type and id """
47 sameobjects
= self
.types
.setdefault(object.type, {})
48 if object.id in sameobjects
:
49 sameobjects
[object.id].merge(object)
51 self
.objects
.append(object)
52 sameobjects
[object.id] = object
54 def getrefno(self
, object):
56 return self
.merged
.getrefno(object)
58 return self
.types
[object.type][object.id].refno
60 def mergeregistry(self
, registry
):
61 for object in registry
.objects
:
63 registry
.merged
= self
65 def write(self
, file, writer
, catalog
):
66 # first we set all refnos
68 for object in self
.objects
:
72 # second, all objects are written, keeping the positions in the output file
74 for object in self
.objects
:
75 fileposes
.append(file.tell())
76 file.write("%i 0 obj\n" % object.refno
)
77 object.write(file, writer
, self
)
78 file.write("endobj\n")
84 "0000000000 65535 f \n" % refno
)
86 for filepos
in fileposes
:
87 file.write("%010i 00000 n \n" % filepos
)
90 file.write("trailer\n"
93 file.write("/Root %i 0 R\n" % self
.getrefno(catalog
))
94 file.write("/Info %i 0 R\n" % self
.getrefno(catalog
.PDFinfo
))
100 def addresource(self
, resourcetype
, resourcename
, object, procset
=None):
101 self
.resources
.setdefault(resourcetype
, {})[resourcename
] = object
103 self
.procsets
[procset
] = 1
105 def writeresources(self
, file):
107 file.write("/ProcSet [ %s ]\n" % " ".join(["/%s" % p
for p
in list(self
.procsets
.keys())]))
109 for resourcetype
, resources
in list(self
.resources
.items()):
110 file.write("/%s <<\n%s\n>>\n" % (resourcetype
, "\n".join(["/%s %i 0 R" % (name
, self
.getrefno(object))
111 for name
, object in list(resources
.items())])))
117 def __init__(self
, type, _id
=None):
118 """create a PDFobject
119 - type has to be a string describing the type of the object
120 - _id is a unique identification used for the object if it is not None.
121 Otherwise id(self) is used
129 def merge(self
, other
):
132 def write(self
, file, writer
, registry
):
133 raise NotImplementedError("write method has to be provided by PDFobject subclass")
136 class PDFcatalog(PDFobject
):
138 def __init__(self
, document
, writer
, registry
):
139 PDFobject
.__init
__(self
, "catalog")
140 self
.PDFform
= PDFform(writer
, registry
)
141 registry
.add(self
.PDFform
)
142 self
.PDFpages
= PDFpages(document
, writer
, registry
)
143 registry
.add(self
.PDFpages
)
144 self
.PDFinfo
= PDFinfo()
145 registry
.add(self
.PDFinfo
)
147 def write(self
, file, writer
, registry
):
150 "/Pages %i 0 R\n" % registry
.getrefno(self
.PDFpages
))
151 if not self
.PDFform
.empty():
152 file.write("/AcroForm %i 0 R\n" % registry
.getrefno(self
.PDFform
))
153 if writer
.fullscreen
:
154 file.write("/PageMode /FullScreen\n")
158 class PDFinfo(PDFobject
):
161 PDFobject
.__init
__(self
, "info")
163 def write(self
, file, writer
, registry
):
164 if time
.timezone
< 0:
165 # divmod on positive numbers, otherwise the minutes have a different sign from the hours
166 timezone
= "-%02i'%02i'" % divmod(-time
.timezone
/60, 60)
167 elif time
.timezone
> 0:
168 timezone
= "+%02i'%02i'" % divmod(time
.timezone
/60, 60)
175 if 32 <= ord(c
) <= 127 and c
not in "()[]<>\\":
178 r
+= "\\%03o" % ord(c
)
183 file.write("/Title (%s)\n" % pdfstring(writer
.title
))
185 file.write("/Author (%s)\n" % pdfstring(writer
.author
))
187 file.write("/Subject (%s)\n" % pdfstring(writer
.subject
))
189 file.write("/Keywords (%s)\n" % pdfstring(writer
.keywords
))
190 file.write("/Creator (PyX %s)\n" % version
.version
)
191 file.write("/CreationDate (D:%s%s)\n" % (time
.strftime("%Y%m%d%H%M"), timezone
))
195 class PDFpages(PDFobject
):
197 def __init__(self
, document
, writer
, registry
):
198 PDFobject
.__init
__(self
, "pages")
199 self
.PDFpagelist
= []
200 for pageno
, page
in enumerate(document
.pages
):
201 page
= PDFpage(page
, pageno
, self
, writer
, registry
)
203 self
.PDFpagelist
.append(page
)
205 def write(self
, file, writer
, registry
):
210 ">>\n" % (" ".join(["%i 0 R" % registry
.getrefno(page
)
211 for page
in self
.PDFpagelist
]),
212 len(self
.PDFpagelist
)))
215 class PDFpage(PDFobject
):
217 def __init__(self
, page
, pageno
, PDFpages
, writer
, registry
):
218 PDFobject
.__init
__(self
, "page")
219 self
.PDFpages
= PDFpages
222 # every page uses its own registry in order to find out which
223 # resources are used within the page. However, the
224 # pageregistry is also merged in the global registry
225 self
.pageregistry
= PDFregistry()
226 self
.pageregistry
.add(self
)
228 self
.PDFannotations
= PDFannotations()
229 self
.pageregistry
.add(self
.PDFannotations
)
230 # we eventually need the form dictionary to append formfields
231 for object in registry
.objects
:
232 if object.type == "form":
233 self
.pageregistry
.add(object)
235 self
.PDFcontent
= PDFcontent(page
, writer
, self
.pageregistry
)
236 self
.pageregistry
.add(self
.PDFcontent
)
237 registry
.mergeregistry(self
.pageregistry
)
239 def write(self
, file, writer
, registry
):
242 "/Parent %i 0 R\n" % registry
.getrefno(self
.PDFpages
))
243 paperformat
= self
.page
.paperformat
245 file.write("/MediaBox [0 0 %f %f]\n" % (unit
.topt(paperformat
.width
), unit
.topt(paperformat
.height
)))
247 file.write("/MediaBox [%f %f %f %f]\n" % self
.PDFcontent
.bbox
.highrestuple_pt())
248 if self
.PDFcontent
.bbox
and writer
.writebbox
:
249 file.write("/CropBox [%f %f %f %f]\n" % self
.PDFcontent
.bbox
.highrestuple_pt())
250 if self
.page
.rotated
:
251 file.write("/Rotate 90\n")
252 if not self
.PDFannotations
.empty():
253 file.write("/Annots %i 0 R\n" % registry
.getrefno(self
.PDFannotations
))
254 file.write("/Contents %i 0 R\n" % registry
.getrefno(self
.PDFcontent
))
255 file.write("/Resources ")
256 self
.pageregistry
.writeresources(file)
260 class PDFcontent(PDFobject
):
262 def __init__(self
, page
, awriter
, registry
):
263 PDFobject
.__init
__(self
, registry
, "content")
264 contentfile
= writer
.writer(io
.BytesIO())
265 self
.bbox
= bbox
.empty()
267 page
.processPDF(contentfile
, awriter
, acontext
, registry
, self
.bbox
)
268 self
.content
= contentfile
.file.getvalue()
270 def write(self
, file, awriter
, registry
):
272 content
= zlib
.compress(self
.content
)
274 content
= self
.content
276 "/Length %i\n" % len(content
))
278 file.write("/Filter /FlateDecode\n")
281 file.write_bytes(content
)
282 file.write("endstream\n")
287 def __init__(self
, document
, file,
288 title
=None, author
=None, subject
=None, keywords
=None,
289 fullscreen
=False, writebbox
=False, compress
=True, compresslevel
=6,
290 strip_fonts
=True, text_as_path
=False, mesh_as_bitmap
=False, mesh_as_bitmap_resolution
=300):
295 self
.subject
= subject
296 self
.keywords
= keywords
297 self
.fullscreen
= fullscreen
298 self
.writebbox
= writebbox
299 if compress
and not haszlib
:
301 warnings
.warn("compression disabled due to missing zlib module")
302 self
.compress
= compress
303 self
.compresslevel
= compresslevel
304 self
.strip_fonts
= strip_fonts
305 self
.text_as_path
= text_as_path
306 self
.mesh_as_bitmap
= mesh_as_bitmap
307 self
.mesh_as_bitmap_resolution
= mesh_as_bitmap_resolution
309 # dictionary mapping font names to dictionaries mapping encoding names to encodings
310 # encodings themselves are mappings from glyphnames to codepoints
313 # the PDFcatalog class automatically builds up the pdfobjects from a document
314 registry
= PDFregistry()
315 catalog
= PDFcatalog(document
, self
, registry
)
316 registry
.add(catalog
)
318 file = writer
.writer(file)
319 file.write_bytes(b
"%PDF-1.4\n%\xc3\xb6\xc3\xa9\n")
320 registry
.write(file, self
, catalog
)
322 def getfontmap(self
):
323 if self
._fontmap
is None:
324 # late import due to cyclic dependency
325 from pyx
.dvi
import mapfile
326 fontmapfiles
= config
.getlist("text", "pdffontmaps", ["pdftex.map"])
327 self
._fontmap
= mapfile
.readfontmap(fontmapfiles
)
331 class PDFannotations(PDFobject
):
334 PDFobject
.__init
__(self
, "annotations")
337 def append(self
, item
):
338 if item
not in self
.annots
:
339 self
.annots
.append(item
)
342 return len(self
.annots
) == 0
344 def write(self
, file, writer
, registry
):
345 # XXX problem: This object will be written to the file even if it is useless (empty)
346 file.write("[ %s ]\n" % " ".join(["%d 0 R" % registry
.getrefno(annot
) for annot
in self
.annots
]))
349 class PDFform(PDFobject
):
351 def __init__(self
, writer
, registry
):
352 PDFobject
.__init
__(self
, "form")
355 def merge(self
, other
):
356 for field
in other
.fields
:
359 def append(self
, field
):
360 if field
not in self
.fields
:
361 self
.fields
.append(field
)
364 return len(self
.fields
) == 0
366 def write(self
, file, writer
, registry
):
367 # XXX problem: This object will be written to the file even if it is useless (empty)
369 file.write("/Fields [")
370 for field
in self
.fields
:
371 file.write(" %d 0 R" % registry
.getrefno(field
))
379 self
.linewidth_pt
= None
380 # XXX there are both stroke and fill color spaces
381 self
.colorspace
= None
384 self
.selectedfont
= None
385 self
.trafo
= trafo
.trafo()
389 def __call__(self
, **kwargs
):
390 newcontext
= copy
.copy(self
)
391 for key
, value
in list(kwargs
.items()):
392 setattr(newcontext
, key
, value
)