drawing.py 2.3 KB

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