如何在python pptx中为shape添加透明度?

时间:2016-07-05 11:43:24

标签: python python-2.7 transparency presentation python-pptx

def new_presentation():
    prs=Presentation()
    img="C:/Users/Dennis/Desktop/Tom-Hiddleston-4-1024x768.jpg"
    mainsld=new_slide(prs, 6)
    mainshp=mainsld.shapes
    mainshp.add_picture(img, 0,0, Inches(10))
    titleshape=mainshp.add_shape(MSO_SHAPE.RECTANGLE, Inches(0), Inches(1), Inches(10), Inches(1))
    titleshape.fill.solid()
    titleshape.fill.fore_color.rgb=RGBColor(0x00,0x64,0x00)
    titleshape.fill.transparency = 0.25 ##doesnt work???##########################
    titleshape.line.fill.background()
    titlebox=mainshp.add_textbox(Inches(1), Inches(0.8),Inches(1), Inches(1)).text_frame.add_paragraph()
    titlebox.text="TOM HIDDLESTON"
    titlebox.font.name="Calibri"
    titlebox.font.size=Pt(36)
    titlebox.font.color.rgb=RGBColor(0x90,0x90,0x00)
    prs.save('test.pptx')

标有" ###### s"应该使形状更加透明,如pptx文档中所写 - 它是一个shape.fill属性。代码中的其他所有内容都可以完美运行我使用的是python 2.7和最新的pptx。感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

经过大量挖掘,我已经能够为此提出解决方案

from pptx import Presentation
from pptx.oxml.xmlchemy import OxmlElement
from pptx.util import Cm
from pptx.enum.shapes import MSO_SHAPE
from pptx.dml.color import RGBColor

def SubElement(parent, tagname, **kwargs):
        element = OxmlElement(tagname)
        element.attrib.update(kwargs)
        parent.append(element)
        return element

def _set_shape_transparency(shape, alpha):
    """ Set the transparency (alpha) of a shape"""
    ts = shape.fill._xPr.solidFill
    sF = ts.get_or_change_to_srgbClr()
    sE = SubElement(sF, 'a:alpha', val=str(alpha))

## Create presentation
prs = Presentation()
## Add a slide (empty slide layout)
slide = prs.slides.add_slide(prs.slide_layouts[6])
##Add a blue box to the slide
blueBox = slide.shapes.add_shape(autoshape_type_id=MSO_SHAPE.RECTANGLE,
                         left=Cm(0),
                         top=Cm(0),
                         height=Cm(10),
                         width=Cm(20))
## Make the box blue
blueBoxFill = blueBox.fill
blueBoxFill.solid()
blueBoxFillColour = blueBoxFill.fore_color
blueBoxFillColour.rgb = RGBColor(0,176,240)
## Set the transparency of the blue box to 56%
_set_shape_transparency(blueBox,44000)
## Save the presentation
prs.save(your_path)

答案 1 :(得分:0)

FillFormat.transparency尚未实施。您看到的文档部分可能是分析页面,这是开发的前提。

这是分析页面: http://python-pptx.readthedocs.io/en/latest/dev/analysis/features/dml-fill.html?highlight=transparency

这是开发的FillFormat(.fill)API: http://python-pptx.readthedocs.io/en/latest/api/dml.html#fillformat-objects

但是,您可以使用FillFormat对象的lxml调用来操作其下的XML。您可能希望从.fill元素中的spPr元素开始:

spPr = titleshape.fill._xPr
print spPr.xml

这是做这种事情的一个例子: https://groups.google.com/forum/#!msg/python-pptx/UTkdemIZICw/qeUJEyKEAQAJ

如果您搜索术语python-pptxOxmlElementlxmlworkaround function的各种组合,您会找到更多。