transparency support by spandan-k ยท Pull Request #1090 ยท scanny/python-pptx
Add Comprehensive Transparency Support to python-pptx
๐ฏ Overview
This PR adds complete transparency/opacity support to python-pptx, enabling developers to control the transparency of shape fills and colors. The implementation follows the DrawingML specification and provides a clean, intuitive API across all layers of the library.
โจ Features Added
๐จ ColorFormat Transparency
- Property:
ColorFormat.transparency(read/write, 0.0-1.0 range) - Behavior:
0.0= completely opaque (no alpha element in XML)1.0= completely transparent (alpha=0 in XML)0.5= 50% transparent (alpha=50000 in XML)
- Validation: Raises
ValueErrorfor values outside 0.0-1.0 range - NoneColor Handling: Returns 0.0 for get, raises
ValueErrorfor set
๐จ FillFormat Transparency
- Property:
FillFormat.transparency(read/write, 0.0-1.0 range) - Delegation: Automatically delegates to underlying solid fill
- Error Handling: Raises
TypeErrorfor non-solid fill types (gradient, pattern, etc.) - Integration: Works seamlessly with existing fill API
๐จ _SolidFill Transparency
- Property:
_SolidFill.transparency(read/write, 0.0-1.0 range) - Delegation: Delegates to
fore_color.transparency - Consistency: Maintains transparency across color changes
๐๏ธ Implementation Details
XML Layer (OXML)
- New Elements: Added support for
<a:alpha>,<a:alphaOff>,<a:alphaMod> - Element Class:
CT_PositiveFixedPercentagefor alpha value handling - Registration: Proper element registration in
__init__.py - Methods:
add_alpha(),clear_alpha()for XML manipulation
Domain Model Layer (DML)
- ColorFormat: Core transparency property with validation
- FillFormat: High-level transparency access for fills
- _SolidFill: Solid fill transparency delegation
- _Color: Low-level transparency implementation
๐ฏ Usage Examples
from pptx import Presentation from pptx.util import Inches # Create presentation and add shape prs = Presentation() slide = prs.slides.add_slide(prs.slide_layouts[0]) shape = slide.shapes.add_shape(MSO_SHAPE.RECTANGLE, Inches(1), Inches(1), Inches(2), Inches(2)) # Set fill color and transparency shape.fill.solid() shape.fill.fore_color.rgb = RGBColor(255, 0, 0) # Red shape.fill.transparency = 0.5 # 50% transparent # Alternative: Set transparency via color shape.fill.fore_color.transparency = 0.3 # 30% transparent # Check transparency print(f"Fill transparency: {shape.fill.transparency}") print(f"Color transparency: {shape.fill.fore_color.transparency}")
XML Structure
<a:solidFill> <a:srgbClr val="FF0000"> <a:alpha val="50000"/> <!-- 50% opaque = 50% transparent --> </a:srgbClr> </a:solidFill>
๐ Notes
- Transparency is only supported for solid fills (not gradients or patterns)
- Setting transparency to 0.0 removes the alpha element for optimal XML
- NoneColor objects cannot have transparency set (must set RGB/theme color first)
- All transparency values are validated to be in the 0.0-1.0 range
Closes #62