drawing.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. from __future__ import absolute_import
  2. from __future__ import division
  3. # Copyright (c) 2010-2019 openpyxl
  4. import math
  5. from openpyxl.compat import deprecated
  6. from openpyxl.styles.colors import Color, BLACK, WHITE
  7. from openpyxl.utils.units import (
  8. pixels_to_EMU,
  9. EMU_to_pixels,
  10. short_color,
  11. )
  12. class Drawing(object):
  13. """ a drawing object - eg container for shapes or charts
  14. we assume user specifies dimensions in pixels; units are
  15. converted to EMU in the drawing part
  16. """
  17. count = 0
  18. def __init__(self):
  19. self.name = ''
  20. self.description = ''
  21. self.coordinates = ((1, 2), (16, 8))
  22. self.left = 0
  23. self.top = 0
  24. self._width = 21 # default in px
  25. self._height = 192 #default in px
  26. self.resize_proportional = False
  27. self.rotation = 0
  28. self.anchortype = "absolute"
  29. self.anchorcol = 0 # left cell
  30. self.anchorrow = 0 # top row
  31. @property
  32. def width(self):
  33. return self._width
  34. @width.setter
  35. def width(self, w):
  36. if self.resize_proportional and w:
  37. ratio = self._height / self._width
  38. self._height = round(ratio * w)
  39. self._width = w
  40. @property
  41. def height(self):
  42. return self._height
  43. @height.setter
  44. def height(self, h):
  45. if self.resize_proportional and h:
  46. ratio = self._width / self._height
  47. self._width = round(ratio * h)
  48. self._height = h
  49. def set_dimension(self, w=0, h=0):
  50. xratio = w / self._width
  51. yratio = h / self._height
  52. if self.resize_proportional and w and h:
  53. if (xratio * self._height) < h:
  54. self._height = math.ceil(xratio * self._height)
  55. self._width = w
  56. else:
  57. self._width = math.ceil(yratio * self._width)
  58. self._height = h
  59. @deprecated("Private method used when serialising")
  60. def get_emu_dimensions(self):
  61. """ return (x, y, w, h) in EMU """
  62. return (pixels_to_EMU(self.left), pixels_to_EMU(self.top),
  63. pixels_to_EMU(self._width), pixels_to_EMU(self._height))
  64. @property
  65. def anchor(self):
  66. from .spreadsheet_drawing import (
  67. OneCellAnchor,
  68. TwoCellAnchor,
  69. AbsoluteAnchor)
  70. if self.anchortype == "absolute":
  71. anchor = AbsoluteAnchor()
  72. anchor.pos.x = pixels_to_EMU(self.left)
  73. anchor.pos.y = pixels_to_EMU(self.top)
  74. elif self.anchortype == "oneCell":
  75. anchor = OneCellAnchor()
  76. anchor._from.col = self.anchorcol
  77. anchor._from.row = self.anchorrow
  78. anchor.ext.width = pixels_to_EMU(self._width)
  79. anchor.ext.height = pixels_to_EMU(self._height)
  80. return anchor