Ejemplo n.º 1
0
    def test_replace_font_color(self):
        ms = self.get_master_ppt()
        slide_pos = 1
        real_slide_pos = slide_pos - 1
        origin_slide = ms.slides[real_slide_pos]
        # check placeholder exists
        title_shape_name = 'title'
        body_shape_name = 'body'
        self.assertTrue(self.find_shape(origin_slide, title_shape_name))
        self.assertTrue(self.find_shape(origin_slide, body_shape_name))

        input = [{
            "slide_pos": slide_pos,
            "contents": {
                title_shape_name: {
                    "text": {
                        "font": {
                            "color": "#219653",
                        },
                        "value": "this is test title"
                    },
                },
                body_shape_name: {
                    "text": {
                        "font": {
                            "color": "#EB5757",
                        },
                        "value": "test \nbody",
                    },
                }
            }
        }]
        make_ppt(self.master_slide, self.target_slide, input)
        ppt = self.get_target_ppt()
        slide = ppt.slides[real_slide_pos]
        self.assertEqual(2, len(slide.shapes))

        contents = input[0]['contents']
        title_shape = self.find_shape(slide, title_shape_name)
        title_font = title_shape.text_frame.paragraphs[0].font
        font_color = title_font.color.rgb

        title_hex_color = contents[title_shape_name]['text']['font']['color'][
            1:]
        self.assertEqual(RGBColor.from_string(title_hex_color), font_color)

        body_shape = self.find_shape(slide, body_shape_name)
        body_font = body_shape.text_frame.paragraphs[0].runs[0].font
        body_color = body_font.color.rgb

        body_hex_color = contents[body_shape_name]['text']['font']['color'][1:]
        self.assertEqual(RGBColor.from_string(body_hex_color), body_color)
def colorlist(value,start_value,start_color,end_value,end_color):
    output = []
    value = int(np.round(value,0))
    r1, g1, b1 = RGBColor.from_string(start_color)
    r2, g2, b2 = RGBColor.from_string(end_color)
    rdelta, gdelta, bdelta = (r2-r1)/(end_value-start_value), (g2-g1)/(end_value-start_value), (b2-b1)/(end_value-start_value)
    for step in range(0,end_value - start_value):
        r1 += rdelta
        g1 += gdelta
        b1 += bdelta
        output.append((int(r1), int(g1), int(b1)))
    color = output[value-start_value]
    return color
Ejemplo n.º 3
0
 def __init__(self, ppt_theme, slide):
     self.__colour_defs = {}
     for colour_def in ppt_theme.colour_scheme():
         defn = colour_def[0]
         if defn.tag == DML('sysClr'):
             self.__colour_defs[colour_def.tag] = RGBColor.from_string(
                 defn.attrib['lastClr'])
         elif defn.tag == DML('srgbClr'):
             self.__colour_defs[colour_def.tag] = RGBColor.from_string(
                 defn.val)
     # The slide's layout master can have colour aliases
     colour_map = slide.slide_layout.slide_master.element.clrMap.attrib
     for key, value in colour_map.items():
         if key != value:
             self.__colour_defs[DML(key)] = self.__colour_defs[DML(value)]
