cidfonts.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. #Copyright ReportLab Europe Ltd. 2000-2017
  2. #see license.txt for license details
  3. #history https://hg.reportlab.com/hg-public/reportlab/log/tip/src/reportlab/pdfbase/cidfonts.py
  4. #$Header $
  5. __version__='3.3.0'
  6. __doc__="""CID (Asian multi-byte) font support.
  7. This defines classes to represent CID fonts. They know how to calculate
  8. their own width and how to write themselves into PDF files."""
  9. import os
  10. import marshal
  11. import time
  12. try:
  13. from hashlib import md5
  14. except ImportError:
  15. from md5 import md5
  16. import reportlab
  17. from reportlab.pdfbase import pdfmetrics
  18. from reportlab.pdfbase._cidfontdata import allowedTypeFaces, allowedEncodings, CIDFontInfo, \
  19. defaultUnicodeEncodings, widthsByUnichar
  20. from reportlab.pdfgen.canvas import Canvas
  21. from reportlab.pdfbase import pdfdoc
  22. from reportlab.lib.rl_accel import escapePDF
  23. from reportlab.rl_config import CMapSearchPath
  24. from reportlab.lib.utils import isSeq, isBytes
  25. #quick hackery for 2.0 release. Now we always do unicode, and have built in
  26. #the CMAP data, any code to load CMap files is not needed.
  27. DISABLE_CMAP = True
  28. def findCMapFile(name):
  29. "Returns full filename, or raises error"
  30. for dirname in CMapSearchPath:
  31. cmapfile = dirname + os.sep + name
  32. if os.path.isfile(cmapfile):
  33. #print "found", cmapfile
  34. return cmapfile
  35. raise IOError('CMAP file for encodings "%s" not found!' % name)
  36. def structToPDF(structure):
  37. "Converts deeply nested structure to PDFdoc dictionary/array objects"
  38. if isinstance(structure,dict):
  39. newDict = {}
  40. for k, v in structure.items():
  41. newDict[k] = structToPDF(v)
  42. return pdfdoc.PDFDictionary(newDict)
  43. elif isSeq(structure):
  44. newList = []
  45. for elem in structure:
  46. newList.append(structToPDF(elem))
  47. return pdfdoc.PDFArray(newList)
  48. else:
  49. return structure
  50. class CIDEncoding(pdfmetrics.Encoding):
  51. """Multi-byte encoding. These are loaded from CMAP files.
  52. A CMAP file is like a mini-codec. It defines the correspondence
  53. between code points in the (multi-byte) input data and Character
  54. IDs. """
  55. # aims to do similar things to Brian Hooper's CMap class,
  56. # but I could not get it working and had to rewrite.
  57. # also, we should really rearrange our current encoding
  58. # into a SingleByteEncoding since many of its methods
  59. # should not apply here.
  60. def __init__(self, name, useCache=1):
  61. self.name = name
  62. self._mapFileHash = None
  63. self._codeSpaceRanges = []
  64. self._notDefRanges = []
  65. self._cmap = {}
  66. self.source = None
  67. if not DISABLE_CMAP:
  68. if useCache:
  69. from reportlab.lib.utils import get_rl_tempdir
  70. fontmapdir = get_rl_tempdir('FastCMAPS')
  71. if os.path.isfile(fontmapdir + os.sep + name + '.fastmap'):
  72. self.fastLoad(fontmapdir)
  73. self.source = fontmapdir + os.sep + name + '.fastmap'
  74. else:
  75. self.parseCMAPFile(name)
  76. self.source = 'CMAP: ' + name
  77. self.fastSave(fontmapdir)
  78. else:
  79. self.parseCMAPFile(name)
  80. def _hash(self, text):
  81. hasher = md5()
  82. hasher.update(text)
  83. return hasher.digest()
  84. def parseCMAPFile(self, name):
  85. """This is a tricky one as CMAP files are Postscript
  86. ones. Some refer to others with a 'usecmap'
  87. command"""
  88. #started = time.clock()
  89. cmapfile = findCMapFile(name)
  90. # this will CRAWL with the unicode encodings...
  91. rawdata = open(cmapfile, 'r').read()
  92. self._mapFileHash = self._hash(rawdata)
  93. #if it contains the token 'usecmap', parse the other
  94. #cmap file first....
  95. usecmap_pos = rawdata.find('usecmap')
  96. if usecmap_pos > -1:
  97. #they tell us to look in another file
  98. #for the code space ranges. The one
  99. # to use will be the previous word.
  100. chunk = rawdata[0:usecmap_pos]
  101. words = chunk.split()
  102. otherCMAPName = words[-1]
  103. #print 'referred to another CMAP %s' % otherCMAPName
  104. self.parseCMAPFile(otherCMAPName)
  105. # now continue parsing this, as it may
  106. # override some settings
  107. words = rawdata.split()
  108. while words != []:
  109. if words[0] == 'begincodespacerange':
  110. words = words[1:]
  111. while words[0] != 'endcodespacerange':
  112. strStart, strEnd, words = words[0], words[1], words[2:]
  113. start = int(strStart[1:-1], 16)
  114. end = int(strEnd[1:-1], 16)
  115. self._codeSpaceRanges.append((start, end),)
  116. elif words[0] == 'beginnotdefrange':
  117. words = words[1:]
  118. while words[0] != 'endnotdefrange':
  119. strStart, strEnd, strValue = words[0:3]
  120. start = int(strStart[1:-1], 16)
  121. end = int(strEnd[1:-1], 16)
  122. value = int(strValue)
  123. self._notDefRanges.append((start, end, value),)
  124. words = words[3:]
  125. elif words[0] == 'begincidrange':
  126. words = words[1:]
  127. while words[0] != 'endcidrange':
  128. strStart, strEnd, strValue = words[0:3]
  129. start = int(strStart[1:-1], 16)
  130. end = int(strEnd[1:-1], 16)
  131. value = int(strValue)
  132. # this means that 'start' corresponds to 'value',
  133. # start+1 corresponds to value+1 and so on up
  134. # to end
  135. offset = 0
  136. while start + offset <= end:
  137. self._cmap[start + offset] = value + offset
  138. offset = offset + 1
  139. words = words[3:]
  140. else:
  141. words = words[1:]
  142. #finished = time.clock()
  143. #print 'parsed CMAP %s in %0.4f seconds' % (self.name, finished - started)
  144. def translate(self, text):
  145. "Convert a string into a list of CIDs"
  146. output = []
  147. cmap = self._cmap
  148. lastChar = ''
  149. for char in text:
  150. if lastChar != '':
  151. #print 'convert character pair "%s"' % (lastChar + char)
  152. num = ord(lastChar) * 256 + ord(char)
  153. else:
  154. #print 'convert character "%s"' % char
  155. num = ord(char)
  156. lastChar = char
  157. found = 0
  158. for low, high in self._codeSpaceRanges:
  159. if low < num < high:
  160. try:
  161. cid = cmap[num]
  162. #print '%d -> %d' % (num, cid)
  163. except KeyError:
  164. #not defined. Try to find the appropriate
  165. # notdef character, or failing that return
  166. # zero
  167. cid = 0
  168. for low2, high2, notdef in self._notDefRanges:
  169. if low2 < num < high2:
  170. cid = notdef
  171. break
  172. output.append(cid)
  173. found = 1
  174. break
  175. if found:
  176. lastChar = ''
  177. else:
  178. lastChar = char
  179. return output
  180. def fastSave(self, directory):
  181. f = open(os.path.join(directory, self.name + '.fastmap'), 'wb')
  182. marshal.dump(self._mapFileHash, f)
  183. marshal.dump(self._codeSpaceRanges, f)
  184. marshal.dump(self._notDefRanges, f)
  185. marshal.dump(self._cmap, f)
  186. f.close()
  187. def fastLoad(self, directory):
  188. started = time.clock()
  189. f = open(os.path.join(directory, self.name + '.fastmap'), 'rb')
  190. self._mapFileHash = marshal.load(f)
  191. self._codeSpaceRanges = marshal.load(f)
  192. self._notDefRanges = marshal.load(f)
  193. self._cmap = marshal.load(f)
  194. f.close()
  195. finished = time.clock()
  196. #print 'loaded %s in %0.4f seconds' % (self.name, finished - started)
  197. def getData(self):
  198. """Simple persistence helper. Return a dict with all that matters."""
  199. return {
  200. 'mapFileHash': self._mapFileHash,
  201. 'codeSpaceRanges': self._codeSpaceRanges,
  202. 'notDefRanges': self._notDefRanges,
  203. 'cmap': self._cmap,
  204. }
  205. class CIDTypeFace(pdfmetrics.TypeFace):
  206. """Multi-byte type face.
  207. Conceptually similar to a single byte typeface,
  208. but the glyphs are identified by a numeric Character
  209. ID (CID) and not a glyph name. """
  210. def __init__(self, name):
  211. """Initialised from one of the canned dictionaries in allowedEncodings
  212. Or rather, it will be shortly..."""
  213. pdfmetrics.TypeFace.__init__(self, name)
  214. self._extractDictInfo(name)
  215. def _extractDictInfo(self, name):
  216. try:
  217. fontDict = CIDFontInfo[name]
  218. except KeyError:
  219. raise KeyError("Unable to find information on CID typeface '%s'" % name +
  220. "Only the following font names work:" + repr(allowedTypeFaces))
  221. descFont = fontDict['DescendantFonts'][0]
  222. self.ascent = descFont['FontDescriptor']['Ascent']
  223. self.descent = descFont['FontDescriptor']['Descent']
  224. self._defaultWidth = descFont['DW']
  225. self._explicitWidths = self._expandWidths(descFont['W'])
  226. # should really support self.glyphWidths, self.glyphNames
  227. # but not done yet.
  228. def _expandWidths(self, compactWidthArray):
  229. """Expands Adobe nested list structure to get a dictionary of widths.
  230. Here is an example of such a structure.::
  231. (
  232. # starting at character ID 1, next n characters have the widths given.
  233. 1, (277,305,500,668,668,906,727,305,445,445,508,668,305,379,305,539),
  234. # all Characters from ID 17 to 26 are 668 em units wide
  235. 17, 26, 668,
  236. 27, (305, 305, 668, 668, 668, 566, 871, 727, 637, 652, 699, 574, 555,
  237. 676, 687, 242, 492, 664, 582, 789, 707, 734, 582, 734, 605, 605,
  238. 641, 668, 727, 945, 609, 609, 574, 445, 668, 445, 668, 668, 590,
  239. 555, 609, 547, 602, 574, 391, 609, 582, 234, 277, 539, 234, 895,
  240. 582, 605, 602, 602, 387, 508, 441, 582, 562, 781, 531, 570, 555,
  241. 449, 246, 449, 668),
  242. # these must be half width katakana and the like.
  243. 231, 632, 500
  244. )
  245. """
  246. data = compactWidthArray[:]
  247. widths = {}
  248. while data:
  249. start, data = data[0], data[1:]
  250. if isSeq(data[0]):
  251. items, data = data[0], data[1:]
  252. for offset in range(len(items)):
  253. widths[start + offset] = items[offset]
  254. else:
  255. end, width, data = data[0], data[1], data[2:]
  256. for idx in range(start, end+1):
  257. widths[idx] = width
  258. return widths
  259. def getCharWidth(self, characterId):
  260. return self._explicitWidths.get(characterId, self._defaultWidth)
  261. class CIDFont(pdfmetrics.Font):
  262. "Represents a built-in multi-byte font"
  263. _multiByte = 1
  264. def __init__(self, face, encoding):
  265. assert face in allowedTypeFaces, "TypeFace '%s' not supported! Use any of these instead: %s" % (face, allowedTypeFaces)
  266. self.faceName = face
  267. #should cache in registry...
  268. self.face = CIDTypeFace(face)
  269. assert encoding in allowedEncodings, "Encoding '%s' not supported! Use any of these instead: %s" % (encoding, allowedEncodings)
  270. self.encodingName = encoding
  271. self.encoding = CIDEncoding(encoding)
  272. #legacy hack doing quick cut and paste.
  273. self.fontName = self.faceName + '-' + self.encodingName
  274. self.name = self.fontName
  275. # need to know if it is vertical or horizontal
  276. self.isVertical = (self.encodingName[-1] == 'V')
  277. #no substitutes initially
  278. self.substitutionFonts = []
  279. def formatForPdf(self, text):
  280. encoded = escapePDF(text)
  281. #print 'encoded CIDFont:', encoded
  282. return encoded
  283. def stringWidth(self, text, size, encoding=None):
  284. """This presumes non-Unicode input. UnicodeCIDFont wraps it for that context"""
  285. cidlist = self.encoding.translate(text)
  286. if self.isVertical:
  287. #this part is "not checked!" but seems to work.
  288. #assume each is 1000 ems high
  289. return len(cidlist) * size
  290. else:
  291. w = 0
  292. for cid in cidlist:
  293. w = w + self.face.getCharWidth(cid)
  294. return 0.001 * w * size
  295. def addObjects(self, doc):
  296. """The explicit code in addMinchoObjects and addGothicObjects
  297. will be replaced by something that pulls the data from
  298. _cidfontdata.py in the next few days."""
  299. internalName = 'F' + repr(len(doc.fontMapping)+1)
  300. bigDict = CIDFontInfo[self.face.name]
  301. bigDict['Name'] = '/' + internalName
  302. bigDict['Encoding'] = '/' + self.encodingName
  303. #convert to PDF dictionary/array objects
  304. cidObj = structToPDF(bigDict)
  305. # link into document, and add to font map
  306. r = doc.Reference(cidObj, internalName)
  307. fontDict = doc.idToObject['BasicFonts'].dict
  308. fontDict[internalName] = r
  309. doc.fontMapping[self.name] = '/' + internalName
  310. class UnicodeCIDFont(CIDFont):
  311. """Wraps up CIDFont to hide explicit encoding choice;
  312. encodes text for output as UTF16.
  313. lang should be one of 'jpn',chs','cht','kor' for now.
  314. if vertical is set, it will select a different widths array
  315. and possibly glyphs for some punctuation marks.
  316. halfWidth is only for Japanese.
  317. >>> dodgy = UnicodeCIDFont('nonexistent')
  318. Traceback (most recent call last):
  319. ...
  320. KeyError: "don't know anything about CID font nonexistent"
  321. >>> heisei = UnicodeCIDFont('HeiseiMin-W3')
  322. >>> heisei.name
  323. 'HeiseiMin-W3'
  324. >>> heisei.language
  325. 'jpn'
  326. >>> heisei.encoding.name
  327. 'UniJIS-UCS2-H'
  328. >>> #This is how PDF data gets encoded.
  329. >>> print(heisei.formatForPdf('hello'))
  330. \\000h\\000e\\000l\\000l\\000o
  331. >>> tokyo = u'\u6771\u4AEC'
  332. >>> print(heisei.formatForPdf(tokyo))
  333. gqJ\\354
  334. >>> print(heisei.stringWidth(tokyo,10))
  335. 20.0
  336. >>> print(heisei.stringWidth('hello world',10))
  337. 45.83
  338. """
  339. def __init__(self, face, isVertical=False, isHalfWidth=False):
  340. #pass
  341. try:
  342. lang, defaultEncoding = defaultUnicodeEncodings[face]
  343. except KeyError:
  344. raise KeyError("don't know anything about CID font %s" % face)
  345. #we know the languages now.
  346. self.language = lang
  347. #rebuilt encoding string. They follow rules which work
  348. #for the 7 fonts provided.
  349. enc = defaultEncoding[:-1]
  350. if isHalfWidth:
  351. enc = enc + 'HW-'
  352. if isVertical:
  353. enc = enc + 'V'
  354. else:
  355. enc = enc + 'H'
  356. #now we can do the more general case
  357. CIDFont.__init__(self, face, enc)
  358. #self.encName = 'utf_16_le'
  359. #it's simpler for unicode, just use the face name
  360. self.name = self.fontName = face
  361. self.vertical = isVertical
  362. self.isHalfWidth = isHalfWidth
  363. self.unicodeWidths = widthsByUnichar[self.name]
  364. def formatForPdf(self, text):
  365. #these ones should be encoded asUTF16 minus the BOM
  366. from codecs import utf_16_be_encode
  367. #print 'formatting %s: %s' % (type(text), repr(text))
  368. if isBytes(text):
  369. text = text.decode('utf8')
  370. utfText = utf_16_be_encode(text)[0]
  371. encoded = escapePDF(utfText)
  372. #print ' encoded:',encoded
  373. return encoded
  374. #
  375. #result = escapePDF(encoded)
  376. #print ' -> %s' % repr(result)
  377. #return result
  378. def stringWidth(self, text, size, encoding=None):
  379. "Just ensure we do width test on characters, not bytes..."
  380. if isBytes(text):
  381. text = text.decode('utf8')
  382. widths = self.unicodeWidths
  383. return size * 0.001 * sum([widths.get(uch, 1000) for uch in text])
  384. #return CIDFont.stringWidth(self, text, size, encoding)
  385. def precalculate(cmapdir):
  386. # crunches through all, making 'fastmap' files
  387. import os
  388. files = os.listdir(cmapdir)
  389. for file in files:
  390. if os.path.isfile(cmapdir + os.sep + file + '.fastmap'):
  391. continue
  392. try:
  393. enc = CIDEncoding(file)
  394. except:
  395. print('cannot parse %s, skipping' % enc)
  396. continue
  397. enc.fastSave(cmapdir)
  398. print('saved %s.fastmap' % file)
  399. def test():
  400. # only works if you have cirrect encodings on your box!
  401. c = Canvas('test_japanese.pdf')
  402. c.setFont('Helvetica', 30)
  403. c.drawString(100,700, 'Japanese Font Support')
  404. pdfmetrics.registerFont(CIDFont('HeiseiMin-W3','90ms-RKSJ-H'))
  405. pdfmetrics.registerFont(CIDFont('HeiseiKakuGo-W5','90ms-RKSJ-H'))
  406. # the two typefaces
  407. c.setFont('HeiseiMin-W3-90ms-RKSJ-H', 16)
  408. # this says "This is HeiseiMincho" in shift-JIS. Not all our readers
  409. # have a Japanese PC, so I escaped it. On a Japanese-capable
  410. # system, print the string to see Kanji
  411. message1 = '\202\261\202\352\202\315\225\275\220\254\226\276\222\251\202\305\202\267\201B'
  412. c.drawString(100, 675, message1)
  413. c.save()
  414. print('saved test_japanese.pdf')
  415. ## print 'CMAP_DIR = ', CMAP_DIR
  416. ## tf1 = CIDTypeFace('HeiseiMin-W3')
  417. ## print 'ascent = ',tf1.ascent
  418. ## print 'descent = ',tf1.descent
  419. ## for cid in [1,2,3,4,5,18,19,28,231,1742]:
  420. ## print 'width of cid %d = %d' % (cid, tf1.getCharWidth(cid))
  421. encName = '90ms-RKSJ-H'
  422. enc = CIDEncoding(encName)
  423. print(message1, '->', enc.translate(message1))
  424. f = CIDFont('HeiseiMin-W3','90ms-RKSJ-H')
  425. print('width = %0.2f' % f.stringWidth(message1, 10))
  426. #testing all encodings
  427. ## import time
  428. ## started = time.time()
  429. ## import glob
  430. ## for encName in _cidfontdata.allowedEncodings:
  431. ## #encName = '90ms-RKSJ-H'
  432. ## enc = CIDEncoding(encName)
  433. ## print 'encoding %s:' % encName
  434. ## print ' codeSpaceRanges = %s' % enc._codeSpaceRanges
  435. ## print ' notDefRanges = %s' % enc._notDefRanges
  436. ## print ' mapping size = %d' % len(enc._cmap)
  437. ## finished = time.time()
  438. ## print 'constructed all encodings in %0.2f seconds' % (finished - started)
  439. if __name__=='__main__':
  440. import doctest
  441. from reportlab.pdfbase import cidfonts
  442. doctest.testmod(cidfonts)
  443. #test()