I have an Area Chart created using Python PPTX, and I need to set the series' fill transparency. I've achieved that with below workaround function, but it seems too convoluted. I am hoping that there are utility functions provided by python-pptx so that there is no need to hack around lxml.
from lxml.etree import Element, SubElement, QName
ns = "http://schemas.openxmlformats.org/drawingml/2006/main"
xPr = prs.slides[3].placeholders[17].chart.series[0].format.fill._xPr
srgbClr = xPr.get_or_change_to_solidFill().get_or_change_to_srgbClr()
alpha = SubElement(srgbClr, QName(ns ,'alpha'), nsmap={'a':ns})
alpha.set('val','50196')
What will be the cleaner way to achieve this?
Well, I'm not sure it's an awful lot cleaner, but if you want to use python-pptx
calls as much as possible, this might be an alternative to consider:
from pptx.dml.color import RGBColor
from pptx.oxml.xmlchemy import OxmlElement
# ---set the fill to solid red using regular python-pptx API---
chart_fill = prs.slides[3].placeholders[17].chart.series[0].format.fill
chart_fill.solid()
chart_fill.fore_color.rgb = RGBColor(255, 0, 0)
# ---add an `a:alpha` child element---
solidFill = chart_fill.fore_color._xFill
alpha = OxmlElement('a:alpha')
alpha.set('val', '50196')
solidFill.srgbClr.append(alpha)
The general concept is that python-pptx
API objects like chart
and format
are proxy objects for an lxml element. The API object composes ("wraps") the lxml element object in a private variable. For example, for an autoshape, the private variable is Shape._sp
. Wherever possible (almost always), that variable has the same name as the element, like _sp
for <p:sp>
. Sometimes the element can have different names. In that case, I replace the variable part with x
. So _xFill
could be an a:solidFill object some times and an a:pattFill object other times.
Also, a while back I started using ._element
as the variable name for the proxy element so it is standardized. Usually I have both (e.g. _sp
and _element
refer to same element object) as they're handy in different circumstances.
To know what the variable name is you can either guess (which works more often than one might expect once you know the pattern) or you can inspect the code or introspect the object. Clicking on the [source]
link in the API documentation once you've found the right proxy object is a fast way to inspect the code. http://python-pptx.readthedocs.io/en/latest/api/dml.html#pptx.dml.color.ColorFormat