Ejemplo n.º 4
0
def fill_color(fill: FillFormat, val: Union[str, tuple, list, None]) -> None:
    '''
    Set the FillFormat color to value specified as a:

    - a named color, like ``black``
    - a hex value, like ``#f80`` or ``#ff8800``
    - an RGB value, like ``rgb(255, 255, 0)`` or ``rgb(1, 0.5, 0.1)``
    - a tuple or list of RGB values, like ``(255, 255, 0)`` or ``[255, 255, 0]``
    - a theme color, like ``ACCENT_1``, ``ACCENT_2``, ``BACKGROUND_1``, ``DARK_1``, ``LIGHT_2``
    - a theme color with a brightness modifier, like ``ACCENT_1+40``, which is 40% brighter than
      Accent 1, or ``ACCENT_2-20`` which is 20% darker than Accent 2
    - ``'none'`` clears the color, i.e. makes it transparent
    '''
    fill.solid()
    if val == 'none':
        fill.background()
    elif isinstance(val, (list, tuple)):
        val = val[:3]
        if any(isinstance(v, float) for v in val) and all(0 <= v <= 1
                                                          for v in val):
            fill.fore_color.rgb = RGBColor(*(int(v * 256 if v < 1 else 255)
                                             for v in val))  # noqa
        else:
            fill.fore_color.rgb = RGBColor(*val)
    elif isinstance(val, str):
        val = color_map.get(val, val).upper()
        if val.startswith('#'):
            if len(val) == 7:
                fill.fore_color.rgb = RGBColor.from_string(val[1:])
            elif len(val) == 4:
                fill.fore_color.rgb = RGBColor.from_string(val[1] * 2 +
                                                           val[2] * 2 +
                                                           val[3] * 2)
        elif val.startswith('RGB('):
            parts = re.findall(r'\d+', val)
            fill.fore_color.rgb = RGBColor(int(parts[0]), int(parts[1]),
                                           int(parts[2]))
        else:
            match = theme_color.match(val)
            if match:
                theme = match.group(1) + ('_' + match.group(2)
                                          if match.group(2) else '')
                fill.fore_color.theme_color = getattr(MSO_THEME_COLOR, theme)
                if match.group(3):
                    fill.fore_color.brightness = float(match.group(3)) / 100
                # else: No brightness adjustment required
            else:
                raise ValueError('Invalid color: %r' % val)
Ejemplo n.º 5
0
def apply_text_css(shape, run, paragraph, **kwargs):
    '''Apply css.'''
    pixcel_to_inch = 10000
    if kwargs.get('color'):
        rows_text = run.font.fill
        rows_text.solid()
        run.font.color.rgb = RGBColor.from_string(
            convert_color_code(kwargs['color']))
    if kwargs.get('font-family'):
        run.font.name = kwargs['font-family']
    if kwargs.get('font-size'):
        run.font.size = pixcel_to_inch * float(kwargs['font-size'])
    if kwargs.get('text-align'):
        if isinstance(kwargs['text-align'], EnumValue) or None:
            paragraph.alignment = kwargs['text-align']
        else:
            paragraph.alignment = getattr(PP_ALIGN,
                                          kwargs['text-align'].upper())
    for prop in {'bold', 'italic', 'underline'}:
        update_prop = kwargs.get(prop)
        if update_prop and not isinstance(update_prop, bool):
            update_prop = ast.literal_eval(update_prop)
        setattr(run.font, prop, update_prop)
    if kwargs.get('text-anchor'):
        shape.vertical_anchor = getattr(MSO_ANCHOR,
                                        shape['text-anchor'].upper())
Ejemplo n.º 6
0
    def new(self, text):
        slide = self.prs.slides.add_slide(self.blank_slide_layout)

        left = Inches(0.5)
        top = Inches(2)
        width = Inches(9)
        height = Inches(3)

        txBox = slide.shapes.add_textbox(left, top, width, height)
        tf = txBox.text_frame
        tf.word_wrap = True
        tf.vertical_anchor = MSO_VERTICAL_ANCHOR.MIDDLE

        p = tf.add_paragraph()
        p.font.size = self.font_size
        p.font.color.rgb = RGBColor.from_string(self.font_color)
        p.alignment = PP_ALIGN.CENTER

        for part in self.get_text_parts(text):
            run = p.add_run()
            run.text = part['text']
            if part['type'] == 'bold':
                run.font.bold = True
            if part['type'] == 'italic':
                run.font.italic = True
Ejemplo n.º 7
0
    def new(self, text):
        slide = self.prs.slides.add_slide(self.blank_slide_layout)
        
        left = Inches (0.5)
        top = Inches (2)
        width = Inches (9)
        height = Inches (3)
    
        txBox = slide.shapes.add_textbox(left, top, width, height)
        #Set background color
        self.slide_bg_color(slide, self.background_color)
        
        tf = txBox.text_frame
        tf.word_wrap = True
        tf.vertical_anchor = MSO_VERTICAL_ANCHOR.MIDDLE

        p = tf.add_paragraph()
        p.font.size = self.font_size
        p.font.color.rgb = RGBColor.from_string(self.font_color)
        p.alignment = PP_ALIGN.CENTER
        
        for part in self.get_text_parts(text):
            run = p.add_run()
            run.text = part['text']
            if part['type'] == 'bold':
                run.font.bold = True
            if part['type'] == 'italic':
                run.font.italic = True
