ttfonts.py 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313
  1. #Copyright ReportLab Europe Ltd. 2000-2017
  2. #see license.txt for license details
  3. __version__ = '$Id$'
  4. __doc__="""TrueType font support
  5. This defines classes to represent TrueType fonts. They know how to calculate
  6. their own width and how to write themselves into PDF files. They support
  7. subsetting and embedding and can represent all 16-bit Unicode characters.
  8. Note on dynamic fonts
  9. ---------------------
  10. Usually a Font in ReportLab corresponds to a fixed set of PDF objects (Font,
  11. FontDescriptor, Encoding). But with dynamic font subsetting a single TTFont
  12. will result in a number of Font/FontDescriptor/Encoding object sets, and the
  13. contents of those will depend on the actual characters used for printing.
  14. To support dynamic font subsetting a concept of "dynamic font" was introduced.
  15. Dynamic Fonts have a _dynamicFont attribute set to 1.
  16. Dynamic fonts have the following additional functions::
  17. def splitString(self, text, doc):
  18. '''Splits text into a number of chunks, each of which belongs to a
  19. single subset. Returns a list of tuples (subset, string). Use
  20. subset numbers with getSubsetInternalName. Doc is used to identify
  21. a document so that different documents may have different dynamically
  22. constructed subsets.'''
  23. def getSubsetInternalName(self, subset, doc):
  24. '''Returns the name of a PDF Font object corresponding to a given
  25. subset of this dynamic font. Use this function instead of
  26. PDFDocument.getInternalFontName.'''
  27. You must never call PDFDocument.getInternalFontName for dynamic fonts.
  28. If you have a traditional static font, mapping to PDF text output operators
  29. is simple::
  30. '%s 14 Tf (%s) Tj' % (getInternalFontName(psfontname), text)
  31. If you have a dynamic font, use this instead::
  32. for subset, chunk in font.splitString(text, doc):
  33. '%s 14 Tf (%s) Tj' % (font.getSubsetInternalName(subset, doc), chunk)
  34. (Tf is a font setting operator and Tj is a text ouput operator. You should
  35. also escape invalid characters in Tj argument, see TextObject._formatText.
  36. Oh, and that 14 up there is font size.)
  37. Canvas and TextObject have special support for dynamic fonts.
  38. """
  39. from struct import pack, unpack, error as structError
  40. from reportlab.lib.utils import getBytesIO, bytestr, isUnicode, char2int, bytesT, isStr, isBytes
  41. from reportlab.pdfbase import pdfmetrics, pdfdoc
  42. from reportlab import rl_config
  43. from reportlab.lib.rl_accel import hex32, add32, calcChecksum, instanceStringWidthTTF
  44. from collections import namedtuple
  45. import os, time
  46. class TTFError(pdfdoc.PDFError):
  47. "TrueType font exception"
  48. pass
  49. def SUBSETN(n,table=bytes.maketrans(b'0123456789',b'ABCDEFGIJK')):
  50. return bytes('%6.6d'%n,'ASCII').translate(table)
  51. #
  52. # Helpers
  53. #
  54. def makeToUnicodeCMap(fontname, subset):
  55. """Creates a ToUnicode CMap for a given subset. See Adobe
  56. _PDF_Reference (ISBN 0-201-75839-3) for more information."""
  57. cmap = [
  58. "/CIDInit /ProcSet findresource begin",
  59. "12 dict begin",
  60. "begincmap",
  61. "/CIDSystemInfo",
  62. "<< /Registry (%s)" % fontname,
  63. "/Ordering (%s)" % fontname,
  64. "/Supplement 0",
  65. ">> def",
  66. "/CMapName /%s def" % fontname,
  67. "/CMapType 2 def",
  68. "1 begincodespacerange",
  69. "<00> <%02X>" % (len(subset) - 1),
  70. "endcodespacerange",
  71. "%d beginbfchar" % len(subset)
  72. ] + ["<%02X> <%04X>" % (i,v) for i,v in enumerate(subset)] + [
  73. "endbfchar",
  74. "endcmap",
  75. "CMapName currentdict /CMap defineresource pop",
  76. "end",
  77. "end"
  78. ]
  79. return '\n'.join(cmap)
  80. def splice(stream, offset, value):
  81. """Splices the given value into stream at the given offset and
  82. returns the resulting stream (the original is unchanged)"""
  83. return stream[:offset] + value + stream[offset + len(value):]
  84. def _set_ushort(stream, offset, value):
  85. """Writes the given unsigned short value into stream at the given
  86. offset and returns the resulting stream (the original is unchanged)"""
  87. return splice(stream, offset, pack(">H", value))
  88. #
  89. # TrueType font handling
  90. #
  91. GF_ARG_1_AND_2_ARE_WORDS = 1 << 0
  92. GF_ARGS_ARE_XY_VALUES = 1 << 1
  93. GF_ROUND_XY_TO_GRID = 1 << 2
  94. GF_WE_HAVE_A_SCALE = 1 << 3
  95. GF_RESERVED = 1 << 4
  96. GF_MORE_COMPONENTS = 1 << 5
  97. GF_WE_HAVE_AN_X_AND_Y_SCALE = 1 << 6
  98. GF_WE_HAVE_A_TWO_BY_TWO = 1 << 7
  99. GF_WE_HAVE_INSTRUCTIONS = 1 << 8
  100. GF_USE_MY_METRICS = 1 << 9
  101. GF_OVERLAP_COMPOUND = 1 << 10
  102. GF_SCALED_COMPONENT_OFFSET = 1 << 11
  103. GF_UNSCALED_COMPONENT_OFFSET = 1 << 12
  104. _cached_ttf_dirs={}
  105. def _ttf_dirs(*roots):
  106. R = _cached_ttf_dirs.get(roots,None)
  107. if R is None:
  108. join = os.path.join
  109. realpath = os.path.realpath
  110. R = []
  111. aR = R.append
  112. for root in roots:
  113. for r, d, f in os.walk(root,followlinks=True):
  114. s = realpath(r)
  115. if s not in R: aR(s)
  116. for s in d:
  117. s = realpath(join(r,s))
  118. if s not in R: aR(s)
  119. _cached_ttf_dirs[roots] = R
  120. return R
  121. def TTFOpenFile(fn):
  122. '''Opens a TTF file possibly after searching TTFSearchPath
  123. returns (filename,file)
  124. '''
  125. from reportlab.lib.utils import rl_isfile, open_for_read
  126. try:
  127. f = open_for_read(fn,'rb')
  128. return fn, f
  129. except IOError:
  130. import os
  131. if not os.path.isabs(fn):
  132. for D in _ttf_dirs(*rl_config.TTFSearchPath):
  133. tfn = os.path.join(D,fn)
  134. if rl_isfile(tfn):
  135. f = open_for_read(tfn,'rb')
  136. return tfn, f
  137. raise TTFError('Can\'t open file "%s"' % fn)
  138. class TTFontParser:
  139. "Basic TTF file parser"
  140. ttfVersions = (0x00010000,0x74727565,0x74746366)
  141. ttcVersions = (0x00010000,0x00020000)
  142. fileKind='TTF'
  143. def __init__(self, file, validate=0,subfontIndex=0):
  144. """Loads and parses a TrueType font file. file can be a filename or a
  145. file object. If validate is set to a false values, skips checksum
  146. validation. This can save time, especially if the font is large.
  147. """
  148. self.validate = validate
  149. self.readFile(file)
  150. isCollection = self.readHeader()
  151. if isCollection:
  152. self.readTTCHeader()
  153. self.getSubfont(subfontIndex)
  154. else:
  155. if self.validate: self.checksumFile()
  156. self.readTableDirectory()
  157. self.subfontNameX = b''
  158. def readTTCHeader(self):
  159. self.ttcVersion = self.read_ulong()
  160. self.fileKind = 'TTC'
  161. self.ttfVersions = self.ttfVersions[:-1]
  162. if self.ttcVersion not in self.ttcVersions:
  163. raise TTFError('"%s" is not a %s file: can\'t read version 0x%8.8x' %(self.filename,self.fileKind,self.ttcVersion))
  164. self.numSubfonts = self.read_ulong()
  165. self.subfontOffsets = []
  166. a = self.subfontOffsets.append
  167. for i in range(self.numSubfonts):
  168. a(self.read_ulong())
  169. def getSubfont(self,subfontIndex):
  170. if self.fileKind!='TTC':
  171. raise TTFError('"%s" is not a TTC file: use this method' % (self.filename,self.fileKind))
  172. try:
  173. pos = self.subfontOffsets[subfontIndex]
  174. except IndexError:
  175. raise TTFError('TTC file "%s": bad subfontIndex %s not in [0,%d]' % (self.filename,subfontIndex,self.numSubfonts-1))
  176. self.seek(pos)
  177. self.readHeader()
  178. self.readTableDirectory()
  179. self.subfontNameX = bytestr('-'+str(subfontIndex))
  180. def readTableDirectory(self):
  181. try:
  182. self.numTables = self.read_ushort()
  183. self.searchRange = self.read_ushort()
  184. self.entrySelector = self.read_ushort()
  185. self.rangeShift = self.read_ushort()
  186. # Read table directory
  187. self.table = {}
  188. self.tables = []
  189. for n in range(self.numTables):
  190. record = {}
  191. record['tag'] = self.read_tag()
  192. record['checksum'] = self.read_ulong()
  193. record['offset'] = self.read_ulong()
  194. record['length'] = self.read_ulong()
  195. self.tables.append(record)
  196. self.table[record['tag']] = record
  197. except:
  198. raise TTFError('Corrupt %s file "%s" cannot read Table Directory' % (self.fileKind, self.filename))
  199. if self.validate: self.checksumTables()
  200. def readHeader(self):
  201. '''read the sfnt header at the current position'''
  202. try:
  203. self.version = version = self.read_ulong()
  204. except:
  205. raise TTFError('"%s" is not a %s file: can\'t read version' %(self.filename,self.fileKind))
  206. if version==0x4F54544F:
  207. raise TTFError('%s file "%s": postscript outlines are not supported'%(self.fileKind,self.filename))
  208. if version not in self.ttfVersions:
  209. raise TTFError('Not a recognized TrueType font: version=0x%8.8X' % version)
  210. return version==self.ttfVersions[-1]
  211. def readFile(self,f):
  212. if not hasattr(self,'_ttf_data'):
  213. if hasattr(f,'read'):
  214. self.filename = getattr(f,'name','(ttf)') #good idea Marius
  215. self._ttf_data = f.read()
  216. else:
  217. self.filename, f = TTFOpenFile(f)
  218. self._ttf_data = f.read()
  219. f.close()
  220. self._pos = 0
  221. def checksumTables(self):
  222. # Check the checksums for all tables
  223. for t in self.tables:
  224. table = self.get_chunk(t['offset'], t['length'])
  225. checksum = calcChecksum(table)
  226. if t['tag'] == 'head':
  227. adjustment = unpack('>l', table[8:8+4])[0]
  228. checksum = add32(checksum, -adjustment)
  229. xchecksum = t['checksum']
  230. if xchecksum != checksum:
  231. raise TTFError('TTF file "%s": invalid checksum %s table: %s (expected %s)' % (self.filename,hex32(checksum),t['tag'],hex32(xchecksum)))
  232. def checksumFile(self):
  233. # Check the checksums for the whole file
  234. checksum = calcChecksum(self._ttf_data)
  235. if 0xB1B0AFBA!=checksum:
  236. raise TTFError('TTF file "%s": invalid checksum %s (expected 0xB1B0AFBA) len: %d &3: %d' % (self.filename,hex32(checksum),len(self._ttf_data),(len(self._ttf_data)&3)))
  237. def get_table_pos(self, tag):
  238. "Returns the offset and size of a given TTF table."
  239. offset = self.table[tag]['offset']
  240. length = self.table[tag]['length']
  241. return (offset, length)
  242. def seek(self, pos):
  243. "Moves read pointer to a given offset in file."
  244. self._pos = pos
  245. def skip(self, delta):
  246. "Skip the given number of bytes."
  247. self._pos = self._pos + delta
  248. def seek_table(self, tag, offset_in_table = 0):
  249. """Moves read pointer to the given offset within a given table and
  250. returns absolute offset of that position in the file."""
  251. self._pos = self.get_table_pos(tag)[0] + offset_in_table
  252. return self._pos
  253. def read_tag(self):
  254. "Read a 4-character tag"
  255. self._pos += 4
  256. return str(self._ttf_data[self._pos - 4:self._pos],'utf8')
  257. def get_chunk(self, pos, length):
  258. "Return a chunk of raw data at given position"
  259. return bytes(self._ttf_data[pos:pos+length])
  260. def read_uint8(self):
  261. self._pos += 1
  262. return int(self._ttf_data[self._pos-1])
  263. def read_ushort(self):
  264. "Reads an unsigned short"
  265. self._pos += 2
  266. return unpack('>H',self._ttf_data[self._pos-2:self._pos])[0]
  267. def read_ulong(self):
  268. "Reads an unsigned long"
  269. self._pos += 4
  270. return unpack('>L',self._ttf_data[self._pos - 4:self._pos])[0]
  271. def read_short(self):
  272. "Reads a signed short"
  273. self._pos += 2
  274. try:
  275. return unpack('>h',self._ttf_data[self._pos-2:self._pos])[0]
  276. except structError as error:
  277. raise TTFError(error)
  278. def get_ushort(self, pos):
  279. "Return an unsigned short at given position"
  280. return unpack('>H',self._ttf_data[pos:pos+2])[0]
  281. def get_ulong(self, pos):
  282. "Return an unsigned long at given position"
  283. return unpack('>L',self._ttf_data[pos:pos+4])[0]
  284. def get_table(self, tag):
  285. "Return the given TTF table"
  286. pos, length = self.get_table_pos(tag)
  287. return self._ttf_data[pos:pos+length]
  288. class TTFontMaker:
  289. "Basic TTF file generator"
  290. def __init__(self):
  291. "Initializes the generator."
  292. self.tables = {}
  293. def add(self, tag, data):
  294. "Adds a table to the TTF file."
  295. if tag == 'head':
  296. data = splice(data, 8, b'\0\0\0\0')
  297. self.tables[tag] = data
  298. def makeStream(self):
  299. "Finishes the generation and returns the TTF file as a string"
  300. stm = getBytesIO()
  301. write = stm.write
  302. tables = self.tables
  303. numTables = len(tables)
  304. searchRange = 1
  305. entrySelector = 0
  306. while searchRange * 2 <= numTables:
  307. searchRange = searchRange * 2
  308. entrySelector = entrySelector + 1
  309. searchRange = searchRange * 16
  310. rangeShift = numTables * 16 - searchRange
  311. # Header
  312. write(pack(">lHHHH", 0x00010000, numTables, searchRange,
  313. entrySelector, rangeShift))
  314. # Table directory
  315. offset = 12 + numTables * 16
  316. wStr = lambda x:write(bytes(tag,'latin1'))
  317. tables_items = list(sorted(tables.items()))
  318. for tag, data in tables_items:
  319. if tag == 'head':
  320. head_start = offset
  321. checksum = calcChecksum(data)
  322. wStr(tag)
  323. write(pack(">LLL", checksum, offset, len(data)))
  324. paddedLength = (len(data)+3)&~3
  325. offset = offset + paddedLength
  326. # Table data
  327. for tag, data in tables_items:
  328. data += b"\0\0\0"
  329. write(data[:len(data)&~3])
  330. checksum = calcChecksum(stm.getvalue())
  331. checksum = add32(0xB1B0AFBA, -checksum)
  332. stm.seek(head_start + 8)
  333. write(pack('>L', checksum))
  334. return stm.getvalue()
  335. #this is used in the cmap encoding fmt==2 case
  336. CMapFmt2SubHeader = namedtuple('CMapFmt2SubHeader', 'firstCode entryCount idDelta idRangeOffset')
  337. class TTFNameBytes(bytesT):
  338. '''class used to return named strings'''
  339. def __new__(cls,b,enc='utf8'):
  340. try:
  341. ustr = b.decode(enc)
  342. except:
  343. ustr = b.decode('latin1')
  344. self = bytesT.__new__(cls,ustr.encode('utf8'))
  345. self.ustr = ustr
  346. return self
  347. class TTFontFile(TTFontParser):
  348. "TTF file parser and generator"
  349. _agfnc = 0
  350. _agfnm = {}
  351. def __init__(self, file, charInfo=1, validate=0,subfontIndex=0):
  352. """Loads and parses a TrueType font file.
  353. file can be a filename or a file object. If validate is set to a false
  354. values, skips checksum validation. This can save time, especially if
  355. the font is large. See TTFontFile.extractInfo for more information.
  356. """
  357. if isStr(subfontIndex): #bytes or unicode
  358. sfi = 0
  359. __dict__ = self.__dict__.copy()
  360. while True:
  361. TTFontParser.__init__(self, file, validate=validate,subfontIndex=sfi)
  362. numSubfonts = self.numSubfonts = self.read_ulong()
  363. self.extractInfo(charInfo)
  364. if (isBytes(subfontIndex) and subfontIndex==self.name
  365. or subfontIndex==self.name.ustr): #we found it
  366. return
  367. if not sfi:
  368. __dict__.update(dict(_ttf_data=self._ttf_data, filename=self.filename))
  369. sfi += 1
  370. if sfi>=numSubfonts:
  371. raise ValueError('cannot find %r subfont %r' % (self.filename, subfontIndex))
  372. self.__dict__.clear()
  373. self.__dict__.update(__dict__)
  374. else:
  375. TTFontParser.__init__(self, file, validate=validate,subfontIndex=subfontIndex)
  376. self.extractInfo(charInfo)
  377. def extractInfo(self, charInfo=1):
  378. """
  379. Extract typographic information from the loaded font file.
  380. The following attributes will be set::
  381. name PostScript font name
  382. flags Font flags
  383. ascent Typographic ascender in 1/1000ths of a point
  384. descent Typographic descender in 1/1000ths of a point
  385. capHeight Cap height in 1/1000ths of a point (0 if not available)
  386. bbox Glyph bounding box [l,t,r,b] in 1/1000ths of a point
  387. _bbox Glyph bounding box [l,t,r,b] in unitsPerEm
  388. unitsPerEm Glyph units per em
  389. italicAngle Italic angle in degrees ccw
  390. stemV stem weight in 1/1000ths of a point (approximate)
  391. If charInfo is true, the following will also be set::
  392. defaultWidth default glyph width in 1/1000ths of a point
  393. charWidths dictionary of character widths for every supported UCS character
  394. code
  395. This will only work if the font has a Unicode cmap (platform 3,
  396. encoding 1, format 4 or platform 0 any encoding format 4). Setting
  397. charInfo to false avoids this requirement
  398. """
  399. # name - Naming table
  400. name_offset = self.seek_table("name")
  401. format = self.read_ushort()
  402. if format != 0:
  403. raise TTFError("Unknown name table format (%d)" % format)
  404. numRecords = self.read_ushort()
  405. string_data_offset = name_offset + self.read_ushort()
  406. names = {1:None,2:None,3:None,4:None,6:None}
  407. K = list(names.keys())
  408. nameCount = len(names)
  409. for i in range(numRecords):
  410. platformId = self.read_ushort()
  411. encodingId = self.read_ushort()
  412. languageId = self.read_ushort()
  413. nameId = self.read_ushort()
  414. length = self.read_ushort()
  415. offset = self.read_ushort()
  416. if nameId not in K: continue
  417. N = None
  418. if platformId == 3 and encodingId == 1 and languageId == 0x409: # Microsoft, Unicode, US English, PS Name
  419. opos = self._pos
  420. try:
  421. self.seek(string_data_offset + offset)
  422. if length % 2 != 0:
  423. raise TTFError("PostScript name is UTF-16BE string of odd length")
  424. N = TTFNameBytes(self.get_chunk(string_data_offset + offset, length),'utf_16_be')
  425. finally:
  426. self._pos = opos
  427. elif platformId == 1 and encodingId == 0 and languageId == 0: # Macintosh, Roman, English, PS Name
  428. # According to OpenType spec, if PS name exists, it must exist
  429. # both in MS Unicode and Macintosh Roman formats. Apparently,
  430. # you can find live TTF fonts which only have Macintosh format.
  431. N = TTFNameBytes(self.get_chunk(string_data_offset + offset, length),'mac_roman')
  432. if N and names[nameId]==None:
  433. names[nameId] = N
  434. nameCount -= 1
  435. if nameCount==0: break
  436. if names[6] is not None:
  437. psName = names[6]
  438. elif names[4] is not None:
  439. psName = names[4]
  440. # Fine, one last try before we bail.
  441. elif names[1] is not None:
  442. psName = names[1]
  443. else:
  444. psName = None
  445. # Don't just assume, check for None since some shoddy fonts cause crashes here...
  446. if not psName:
  447. if rl_config.autoGenerateTTFMissingTTFName:
  448. fn = self.filename
  449. if fn:
  450. bfn = os.path.splitext(os.path.basename(fn))[0]
  451. if not fn:
  452. psName = bytestr('_RL_%s_%s_TTF' % (time.time(), self.__class__._agfnc))
  453. self.__class__._agfnc += 1
  454. else:
  455. psName = self._agfnm.get(fn,'')
  456. if not psName:
  457. if bfn:
  458. psName = bytestr('_RL_%s_TTF' % bfn)
  459. else:
  460. psName = bytestr('_RL_%s_%s_TTF' % (time.time(), self.__class__._agfnc))
  461. self.__class__._agfnc += 1
  462. self._agfnm[fn] = psName
  463. else:
  464. raise TTFError("Could not find PostScript font name")
  465. psName = psName.__class__(psName.replace(b" ", b"-")) #Dinu Gherman's fix for font names with spaces
  466. for c in psName:
  467. if char2int(c)>126 or c in b' [](){}<>/%':
  468. raise TTFError("psName=%r contains invalid character %s" % (psName,ascii(c)))
  469. self.name = psName
  470. self.familyName = names[1] or psName
  471. self.styleName = names[2] or 'Regular'
  472. self.fullName = names[4] or psName
  473. self.uniqueFontID = names[3] or psName
  474. # head - Font header table
  475. try:
  476. self.seek_table("head")
  477. except:
  478. raise TTFError('head table not found ttf name=%s' % self.name)
  479. ver_maj, ver_min = self.read_ushort(), self.read_ushort()
  480. if ver_maj != 1:
  481. raise TTFError('Unknown head table version %d.%04x' % (ver_maj, ver_min))
  482. self.fontRevision = self.read_ushort(), self.read_ushort()
  483. self.skip(4)
  484. magic = self.read_ulong()
  485. if magic != 0x5F0F3CF5:
  486. raise TTFError('Invalid head table magic %04x' % magic)
  487. self.skip(2)
  488. self.unitsPerEm = unitsPerEm = self.read_ushort()
  489. scale = lambda x, unitsPerEm=unitsPerEm: x * 1000. / unitsPerEm
  490. self.skip(16)
  491. xMin = self.read_short()
  492. yMin = self.read_short()
  493. xMax = self.read_short()
  494. yMax = self.read_short()
  495. self.bbox = list(map(scale, [xMin, yMin, xMax, yMax]))
  496. self.skip(3*2)
  497. indexToLocFormat = self.read_ushort()
  498. glyphDataFormat = self.read_ushort()
  499. # OS/2 - OS/2 and Windows metrics table
  500. # (needs data from head table)
  501. subsettingAllowed = True
  502. if "OS/2" in self.table:
  503. self.seek_table("OS/2")
  504. version = self.read_ushort()
  505. self.skip(2)
  506. usWeightClass = self.read_ushort()
  507. self.skip(2)
  508. fsType = self.read_ushort()
  509. if fsType==0x0002 or (fsType & 0x0300):
  510. subsettingAllowed = os.path.basename(self.filename) not in rl_config.allowTTFSubsetting
  511. self.skip(58) #11*2 + 10 + 4*4 + 4 + 3*2
  512. sTypoAscender = self.read_short()
  513. sTypoDescender = self.read_short()
  514. self.ascent = scale(sTypoAscender) # XXX: for some reason it needs to be multiplied by 1.24--1.28
  515. self.descent = scale(sTypoDescender)
  516. if version > 1:
  517. self.skip(16) #3*2 + 2*4 + 2
  518. sCapHeight = self.read_short()
  519. self.capHeight = scale(sCapHeight)
  520. else:
  521. self.capHeight = self.ascent
  522. else:
  523. # Microsoft TTFs require an OS/2 table; Apple ones do not. Try to
  524. # cope. The data is not very important anyway.
  525. usWeightClass = 500
  526. self.ascent = scale(yMax)
  527. self.descent = scale(yMin)
  528. self.capHeight = self.ascent
  529. # There's no way to get stemV from a TTF file short of analyzing actual outline data
  530. # This fuzzy formula is taken from pdflib sources, but we could just use 0 here
  531. self.stemV = 50 + int((usWeightClass / 65.0) ** 2)
  532. # post - PostScript table
  533. # (needs data from OS/2 table)
  534. self.seek_table("post")
  535. ver_maj, ver_min = self.read_ushort(), self.read_ushort()
  536. if ver_maj not in (1, 2, 3, 4):
  537. # Adobe/MS documents 1, 2, 2.5, 3; Apple also has 4.
  538. # From Apple docs it seems that we do not need to care
  539. # about the exact version, so if you get this error, you can
  540. # try to remove this check altogether.
  541. raise TTFError('Unknown post table version %d.%04x' % (ver_maj, ver_min))
  542. self.italicAngle = self.read_short() + self.read_ushort() / 65536.0
  543. self.underlinePosition = self.read_short()
  544. self.underlineThickness = self.read_short()
  545. isFixedPitch = self.read_ulong()
  546. self.flags = FF_SYMBOLIC # All fonts that contain characters
  547. # outside the original Adobe character
  548. # set are considered "symbolic".
  549. if self.italicAngle!= 0:
  550. self.flags = self.flags | FF_ITALIC
  551. if usWeightClass >= 600: # FW_REGULAR == 500, FW_SEMIBOLD == 600
  552. self.flags = self.flags | FF_FORCEBOLD
  553. if isFixedPitch:
  554. self.flags = self.flags | FF_FIXED
  555. # XXX: FF_SERIF? FF_SCRIPT? FF_ALLCAP? FF_SMALLCAP?
  556. # hhea - Horizontal header table
  557. self.seek_table("hhea")
  558. ver_maj, ver_min = self.read_ushort(), self.read_ushort()
  559. if ver_maj != 1:
  560. raise TTFError('Unknown hhea table version %d.%04x' % (ver_maj, ver_min))
  561. self.skip(28)
  562. metricDataFormat = self.read_ushort()
  563. if metricDataFormat != 0:
  564. raise TTFError('Unknown horizontal metric data format (%d)' % metricDataFormat)
  565. numberOfHMetrics = self.read_ushort()
  566. if numberOfHMetrics == 0:
  567. raise TTFError('Number of horizontal metrics is 0')
  568. # maxp - Maximum profile table
  569. self.seek_table("maxp")
  570. ver_maj, ver_min = self.read_ushort(), self.read_ushort()
  571. if ver_maj != 1:
  572. raise TTFError('Unknown maxp table version %d.%04x' % (ver_maj, ver_min))
  573. self.numGlyphs = numGlyphs = self.read_ushort()
  574. if not subsettingAllowed:
  575. if self.numGlyphs>0xFF:
  576. raise TTFError('Font does not allow subsetting/embedding (%04X)' % fsType)
  577. else:
  578. self._full_font = True
  579. else:
  580. self._full_font = False
  581. if not charInfo:
  582. self.charToGlyph = None
  583. self.defaultWidth = None
  584. self.charWidths = None
  585. return
  586. if glyphDataFormat != 0:
  587. raise TTFError('Unknown glyph data format (%d)' % glyphDataFormat)
  588. # cmap - Character to glyph index mapping table
  589. cmap_offset = self.seek_table("cmap")
  590. cmapVersion = self.read_ushort()
  591. cmapTableCount = self.read_ushort()
  592. if cmapTableCount==0 and cmapVersion!=0:
  593. cmapTableCount, cmapVersion = cmapVersion, cmapTableCount
  594. encoffs = None
  595. enc = 0
  596. for n in range(cmapTableCount):
  597. platform = self.read_ushort()
  598. encoding = self.read_ushort()
  599. offset = self.read_ulong()
  600. if platform==3:
  601. enc = 1
  602. encoffs = offset
  603. elif platform==1 and encoding==0 and enc!=1:
  604. enc = 2
  605. encoffs = offset
  606. elif platform==1 and encoding==1:
  607. enc = 1
  608. encoffs = offset
  609. elif platform==0 and encoding!=5:
  610. enc = 1
  611. encoffs = offset
  612. if encoffs is None:
  613. raise TTFError('could not find a suitable cmap encoding')
  614. encoffs += cmap_offset
  615. self.seek(encoffs)
  616. fmt = self.read_ushort()
  617. self.charToGlyph = charToGlyph = {}
  618. glyphToChar = {}
  619. if fmt in (13,12,10,8):
  620. self.skip(2) #padding
  621. length = self.read_ulong()
  622. lang = self.read_ulong()
  623. else:
  624. length = self.read_ushort()
  625. lang = self.read_ushort()
  626. if fmt==0:
  627. T = [self.read_uint8() for i in range(length-6)]
  628. for unichar in range(min(256,self.numGlyphs,len(table))):
  629. glyph = T[glyph]
  630. charToGlyph[unichar] = glyph
  631. glyphToChar.setdefault(glyph,[]).append(unichar)
  632. elif fmt==4:
  633. limit = encoffs + length
  634. segCount = int(self.read_ushort() / 2.0)
  635. self.skip(6)
  636. endCount = [self.read_ushort() for _ in range(segCount)]
  637. self.skip(2)
  638. startCount = [self.read_ushort() for _ in range(segCount)]
  639. idDelta = [self.read_short() for _ in range(segCount)]
  640. idRangeOffset_start = self._pos
  641. idRangeOffset = [self.read_ushort() for _ in range(segCount)]
  642. # Now it gets tricky.
  643. for n in range(segCount):
  644. for unichar in range(startCount[n], endCount[n] + 1):
  645. if idRangeOffset[n] == 0:
  646. glyph = (unichar + idDelta[n]) & 0xFFFF
  647. else:
  648. offset = (unichar - startCount[n]) * 2 + idRangeOffset[n]
  649. offset = idRangeOffset_start + 2 * n + offset
  650. if offset >= limit:
  651. # workaround for broken fonts (like Thryomanes)
  652. glyph = 0
  653. else:
  654. glyph = self.get_ushort(offset)
  655. if glyph != 0:
  656. glyph = (glyph + idDelta[n]) & 0xFFFF
  657. charToGlyph[unichar] = glyph
  658. glyphToChar.setdefault(glyph,[]).append(unichar)
  659. elif fmt==6:
  660. first = self.read_ushort()
  661. count = self.read_ushort()
  662. for glyph in range(first,first+count):
  663. unichar = self.read_ushort()
  664. charToGlyph[unichar] = glyph
  665. glyphToChar.setdefault(glyph,[]).append(unichar)
  666. elif fmt==10:
  667. first = self.read_ulong()
  668. count = self.read_ulong()
  669. for glyph in range(first,first+count):
  670. unichar = self.read_ushort()
  671. charToGlyph[unichar] = glyph
  672. glyphToChar.setdefault(glyph,[]).append(unichar)
  673. elif fmt==12:
  674. segCount = self.read_ulong()
  675. for n in range(segCount):
  676. start = self.read_ulong()
  677. end = self.read_ulong()
  678. inc = self.read_ulong() - start
  679. for unichar in range(start,end+1):
  680. glyph = unichar + inc
  681. charToGlyph[unichar] = glyph
  682. glyphToChar.setdefault(glyph,[]).append(unichar)
  683. elif fmt==13:
  684. segCount = self.read_ulong()
  685. for n in range(segCount):
  686. start = self.read_ulong()
  687. end = self.read_ulong()
  688. gid = self.read_ulong()
  689. for unichar in range(start,end+1):
  690. charToGlyph[unichar] = gid
  691. glyphToChar.setdefault(gid,[]).append(unichar)
  692. elif fmt==2:
  693. T = [self.read_ushort() for i in range(256)] #subheader keys
  694. maxSHK = max(T)
  695. SH = []
  696. for i in range(maxSHK+1):
  697. firstCode = self.read_ushort()
  698. entryCount = self.read_ushort()
  699. idDelta = self.read_ushort()
  700. idRangeOffset = (self.read_ushort()-(maxSHK-i)*8-2)>>1
  701. SH.append(CMapFmt2SubHeader(firstCode,entryCount,idDelta,idRangeOffset))
  702. #number of glyph indexes to read. it is the length of the entire subtable minus that bit we've read so far
  703. entryCount = (length-(self._pos-(cmap_offset+encoffs)))>>1
  704. glyphs = [self.read_short() for i in range(entryCount)]
  705. last = -1
  706. for unichar in range(256):
  707. if T[unichar]==0:
  708. #Special case, single byte encoding entry, look unichar up in subhead
  709. if last!=-1:
  710. glyph = 0
  711. elif (unichar<SH[0].firstCode or unichar>=SH[0].firstCode+SH[0].entryCount or
  712. SH[0].idRangeOffset+(unichar-SH[0].firstCode)>=entryCount):
  713. glyph = 0
  714. else:
  715. glyph = glyphs[SH[0].idRangeOffset+(unichar-SH[0].firstCode)]
  716. if glyph!=0:
  717. glyph += SH[0].idDelta
  718. #assume the single byte codes are ascii
  719. if glyph!=0 and glyph<self.numGlyphs:
  720. charToGlyph[unichar] = glyph
  721. glyphToChar.setdefault(glyph,[]).append(unichar)
  722. else:
  723. k = T[unichar]
  724. for j in range(SH[k].entryCount):
  725. if SH[k].idRangeOffset+j>=entryCount:
  726. glyph = 0
  727. else:
  728. glyph = glyphs[SH[k].idRangeOffset+j]
  729. if glyph!= 0:
  730. glyph += SH[k].idDelta
  731. if glyph!=0 and glyph<self.numGlyphs:
  732. enc = (unichar<<8)|(j+SH[k].firstCode)
  733. charToGlyph[enc] = glyph
  734. glyphToChar.setdefault(glyph,[]).append(enc)
  735. if last==-1:
  736. last = unichar
  737. else:
  738. raise ValueError('Unsupported cmap encoding format %d' % fmt)
  739. # hmtx - Horizontal metrics table
  740. # (needs data from hhea, maxp, and cmap tables)
  741. self.seek_table("hmtx")
  742. aw = None
  743. self.charWidths = charWidths = {}
  744. self.hmetrics = []
  745. for glyph in range(numberOfHMetrics):
  746. # advance width and left side bearing. lsb is actually signed
  747. # short, but we don't need it anyway (except for subsetting)
  748. aw, lsb = self.read_ushort(), self.read_ushort()
  749. self.hmetrics.append((aw, lsb))
  750. aw = scale(aw)
  751. if glyph == 0:
  752. self.defaultWidth = aw
  753. if glyph in glyphToChar:
  754. for char in glyphToChar[glyph]:
  755. charWidths[char] = aw
  756. for glyph in range(numberOfHMetrics, numGlyphs):
  757. # the rest of the table only lists advance left side bearings.
  758. # so we reuse aw set by the last iteration of the previous loop
  759. lsb = self.read_ushort()
  760. self.hmetrics.append((aw, lsb))
  761. if glyph in glyphToChar:
  762. for char in glyphToChar[glyph]:
  763. charWidths[char] = aw
  764. # loca - Index to location
  765. if 'loca' not in self.table: raise TTFError('missing location table')
  766. self.seek_table('loca')
  767. self.glyphPos = []
  768. if indexToLocFormat == 0:
  769. for n in range(numGlyphs + 1):
  770. self.glyphPos.append(self.read_ushort() << 1)
  771. elif indexToLocFormat == 1:
  772. for n in range(numGlyphs + 1):
  773. self.glyphPos.append(self.read_ulong())
  774. else:
  775. raise TTFError('Unknown location table format (%d)' % indexToLocFormat)
  776. if 0x20 in charToGlyph:
  777. charToGlyph[0xa0] = charToGlyph[0x20]
  778. charWidths[0xa0] = charWidths[0x20]
  779. elif 0xa0 in charToGlyph:
  780. charToGlyph[0x20] = charToGlyph[0xa0]
  781. charWidths[0x20] = charWidths[0xa0]
  782. # Subsetting
  783. def makeSubset(self, subset):
  784. """Create a subset of a TrueType font"""
  785. output = TTFontMaker()
  786. # Build a mapping of glyphs in the subset to glyph numbers in
  787. # the original font. Also build a mapping of UCS codes to
  788. # glyph values in the new font.
  789. # Start with 0 -> 0: "missing character"
  790. glyphMap = [0] # new glyph index -> old glyph index
  791. glyphSet = {0:0} # old glyph index -> new glyph index
  792. codeToGlyph = {} # unicode -> new glyph index
  793. for code in subset:
  794. if code in self.charToGlyph:
  795. originalGlyphIdx = self.charToGlyph[code]
  796. else:
  797. originalGlyphIdx = 0
  798. if originalGlyphIdx not in glyphSet:
  799. glyphSet[originalGlyphIdx] = len(glyphMap)
  800. glyphMap.append(originalGlyphIdx)
  801. codeToGlyph[code] = glyphSet[originalGlyphIdx]
  802. # Also include glyphs that are parts of composite glyphs
  803. start = self.get_table_pos('glyf')[0]
  804. n = 0
  805. while n < len(glyphMap):
  806. originalGlyphIdx = glyphMap[n]
  807. glyphPos = self.glyphPos[originalGlyphIdx]
  808. glyphLen = self.glyphPos[originalGlyphIdx + 1] - glyphPos
  809. n += 1
  810. if not glyphLen: continue
  811. self.seek(start + glyphPos)
  812. numberOfContours = self.read_short()
  813. if numberOfContours < 0:
  814. # composite glyph
  815. self.skip(8)
  816. flags = GF_MORE_COMPONENTS
  817. while flags & GF_MORE_COMPONENTS:
  818. flags = self.read_ushort()
  819. glyphIdx = self.read_ushort()
  820. if glyphIdx not in glyphSet:
  821. glyphSet[glyphIdx] = len(glyphMap)
  822. glyphMap.append(glyphIdx)
  823. if flags & GF_ARG_1_AND_2_ARE_WORDS:
  824. self.skip(4)
  825. else:
  826. self.skip(2)
  827. if flags & GF_WE_HAVE_A_SCALE:
  828. self.skip(2)
  829. elif flags & GF_WE_HAVE_AN_X_AND_Y_SCALE:
  830. self.skip(4)
  831. elif flags & GF_WE_HAVE_A_TWO_BY_TWO:
  832. self.skip(8)
  833. # The following tables are simply copied from the original
  834. for tag in ('name', 'OS/2', 'cvt ', 'fpgm', 'prep'):
  835. try:
  836. output.add(tag, self.get_table(tag))
  837. except KeyError:
  838. # Apparently some of the tables are optional (cvt, fpgm, prep).
  839. # The lack of the required ones (name, OS/2) would have already
  840. # been caught before.
  841. pass
  842. # post - PostScript
  843. post = b"\x00\x03\x00\x00" + self.get_table('post')[4:16] + b"\x00" * 16
  844. output.add('post', post)
  845. numGlyphs = len(glyphMap)
  846. # hmtx - Horizontal Metrics
  847. hmtx = []
  848. for n in range(numGlyphs):
  849. aw, lsb = self.hmetrics[glyphMap[n]]
  850. hmtx.append(int(aw))
  851. hmtx.append(int(lsb))
  852. #work out n as 0 or first aw that's the start of a run
  853. n = len(hmtx)-2
  854. while n and hmtx[n]==hmtx[n-2]:
  855. n -= 2
  856. if not n: n = 2 #need at least one pair
  857. numberOfHMetrics = n>>1 #number of full H Metric pairs
  858. hmtx = hmtx[:n] + hmtx[n+1::2] #full pairs + all the trailing lsb's
  859. hmtx = pack(*([">%dH" % len(hmtx)] + hmtx))
  860. output.add('hmtx', hmtx)
  861. # hhea - Horizontal Header
  862. hhea = self.get_table('hhea')
  863. hhea = _set_ushort(hhea, 34, numberOfHMetrics)
  864. output.add('hhea', hhea)
  865. # maxp - Maximum Profile
  866. maxp = self.get_table('maxp')
  867. maxp = _set_ushort(maxp, 4, numGlyphs)
  868. output.add('maxp', maxp)
  869. # cmap - Character to glyph mapping
  870. # XXX maybe use format 0 if possible, not 6?
  871. entryCount = len(subset)
  872. length = 10 + entryCount * 2
  873. cmap = [0, 1, # version, number of tables
  874. 1, 0, 0,12, # platform, encoding, offset (hi,lo)
  875. 6, length, 0, # format, length, language
  876. 0,
  877. entryCount] + \
  878. list(map(codeToGlyph.get, subset))
  879. cmap = pack(*([">%dH" % len(cmap)] + cmap))
  880. output.add('cmap', cmap)
  881. # glyf - Glyph data
  882. glyphData = self.get_table('glyf')
  883. offsets = []
  884. glyf = []
  885. pos = 0
  886. for n in range(numGlyphs):
  887. offsets.append(pos)
  888. originalGlyphIdx = glyphMap[n]
  889. glyphPos = self.glyphPos[originalGlyphIdx]
  890. glyphLen = self.glyphPos[originalGlyphIdx + 1] - glyphPos
  891. data = glyphData[glyphPos:glyphPos+glyphLen]
  892. # Fix references in composite glyphs
  893. if glyphLen > 2 and unpack(">h", data[:2])[0] < 0:
  894. # composite glyph
  895. pos_in_glyph = 10
  896. flags = GF_MORE_COMPONENTS
  897. while flags & GF_MORE_COMPONENTS:
  898. flags = unpack(">H", data[pos_in_glyph:pos_in_glyph+2])[0]
  899. glyphIdx = unpack(">H", data[pos_in_glyph+2:pos_in_glyph+4])[0]
  900. data = _set_ushort(data, pos_in_glyph + 2, glyphSet[glyphIdx])
  901. pos_in_glyph = pos_in_glyph + 4
  902. if flags & GF_ARG_1_AND_2_ARE_WORDS:
  903. pos_in_glyph = pos_in_glyph + 4
  904. else:
  905. pos_in_glyph = pos_in_glyph + 2
  906. if flags & GF_WE_HAVE_A_SCALE:
  907. pos_in_glyph = pos_in_glyph + 2
  908. elif flags & GF_WE_HAVE_AN_X_AND_Y_SCALE:
  909. pos_in_glyph = pos_in_glyph + 4
  910. elif flags & GF_WE_HAVE_A_TWO_BY_TWO:
  911. pos_in_glyph = pos_in_glyph + 8
  912. glyf.append(data)
  913. pos = pos + glyphLen
  914. if pos % 4 != 0:
  915. padding = 4 - pos % 4
  916. glyf.append(b'\0' * padding)
  917. pos = pos + padding
  918. offsets.append(pos)
  919. output.add('glyf', b''.join(glyf))
  920. # loca - Index to location
  921. loca = []
  922. if (pos + 1) >> 1 > 0xFFFF:
  923. indexToLocFormat = 1 # long format
  924. for offset in offsets:
  925. loca.append(offset)
  926. loca = pack(*([">%dL" % len(loca)] + loca))
  927. else:
  928. indexToLocFormat = 0 # short format
  929. for offset in offsets:
  930. loca.append(offset >> 1)
  931. loca = pack(*([">%dH" % len(loca)] + loca))
  932. output.add('loca', loca)
  933. # head - Font header
  934. head = self.get_table('head')
  935. head = _set_ushort(head, 50, indexToLocFormat)
  936. output.add('head', head)
  937. return output.makeStream()
  938. #
  939. # TrueType font embedding
  940. #
  941. # PDF font flags (see PDF Reference Guide table 5.19)
  942. FF_FIXED = 1 << 1-1
  943. FF_SERIF = 1 << 2-1
  944. FF_SYMBOLIC = 1 << 3-1
  945. FF_SCRIPT = 1 << 4-1
  946. FF_NONSYMBOLIC = 1 << 6-1
  947. FF_ITALIC = 1 << 7-1
  948. FF_ALLCAP = 1 << 17-1
  949. FF_SMALLCAP = 1 << 18-1
  950. FF_FORCEBOLD = 1 << 19-1
  951. class TTFontFace(TTFontFile, pdfmetrics.TypeFace):
  952. """TrueType typeface.
  953. Conceptually similar to a single byte typeface, but the glyphs are
  954. identified by UCS character codes instead of glyph names."""
  955. def __init__(self, filename, validate=0, subfontIndex=0):
  956. "Loads a TrueType font from filename."
  957. pdfmetrics.TypeFace.__init__(self, None)
  958. TTFontFile.__init__(self, filename, validate=validate, subfontIndex=subfontIndex)
  959. def getCharWidth(self, code):
  960. "Returns the width of character U+<code>"
  961. return self.charWidths.get(code, self.defaultWidth)
  962. def addSubsetObjects(self, doc, fontname, subset):
  963. """Generate a TrueType font subset and add it to the PDF document.
  964. Returns a PDFReference to the new FontDescriptor object."""
  965. fontFile = pdfdoc.PDFStream()
  966. fontFile.content = self.makeSubset(subset)
  967. fontFile.dictionary['Length1'] = len(fontFile.content)
  968. if doc.compression:
  969. fontFile.filters = [pdfdoc.PDFZCompress]
  970. fontFileRef = doc.Reference(fontFile, 'fontFile:%s(%s)' % (self.filename, fontname))
  971. flags = self.flags & ~ FF_NONSYMBOLIC
  972. flags = flags | FF_SYMBOLIC
  973. fontDescriptor = pdfdoc.PDFDictionary({
  974. 'Type': '/FontDescriptor',
  975. 'Ascent': self.ascent,
  976. 'CapHeight': self.capHeight,
  977. 'Descent': self.descent,
  978. 'Flags': flags,
  979. 'FontBBox': pdfdoc.PDFArray(self.bbox),
  980. 'FontName': pdfdoc.PDFName(fontname),
  981. 'ItalicAngle': self.italicAngle,
  982. 'StemV': self.stemV,
  983. 'FontFile2': fontFileRef,
  984. })
  985. return doc.Reference(fontDescriptor, 'fontDescriptor:' + fontname)
  986. class TTEncoding:
  987. """Encoding for TrueType fonts (always UTF-8).
  988. TTEncoding does not directly participate in PDF object creation, since
  989. we need a number of different 8-bit encodings for every generated font
  990. subset. TTFont itself cares about that."""
  991. def __init__(self):
  992. self.name = "UTF-8"
  993. class TTFont:
  994. """Represents a TrueType font.
  995. Its encoding is always UTF-8.
  996. Note: you cannot use the same TTFont object for different documents
  997. at the same time.
  998. Example of usage:
  999. font = ttfonts.TTFont('PostScriptFontName', '/path/to/font.ttf')
  1000. pdfmetrics.registerFont(font)
  1001. canvas.setFont('PostScriptFontName', size)
  1002. canvas.drawString(x, y, "Some text encoded in UTF-8")
  1003. """
  1004. class State:
  1005. namePrefix = 'F'
  1006. def __init__(self,asciiReadable=None,ttf=None):
  1007. A = self.assignments = {}
  1008. self.nextCode = 0
  1009. self.internalName = None
  1010. self.frozen = 0
  1011. if getattr(getattr(ttf,'face',None),'_full_font',None):
  1012. C = set(self.charToGlyph.keys())
  1013. if 0xa0 in C: C.remove(0xa0)
  1014. for n in range(256):
  1015. if n in C:
  1016. A[n] = n
  1017. C.remove(n)
  1018. for n in C:
  1019. A[n] = n
  1020. self.subsets = [[n for n in A]]
  1021. self.frozen = True
  1022. return
  1023. if asciiReadable is None:
  1024. asciiReadable = rl_config.ttfAsciiReadable
  1025. if asciiReadable:
  1026. # Let's add the first 128 unicodes to the 0th subset, so ' '
  1027. # always has code 32 (for word spacing to work) and the ASCII
  1028. # output is readable
  1029. subset0 = list(range(128))
  1030. self.subsets = [subset0]
  1031. for n in subset0:
  1032. A[n] = n
  1033. self.nextCode = 128
  1034. else:
  1035. self.subsets = [[32]*33]
  1036. A[32] = 32
  1037. _multiByte = 1 # We want our own stringwidth
  1038. _dynamicFont = 1 # We want dynamic subsetting
  1039. def __init__(self, name, filename, validate=0, subfontIndex=0,asciiReadable=None):
  1040. """Loads a TrueType font from filename.
  1041. If validate is set to a false values, skips checksum validation. This
  1042. can save time, especially if the font is large.
  1043. """
  1044. self.fontName = name
  1045. self.face = TTFontFace(filename, validate=validate, subfontIndex=subfontIndex)
  1046. self.encoding = TTEncoding()
  1047. from weakref import WeakKeyDictionary
  1048. self.state = WeakKeyDictionary()
  1049. if asciiReadable is None:
  1050. asciiReadable = rl_config.ttfAsciiReadable
  1051. self._asciiReadable = asciiReadable
  1052. def stringWidth(self,text,size,encoding='utf8'):
  1053. return instanceStringWidthTTF(self,text,size,encoding)
  1054. def _assignState(self,doc,asciiReadable=None,namePrefix=None):
  1055. '''convenience function for those wishing to roll their own state properties'''
  1056. if asciiReadable is None:
  1057. asciiReadable = self._asciiReadable
  1058. try:
  1059. state = self.state[doc]
  1060. except KeyError:
  1061. state = self.state[doc] = TTFont.State(asciiReadable,self)
  1062. if namePrefix is not None:
  1063. state.namePrefix = namePrefix
  1064. return state
  1065. def splitString(self, text, doc, encoding='utf-8'):
  1066. """Splits text into a number of chunks, each of which belongs to a
  1067. single subset. Returns a list of tuples (subset, string). Use subset
  1068. numbers with getSubsetInternalName. Doc is needed for distinguishing
  1069. subsets when building different documents at the same time."""
  1070. asciiReadable = self._asciiReadable
  1071. try: state = self.state[doc]
  1072. except KeyError: state = self.state[doc] = TTFont.State(asciiReadable,self)
  1073. curSet = -1
  1074. cur = []
  1075. results = []
  1076. if not isUnicode(text):
  1077. text = text.decode('utf-8') # encoding defaults to utf-8
  1078. assignments = state.assignments
  1079. subsets = state.subsets
  1080. reserveTTFNotdef = rl_config.reserveTTFNotdef
  1081. for code in map(ord,text):
  1082. if code==0xa0: code = 32 #map nbsp into space
  1083. if code in assignments:
  1084. n = assignments[code]
  1085. else:
  1086. if state.frozen:
  1087. raise pdfdoc.PDFError("Font %s is already frozen, cannot add new character U+%04X" % (self.fontName, code))
  1088. n = state.nextCode
  1089. if n&0xFF==32:
  1090. # make code 32 always be a space character
  1091. if n!=32: subsets[n >> 8].append(32)
  1092. state.nextCode += 1
  1093. n = state.nextCode
  1094. if n>32:
  1095. if not(n&0xFF):
  1096. if reserveTTFNotdef:
  1097. subsets.append([0]) #force code 0 in as notdef
  1098. state.nextCode += 1
  1099. n = state.nextCode
  1100. else:
  1101. subsets.append([])
  1102. subsets[n >> 8].append(code)
  1103. else:
  1104. subsets[0][n] = code
  1105. state.nextCode += 1
  1106. assignments[code] = n
  1107. #subsets[n>>8].append(code)
  1108. if (n >> 8) != curSet:
  1109. if cur:
  1110. results.append((curSet,bytes(cur)))
  1111. curSet = (n >> 8)
  1112. cur = []
  1113. cur.append(n & 0xFF)
  1114. if cur:
  1115. results.append((curSet,bytes(cur)))
  1116. return results
  1117. def getSubsetInternalName(self, subset, doc):
  1118. """Returns the name of a PDF Font object corresponding to a given
  1119. subset of this dynamic font. Use this function instead of
  1120. PDFDocument.getInternalFontName."""
  1121. try: state = self.state[doc]
  1122. except KeyError: state = self.state[doc] = TTFont.State(self._asciiReadable)
  1123. if subset < 0 or subset >= len(state.subsets):
  1124. raise IndexError('Subset %d does not exist in font %s' % (subset, self.fontName))
  1125. if state.internalName is None:
  1126. state.internalName = state.namePrefix +repr(len(doc.fontMapping) + 1)
  1127. doc.fontMapping[self.fontName] = '/' + state.internalName
  1128. doc.delayedFonts.append(self)
  1129. return '/%s+%d' % (state.internalName, subset)
  1130. def addObjects(self, doc):
  1131. """Makes one or more PDF objects to be added to the document. The
  1132. caller supplies the internal name to be used (typically F1, F2, ... in
  1133. sequence).
  1134. This method creates a number of Font and FontDescriptor objects. Every
  1135. FontDescriptor is a (no more than) 256 character subset of the original
  1136. TrueType font."""
  1137. try: state = self.state[doc]
  1138. except KeyError: state = self.state[doc] = TTFont.State(self._asciiReadable)
  1139. state.frozen = 1
  1140. for n,subset in enumerate(state.subsets):
  1141. internalName = self.getSubsetInternalName(n, doc)[1:]
  1142. baseFontName = (b''.join((SUBSETN(n),b'+',self.face.name,self.face.subfontNameX))).decode('pdfdoc')
  1143. pdfFont = pdfdoc.PDFTrueTypeFont()
  1144. pdfFont.__Comment__ = 'Font %s subset %d' % (self.fontName, n)
  1145. pdfFont.Name = internalName
  1146. pdfFont.BaseFont = baseFontName
  1147. pdfFont.FirstChar = 0
  1148. pdfFont.LastChar = len(subset) - 1
  1149. widths = list(map(self.face.getCharWidth, subset))
  1150. pdfFont.Widths = pdfdoc.PDFArray(widths)
  1151. cmapStream = pdfdoc.PDFStream()
  1152. cmapStream.content = makeToUnicodeCMap(baseFontName, subset)
  1153. if doc.compression:
  1154. cmapStream.filters = [pdfdoc.PDFZCompress]
  1155. pdfFont.ToUnicode = doc.Reference(cmapStream, 'toUnicodeCMap:' + baseFontName)
  1156. pdfFont.FontDescriptor = self.face.addSubsetObjects(doc, baseFontName, subset)
  1157. # link it in
  1158. ref = doc.Reference(pdfFont, internalName)
  1159. fontDict = doc.idToObject['BasicFonts'].dict
  1160. fontDict[internalName] = pdfFont
  1161. del self.state[doc]
  1162. #preserve the initial values here
  1163. def _reset():
  1164. _cached_ttf_dirs.clear()
  1165. from reportlab.rl_config import register_reset
  1166. register_reset(_reset)
  1167. del register_reset