-
-
Notifications
You must be signed in to change notification settings - Fork 7.5k
/
backend_pdf.py
2827 lines (2454 loc) · 104 KB
/
backend_pdf.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
A PDF Matplotlib backend.
Author: Jouni K Seppänen <jks@iki.fi> and others.
"""
import codecs
from datetime import timezone
from datetime import datetime
from enum import Enum
from functools import total_ordering
from io import BytesIO
import itertools
import logging
import math
import os
import string
import struct
import sys
import time
import types
import warnings
import zlib
import numpy as np
from PIL import Image
import matplotlib as mpl
from matplotlib import _api, _text_helpers, _type1font, cbook, dviread
from matplotlib._pylab_helpers import Gcf
from matplotlib.backend_bases import (
_Backend, FigureCanvasBase, FigureManagerBase, GraphicsContextBase,
RendererBase)
from matplotlib.backends.backend_mixed import MixedModeRenderer
from matplotlib.figure import Figure
from matplotlib.font_manager import get_font, fontManager as _fontManager
from matplotlib._afm import AFM
from matplotlib.ft2font import (FIXED_WIDTH, ITALIC, LOAD_NO_SCALE,
LOAD_NO_HINTING, KERNING_UNFITTED, FT2Font)
from matplotlib.transforms import Affine2D, BboxBase
from matplotlib.path import Path
from matplotlib.dates import UTC
from matplotlib import _path
from . import _backend_pdf_ps
_log = logging.getLogger(__name__)
# Overview
#
# The low-level knowledge about pdf syntax lies mainly in the pdfRepr
# function and the classes Reference, Name, Operator, and Stream. The
# PdfFile class knows about the overall structure of pdf documents.
# It provides a "write" method for writing arbitrary strings in the
# file, and an "output" method that passes objects through the pdfRepr
# function before writing them in the file. The output method is
# called by the RendererPdf class, which contains the various draw_foo
# methods. RendererPdf contains a GraphicsContextPdf instance, and
# each draw_foo calls self.check_gc before outputting commands. This
# method checks whether the pdf graphics state needs to be modified
# and outputs the necessary commands. GraphicsContextPdf represents
# the graphics state, and its "delta" method returns the commands that
# modify the state.
# Add "pdf.use14corefonts: True" in your configuration file to use only
# the 14 PDF core fonts. These fonts do not need to be embedded; every
# PDF viewing application is required to have them. This results in very
# light PDF files you can use directly in LaTeX or ConTeXt documents
# generated with pdfTeX, without any conversion.
# These fonts are: Helvetica, Helvetica-Bold, Helvetica-Oblique,
# Helvetica-BoldOblique, Courier, Courier-Bold, Courier-Oblique,
# Courier-BoldOblique, Times-Roman, Times-Bold, Times-Italic,
# Times-BoldItalic, Symbol, ZapfDingbats.
#
# Some tricky points:
#
# 1. The clip path can only be widened by popping from the state
# stack. Thus the state must be pushed onto the stack before narrowing
# the clip path. This is taken care of by GraphicsContextPdf.
#
# 2. Sometimes it is necessary to refer to something (e.g., font,
# image, or extended graphics state, which contains the alpha value)
# in the page stream by a name that needs to be defined outside the
# stream. PdfFile provides the methods fontName, imageObject, and
# alphaState for this purpose. The implementations of these methods
# should perhaps be generalized.
# TODOs:
#
# * encoding of fonts, including mathtext fonts and Unicode support
# * TTF support has lots of small TODOs, e.g., how do you know if a font
# is serif/sans-serif, or symbolic/non-symbolic?
# * draw_quad_mesh
def _fill(strings, linelen=75):
"""
Make one string from sequence of strings, with whitespace in between.
The whitespace is chosen to form lines of at most *linelen* characters,
if possible.
"""
currpos = 0
lasti = 0
result = []
for i, s in enumerate(strings):
length = len(s)
if currpos + length < linelen:
currpos += length + 1
else:
result.append(b' '.join(strings[lasti:i]))
lasti = i
currpos = length
result.append(b' '.join(strings[lasti:]))
return b'\n'.join(result)
def _create_pdf_info_dict(backend, metadata):
"""
Create a PDF infoDict based on user-supplied metadata.
A default ``Creator``, ``Producer``, and ``CreationDate`` are added, though
the user metadata may override it. The date may be the current time, or a
time set by the ``SOURCE_DATE_EPOCH`` environment variable.
Metadata is verified to have the correct keys and their expected types. Any
unknown keys/types will raise a warning.
Parameters
----------
backend : str
The name of the backend to use in the Producer value.
metadata : dict[str, Union[str, datetime, Name]]
A dictionary of metadata supplied by the user with information
following the PDF specification, also defined in
`~.backend_pdf.PdfPages` below.
If any value is *None*, then the key will be removed. This can be used
to remove any pre-defined values.
Returns
-------
dict[str, Union[str, datetime, Name]]
A validated dictionary of metadata.
"""
# get source date from SOURCE_DATE_EPOCH, if set
# See https://reproducible-builds.org/specs/source-date-epoch/
source_date_epoch = os.getenv("SOURCE_DATE_EPOCH")
if source_date_epoch:
source_date = datetime.fromtimestamp(int(source_date_epoch), timezone.utc)
source_date = source_date.replace(tzinfo=UTC)
else:
source_date = datetime.today()
info = {
'Creator': f'Matplotlib v{mpl.__version__}, https://matplotlib.org',
'Producer': f'Matplotlib {backend} backend v{mpl.__version__}',
'CreationDate': source_date,
**metadata
}
info = {k: v for (k, v) in info.items() if v is not None}
def is_string_like(x):
return isinstance(x, str)
is_string_like.text_for_warning = "an instance of str"
def is_date(x):
return isinstance(x, datetime)
is_date.text_for_warning = "an instance of datetime.datetime"
def check_trapped(x):
if isinstance(x, Name):
return x.name in (b'True', b'False', b'Unknown')
else:
return x in ('True', 'False', 'Unknown')
check_trapped.text_for_warning = 'one of {"True", "False", "Unknown"}'
keywords = {
'Title': is_string_like,
'Author': is_string_like,
'Subject': is_string_like,
'Keywords': is_string_like,
'Creator': is_string_like,
'Producer': is_string_like,
'CreationDate': is_date,
'ModDate': is_date,
'Trapped': check_trapped,
}
for k in info:
if k not in keywords:
_api.warn_external(f'Unknown infodict keyword: {k!r}. '
f'Must be one of {set(keywords)!r}.')
elif not keywords[k](info[k]):
_api.warn_external(f'Bad value for infodict keyword {k}. '
f'Got {info[k]!r} which is not '
f'{keywords[k].text_for_warning}.')
if 'Trapped' in info:
info['Trapped'] = Name(info['Trapped'])
return info
def _datetime_to_pdf(d):
"""
Convert a datetime to a PDF string representing it.
Used for PDF and PGF.
"""
r = d.strftime('D:%Y%m%d%H%M%S')
z = d.utcoffset()
if z is not None:
z = z.seconds
else:
if time.daylight:
z = time.altzone
else:
z = time.timezone
if z == 0:
r += 'Z'
elif z < 0:
r += "+%02d'%02d'" % ((-z) // 3600, (-z) % 3600)
else:
r += "-%02d'%02d'" % (z // 3600, z % 3600)
return r
def _calculate_quad_point_coordinates(x, y, width, height, angle=0):
"""
Calculate the coordinates of rectangle when rotated by angle around x, y
"""
angle = math.radians(-angle)
sin_angle = math.sin(angle)
cos_angle = math.cos(angle)
a = x + height * sin_angle
b = y + height * cos_angle
c = x + width * cos_angle + height * sin_angle
d = y - width * sin_angle + height * cos_angle
e = x + width * cos_angle
f = y - width * sin_angle
return ((x, y), (e, f), (c, d), (a, b))
def _get_coordinates_of_block(x, y, width, height, angle=0):
"""
Get the coordinates of rotated rectangle and rectangle that covers the
rotated rectangle.
"""
vertices = _calculate_quad_point_coordinates(x, y, width,
height, angle)
# Find min and max values for rectangle
# adjust so that QuadPoints is inside Rect
# PDF docs says that QuadPoints should be ignored if any point lies
# outside Rect, but for Acrobat it is enough that QuadPoints is on the
# border of Rect.
pad = 0.00001 if angle % 90 else 0
min_x = min(v[0] for v in vertices) - pad
min_y = min(v[1] for v in vertices) - pad
max_x = max(v[0] for v in vertices) + pad
max_y = max(v[1] for v in vertices) + pad
return (tuple(itertools.chain.from_iterable(vertices)),
(min_x, min_y, max_x, max_y))
def _get_link_annotation(gc, x, y, width, height, angle=0):
"""
Create a link annotation object for embedding URLs.
"""
quadpoints, rect = _get_coordinates_of_block(x, y, width, height, angle)
link_annotation = {
'Type': Name('Annot'),
'Subtype': Name('Link'),
'Rect': rect,
'Border': [0, 0, 0],
'A': {
'S': Name('URI'),
'URI': gc.get_url(),
},
}
if angle % 90:
# Add QuadPoints
link_annotation['QuadPoints'] = quadpoints
return link_annotation
# PDF strings are supposed to be able to include any eight-bit data, except
# that unbalanced parens and backslashes must be escaped by a backslash.
# However, sf bug #2708559 shows that the carriage return character may get
# read as a newline; these characters correspond to \gamma and \Omega in TeX's
# math font encoding. Escaping them fixes the bug.
_str_escapes = str.maketrans({
'\\': '\\\\', '(': '\\(', ')': '\\)', '\n': '\\n', '\r': '\\r'})
def pdfRepr(obj):
"""Map Python objects to PDF syntax."""
# Some objects defined later have their own pdfRepr method.
if hasattr(obj, 'pdfRepr'):
return obj.pdfRepr()
# Floats. PDF does not have exponential notation (1.0e-10) so we
# need to use %f with some precision. Perhaps the precision
# should adapt to the magnitude of the number?
elif isinstance(obj, (float, np.floating)):
if not np.isfinite(obj):
raise ValueError("Can only output finite numbers in PDF")
r = b"%.10f" % obj
return r.rstrip(b'0').rstrip(b'.')
# Booleans. Needs to be tested before integers since
# isinstance(True, int) is true.
elif isinstance(obj, bool):
return [b'false', b'true'][obj]
# Integers are written as such.
elif isinstance(obj, (int, np.integer)):
return b"%d" % obj
# Non-ASCII Unicode strings are encoded in UTF-16BE with byte-order mark.
elif isinstance(obj, str):
return pdfRepr(obj.encode('ascii') if obj.isascii()
else codecs.BOM_UTF16_BE + obj.encode('UTF-16BE'))
# Strings are written in parentheses, with backslashes and parens
# escaped. Actually balanced parens are allowed, but it is
# simpler to escape them all. TODO: cut long strings into lines;
# I believe there is some maximum line length in PDF.
# Despite the extra decode/encode, translate is faster than regex.
elif isinstance(obj, bytes):
return (
b'(' +
obj.decode('latin-1').translate(_str_escapes).encode('latin-1')
+ b')')
# Dictionaries. The keys must be PDF names, so if we find strings
# there, we make Name objects from them. The values may be
# anything, so the caller must ensure that PDF names are
# represented as Name objects.
elif isinstance(obj, dict):
return _fill([
b"<<",
*[Name(k).pdfRepr() + b" " + pdfRepr(v) for k, v in obj.items()],
b">>",
])
# Lists.
elif isinstance(obj, (list, tuple)):
return _fill([b"[", *[pdfRepr(val) for val in obj], b"]"])
# The null keyword.
elif obj is None:
return b'null'
# A date.
elif isinstance(obj, datetime):
return pdfRepr(_datetime_to_pdf(obj))
# A bounding box
elif isinstance(obj, BboxBase):
return _fill([pdfRepr(val) for val in obj.bounds])
else:
raise TypeError(f"Don't know a PDF representation for {type(obj)} "
"objects")
def _font_supports_glyph(fonttype, glyph):
"""
Returns True if the font is able to provide codepoint *glyph* in a PDF.
For a Type 3 font, this method returns True only for single-byte
characters. For Type 42 fonts this method return True if the character is
from the Basic Multilingual Plane.
"""
if fonttype == 3:
return glyph <= 255
if fonttype == 42:
return glyph <= 65535
raise NotImplementedError()
class Reference:
"""
PDF reference object.
Use PdfFile.reserveObject() to create References.
"""
def __init__(self, id):
self.id = id
def __repr__(self):
return "<Reference %d>" % self.id
def pdfRepr(self):
return b"%d 0 R" % self.id
def write(self, contents, file):
write = file.write
write(b"%d 0 obj\n" % self.id)
write(pdfRepr(contents))
write(b"\nendobj\n")
@total_ordering
class Name:
"""PDF name object."""
__slots__ = ('name',)
_hexify = {c: '#%02x' % c
for c in {*range(256)} - {*range(ord('!'), ord('~') + 1)}}
def __init__(self, name):
if isinstance(name, Name):
self.name = name.name
else:
if isinstance(name, bytes):
name = name.decode('ascii')
self.name = name.translate(self._hexify).encode('ascii')
def __repr__(self):
return "<Name %s>" % self.name
def __str__(self):
return '/' + self.name.decode('ascii')
def __eq__(self, other):
return isinstance(other, Name) and self.name == other.name
def __lt__(self, other):
return isinstance(other, Name) and self.name < other.name
def __hash__(self):
return hash(self.name)
def pdfRepr(self):
return b'/' + self.name
class Verbatim:
"""Store verbatim PDF command content for later inclusion in the stream."""
def __init__(self, x):
self._x = x
def pdfRepr(self):
return self._x
class Op(Enum):
"""PDF operators (not an exhaustive list)."""
close_fill_stroke = b'b'
fill_stroke = b'B'
fill = b'f'
closepath = b'h'
close_stroke = b's'
stroke = b'S'
endpath = b'n'
begin_text = b'BT'
end_text = b'ET'
curveto = b'c'
rectangle = b're'
lineto = b'l'
moveto = b'm'
concat_matrix = b'cm'
use_xobject = b'Do'
setgray_stroke = b'G'
setgray_nonstroke = b'g'
setrgb_stroke = b'RG'
setrgb_nonstroke = b'rg'
setcolorspace_stroke = b'CS'
setcolorspace_nonstroke = b'cs'
setcolor_stroke = b'SCN'
setcolor_nonstroke = b'scn'
setdash = b'd'
setlinejoin = b'j'
setlinecap = b'J'
setgstate = b'gs'
gsave = b'q'
grestore = b'Q'
textpos = b'Td'
selectfont = b'Tf'
textmatrix = b'Tm'
show = b'Tj'
showkern = b'TJ'
setlinewidth = b'w'
clip = b'W'
shading = b'sh'
def pdfRepr(self):
return self.value
@classmethod
def paint_path(cls, fill, stroke):
"""
Return the PDF operator to paint a path.
Parameters
----------
fill : bool
Fill the path with the fill color.
stroke : bool
Stroke the outline of the path with the line color.
"""
if stroke:
if fill:
return cls.fill_stroke
else:
return cls.stroke
else:
if fill:
return cls.fill
else:
return cls.endpath
class Stream:
"""
PDF stream object.
This has no pdfRepr method. Instead, call begin(), then output the
contents of the stream by calling write(), and finally call end().
"""
__slots__ = ('id', 'len', 'pdfFile', 'file', 'compressobj', 'extra', 'pos')
def __init__(self, id, len, file, extra=None, png=None):
"""
Parameters
----------
id : int
Object id of the stream.
len : Reference or None
An unused Reference object for the length of the stream;
None means to use a memory buffer so the length can be inlined.
file : PdfFile
The underlying object to write the stream to.
extra : dict from Name to anything, or None
Extra key-value pairs to include in the stream header.
png : dict or None
If the data is already png encoded, the decode parameters.
"""
self.id = id # object id
self.len = len # id of length object
self.pdfFile = file
self.file = file.fh # file to which the stream is written
self.compressobj = None # compression object
if extra is None:
self.extra = dict()
else:
self.extra = extra.copy()
if png is not None:
self.extra.update({'Filter': Name('FlateDecode'),
'DecodeParms': png})
self.pdfFile.recordXref(self.id)
if mpl.rcParams['pdf.compression'] and not png:
self.compressobj = zlib.compressobj(
mpl.rcParams['pdf.compression'])
if self.len is None:
self.file = BytesIO()
else:
self._writeHeader()
self.pos = self.file.tell()
def _writeHeader(self):
write = self.file.write
write(b"%d 0 obj\n" % self.id)
dict = self.extra
dict['Length'] = self.len
if mpl.rcParams['pdf.compression']:
dict['Filter'] = Name('FlateDecode')
write(pdfRepr(dict))
write(b"\nstream\n")
def end(self):
"""Finalize stream."""
self._flush()
if self.len is None:
contents = self.file.getvalue()
self.len = len(contents)
self.file = self.pdfFile.fh
self._writeHeader()
self.file.write(contents)
self.file.write(b"\nendstream\nendobj\n")
else:
length = self.file.tell() - self.pos
self.file.write(b"\nendstream\nendobj\n")
self.pdfFile.writeObject(self.len, length)
def write(self, data):
"""Write some data on the stream."""
if self.compressobj is None:
self.file.write(data)
else:
compressed = self.compressobj.compress(data)
self.file.write(compressed)
def _flush(self):
"""Flush the compression object."""
if self.compressobj is not None:
compressed = self.compressobj.flush()
self.file.write(compressed)
self.compressobj = None
def _get_pdf_charprocs(font_path, glyph_ids):
font = get_font(font_path, hinting_factor=1)
conv = 1000 / font.units_per_EM # Conversion to PS units (1/1000's).
procs = {}
for glyph_id in glyph_ids:
g = font.load_glyph(glyph_id, LOAD_NO_SCALE)
# NOTE: We should be using round(), but instead use
# "(x+.5).astype(int)" to keep backcompat with the old ttconv code
# (this is different for negative x's).
d1 = (np.array([g.horiAdvance, 0, *g.bbox]) * conv + .5).astype(int)
v, c = font.get_path()
v = (v * 64).astype(int) # Back to TrueType's internal units (1/64's).
# Backcompat with old ttconv code: control points between two quads are
# omitted if they are exactly at the midpoint between the control of
# the quad before and the quad after, but ttconv used to interpolate
# *after* conversion to PS units, causing floating point errors. Here
# we reproduce ttconv's logic, detecting these "implicit" points and
# re-interpolating them. Note that occasionally (e.g. with DejaVu Sans
# glyph "0") a point detected as "implicit" is actually explicit, and
# will thus be shifted by 1.
quads, = np.nonzero(c == 3)
quads_on = quads[1::2]
quads_mid_on = np.array(
sorted({*quads_on} & {*(quads - 1)} & {*(quads + 1)}), int)
implicit = quads_mid_on[
(v[quads_mid_on] # As above, use astype(int), not // division
== ((v[quads_mid_on - 1] + v[quads_mid_on + 1]) / 2).astype(int))
.all(axis=1)]
if (font.postscript_name, glyph_id) in [
("DejaVuSerif-Italic", 77), # j
("DejaVuSerif-Italic", 135), # \AA
]:
v[:, 0] -= 1 # Hard-coded backcompat (FreeType shifts glyph by 1).
v = (v * conv + .5).astype(int) # As above re: truncation vs rounding.
v[implicit] = (( # Fix implicit points; again, truncate.
(v[implicit - 1] + v[implicit + 1]) / 2).astype(int))
procs[font.get_glyph_name(glyph_id)] = (
" ".join(map(str, d1)).encode("ascii") + b" d1\n"
+ _path.convert_to_string(
Path(v, c), None, None, False, None, -1,
# no code for quad Beziers triggers auto-conversion to cubics.
[b"m", b"l", b"", b"c", b"h"], True)
+ b"f")
return procs
class PdfFile:
"""PDF file object."""
def __init__(self, filename, metadata=None):
"""
Parameters
----------
filename : str or path-like or file-like
Output target; if a string, a file will be opened for writing.
metadata : dict from strings to strings and dates
Information dictionary object (see PDF reference section 10.2.1
'Document Information Dictionary'), e.g.:
``{'Creator': 'My software', 'Author': 'Me', 'Title': 'Awesome'}``.
The standard keys are 'Title', 'Author', 'Subject', 'Keywords',
'Creator', 'Producer', 'CreationDate', 'ModDate', and
'Trapped'. Values have been predefined for 'Creator', 'Producer'
and 'CreationDate'. They can be removed by setting them to `None`.
"""
super().__init__()
self._object_seq = itertools.count(1) # consumed by reserveObject
self.xrefTable = [[0, 65535, 'the zero object']]
self.passed_in_file_object = False
self.original_file_like = None
self.tell_base = 0
fh, opened = cbook.to_filehandle(filename, "wb", return_opened=True)
if not opened:
try:
self.tell_base = filename.tell()
except OSError:
fh = BytesIO()
self.original_file_like = filename
else:
fh = filename
self.passed_in_file_object = True
self.fh = fh
self.currentstream = None # stream object to write to, if any
fh.write(b"%PDF-1.4\n") # 1.4 is the first version to have alpha
# Output some eight-bit chars as a comment so various utilities
# recognize the file as binary by looking at the first few
# lines (see note in section 3.4.1 of the PDF reference).
fh.write(b"%\254\334 \253\272\n")
self.rootObject = self.reserveObject('root')
self.pagesObject = self.reserveObject('pages')
self.pageList = []
self.fontObject = self.reserveObject('fonts')
self._extGStateObject = self.reserveObject('extended graphics states')
self.hatchObject = self.reserveObject('tiling patterns')
self.gouraudObject = self.reserveObject('Gouraud triangles')
self.XObjectObject = self.reserveObject('external objects')
self.resourceObject = self.reserveObject('resources')
root = {'Type': Name('Catalog'),
'Pages': self.pagesObject}
self.writeObject(self.rootObject, root)
self.infoDict = _create_pdf_info_dict('pdf', metadata or {})
self.fontNames = {} # maps filenames to internal font names
self._internal_font_seq = (Name(f'F{i}') for i in itertools.count(1))
self.dviFontInfo = {} # maps dvi font names to embedding information
# differently encoded Type-1 fonts may share the same descriptor
self.type1Descriptors = {}
self._character_tracker = _backend_pdf_ps.CharacterTracker()
self.alphaStates = {} # maps alpha values to graphics state objects
self._alpha_state_seq = (Name(f'A{i}') for i in itertools.count(1))
self._soft_mask_states = {}
self._soft_mask_seq = (Name(f'SM{i}') for i in itertools.count(1))
self._soft_mask_groups = []
self.hatchPatterns = {}
self._hatch_pattern_seq = (Name(f'H{i}') for i in itertools.count(1))
self.gouraudTriangles = []
self._images = {}
self._image_seq = (Name(f'I{i}') for i in itertools.count(1))
self.markers = {}
self.multi_byte_charprocs = {}
self.paths = []
# A list of annotations for each page. Each entry is a tuple of the
# overall Annots object reference that's inserted into the page object,
# followed by a list of the actual annotations.
self._annotations = []
# For annotations added before a page is created; mostly for the
# purpose of newTextnote.
self.pageAnnotations = []
# The PDF spec recommends to include every procset
procsets = [Name(x) for x in "PDF Text ImageB ImageC ImageI".split()]
# Write resource dictionary.
# Possibly TODO: more general ExtGState (graphics state dictionaries)
# ColorSpace Pattern Shading Properties
resources = {'Font': self.fontObject,
'XObject': self.XObjectObject,
'ExtGState': self._extGStateObject,
'Pattern': self.hatchObject,
'Shading': self.gouraudObject,
'ProcSet': procsets}
self.writeObject(self.resourceObject, resources)
def newPage(self, width, height):
self.endStream()
self.width, self.height = width, height
contentObject = self.reserveObject('page contents')
annotsObject = self.reserveObject('annotations')
thePage = {'Type': Name('Page'),
'Parent': self.pagesObject,
'Resources': self.resourceObject,
'MediaBox': [0, 0, 72 * width, 72 * height],
'Contents': contentObject,
'Annots': annotsObject,
}
pageObject = self.reserveObject('page')
self.writeObject(pageObject, thePage)
self.pageList.append(pageObject)
self._annotations.append((annotsObject, self.pageAnnotations))
self.beginStream(contentObject.id,
self.reserveObject('length of content stream'))
# Initialize the pdf graphics state to match the default Matplotlib
# graphics context (colorspace and joinstyle).
self.output(Name('DeviceRGB'), Op.setcolorspace_stroke)
self.output(Name('DeviceRGB'), Op.setcolorspace_nonstroke)
self.output(GraphicsContextPdf.joinstyles['round'], Op.setlinejoin)
# Clear the list of annotations for the next page
self.pageAnnotations = []
def newTextnote(self, text, positionRect=[-100, -100, 0, 0]):
# Create a new annotation of type text
theNote = {'Type': Name('Annot'),
'Subtype': Name('Text'),
'Contents': text,
'Rect': positionRect,
}
self.pageAnnotations.append(theNote)
def _get_subsetted_psname(self, ps_name, charmap):
def toStr(n, base):
if n < base:
return string.ascii_uppercase[n]
else:
return (
toStr(n // base, base) + string.ascii_uppercase[n % base]
)
# encode to string using base 26
hashed = hash(frozenset(charmap.keys())) % ((sys.maxsize + 1) * 2)
prefix = toStr(hashed, 26)
# get first 6 characters from prefix
return prefix[:6] + "+" + ps_name
def finalize(self):
"""Write out the various deferred objects and the pdf end matter."""
self.endStream()
self._write_annotations()
self.writeFonts()
self.writeExtGSTates()
self._write_soft_mask_groups()
self.writeHatches()
self.writeGouraudTriangles()
xobjects = {
name: ob for image, name, ob in self._images.values()}
for tup in self.markers.values():
xobjects[tup[0]] = tup[1]
for name, value in self.multi_byte_charprocs.items():
xobjects[name] = value
for name, path, trans, ob, join, cap, padding, filled, stroked \
in self.paths:
xobjects[name] = ob
self.writeObject(self.XObjectObject, xobjects)
self.writeImages()
self.writeMarkers()
self.writePathCollectionTemplates()
self.writeObject(self.pagesObject,
{'Type': Name('Pages'),
'Kids': self.pageList,
'Count': len(self.pageList)})
self.writeInfoDict()
# Finalize the file
self.writeXref()
self.writeTrailer()
def close(self):
"""Flush all buffers and free all resources."""
self.endStream()
if self.passed_in_file_object:
self.fh.flush()
else:
if self.original_file_like is not None:
self.original_file_like.write(self.fh.getvalue())
self.fh.close()
def write(self, data):
if self.currentstream is None:
self.fh.write(data)
else:
self.currentstream.write(data)
def output(self, *data):
self.write(_fill([pdfRepr(x) for x in data]))
self.write(b'\n')
def beginStream(self, id, len, extra=None, png=None):
assert self.currentstream is None
self.currentstream = Stream(id, len, self, extra, png)
def endStream(self):
if self.currentstream is not None:
self.currentstream.end()
self.currentstream = None
def outputStream(self, ref, data, *, extra=None):
self.beginStream(ref.id, None, extra)
self.currentstream.write(data)
self.endStream()
def _write_annotations(self):
for annotsObject, annotations in self._annotations:
self.writeObject(annotsObject, annotations)
def fontName(self, fontprop):
"""
Select a font based on fontprop and return a name suitable for
Op.selectfont. If fontprop is a string, it will be interpreted
as the filename of the font.
"""
if isinstance(fontprop, str):
filenames = [fontprop]
elif mpl.rcParams['pdf.use14corefonts']:
filenames = _fontManager._find_fonts_by_props(
fontprop, fontext='afm', directory=RendererPdf._afm_font_dir
)
else:
filenames = _fontManager._find_fonts_by_props(fontprop)
first_Fx = None
for fname in filenames:
Fx = self.fontNames.get(fname)
if not first_Fx:
first_Fx = Fx
if Fx is None:
Fx = next(self._internal_font_seq)
self.fontNames[fname] = Fx
_log.debug('Assigning font %s = %r', Fx, fname)
if not first_Fx:
first_Fx = Fx
# find_fontsprop's first value always adheres to
# findfont's value, so technically no behaviour change
return first_Fx
def dviFontName(self, dvifont):
"""
Given a dvi font object, return a name suitable for Op.selectfont.
This registers the font information in ``self.dviFontInfo`` if not yet
registered.
"""
dvi_info = self.dviFontInfo.get(dvifont.texname)
if dvi_info is not None:
return dvi_info.pdfname
tex_font_map = dviread.PsfontsMap(dviread.find_tex_file('pdftex.map'))
psfont = tex_font_map[dvifont.texname]
if psfont.filename is None:
raise ValueError(
"No usable font file found for {} (TeX: {}); "
"the font may lack a Type-1 version"
.format(psfont.psname, dvifont.texname))
pdfname = next(self._internal_font_seq)
_log.debug('Assigning font %s = %s (dvi)', pdfname, dvifont.texname)
self.dviFontInfo[dvifont.texname] = types.SimpleNamespace(
dvifont=dvifont,
pdfname=pdfname,
fontfile=psfont.filename,
basefont=psfont.psname,
encodingfile=psfont.encoding,
effects=psfont.effects)
return pdfname
def writeFonts(self):
fonts = {}
for dviname, info in sorted(self.dviFontInfo.items()):
Fx = info.pdfname
_log.debug('Embedding Type-1 font %s from dvi.', dviname)
fonts[Fx] = self._embedTeXFont(info)
for filename in sorted(self.fontNames):
Fx = self.fontNames[filename]
_log.debug('Embedding font %s.', filename)
if filename.endswith('.afm'):
# from pdf.use14corefonts
_log.debug('Writing AFM font.')
fonts[Fx] = self._write_afm_font(filename)
else:
# a normal TrueType font
_log.debug('Writing TrueType font.')
chars = self._character_tracker.used.get(filename)
if chars:
fonts[Fx] = self.embedTTF(filename, chars)
self.writeObject(self.fontObject, fonts)
def _write_afm_font(self, filename):
with open(filename, 'rb') as fh:
font = AFM(fh)
fontname = font.get_fontname()
fontdict = {'Type': Name('Font'),
'Subtype': Name('Type1'),
'BaseFont': Name(fontname),
'Encoding': Name('WinAnsiEncoding')}
fontdictObject = self.reserveObject('font dictionary')
self.writeObject(fontdictObject, fontdict)
return fontdictObject
def _embedTeXFont(self, fontinfo):
_log.debug('Embedding TeX font %s - fontinfo=%s',
fontinfo.dvifont.texname, fontinfo.__dict__)
# Widths
widthsObject = self.reserveObject('font widths')
self.writeObject(widthsObject, fontinfo.dvifont.widths)
# Font dictionary
fontdictObject = self.reserveObject('font dictionary')
fontdict = {
'Type': Name('Font'),