Ejemplo n.º 8
0
def apply_conditional_formatting_to_columns(prs, slide_num, shape_id,
                                            col_rules):
    # Find the powerpoint table
    slide = prs.slides[slide_num]
    table = slide.shapes[shape_id]

    # Get the table dimensions
    num_rows = len(table.table.rows)
    num_cols = len(table.table.columns)

    # Visit all columns that have a rule defined
    for rule in col_rules:
        col_ind = rule['column']

        # Visit all rows
        for row_ind in range(num_rows):

            # Read the cell value
            cell_value_str = table.table.cell(row_ind, col_ind).text

            # Compute the conditional color
            conditional_color = rule['func'](cell_value_str)

            # Apply the color to all paragraphs and runs
            if conditional_color is not None:
                for para in table.table.cell(row_ind,
                                             col_ind).text_frame.paragraphs:
                    for run in para.runs:
                        run.font.color.rgb = RGBColor.from_string(
                            conditional_color)
Ejemplo n.º 9
0
    def set_title_box(self, options):
        title_box = self.slide.shapes.title
        dim = self.get_box_dimensions_from_shape(title_box)
        dim = self.update_box_dimensions(
            dim, self.make_length_from_options(options, 'left'),
            self.make_length_from_options(options, 'top'),
            self.make_length_from_options(options, 'width'),
            self.make_length_from_options(options, 'height'))

        title_box.left = dim[0]
        title_box.top = dim[1]
        title_box.width = dim[2]
        title_box.height = dim[3]

        bg_color = options.get('bg_color')
        if bg_color is not None:
            rgb = RGBColor.from_string(bg_color)
            title_box.fill.solid()
            title_box.fill.fore_color.rgb = rgb
        # set margins on title textframe

        margin_props = [
            'margin_left', 'margin_right', 'margin_top', 'margin_bottom'
        ]

        for p in margin_props:
            m = self.make_length_from_options(options, p)
            if m is not None:
                title_box.text_frame.__setattr__(p, m)

        # raise title to top
        cursor_sp = self.slide.shapes[-1]._element
        cursor_sp.addnext(title_box._element)
Ejemplo n.º 10
0
 def apply_table_css(self, cell, paragraph, run, info):
     '''Apply Table style.'''
     if info.get('fill'):
         cell_fill = cell.fill
         cell_fill.solid()
         cell_fill.fore_color.rgb = RGBColor.from_string(convert_color_code(info['fill']))
     apply_text_css(cell, run, paragraph, **info)
Ejemplo n.º 11
0
 def __addpara(self, this_paragraph, para_source):
     this_paragraph.text = para_source.get('text', '無')
     this_paragraph.level = para_source.get('level', 0)
     if 'size' in para_source:
         this_paragraph.font.size = Pt(para_source['size'])
     if 'color' in para_source:
         this_paragraph.font.color.rgb = RGBColor.from_string(
             para_source['color'])
def ColorScaleRule(value,start_value,start_color, mid_value,mid_color,end_color,end_value):
    value = int(np.round(value,0))

    if value in range(start_value,mid_value):
        return colorlist(value,start_value,start_color,mid_value,mid_color)   
    elif value in range(mid_value,end_value):
        return colorlist(value,mid_value,mid_color,end_value,end_color)
    else:
        return RGBColor.from_string(end_color)
Ejemplo n.º 13
0
def chart_css(fill, style, color):
    '''Function to add opacity to charts.'''
    fill.solid()
    pix_to_inch = 100000
    fill.fore_color.rgb = RGBColor.from_string(utils.convert_color_code(color))
    solid_fill = fill.fore_color._xFill
    alpha = OxmlElement('a:alpha')
    alpha.set('val', '%d' % (pix_to_inch * style.get('opacity', 1.0)))
    solid_fill.srgbClr.append(alpha)
    return fill
