8000 Merge pull request #14413 from jkseppan/pdf-improve · matplotlib/matplotlib@d19e8c1 · GitHub
[go: up one dir, main page]

Skip to content

Commit d19e8c1

Browse files
authored
Merge pull request #14413 from jkseppan/pdf-improve
MAINT: small improvements to the pdf backend
2 parents c7bae08 + 73de372 commit d19e8c1

File tree

2 files changed

+60
-34
lines changed

2 files changed

+60
-34
lines changed
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
Removals
2+
````````
3+
4+
The following members of ``matplotlib.backends.backend_pdf.PdfFile`` were removed:
5+
6+
- ``nextObject``
7+
- ``nextFont``
8+
- ``nextAlphaState``
9+
- ``nextHatch``
10+
- ``nextImage``

lib/matplotlib/backends/backend_pdf.py

Lines changed: 50 additions & 34 deletions
< 629A tr class="diff-line-row">
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,10 @@
88
from datetime import datetime
99
from functools import total_ordering
1010
from io import BytesIO
11+
import itertools
1112
import logging
1213
import math
1314
import os
14-
import pathlib
1515
import re
1616
import struct
1717
import time
@@ -90,7 +90,7 @@
9090
# * encoding of fonts, including mathtext fonts and unicode support
9191
# * TTF support has lots of small TODOs, e.g., how do you know if a font
9292
# is serif/sans-serif, or symbolic/non-symbolic?
93-
# * draw_markers, draw_line_collection, etc.
93+
# * draw_quad_mesh
9494

9595

9696
def fill(strings, linelen=75):
@@ -348,11 +348,22 @@ class Stream:
348348
__slots__ = ('id', 'len', 'pdfFile', 'file', 'compressobj', 'extra', 'pos')
349349

350350
def __init__(self, id, len, file, extra=None, png=None):
351-
"""id: object id of stream; len: an unused Reference object for the
352-
length of the stream, or None (to use a memory buffer); file:
353-
a PdfFile; extra: a dictionary of extra key-value pairs to
354-
include in the stream header; png: if the data is already
355-
png compressed, the decode parameters"""
351+
"""
352+
Parameters
353+
----------
354+
355+
id : int
356+
Object id of the stream.
357+
len : Reference or None
358+
An unused Reference object for the length of the stream;
359+
None means to use a memory buffer so the length can be inlined.
360+
file : PdfFile
361+
The underlying object to write the stream to.
362+
extra : dict from Name to anything, or None
363+
Extra key-value pairs to include in the stream header.
364+
png : dict or None
365+
If the data is already png encoded, the decode parameters.
366+
"""
356367
self.id = id # object id
357368
self.len = len # id of length object
358369
self.pdfFile = file
@@ -424,7 +435,25 @@ class PdfFile:
424435
"""PDF file object."""
425436

426437
def __init__(self, filename, metadata=None):
427-
self.nextObject = 1 # next free object id
438+
"""
439+
Parameters
440+
----------
441+
442+
filename : file-like object or string
443+
Output target; if a string, a file will be opened for writing.
444+
metadata : dict from strings to strings and dates
445+
Information dictionary object (see PDF reference section 10.2.1
446+
'Document Information Dictionary'), e.g.:
447+
`{'Creator': 'My software', 'Author': 'Me',
448+
'Title': 'Awesome fig'}`.
449+
450+
The standard keys are `'Title'`, `'Author'`, `'Subject'`,
451+
`'Keywords'`, `'Creator'`, `'Producer'`, `'CreationDate'`,
452+
`'ModDate'`, and `'Trapped'`. Values have been predefined
453+
for `'Creator'`, `'Producer'` and `'CreationDate'`. They
454+
can be removed by setting them to `None`.
455+
"""
456+
self._object_seq = itertools.count(1) # consumed by reserveObject
428457
self.xrefTable = [[0, 65535, 'the zero object']]
429458
self.passed_in_file_object = False
430459
self.original_file_like = None
@@ -482,21 +511,21 @@ def __init__(self, filename, metadata=None):
482511
if v is not None}
483512

484513
self.fontNames = {} # maps filenames to internal font names
485-
self.nextFont = 1 # next free internal font name
514+
self._internal_font_seq = (Name(f'F{i}') for i in itertools.count(1))
486515
self.dviFontInfo = {} # maps dvi font names to embedding information
487516
# differently encoded Type-1 fonts may share the same descriptor
488517
self.type1Descriptors = {}
489518
self.used_characters = {}
490519

