PSDraw.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. #
  2. # The Python Imaging Library
  3. # $Id$
  4. #
  5. # Simple PostScript graphics interface
  6. #
  7. # History:
  8. # 1996-04-20 fl Created
  9. # 1999-01-10 fl Added gsave/grestore to image method
  10. # 2005-05-04 fl Fixed floating point issue in image (from Eric Etheridge)
  11. #
  12. # Copyright (c) 1997-2005 by Secret Labs AB. All rights reserved.
  13. # Copyright (c) 1996 by Fredrik Lundh.
  14. #
  15. # See the README file for information on usage and redistribution.
  16. #
  17. from __future__ import annotations
  18. import sys
  19. from . import EpsImagePlugin
  20. TYPE_CHECKING = False
  21. if TYPE_CHECKING:
  22. from typing import IO
  23. ##
  24. # Simple PostScript graphics interface.
  25. class PSDraw:
  26. """
  27. Sets up printing to the given file. If ``fp`` is omitted,
  28. ``sys.stdout.buffer`` is assumed.
  29. """
  30. def __init__(self, fp: IO[bytes] | None = None) -> None:
  31. if not fp:
  32. fp = sys.stdout.buffer
  33. self.fp = fp
  34. def begin_document(self, id: str | None = None) -> None:
  35. """Set up printing of a document. (Write PostScript DSC header.)"""
  36. # FIXME: incomplete
  37. self.fp.write(
  38. b"%!PS-Adobe-3.0\n"
  39. b"save\n"
  40. b"/showpage { } def\n"
  41. b"%%EndComments\n"
  42. b"%%BeginDocument\n"
  43. )
  44. # self.fp.write(ERROR_PS) # debugging!
  45. self.fp.write(EDROFF_PS)
  46. self.fp.write(VDI_PS)
  47. self.fp.write(b"%%EndProlog\n")
  48. self.isofont: dict[bytes, int] = {}
  49. def end_document(self) -> None:
  50. """Ends printing. (Write PostScript DSC footer.)"""
  51. self.fp.write(b"%%EndDocument\nrestore showpage\n%%End\n")
  52. if hasattr(self.fp, "flush"):
  53. self.fp.flush()
  54. def setfont(self, font: str, size: int) -> None:
  55. """
  56. Selects which font to use.
  57. :param font: A PostScript font name
  58. :param size: Size in points.
  59. """
  60. font_bytes = bytes(font, "UTF-8")
  61. if font_bytes not in self.isofont:
  62. # reencode font
  63. self.fp.write(
  64. b"/PSDraw-%s ISOLatin1Encoding /%s E\n" % (font_bytes, font_bytes)
  65. )
  66. self.isofont[font_bytes] = 1
  67. # rough
  68. self.fp.write(b"/F0 %d /PSDraw-%s F\n" % (size, font_bytes))
  69. def line(self, xy0: tuple[int, int], xy1: tuple[int, int]) -> None:
  70. """
  71. Draws a line between the two points. Coordinates are given in
  72. PostScript point coordinates (72 points per inch, (0, 0) is the lower
  73. left corner of the page).
  74. """
  75. self.fp.write(b"%d %d %d %d Vl\n" % (*xy0, *xy1))
  76. def rectangle(self, box: tuple[int, int, int, int]) -> None:
  77. """
  78. Draws a rectangle.
  79. :param box: A tuple of four integers, specifying left, bottom, width and
  80. height.
  81. """
  82. self.fp.write(b"%d %d M 0 %d %d Vr\n" % box)
  83. def text(self, xy: tuple[int, int], text: str, *, escape: bool = False) -> None:
  84. """
  85. Draws text at the given position. You must use
  86. :py:meth:`~PIL.PSDraw.PSDraw.setfont` before calling this method.
  87. :param xy: The position, in PostScript point coordinates.
  88. :param text: The text to draw, encoded as Latin-1.
  89. :param escape: Whether to escape backslashes in the text. This keyword-only
  90. boolean defaults to ``False``, leaving backslashes unchanged for backwards
  91. compatibility. Parentheses are always escaped.
  92. .. versionadded:: 13.0.0
  93. """
  94. # The font is loaded as ISOLatin1Encoding, so use latin-1 here.
  95. text_bytes = bytes(text, "latin-1")
  96. if escape:
  97. text_bytes = text_bytes.replace(b"\\", b"\\\\")
  98. for char in (b"(", b")"):
  99. text_bytes = text_bytes.replace(char, b"\\" + char)
  100. self.fp.write(b"%d %d M (%s) S\n" % (xy + (text_bytes,)))
  101. if TYPE_CHECKING:
  102. from . import Image
  103. def image(
  104. self, box: tuple[int, int, int, int], im: Image.Image, dpi: int | None = None
  105. ) -> None:
  106. """Draw a PIL image, centered in the given box."""
  107. # default resolution depends on mode
  108. if not dpi:
  109. if im.mode == "1":
  110. dpi = 200 # fax
  111. else:
  112. dpi = 100 # grayscale
  113. # image size (on paper)
  114. x = im.size[0] * 72 / dpi
  115. y = im.size[1] * 72 / dpi
  116. # max allowed size
  117. xmax = float(box[2] - box[0])
  118. ymax = float(box[3] - box[1])
  119. if x > xmax:
  120. y = y * xmax / x
  121. x = xmax
  122. if y > ymax:
  123. x = x * ymax / y
  124. y = ymax
  125. dx = (xmax - x) / 2 + box[0]
  126. dy = (ymax - y) / 2 + box[1]
  127. self.fp.write(b"gsave\n%f %f translate\n" % (dx, dy))
  128. if (x, y) != im.size:
  129. # EpsImagePlugin._save prints the image at (0,0,xsize,ysize)
  130. sx = x / im.size[0]
  131. sy = y / im.size[1]
  132. self.fp.write(b"%f %f scale\n" % (sx, sy))
  133. EpsImagePlugin._save(im, self.fp, "", 0)
  134. self.fp.write(b"\ngrestore\n")
  135. # --------------------------------------------------------------------
  136. # PostScript driver
  137. #
  138. # EDROFF.PS -- PostScript driver for Edroff 2
  139. #
  140. # History:
  141. # 94-01-25 fl: created (edroff 2.04)
  142. #
  143. # Copyright (c) Fredrik Lundh 1994.
  144. #
  145. EDROFF_PS = b"""\
  146. /S { show } bind def
  147. /P { moveto show } bind def
  148. /M { moveto } bind def
  149. /X { 0 rmoveto } bind def
  150. /Y { 0 exch rmoveto } bind def
  151. /E { findfont
  152. dup maxlength dict begin
  153. {
  154. 1 index /FID ne { def } { pop pop } ifelse
  155. } forall
  156. /Encoding exch def
  157. dup /FontName exch def
  158. currentdict end definefont pop
  159. } bind def
  160. /F { findfont exch scalefont dup setfont
  161. [ exch /setfont cvx ] cvx bind def
  162. } bind def
  163. """
  164. #
  165. # VDI.PS -- PostScript driver for VDI meta commands
  166. #
  167. # History:
  168. # 94-01-25 fl: created (edroff 2.04)
  169. #
  170. # Copyright (c) Fredrik Lundh 1994.
  171. #
  172. VDI_PS = b"""\
  173. /Vm { moveto } bind def
  174. /Va { newpath arcn stroke } bind def
  175. /Vl { moveto lineto stroke } bind def
  176. /Vc { newpath 0 360 arc closepath } bind def
  177. /Vr { exch dup 0 rlineto
  178. exch dup 0 exch rlineto
  179. exch neg 0 rlineto
  180. 0 exch neg rlineto
  181. setgray fill } bind def
  182. /Tm matrix def
  183. /Ve { Tm currentmatrix pop
  184. translate scale newpath 0 0 .5 0 360 arc closepath
  185. Tm setmatrix
  186. } bind def
  187. /Vf { currentgray exch setgray fill setgray } bind def
  188. """
  189. #
  190. # ERROR.PS -- Error handler
  191. #
  192. # History:
  193. # 89-11-21 fl: created (pslist 1.10)
  194. #
  195. ERROR_PS = b"""\
  196. /landscape false def
  197. /errorBUF 200 string def
  198. /errorNL { currentpoint 10 sub exch pop 72 exch moveto } def
  199. errordict begin /handleerror {
  200. initmatrix /Courier findfont 10 scalefont setfont
  201. newpath 72 720 moveto $error begin /newerror false def
  202. (PostScript Error) show errorNL errorNL
  203. (Error: ) show
  204. /errorname load errorBUF cvs show errorNL errorNL
  205. (Command: ) show
  206. /command load dup type /stringtype ne { errorBUF cvs } if show
  207. errorNL errorNL
  208. (VMstatus: ) show
  209. vmstatus errorBUF cvs show ( bytes available, ) show
  210. errorBUF cvs show ( bytes used at level ) show
  211. errorBUF cvs show errorNL errorNL
  212. (Operand stargck: ) show errorNL /ostargck load {
  213. dup type /stringtype ne { errorBUF cvs } if 72 0 rmoveto show errorNL
  214. } forall errorNL
  215. (Execution stargck: ) show errorNL /estargck load {
  216. dup type /stringtype ne { errorBUF cvs } if 72 0 rmoveto show errorNL
  217. } forall
  218. end showpage
  219. } def end
  220. """