Ejemplo n.º 14
0
 def generate_color(self):
     if self._color_input_type == "rgb_list":
         rgb_list = [
             self._color_input[0], self._color_input[1],
             self._color_input[2]
         ]
         self._color = self.generate_color_from_rgb_list(rgb_list)
     elif self._color_input_type == "rgb_str":
         rgb_list = self._color_input.split(" ")
         self._color = self.generate_color_from_rgb_list(rgb_list)
     elif self._color_input_type == "hex":
         self._color = RGBColor.from_string(self._color_input)
Ejemplo n.º 15
0
def add_rect(slide, left, top, width, height, fill='89ABBF'):
    # left, top, width, height = Inches(0), Inches(0), Inches(13.3326), Inches(0.10625)
    # left, top, width, height = Inches(0), Inches(0), Length(12192000), Length(100000)
    shape = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, left, top, width,
                                   height)

    shape_fill = shape.fill
    shape_fill.solid()
    # shape_fill.fore_color.rgb = RGBColor(180, 216, 222)
    shape_fill.fore_color.rgb = RGBColor.from_string(fill)

    shape_border_line = shape.line
    shape_border_line.fill.background()
def OtherColorScaleRule(sheetname,value):
    start_color = '00ff7f'
    mid_color = 'ffff00'
    end_color = 'ffff00'
    if sheetname in ('Contention & Ready Time','CPU Co-Stop'):
        start_value = 0
        mid_value = 5
        end_value = 5
        color = ColorScaleRule(value,start_value,start_color, mid_value,mid_color,end_color,end_value)
    elif sheetname == 'Latency' :
        start_value = 0
        mid_value = 15
        end_value = 15
        color = ColorScaleRule(value,start_value,start_color, mid_value,mid_color,end_color,end_value)
    
    elif sheetname in ('Packet Drop','VMs at Risk'):
        start_value = 0
        mid_value = 1
        end_value = 1
        if value == 0:
            color = RGBColor.from_string('00ff7f')
        else:
            color = RGBColor.from_string('ffff00')
    return color 
