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