reportLabPen.py 2.0 KB

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