Ejemplo n.º 17
0
def insert_table(slide, t, top=None, col_width=None):
    (left, width, height) = (296260, 8551480, 5078313)
    if top is None:
        top = 1347965 + 25 * 914400 // 72
    rows = len(t)
    cols = len(t.header())
    table = slide.shapes.add_table(rows + 1, cols, left, top, width,
                                   height).table

    #table.columns[0].width = Inches(2.0)
    #table.columns[1].width = Inches(4.0)

    # write column headings
    S_header = t.header()
    if col_width is not None:
        width_remain = width
        for k, v in col_width.items():
            i = t.col_index(k)
            table.columns[i].width = int(v)
            width_remain -= v
        w = int(max(width_remain / (cols - len(col_width)), 914400 // 2))
        for i, x in enumerate(S_header):
            if x not in col_width:
                table.columns[i].width = w
    table.rows[0].height = 14 * 914400 // 72

    for i in range(cols):
        table.cell(0, i).text = S_header[i]
        for j in range(rows):
            table.cell(j + 1,
                       i).text = '' if pd.isnull(t.iat[j,
                                                       i]) else str(t.iat[j,
                                                                          i])
    if '_Color_' in S_header:  # used for color legend
        j = util.index('_Color_', S_header)
        for i in range(1, rows + 1):
            table.cell(i, j).fill.solid()
            s_hex = t.iat[i - 1, j].replace('#', '')
            if re.search(r'^[A-F0-9]{6}$', s_hex):
                table.cell(i,
                           j).fill.fore_color.rgb = RGBColor.from_string(s_hex)
    return table
Ejemplo n.º 18
0
    def configureText(self,
                      para,
                      text,
                      size,
                      align=2,
                      clr='000000',
                      bold=False,
                      italic=False):
        para.alignment = align
        run = para.add_run()
        run.text = str(text)

        font = run.font
        font.name = 'Liberation Serif'
        font.size = Pt(int(size))
        font.bold = bold
        font.italic = italic
        font.fill.solid()
        color = RGBColor.from_string(clr)
        font.fill.fore_color.rgb = color
def add_textbox_centered_full_width(prs,
                                    slide_num,
                                    text_string,
                                    top_inch=4.4,
                                    height_inch=1.0,
                                    font_size_pt=24,
                                    font_name='Calabri',
                                    fill_hex=''):

    # Insert the text box
    text_shape = prs.slides[slide_num].shapes.add_textbox(
        left=Inches(0),
        top=Inches(top_inch),
        width=Inches(prs.slide_width.inches),
        height=Inches(height_inch))

    # Set the text string
    text_frame = text_shape.text_frame
    text_paragraph = text_frame.paragraphs[0]
    text_run = text_paragraph.add_run()
    text_run.text = text_string

    # Set center alignment
    text_frame.vertical_anchor = MSO_VERTICAL_ANCHOR.MIDDLE
    text_paragraph.alignment = PP_PARAGRAPH_ALIGNMENT.CENTER

    # Set the font
    font = text_run.font
    font.name = font_name
    font.size = Pt(font_size_pt)
    font.bold = False
    font.italic = False
    font.color.theme_color = MSO_THEME_COLOR_INDEX.TEXT_1

    # Set the fill color
    if len(fill_hex) > 0:
        text_shape.fill.solid()
        text_shape.fill.fore_color.rgb = RGBColor.from_string(fill_hex)

    return prs
Ejemplo n.º 20
0
def main():
	trainer_dict, battle_dict = load_pickle("../omega.pickle")

	trainer_wins = enemy_wins = draws = 0
	battle_list = list(battle_dict.values())

	lorelei_draws = [b for b in battle_list if b.player.class_id == 244 and b.winner.startswith("Draw")]
	pokemon_lorelei_drew_against = [p for b in lorelei_draws for p in b.enemy.party_mons]
	print("Pokémon Lorelei drew against:")
	print("\n".join([f"Lv. {p.level} {p.species}" for p in pokemon_lorelei_drew_against]))

	battles_with_wasted_heal(battle_list)

	for battle in battle_list:
		if battle.winner == 'trainer':
			trainer_wins += 1
		elif battle.winner == 'enemy':
			enemy_wins += 1
		else:
			draws += 1
		if battle.player != battle.enemy:
			update_elo(battle.player, battle.enemy, battle.winner)

	oddish_battles = [b for b in battle_list if b.enemy.party_mons[0].species == "ODDISH" and b.player.party_mons[0].species == "ODDISH" and "Draw" in b.winner]

	print("Trainer wins:", trainer_wins, "enemy wins:", enemy_wins, "draws:", draws)
	battle_trainers = list(trainer_dict.values())
	battle_trainers.sort(key=lambda t: t.elo)

	elo_list = [t.elo for t in battle_trainers]
	kde_boundaries = kde_cluster(elo_list, K=28)

	for b in range(1, 281):
		kde_cluster(elo_list, K=b/10, save=True, index=b)

	greatest_diff_boundaries = greatest_diffs_cluster(elo_list, cluster_count=14)
	human_boundaries = [444.6391, 561.3502, 1038.7349, 1118.5088, 1225.8032,
	                    1358.1477, 1500.3403, 1661.6945, 1782.0818, 1887.0274, 2214.7272,
	                    2370.2143, 2559.3289]

	print(greatest_diff_boundaries)
	current_kde_tier = 0
	current_diff_tier = 0
	current_human_tier = 0
	for trainer in battle_trainers:
		if current_kde_tier < len(kde_boundaries) and trainer.elo > kde_boundaries[current_kde_tier]:
			current_kde_tier += 1
		if current_diff_tier < len(greatest_diff_boundaries) and trainer.elo > greatest_diff_boundaries[
			current_diff_tier]:
			current_diff_tier += 1
		if current_human_tier < len(human_boundaries) and trainer.elo >= human_boundaries[current_human_tier] - 0.1:
			current_human_tier += 1
		trainer.tier = current_human_tier
		win_count, lose_count, draw_count = trainer.get_win_rate()
		print("\t".join(
			("trainer:", trainer.identifier, "location", trainer.location if trainer.location else "somewhere",
			 "party:", ", ".join(f"Lv. {mon.level} {mon.species}" for mon in trainer.party_mons),
			 "class:", str(trainer.class_id), "instance:", str(trainer.instance_id),
			 "win count:", str(win_count), "lose count:", str(lose_count),
			 "draw count:", str(draw_count), "elo:", str(trainer.elo),
			 "kde tier:", str(current_kde_tier), "diff tier:", str(current_diff_tier))))

	battle_list.sort(key=lambda b: b.losing_trainer.elo - b.winning_trainer.elo, reverse=True)
	for upset in battle_list[:100]:
		print("\t".join((upset.original_path, upset.winning_trainer.identifier, str(upset.winning_trainer.elo),
		                 upset.losing_trainer.identifier, str(upset.losing_trainer.elo),
		                 str(upset.losing_trainer.elo - upset.winning_trainer.elo))))

	if DO_POWERPOINT:
		trainer_list = list(trainer_dict.values())
		trainer_list.sort(key=lambda t: t.elo)

		for trainer in trainer_list:
			decisive_battles = [b for b in trainer.battles if "Draw" not in b.winner]
			victories = [b for b in decisive_battles if b.winning_trainer == trainer]
			defeats = [b for b in decisive_battles if b.losing_trainer == trainer]
			trainer.greatest_victory = max(victories, key=lambda b: b.losing_trainer.elo)
			trainer.greatest_defeat = min(defeats, key=lambda b: b.winning_trainer.elo)

		tier_names = ["F", "D-", "D", "D+", "C-", "C",
		              "C+", "B-", "B", "B+", "A-", "A", "A+",
		              "S", "S+"]
		tier_colors = ["00b050", "24bb45", "4bc735", "6fd226", "93de15", "b8e900",
		               "dcf400", "ffff00", "ffd600", "ffac00", "ff5d00", "ff5700",
		               "ff2b00", "ff0000", "ff0000"]

		lose_width = 3741321

		from pptx import Presentation
		from pptx.dml.color import RGBColor

		prs = Presentation("base.pptm")
		prs.slide_height = prs.slide_height // 4
		for i, slide in enumerate(prs.slides):
			trainer = trainer_list[i]
			battle_count = trainer.win_count + trainer.draw_count + trainer.lose_count
			for shape in slide.shapes:
				if shape.name == "win":
					shape.width = int(trainer.win_count / battle_count * lose_width)
				elif shape.name == "draw":
					shape.width = int((trainer.win_count + trainer.draw_count) / battle_count * lose_width)
				elif shape.name == "tier":
					shape.fill.fore_color.rgb = RGBColor.from_string(tier_colors[trainer.tier])
				elif shape.name == "pic":
					image, rid = shape.part.get_or_add_image_part(
						"V:\\Dropbox\\elo-world\\video\\3d\\textures\\trainer_sprites\\" +
						get_trainer_by_id(trainer.class_id, trainer.instance_id)[0]["sprite"])
					shape._element.blipFill.blip.rEmbed = rid
				elif shape.name == "pkmn":
					for i, cell in enumerate(shape.table.iter_cells()):
						for p in cell.text_frame.paragraphs:
							for r in p.runs:
								if i < len(trainer.party_mons):
									if "Lv" in r.text:
										r.text = f"Lv. {trainer.party_mons[i].level}"
									else:
										r.text = f"{trainer.party_mons[i].species}"
								else:
									r.text = " "
				elif shape.name == "upset":
					for cell in shape.table.iter_cells():
						for p in cell.text_frame.paragraphs:
							for r in p.runs:
								if r.text == "dna":
									r.text = f"{tier_names[trainer.greatest_defeat.winning_trainer.tier]} {trainer.greatest_defeat.winning_trainer.name}"
								elif r.text == "dnu":
									r.text = f"{trainer.greatest_defeat.winning_trainer.instance_id} - {int(trainer.greatest_defeat.winning_trainer.elo)}"
								elif r.text == "vna":
									r.text = f"{tier_names[trainer.greatest_victory.losing_trainer.tier]} {trainer.greatest_victory.losing_trainer.name}"
								elif r.text == "vnu":
									r.text = f"{trainer.greatest_victory.losing_trainer.instance_id} - {int(trainer.greatest_victory.losing_trainer.elo)}"

				if shape.has_text_frame:
					for p in shape.text_frame.paragraphs:
						for r in p.runs:
							if r.text == "t":
								r.text = tier_names[trainer.tier]
							elif r.text == "ra":
								r.text = str(len(trainer_list) - i)
							elif r.text == "na":
								r.text = trainer.name
							elif r.text == "nu":
								r.text = str(trainer.instance_id)
							elif r.text == "wld":
								r.text = f"W-D-L:{trainer.win_count}-{trainer.draw_count}-{trainer.lose_count}"
							elif r.text == "elo":
								r.text = str(int(trainer.elo))
							elif r.text == "loc":
								r.text = trainer.location

		prs.save("test1.pptm")
Ejemplo n.º 21
0
def set_font_color(run, key, value):
    rgb = RGBColor.from_string(value)
    run.font.color.rgb = rgb
Ejemplo n.º 22
0
def set_shape_bg_color(shape, key, value):
    rgb = RGBColor.from_string(value)
    shape.fill.solid()
    shape.fill.fore_color.rgb = rgb
def insert_excel_range(prs,
                       wb,
                       sheet=0,
                       col_start='A',
                       col_stop='B',
                       row_start=1,
                       row_stop=2,
                       slide_num=0,
                       top_inch=1,
                       left_inch=1,
                       width_inch=3,
                       height_inch=3,
                       font_size_factor=1.0):
    # Load the office theme colors
    office_theme_colors = load_office_theme_colors()

    # Create the empty powerpoint table
    slide = prs.slides[slide_num]
    num_row = row_stop - row_start + 1
    num_col = ord(col_stop) - ord(col_start) + 1
    table = slide.shapes.add_table(rows=num_row,
                                   cols=num_col,
                                   left=Inches(left_inch),
                                   top=Inches(top_inch),
                                   width=Inches(width_inch),
                                   height=Inches(height_inch))

    # Turn off special first-row formatting
    table.table.first_row = False

    # Set minimum row heights
    for row in table.table.rows:
        row.height = 0

    # Merge ranges as needed
    for merge_range in wb[sheet].merged_cells.ranges:

        merge_range_bounds = merge_range.bounds
        top_left_col = merge_range_bounds[0] - 1 - (ord(col_start) - ord('A'))
        top_left_row = merge_range_bounds[1] - row_start
        bottom_right_col = merge_range_bounds[2] - 1 - (ord(col_start) -
                                                        ord('A'))
        bottom_right_row = merge_range_bounds[3] - row_start

        if (top_left_col >= 0 and top_left_row >= 0 and bottom_right_col <=
            (ord(col_stop) - ord(col_start)) and bottom_right_row <=
            (row_stop - row_start)):
            origin_cell = table.table.cell(top_left_row, top_left_col)
            other_cell = table.table.cell(bottom_right_row, bottom_right_col)
            origin_cell.merge(other_cell)

    # Fill the powerpoint table cell-by-cell
    for row in range(row_start - row_start, row_stop - row_start + 1):
        for col in range(0, ord(col_stop) - ord(col_start) + 1):
            excel_col_letter = chr((col + ord(col_start) - ord('A')) +
                                   ord('A'))
            excel_row_num = row + row_start
            cell_ref = str(excel_col_letter) + str(excel_row_num)

            # Get the excel cell value
            cell_value = get_cell_value(wb, sheet, cell_ref)

            # Set the cell value
            table.table.cell(row, col).text = cell_value

            # Get the excel cell font color
            cell_font_color = get_cell_font_color(wb, sheet, cell_ref,
                                                  office_theme_colors)

            # Transfer font color and set font weight to normal
            for para in table.table.cell(row, col).text_frame.paragraphs:
                for run in para.runs:
                    run.font.color.rgb = RGBColor.from_string(cell_font_color)
                    # run.font.bold = False

            # Get the excel cell fill color
            cell_fill_color = get_cell_fill_color(wb, sheet, cell_ref,
                                                  office_theme_colors)

            # Transfer fill color
            table.table.cell(row, col).fill.solid()
            table.table.cell(row,
                             col).fill.fore_color.rgb = RGBColor.from_string(
                                 cell_fill_color)

            # Transfer the font size
            cell_font_size = get_cell_font_size(wb, sheet, cell_ref)
            for para in table.table.cell(row, col).text_frame.paragraphs:
                for run in para.runs:
                    run.font.size = Pt(
                        int(round(cell_font_size * font_size_factor)))

            # Get cell alignment
            cell_alignment = get_cell_alignment(wb, sheet, cell_ref)

            # Set cell alignment
            for para in table.table.cell(row, col).text_frame.paragraphs:
                if cell_alignment is None:
                    pass
                elif cell_alignment.upper() == 'LEFT':
                    para.alignment = PP_PARAGRAPH_ALIGNMENT.LEFT
                elif cell_alignment.upper() == 'RIGHT':
                    para.alignment = PP_PARAGRAPH_ALIGNMENT.RIGHT
                elif cell_alignment.upper() == 'CENTER':
                    para.alignment = PP_PARAGRAPH_ALIGNMENT.CENTER
    return prs
Ejemplo n.º 24
0
 def addWhiteSlide(self):
     self.slide = self.presentation.slides.add_slide(
         self.blank_slide_layout)
     self.slide.background.fill.solid()
     color = RGBColor.from_string('ffffff')
     self.slide.background.fill.fore_color.rgb = color
Ejemplo n.º 25
0
 def it_can_construct_from_a_hex_string_rgb_value(self):
     rgb = RGBColor.from_string('123456')
     assert rgb == RGBColor(0x12, 0x34, 0x56)
Ejemplo n.º 26
0
    def test_raw_type(self):
        ms = self.get_master_ppt()
        slide_pos = 3
        real_slide_pos = slide_pos - 1
        origin_slide = ms.slides[real_slide_pos]
        # check placeholder exists
        shape_name = 'table'
        self.assertTrue(self.find_shape(origin_slide, shape_name))
        black_color = '000000'
        green_color = '00F900'
        input = [{
            "slide_pos": slide_pos,
            "contents": {
                shape_name: {
                    "table": {
                        "data_type":
                        "raw",
                        "data": [
                            [
                                {
                                    "value": "now black",
                                    "font": {
                                        "color": f"#{black_color}"
                                    }
                                },
                                {
                                    "value": "no bold",
                                    "font": {
                                        "bold": False
                                    }
                                },
                                {
                                    "value": "no underline",
                                    "font": {
                                        "underline": False
                                    }
                                },
                                {
                                    "value": "no italic",
                                    "font": {
                                        "italic": False
                                    }
                                },
                            ],
                            [
                                {
                                    "value": "this is green",
                                    "font": {
                                        "color": f"#{green_color}"
                                    }
                                },
                                {
                                    "value": "this is bold",
                                    "font": {
                                        "bold": True
                                    }
                                },
                                {
                                    "value": "this is underline",
                                    "font": {
                                        "underline": True
                                    }
                                },
                                {
                                    "value": "this is italic",
                                    "font": {
                                        "italic": True
                                    }
                                },
                            ],
                        ],
                    }
                },
            }
        }]
        make_ppt(self.master_slide, self.target_slide, input)
        ppt = self.get_target_ppt()
        slide = ppt.slides[real_slide_pos]

        table_shape = self.find_shape(slide, shape_name)
        color_text, bold_text, underline_text, italic_text = (
            cell.text_frame.paragraphs[0].runs[0].font
            for cell in table_shape.table.rows[0].cells)
        self.assertEqual(RGBColor.from_string(black_color),
                         color_text.color.rgb)
        self.assertFalse(bold_text.bold)
        self.assertFalse(underline_text.underline)
        self.assertFalse(italic_text.italic)

        color_text, bold_text, underline_text, italic_text = (
            cell.text_frame.paragraphs[0].runs[0].font
            for cell in table_shape.table.rows[1].cells)
        self.assertEqual(RGBColor.from_string(green_color),
                         color_text.color.rgb)
        self.assertTrue(bold_text.bold)
        self.assertTrue(underline_text.underline)
        self.assertTrue(italic_text.italic)
Ejemplo n.º 27
0
def replace_font_style(subshape: Union[_Run, _Paragraph],
                       text_frame_data: TextStyle):
    if font_style := text_frame_data.font:
        if font_color := font_style.color:
            # font_color value must be hex cololr ex) #ffffff
            subshape.font.color.rgb = RGBColor.from_string(font_color[1:])
Ejemplo n.º 28
0
 def it_can_construct_from_a_hex_string_rgb_value(self):
     rgb = RGBColor.from_string('123456')
     assert rgb == RGBColor(0x12, 0x34, 0x56)