1from fontTools.pens.basePen import BasePen 2from reportlab.graphics.shapes import Path 3 4 5__all__ = ["ReportLabPen"] 6 7 8class ReportLabPen(BasePen): 9 """A pen for drawing onto a ``reportlab.graphics.shapes.Path`` object.""" 10 11 def __init__(self, glyphSet, path=None): 12 BasePen.__init__(self, glyphSet) 13 if path is None: 14 path = Path() 15 self.path = path 16 17 def _moveTo(self, p): 18 (x, y) = p 19 self.path.moveTo(x, y) 20 21 def _lineTo(self, p): 22 (x, y) = p 23 self.path.lineTo(x, y) 24 25 def _curveToOne(self, p1, p2, p3): 26 (x1, y1) = p1 27 (x2, y2) = p2 28 (x3, y3) = p3 29 self.path.curveTo(x1, y1, x2, y2, x3, y3) 30 31 def _closePath(self): 32 self.path.closePath() 33 34 35if __name__ == "__main__": 36 import sys 37 38 if len(sys.argv) < 3: 39 print( 40 "Usage: reportLabPen.py <OTF/TTF font> <glyphname> [<image file to create>]" 41 ) 42 print( 43 " If no image file name is created, by default <glyphname>.png is created." 44 ) 45 print(" example: reportLabPen.py Arial.TTF R test.png") 46 print( 47 " (The file format will be PNG, regardless of the image file name supplied)" 48 ) 49 sys.exit(0) 50 51 from fontTools.ttLib import TTFont 52 from reportlab.lib import colors 53 54 path = sys.argv[1] 55 glyphName = sys.argv[2] 56 if len(sys.argv) > 3: 57 imageFile = sys.argv[3] 58 else: 59 imageFile = "%s.png" % glyphName 60 61 font = TTFont(path) # it would work just as well with fontTools.t1Lib.T1Font 62 gs = font.getGlyphSet() 63 pen = ReportLabPen(gs, Path(fillColor=colors.red, strokeWidth=5)) 64 g = gs[glyphName] 65 g.draw(pen) 66 67 w, h = g.width, 1000 68 from reportlab.graphics import renderPM 69 from reportlab.graphics.shapes import Group, Drawing, scale 70 71 # Everything is wrapped in a group to allow transformations. 72 g = Group(pen.path) 73 g.translate(0, 200) 74 g.scale(0.3, 0.3) 75 76 d = Drawing(w, h) 77 d.add(g) 78 79 renderPM.drawToFile(d, imageFile, fmt="PNG") 80