491520
self.alphaStates = {} # maps alpha values to graphics state objects
492-
self.nextAlphaState = 1
521+
self._alpha_state_seq = (Name(f'A{i}') for i in itertools.count(1))
493522
# reproducible writeHatches needs an ordered dict:
494523
self.hatchPatterns = collections.OrderedDict()
495-
self.nextHatch = 1
524+
self._hatch_pattern_seq = (Name(f'H{i}') for i in itertools.count(1))
496525
self.gouraudTriangles = []
497526

498527
self._images = collections.OrderedDict() # reproducible writeImages
499-
self.nextImage = 1
528+
self._image_seq = (Name(f'I{i}') for i in itertools.count(1))
500529

501530
self.markers = collections.OrderedDict() # reproducible writeMarkers
502531
self.multi_byte_charprocs = {}
@@ -643,9 +672,8 @@ def fontName(self, fontprop):
643672

644673
Fx = self.fontNames.get(filename)
645674
if Fx is None:
646-
Fx = Name('F%d' % self.nextFont)
675+
Fx = next(self._internal_font_seq)
647676
self.fontNames[filename] = Fx
648-
self.nextFont += 1
649677
_log.debug('Assigning font %s = %r', Fx, filename)
650678

651679
return Fx
@@ -669,8 +697,7 @@ def dviFontName(self, dvifont):
669697
"the font may lack a Type-1 version"
670698
.format(psfont.psname, dvifont.texname))
671699

672-
pdfname = Name('F%d' % self.nextFont)
673-
self.nextFont += 1
700+
pdfname = next(self._internal_font_seq)
674701
_log.debug('Assigning font %s = %s (dvi)', pdfname, dvifont.texname)
675702
self.dviFontInfo[dvifont.texname] = types.SimpleNamespace(
676703
dvifont=dvifont,
@@ -1186,8 +1213,7 @@ def alphaState(self, alpha):
11861213
if state is not None:
11871214
return state[0]
11881215

1189-
name = Name('A%d' % self.nextAlphaState)
1190-
self.nextAlphaState += 1
1216+
name = next(self._alpha_state_seq)
11911217
self.alphaStates[alpha] = \
11921218
(name, {'Type': Name('ExtGState'),
11931219
'CA': alpha[0], 'ca': alpha[1]})
@@ -1207,8 +1233,7 @@ def hatchPattern(self, hatch_style):
12071233
if pattern is not None:
12081234
return pattern
12091235

1210-
name = Name('H%d' % self.nextHatch)
1211-
self.nextHatch += 1
1236+
name = next(self._hatch_pattern_seq)
12121237
self.hatchPatterns[hatch_style] = name
12131238
return name
12141239

@@ -1300,9 +1325,8 @@ def imageObject(self, image):
13001325
if entry is not None:
13011326
return entry[1]
13021327

1303-
name = Name('I%d' % self.nextImage)
1304-
ob = self.reserveObject('image %d' % self.nextImage)
1305-
self.nextImage += 1
1328+
name = next(self._image_seq)
1329+
ob = self.reserveObject(f'image {name}')
13061330
self._images[id(image)] = (image, name, ob)
13071331
return name
13081332

@@ -1495,8 +1519,7 @@ def reserveObject(self, name=''):
14951519
the object with writeObject.
14961520
"""
14971521

1498-
id = self.nextObject
1499-
self.nextObject += 1
1522+
id = next(self._object_seq)
15001523
self.xrefTable.append([None, 0, name])
15011524
return Reference(id)
15021525

@@ -1510,7 +1533,7 @@ def writeObject(self, object, contents):
15101533
def writeXref(self):
15111534
"""Write out the xref table."""
15121535
self.startxref = self.fh.tell() - self.tell_base
1513-
self.write(b"xref\n0 %d\n" % self.nextObject)
1536+
self.write(b"xref\n0 %d\n" % len(self.xrefTable))
15141537
for i, (offset, generation, name) in enumerate(self.xrefTable):
15151538
if offset is None:
15161539
raise AssertionError(
@@ -1557,7 +1580,7 @@ def writeTrailer(self):
15571580

15581581
self.write(b"trailer\n")
15591582
self.write(pdfRepr(
1560-
{'Size': self.nextObject,
1583+
{'Size': len(self.xrefTable),
15611584
'Root': self.rootObject,
15621585
'Info': self.infoObject}))
15631586
# Could add 'ID'
@@ -2316,13 +2339,6 @@ def finalize(self):
23162339
cmds.extend(self.pop())
23172340
return cmds
23182341

2319-
########################################################################
2320-
#
2321-
# The following functions and classes are for pylab and implement
2322-
# window/figure managers, etc...
2323-
#
2324-
########################################################################
2325-
23262342

23272343
class PdfPages:
23282344
"""

0 commit comments

Comments
 (0)
0