Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for rgb as color from json #103

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions sane_doc_reports/styles/colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,38 @@ def name_to_hex(color_name: str):
""" Get the hex representation of a color name (CSS4) """
return colors[color_name].lower()

def combine_rgba_with_white_background(rgba_color_string):
""" Turns rgba color string to a RGB object"""
# Extract the RGBA values
rgba_values = rgba_color_string.strip("rgba()").split(',')
r_source, g_source, b_source = map(int, rgba_values[:3])
alpha = float(rgba_values[-1])

# Calculate the combined RGB values assuming a white background (255, 255, 255)
r_combined = int(((1 - alpha) * 255) + (alpha * r_source))
g_combined = int(((1 - alpha) * 255) + (alpha * g_source))
b_combined = int(((1 - alpha) * 255) + (alpha * b_source))

return RGBColor(r_combined, g_combined, b_combined)
def parse_color_string(color_string):
"""
Parses rgb/rgba color string to a RGB object
"""
color_string = color_string.strip() # Remove leading/trailing whitespace
if color_string.startswith("rgb("):
rgb_values = color_string[len("rgb("):-1].split(',')
if len(rgb_values) != 3:
raise ValueError("Invalid RGB color format")
r, g, b = map(int, rgb_values)
return RGBColor(r, g, b)
elif color_string.startswith("rgba("):
rgba_values = color_string[len("rgba("):-1].split(',')
if len(rgba_values) != 4:
raise ValueError("Invalid RGBA color format")
else:
return combine_rgba_with_white_background(color_string)
else:
raise ValueError("Unsupported color format")

def hex_to_rgb(hex_color: str):
"""
Expand Down
7 changes: 5 additions & 2 deletions sane_doc_reports/styles/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from sane_doc_reports.domain import CellObject
from sane_doc_reports.domain.Section import Section
from sane_doc_reports.styles.colors import name_to_rgb, hex_to_rgb, name_to_hex
from sane_doc_reports.styles.colors import name_to_rgb, hex_to_rgb, name_to_hex, parse_color_string
from sane_doc_reports.conf import PYDOCX_FONT_SIZE, PYDOCX_FONT, \
PYDOCX_FONT_BOLD, PYDOCX_FONT_STRIKE, PYDOCX_FONT_UNDERLINE, \
PYDOCX_FONT_ITALIC, PYDOCX_FONT_COLOR, PYDOCX_TEXT_ALIGN, \
Expand Down Expand Up @@ -40,7 +40,10 @@ def _apply_cell_styling(cell_object: CellObject, section: Section):

# Font color
if PYDOCX_FONT_COLOR in style:
if style[PYDOCX_FONT_COLOR][0] != '#':
if style[PYDOCX_FONT_COLOR][:3] == 'rgb':
cell_object.run.font.color.rgb = parse_color_string(
style[PYDOCX_FONT_COLOR])
elif style[PYDOCX_FONT_COLOR][0] != '#':
cell_object.run.font.color.rgb = name_to_rgb(
style[PYDOCX_FONT_COLOR])
else:
Expand Down
42 changes: 42 additions & 0 deletions tests/library/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import arrow
import pytest
from arrow.parser import ParserError
from docx.shared import RGBColor

from sane_doc_reports.styles.colors import parse_color_string
from sane_doc_reports.utils import get_formatted_date, has_anomalies


Expand Down Expand Up @@ -61,3 +63,43 @@ def test_has_anomalies():
assert has_anomalies(yes_anoms) is True
yes_anoms = [1, 200, 100, 200, 1]
assert has_anomalies(yes_anoms) is True

def test_parse_rgb():
"""
Given: rgb string to parse to RGB object
When: styling a cell.
Then: assert the correct object is returned.
"""
# Test parsing an RGB color string
rgb_color_string = "rgb(55,56,57)"
parsed_color = parse_color_string(rgb_color_string)

# Expected RGBColor object
expected_color = RGBColor(55, 56, 57)

assert parsed_color == expected_color

def test_parse_rgba():
"""
Given: rgba string to parse to RGB object
When: styling a cell.
Then: assert the correct object is returned.
"""
rgba_color_string = "rgba(55,56,57,0.5)"
parsed_color = parse_color_string(rgba_color_string)

# Expected combined RGBColor object (based on combine_rgba_with_white_background)
expected_color = RGBColor(155, 155, 156)

assert parsed_color == expected_color

def test_invalid_format():
"""
Given: rgb string to parse to RGB object
When: styling a cell.
Then: assert the correct object is returned.
"""
invalid_color_string = "invalid_color_format"

with pytest.raises(ValueError):
parse_color_string(invalid_color_string)