Harbor format: 14 coding_additions tasks (part 6)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+3
- tasks/tasksmith-74f059424102/environment/source/src/pptx/oxml/slide.pyAdded+347
- tasks/tasksmith-74f059424102/environment/source/src/pptx/oxml/table.pyAdded+588
- tasks/tasksmith-74f059424102/environment/source/src/pptx/oxml/text.pyAdded+618
- tasks/tasksmith-74f059424102/environment/source/src/pptx/oxml/theme.pyAdded+29
- tasks/tasksmith-74f059424102/environment/source/src/pptx/oxml/xmlchemy.pyAdded+717
- tasks/tasksmith-74f059424102/environment/source/src/pptx/package.pyAdded+222
- tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/__init__.pyAdded
- tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/chart.pyAdded+95
- tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/coreprops.pyAdded+167
- tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/embeddedpackage.pyAdded+93
- tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/image.pyAdded+275
- tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/media.pyAdded+37
- tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/presentation.pyAdded+126
- tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/slide.pyAdded+297
- tasks/tasksmith-74f059424102/environment/source/src/pptx/presentation.pyAdded+113
- tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/__init__.pyAdded+26
- tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/autoshape.pyAdded+355
- tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/base.pyAdded+244
- tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/connector.pyAdded+297
- tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/freeform.pyAdded+338
- tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/graphfrm.pyAdded+166
- tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/group.pyAdded+69
- tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/picture.pyAdded+203
- tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/placeholder.pyAdded+407
- tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/shapetree.pyAdded+1190
- tasks/tasksmith-74f059424102/environment/source/src/pptx/shared.pyAdded+82
- tasks/tasksmith-74f059424102/environment/source/src/pptx/slide.pyAdded+498
- tasks/tasksmith-74f059424102/environment/source/src/pptx/spec.pyAdded+632
- tasks/tasksmith-74f059424102/environment/source/src/pptx/table.pyAdded+496
- tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/default.pptxAdded
- tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/docx-icon.emfAdded
- tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/generic-icon.emfAdded
- tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/notes.xmlAdded+23
- tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/notesMaster.xmlAdded+352
- tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/pptx-icon.emfAdded
- tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/theme.xmlAdded+321
- tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/xlsx-icon.emfAdded
- tasks/tasksmith-74f059424102/environment/source/src/pptx/text/__init__.pyAdded
- tasks/tasksmith-74f059424102/environment/source/src/pptx/text/fonts.pyAdded+399
- tasks/tasksmith-74f059424102/environment/source/src/pptx/text/layout.pyAdded+325
- tasks/tasksmith-74f059424102/environment/source/src/pptx/text/text.pyAdded+681
- tasks/tasksmith-74f059424102/environment/source/src/pptx/types.pyAdded+36
- tasks/tasksmith-74f059424102/environment/source/src/pptx/util.pyAdded+214
- tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/PKG-INFOAdded+599
- tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/SOURCES.txtAdded+502
- tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/dependency_links.txtAdded+1
- tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/not-zip-safeAdded+1
- tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/requires.txtAdded+3
- tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/top_level.txtAdded+1
87 unmodified lines88899087 unmodified linestasks/tasksmith-74f059424102/environment/source/spec/ISO-IEC-29500-2/ISO-IEC-29500-2.pdf filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/environment/source/spec/ISO-IEC-29500-3/ISO-IEC-29500-3.pdf filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/environment/source/spec/ISO-IEC-29500-4/ISO-IEC-29500-4.pdf filter=lfs diff=lfs merge=lfs -text87 unmodified lines88899091929387 unmodified linestasks/tasksmith-74f059424102/environment/source/spec/ISO-IEC-29500-2/ISO-IEC-29500-2.pdf filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/environment/source/spec/ISO-IEC-29500-3/ISO-IEC-29500-3.pdf filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/environment/source/spec/ISO-IEC-29500-4/ISO-IEC-29500-4.pdf filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/environment/source/src/pptx/templates/docx-icon.emf filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/environment/source/src/pptx/templates/xlsx-icon.emf filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/environment/source/tests/test_files/calibriz.ttf filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347"""Slide-related custom element classes, including those for masters."""
from __future__ import annotations
from typing import TYPE_CHECKING, Callable, cast
from pptx.oxml import parse_from_template, parse_xmlfrom pptx.oxml.dml.fill import CT_GradientFillPropertiesfrom pptx.oxml.ns import nsdeclsfrom pptx.oxml.simpletypes import XsdStringfrom pptx.oxml.xmlchemy import ( BaseOxmlElement, Choice, OneAndOnlyOne, OptionalAttribute, RequiredAttribute, ZeroOrMore, ZeroOrOne, ZeroOrOneChoice,)
if TYPE_CHECKING: from pptx.oxml.shapes.groupshape import CT_GroupShape
class _BaseSlideElement(BaseOxmlElement): """Base class for the six slide types, providing common methods."""
cSld: CT_CommonSlideData
@property def spTree(self) -> CT_GroupShape: """Return required `p:cSld/p:spTree` grandchild.""" return self.cSld.spTree
class CT_Background(BaseOxmlElement): """`p:bg` element."""
_insert_bgPr: Callable[[CT_BackgroundProperties], None]
# ---these two are actually a choice, not a sequence, but simpler for # ---present purposes this way. _tag_seq = ("p:bgPr", "p:bgRef") bgPr: CT_BackgroundProperties | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] "p:bgPr", successors=() ) bgRef = ZeroOrOne("p:bgRef", successors=()) del _tag_seq
def add_noFill_bgPr(self): """Return a new `p:bgPr` element with noFill properties.""" xml = "<p:bgPr %s>\n" " <a:noFill/>\n" " <a:effectLst/>\n" "</p:bgPr>" % nsdecls("a", "p") bgPr = cast(CT_BackgroundProperties, parse_xml(xml)) self._insert_bgPr(bgPr) return bgPr
class CT_BackgroundProperties(BaseOxmlElement): """`p:bgPr` element."""
_tag_seq = ( "a:noFill", "a:solidFill", "a:gradFill", "a:blipFill", "a:pattFill", "a:grpFill", "a:effectLst", "a:effectDag", "a:extLst", ) eg_fillProperties = ZeroOrOneChoice( ( Choice("a:noFill"), Choice("a:solidFill"), Choice("a:gradFill"), Choice("a:blipFill"), Choice("a:pattFill"), Choice("a:grpFill"), ), successors=_tag_seq[6:], ) del _tag_seq
def _new_gradFill(self): """Override default to add default gradient subtree.""" return CT_GradientFillProperties.new_gradFill()
class CT_CommonSlideData(BaseOxmlElement): """`p:cSld` element."""
_remove_bg: Callable[[], None] get_or_add_bg: Callable[[], CT_Background]
_tag_seq = ("p:bg", "p:spTree", "p:custDataLst", "p:controls", "p:extLst") bg: CT_Background | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] "p:bg", successors=_tag_seq[1:] ) spTree: CT_GroupShape = OneAndOnlyOne("p:spTree") # pyright: ignore[reportAssignmentType] del _tag_seq name: str = OptionalAttribute( # pyright: ignore[reportAssignmentType] "name", XsdString, default="" )
def get_or_add_bgPr(self) -> CT_BackgroundProperties: """Return `p:bg/p:bgPr` grandchild.
If no such grandchild is present, any existing `p:bg` child is first removed and a new default `p:bg` with noFill settings is added. """ bg = self.bg if bg is None or bg.bgPr is None: bg = self._change_to_noFill_bg() return cast(CT_BackgroundProperties, bg.bgPr)
def _change_to_noFill_bg(self) -> CT_Background: """Establish a `p:bg` child with no-fill settings.
Any existing `p:bg` child is first removed. """ self._remove_bg() bg = self.get_or_add_bg() bg.add_noFill_bgPr() return bg
class CT_NotesMaster(_BaseSlideElement): """`p:notesMaster` element, root of a notes master part."""
_tag_seq = ("p:cSld", "p:clrMap", "p:hf", "p:notesStyle", "p:extLst") cSld: CT_CommonSlideData = OneAndOnlyOne("p:cSld") # pyright: ignore[reportAssignmentType] del _tag_seq
@classmethod def new_default(cls) -> CT_NotesMaster: """Return a new `p:notesMaster` element based on the built-in default template.""" return cast(CT_NotesMaster, parse_from_template("notesMaster"))
class CT_NotesSlide(_BaseSlideElement): """`p:notes` element, root of a notes slide part."""
_tag_seq = ("p:cSld", "p:clrMapOvr", "p:extLst") cSld: CT_CommonSlideData = OneAndOnlyOne("p:cSld") # pyright: ignore[reportAssignmentType] del _tag_seq
@classmethod def new(cls) -> CT_NotesSlide: """Return a new ``<p:notes>`` element based on the default template.
Note that the template does not include placeholders, which must be subsequently cloned from the notes master. """ return cast(CT_NotesSlide, parse_from_template("notes"))
class CT_Slide(_BaseSlideElement): """`p:sld` element, root element of a slide part (XML document)."""
_tag_seq = ("p:cSld", "p:clrMapOvr", "p:transition", "p:timing", "p:extLst") cSld: CT_CommonSlideData = OneAndOnlyOne("p:cSld") # pyright: ignore[reportAssignmentType] clrMapOvr = ZeroOrOne("p:clrMapOvr", successors=_tag_seq[2:]) timing = ZeroOrOne("p:timing", successors=_tag_seq[4:]) del _tag_seq
@classmethod def new(cls) -> CT_Slide: """Return new `p:sld` element configured as base slide shape.""" return cast(CT_Slide, parse_xml(cls._sld_xml()))
@property def bg(self): """Return `p:bg` grandchild or None if not present.""" return self.cSld.bg
def get_or_add_childTnLst(self): """Return parent element for a new `p:video` child element.
The `p:video` element causes play controls to appear under a video shape (pic shape containing video). There can be more than one video shape on a slide, which causes the precondition to vary. It needs to handle the case when there is no `p:sld/p:timing` element and when that element already exists. If the case isn't simple, it just nukes what's there and adds a fresh one. This could theoretically remove desired existing timing information, but there isn't any evidence available to me one way or the other, so I've taken the simple approach. """ childTnLst = self._childTnLst if childTnLst is None: childTnLst = self._add_childTnLst() return childTnLst
def _add_childTnLst(self): """Add `./p:timing/p:tnLst/p:par/p:cTn/p:childTnLst` descendant.
Any existing `p:timing` child element is ruthlessly removed and replaced. """ self.remove(self.get_or_add_timing()) timing = parse_xml(self._childTnLst_timing_xml()) self._insert_timing(timing) return timing.xpath("./p:tnLst/p:par/p:cTn/p:childTnLst")[0]
@property def _childTnLst(self): """Return `./p:timing/p:tnLst/p:par/p:cTn/p:childTnLst` descendant.
Return None if that element is not present. """ childTnLsts = self.xpath("./p:timing/p:tnLst/p:par/p:cTn/p:childTnLst") if not childTnLsts: return None return childTnLsts[0]
@staticmethod def _childTnLst_timing_xml(): return ( "<p:timing %s>\n" " <p:tnLst>\n" " <p:par>\n" ' <p:cTn id="1" dur="indefinite" restart="never" nodeType="' 'tmRoot">\n' " <p:childTnLst/>\n" " </p:cTn>\n" " </p:par>\n" " </p:tnLst>\n" "</p:timing>" % nsdecls("p") )
@staticmethod def _sld_xml(): return ( "<p:sld %s>\n" " <p:cSld>\n" " <p:spTree>\n" " <p:nvGrpSpPr>\n" ' <p:cNvPr id="1" name=""/>\n' " <p:cNvGrpSpPr/>\n" " <p:nvPr/>\n" " </p:nvGrpSpPr>\n" " <p:grpSpPr/>\n" " </p:spTree>\n" " </p:cSld>\n" " <p:clrMapOvr>\n" " <a:masterClrMapping/>\n" " </p:clrMapOvr>\n" "</p:sld>" % nsdecls("a", "p", "r") )
class CT_SlideLayout(_BaseSlideElement): """`p:sldLayout` element, root of a slide layout part."""
_tag_seq = ("p:cSld", "p:clrMapOvr", "p:transition", "p:timing", "p:hf", "p:extLst") cSld: CT_CommonSlideData = OneAndOnlyOne("p:cSld") # pyright: ignore[reportAssignmentType] del _tag_seq
class CT_SlideLayoutIdList(BaseOxmlElement): """`p:sldLayoutIdLst` element, child of `p:sldMaster`.
Contains references to the slide layouts that inherit from the slide master. """
sldLayoutId_lst: list[CT_SlideLayoutIdListEntry]
sldLayoutId = ZeroOrMore("p:sldLayoutId")
class CT_SlideLayoutIdListEntry(BaseOxmlElement): """`p:sldLayoutId` element, child of `p:sldLayoutIdLst`.
Contains a reference to a slide layout. """
rId: str = RequiredAttribute("r:id", XsdString) # pyright: ignore[reportAssignmentType]
class CT_SlideMaster(_BaseSlideElement): """`p:sldMaster` element, root of a slide master part."""
get_or_add_sldLayoutIdLst: Callable[[], CT_SlideLayoutIdList]
_tag_seq = ( "p:cSld", "p:clrMap", "p:sldLayoutIdLst", "p:transition", "p:timing", "p:hf", "p:txStyles", "p:extLst", ) cSld: CT_CommonSlideData = OneAndOnlyOne("p:cSld") # pyright: ignore[reportAssignmentType] sldLayoutIdLst: CT_SlideLayoutIdList = ZeroOrOne( # pyright: ignore[reportAssignmentType] "p:sldLayoutIdLst", successors=_tag_seq[3:] ) del _tag_seq
class CT_SlideTiming(BaseOxmlElement): """`p:timing` element, specifying animations and timed behaviors."""
_tag_seq = ("p:tnLst", "p:bldLst", "p:extLst") tnLst = ZeroOrOne("p:tnLst", successors=_tag_seq[1:]) del _tag_seq
class CT_TimeNodeList(BaseOxmlElement): """`p:tnLst` or `p:childTnList` element."""
def add_video(self, shape_id): """Add a new `p:video` child element for movie having *shape_id*.""" video_xml = ( "<p:video %s>\n" ' <p:cMediaNode vol="80000">\n' ' <p:cTn id="%d" fill="hold" display="0">\n' " <p:stCondLst>\n" ' <p:cond delay="indefinite"/>\n' " </p:stCondLst>\n" " </p:cTn>\n" " <p:tgtEl>\n" ' <p:spTgt spid="%d"/>\n' " </p:tgtEl>\n" " </p:cMediaNode>\n" "</p:video>\n" % (nsdecls("p"), self._next_cTn_id, shape_id) ) video = parse_xml(video_xml) self.append(video)
@property def _next_cTn_id(self): """Return the next available unique ID (int) for p:cTn element.""" cTn_id_strs = self.xpath("/p:sld/p:timing//p:cTn/@id") ids = [int(id_str) for id_str in cTn_id_strs] return max(ids) + 1
class CT_TLMediaNodeVideo(BaseOxmlElement): """`p:video` element, specifying video media details."""
_tag_seq = ("p:cMediaNode",) cMediaNode = OneAndOnlyOne("p:cMediaNode") del _tag_seq123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588"""Custom element classes for table-related XML elements"""
from __future__ import annotations
from typing import TYPE_CHECKING, Callable, Iterator, cast
from pptx.enum.text import MSO_VERTICAL_ANCHORfrom pptx.oxml import parse_xmlfrom pptx.oxml.dml.fill import CT_GradientFillPropertiesfrom pptx.oxml.ns import nsdeclsfrom pptx.oxml.simpletypes import ST_Coordinate, ST_Coordinate32, XsdBoolean, XsdIntfrom pptx.oxml.text import CT_TextBodyfrom pptx.oxml.xmlchemy import ( BaseOxmlElement, Choice, OneAndOnlyOne, OptionalAttribute, RequiredAttribute, ZeroOrMore, ZeroOrOne, ZeroOrOneChoice,)from pptx.util import Emu, lazyproperty
if TYPE_CHECKING: from pptx.util import Length
class CT_Table(BaseOxmlElement): """`a:tbl` custom element class"""
get_or_add_tblPr: Callable[[], CT_TableProperties] tr_lst: list[CT_TableRow] _add_tr: Callable[..., CT_TableRow]
_tag_seq = ("a:tblPr", "a:tblGrid", "a:tr") tblPr: CT_TableProperties | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] "a:tblPr", successors=_tag_seq[1:] ) tblGrid: CT_TableGrid = OneAndOnlyOne("a:tblGrid") # pyright: ignore[reportAssignmentType] tr = ZeroOrMore("a:tr", successors=_tag_seq[3:]) del _tag_seq
def add_tr(self, height: Length) -> CT_TableRow: """Return a newly created `a:tr` child element having its `h` attribute set to `height`.""" return self._add_tr(h=height)
@property def bandCol(self) -> bool: return self._get_boolean_property("bandCol")
@bandCol.setter def bandCol(self, value: bool): self._set_boolean_property("bandCol", value)
@property def bandRow(self) -> bool: return self._get_boolean_property("bandRow")
@bandRow.setter def bandRow(self, value: bool): self._set_boolean_property("bandRow", value)
@property def firstCol(self) -> bool: return self._get_boolean_property("firstCol")
@firstCol.setter def firstCol(self, value: bool): self._set_boolean_property("firstCol", value)
@property def firstRow(self) -> bool: return self._get_boolean_property("firstRow")
@firstRow.setter def firstRow(self, value: bool): self._set_boolean_property("firstRow", value)
def iter_tcs(self) -> Iterator[CT_TableCell]: """Generate each `a:tc` element in this tbl.
`a:tc` elements are generated left-to-right, top-to-bottom. """ return (tc for tr in self.tr_lst for tc in tr.tc_lst)
@property def lastCol(self) -> bool: return self._get_boolean_property("lastCol")
@lastCol.setter def lastCol(self, value: bool): self._set_boolean_property("lastCol", value)
@property def lastRow(self) -> bool: return self._get_boolean_property("lastRow")
@lastRow.setter def lastRow(self, value: bool): self._set_boolean_property("lastRow", value)
@classmethod def new_tbl( cls, rows: int, cols: int, width: int, height: int, tableStyleId: str | None = None ) -> CT_Table: """Return a new `p:tbl` element tree.""" # working hypothesis is this is the default table style GUID if tableStyleId is None: tableStyleId = "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}"
xml = cls._tbl_tmpl() % (tableStyleId) tbl = cast(CT_Table, parse_xml(xml))
# add specified number of rows and columns rowheight = height // rows colwidth = width // cols
for col in range(cols): # adjust width of last col to absorb any div error if col == cols - 1: colwidth = width - ((cols - 1) * colwidth) tbl.tblGrid.add_gridCol(width=Emu(colwidth))
for row in range(rows): # adjust height of last row to absorb any div error if row == rows - 1: rowheight = height - ((rows - 1) * rowheight) tr = tbl.add_tr(height=Emu(rowheight)) for col in range(cols): tr.add_tc()
return tbl
def tc(self, row_idx: int, col_idx: int) -> CT_TableCell: """Return `a:tc` element at `row_idx`, `col_idx`.""" return self.tr_lst[row_idx].tc_lst[col_idx]
def _get_boolean_property(self, propname: str) -> bool: """Generalized getter for the boolean properties on the `a:tblPr` child element.
Defaults to False if `propname` attribute is missing or `a:tblPr` element itself is not present. """ tblPr = self.tblPr if tblPr is None: return False propval = getattr(tblPr, propname) return {True: True, False: False, None: False}[propval]
def _set_boolean_property(self, propname: str, value: bool) -> None: """Generalized setter for boolean properties on the `a:tblPr` child element.
Sets `propname` attribute appropriately based on `value`. If `value` is True, the attribute is set to "1"; a tblPr child element is added if necessary. If `value` is False, the `propname` attribute is removed if present, allowing its default value of False to be its effective value. """ if value not in (True, False): raise ValueError("assigned value must be either True or False, got %s" % value) tblPr = self.get_or_add_tblPr() setattr(tblPr, propname, value)
@classmethod def _tbl_tmpl(cls): return ( "<a:tbl %s>\n" ' <a:tblPr firstRow="1" bandRow="1">\n' " <a:tableStyleId>%s</a:tableStyleId>\n" " </a:tblPr>\n" " <a:tblGrid/>\n" "</a:tbl>" % (nsdecls("a"), "%s") )
class CT_TableCell(BaseOxmlElement): """`a:tc` custom element class"""
get_or_add_tcPr: Callable[[], CT_TableCellProperties] get_or_add_txBody: Callable[[], CT_TextBody]
_tag_seq = ("a:txBody", "a:tcPr", "a:extLst") txBody: CT_TextBody | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] "a:txBody", successors=_tag_seq[1:] ) tcPr: CT_TableCellProperties | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] "a:tcPr", successors=_tag_seq[2:] ) del _tag_seq
gridSpan: int = OptionalAttribute( # pyright: ignore[reportAssignmentType] "gridSpan", XsdInt, default=1 ) rowSpan: int = OptionalAttribute( # pyright: ignore[reportAssignmentType] "rowSpan", XsdInt, default=1 ) hMerge: bool = OptionalAttribute( # pyright: ignore[reportAssignmentType] "hMerge", XsdBoolean, default=False ) vMerge: bool = OptionalAttribute( # pyright: ignore[reportAssignmentType] "vMerge", XsdBoolean, default=False )
@property def anchor(self) -> MSO_VERTICAL_ANCHOR | None: """String held in `anchor` attribute of `a:tcPr` child element of this `a:tc` element.""" if self.tcPr is None: return None return self.tcPr.anchor
@anchor.setter def anchor(self, anchor_enum_idx: MSO_VERTICAL_ANCHOR | None): """Set value of anchor attribute on `a:tcPr` child element.""" if anchor_enum_idx is None and self.tcPr is None: return tcPr = self.get_or_add_tcPr() tcPr.anchor = anchor_enum_idx
def append_ps_from(self, spanned_tc: CT_TableCell): """Append `a:p` elements taken from `spanned_tc`.
Any non-empty paragraph elements in `spanned_tc` are removed and appended to the text-frame of this cell. If `spanned_tc` is left with no content after this process, a single empty `a:p` element is added to ensure the cell is compliant with the spec. """ source_txBody = spanned_tc.get_or_add_txBody() target_txBody = self.get_or_add_txBody()
# ---if source is empty, there's nothing to do--- if source_txBody.is_empty: return
# ---a single empty paragraph in target is overwritten--- if target_txBody.is_empty: target_txBody.clear_content()
for p in source_txBody.p_lst: target_txBody.append(p)
# ---neither source nor target can be left without ps--- source_txBody.unclear_content() target_txBody.unclear_content()
@property def col_idx(self) -> int: """Offset of this cell's column in its table.""" # ---tc elements come before any others in `a:tr` element--- return cast(CT_TableRow, self.getparent()).index(self)
@property def is_merge_origin(self) -> bool: """True if cell is top-left in merged cell range.""" if self.gridSpan > 1 and not self.vMerge: return True return self.rowSpan > 1 and not self.hMerge
@property def is_spanned(self) -> bool: """True if cell is in merged cell range but not merge origin cell.""" return self.hMerge or self.vMerge
@property def marT(self) -> Length: """Top margin for this cell.
This value is stored in the `marT` attribute of the `a:tcPr` child element of this `a:tc`.
Read/write. If the attribute is not present, the default value `45720` (0.05 inches) is returned for top and bottom; `91440` (0.10 inches) is the default for left and right. Assigning |None| to any `marX` property clears that attribute from the element, effectively setting it to the default value. """ return self._get_marX("marT", Emu(45720))
@marT.setter def marT(self, value: Length | None): self._set_marX("marT", value)
@property def marR(self) -> Length: """Right margin value represented in `marR` attribute.""" return self._get_marX("marR", Emu(91440))
@marR.setter def marR(self, value: Length | None): self._set_marX("marR", value)
@property def marB(self) -> Length: """Bottom margin value represented in `marB` attribute.""" return self._get_marX("marB", Emu(45720))
@marB.setter def marB(self, value: Length | None): self._set_marX("marB", value)
@property def marL(self) -> Length: """Left margin value represented in `marL` attribute.""" return self._get_marX("marL", Emu(91440))
@marL.setter def marL(self, value: Length | None): self._set_marX("marL", value)
@classmethod def new(cls) -> CT_TableCell: """Return a new `a:tc` element subtree.""" return cast( CT_TableCell, parse_xml( f"<a:tc {nsdecls('a')}>\n" f" <a:txBody>\n" f" <a:bodyPr/>\n" f" <a:lstStyle/>\n" f" <a:p/>\n" f" </a:txBody>\n" f" <a:tcPr/>\n" f"</a:tc>" ), )
@property def row_idx(self) -> int: """Offset of this cell's row in its table.""" return cast(CT_TableRow, self.getparent()).row_idx
@property def tbl(self) -> CT_Table: """Table element this cell belongs to.""" return cast(CT_Table, self.xpath("ancestor::a:tbl")[0])
@property def text(self) -> str: # pyright: ignore[reportIncompatibleMethodOverride] """str text contained in cell""" # ---note this shadows lxml _Element.text--- txBody = self.txBody if txBody is None: return "" return "\n".join([p.text for p in txBody.p_lst])
def _get_marX(self, attr_name: str, default: Length) -> Length: """Generalized method to get margin values.""" if self.tcPr is None: return Emu(default) return Emu(int(self.tcPr.get(attr_name, default)))
def _new_txBody(self) -> CT_TextBody: return CT_TextBody.new_a_txBody()
def _set_marX(self, marX: str, value: Length | None) -> None: """Set value of marX attribute on `a:tcPr` child element.
If `marX` is |None|, the marX attribute is removed. `marX` is a string, one of `('marL', 'marR', 'marT', 'marB')`. """ if value is None and self.tcPr is None: return tcPr = self.get_or_add_tcPr() setattr(tcPr, marX, value)
class CT_TableCellProperties(BaseOxmlElement): """`a:tcPr` custom element class"""
eg_fillProperties = ZeroOrOneChoice( ( Choice("a:noFill"), Choice("a:solidFill"), Choice("a:gradFill"), Choice("a:blipFill"), Choice("a:pattFill"), Choice("a:grpFill"), ), successors=("a:headers", "a:extLst"), ) anchor: MSO_VERTICAL_ANCHOR | None = OptionalAttribute( # pyright: ignore[reportAssignmentType] "anchor", MSO_VERTICAL_ANCHOR ) marL: Length | None = OptionalAttribute( # pyright: ignore[reportAssignmentType] "marL", ST_Coordinate32 ) marR: Length | None = OptionalAttribute( # pyright: ignore[reportAssignmentType] "marR", ST_Coordinate32 ) marT: Length | None = OptionalAttribute( # pyright: ignore[reportAssignmentType] "marT", ST_Coordinate32 ) marB: Length | None = OptionalAttribute( # pyright: ignore[reportAssignmentType] "marB", ST_Coordinate32 )
def _new_gradFill(self): return CT_GradientFillProperties.new_gradFill()
class CT_TableCol(BaseOxmlElement): """`a:gridCol` custom element class."""
w: Length = RequiredAttribute("w", ST_Coordinate) # pyright: ignore[reportAssignmentType]
class CT_TableGrid(BaseOxmlElement): """`a:tblGrid` custom element class."""
gridCol_lst: list[CT_TableCol] _add_gridCol: Callable[..., CT_TableCol]
gridCol = ZeroOrMore("a:gridCol")
def add_gridCol(self, width: Length) -> CT_TableCol: """A newly appended `a:gridCol` child element having its `w` attribute set to `width`.""" return self._add_gridCol(w=width)
class CT_TableProperties(BaseOxmlElement): """`a:tblPr` custom element class."""
bandRow = OptionalAttribute("bandRow", XsdBoolean, default=False) bandCol = OptionalAttribute("bandCol", XsdBoolean, default=False) firstRow = OptionalAttribute("firstRow", XsdBoolean, default=False) firstCol = OptionalAttribute("firstCol", XsdBoolean, default=False) lastRow = OptionalAttribute("lastRow", XsdBoolean, default=False) lastCol = OptionalAttribute("lastCol", XsdBoolean, default=False)
class CT_TableRow(BaseOxmlElement): """`a:tr` custom element class."""
tc_lst: list[CT_TableCell] _add_tc: Callable[[], CT_TableCell]
tc = ZeroOrMore("a:tc", successors=("a:extLst",)) h: Length = RequiredAttribute("h", ST_Coordinate) # pyright: ignore[reportAssignmentType]
def add_tc(self) -> CT_TableCell: """A newly added minimal valid `a:tc` child element.""" return self._add_tc()
@property def row_idx(self) -> int: """Offset of this row in its table.""" return cast(CT_Table, self.getparent()).tr_lst.index(self)
def _new_tc(self): return CT_TableCell.new()
class TcRange(object): """A 2D block of `a:tc` cell elements in a table.
This object assumes the structure of the underlying table does not change during its lifetime. Structural changes in this context would be insertion or removal of rows or columns.
The client is expected to create, use, and then abandon an instance in the context of a single user operation that is known to have no structural side-effects of this type. """
def __init__(self, tc: CT_TableCell, other_tc: CT_TableCell): self._tc = tc self._other_tc = other_tc
@classmethod def from_merge_origin(cls, tc: CT_TableCell): """Return instance created from merge-origin tc element.""" other_tc = tc.tbl.tc( tc.row_idx + tc.rowSpan - 1, # ---other_row_idx tc.col_idx + tc.gridSpan - 1, # ---other_col_idx ) return cls(tc, other_tc)
@lazyproperty def contains_merged_cell(self) -> bool: """True if one or more cells in range are part of a merged cell.""" for tc in self.iter_tcs(): if tc.gridSpan > 1: return True if tc.rowSpan > 1: return True if tc.hMerge: return True if tc.vMerge: return True return False
@lazyproperty def dimensions(self) -> tuple[int, int]: """(row_count, col_count) pair describing size of range.""" _, _, width, height = self._extents return height, width
@lazyproperty def in_same_table(self): """True if both cells provided to constructor are in same table.""" if self._tc.tbl is self._other_tc.tbl: return True return False
def iter_except_left_col_tcs(self): """Generate each `a:tc` element not in leftmost column of range.""" for tr in self._tbl.tr_lst[self._top : self._bottom]: for tc in tr.tc_lst[self._left + 1 : self._right]: yield tc
def iter_except_top_row_tcs(self): """Generate each `a:tc` element in non-first rows of range.""" for tr in self._tbl.tr_lst[self._top + 1 : self._bottom]: for tc in tr.tc_lst[self._left : self._right]: yield tc
def iter_left_col_tcs(self): """Generate each `a:tc` element in leftmost column of range.""" col_idx = self._left for tr in self._tbl.tr_lst[self._top : self._bottom]: yield tr.tc_lst[col_idx]
def iter_tcs(self): """Generate each `a:tc` element in this range.
Cell elements are generated left-to-right, top-to-bottom. """ return ( tc for tr in self._tbl.tr_lst[self._top : self._bottom] for tc in tr.tc_lst[self._left : self._right] )
def iter_top_row_tcs(self): """Generate each `a:tc` element in topmost row of range.""" tr = self._tbl.tr_lst[self._top] for tc in tr.tc_lst[self._left : self._right]: yield tc
def move_content_to_origin(self): """Move all paragraphs in range to origin cell.""" tcs = list(self.iter_tcs()) origin_tc = tcs[0] for spanned_tc in tcs[1:]: origin_tc.append_ps_from(spanned_tc)
@lazyproperty def _bottom(self): """Index of row following last row of range""" _, top, _, height = self._extents return top + height
@lazyproperty def _extents(self) -> tuple[int, int, int, int]: """A (left, top, width, height) tuple describing range extents.
Note this is normalized to accommodate the various orderings of the corner cells provided on construction, which may be in any of four configurations such as (top-left, bottom-right), (bottom-left, top-right), etc. """
def start_and_size(idx: int, other_idx: int) -> tuple[int, int]: """Return beginning and length of range based on two indexes.""" return min(idx, other_idx), abs(idx - other_idx) + 1
tc, other_tc = self._tc, self._other_tc
left, width = start_and_size(tc.col_idx, other_tc.col_idx) top, height = start_and_size(tc.row_idx, other_tc.row_idx)
return left, top, width, height
@lazyproperty def _left(self): """Index of leftmost column in range.""" left, _, _, _ = self._extents return left
@lazyproperty def _right(self): """Index of column following the last column in range.""" left, _, width, _ = self._extents return left + width
@lazyproperty def _tbl(self): """`a:tbl` element containing this cell range.""" return self._tc.tbl
@lazyproperty def _top(self): """Index of topmost row in range.""" _, top, _, _ = self._extents return top123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618"""Custom element classes for text-related XML elements"""
from __future__ import annotations
import refrom typing import TYPE_CHECKING, Callable, cast
from pptx.enum.lang import MSO_LANGUAGE_IDfrom pptx.enum.text import ( MSO_AUTO_SIZE, MSO_TEXT_UNDERLINE_TYPE, MSO_VERTICAL_ANCHOR, PP_PARAGRAPH_ALIGNMENT,)from pptx.exc import InvalidXmlErrorfrom pptx.oxml import parse_xmlfrom pptx.oxml.dml.fill import CT_GradientFillPropertiesfrom pptx.oxml.ns import nsdeclsfrom pptx.oxml.simpletypes import ( ST_Coordinate32, ST_TextFontScalePercentOrPercentString, ST_TextFontSize, ST_TextIndentLevelType, ST_TextSpacingPercentOrPercentString, ST_TextSpacingPoint, ST_TextTypeface, ST_TextWrappingType, XsdBoolean,)from pptx.oxml.xmlchemy import ( BaseOxmlElement, Choice, OneAndOnlyOne, OneOrMore, OptionalAttribute, RequiredAttribute, ZeroOrMore, ZeroOrOne, ZeroOrOneChoice,)from pptx.util import Emu, Length
if TYPE_CHECKING: from pptx.oxml.action import CT_Hyperlink
class CT_RegularTextRun(BaseOxmlElement): """`a:r` custom element class"""
get_or_add_rPr: Callable[[], CT_TextCharacterProperties]
rPr: CT_TextCharacterProperties | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] "a:rPr", successors=("a:t",) ) t: BaseOxmlElement = OneAndOnlyOne("a:t") # pyright: ignore[reportAssignmentType]
@property def text(self) -> str: """All text of (required) `a:t` child.""" text = self.t.text # -- t.text is None when t element is empty, e.g. '<a:t/>' -- return text or ""
@text.setter def text(self, value: str): # pyright: ignore[reportIncompatibleMethodOverride] self.t.text = self._escape_ctrl_chars(value)
@staticmethod def _escape_ctrl_chars(s: str) -> str: """Return str after replacing each control character with a plain-text escape.
For example, a BEL character (x07) would appear as "_x0007_". Horizontal-tab (x09) and line-feed (x0A) are not escaped. All other characters in the range x00-x1F are escaped. """ return re.sub(r"([\x00-\x08\x0B-\x1F])", lambda match: "_x%04X_" % ord(match.group(1)), s)
class CT_TextBody(BaseOxmlElement): """`p:txBody` custom element class.
Also used for `c:txPr` in charts and perhaps other elements. """
add_p: Callable[[], CT_TextParagraph] p_lst: list[CT_TextParagraph]
bodyPr: CT_TextBodyProperties = OneAndOnlyOne( # pyright: ignore[reportAssignmentType] "a:bodyPr" ) p: CT_TextParagraph = OneOrMore("a:p") # pyright: ignore[reportAssignmentType]
def clear_content(self): """Remove all `a:p` children, but leave any others.
cf. lxml `_Element.clear()` method which removes all children. """ for p in self.p_lst: self.remove(p)
@property def defRPr(self) -> CT_TextCharacterProperties: """`a:defRPr` element of required first `p` child, added with its ancestors if not present.
Used when element is a ``c:txPr`` in a chart and the `p` element is used only to specify formatting, not content. """ p = self.p_lst[0] pPr = p.get_or_add_pPr() defRPr = pPr.get_or_add_defRPr() return defRPr
@property def is_empty(self) -> bool: """True if only a single empty `a:p` element is present.""" ps = self.p_lst if len(ps) > 1: return False
if not ps: raise InvalidXmlError("p:txBody must have at least one a:p")
if ps[0].text != "": return False return True
@classmethod def new(cls): """Return a new `p:txBody` element tree.""" xml = cls._txBody_tmpl() txBody = parse_xml(xml) return txBody
@classmethod def new_a_txBody(cls) -> CT_TextBody: """Return a new `a:txBody` element tree.
Suitable for use in a table cell and possibly other situations. """ xml = cls._a_txBody_tmpl() txBody = cast(CT_TextBody, parse_xml(xml)) return txBody
@classmethod def new_p_txBody(cls): """Return a new `p:txBody` element tree, suitable for use in an `p:sp` element.""" xml = cls._p_txBody_tmpl() return parse_xml(xml)
@classmethod def new_txPr(cls): """Return a `c:txPr` element tree.
Suitable for use in a chart object like data labels or tick labels. """ xml = ( "<c:txPr %s>\n" " <a:bodyPr/>\n" " <a:lstStyle/>\n" " <a:p>\n" " <a:pPr>\n" " <a:defRPr/>\n" " </a:pPr>\n" " </a:p>\n" "</c:txPr>\n" ) % nsdecls("c", "a") txPr = parse_xml(xml) return txPr
def unclear_content(self): """Ensure p:txBody has at least one a:p child.
Intuitively, reverse a ".clear_content()" operation to minimum conformance with spec (single empty paragraph). """ if len(self.p_lst) > 0: return self.add_p()
@classmethod def _a_txBody_tmpl(cls): return "<a:txBody %s>\n" " <a:bodyPr/>\n" " <a:p/>\n" "</a:txBody>\n" % (nsdecls("a"))
@classmethod def _p_txBody_tmpl(cls): return ( "<p:txBody %s>\n" " <a:bodyPr/>\n" " <a:p/>\n" "</p:txBody>\n" % (nsdecls("p", "a")) )
@classmethod def _txBody_tmpl(cls): return ( "<p:txBody %s>\n" " <a:bodyPr/>\n" " <a:lstStyle/>\n" " <a:p/>\n" "</p:txBody>\n" % (nsdecls("a", "p")) )
class CT_TextBodyProperties(BaseOxmlElement): """`a:bodyPr` custom element class."""
_add_noAutofit: Callable[[], BaseOxmlElement] _add_normAutofit: Callable[[], CT_TextNormalAutofit] _add_spAutoFit: Callable[[], BaseOxmlElement] _remove_eg_textAutoFit: Callable[[], None]
noAutofit: BaseOxmlElement | None normAutofit: CT_TextNormalAutofit | None spAutoFit: BaseOxmlElement | None
eg_textAutoFit = ZeroOrOneChoice( (Choice("a:noAutofit"), Choice("a:normAutofit"), Choice("a:spAutoFit")), successors=("a:scene3d", "a:sp3d", "a:flatTx", "a:extLst"), ) lIns: Length = OptionalAttribute( # pyright: ignore[reportAssignmentType] "lIns", ST_Coordinate32, default=Emu(91440) ) tIns: Length = OptionalAttribute( # pyright: ignore[reportAssignmentType] "tIns", ST_Coordinate32, default=Emu(45720) ) rIns: Length = OptionalAttribute( # pyright: ignore[reportAssignmentType] "rIns", ST_Coordinate32, default=Emu(91440) ) bIns: Length = OptionalAttribute( # pyright: ignore[reportAssignmentType] "bIns", ST_Coordinate32, default=Emu(45720) ) anchor: MSO_VERTICAL_ANCHOR | None = OptionalAttribute( # pyright: ignore[reportAssignmentType] "anchor", MSO_VERTICAL_ANCHOR ) wrap: str | None = OptionalAttribute( # pyright: ignore[reportAssignmentType] "wrap", ST_TextWrappingType )
@property def autofit(self): """The autofit setting for the text frame, a member of the `MSO_AUTO_SIZE` enumeration.""" if self.noAutofit is not None: return MSO_AUTO_SIZE.NONE if self.normAutofit is not None: return MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE if self.spAutoFit is not None: return MSO_AUTO_SIZE.SHAPE_TO_FIT_TEXT return None
@autofit.setter def autofit(self, value: MSO_AUTO_SIZE | None): if value is not None and value not in MSO_AUTO_SIZE: raise ValueError( f"only None or a member of the MSO_AUTO_SIZE enumeration can be assigned to" f" CT_TextBodyProperties.autofit, got {value}" ) self._remove_eg_textAutoFit() if value == MSO_AUTO_SIZE.NONE: self._add_noAutofit() elif value == MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE: self._add_normAutofit() elif value == MSO_AUTO_SIZE.SHAPE_TO_FIT_TEXT: self._add_spAutoFit()
class CT_TextCharacterProperties(BaseOxmlElement): """Custom element class for `a:rPr`, `a:defRPr`, and `a:endParaRPr`.
'rPr' is short for 'run properties', and it corresponds to the |Font| proxy class. """
get_or_add_hlinkClick: Callable[[], CT_Hyperlink] get_or_add_latin: Callable[[], CT_TextFont] _remove_latin: Callable[[], None] _remove_hlinkClick: Callable[[], None]
eg_fillProperties = ZeroOrOneChoice( ( Choice("a:noFill"), Choice("a:solidFill"), Choice("a:gradFill"), Choice("a:blipFill"), Choice("a:pattFill"), Choice("a:grpFill"), ), successors=( "a:effectLst", "a:effectDag", "a:highlight", "a:uLnTx", "a:uLn", "a:uFillTx", "a:uFill", "a:latin", "a:ea", "a:cs", "a:sym", "a:hlinkClick", "a:hlinkMouseOver", "a:rtl", "a:extLst", ), ) latin: CT_TextFont | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] "a:latin", successors=( "a:ea", "a:cs", "a:sym", "a:hlinkClick", "a:hlinkMouseOver", "a:rtl", "a:extLst", ), ) hlinkClick: CT_Hyperlink | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] "a:hlinkClick", successors=("a:hlinkMouseOver", "a:rtl", "a:extLst") )
lang: MSO_LANGUAGE_ID | None = OptionalAttribute( # pyright: ignore[reportAssignmentType] "lang", MSO_LANGUAGE_ID ) sz: int | None = OptionalAttribute( # pyright: ignore[reportAssignmentType] "sz", ST_TextFontSize ) b: bool | None = OptionalAttribute("b", XsdBoolean) # pyright: ignore[reportAssignmentType] i: bool | None = OptionalAttribute("i", XsdBoolean) # pyright: ignore[reportAssignmentType] u: MSO_TEXT_UNDERLINE_TYPE | None = OptionalAttribute( # pyright: ignore[reportAssignmentType] "u", MSO_TEXT_UNDERLINE_TYPE )
def _new_gradFill(self): return CT_GradientFillProperties.new_gradFill()
def add_hlinkClick(self, rId: str) -> CT_Hyperlink: """Add an `a:hlinkClick` child element with r:id attribute set to `rId`.""" hlinkClick = self.get_or_add_hlinkClick() hlinkClick.rId = rId return hlinkClick
class CT_TextField(BaseOxmlElement): """`a:fld` field element, for either a slide number or date field."""
get_or_add_rPr: Callable[[], CT_TextCharacterProperties]
rPr: CT_TextCharacterProperties | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] "a:rPr", successors=("a:pPr", "a:t") ) t: BaseOxmlElement | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] "a:t", successors=() )
@property def text(self) -> str: # pyright: ignore[reportIncompatibleMethodOverride] """The text of the `a:t` child element.""" t = self.t if t is None: return "" return t.text or ""
class CT_TextFont(BaseOxmlElement): """Custom element class for `a:latin`, `a:ea`, `a:cs`, and `a:sym`.
These occur as child elements of CT_TextCharacterProperties, e.g. `a:rPr`. """
typeface: str = RequiredAttribute( # pyright: ignore[reportAssignmentType] "typeface", ST_TextTypeface )
class CT_TextLineBreak(BaseOxmlElement): """`a:br` line break element"""
get_or_add_rPr: Callable[[], CT_TextCharacterProperties]
rPr = ZeroOrOne("a:rPr", successors=())
@property def text(self): # pyright: ignore[reportIncompatibleMethodOverride] """Unconditionally a single vertical-tab character.
A line break element can contain no text other than the implicit line feed it represents. """ return "\v"
class CT_TextNormalAutofit(BaseOxmlElement): """`a:normAutofit` element specifying fit text to shape font reduction, etc."""
fontScale = OptionalAttribute( "fontScale", ST_TextFontScalePercentOrPercentString, default=100.0 )
class CT_TextParagraph(BaseOxmlElement): """`a:p` custom element class"""
get_or_add_endParaRPr: Callable[[], CT_TextCharacterProperties] get_or_add_pPr: Callable[[], CT_TextParagraphProperties] r_lst: list[CT_RegularTextRun] _add_br: Callable[[], CT_TextLineBreak] _add_r: Callable[[], CT_RegularTextRun]
pPr: CT_TextParagraphProperties | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] "a:pPr", successors=("a:r", "a:br", "a:fld", "a:endParaRPr") ) r = ZeroOrMore("a:r", successors=("a:endParaRPr",)) br = ZeroOrMore("a:br", successors=("a:endParaRPr",)) endParaRPr: CT_TextCharacterProperties | None = ZeroOrOne( "a:endParaRPr", successors=() ) # pyright: ignore[reportAssignmentType]
def add_br(self) -> CT_TextLineBreak: """Return a newly appended `a:br` element.""" return self._add_br()
def add_r(self, text: str | None = None) -> CT_RegularTextRun: """Return a newly appended `a:r` element.""" r = self._add_r() if text: r.text = text return r
def append_text(self, text: str): """Append `a:r` and `a:br` elements to `p` based on `text`.
Any `\n` or `\v` (vertical-tab) characters in `text` delimit `a:r` (run) elements and themselves are translated to `a:br` (line-break) elements. The vertical-tab character appears in clipboard text from PowerPoint at "soft" line-breaks (new-line, but not new paragraph). """ for idx, r_str in enumerate(re.split("\n|\v", text)): # ---breaks are only added _between_ items, not at start--- if idx > 0: self.add_br() # ---runs that would be empty are not added--- if r_str: self.add_r(r_str)
@property def content_children(self) -> tuple[CT_RegularTextRun | CT_TextLineBreak | CT_TextField, ...]: """Sequence containing text-container child elements of this `a:p` element.
These include `a:r`, `a:br`, and `a:fld`. """ return tuple( e for e in self if isinstance(e, (CT_RegularTextRun, CT_TextLineBreak, CT_TextField)) )
@property def text(self) -> str: # pyright: ignore[reportIncompatibleMethodOverride] """str text contained in this paragraph.""" # ---note this shadows the lxml _Element.text--- return "".join([child.text for child in self.content_children])
def _new_r(self): r_xml = "<a:r %s><a:t/></a:r>" % nsdecls("a") return parse_xml(r_xml)
class CT_TextParagraphProperties(BaseOxmlElement): """`a:pPr` custom element class."""
get_or_add_defRPr: Callable[[], CT_TextCharacterProperties] _add_lnSpc: Callable[[], CT_TextSpacing] _add_spcAft: Callable[[], CT_TextSpacing] _add_spcBef: Callable[[], CT_TextSpacing] _remove_lnSpc: Callable[[], None] _remove_spcAft: Callable[[], None] _remove_spcBef: Callable[[], None]
_tag_seq = ( "a:lnSpc", "a:spcBef", "a:spcAft", "a:buClrTx", "a:buClr", "a:buSzTx", "a:buSzPct", "a:buSzPts", "a:buFontTx", "a:buFont", "a:buNone", "a:buAutoNum", "a:buChar", "a:buBlip", "a:tabLst", "a:defRPr", "a:extLst", ) lnSpc: CT_TextSpacing | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] "a:lnSpc", successors=_tag_seq[1:] ) spcBef: CT_TextSpacing | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] "a:spcBef", successors=_tag_seq[2:] ) spcAft: CT_TextSpacing | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] "a:spcAft", successors=_tag_seq[3:] ) defRPr: CT_TextCharacterProperties | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] "a:defRPr", successors=_tag_seq[16:] ) lvl: int = OptionalAttribute( # pyright: ignore[reportAssignmentType] "lvl", ST_TextIndentLevelType, default=0 ) algn: PP_PARAGRAPH_ALIGNMENT | None = OptionalAttribute( "algn", PP_PARAGRAPH_ALIGNMENT ) # pyright: ignore[reportAssignmentType] del _tag_seq
@property def line_spacing(self) -> float | Length | None: """The spacing between baselines of successive lines in this paragraph.
A float value indicates a number of lines. A |Length| value indicates a fixed spacing. Value is contained in `./a:lnSpc/a:spcPts/@val` or `./a:lnSpc/a:spcPct/@val`. Value is |None| if no element is present. """ lnSpc = self.lnSpc if lnSpc is None: return None if lnSpc.spcPts is not None: return lnSpc.spcPts.val return cast(CT_TextSpacingPercent, lnSpc.spcPct).val
@line_spacing.setter def line_spacing(self, value: float | Length | None): self._remove_lnSpc() if value is None: return if isinstance(value, Length): self._add_lnSpc().set_spcPts(value) else: self._add_lnSpc().set_spcPct(value)
@property def space_after(self) -> Length | None: """The EMU equivalent of the centipoints value in `./a:spcAft/a:spcPts/@val`.""" spcAft = self.spcAft if spcAft is None: return None spcPts = spcAft.spcPts if spcPts is None: return None return spcPts.val
@space_after.setter def space_after(self, value: Length | None): self._remove_spcAft() if value is not None: self._add_spcAft().set_spcPts(value)
@property def space_before(self): """The EMU equivalent of the centipoints value in `./a:spcBef/a:spcPts/@val`.""" spcBef = self.spcBef if spcBef is None: return None spcPts = spcBef.spcPts if spcPts is None: return None return spcPts.val
@space_before.setter def space_before(self, value: Length | None): self._remove_spcBef() if value is not None: self._add_spcBef().set_spcPts(value)
class CT_TextSpacing(BaseOxmlElement): """Used for `a:lnSpc`, `a:spcBef`, and `a:spcAft` elements."""
get_or_add_spcPct: Callable[[], CT_TextSpacingPercent] get_or_add_spcPts: Callable[[], CT_TextSpacingPoint] _remove_spcPct: Callable[[], None] _remove_spcPts: Callable[[], None]
# this should actually be a OneAndOnlyOneChoice, but that's not # implemented yet. spcPct: CT_TextSpacingPercent | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] "a:spcPct" ) spcPts: CT_TextSpacingPoint | None = ZeroOrOne( # pyright: ignore[reportAssignmentType] "a:spcPts" )
def set_spcPct(self, value: float): """Set spacing to `value` lines, e.g. 1.75 lines.
A ./a:spcPts child is removed if present. """ self._remove_spcPts() spcPct = self.get_or_add_spcPct() spcPct.val = value
def set_spcPts(self, value: Length): """Set spacing to `value` points. A ./a:spcPct child is removed if present.""" self._remove_spcPct() spcPts = self.get_or_add_spcPts() spcPts.val = value
class CT_TextSpacingPercent(BaseOxmlElement): """`a:spcPct` element, specifying spacing in thousandths of a percent in its `val` attribute."""
val: float = RequiredAttribute( # pyright: ignore[reportAssignmentType] "val", ST_TextSpacingPercentOrPercentString )
class CT_TextSpacingPoint(BaseOxmlElement): """`a:spcPts` element, specifying spacing in centipoints in its `val` attribute."""
val: Length = RequiredAttribute( # pyright: ignore[reportAssignmentType] "val", ST_TextSpacingPoint )1234567891011121314151617181920212223242526272829"""lxml custom element classes for theme-related XML elements."""
from __future__ import annotations
from . import parse_from_templatefrom .xmlchemy import BaseOxmlElement
class CT_OfficeStyleSheet(BaseOxmlElement): """ ``<a:theme>`` element, root of a theme part """
_tag_seq = ( "a:themeElements", "a:objectDefaults", "a:extraClrSchemeLst", "a:custClrLst", "a:extLst", ) del _tag_seq
@classmethod def new_default(cls): """ Return a new ``<a:theme>`` element containing default settings suitable for use with a notes master. """ return parse_from_template("theme")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717"""Base and meta classes enabling declarative definition of custom element classes."""
from __future__ import annotations
import refrom typing import Any, Callable, Iterable, Protocol, Sequence, Type, cast
from lxml import etreefrom lxml.etree import ElementBase, _Element # pyright: ignore[reportPrivateUsage]
from pptx.exc import InvalidXmlErrorfrom pptx.oxml import oxml_parserfrom pptx.oxml.ns import NamespacePrefixedTag, _nsmap, qn # pyright: ignore[reportPrivateUsage]from pptx.util import lazyproperty
class AttributeType(Protocol): """Interface for an object that can act as an attribute type.
An attribute-type specifies how values are transformed to and from the XML "string" value of the attribute. """
@classmethod def from_xml(cls, xml_value: str) -> Any: """Transform an attribute value to a Python value.""" ...
@classmethod def to_xml(cls, value: Any) -> str: """Transform a Python value to a str value suitable to this XML attribute.""" ...
def OxmlElement(nsptag_str: str, nsmap: dict[str, str] | None = None) -> BaseOxmlElement: """Return a "loose" lxml element having the tag specified by `nsptag_str`.
`nsptag_str` must contain the standard namespace prefix, e.g. 'a:tbl'. The resulting element is an instance of the custom element class for this tag name if one is defined. """ nsptag = NamespacePrefixedTag(nsptag_str) nsmap = nsmap if nsmap is not None else nsptag.nsmap return oxml_parser.makeelement(nsptag.clark_name, nsmap=nsmap)
def serialize_for_reading(element: ElementBase): """ Serialize *element* to human-readable XML suitable for tests. No XML declaration. """ xml = etree.tostring(element, encoding="unicode", pretty_print=True) return XmlString(xml)
class XmlString(str): """Provides string comparison override suitable for serialized XML; useful for tests."""
# ' <w:xyz xmlns:a="http://ns/decl/a" attr_name="val">text</w:xyz>' # | | || | # +----------+------------------------------------------++-----------+ # front attrs | text # close
_xml_elm_line_patt = re.compile(r"( *</?[\w:]+)(.*?)(/?>)([^<]*</[\w:]+>)?")
def __eq__(self, other: object) -> bool: if not isinstance(other, str): return False lines = self.splitlines() lines_other = other.splitlines() if len(lines) != len(lines_other): return False for line, line_other in zip(lines, lines_other): if not self._eq_elm_strs(line, line_other): return False return True
def __ne__(self, other: object) -> bool: return not self.__eq__(other)
def _attr_seq(self, attrs: str) -> list[str]: """Return a sequence of attribute strings parsed from *attrs*.
Each attribute string is stripped of whitespace on both ends. """ attrs = attrs.strip() attr_lst = attrs.split() return sorted(attr_lst)
def _eq_elm_strs(self, line: str, line_2: str) -> bool: """True if the element in `line_2` is XML-equivalent to the element in `line`.
In particular, the order of attributes in XML is not significant. """ front, attrs, close, text = self._parse_line(line) front_2, attrs_2, close_2, text_2 = self._parse_line(line_2) if front != front_2: return False if self._attr_seq(attrs) != self._attr_seq(attrs_2): return False if close != close_2: return False if text != text_2: return False return True
def _parse_line(self, line: str): """Return front, attrs, close, text 4-tuple result of parsing XML element string `line`.""" match = self._xml_elm_line_patt.match(line) if match is None: raise ValueError("`line` does not match pattern for an XML element") front, attrs, close, text = [match.group(n) for n in range(1, 5)] return front, attrs, close, text
class MetaOxmlElement(type): """Metaclass for BaseOxmlElement."""
def __init__(cls, clsname: str, bases: tuple[type, ...], clsdict: dict[str, Any]): dispatchable = ( OneAndOnlyOne, OneOrMore, OptionalAttribute, RequiredAttribute, ZeroOrMore, ZeroOrOne, ZeroOrOneChoice, ) for key, value in clsdict.items(): if isinstance(value, dispatchable): value.populate_class_members(cls, key)
class BaseAttribute: """Base class for OptionalAttribute and RequiredAttribute, providing common methods."""
def __init__(self, attr_name: str, simple_type: type[AttributeType]): self._attr_name = attr_name self._simple_type = simple_type
def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str): """ Add the appropriate methods to *element_cls*. """ self._element_cls = element_cls self._prop_name = prop_name
self._add_attr_property()
def _add_attr_property(self): """Add a read/write `{prop_name}` property to the element class.
The property returns the interpreted value of this attribute on access and changes the attribute value to its ST_* counterpart on assignment. """ property_ = property(self._getter, self._setter, None) # assign unconditionally to overwrite element name definition setattr(self._element_cls, self._prop_name, property_)
@property def _clark_name(self): if ":" in self._attr_name: return qn(self._attr_name) return self._attr_name
@property def _getter(self) -> Callable[[BaseOxmlElement], Any]: """Callable suitable for the "get" side of the attribute property descriptor.""" raise NotImplementedError("must be implemented by each subclass")
@property def _setter(self) -> Callable[[BaseOxmlElement, Any], None]: """Callable suitable for the "set" side of the attribute property descriptor.""" raise NotImplementedError("must be implemented by each subclass")
class OptionalAttribute(BaseAttribute): """Defines an optional attribute on a custom element class.
An optional attribute returns a default value when not present for reading. When assigned |None|, the attribute is removed. """
def __init__(self, attr_name: str, simple_type: type[AttributeType], default: Any = None): super(OptionalAttribute, self).__init__(attr_name, simple_type) self._default = default
@property def _docstring(self): """ Return the string to use as the ``__doc__`` attribute of the property for this attribute. """ return ( "%s type-converted value of ``%s`` attribute, or |None| (or spec" "ified default value) if not present. Assigning the default valu" "e causes the attribute to be removed from the element." % (self._simple_type.__name__, self._attr_name) )
@property def _getter(self) -> Callable[[BaseOxmlElement], Any]: """Callable suitable for the "get" side of the attribute property descriptor."""
def get_attr_value(obj: BaseOxmlElement) -> Any: attr_str_value = obj.get(self._clark_name) if attr_str_value is None: return self._default return self._simple_type.from_xml(attr_str_value)
get_attr_value.__doc__ = self._docstring return get_attr_value
@property def _setter(self) -> Callable[[BaseOxmlElement, Any], None]: """Callable suitable for the "set" side of the attribute property descriptor."""
def set_attr_value(obj: BaseOxmlElement, value: Any) -> None: # -- when an XML attribute has a default value, setting it to that default removes the # -- attribute from the element (when it is present) if value == self._default: if self._clark_name in obj.attrib: del obj.attrib[self._clark_name] return str_value = self._simple_type.to_xml(value) obj.set(self._clark_name, str_value)
return set_attr_value
class RequiredAttribute(BaseAttribute): """Defines a required attribute on a custom element class.
A required attribute is assumed to be present for reading, so does not have a default value; its actual value is always used. If missing on read, an |InvalidXmlError| is raised. It also does not remove the attribute if |None| is assigned. Assigning |None| raises |TypeError| or |ValueError|, depending on the simple type of the attribute. """
@property def _getter(self) -> Callable[[BaseOxmlElement], Any]: """Callable suitable for the "get" side of the attribute property descriptor."""
def get_attr_value(obj: BaseOxmlElement) -> Any: attr_str_value = obj.get(self._clark_name) if attr_str_value is None: raise InvalidXmlError( "required '%s' attribute not present on element %s" % (self._attr_name, obj.tag) ) return self._simple_type.from_xml(attr_str_value)
get_attr_value.__doc__ = self._docstring return get_attr_value
@property def _docstring(self): """ Return the string to use as the ``__doc__`` attribute of the property for this attribute. """ return "%s type-converted value of ``%s`` attribute." % ( self._simple_type.__name__, self._attr_name, )
@property def _setter(self) -> Callable[[BaseOxmlElement, Any], None]: """Callable suitable for the "set" side of the attribute property descriptor."""
def set_attr_value(obj: BaseOxmlElement, value: Any) -> None: str_value = self._simple_type.to_xml(value) obj.set(self._clark_name, str_value)
return set_attr_value
class _BaseChildElement: """Base class for the child element classes corresponding to varying cardinalities.
Subclasses include ZeroOrOne and ZeroOrMore. """
def __init__(self, nsptagname: str, successors: Sequence[str] = ()): super(_BaseChildElement, self).__init__() self._nsptagname = nsptagname self._successors = successors
def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str): """Baseline behavior for adding the appropriate methods to `element_cls`.""" self._element_cls = element_cls self._prop_name = prop_name
def _add_adder(self): """Add an ``_add_x()`` method to the element class for this child element."""
def _add_child(obj: BaseOxmlElement, **attrs: Any): new_method = getattr(obj, self._new_method_name) child = new_method() for key, value in attrs.items(): setattr(child, key, value) insert_method = getattr(obj, self._insert_method_name) insert_method(child) return child
_add_child.__doc__ = ( "Add a new ``<%s>`` child element unconditionally, inserted in t" "he correct sequence." % self._nsptagname ) self._add_to_class(self._add_method_name, _add_child)
def _add_creator(self): """Add a `_new_{prop_name}()` method to the element class.
This method creates a new, empty element of the correct type, having no attributes. """ creator = self._creator creator.__doc__ = ( 'Return a "loose", newly created ``<%s>`` element having no attri' "butes, text, or children." % self._nsptagname ) self._add_to_class(self._new_method_name, creator)
def _add_getter(self): """Add a read-only `{prop_name}` property to the parent element class.
The property locates and returns this child element or `None` if not present. """ property_ = property(self._getter, None, None) # assign unconditionally to overwrite element name definition setattr(self._element_cls, self._prop_name, property_)
def _add_inserter(self): """Add an ``_insert_x()`` method to the element class for this child element."""
def _insert_child(obj: BaseOxmlElement, child: BaseOxmlElement): obj.insert_element_before(child, *self._successors) return child
_insert_child.__doc__ = ( "Return the passed ``<%s>`` element after inserting it as a chil" "d in the correct sequence." % self._nsptagname ) self._add_to_class(self._insert_method_name, _insert_child)
def _add_list_getter(self): """ Add a read-only ``{prop_name}_lst`` property to the element class to retrieve a list of child elements matching this type. """ prop_name = f"{self._prop_name}_lst" property_ = property(self._list_getter, None, None) setattr(self._element_cls, prop_name, property_)
@lazyproperty def _add_method_name(self): return "_add_%s" % self._prop_name
def _add_to_class(self, name: str, method: Callable[..., Any]): """Add `method` to the target class as `name`, unless `name` is already defined there.""" if hasattr(self._element_cls, name): return setattr(self._element_cls, name, method)
@property def _creator(self) -> Callable[[BaseOxmlElement], BaseOxmlElement]: """Callable that creates a new, empty element of the child type, having no attributes."""
def new_child_element(obj: BaseOxmlElement): return OxmlElement(self._nsptagname)
return new_child_element
@property def _getter(self) -> Callable[[BaseOxmlElement], BaseOxmlElement | None]: """Callable suitable for the "get" side of the property descriptor.
This default getter returns the child element with matching tag name or |None| if not present. """
def get_child_element(obj: BaseOxmlElement) -> BaseOxmlElement | None: return obj.find(qn(self._nsptagname))
get_child_element.__doc__ = ( "``<%s>`` child element or |None| if not present." % self._nsptagname ) return get_child_element
@lazyproperty def _insert_method_name(self): return "_insert_%s" % self._prop_name
@property def _list_getter(self) -> Callable[[BaseOxmlElement], list[BaseOxmlElement]]: """Callable suitable for the "get" side of a list property descriptor."""
def get_child_element_list(obj: BaseOxmlElement) -> list[BaseOxmlElement]: return cast("list[BaseOxmlElement]", obj.findall(qn(self._nsptagname)))
get_child_element_list.__doc__ = ( "A list containing each of the ``<%s>`` child elements, in the o" "rder they appear." % self._nsptagname ) return get_child_element_list
@lazyproperty def _remove_method_name(self): return "_remove_%s" % self._prop_name
@lazyproperty def _new_method_name(self): return "_new_%s" % self._prop_name
class Choice(_BaseChildElement): """Defines a child element belonging to a group, only one of which may appear as a child."""
@property def nsptagname(self): return self._nsptagname
def populate_class_members( # pyright: ignore[reportIncompatibleMethodOverride] self, element_cls: Type[BaseOxmlElement], group_prop_name: str, successors: Sequence[str] ): """Add the appropriate methods to `element_cls`.""" self._element_cls = element_cls self._group_prop_name = group_prop_name self._successors = successors
self._add_getter() self._add_creator() self._add_inserter() self._add_adder() self._add_get_or_change_to_method()
def _add_get_or_change_to_method(self) -> None: """Add a `get_or_change_to_x()` method to the element class for this child element."""
def get_or_change_to_child(obj: BaseOxmlElement): child = getattr(obj, self._prop_name) if child is not None: return child remove_group_method = getattr(obj, self._remove_group_method_name) remove_group_method() add_method = getattr(obj, self._add_method_name) child = add_method() return child
get_or_change_to_child.__doc__ = ( "Return the ``<%s>`` child, replacing any other group element if" " found." ) % self._nsptagname self._add_to_class(self._get_or_change_to_method_name, get_or_change_to_child)
@property def _prop_name(self): """ Calculate property name from tag name, e.g. a:schemeClr -> schemeClr. """ if ":" in self._nsptagname: start = self._nsptagname.index(":") + 1 else: start = 0 return self._nsptagname[start:]
@lazyproperty def _get_or_change_to_method_name(self): return "get_or_change_to_%s" % self._prop_name
@lazyproperty def _remove_group_method_name(self): return "_remove_%s" % self._group_prop_name
class OneAndOnlyOne(_BaseChildElement): """Defines a required child element for MetaOxmlElement."""
def __init__(self, nsptagname: str): super(OneAndOnlyOne, self).__init__(nsptagname, ())
def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str): """ Add the appropriate methods to *element_cls*. """ super(OneAndOnlyOne, self).populate_class_members(element_cls, prop_name) self._add_getter()
@property def _getter(self) -> Callable[[BaseOxmlElement], BaseOxmlElement]: """Callable suitable for the "get" side of the property descriptor."""
def get_child_element(obj: BaseOxmlElement) -> BaseOxmlElement: child = obj.find(qn(self._nsptagname)) if child is None: raise InvalidXmlError( "required ``<%s>`` child element not present" % self._nsptagname ) return child
get_child_element.__doc__ = "Required ``<%s>`` child element." % self._nsptagname return get_child_element
class OneOrMore(_BaseChildElement): """Defines a repeating child element for MetaOxmlElement that must appear at least once."""
def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str): """Add the appropriate methods to *element_cls*.""" super(OneOrMore, self).populate_class_members(element_cls, prop_name) self._add_list_getter() self._add_creator() self._add_inserter() self._add_adder() self._add_public_adder() delattr(element_cls, prop_name)
def _add_public_adder(self) -> None: """Add a public `.add_x()` method to the parent element class."""
def add_child(obj: BaseOxmlElement) -> BaseOxmlElement: private_add_method = getattr(obj, self._add_method_name) child = private_add_method() return child
add_child.__doc__ = ( "Add a new ``<%s>`` child element unconditionally, inserted in t" "he correct sequence." % self._nsptagname ) self._add_to_class(self._public_add_method_name, add_child)
@lazyproperty def _public_add_method_name(self): """ add_childElement() is public API for a repeating element, allowing new elements to be added to the sequence. May be overridden to provide a friendlier API to clients having domain appropriate parameter names for required attributes. """ return "add_%s" % self._prop_name
class ZeroOrMore(_BaseChildElement): """ Defines an optional repeating child element for MetaOxmlElement. """
def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str): """ Add the appropriate methods to *element_cls*. """ super(ZeroOrMore, self).populate_class_members(element_cls, prop_name) self._add_list_getter() self._add_creator() self._add_inserter() self._add_adder() delattr(element_cls, prop_name)
class ZeroOrOne(_BaseChildElement): """Defines an optional child element for MetaOxmlElement."""
def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str): """Add the appropriate methods to `element_cls`.""" super(ZeroOrOne, self).populate_class_members(element_cls, prop_name) self._add_getter() self._add_creator() self._add_inserter() self._add_adder() self._add_get_or_adder() self._add_remover()
def _add_get_or_adder(self): """Add a `.get_or_add_x()` method to the element class for this child element."""
def get_or_add_child(obj: BaseOxmlElement) -> BaseOxmlElement: child = getattr(obj, self._prop_name) if child is None: add_method = getattr(obj, self._add_method_name) child = add_method() return child
get_or_add_child.__doc__ = ( "Return the ``<%s>`` child element, newly added if not present." ) % self._nsptagname self._add_to_class(self._get_or_add_method_name, get_or_add_child)
def _add_remover(self): """Add a `._remove_x()` method to the element class for this child element."""
def _remove_child(obj: BaseOxmlElement) -> None: obj.remove_all(self._nsptagname)
_remove_child.__doc__ = f"Remove all `{self._nsptagname}` child elements." self._add_to_class(self._remove_method_name, _remove_child)
@lazyproperty def _get_or_add_method_name(self): return "get_or_add_%s" % self._prop_name
class ZeroOrOneChoice(_BaseChildElement): """An `EG_*` element group where at most one of its members may appear as a child."""
def __init__(self, choices: Iterable[Choice], successors: Iterable[str] = ()): self._choices = tuple(choices) self._successors = tuple(successors)
def populate_class_members(self, element_cls: Type[BaseOxmlElement], prop_name: str): """Add the appropriate methods to `element_cls`.""" super(ZeroOrOneChoice, self).populate_class_members(element_cls, prop_name) self._add_choice_getter() for choice in self._choices: choice.populate_class_members(element_cls, self._prop_name, self._successors) self._add_group_remover()
def _add_choice_getter(self): """Add a read-only `.{prop_name}` property to the element class.
The property returns the present member of this group, or |None| if none are present. """ property_ = property(self._choice_getter, None, None) # assign unconditionally to overwrite element name definition setattr(self._element_cls, self._prop_name, property_)
def _add_group_remover(self): """Add a `._remove_eg_x()` method to the element class for this choice group."""
def _remove_choice_group(obj: BaseOxmlElement) -> None: for tagname in self._member_nsptagnames: obj.remove_all(tagname)
_remove_choice_group.__doc__ = "Remove the current choice group child element if present." self._add_to_class(self._remove_choice_group_method_name, _remove_choice_group)
@property def _choice_getter(self): """ Return a function object suitable for the "get" side of the property descriptor. """
def get_group_member_element(obj: BaseOxmlElement) -> BaseOxmlElement | None: return cast( "BaseOxmlElement | None", obj.first_child_found_in(*self._member_nsptagnames) )
get_group_member_element.__doc__ = ( "Return the child element belonging to this element group, or " "|None| if no member child is present." ) return get_group_member_element
@lazyproperty def _member_nsptagnames(self) -> list[str]: """Sequence of namespace-prefixed tagnames, one for each member element of choice group.""" return [choice.nsptagname for choice in self._choices]
@lazyproperty def _remove_choice_group_method_name(self): """Function-name for choice remover.""" return f"_remove_{self._prop_name}"
# -- lxml typing isn't quite right here, just ignore this error on _Element --class BaseOxmlElement(etree.ElementBase, metaclass=MetaOxmlElement): """Effective base class for all custom element classes.
Adds standardized behavior to all classes in one place. """
def __repr__(self): return "<%s '<%s>' at 0x%0x>" % ( self.__class__.__name__, self._nsptag, id(self), )
def first_child_found_in(self, *tagnames: str) -> _Element | None: """First child with tag in `tagnames`, or None if not found.""" for tagname in tagnames: child = self.find(qn(tagname)) if child is not None: return child return None
def insert_element_before(self, elm: ElementBase, *tagnames: str): successor = self.first_child_found_in(*tagnames) if successor is not None: successor.addprevious(elm) else: self.append(elm) return elm
def remove_all(self, *tagnames: str) -> None: """Remove child elements with tagname (e.g. "a:p") in `tagnames`.""" for tagname in tagnames: matching = self.findall(qn(tagname)) for child in matching: self.remove(child)
@property def xml(self) -> str: """XML string for this element, suitable for testing purposes.
Pretty printed for readability and without an XML declaration at the top. """ return serialize_for_reading(self)
def xpath(self, xpath_str: str) -> Any: # pyright: ignore[reportIncompatibleMethodOverride] """Override of `lxml` _Element.xpath() method.
Provides standard Open XML namespace mapping (`nsmap`) in centralized location. """ return super().xpath(xpath_str, namespaces=_nsmap)
@property def _nsptag(self) -> str: return NamespacePrefixedTag.from_clark_name(self.tag)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222"""Overall .pptx package."""
from __future__ import annotations
from typing import IO, Iterator
from pptx.opc.constants import RELATIONSHIP_TYPE as RTfrom pptx.opc.package import OpcPackagefrom pptx.opc.packuri import PackURIfrom pptx.parts.coreprops import CorePropertiesPartfrom pptx.parts.image import Image, ImagePartfrom pptx.parts.media import MediaPartfrom pptx.util import lazyproperty
class Package(OpcPackage): """An overall .pptx package."""
@lazyproperty def core_properties(self) -> CorePropertiesPart: """Instance of |CoreProperties| holding read/write Dublin Core doc properties.
Creates a default core properties part if one is not present (not common). """ try: return self.part_related_by(RT.CORE_PROPERTIES) except KeyError: core_props = CorePropertiesPart.default(self) self.relate_to(core_props, RT.CORE_PROPERTIES) return core_props
def get_or_add_image_part(self, image_file: str | IO[bytes]): """ Return an |ImagePart| object containing the image in *image_file*. If the image part already exists in this package, it is reused, otherwise a new one is created. """ return self._image_parts.get_or_add_image_part(image_file)
def get_or_add_media_part(self, media): """Return a |MediaPart| object containing the media in *media*.
If a media part for this media bytestream ("file") is already present in this package, it is reused, otherwise a new one is created. """ return self._media_parts.get_or_add_media_part(media)
def next_image_partname(self, ext: str) -> PackURI: """Return a |PackURI| instance representing the next available image partname.
Partname uses the next available sequence number. *ext* is used as the extention on the returned partname. """
def first_available_image_idx(): image_idxs = sorted( [ part.partname.idx for part in self.iter_parts() if ( part.partname.startswith("/ppt/media/image") and part.partname.idx is not None ) ] ) for i, image_idx in enumerate(image_idxs): idx = i + 1 if idx < image_idx: return idx return len(image_idxs) + 1
idx = first_available_image_idx() return PackURI("/ppt/media/image%d.%s" % (idx, ext))
def next_media_partname(self, ext): """Return |PackURI| instance for next available media partname.
Partname is first available, starting at sequence number 1. Empty sequence numbers are reused. *ext* is used as the extension on the returned partname. """
def first_available_media_idx(): media_idxs = sorted( [ part.partname.idx for part in self.iter_parts() if part.partname.startswith("/ppt/media/media") ] ) for i, media_idx in enumerate(media_idxs): idx = i + 1 if idx < media_idx: return idx return len(media_idxs) + 1
idx = first_available_media_idx() return PackURI("/ppt/media/media%d.%s" % (idx, ext))
@property def presentation_part(self): """ Reference to the |Presentation| instance contained in this package. """ return self.main_document_part
@lazyproperty def _image_parts(self): """ |_ImageParts| object providing access to the image parts in this package. """ return _ImageParts(self)
@lazyproperty def _media_parts(self): """Return |_MediaParts| object for this package.
The media parts object provides access to all the media parts in this package. """ return _MediaParts(self)
class _ImageParts(object): """Provides access to the image parts in a package."""
def __init__(self, package): super(_ImageParts, self).__init__() self._package = package
def __iter__(self) -> Iterator[ImagePart]: """Generate a reference to each |ImagePart| object in the package.""" image_parts = [] for rel in self._package.iter_rels(): if rel.is_external: continue if rel.reltype != RT.IMAGE: continue image_part = rel.target_part if image_part in image_parts: continue image_parts.append(image_part) yield image_part
def get_or_add_image_part(self, image_file: str | IO[bytes]) -> ImagePart: """Return |ImagePart| object containing the image in `image_file`.
`image_file` can be either a path to an image file or a file-like object containing an image. If an image part containing this same image already exists, that instance is returned, otherwise a new image part is created. """ image = Image.from_file(image_file) image_part = self._find_by_sha1(image.sha1) return image_part if image_part else ImagePart.new(self._package, image)
def _find_by_sha1(self, sha1: str) -> ImagePart | None: """ Return an |ImagePart| object belonging to this package or |None| if no matching image part is found. The image part is identified by the SHA1 hash digest of the image binary it contains. """ for image_part in self: # ---skip unknown/unsupported image types, like SVG--- if not hasattr(image_part, "sha1"): continue if image_part.sha1 == sha1: return image_part return None
class _MediaParts(object): """Provides access to the media parts in a package.
Supports iteration and :meth:`get()` using the media object SHA1 hash as its key. """
def __init__(self, package): super(_MediaParts, self).__init__() self._package = package
def __iter__(self): """Generate a reference to each |MediaPart| object in the package.""" # A media part can appear in more than one relationship (and commonly # does in the case of video). Use media_parts to keep track of those # that have been "yielded"; they can be skipped if they occur again. media_parts = [] for rel in self._package.iter_rels(): if rel.is_external: continue if rel.reltype not in (RT.MEDIA, RT.VIDEO): continue media_part = rel.target_part if media_part in media_parts: continue media_parts.append(media_part) yield media_part
def get_or_add_media_part(self, media): """Return a |MediaPart| object containing the media in *media*.
If this package already contains a media part for the same bytestream, that instance is returned, otherwise a new media part is created. """ media_part = self._find_by_sha1(media.sha1) if media_part is None: media_part = MediaPart.new(self._package, media) return media_part
def _find_by_sha1(self, sha1): """Return |MediaPart| object having *sha1* hash or None if not found.
All media parts belonging to this package are considered. A media part is identified by the SHA1 hash digest of its bytestream ("file"). """ for media_part in self: if media_part.sha1 == sha1: return media_part return None1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495"""Chart part objects, including Chart and Charts."""
from __future__ import annotations
from typing import TYPE_CHECKING
from pptx.chart.chart import Chartfrom pptx.opc.constants import CONTENT_TYPE as CTfrom pptx.opc.constants import RELATIONSHIP_TYPE as RTfrom pptx.opc.package import XmlPartfrom pptx.parts.embeddedpackage import EmbeddedXlsxPartfrom pptx.util import lazyproperty
if TYPE_CHECKING: from pptx.chart.data import ChartData from pptx.enum.chart import XL_CHART_TYPE from pptx.package import Package
class ChartPart(XmlPart): """A chart part.
Corresponds to parts having partnames matching ppt/charts/chart[1-9][0-9]*.xml """
partname_template = "/ppt/charts/chart%d.xml"
@classmethod def new(cls, chart_type: XL_CHART_TYPE, chart_data: ChartData, package: Package): """Return new |ChartPart| instance added to `package`.
Returned chart-part contains a chart of `chart_type` depicting `chart_data`. """ chart_part = cls.load( package.next_partname(cls.partname_template), CT.DML_CHART, package, chart_data.xml_bytes(chart_type), ) chart_part.chart_workbook.update_from_xlsx_blob(chart_data.xlsx_blob) return chart_part
@lazyproperty def chart(self): """|Chart| object representing the chart in this part.""" return Chart(self._element, self)
@lazyproperty def chart_workbook(self): """ The |ChartWorkbook| object providing access to the external chart data in a linked or embedded Excel workbook. """ return ChartWorkbook(self._element, self)
class ChartWorkbook(object): """Provides access to external chart data in a linked or embedded Excel workbook."""
def __init__(self, chartSpace, chart_part): super(ChartWorkbook, self).__init__() self._chartSpace = chartSpace self._chart_part = chart_part
def update_from_xlsx_blob(self, xlsx_blob): """ Replace the Excel spreadsheet in the related |EmbeddedXlsxPart| with the Excel binary in *xlsx_blob*, adding a new |EmbeddedXlsxPart| if there isn't one. """ xlsx_part = self.xlsx_part if xlsx_part is None: self.xlsx_part = EmbeddedXlsxPart.new(xlsx_blob, self._chart_part.package) return xlsx_part.blob = xlsx_blob
@property def xlsx_part(self): """Optional |EmbeddedXlsxPart| object containing data for this chart.
This related part has its rId at `c:chartSpace/c:externalData/@rId`. This value is |None| if there is no `<c:externalData>` element. """ xlsx_part_rId = self._chartSpace.xlsx_part_rId return None if xlsx_part_rId is None else self._chart_part.related_part(xlsx_part_rId)
@xlsx_part.setter def xlsx_part(self, xlsx_part): """ Set the related |EmbeddedXlsxPart| to *xlsx_part*. Assume one does not already exist. """ rId = self._chart_part.relate_to(xlsx_part, RT.PACKAGE) externalData = self._chartSpace.get_or_add_externalData() externalData.rId = rId123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167"""Core properties part, corresponds to ``/docProps/core.xml`` part in package."""
from __future__ import annotations
import datetime as dtfrom typing import TYPE_CHECKING
from pptx.opc.constants import CONTENT_TYPE as CTfrom pptx.opc.package import XmlPartfrom pptx.opc.packuri import PackURIfrom pptx.oxml.coreprops import CT_CoreProperties
if TYPE_CHECKING: from pptx.package import Package
class CorePropertiesPart(XmlPart): """Corresponds to part named `/docProps/core.xml`.
Contains the core document properties for this document package. """
_element: CT_CoreProperties
@classmethod def default(cls, package: Package): """Return default new |CorePropertiesPart| instance suitable as starting point.
This provides a base for adding core-properties to a package that doesn't yet have any. """ core_props = cls._new(package) core_props.title = "PowerPoint Presentation" core_props.last_modified_by = "python-pptx" core_props.revision = 1 core_props.modified = dt.datetime.now(dt.timezone.utc).replace(tzinfo=None) return core_props
@property def author(self) -> str: return self._element.author_text
@author.setter def author(self, value: str): self._element.author_text = value
@property def category(self) -> str: return self._element.category_text
@category.setter def category(self, value: str): self._element.category_text = value
@property def comments(self) -> str: return self._element.comments_text
@comments.setter def comments(self, value: str): self._element.comments_text = value
@property def content_status(self) -> str: return self._element.contentStatus_text
@content_status.setter def content_status(self, value: str): self._element.contentStatus_text = value
@property def created(self): return self._element.created_datetime
@created.setter def created(self, value: dt.datetime): self._element.created_datetime = value
@property def identifier(self) -> str: return self._element.identifier_text
@identifier.setter def identifier(self, value: str): self._element.identifier_text = value
@property def keywords(self) -> str: return self._element.keywords_text
@keywords.setter def keywords(self, value: str): self._element.keywords_text = value
@property def language(self) -> str: return self._element.language_text
@language.setter def language(self, value: str): self._element.language_text = value
@property def last_modified_by(self) -> str: return self._element.lastModifiedBy_text
@last_modified_by.setter def last_modified_by(self, value: str): self._element.lastModifiedBy_text = value
@property def last_printed(self): return self._element.lastPrinted_datetime
@last_printed.setter def last_printed(self, value: dt.datetime): self._element.lastPrinted_datetime = value
@property def modified(self): return self._element.modified_datetime
@modified.setter def modified(self, value: dt.datetime): self._element.modified_datetime = value
@property def revision(self): return self._element.revision_number
@revision.setter def revision(self, value: int): self._element.revision_number = value
@property def subject(self) -> str: return self._element.subject_text
@subject.setter def subject(self, value: str): self._element.subject_text = value
@property def title(self) -> str: return self._element.title_text
@title.setter def title(self, value: str): self._element.title_text = value
@property def version(self) -> str: return self._element.version_text
@version.setter def version(self, value: str): self._element.version_text = value
@classmethod def _new(cls, package: Package) -> CorePropertiesPart: """Return new empty |CorePropertiesPart| instance.""" return CorePropertiesPart( PackURI("/docProps/core.xml"), CT.OPC_CORE_PROPERTIES, package, CT_CoreProperties.new_coreProperties(), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293"""Embedded Package part objects.
"Package" in this context means another OPC package, i.e. a DOCX, PPTX, or XLSX "file"."""
from __future__ import annotations
from typing import TYPE_CHECKING
from pptx.enum.shapes import PROG_IDfrom pptx.opc.constants import CONTENT_TYPE as CTfrom pptx.opc.package import Part
if TYPE_CHECKING: from pptx.package import Package
class EmbeddedPackagePart(Part): """A distinct OPC package, e.g. an Excel file, embedded in this PPTX package.
Has a partname like: `ppt/embeddings/Microsoft_Excel_Sheet1.xlsx`. """
@classmethod def factory(cls, prog_id: PROG_ID | str, object_blob: bytes, package: Package): """Return a new |EmbeddedPackagePart| subclass instance added to *package*.
The subclass is determined by `prog_id` which corresponds to the "application" used to open the "file-type" of `object_blob`. The returned part contains the bytes of `object_blob` and has the content-type also determined by `prog_id`. """ # --- a generic OLE object has no subclass --- if not isinstance(prog_id, PROG_ID): return cls( package.next_partname("/ppt/embeddings/oleObject%d.bin"), CT.OFC_OLE_OBJECT, package, object_blob, )
# --- A Microsoft Office file-type is a distinguished package object --- EmbeddedPartCls = { PROG_ID.DOCX: EmbeddedDocxPart, PROG_ID.PPTX: EmbeddedPptxPart, PROG_ID.XLSX: EmbeddedXlsxPart, }[prog_id]
return EmbeddedPartCls.new(object_blob, package)
@classmethod def new(cls, blob: bytes, package: Package): """Return new |EmbeddedPackagePart| subclass object.
The returned part object contains `blob` and is added to `package`. """ return cls( package.next_partname(cls.partname_template), cls.content_type, package, blob, )
class EmbeddedDocxPart(EmbeddedPackagePart): """A Word .docx file stored in a part.
This part-type arises when a Word document appears as an embedded OLE-object shape. """
partname_template = "/ppt/embeddings/Microsoft_Word_Document%d.docx" content_type = CT.WML_DOCUMENT
class EmbeddedPptxPart(EmbeddedPackagePart): """A PowerPoint file stored in a part.
This part-type arises when a PowerPoint presentation (.pptx file) appears as an embedded OLE-object shape. """
partname_template = "/ppt/embeddings/Microsoft_PowerPoint_Presentation%d.pptx" content_type = CT.PML_PRESENTATION
class EmbeddedXlsxPart(EmbeddedPackagePart): """An Excel file stored in a part.
This part-type arises as the data source for a chart, but may also be the OLE-object for an embedded object shape. """
partname_template = "/ppt/embeddings/Microsoft_Excel_Sheet%d.xlsx" content_type = CT.SML_SHEET123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275"""ImagePart and related objects."""
from __future__ import annotations
import hashlibimport ioimport osfrom typing import IO, TYPE_CHECKING, Any, cast
from PIL import Image as PIL_Image
from pptx.opc.package import Partfrom pptx.opc.spec import image_content_typesfrom pptx.util import Emu, lazyproperty
if TYPE_CHECKING: from pptx.opc.packuri import PackURI from pptx.package import Package from pptx.util import Length
class ImagePart(Part): """An image part.
An image part generally has a partname matching the regex `ppt/media/image[1-9][0-9]*.*`. """
def __init__( self, partname: PackURI, content_type: str, package: Package, blob: bytes, filename: str | None = None, ): super(ImagePart, self).__init__(partname, content_type, package, blob) self._blob = blob self._filename = filename
@classmethod def new(cls, package: Package, image: Image) -> ImagePart: """Return new |ImagePart| instance containing `image`.
`image` is an |Image| object. """ return cls( package.next_image_partname(image.ext), image.content_type, package, image.blob, image.filename, )
@property def desc(self) -> str: """The filename associated with this image.
Either the filename of the original image or a generic name of the form `image.ext` where `ext` is appropriate to the image file format, e.g. `'jpg'`. An image created using a path will have that filename; one created with a file-like object will have a generic name. """ # -- return generic filename if original filename is unknown -- if self._filename is None: return f"image.{self.ext}" return self._filename
@property def ext(self) -> str: """File-name extension for this image e.g. `'png'`.""" return self.partname.ext
@property def image(self) -> Image: """An |Image| object containing the image in this image part.
Note this is a `pptx.image.Image` object, not a PIL Image. """ return Image(self._blob, self.desc)
def scale(self, scaled_cx: int | None, scaled_cy: int | None) -> tuple[int, int]: """Return scaled image dimensions in EMU based on the combination of parameters supplied.
If `scaled_cx` and `scaled_cy` are both |None|, the native image size is returned. If neither `scaled_cx` nor `scaled_cy` is |None|, their values are returned unchanged. If a value is provided for either `scaled_cx` or `scaled_cy` and the other is |None|, the missing value is calculated such that the image's aspect ratio is preserved. """ image_cx, image_cy = self._native_size
if scaled_cx and scaled_cy: return scaled_cx, scaled_cy
if scaled_cx and not scaled_cy: scaling_factor = float(scaled_cx) / float(image_cx) scaled_cy = int(round(image_cy * scaling_factor)) return scaled_cx, scaled_cy
if not scaled_cx and scaled_cy: scaling_factor = float(scaled_cy) / float(image_cy) scaled_cx = int(round(image_cx * scaling_factor)) return scaled_cx, scaled_cy
# -- only remaining case is both `scaled_cx` and `scaled_cy` are `None` -- return image_cx, image_cy
@lazyproperty def sha1(self) -> str: """The 40-character SHA1 hash digest for the image binary of this image part.
like: `"1be010ea47803b00e140b852765cdf84f491da47"`. """ return hashlib.sha1(self._blob).hexdigest()
@property def _dpi(self) -> tuple[int, int]: """(horz_dpi, vert_dpi) pair representing the dots-per-inch resolution of this image.""" image = Image.from_blob(self._blob) return image.dpi
@property def _native_size(self) -> tuple[Length, Length]: """A (width, height) 2-tuple representing the native dimensions of the image in EMU.
Calculated based on the image DPI value, if present, assuming 72 dpi as a default. """ EMU_PER_INCH = 914400 horz_dpi, vert_dpi = self._dpi width_px, height_px = self._px_size
width = EMU_PER_INCH * width_px / horz_dpi height = EMU_PER_INCH * height_px / vert_dpi
return Emu(int(width)), Emu(int(height))
@property def _px_size(self) -> tuple[int, int]: """A (width, height) 2-tuple representing the dimensions of this image in pixels.""" image = Image.from_blob(self._blob) return image.size
class Image(object): """Immutable value object representing an image such as a JPEG, PNG, or GIF."""
def __init__(self, blob: bytes, filename: str | None): super(Image, self).__init__() self._blob = blob self._filename = filename
@classmethod def from_blob(cls, blob: bytes, filename: str | None = None) -> Image: """Return a new |Image| object loaded from the image binary in `blob`.""" return cls(blob, filename)
@classmethod def from_file(cls, image_file: str | IO[bytes]) -> Image: """Return a new |Image| object loaded from `image_file`.
`image_file` can be either a path (str) or a file-like object. """ if isinstance(image_file, str): # treat image_file as a path with open(image_file, "rb") as f: blob = f.read() filename = os.path.basename(image_file) else: # assume image_file is a file-like object # ---reposition file cursor if it has one--- if callable(getattr(image_file, "seek")): image_file.seek(0) blob = image_file.read() filename = None
return cls.from_blob(blob, filename)
@property def blob(self) -> bytes: """The binary image bytestream of this image.""" return self._blob
@lazyproperty def content_type(self) -> str: """MIME-type of this image, e.g. `"image/jpeg"`.""" return image_content_types[self.ext]
@lazyproperty def dpi(self) -> tuple[int, int]: """A (horz_dpi, vert_dpi) 2-tuple specifying the dots-per-inch resolution of this image.
A default value of (72, 72) is used if the dpi is not specified in the image file. """
def int_dpi(dpi: Any): """Return an integer dots-per-inch value corresponding to `dpi`.
If `dpi` is |None|, a non-numeric type, less than 1 or greater than 2048, 72 is returned. """ try: int_dpi = int(round(float(dpi))) if int_dpi < 1 or int_dpi > 2048: int_dpi = 72 except (TypeError, ValueError): int_dpi = 72 return int_dpi
def normalize_pil_dpi(pil_dpi: tuple[int, int] | None): """Return a (horz_dpi, vert_dpi) 2-tuple corresponding to `pil_dpi`.
The value for the 'dpi' key in the `info` dict of a PIL image. If the 'dpi' key is not present or contains an invalid value, `(72, 72)` is returned. """ if isinstance(pil_dpi, tuple): return (int_dpi(pil_dpi[0]), int_dpi(pil_dpi[1])) return (72, 72)
return normalize_pil_dpi(self._pil_props[2])
@lazyproperty def ext(self) -> str: """Canonical file extension for this image e.g. `'png'`.
The returned extension is all lowercase and is the canonical extension for the content type of this image, regardless of what extension may have been used in its filename, if any. """ ext_map = { "BMP": "bmp", "GIF": "gif", "JPEG": "jpg", "PNG": "png", "TIFF": "tiff", "WMF": "wmf", } format = self._format if format not in ext_map: tmpl = "unsupported image format, expected one of: %s, got '%s'" raise ValueError(tmpl % (ext_map.keys(), format)) return ext_map[format]
@property def filename(self) -> str | None: """Filename from path used to load this image, if loaded from the filesystem.
|None| if no filename was used in loading, such as when loaded from an in-memory stream. """ return self._filename
@lazyproperty def sha1(self) -> str: """SHA1 hash digest of the image blob.""" return hashlib.sha1(self._blob).hexdigest()
@lazyproperty def size(self) -> tuple[int, int]: """A (width, height) 2-tuple specifying the dimensions of this image in pixels.""" return self._pil_props[1]
@property def _format(self) -> str | None: """The PIL Image format of this image, e.g. 'PNG'.""" return self._pil_props[0]
@lazyproperty def _pil_props(self) -> tuple[str | None, tuple[int, int], tuple[int, int] | None]: """tuple of image properties extracted from this image using Pillow.""" stream = io.BytesIO(self._blob) pil_image = PIL_Image.open(stream) # pyright: ignore[reportUnknownMemberType] format = pil_image.format width_px, height_px = pil_image.size dpi = cast( "tuple[int, int] | None", pil_image.info.get("dpi"), # pyright: ignore[reportUnknownMemberType] ) stream.close() return (format, (width_px, height_px), dpi)12345678910111213141516171819202122232425262728293031323334353637"""MediaPart and related objects."""
from __future__ import annotations
import hashlib
from pptx.opc.package import Partfrom pptx.util import lazyproperty
class MediaPart(Part): """A media part, containing an audio or video resource.
A media part generally has a partname matching the regex `ppt/media/media[1-9][0-9]*.*`. """
@classmethod def new(cls, package, media): """Return new |MediaPart| instance containing `media`.
`media` must be a |Media| object. """ return cls( package.next_media_partname(media.ext), media.content_type, package, media.blob, )
@lazyproperty def sha1(self): """The SHA1 hash digest for the media binary of this media part.
Example: `'1be010ea47803b00e140b852765cdf84f491da47'` """ return hashlib.sha1(self._blob).hexdigest()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126"""Presentation part, the main part in a .pptx package."""
from __future__ import annotations
from typing import IO, TYPE_CHECKING, Iterable
from pptx.opc.constants import RELATIONSHIP_TYPE as RTfrom pptx.opc.package import XmlPartfrom pptx.opc.packuri import PackURIfrom pptx.parts.slide import NotesMasterPart, SlidePartfrom pptx.presentation import Presentationfrom pptx.util import lazyproperty
if TYPE_CHECKING: from pptx.parts.coreprops import CorePropertiesPart from pptx.slide import NotesMaster, Slide, SlideLayout, SlideMaster
class PresentationPart(XmlPart): """Top level class in object model.
Represents the contents of the /ppt directory of a .pptx file. """
def add_slide(self, slide_layout: SlideLayout): """Return (rId, slide) pair of a newly created blank slide.
New slide inherits appearance from `slide_layout`. """ partname = self._next_slide_partname slide_layout_part = slide_layout.part slide_part = SlidePart.new(partname, self.package, slide_layout_part) rId = self.relate_to(slide_part, RT.SLIDE) return rId, slide_part.slide
@property def core_properties(self) -> CorePropertiesPart: """A |CoreProperties| object for the presentation.
Provides read/write access to the Dublin Core properties of this presentation. """ return self.package.core_properties
def get_slide(self, slide_id: int) -> Slide | None: """Return optional related |Slide| object identified by `slide_id`.
Returns |None| if no slide with `slide_id` is related to this presentation. """ for sldId in self._element.sldIdLst: if sldId.id == slide_id: return self.related_part(sldId.rId).slide return None
@lazyproperty def notes_master(self) -> NotesMaster: """ Return the |NotesMaster| object for this presentation. If the presentation does not have a notes master, one is created from a default template. The same single instance is returned on each call. """ return self.notes_master_part.notes_master
@lazyproperty def notes_master_part(self) -> NotesMasterPart: """Return the |NotesMasterPart| object for this presentation.
If the presentation does not have a notes master, one is created from a default template. The same single instance is returned on each call. """ try: return self.part_related_by(RT.NOTES_MASTER) except KeyError: notes_master_part = NotesMasterPart.create_default(self.package) self.relate_to(notes_master_part, RT.NOTES_MASTER) return notes_master_part
@lazyproperty def presentation(self): """ A |Presentation| object providing access to the content of this presentation. """ return Presentation(self._element, self)
def related_slide(self, rId: str) -> Slide: """Return |Slide| object for related |SlidePart| related by `rId`.""" return self.related_part(rId).slide
def related_slide_master(self, rId: str) -> SlideMaster: """Return |SlideMaster| object for |SlideMasterPart| related by `rId`.""" return self.related_part(rId).slide_master
def rename_slide_parts(self, rIds: Iterable[str]): """Assign incrementing partnames to the slide parts identified by `rIds`.
Partnames are like `/ppt/slides/slide9.xml` and are assigned in the order their id appears in the `rIds` sequence. The name portion is always `slide`. The number part forms a continuous sequence starting at 1 (e.g. 1, 2, ... 10, ...). The extension is always `.xml`. """ for idx, rId in enumerate(rIds): slide_part = self.related_part(rId) slide_part.partname = PackURI("/ppt/slides/slide%d.xml" % (idx + 1))
def save(self, path_or_stream: str | IO[bytes]): """Save this presentation package to `path_or_stream`.
`path_or_stream` can be either a path to a filesystem location (a string) or a file-like object. """ self.package.save(path_or_stream)
def slide_id(self, slide_part): """Return the slide-id associated with `slide_part`.""" for sldId in self._element.sldIdLst: if self.related_part(sldId.rId) is slide_part: return sldId.id raise ValueError("matching slide_part not found")
@property def _next_slide_partname(self): """Return |PackURI| instance containing next available slide partname.""" sldIdLst = self._element.get_or_add_sldIdLst() partname_str = "/ppt/slides/slide%d.xml" % (len(sldIdLst) + 1) return PackURI(partname_str)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297"""Slide and related objects."""
from __future__ import annotations
from typing import IO, TYPE_CHECKING, cast
from pptx.enum.shapes import PROG_IDfrom pptx.opc.constants import CONTENT_TYPE as CTfrom pptx.opc.constants import RELATIONSHIP_TYPE as RTfrom pptx.opc.package import XmlPartfrom pptx.opc.packuri import PackURIfrom pptx.oxml.slide import CT_NotesMaster, CT_NotesSlide, CT_Slidefrom pptx.oxml.theme import CT_OfficeStyleSheetfrom pptx.parts.chart import ChartPartfrom pptx.parts.embeddedpackage import EmbeddedPackagePartfrom pptx.slide import NotesMaster, NotesSlide, Slide, SlideLayout, SlideMasterfrom pptx.util import lazyproperty
if TYPE_CHECKING: from pptx.chart.data import ChartData from pptx.enum.chart import XL_CHART_TYPE from pptx.media import Video from pptx.parts.image import Image, ImagePart
class BaseSlidePart(XmlPart): """Base class for slide parts.
This includes slide, slide-layout, and slide-master parts, but also notes-slide, notes-master, and handout-master parts. """
_element: CT_Slide
def get_image(self, rId: str) -> Image: """Return an |Image| object containing the image related to this slide by *rId*.
Raises |KeyError| if no image is related by that id, which would generally indicate a corrupted .pptx file. """ return cast("ImagePart", self.related_part(rId)).image
def get_or_add_image_part(self, image_file: str | IO[bytes]): """Return `(image_part, rId)` pair corresponding to `image_file`.
The returned |ImagePart| object contains the image in `image_file` and is related to this slide with the key `rId`. If either the image part or relationship already exists, they are reused, otherwise they are newly created. """ image_part = self._package.get_or_add_image_part(image_file) rId = self.relate_to(image_part, RT.IMAGE) return image_part, rId
@property def name(self) -> str: """Internal name of this slide.""" return self._element.cSld.name
class NotesMasterPart(BaseSlidePart): """Notes master part.
Corresponds to package file `ppt/notesMasters/notesMaster1.xml`. """
@classmethod def create_default(cls, package): """ Create and return a default notes master part, including creating the new theme it requires. """ notes_master_part = cls._new(package) theme_part = cls._new_theme_part(package) notes_master_part.relate_to(theme_part, RT.THEME) return notes_master_part
@lazyproperty def notes_master(self): """ Return the |NotesMaster| object that proxies this notes master part. """ return NotesMaster(self._element, self)
@classmethod def _new(cls, package): """ Create and return a standalone, default notes master part based on the built-in template (without any related parts, such as theme). """ return NotesMasterPart( PackURI("/ppt/notesMasters/notesMaster1.xml"), CT.PML_NOTES_MASTER, package, CT_NotesMaster.new_default(), )
@classmethod def _new_theme_part(cls, package): """Return new default theme-part suitable for use with a notes master.""" return XmlPart( package.next_partname("/ppt/theme/theme%d.xml"), CT.OFC_THEME, package, CT_OfficeStyleSheet.new_default(), )
class NotesSlidePart(BaseSlidePart): """Notes slide part.
Contains the slide notes content and the layout for the slide handout page. Corresponds to package file `ppt/notesSlides/notesSlide[1-9][0-9]*.xml`. """
@classmethod def new(cls, package, slide_part): """Return new |NotesSlidePart| for the slide in `slide_part`.
The new notes-slide part is based on the (singleton) notes master and related to both the notes-master part and `slide_part`. If no notes-master is present, one is created based on the default template. """ notes_master_part = package.presentation_part.notes_master_part notes_slide_part = cls._add_notes_slide_part(package, slide_part, notes_master_part) notes_slide = notes_slide_part.notes_slide notes_slide.clone_master_placeholders(notes_master_part.notes_master) return notes_slide_part
@lazyproperty def notes_master(self): """Return the |NotesMaster| object this notes slide inherits from.""" notes_master_part = self.part_related_by(RT.NOTES_MASTER) return notes_master_part.notes_master
@lazyproperty def notes_slide(self): """Return the |NotesSlide| object that proxies this notes slide part.""" return NotesSlide(self._element, self)
@classmethod def _add_notes_slide_part(cls, package, slide_part, notes_master_part): """Create and return a new notes-slide part.
The return part is fully related, but has no shape content (i.e. placeholders not cloned). """ notes_slide_part = NotesSlidePart( package.next_partname("/ppt/notesSlides/notesSlide%d.xml"), CT.PML_NOTES_SLIDE, package, CT_NotesSlide.new(), ) notes_slide_part.relate_to(notes_master_part, RT.NOTES_MASTER) notes_slide_part.relate_to(slide_part, RT.SLIDE) return notes_slide_part
class SlidePart(BaseSlidePart): """Slide part. Corresponds to package files ppt/slides/slide[1-9][0-9]*.xml."""
@classmethod def new(cls, partname, package, slide_layout_part): """Return newly-created blank slide part.
The new slide-part has `partname` and a relationship to `slide_layout_part`. """ slide_part = cls(partname, CT.PML_SLIDE, package, CT_Slide.new()) slide_part.relate_to(slide_layout_part, RT.SLIDE_LAYOUT) return slide_part
def add_chart_part(self, chart_type: XL_CHART_TYPE, chart_data: ChartData): """Return str rId of new |ChartPart| object containing chart of `chart_type`.
The chart depicts `chart_data` and is related to the slide contained in this part by `rId`. """ return self.relate_to(ChartPart.new(chart_type, chart_data, self._package), RT.CHART)
def add_embedded_ole_object_part( self, prog_id: PROG_ID | str, ole_object_file: str | IO[bytes] ): """Return rId of newly-added OLE-object part formed from `ole_object_file`.""" relationship_type = RT.PACKAGE if isinstance(prog_id, PROG_ID) else RT.OLE_OBJECT return self.relate_to( EmbeddedPackagePart.factory( prog_id, self._blob_from_file(ole_object_file), self._package ), relationship_type, )
def get_or_add_video_media_part(self, video: Video) -> tuple[str, str]: """Return rIds for media and video relationships to media part.
A new |MediaPart| object is created if it does not already exist (such as would occur if the same video appeared more than once in a presentation). Two relationships to the media part are created, one each with MEDIA and VIDEO relationship types. The need for two appears to be for legacy support for an earlier (pre-Office 2010) PowerPoint media embedding strategy. """ media_part = self._package.get_or_add_media_part(video) media_rId = self.relate_to(media_part, RT.MEDIA) video_rId = self.relate_to(media_part, RT.VIDEO) return media_rId, video_rId
@property def has_notes_slide(self): """ Return True if this slide has a notes slide, False otherwise. A notes slide is created by the :attr:`notes_slide` property when one doesn't exist; use this property to test for a notes slide without the possible side-effect of creating one. """ try: self.part_related_by(RT.NOTES_SLIDE) except KeyError: return False return True
@lazyproperty def notes_slide(self) -> NotesSlide: """The |NotesSlide| instance associated with this slide.
If the slide does not have a notes slide, a new one is created. The same single instance is returned on each call. """ try: notes_slide_part = self.part_related_by(RT.NOTES_SLIDE) except KeyError: notes_slide_part = self._add_notes_slide_part() return notes_slide_part.notes_slide
@lazyproperty def slide(self): """ The |Slide| object representing this slide part. """ return Slide(self._element, self)
@property def slide_id(self) -> int: """Return the slide identifier stored in the presentation part for this slide part.""" presentation_part = self.package.presentation_part return presentation_part.slide_id(self)
@property def slide_layout(self) -> SlideLayout: """|SlideLayout| object the slide in this part inherits appearance from.""" slide_layout_part = self.part_related_by(RT.SLIDE_LAYOUT) return slide_layout_part.slide_layout
def _add_notes_slide_part(self): """ Return a newly created |NotesSlidePart| object related to this slide part. Caller is responsible for ensuring this slide doesn't already have a notes slide part. """ notes_slide_part = NotesSlidePart.new(self.package, self) self.relate_to(notes_slide_part, RT.NOTES_SLIDE) return notes_slide_part
class SlideLayoutPart(BaseSlidePart): """Slide layout part.
Corresponds to package files ``ppt/slideLayouts/slideLayout[1-9][0-9]*.xml``. """
@lazyproperty def slide_layout(self): """ The |SlideLayout| object representing this part. """ return SlideLayout(self._element, self)
@property def slide_master(self) -> SlideMaster: """Slide master from which this slide layout inherits properties.""" return self.part_related_by(RT.SLIDE_MASTER).slide_master
class SlideMasterPart(BaseSlidePart): """Slide master part.
Corresponds to package files ppt/slideMasters/slideMaster[1-9][0-9]*.xml. """
def related_slide_layout(self, rId: str) -> SlideLayout: """Return |SlideLayout| related to this slide-master by key `rId`.""" return self.related_part(rId).slide_layout
@lazyproperty def slide_master(self): """ The |SlideMaster| object representing this part. """ return SlideMaster(self._element, self)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113"""Main presentation object."""
from __future__ import annotations
from typing import IO, TYPE_CHECKING, cast
from pptx.shared import PartElementProxyfrom pptx.slide import SlideMasters, Slidesfrom pptx.util import lazyproperty
if TYPE_CHECKING: from pptx.oxml.presentation import CT_Presentation, CT_SlideId from pptx.parts.presentation import PresentationPart from pptx.slide import NotesMaster, SlideLayouts from pptx.util import Length
class Presentation(PartElementProxy): """PresentationML (PML) presentation.
Not intended to be constructed directly. Use :func:`pptx.Presentation` to open or create a presentation. """
_element: CT_Presentation part: PresentationPart # pyright: ignore[reportIncompatibleMethodOverride]
@property def core_properties(self): """|CoreProperties| instance for this presentation.
Provides read/write access to the Dublin Core document properties for the presentation. """ return self.part.core_properties
@property def notes_master(self) -> NotesMaster: """Instance of |NotesMaster| for this presentation.
If the presentation does not have a notes master, one is created from a default template and returned. The same single instance is returned on each call. """ return self.part.notes_master
def save(self, file: str | IO[bytes]): """Writes this presentation to `file`.
`file` can be either a file-path or a file-like object open for writing bytes. """ self.part.save(file)
@property def slide_height(self) -> Length | None: """Height of slides in this presentation, in English Metric Units (EMU).
Returns |None| if no slide width is defined. Read/write. """ sldSz = self._element.sldSz if sldSz is None: return None return sldSz.cy
@slide_height.setter def slide_height(self, height: Length): sldSz = self._element.get_or_add_sldSz() sldSz.cy = height
@property def slide_layouts(self) -> SlideLayouts: """|SlideLayouts| collection belonging to the first |SlideMaster| of this presentation.
A presentation can have more than one slide master and each master will have its own set of layouts. This property is a convenience for the common case where the presentation has only a single slide master. """ return self.slide_masters[0].slide_layouts
@property def slide_master(self): """ First |SlideMaster| object belonging to this presentation. Typically, presentations have only a single slide master. This property provides simpler access in that common case. """ return self.slide_masters[0]
@lazyproperty def slide_masters(self) -> SlideMasters: """|SlideMasters| collection of slide-masters belonging to this presentation.""" return SlideMasters(self._element.get_or_add_sldMasterIdLst(), self)
@property def slide_width(self): """ Width of slides in this presentation, in English Metric Units (EMU). Returns |None| if no slide width is defined. Read/write. """ sldSz = self._element.sldSz if sldSz is None: return None return sldSz.cx
@slide_width.setter def slide_width(self, width: Length): sldSz = self._element.get_or_add_sldSz() sldSz.cx = width
@lazyproperty def slides(self): """|Slides| object containing the slides in this presentation.""" sldIdLst = self._element.get_or_add_sldIdLst() self.part.rename_slide_parts([cast("CT_SlideId", sldId).rId for sldId in sldIdLst]) return Slides(sldIdLst, self)1234567891011121314151617181920212223242526"""Objects used across sub-package."""
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING: from pptx.opc.package import XmlPart from pptx.types import ProvidesPart
class Subshape(object): """Provides access to the containing part for drawing elements that occur below a shape.
Access to the part is required for example to add or drop a relationship. Provides `self._parent` attribute to subclasses. """
def __init__(self, parent: ProvidesPart): super(Subshape, self).__init__() self._parent = parent
@property def part(self) -> XmlPart: """The package part containing this object.""" return self._parent.part123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355"""Autoshape-related objects such as Shape and Adjustment."""
from __future__ import annotations
from numbers import Numberfrom typing import TYPE_CHECKING, Iterablefrom xml.sax import saxutils
from pptx.dml.fill import FillFormatfrom pptx.dml.line import LineFormatfrom pptx.enum.shapes import MSO_AUTO_SHAPE_TYPE, MSO_SHAPE_TYPEfrom pptx.shapes.base import BaseShapefrom pptx.spec import autoshape_typesfrom pptx.text.text import TextFramefrom pptx.util import lazyproperty
if TYPE_CHECKING: from pptx.oxml.shapes.autoshape import CT_GeomGuide, CT_PresetGeometry2D, CT_Shape from pptx.spec import AdjustmentValue from pptx.types import ProvidesPart
class Adjustment: """An adjustment value for an autoshape.
An adjustment value corresponds to the position of an adjustment handle on an auto shape. Adjustment handles are the small yellow diamond-shaped handles that appear on certain auto shapes and allow the outline of the shape to be adjusted. For example, a rounded rectangle has an adjustment handle that allows the radius of its corner rounding to be adjusted.
Values are |float| and generally range from 0.0 to 1.0, although the value can be negative or greater than 1.0 in certain circumstances. """
def __init__(self, name: str, def_val: int, actual: int | None = None): super(Adjustment, self).__init__() self.name = name self.def_val = def_val self.actual = actual
@property def effective_value(self) -> float: """Read/write |float| representing normalized adjustment value for this adjustment.
Actual values are a large-ish integer expressed in shape coordinates, nominally between 0 and 100,000. The effective value is normalized to a corresponding value nominally between 0.0 and 1.0. Intuitively this represents the proportion of the width or height of the shape at which the adjustment value is located from its starting point. For simple shapes such as a rounded rectangle, this intuitive correspondence holds. For more complicated shapes and at more extreme shape proportions (e.g. width is much greater than height), the value can become negative or greater than 1.0. """ raw_value = self.actual if self.actual is not None else self.def_val return self._normalize(raw_value)
@effective_value.setter def effective_value(self, value: float): if not isinstance(value, Number): raise ValueError(f"adjustment value must be numeric, got {repr(value)}") self.actual = self._denormalize(value)
@staticmethod def _denormalize(value: float) -> int: """Return integer corresponding to normalized `raw_value` on unit basis of 100,000.
See Adjustment.normalize for additional details. """ return int(value * 100000.0)
@staticmethod def _normalize(raw_value: int) -> float: """Return normalized value for `raw_value`.
A normalized value is a |float| between 0.0 and 1.0 for nominal raw values between 0 and 100,000. Raw values less than 0 and greater than 100,000 are valid and return values calculated on the same unit basis of 100,000. """ return raw_value / 100000.0
@property def val(self) -> int: """Denormalized effective value.
Expressed in shape coordinates, this is suitable for using in the XML. """ return self.actual if self.actual is not None else self.def_val
class AdjustmentCollection: """Sequence of |Adjustment| instances for an auto shape.
Each represents an available adjustment for a shape of its type. Supports `len()` and indexed access, e.g. `shape.adjustments[1] = 0.15`. """
def __init__(self, prstGeom: CT_PresetGeometry2D): super(AdjustmentCollection, self).__init__() self._adjustments_ = self._initialized_adjustments(prstGeom) self._prstGeom = prstGeom
def __getitem__(self, idx: int) -> float: """Provides indexed access, (e.g. 'adjustments[9]').""" return self._adjustments_[idx].effective_value
def __setitem__(self, idx: int, value: float): """Provides item assignment via an indexed expression, e.g. `adjustments[9] = 999.9`.
Causes all adjustment values in collection to be written to the XML. """ self._adjustments_[idx].effective_value = value self._rewrite_guides()
def _initialized_adjustments(self, prstGeom: CT_PresetGeometry2D | None) -> list[Adjustment]: """Return an initialized list of adjustment values based on the contents of `prstGeom`.""" if prstGeom is None: return [] davs = AutoShapeType.default_adjustment_values(prstGeom.prst) adjustments = [Adjustment(name, def_val) for name, def_val in davs] self._update_adjustments_with_actuals(adjustments, prstGeom.gd_lst) return adjustments
def _rewrite_guides(self): """Write `a:gd` elements to the XML, one for each adjustment value.
Any existing guide elements are overwritten. """ guides = [(adj.name, adj.val) for adj in self._adjustments_] self._prstGeom.rewrite_guides(guides)
@staticmethod def _update_adjustments_with_actuals( adjustments: Iterable[Adjustment], guides: Iterable[CT_GeomGuide] ): """Update |Adjustment| instances in `adjustments` with actual values held in `guides`.
`guides` is a list of `a:gd` elements. Guides with a name that does not match an adjustment object are skipped. """ adjustments_by_name = dict((adj.name, adj) for adj in adjustments) for gd in guides: name = gd.name actual = int(gd.fmla[4:]) try: adjustment = adjustments_by_name[name] except KeyError: continue adjustment.actual = actual return
@property def _adjustments(self) -> tuple[Adjustment, ...]: """Sequence of |Adjustment| objects contained in collection.""" return tuple(self._adjustments_)
def __len__(self): """Implement built-in function len()""" return len(self._adjustments_)
class AutoShapeType: """Provides access to metadata for an auto-shape of type identified by `autoshape_type_id`.
Instances are cached, so no more than one instance for a particular auto shape type is in memory.
Instances provide the following attributes:
.. attribute:: autoshape_type_id
Integer uniquely identifying this auto shape type. Corresponds to a value in `pptx.constants.MSO` like `MSO_SHAPE.ROUNDED_RECTANGLE`.
.. attribute:: basename
Base part of shape name for auto shapes of this type, e.g. `Rounded Rectangle` becomes `Rounded Rectangle 99` when the distinguishing integer is added to the shape name.
.. attribute:: prst
String identifier for this auto shape type used in the `a:prstGeom` element.
"""
_instances: dict[MSO_AUTO_SHAPE_TYPE, AutoShapeType] = {}
def __new__(cls, autoshape_type_id: MSO_AUTO_SHAPE_TYPE) -> AutoShapeType: """Only create new instance on first call for content_type.
After that, use cached instance. """ # -- if there's not a matching instance in the cache, create one -- if autoshape_type_id not in cls._instances: inst = super(AutoShapeType, cls).__new__(cls) cls._instances[autoshape_type_id] = inst # -- return the instance; note that __init__() gets called either way -- return cls._instances[autoshape_type_id]
def __init__(self, autoshape_type_id: MSO_AUTO_SHAPE_TYPE): """Initialize attributes from constant values in `pptx.spec`.""" # -- skip loading if this instance is from the cache -- if hasattr(self, "_loaded"): return # -- raise on bad autoshape_type_id -- if autoshape_type_id not in autoshape_types: raise KeyError( "no autoshape type with id '%s' in pptx.spec.autoshape_types" % autoshape_type_id ) # -- otherwise initialize new instance -- autoshape_type = autoshape_types[autoshape_type_id] self._autoshape_type_id = autoshape_type_id self._basename = autoshape_type["basename"] self._loaded = True
@property def autoshape_type_id(self) -> MSO_AUTO_SHAPE_TYPE: """MSO_AUTO_SHAPE_TYPE enumeration member identifying this auto shape type.""" return self._autoshape_type_id
@property def basename(self) -> str: """Base of shape name for this auto shape type.
A shape name is like "Rounded Rectangle 7" and appears as an XML attribute for example at `p:sp/p:nvSpPr/p:cNvPr{name}`. This basename value is the name less the distinguishing integer. This value is escaped because at least one autoshape-type name includes double quotes ('"No" Symbol'). """ return saxutils.escape(self._basename, {'"': """})
@classmethod def default_adjustment_values(cls, prst: MSO_AUTO_SHAPE_TYPE) -> tuple[AdjustmentValue, ...]: """Sequence of (name, value) pair adjustment value defaults for `prst` autoshape-type.""" return autoshape_types[prst]["avLst"]
@classmethod def id_from_prst(cls, prst: str) -> MSO_AUTO_SHAPE_TYPE: """Select auto shape type with matching `prst`.
e.g. `MSO_SHAPE.RECTANGLE` corresponding to preset geometry keyword `"rect"`. """ return MSO_AUTO_SHAPE_TYPE.from_xml(prst)
@property def prst(self): """ Preset geometry identifier string for this auto shape. Used in the `prst` attribute of `a:prstGeom` element to specify the geometry to be used in rendering the shape, for example `'roundRect'`. """ return MSO_AUTO_SHAPE_TYPE.to_xml(self._autoshape_type_id)
class Shape(BaseShape): """A shape that can appear on a slide.
Corresponds to the `p:sp` element that can appear in any of the slide-type parts (slide, slideLayout, slideMaster, notesPage, notesMaster, handoutMaster). """
def __init__(self, sp: CT_Shape, parent: ProvidesPart): super(Shape, self).__init__(sp, parent) self._sp = sp
@lazyproperty def adjustments(self) -> AdjustmentCollection: """Read-only reference to |AdjustmentCollection| instance for this shape.""" return AdjustmentCollection(self._sp.prstGeom)
@property def auto_shape_type(self): """Enumeration value identifying the type of this auto shape.
Like `MSO_SHAPE.ROUNDED_RECTANGLE`. Raises |ValueError| if this shape is not an auto shape. """ if not self._sp.is_autoshape: raise ValueError("shape is not an auto shape") return self._sp.prst
@lazyproperty def fill(self): """|FillFormat| instance for this shape.
Provides access to fill properties such as fill color. """ return FillFormat.from_fill_parent(self._sp.spPr)
def get_or_add_ln(self): """Return the `a:ln` element containing the line format properties XML for this shape.""" return self._sp.get_or_add_ln()
@property def has_text_frame(self) -> bool: """|True| if this shape can contain text. Always |True| for an AutoShape.""" return True
@lazyproperty def line(self): """|LineFormat| instance for this shape.
Provides access to line properties such as line color. """ return LineFormat(self)
@property def ln(self): """The `a:ln` element containing the line format properties such as line color and width.
|None| if no `a:ln` element is present. """ return self._sp.ln
@property def shape_type(self) -> MSO_SHAPE_TYPE: """Unique integer identifying the type of this shape, like `MSO_SHAPE_TYPE.TEXT_BOX`.""" if self.is_placeholder: return MSO_SHAPE_TYPE.PLACEHOLDER if self._sp.has_custom_geometry: return MSO_SHAPE_TYPE.FREEFORM if self._sp.is_autoshape: return MSO_SHAPE_TYPE.AUTO_SHAPE if self._sp.is_textbox: return MSO_SHAPE_TYPE.TEXT_BOX raise NotImplementedError("Shape instance of unrecognized shape type")
@property def text(self) -> str: """Read/write. Text in shape as a single string.
The returned string will contain a newline character (`"\\n"`) separating each paragraph and a vertical-tab (`"\\v"`) character for each line break (soft carriage return) in the shape's text.
Assignment to `text` replaces any text previously contained in the shape, along with any paragraph or font formatting applied to it. A newline character (`"\\n"`) in the assigned text causes a new paragraph to be started. A vertical-tab (`"\\v"`) character in the assigned text causes a line-break (soft carriage-return) to be inserted. (The vertical-tab character appears in clipboard text copied from PowerPoint as its str encoding of line-breaks.) """ return self.text_frame.text
@text.setter def text(self, text: str): self.text_frame.text = text
@property def text_frame(self): """|TextFrame| instance for this shape.
Contains the text of the shape and provides access to text formatting properties. """ txBody = self._sp.get_or_add_txBody() return TextFrame(txBody, self)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244"""Base shape-related objects such as BaseShape."""
from __future__ import annotations
from typing import TYPE_CHECKING, cast
from pptx.action import ActionSettingfrom pptx.dml.effect import ShadowFormatfrom pptx.shared import ElementProxyfrom pptx.util import lazyproperty
if TYPE_CHECKING: from pptx.enum.shapes import MSO_SHAPE_TYPE, PP_PLACEHOLDER from pptx.oxml.shapes import ShapeElement from pptx.oxml.shapes.shared import CT_Placeholder from pptx.parts.slide import BaseSlidePart from pptx.types import ProvidesPart from pptx.util import Length
class BaseShape(object): """Base class for shape objects.
Subclasses include |Shape|, |Picture|, and |GraphicFrame|. """
def __init__(self, shape_elm: ShapeElement, parent: ProvidesPart): super().__init__() self._element = shape_elm self._parent = parent
def __eq__(self, other: object) -> bool: """|True| if this shape object proxies the same element as *other*.
Equality for proxy objects is defined as referring to the same XML element, whether or not they are the same proxy object instance. """ if not isinstance(other, BaseShape): return False return self._element is other._element
def __ne__(self, other: object) -> bool: if not isinstance(other, BaseShape): return True return self._element is not other._element
@lazyproperty def click_action(self) -> ActionSetting: """|ActionSetting| instance providing access to click behaviors.
Click behaviors are hyperlink-like behaviors including jumping to a hyperlink (web page) or to another slide in the presentation. The click action is that defined on the overall shape, not a run of text within the shape. An |ActionSetting| object is always returned, even when no click behavior is defined on the shape. """ cNvPr = self._element._nvXxPr.cNvPr # pyright: ignore[reportPrivateUsage] return ActionSetting(cNvPr, self)
@property def element(self) -> ShapeElement: """`lxml` element for this shape, e.g. a CT_Shape instance.
Note that manipulating this element improperly can produce an invalid presentation file. Make sure you know what you're doing if you use this to change the underlying XML. """ return self._element
@property def has_chart(self) -> bool: """|True| if this shape is a graphic frame containing a chart object.
|False| otherwise. When |True|, the chart object can be accessed using the ``.chart`` property. """ # This implementation is unconditionally False, the True version is # on GraphicFrame subclass. return False
@property def has_table(self) -> bool: """|True| if this shape is a graphic frame containing a table object.
|False| otherwise. When |True|, the table object can be accessed using the ``.table`` property. """ # This implementation is unconditionally False, the True version is # on GraphicFrame subclass. return False
@property def has_text_frame(self) -> bool: """|True| if this shape can contain text.""" # overridden on Shape to return True. Only <p:sp> has text frame return False
@property def height(self) -> Length: """Read/write. Integer distance between top and bottom extents of shape in EMUs.""" return self._element.cy
@height.setter def height(self, value: Length): self._element.cy = value
@property def is_placeholder(self) -> bool: """True if this shape is a placeholder.
A shape is a placeholder if it has a <p:ph> element. """ return self._element.has_ph_elm
@property def left(self) -> Length: """Integer distance of the left edge of this shape from the left edge of the slide.
Read/write. Expressed in English Metric Units (EMU) """ return self._element.x
@left.setter def left(self, value: Length): self._element.x = value
@property def name(self) -> str: """Name of this shape, e.g. 'Picture 7'.""" return self._element.shape_name
@name.setter def name(self, value: str): self._element._nvXxPr.cNvPr.name = value # pyright: ignore[reportPrivateUsage]
@property def part(self) -> BaseSlidePart: """The package part containing this shape.
A |BaseSlidePart| subclass in this case. Access to a slide part should only be required if you are extending the behavior of |pp| API objects. """ return cast("BaseSlidePart", self._parent.part)
@property def placeholder_format(self) -> _PlaceholderFormat: """Provides access to placeholder-specific properties such as placeholder type.
Raises |ValueError| on access if the shape is not a placeholder. """ ph = self._element.ph if ph is None: raise ValueError("shape is not a placeholder") return _PlaceholderFormat(ph)
@property def rotation(self) -> float: """Degrees of clockwise rotation.
Read/write float. Negative values can be assigned to indicate counter-clockwise rotation, e.g. assigning -45.0 will change setting to 315.0. """ return self._element.rot
@rotation.setter def rotation(self, value: float): self._element.rot = value
@lazyproperty def shadow(self) -> ShadowFormat: """|ShadowFormat| object providing access to shadow for this shape.
A |ShadowFormat| object is always returned, even when no shadow is explicitly defined on this shape (i.e. it inherits its shadow behavior). """ return ShadowFormat(self._element.spPr)
@property def shape_id(self) -> int: """Read-only positive integer identifying this shape.
The id of a shape is unique among all shapes on a slide. """ return self._element.shape_id
@property def shape_type(self) -> MSO_SHAPE_TYPE: """A member of MSO_SHAPE_TYPE classifying this shape by type.
Like ``MSO_SHAPE_TYPE.CHART``. Must be implemented by subclasses. """ raise NotImplementedError(f"{type(self).__name__} does not implement `.shape_type`")
@property def top(self) -> Length: """Distance from the top edge of the slide to the top edge of this shape.
Read/write. Expressed in English Metric Units (EMU) """ return self._element.y
@top.setter def top(self, value: Length): self._element.y = value
@property def width(self) -> Length: """Distance between left and right extents of this shape.
Read/write. Expressed in English Metric Units (EMU). """ return self._element.cx
@width.setter def width(self, value: Length): self._element.cx = value
class _PlaceholderFormat(ElementProxy): """Provides properties specific to placeholders, such as the placeholder type.
Accessed via the :attr:`~.BaseShape.placeholder_format` property of a placeholder shape, """
def __init__(self, element: CT_Placeholder): super().__init__(element) self._ph = element
@property def element(self) -> CT_Placeholder: """The `p:ph` element proxied by this object.""" return self._ph
@property def idx(self) -> int: """Integer placeholder 'idx' attribute.""" return self._ph.idx
@property def type(self) -> PP_PLACEHOLDER: """Placeholder type.
A member of the :ref:`PpPlaceholderType` enumeration, e.g. PP_PLACEHOLDER.CHART """ return self._ph.type123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297"""Connector (line) shape and related objects.
A connector is a line shape having end-points that can be connected to otherobjects (but not to other connectors). A connector can be straight, haveelbows, or can be curved."""
from __future__ import annotations
from pptx.dml.line import LineFormatfrom pptx.enum.shapes import MSO_SHAPE_TYPEfrom pptx.shapes.base import BaseShapefrom pptx.util import Emu, lazyproperty
class Connector(BaseShape): """Connector (line) shape.
A connector is a linear shape having end-points that can be connected to other objects (but not to other connectors). A connector can be straight, have elbows, or can be curved. """
def begin_connect(self, shape, cxn_pt_idx): """ **EXPERIMENTAL** - *The current implementation only works properly with rectangular shapes, such as pictures and rectangles. Use with other shape types may cause unexpected visual alignment of the connected end-point and could lead to a load error if cxn_pt_idx exceeds the connection point count available on the connected shape. That said, a quick test should reveal what to expect when using this method with other shape types.*
Connect the beginning of this connector to *shape* at the connection point specified by *cxn_pt_idx*. Each shape has zero or more connection points and they are identified by index, starting with 0. Generally, the first connection point of a shape is at the top center of its bounding box and numbering proceeds counter-clockwise from there. However this is only a convention and may vary, especially with non built-in shapes. """ self._connect_begin_to(shape, cxn_pt_idx) self._move_begin_to_cxn(shape, cxn_pt_idx)
@property def begin_x(self): """ Return the X-position of the begin point of this connector, in English Metric Units (as a |Length| object). """ cxnSp = self._element x, cx, flipH = cxnSp.x, cxnSp.cx, cxnSp.flipH begin_x = x + cx if flipH else x return Emu(begin_x)
@begin_x.setter def begin_x(self, value): cxnSp = self._element x, cx, flipH, new_x = cxnSp.x, cxnSp.cx, cxnSp.flipH, int(value)
if flipH: old_x = x + cx dx = abs(new_x - old_x) if new_x >= old_x: cxnSp.cx = cx + dx elif dx <= cx: cxnSp.cx = cx - dx else: cxnSp.flipH = False cxnSp.x = new_x cxnSp.cx = dx - cx else: dx = abs(new_x - x) if new_x <= x: cxnSp.x = new_x cxnSp.cx = cx + dx elif dx <= cx: cxnSp.x = new_x cxnSp.cx = cx - dx else: cxnSp.flipH = True cxnSp.x = x + cx cxnSp.cx = dx - cx
@property def begin_y(self): """ Return the Y-position of the begin point of this connector, in English Metric Units (as a |Length| object). """ cxnSp = self._element y, cy, flipV = cxnSp.y, cxnSp.cy, cxnSp.flipV begin_y = y + cy if flipV else y return Emu(begin_y)
@begin_y.setter def begin_y(self, value): cxnSp = self._element y, cy, flipV, new_y = cxnSp.y, cxnSp.cy, cxnSp.flipV, int(value)
if flipV: old_y = y + cy dy = abs(new_y - old_y) if new_y >= old_y: cxnSp.cy = cy + dy elif dy <= cy: cxnSp.cy = cy - dy else: cxnSp.flipV = False cxnSp.y = new_y cxnSp.cy = dy - cy else: dy = abs(new_y - y) if new_y <= y: cxnSp.y = new_y cxnSp.cy = cy + dy elif dy <= cy: cxnSp.y = new_y cxnSp.cy = cy - dy else: cxnSp.flipV = True cxnSp.y = y + cy cxnSp.cy = dy - cy
def end_connect(self, shape, cxn_pt_idx): """ **EXPERIMENTAL** - *The current implementation only works properly with rectangular shapes, such as pictures and rectangles. Use with other shape types may cause unexpected visual alignment of the connected end-point and could lead to a load error if cxn_pt_idx exceeds the connection point count available on the connected shape. That said, a quick test should reveal what to expect when using this method with other shape types.*
Connect the ending of this connector to *shape* at the connection point specified by *cxn_pt_idx*. """ self._connect_end_to(shape, cxn_pt_idx) self._move_end_to_cxn(shape, cxn_pt_idx)
@property def end_x(self): """ Return the X-position of the end point of this connector, in English Metric Units (as a |Length| object). """ cxnSp = self._element x, cx, flipH = cxnSp.x, cxnSp.cx, cxnSp.flipH end_x = x if flipH else x + cx return Emu(end_x)
@end_x.setter def end_x(self, value): cxnSp = self._element x, cx, flipH, new_x = cxnSp.x, cxnSp.cx, cxnSp.flipH, int(value)
if flipH: dx = abs(new_x - x) if new_x <= x: cxnSp.x = new_x cxnSp.cx = cx + dx elif dx <= cx: cxnSp.x = new_x cxnSp.cx = cx - dx else: cxnSp.flipH = False cxnSp.x = x + cx cxnSp.cx = dx - cx else: old_x = x + cx dx = abs(new_x - old_x) if new_x >= old_x: cxnSp.cx = cx + dx elif dx <= cx: cxnSp.cx = cx - dx else: cxnSp.flipH = True cxnSp.x = new_x cxnSp.cx = dx - cx
@property def end_y(self): """ Return the Y-position of the end point of this connector, in English Metric Units (as a |Length| object). """ cxnSp = self._element y, cy, flipV = cxnSp.y, cxnSp.cy, cxnSp.flipV end_y = y if flipV else y + cy return Emu(end_y)
@end_y.setter def end_y(self, value): cxnSp = self._element y, cy, flipV, new_y = cxnSp.y, cxnSp.cy, cxnSp.flipV, int(value)
if flipV: dy = abs(new_y - y) if new_y <= y: cxnSp.y = new_y cxnSp.cy = cy + dy elif dy <= cy: cxnSp.y = new_y cxnSp.cy = cy - dy else: cxnSp.flipV = False cxnSp.y = y + cy cxnSp.cy = dy - cy else: old_y = y + cy dy = abs(new_y - old_y) if new_y >= old_y: cxnSp.cy = cy + dy elif dy <= cy: cxnSp.cy = cy - dy else: cxnSp.flipV = True cxnSp.y = new_y cxnSp.cy = dy - cy
def get_or_add_ln(self): """Helper method required by |LineFormat|.""" return self._element.spPr.get_or_add_ln()
@lazyproperty def line(self): """|LineFormat| instance for this connector.
Provides access to line properties such as line color, width, and line style. """ return LineFormat(self)
@property def ln(self): """Helper method required by |LineFormat|.
The ``<a:ln>`` element containing the line format properties such as line color and width. |None| if no `<a:ln>` element is present. """ return self._element.spPr.ln
@property def shape_type(self): """Member of `MSO_SHAPE_TYPE` identifying the type of this shape.
Unconditionally `MSO_SHAPE_TYPE.LINE` for a `Connector` object. """ return MSO_SHAPE_TYPE.LINE
def _connect_begin_to(self, shape, cxn_pt_idx): """ Add or update a stCxn element for this connector that connects its begin point to the connection point of *shape* specified by *cxn_pt_idx*. """ cNvCxnSpPr = self._element.nvCxnSpPr.cNvCxnSpPr stCxn = cNvCxnSpPr.get_or_add_stCxn() stCxn.id = shape.shape_id stCxn.idx = cxn_pt_idx
def _connect_end_to(self, shape, cxn_pt_idx): """ Add or update an endCxn element for this connector that connects its end point to the connection point of *shape* specified by *cxn_pt_idx*. """ cNvCxnSpPr = self._element.nvCxnSpPr.cNvCxnSpPr endCxn = cNvCxnSpPr.get_or_add_endCxn() endCxn.id = shape.shape_id endCxn.idx = cxn_pt_idx
def _move_begin_to_cxn(self, shape, cxn_pt_idx): """ Move the begin point of this connector to coordinates of the connection point of *shape* specified by *cxn_pt_idx*. """ x, y, cx, cy = shape.left, shape.top, shape.width, shape.height self.begin_x, self.begin_y = { 0: (int(x + cx / 2), y), 1: (x, int(y + cy / 2)), 2: (int(x + cx / 2), y + cy), 3: (x + cx, int(y + cy / 2)), }[cxn_pt_idx]
def _move_end_to_cxn(self, shape, cxn_pt_idx): """ Move the end point of this connector to the coordinates of the connection point of *shape* specified by *cxn_pt_idx*. """ x, y, cx, cy = shape.left, shape.top, shape.width, shape.height self.end_x, self.end_y = { 0: (int(x + cx / 2), y), 1: (x, int(y + cy / 2)), 2: (int(x + cx / 2), y + cy), 3: (x + cx, int(y + cy / 2)), }[cxn_pt_idx]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338"""Objects related to construction of freeform shapes."""
from __future__ import annotations
from collections.abc import Sequencefrom typing import TYPE_CHECKING, Iterable, Iterator
from pptx.util import Emu, lazyproperty
if TYPE_CHECKING: from typing_extensions import TypeAlias
from pptx.oxml.shapes.autoshape import ( CT_Path2D, CT_Path2DClose, CT_Path2DLineTo, CT_Path2DMoveTo, CT_Shape, ) from pptx.shapes.shapetree import _BaseGroupShapes # pyright: ignore[reportPrivateUsage] from pptx.util import Length
CT_DrawingOperation: TypeAlias = "CT_Path2DClose | CT_Path2DLineTo | CT_Path2DMoveTo"DrawingOperation: TypeAlias = "_LineSegment | _MoveTo | _Close"
class FreeformBuilder(Sequence[DrawingOperation]): """Allows a freeform shape to be specified and created.
The initial pen position is provided on construction. From there, drawing proceeds using successive calls to draw line segments. The freeform shape may be closed by calling the :meth:`close` method.
A shape may have more than one contour, in which case overlapping areas are "subtracted". A contour is a sequence of line segments beginning with a "move-to" operation. A move-to operation is automatically inserted in each new freeform; additional move-to ops can be inserted with the `.move_to()` method. """
def __init__( self, shapes: _BaseGroupShapes, start_x: Length, start_y: Length, x_scale: float, y_scale: float, ): super(FreeformBuilder, self).__init__() self._shapes = shapes self._start_x = start_x self._start_y = start_y self._x_scale = x_scale self._y_scale = y_scale
def __getitem__( # pyright: ignore[reportIncompatibleMethodOverride] self, idx: int ) -> DrawingOperation: return self._drawing_operations.__getitem__(idx)
def __iter__(self) -> Iterator[DrawingOperation]: return self._drawing_operations.__iter__()
def __len__(self): return self._drawing_operations.__len__()
@classmethod def new( cls, shapes: _BaseGroupShapes, start_x: float, start_y: float, x_scale: float, y_scale: float, ): """Return a new |FreeformBuilder| object.
The initial pen location is specified (in local coordinates) by (`start_x`, `start_y`). """ return cls(shapes, Emu(int(round(start_x))), Emu(int(round(start_y))), x_scale, y_scale)
def add_line_segments(self, vertices: Iterable[tuple[float, float]], close: bool = True): """Add a straight line segment to each point in `vertices`.
`vertices` must be an iterable of (x, y) pairs (2-tuples). Each x and y value is rounded to the nearest integer before use. The optional `close` parameter determines whether the resulting contour is `closed` or left `open`.
Returns this |FreeformBuilder| object so it can be used in chained calls. """ for x, y in vertices: self._add_line_segment(x, y) if close: self._add_close() return self
def convert_to_shape(self, origin_x: Length = Emu(0), origin_y: Length = Emu(0)): """Return new freeform shape positioned relative to specified offset.
`origin_x` and `origin_y` locate the origin of the local coordinate system in slide coordinates (EMU), perhaps most conveniently by use of a |Length| object.
Note that this method may be called more than once to add multiple shapes of the same geometry in different locations on the slide. """ sp = self._add_freeform_sp(origin_x, origin_y) path = self._start_path(sp) for drawing_operation in self: drawing_operation.apply_operation_to(path) return self._shapes._shape_factory(sp) # pyright: ignore[reportPrivateUsage]
def move_to(self, x: float, y: float): """Move pen to (x, y) (local coordinates) without drawing line.
Returns this |FreeformBuilder| object so it can be used in chained calls. """ self._drawing_operations.append(_MoveTo.new(self, x, y)) return self
@property def shape_offset_x(self) -> Length: """Return x distance of shape origin from local coordinate origin.
The returned integer represents the leftmost extent of the freeform shape, in local coordinates. Note that the bounding box of the shape need not start at the local origin. """ min_x = self._start_x for drawing_operation in self: if isinstance(drawing_operation, _Close): continue min_x = min(min_x, drawing_operation.x) return Emu(min_x)
@property def shape_offset_y(self) -> Length: """Return y distance of shape origin from local coordinate origin.
The returned integer represents the topmost extent of the freeform shape, in local coordinates. Note that the bounding box of the shape need not start at the local origin. """ min_y = self._start_y for drawing_operation in self: if isinstance(drawing_operation, _Close): continue min_y = min(min_y, drawing_operation.y) return Emu(min_y)
def _add_close(self): """Add a close |_Close| operation to the drawing sequence.""" self._drawing_operations.append(_Close.new())
def _add_freeform_sp(self, origin_x: Length, origin_y: Length): """Add a freeform `p:sp` element having no drawing elements.
`origin_x` and `origin_y` are specified in slide coordinates, and represent the location of the local coordinates origin on the slide. """ spTree = self._shapes._spTree # pyright: ignore[reportPrivateUsage] return spTree.add_freeform_sp( origin_x + self._left, origin_y + self._top, self._width, self._height )
def _add_line_segment(self, x: float, y: float) -> None: """Add a |_LineSegment| operation to the drawing sequence.""" self._drawing_operations.append(_LineSegment.new(self, x, y))
@lazyproperty def _drawing_operations(self) -> list[DrawingOperation]: """Return the sequence of drawing operation objects for freeform.""" return []
@property def _dx(self) -> Length: """Return width of this shape's path in local units.""" min_x = max_x = self._start_x for drawing_operation in self: if isinstance(drawing_operation, _Close): continue min_x = min(min_x, drawing_operation.x) max_x = max(max_x, drawing_operation.x) return Emu(max_x - min_x)
@property def _dy(self) -> Length: """Return integer height of this shape's path in local units.""" min_y = max_y = self._start_y for drawing_operation in self: if isinstance(drawing_operation, _Close): continue min_y = min(min_y, drawing_operation.y) max_y = max(max_y, drawing_operation.y) return Emu(max_y - min_y)
@property def _height(self): """Return vertical size of this shape's path in slide coordinates.
This value is based on the actual extents of the shape and does not include any positioning offset. """ return int(round(self._dy * self._y_scale))
@property def _left(self): """Return leftmost extent of this shape's path in slide coordinates.
Note that this value does not include any positioning offset; it assumes the drawing (local) coordinate origin is at (0, 0) on the slide. """ return int(round(self.shape_offset_x * self._x_scale))
def _local_to_shape(self, local_x: Length, local_y: Length) -> tuple[Length, Length]: """Translate local coordinates point to shape coordinates.
Shape coordinates have the same unit as local coordinates, but are offset such that the origin of the shape coordinate system (0, 0) is located at the top-left corner of the shape bounding box. """ return Emu(local_x - self.shape_offset_x), Emu(local_y - self.shape_offset_y)
def _start_path(self, sp: CT_Shape) -> CT_Path2D: """Return a newly created `a:path` element added to `sp`.
The returned `a:path` element has an `a:moveTo` element representing the shape starting point as its only child. """ path = sp.add_path(w=self._dx, h=self._dy) path.add_moveTo(*self._local_to_shape(self._start_x, self._start_y)) return path
@property def _top(self): """Return topmost extent of this shape's path in slide coordinates.
Note that this value does not include any positioning offset; it assumes the drawing (local) coordinate origin is located at slide coordinates (0, 0) (top-left corner of slide). """ return int(round(self.shape_offset_y * self._y_scale))
@property def _width(self): """Return width of this shape's path in slide coordinates.
This value is based on the actual extents of the shape path and does not include any positioning offset. """ return int(round(self._dx * self._x_scale))
class _BaseDrawingOperation(object): """Base class for freeform drawing operations.
A drawing operation has at least one location (x, y) in local coordinates. """
def __init__(self, freeform_builder: FreeformBuilder, x: Length, y: Length): super(_BaseDrawingOperation, self).__init__() self._freeform_builder = freeform_builder self._x = x self._y = y
def apply_operation_to(self, path: CT_Path2D) -> CT_DrawingOperation: """Add the XML element(s) implementing this operation to `path`.
Must be implemented by each subclass. """ raise NotImplementedError("must be implemented by each subclass")
@property def x(self) -> Length: """Return the horizontal (x) target location of this operation.
The returned value is an integer in local coordinates. """ return self._x
@property def y(self) -> Length: """Return the vertical (y) target location of this operation.
The returned value is an integer in local coordinates. """ return self._y
class _Close(object): """Specifies adding a `<a:close/>` element to the current contour."""
@classmethod def new(cls) -> _Close: """Return a new _Close object.""" return cls()
def apply_operation_to(self, path: CT_Path2D) -> CT_Path2DClose: """Add `a:close` element to `path`.""" return path.add_close()
class _LineSegment(_BaseDrawingOperation): """Specifies a straight line segment ending at the specified point."""
@classmethod def new(cls, freeform_builder: FreeformBuilder, x: float, y: float) -> _LineSegment: """Return a new _LineSegment object ending at point *(x, y)*.
Both `x` and `y` are rounded to the nearest integer before use. """ return cls(freeform_builder, Emu(int(round(x))), Emu(int(round(y))))
def apply_operation_to(self, path: CT_Path2D) -> CT_Path2DLineTo: """Add `a:lnTo` element to `path` for this line segment.
Returns the `a:lnTo` element newly added to the path. """ return path.add_lnTo( Emu(self._x - self._freeform_builder.shape_offset_x), Emu(self._y - self._freeform_builder.shape_offset_y), )
class _MoveTo(_BaseDrawingOperation): """Specifies a new pen position."""
@classmethod def new(cls, freeform_builder: FreeformBuilder, x: float, y: float) -> _MoveTo: """Return a new _MoveTo object for move to point `(x, y)`.
Both `x` and `y` are rounded to the nearest integer before use. """ return cls(freeform_builder, Emu(int(round(x))), Emu(int(round(y))))
def apply_operation_to(self, path: CT_Path2D) -> CT_Path2DMoveTo: """Add `a:moveTo` element to `path` for this line segment.""" return path.add_moveTo( Emu(self._x - self._freeform_builder.shape_offset_x), Emu(self._y - self._freeform_builder.shape_offset_y), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166"""Graphic Frame shape and related objects.
A graphic frame is a common container for table, chart, smart art, and mediaobjects."""
from __future__ import annotations
from typing import TYPE_CHECKING, cast
from pptx.enum.shapes import MSO_SHAPE_TYPEfrom pptx.shapes.base import BaseShapefrom pptx.shared import ParentedElementProxyfrom pptx.spec import ( GRAPHIC_DATA_URI_CHART, GRAPHIC_DATA_URI_OLEOBJ, GRAPHIC_DATA_URI_TABLE,)from pptx.table import Tablefrom pptx.util import lazyproperty
if TYPE_CHECKING: from pptx.chart.chart import Chart from pptx.dml.effect import ShadowFormat from pptx.oxml.shapes.graphfrm import CT_GraphicalObjectData, CT_GraphicalObjectFrame from pptx.parts.chart import ChartPart from pptx.parts.slide import BaseSlidePart from pptx.types import ProvidesPart
class GraphicFrame(BaseShape): """Container shape for table, chart, smart art, and media objects.
Corresponds to a `p:graphicFrame` element in the shape tree. """
def __init__(self, graphicFrame: CT_GraphicalObjectFrame, parent: ProvidesPart): super().__init__(graphicFrame, parent) self._graphicFrame = graphicFrame
@property def chart(self) -> Chart: """The |Chart| object containing the chart in this graphic frame.
Raises |ValueError| if this graphic frame does not contain a chart. """ if not self.has_chart: raise ValueError("shape does not contain a chart") return self.chart_part.chart
@property def chart_part(self) -> ChartPart: """The |ChartPart| object containing the chart in this graphic frame.""" chart_rId = self._graphicFrame.chart_rId if chart_rId is None: raise ValueError("this graphic frame does not contain a chart") return cast("ChartPart", self.part.related_part(chart_rId))
@property def has_chart(self) -> bool: """|True| if this graphic frame contains a chart object. |False| otherwise.
When |True|, the chart object can be accessed using the `.chart` property. """ return self._graphicFrame.graphicData_uri == GRAPHIC_DATA_URI_CHART
@property def has_table(self) -> bool: """|True| if this graphic frame contains a table object, |False| otherwise.
When |True|, the table object can be accessed using the `.table` property. """ return self._graphicFrame.graphicData_uri == GRAPHIC_DATA_URI_TABLE
@property def ole_format(self) -> _OleFormat: """_OleFormat object for this graphic-frame shape.
Raises `ValueError` on a GraphicFrame instance that does not contain an OLE object.
An shape that contains an OLE object will have `.shape_type` of either `EMBEDDED_OLE_OBJECT` or `LINKED_OLE_OBJECT`. """ if not self._graphicFrame.has_oleobj: raise ValueError("not an OLE-object shape") return _OleFormat(self._graphicFrame.graphicData, self._parent)
@lazyproperty def shadow(self) -> ShadowFormat: """Unconditionally raises |NotImplementedError|.
Access to the shadow effect for graphic-frame objects is content-specific (i.e. different for charts, tables, etc.) and has not yet been implemented. """ raise NotImplementedError("shadow property on GraphicFrame not yet supported")
@property def shape_type(self) -> MSO_SHAPE_TYPE: """Optional member of `MSO_SHAPE_TYPE` identifying the type of this shape.
Possible values are `MSO_SHAPE_TYPE.CHART`, `MSO_SHAPE_TYPE.TABLE`, `MSO_SHAPE_TYPE.EMBEDDED_OLE_OBJECT`, `MSO_SHAPE_TYPE.LINKED_OLE_OBJECT`.
This value is `None` when none of these four types apply, for example when the shape contains SmartArt. """ graphicData_uri = self._graphicFrame.graphicData_uri if graphicData_uri == GRAPHIC_DATA_URI_CHART: return MSO_SHAPE_TYPE.CHART elif graphicData_uri == GRAPHIC_DATA_URI_TABLE: return MSO_SHAPE_TYPE.TABLE elif graphicData_uri == GRAPHIC_DATA_URI_OLEOBJ: return ( MSO_SHAPE_TYPE.EMBEDDED_OLE_OBJECT if self._graphicFrame.is_embedded_ole_obj else MSO_SHAPE_TYPE.LINKED_OLE_OBJECT ) else: return None # pyright: ignore[reportReturnType]
@property def table(self) -> Table: """The |Table| object contained in this graphic frame.
Raises |ValueError| if this graphic frame does not contain a table. """ if not self.has_table: raise ValueError("shape does not contain a table") tbl = self._graphicFrame.graphic.graphicData.tbl return Table(tbl, self)
class _OleFormat(ParentedElementProxy): """Provides attributes on an embedded OLE object."""
part: BaseSlidePart # pyright: ignore[reportIncompatibleMethodOverride]
def __init__(self, graphicData: CT_GraphicalObjectData, parent: ProvidesPart): super().__init__(graphicData, parent) self._graphicData = graphicData
@property def blob(self) -> bytes | None: """Optional bytes of OLE object, suitable for loading or saving as a file.
This value is `None` if the embedded object does not represent a "file". """ blob_rId = self._graphicData.blob_rId if blob_rId is None: return None return self.part.related_part(blob_rId).blob
@property def prog_id(self) -> str | None: """str "progId" attribute of this embedded OLE object.
The progId is a str like "Excel.Sheet.12" that identifies the "file-type" of the embedded object, or perhaps more precisely, the application (aka. "server" in OLE parlance) to be used to open this object. """ return self._graphicData.progId
@property def show_as_icon(self) -> bool | None: """True when OLE object should appear as an icon (rather than preview).""" return self._graphicData.showAsIcon123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869"""GroupShape and related objects."""
from __future__ import annotations
from typing import TYPE_CHECKING
from pptx.dml.effect import ShadowFormatfrom pptx.enum.shapes import MSO_SHAPE_TYPEfrom pptx.shapes.base import BaseShapefrom pptx.util import lazyproperty
if TYPE_CHECKING: from pptx.action import ActionSetting from pptx.oxml.shapes.groupshape import CT_GroupShape from pptx.shapes.shapetree import GroupShapes from pptx.types import ProvidesPart
class GroupShape(BaseShape): """A shape that acts as a container for other shapes."""
def __init__(self, grpSp: CT_GroupShape, parent: ProvidesPart): super().__init__(grpSp, parent) self._grpSp = grpSp
@lazyproperty def click_action(self) -> ActionSetting: """Unconditionally raises `TypeError`.
A group shape cannot have a click action or hover action. """ raise TypeError("a group shape cannot have a click action")
@property def has_text_frame(self) -> bool: """Unconditionally |False|.
A group shape does not have a textframe and cannot itself contain text. This does not impact the ability of shapes contained by the group to each have their own text. """ return False
@lazyproperty def shadow(self) -> ShadowFormat: """|ShadowFormat| object representing shadow effect for this group.
A |ShadowFormat| object is always returned, even when no shadow is explicitly defined on this group shape (i.e. when the group inherits its shadow behavior). """ return ShadowFormat(self._grpSp.grpSpPr)
@property def shape_type(self) -> MSO_SHAPE_TYPE: """Member of :ref:`MsoShapeType` identifying the type of this shape.
Unconditionally `MSO_SHAPE_TYPE.GROUP` in this case """ return MSO_SHAPE_TYPE.GROUP
@lazyproperty def shapes(self) -> GroupShapes: """|GroupShapes| object for this group.
The |GroupShapes| object provides access to the group's member shapes and provides methods for adding new ones. """ from pptx.shapes.shapetree import GroupShapes
return GroupShapes(self._element, self)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203"""Shapes based on the `p:pic` element, including Picture and Movie."""
from __future__ import annotations
from typing import TYPE_CHECKING
from pptx.dml.line import LineFormatfrom pptx.enum.shapes import MSO_SHAPE, MSO_SHAPE_TYPE, PP_MEDIA_TYPEfrom pptx.shapes.base import BaseShapefrom pptx.shared import ParentedElementProxyfrom pptx.util import lazyproperty
if TYPE_CHECKING: from pptx.oxml.shapes.picture import CT_Picture from pptx.oxml.shapes.shared import CT_LineProperties from pptx.types import ProvidesPart
class _BasePicture(BaseShape): """Base class for shapes based on a `p:pic` element."""
def __init__(self, pic: CT_Picture, parent: ProvidesPart): super(_BasePicture, self).__init__(pic, parent) self._pic = pic
@property def crop_bottom(self) -> float: """|float| representing relative portion cropped from shape bottom.
Read/write. 1.0 represents 100%. For example, 25% is represented by 0.25. Negative values are valid as are values greater than 1.0. """ return self._pic.srcRect_b
@crop_bottom.setter def crop_bottom(self, value: float): self._pic.srcRect_b = value
@property def crop_left(self) -> float: """|float| representing relative portion cropped from left of shape.
Read/write. 1.0 represents 100%. A negative value extends the side beyond the image boundary. """ return self._pic.srcRect_l
@crop_left.setter def crop_left(self, value: float): self._pic.srcRect_l = value
@property def crop_right(self) -> float: """|float| representing relative portion cropped from right of shape.
Read/write. 1.0 represents 100%. """ return self._pic.srcRect_r
@crop_right.setter def crop_right(self, value: float): self._pic.srcRect_r = value
@property def crop_top(self) -> float: """|float| representing relative portion cropped from shape top.
Read/write. 1.0 represents 100%. """ return self._pic.srcRect_t
@crop_top.setter def crop_top(self, value: float): self._pic.srcRect_t = value
def get_or_add_ln(self): """Return the `a:ln` element for this `p:pic`-based image.
The `a:ln` element contains the line format properties XML. """ return self._pic.get_or_add_ln()
@lazyproperty def line(self) -> LineFormat: """Provides access to properties of the picture outline, such as its color and width.""" return LineFormat(self)
@property def ln(self) -> CT_LineProperties | None: """The `a:ln` element for this `p:pic`.
Contains the line format properties such as line color and width. |None| if no `a:ln` element is present. """ return self._pic.ln
class Movie(_BasePicture): """A movie shape, one that places a video on a slide.
Like |Picture|, a movie shape is based on the `p:pic` element. A movie is composed of a video and a *poster frame*, the placeholder image that represents the video before it is played. """
@lazyproperty def media_format(self) -> _MediaFormat: """The |_MediaFormat| object for this movie.
The |_MediaFormat| object provides access to formatting properties for the movie. """ return _MediaFormat(self._pic, self)
@property def media_type(self) -> PP_MEDIA_TYPE: """Member of :ref:`PpMediaType` describing this shape.
The return value is unconditionally `PP_MEDIA_TYPE.MOVIE` in this case. """ return PP_MEDIA_TYPE.MOVIE
@property def poster_frame(self): """Return |Image| object containing poster frame for this movie.
Returns |None| if this movie has no poster frame (uncommon). """ slide_part, rId = self.part, self._pic.blip_rId if rId is None: return None return slide_part.get_image(rId)
@property def shape_type(self) -> MSO_SHAPE_TYPE: """Return member of :ref:`MsoShapeType` describing this shape.
The return value is unconditionally `MSO_SHAPE_TYPE.MEDIA` in this case. """ return MSO_SHAPE_TYPE.MEDIA
class Picture(_BasePicture): """A picture shape, one that places an image on a slide.
Based on the `p:pic` element. """
@property def auto_shape_type(self) -> MSO_SHAPE | None: """Member of MSO_SHAPE indicating masking shape.
A picture can be masked by any of the so-called "auto-shapes" available in PowerPoint, such as an ellipse or triangle. When a picture is masked by a shape, the shape assumes the same dimensions as the picture and the portion of the picture outside the shape boundaries does not appear. Note the default value for a newly-inserted picture is `MSO_AUTO_SHAPE_TYPE.RECTANGLE`, which performs no cropping because the extents of the rectangle exactly correspond to the extents of the picture.
The available shapes correspond to the members of :ref:`MsoAutoShapeType`.
The return value can also be |None|, indicating the picture either has no geometry (not expected) or has custom geometry, like a freeform shape. A picture with no geometry will have no visible representation on the slide, although it can be selected. This is because without geometry, there is no "inside-the-shape" for it to appear in. """ prstGeom = self._pic.spPr.prstGeom if prstGeom is None: # ---generally means cropped with freeform--- return None return prstGeom.prst
@auto_shape_type.setter def auto_shape_type(self, member: MSO_SHAPE): MSO_SHAPE.validate(member) spPr = self._pic.spPr prstGeom = spPr.prstGeom if prstGeom is None: spPr._remove_custGeom() # pyright: ignore[reportPrivateUsage] prstGeom = spPr._add_prstGeom() # pyright: ignore[reportPrivateUsage] prstGeom.prst = member
@property def image(self): """The |Image| object for this picture.
Provides access to the properties and bytes of the image in this picture shape. """ slide_part, rId = self.part, self._pic.blip_rId if rId is None: raise ValueError("no embedded image") return slide_part.get_image(rId)
@property def shape_type(self) -> MSO_SHAPE_TYPE: """Unconditionally `MSO_SHAPE_TYPE.PICTURE` in this case.""" return MSO_SHAPE_TYPE.PICTURE
class _MediaFormat(ParentedElementProxy): """Provides access to formatting properties for a Media object.
Media format properties are things like start point, volume, and compression type. """123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407"""Placeholder-related objects.
Specific to shapes having a `p:ph` element. A placeholder has distinct behaviorsdepending on whether it appears on a slide, layout, or master. Hence there is anon-trivial class inheritance structure."""
from __future__ import annotations
from typing import TYPE_CHECKING
from pptx.enum.shapes import MSO_SHAPE_TYPE, PP_PLACEHOLDERfrom pptx.oxml.shapes.graphfrm import CT_GraphicalObjectFramefrom pptx.oxml.shapes.picture import CT_Picturefrom pptx.shapes.autoshape import Shapefrom pptx.shapes.graphfrm import GraphicFramefrom pptx.shapes.picture import Picturefrom pptx.util import Emu
if TYPE_CHECKING: from pptx.oxml.shapes.autoshape import CT_Shape
class _InheritsDimensions(object): """ Mixin class that provides inherited dimension behavior. Specifically, left, top, width, and height report the value from the layout placeholder where they would have otherwise reported |None|. This behavior is distinctive to placeholders. :meth:`_base_placeholder` must be overridden by all subclasses to provide lookup of the appropriate base placeholder to inherit from. """
@property def height(self): """ The effective height of this placeholder shape; its directly-applied height if it has one, otherwise the height of its parent layout placeholder. """ return self._effective_value("height")
@height.setter def height(self, value): self._element.cy = value
@property def left(self): """ The effective left of this placeholder shape; its directly-applied left if it has one, otherwise the left of its parent layout placeholder. """ return self._effective_value("left")
@left.setter def left(self, value): self._element.x = value
@property def shape_type(self): """ Member of :ref:`MsoShapeType` specifying the type of this shape. Unconditionally ``MSO_SHAPE_TYPE.PLACEHOLDER`` in this case. Read-only. """ return MSO_SHAPE_TYPE.PLACEHOLDER
@property def top(self): """ The effective top of this placeholder shape; its directly-applied top if it has one, otherwise the top of its parent layout placeholder. """ return self._effective_value("top")
@top.setter def top(self, value): self._element.y = value
@property def width(self): """ The effective width of this placeholder shape; its directly-applied width if it has one, otherwise the width of its parent layout placeholder. """ return self._effective_value("width")
@width.setter def width(self, value): self._element.cx = value
@property def _base_placeholder(self): """ Return the layout or master placeholder shape this placeholder inherits from. Not to be confused with an instance of |BasePlaceholder| (necessarily). """ raise NotImplementedError("Must be implemented by all subclasses.")
def _effective_value(self, attr_name): """ The effective value of *attr_name* on this placeholder shape; its directly-applied value if it has one, otherwise the value on the layout placeholder it inherits from. """ directly_applied_value = getattr(super(_InheritsDimensions, self), attr_name) if directly_applied_value is not None: return directly_applied_value return self._inherited_value(attr_name)
def _inherited_value(self, attr_name): """ Return the attribute value, e.g. 'width' of the base placeholder this placeholder inherits from. """ base_placeholder = self._base_placeholder if base_placeholder is None: return None inherited_value = getattr(base_placeholder, attr_name) return inherited_value
class _BaseSlidePlaceholder(_InheritsDimensions, Shape): """Base class for placeholders on slides.
Provides common behaviors such as inherited dimensions. """
@property def is_placeholder(self): """ Boolean indicating whether this shape is a placeholder. Unconditionally |True| in this case. """ return True
@property def shape_type(self): """ Member of :ref:`MsoShapeType` specifying the type of this shape. Unconditionally ``MSO_SHAPE_TYPE.PLACEHOLDER`` in this case. Read-only. """ return MSO_SHAPE_TYPE.PLACEHOLDER
@property def _base_placeholder(self): """ Return the layout placeholder this slide placeholder inherits from. Not to be confused with an instance of |BasePlaceholder| (necessarily). """ layout, idx = self.part.slide_layout, self._element.ph_idx return layout.placeholders.get(idx=idx)
def _replace_placeholder_with(self, element): """ Substitute *element* for this placeholder element in the shapetree. This placeholder's `._element` attribute is set to |None| and its original element is free for garbage collection. Any attribute access (including a method call) on this placeholder after this call raises |AttributeError|. """ element._nvXxPr.nvPr._insert_ph(self._element.ph) self._element.addprevious(element) self._element.getparent().remove(self._element) self._element = None
class BasePlaceholder(Shape): """ NOTE: This class is deprecated and will be removed from a future release along with the properties *idx*, *orient*, *ph_type*, and *sz*. The *idx* property will be available via the .placeholder_format property. The others will be accessed directly from the oxml layer as they are only used for internal purposes.
Base class for placeholder subclasses that differentiate the varying behaviors of placeholders on a master, layout, and slide. """
@property def idx(self): """ Integer placeholder 'idx' attribute, e.g. 0 """ return self._sp.ph_idx
@property def orient(self): """ Placeholder orientation, e.g. ST_Direction.HORZ """ return self._sp.ph_orient
@property def ph_type(self): """ Placeholder type, e.g. PP_PLACEHOLDER.CENTER_TITLE """ return self._sp.ph_type
@property def sz(self): """ Placeholder 'sz' attribute, e.g. ST_PlaceholderSize.FULL """ return self._sp.ph_sz
class LayoutPlaceholder(_InheritsDimensions, Shape): """Placeholder shape on a slide layout.
Provides differentiated behavior for slide layout placeholders, in particular, inheriting shape properties from the master placeholder having the same type, when a matching one exists. """
element: CT_Shape # pyright: ignore[reportIncompatibleMethodOverride]
@property def _base_placeholder(self): """ Return the master placeholder this layout placeholder inherits from. """ base_ph_type = { PP_PLACEHOLDER.BODY: PP_PLACEHOLDER.BODY, PP_PLACEHOLDER.CHART: PP_PLACEHOLDER.BODY, PP_PLACEHOLDER.BITMAP: PP_PLACEHOLDER.BODY, PP_PLACEHOLDER.CENTER_TITLE: PP_PLACEHOLDER.TITLE, PP_PLACEHOLDER.ORG_CHART: PP_PLACEHOLDER.BODY, PP_PLACEHOLDER.DATE: PP_PLACEHOLDER.DATE, PP_PLACEHOLDER.FOOTER: PP_PLACEHOLDER.FOOTER, PP_PLACEHOLDER.MEDIA_CLIP: PP_PLACEHOLDER.BODY, PP_PLACEHOLDER.OBJECT: PP_PLACEHOLDER.BODY, PP_PLACEHOLDER.PICTURE: PP_PLACEHOLDER.BODY, PP_PLACEHOLDER.SLIDE_NUMBER: PP_PLACEHOLDER.SLIDE_NUMBER, PP_PLACEHOLDER.SUBTITLE: PP_PLACEHOLDER.BODY, PP_PLACEHOLDER.TABLE: PP_PLACEHOLDER.BODY, PP_PLACEHOLDER.TITLE: PP_PLACEHOLDER.TITLE, }[self._element.ph_type] slide_master = self.part.slide_master return slide_master.placeholders.get(base_ph_type, None)
class MasterPlaceholder(BasePlaceholder): """Placeholder shape on a slide master."""
element: CT_Shape # pyright: ignore[reportIncompatibleMethodOverride]
class NotesSlidePlaceholder(_InheritsDimensions, Shape): """ Placeholder shape on a notes slide. Inherits shape properties from the placeholder on the notes master that has the same type (e.g. 'body'). """
@property def _base_placeholder(self): """ Return the notes master placeholder this notes slide placeholder inherits from, or |None| if no placeholder of the matching type is present. """ notes_master = self.part.notes_master ph_type = self.element.ph_type return notes_master.placeholders.get(ph_type=ph_type)
class SlidePlaceholder(_BaseSlidePlaceholder): """ Placeholder shape on a slide. Inherits shape properties from its corresponding slide layout placeholder. """
class ChartPlaceholder(_BaseSlidePlaceholder): """Placeholder shape that can only accept a chart."""
def insert_chart(self, chart_type, chart_data): """ Return a |PlaceholderGraphicFrame| object containing a new chart of *chart_type* depicting *chart_data* and having the same position and size as this placeholder. *chart_type* is one of the :ref:`XlChartType` enumeration values. *chart_data* is a |ChartData| object populated with the categories and series values for the chart. Note that the new |Chart| object is not returned directly. The chart object may be accessed using the :attr:`~.PlaceholderGraphicFrame.chart` property of the returned |PlaceholderGraphicFrame| object. """ rId = self.part.add_chart_part(chart_type, chart_data) graphicFrame = self._new_chart_graphicFrame( rId, self.left, self.top, self.width, self.height ) self._replace_placeholder_with(graphicFrame) return PlaceholderGraphicFrame(graphicFrame, self._parent)
def _new_chart_graphicFrame(self, rId, x, y, cx, cy): """ Return a newly created `p:graphicFrame` element having the specified position and size and containing the chart identified by *rId*. """ id_, name = self.shape_id, self.name return CT_GraphicalObjectFrame.new_chart_graphicFrame(id_, name, rId, x, y, cx, cy)
class PicturePlaceholder(_BaseSlidePlaceholder): """Placeholder shape that can only accept a picture."""
def insert_picture(self, image_file): """Return a |PlaceholderPicture| object depicting the image in `image_file`.
`image_file` may be either a path (string) or a file-like object. The image is cropped to fill the entire space of the placeholder. A |PlaceholderPicture| object has all the properties and methods of a |Picture| shape except that the value of its :attr:`~._BaseSlidePlaceholder.shape_type` property is `MSO_SHAPE_TYPE.PLACEHOLDER` instead of `MSO_SHAPE_TYPE.PICTURE`. """ pic = self._new_placeholder_pic(image_file) self._replace_placeholder_with(pic) return PlaceholderPicture(pic, self._parent)
def _new_placeholder_pic(self, image_file): """ Return a new `p:pic` element depicting the image in *image_file*, suitable for use as a placeholder. In particular this means not having an `a:xfrm` element, allowing its extents to be inherited from its layout placeholder. """ rId, desc, image_size = self._get_or_add_image(image_file) shape_id, name = self.shape_id, self.name pic = CT_Picture.new_ph_pic(shape_id, name, desc, rId) pic.crop_to_fit(image_size, (self.width, self.height)) return pic
def _get_or_add_image(self, image_file): """ Return an (rId, description, image_size) 3-tuple identifying the related image part containing *image_file* and describing the image. """ image_part, rId = self.part.get_or_add_image_part(image_file) desc, image_size = image_part.desc, image_part._px_size return rId, desc, image_size
class PlaceholderGraphicFrame(GraphicFrame): """ Placeholder shape populated with a table, chart, or smart art. """
@property def is_placeholder(self): """ Boolean indicating whether this shape is a placeholder. Unconditionally |True| in this case. """ return True
class PlaceholderPicture(_InheritsDimensions, Picture): """ Placeholder shape populated with a picture. """
@property def _base_placeholder(self): """ Return the layout placeholder this picture placeholder inherits from. """ layout, idx = self.part.slide_layout, self._element.ph_idx return layout.placeholders.get(idx=idx)
class TablePlaceholder(_BaseSlidePlaceholder): """Placeholder shape that can only accept a table."""
def insert_table(self, rows, cols): """Return |PlaceholderGraphicFrame| object containing a `rows` by `cols` table.
The position and width of the table are those of the placeholder and its height is proportional to the number of rows. A |PlaceholderGraphicFrame| object has all the properties and methods of a |GraphicFrame| shape except that the value of its :attr:`~._BaseSlidePlaceholder.shape_type` property is unconditionally `MSO_SHAPE_TYPE.PLACEHOLDER`. Note that the return value is not the new table but rather *contains* the new table. The table can be accessed using the :attr:`~.PlaceholderGraphicFrame.table` property of the returned |PlaceholderGraphicFrame| object. """ graphicFrame = self._new_placeholder_table(rows, cols) self._replace_placeholder_with(graphicFrame) return PlaceholderGraphicFrame(graphicFrame, self._parent)
def _new_placeholder_table(self, rows, cols): """ Return a newly added `p:graphicFrame` element containing an empty table with *rows* rows and *cols* columns, positioned at the location of this placeholder and having its same width. The table's height is determined by the number of rows. """ shape_id, name, height = self.shape_id, self.name, Emu(rows * 370840) return CT_GraphicalObjectFrame.new_table_graphicFrame( shape_id, name, rows, cols, self.left, self.top, self.width, height )12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190"""The shape tree, the structure that holds a slide's shapes."""
from __future__ import annotations
import ioimport osfrom typing import IO, TYPE_CHECKING, Callable, Iterable, Iterator, cast
from pptx.enum.shapes import PP_PLACEHOLDER, PROG_IDfrom pptx.media import SPEAKER_IMAGE_BYTES, Videofrom pptx.opc.constants import CONTENT_TYPE as CTfrom pptx.oxml.ns import qnfrom pptx.oxml.shapes.autoshape import CT_Shapefrom pptx.oxml.shapes.graphfrm import CT_GraphicalObjectFramefrom pptx.oxml.shapes.picture import CT_Picturefrom pptx.oxml.simpletypes import ST_Directionfrom pptx.shapes.autoshape import AutoShapeType, Shapefrom pptx.shapes.base import BaseShapefrom pptx.shapes.connector import Connectorfrom pptx.shapes.freeform import FreeformBuilderfrom pptx.shapes.graphfrm import GraphicFramefrom pptx.shapes.group import GroupShapefrom pptx.shapes.picture import Movie, Picturefrom pptx.shapes.placeholder import ( ChartPlaceholder, LayoutPlaceholder, MasterPlaceholder, NotesSlidePlaceholder, PicturePlaceholder, PlaceholderGraphicFrame, PlaceholderPicture, SlidePlaceholder, TablePlaceholder,)from pptx.shared import ParentedElementProxyfrom pptx.util import Emu, lazyproperty
if TYPE_CHECKING: from pptx.chart.chart import Chart from pptx.chart.data import ChartData from pptx.enum.chart import XL_CHART_TYPE from pptx.enum.shapes import MSO_CONNECTOR_TYPE, MSO_SHAPE from pptx.oxml.shapes import ShapeElement from pptx.oxml.shapes.connector import CT_Connector from pptx.oxml.shapes.groupshape import CT_GroupShape from pptx.parts.image import ImagePart from pptx.parts.slide import SlidePart from pptx.slide import Slide, SlideLayout from pptx.types import ProvidesPart from pptx.util import Length
# +-- _BaseShapes# | |# | +-- _BaseGroupShapes# | | |# | | +-- GroupShapes# | | |# | | +-- SlideShapes# | |# | +-- LayoutShapes# | |# | +-- MasterShapes# | |# | +-- NotesSlideShapes# | |# | +-- BasePlaceholders# | |# | +-- LayoutPlaceholders# | |# | +-- MasterPlaceholders# | |# | +-- NotesSlidePlaceholders# |# +-- SlidePlaceholders
class _BaseShapes(ParentedElementProxy): """Base class for a shape collection appearing in a slide-type object.
Subclasses include Slide, SlideLayout, and SlideMaster. Provides common methods. """
def __init__(self, spTree: CT_GroupShape, parent: ProvidesPart): super(_BaseShapes, self).__init__(spTree, parent) self._spTree = spTree self._cached_max_shape_id = None
def __getitem__(self, idx: int) -> BaseShape: """Return shape at `idx` in sequence, e.g. `shapes[2]`.""" shape_elms = list(self._iter_member_elms()) try: shape_elm = shape_elms[idx] except IndexError: raise IndexError("shape index out of range") return self._shape_factory(shape_elm)
def __iter__(self) -> Iterator[BaseShape]: """Generate a reference to each shape in the collection, in sequence.""" for shape_elm in self._iter_member_elms(): yield self._shape_factory(shape_elm)
def __len__(self) -> int: """Return count of shapes in this shape tree.
A group shape contributes 1 to the total, without regard to the number of shapes contained in the group. """ shape_elms = list(self._iter_member_elms()) return len(shape_elms)
def clone_placeholder(self, placeholder: LayoutPlaceholder) -> None: """Add a new placeholder shape based on `placeholder`.""" sp = placeholder.element ph_type, orient, sz, idx = (sp.ph_type, sp.ph_orient, sp.ph_sz, sp.ph_idx) id_ = self._next_shape_id name = self._next_ph_name(ph_type, id_, orient) self._spTree.add_placeholder(id_, name, ph_type, orient, sz, idx)
def ph_basename(self, ph_type: PP_PLACEHOLDER) -> str: """Return the base name for a placeholder of `ph_type` in this shape collection.
There is some variance between slide types, for example a notes slide uses a different name for the body placeholder, so this method can be overriden by subclasses. """ return { PP_PLACEHOLDER.BITMAP: "ClipArt Placeholder", PP_PLACEHOLDER.BODY: "Text Placeholder", PP_PLACEHOLDER.CENTER_TITLE: "Title", PP_PLACEHOLDER.CHART: "Chart Placeholder", PP_PLACEHOLDER.DATE: "Date Placeholder", PP_PLACEHOLDER.FOOTER: "Footer Placeholder", PP_PLACEHOLDER.HEADER: "Header Placeholder", PP_PLACEHOLDER.MEDIA_CLIP: "Media Placeholder", PP_PLACEHOLDER.OBJECT: "Content Placeholder", PP_PLACEHOLDER.ORG_CHART: "SmartArt Placeholder", PP_PLACEHOLDER.PICTURE: "Picture Placeholder", PP_PLACEHOLDER.SLIDE_NUMBER: "Slide Number Placeholder", PP_PLACEHOLDER.SUBTITLE: "Subtitle", PP_PLACEHOLDER.TABLE: "Table Placeholder", PP_PLACEHOLDER.TITLE: "Title", }[ph_type]
@property def turbo_add_enabled(self) -> bool: """True if "turbo-add" mode is enabled. Read/Write.
EXPERIMENTAL: This feature can radically improve performance when adding large numbers (hundreds of shapes) to a slide. It works by caching the last shape ID used and incrementing that value to assign the next shape id. This avoids repeatedly searching all shape ids in the slide each time a new ID is required.
Performance is not noticeably improved for a slide with a relatively small number of shapes, but because the search time rises with the square of the shape count, this option can be useful for optimizing generation of a slide composed of many shapes.
Shape-id collisions can occur (causing a repair error on load) if more than one |Slide| object is used to interact with the same slide in the presentation. Note that the |Slides| collection creates a new |Slide| object each time a slide is accessed (e.g. `slide = prs.slides[0]`, so you must be careful to limit use to a single |Slide| object. """ return self._cached_max_shape_id is not None
@turbo_add_enabled.setter def turbo_add_enabled(self, value: bool): enable = bool(value) self._cached_max_shape_id = self._spTree.max_shape_id if enable else None
@staticmethod def _is_member_elm(shape_elm: ShapeElement) -> bool: """Return true if `shape_elm` represents a member of this collection, False otherwise.""" return True
def _iter_member_elms(self) -> Iterator[ShapeElement]: """Generate each child of the `p:spTree` element that corresponds to a shape.
Items appear in XML document order. """ for shape_elm in self._spTree.iter_shape_elms(): if self._is_member_elm(shape_elm): yield shape_elm
def _next_ph_name(self, ph_type: PP_PLACEHOLDER, id: int, orient: str) -> str: """Next unique placeholder name for placeholder shape of type `ph_type`.
Usually will be standard placeholder root name suffixed with id-1, e.g. _next_ph_name(ST_PlaceholderType.TBL, 4, 'horz') ==> 'Table Placeholder 3'. The number is incremented as necessary to make the name unique within the collection. If `orient` is `'vert'`, the placeholder name is prefixed with `'Vertical '`. """ basename = self.ph_basename(ph_type)
# prefix rootname with 'Vertical ' if orient is 'vert' if orient == ST_Direction.VERT: basename = "Vertical %s" % basename
# increment numpart as necessary to make name unique numpart = id - 1 names = self._spTree.xpath("//p:cNvPr/@name") while True: name = "%s %d" % (basename, numpart) if name not in names: break numpart += 1
return name
@property def _next_shape_id(self) -> int: """Return a unique shape id suitable for use with a new shape.
The returned id is 1 greater than the maximum shape id used so far. In practice, the minimum id is 2 because the spTree element is always assigned id="1". """ # ---presence of cached-max-shape-id indicates turbo mode is on--- if self._cached_max_shape_id is not None: self._cached_max_shape_id += 1 return self._cached_max_shape_id
return self._spTree.max_shape_id + 1
def _shape_factory(self, shape_elm: ShapeElement) -> BaseShape: """Return an instance of the appropriate shape proxy class for `shape_elm`.""" return BaseShapeFactory(shape_elm, self)
class _BaseGroupShapes(_BaseShapes): """Base class for shape-trees that can add shapes."""
part: SlidePart # pyright: ignore[reportIncompatibleMethodOverride] _element: CT_GroupShape
def __init__(self, grpSp: CT_GroupShape, parent: ProvidesPart): super(_BaseGroupShapes, self).__init__(grpSp, parent) self._grpSp = grpSp
def add_chart( self, chart_type: XL_CHART_TYPE, x: Length, y: Length, cx: Length, cy: Length, chart_data: ChartData, ) -> Chart: """Add a new chart of `chart_type` to the slide.
The chart is positioned at (`x`, `y`), has size (`cx`, `cy`), and depicts `chart_data`. `chart_type` is one of the :ref:`XlChartType` enumeration values. `chart_data` is a |ChartData| object populated with the categories and series values for the chart.
Note that a |GraphicFrame| shape object is returned, not the |Chart| object contained in that graphic frame shape. The chart object may be accessed using the :attr:`chart` property of the returned |GraphicFrame| object. """ rId = self.part.add_chart_part(chart_type, chart_data) graphicFrame = self._add_chart_graphicFrame(rId, x, y, cx, cy) self._recalculate_extents() return cast("Chart", self._shape_factory(graphicFrame))
def add_connector( self, connector_type: MSO_CONNECTOR_TYPE, begin_x: Length, begin_y: Length, end_x: Length, end_y: Length, ) -> Connector: """Add a newly created connector shape to the end of this shape tree.
`connector_type` is a member of the :ref:`MsoConnectorType` enumeration and the end-point values are specified as EMU values. The returned connector is of type `connector_type` and has begin and end points as specified. """ cxnSp = self._add_cxnSp(connector_type, begin_x, begin_y, end_x, end_y) self._recalculate_extents() return cast(Connector, self._shape_factory(cxnSp))
def add_group_shape(self, shapes: Iterable[BaseShape] = ()) -> GroupShape: """Return a |GroupShape| object newly appended to this shape tree.
The group shape is empty and must be populated with shapes using methods on its shape tree, available on its `.shapes` property. The position and extents of the group shape are determined by the shapes it contains; its position and extents are recalculated each time a shape is added to it. """ shapes = tuple(shapes) grpSp = self._element.add_grpSp() for shape in shapes: grpSp.insert_element_before( shape._element, "p:extLst" # pyright: ignore[reportPrivateUsage] ) if shapes: grpSp.recalculate_extents() return cast(GroupShape, self._shape_factory(grpSp))
def add_ole_object( self, object_file: str | IO[bytes], prog_id: str, left: Length, top: Length, width: Length | None = None, height: Length | None = None, icon_file: str | IO[bytes] | None = None, icon_width: Length | None = None, icon_height: Length | None = None, ) -> GraphicFrame: """Return newly-created GraphicFrame shape embedding `object_file`.
The returned graphic-frame shape contains `object_file` as an embedded OLE object. It is displayed as an icon at `left`, `top` with size `width`, `height`. `width` and `height` may be omitted when `prog_id` is a member of `PROG_ID`, in which case the default icon size is used. This is advised for best appearance where applicable because it avoids an icon with a "stretched" appearance.
`object_file` may either be a str path to a file or file-like object (such as `io.BytesIO`) containing the bytes of the object to be embedded (such as an Excel file).
`prog_id` can be either a member of `pptx.enum.shapes.PROG_ID` or a str value like `"Adobe.Exchange.7"` determined by inspecting the XML generated by PowerPoint for an object of the desired type.
`icon_file` may either be a str path to an image file or a file-like object containing the image. The image provided will be displayed in lieu of the OLE object; double-clicking on the image opens the object (subject to operating-system limitations). The image file can be any supported image file. Those produced by PowerPoint itself are generally EMF and can be harvested from a PPTX package that embeds such an object. PNG and JPG also work fine.
`icon_width` and `icon_height` are `Length` values (e.g. Emu() or Inches()) that describe the size of the icon image within the shape. These should be omitted unless a custom `icon_file` is provided. The dimensions must be discovered by inspecting the XML. Automatic resizing of the OLE-object shape can occur when the icon is double-clicked if these values are not as set by PowerPoint. This behavior may only manifest in the Windows version of PowerPoint. """ graphicFrame = _OleObjectElementCreator.graphicFrame( self, self._next_shape_id, object_file, prog_id, left, top, width, height, icon_file, icon_width, icon_height, ) self._spTree.append(graphicFrame) self._recalculate_extents() return cast(GraphicFrame, self._shape_factory(graphicFrame))
def add_picture( self, image_file: str | IO[bytes], left: Length, top: Length, width: Length | None = None, height: Length | None = None, ) -> Picture: """Add picture shape displaying image in `image_file`.
`image_file` can be either a path to a file (a string) or a file-like object. The picture is positioned with its top-left corner at (`top`, `left`). If `width` and `height` are both |None|, the native size of the image is used. If only one of `width` or `height` is used, the unspecified dimension is calculated to preserve the aspect ratio of the image. If both are specified, the picture is stretched to fit, without regard to its native aspect ratio. """ image_part, rId = self.part.get_or_add_image_part(image_file) pic = self._add_pic_from_image_part(image_part, rId, left, top, width, height) self._recalculate_extents() return cast(Picture, self._shape_factory(pic))
def add_shape( self, autoshape_type_id: MSO_SHAPE, left: Length, top: Length, width: Length, height: Length ) -> Shape: """Return new |Shape| object appended to this shape tree.
`autoshape_type_id` is a member of :ref:`MsoAutoShapeType` e.g. `MSO_SHAPE.RECTANGLE` specifying the type of shape to be added. The remaining arguments specify the new shape's position and size. """ autoshape_type = AutoShapeType(autoshape_type_id) sp = self._add_sp(autoshape_type, left, top, width, height) self._recalculate_extents() return cast(Shape, self._shape_factory(sp))
def add_textbox(self, left: Length, top: Length, width: Length, height: Length) -> Shape: """Return newly added text box shape appended to this shape tree.
The text box is of the specified size, located at the specified position on the slide. """ sp = self._add_textbox_sp(left, top, width, height) self._recalculate_extents() return cast(Shape, self._shape_factory(sp))
def build_freeform( self, start_x: float = 0, start_y: float = 0, scale: tuple[float, float] | float = 1.0 ) -> FreeformBuilder: """Return |FreeformBuilder| object to specify a freeform shape.
The optional `start_x` and `start_y` arguments specify the starting pen position in local coordinates. They will be rounded to the nearest integer before use and each default to zero.
The optional `scale` argument specifies the size of local coordinates proportional to slide coordinates (EMU). If the vertical scale is different than the horizontal scale (local coordinate units are "rectangular"), a pair of numeric values can be provided as the `scale` argument, e.g. `scale=(1.0, 2.0)`. In this case the first number is interpreted as the horizontal (X) scale and the second as the vertical (Y) scale.
A convenient method for calculating scale is to divide a |Length| object by an equivalent count of local coordinate units, e.g. `scale = Inches(1)/1000` for 1000 local units per inch. """ x_scale, y_scale = scale if isinstance(scale, tuple) else (scale, scale)
return FreeformBuilder.new(self, start_x, start_y, x_scale, y_scale)
def index(self, shape: BaseShape) -> int: """Return the index of `shape` in this sequence.
Raises |ValueError| if `shape` is not in the collection. """ shape_elms = list(self._element.iter_shape_elms()) return shape_elms.index(shape.element)
def _add_chart_graphicFrame( self, rId: str, x: Length, y: Length, cx: Length, cy: Length ) -> CT_GraphicalObjectFrame: """Return new `p:graphicFrame` element appended to this shape tree.
The `p:graphicFrame` element has the specified position and size and refers to the chart part identified by `rId`. """ shape_id = self._next_shape_id name = "Chart %d" % (shape_id - 1) graphicFrame = CT_GraphicalObjectFrame.new_chart_graphicFrame( shape_id, name, rId, x, y, cx, cy ) self._spTree.append(graphicFrame) return graphicFrame
def _add_cxnSp( self, connector_type: MSO_CONNECTOR_TYPE, begin_x: Length, begin_y: Length, end_x: Length, end_y: Length, ) -> CT_Connector: """Return a newly-added `p:cxnSp` element as specified.
The `p:cxnSp` element is for a connector of `connector_type` beginning at (`begin_x`, `begin_y`) and extending to (`end_x`, `end_y`). """ id_ = self._next_shape_id name = "Connector %d" % (id_ - 1)
flipH, flipV = begin_x > end_x, begin_y > end_y x, y = min(begin_x, end_x), min(begin_y, end_y) cx, cy = abs(end_x - begin_x), abs(end_y - begin_y)
return self._element.add_cxnSp(id_, name, connector_type, x, y, cx, cy, flipH, flipV)
def _add_pic_from_image_part( self, image_part: ImagePart, rId: str, x: Length, y: Length, cx: Length | None, cy: Length | None, ) -> CT_Picture: """Return a newly appended `p:pic` element as specified.
The `p:pic` element displays the image in `image_part` with size and position specified by `x`, `y`, `cx`, and `cy`. The element is appended to the shape tree, causing it to be displayed first in z-order on the slide. """ id_ = self._next_shape_id scaled_cx, scaled_cy = image_part.scale(cx, cy) name = "Picture %d" % (id_ - 1) desc = image_part.desc pic = self._grpSp.add_pic(id_, name, desc, rId, x, y, scaled_cx, scaled_cy) return pic
def _add_sp( self, autoshape_type: AutoShapeType, x: Length, y: Length, cx: Length, cy: Length ) -> CT_Shape: """Return newly-added `p:sp` element as specified.
`p:sp` element is of `autoshape_type` at position (`x`, `y`) and of size (`cx`, `cy`). """ id_ = self._next_shape_id name = "%s %d" % (autoshape_type.basename, id_ - 1) sp = self._grpSp.add_autoshape(id_, name, autoshape_type.prst, x, y, cx, cy) return sp
def _add_textbox_sp(self, x: Length, y: Length, cx: Length, cy: Length) -> CT_Shape: """Return newly-appended textbox `p:sp` element.
Element has position (`x`, `y`) and size (`cx`, `cy`). """ id_ = self._next_shape_id name = "TextBox %d" % (id_ - 1) sp = self._spTree.add_textbox(id_, name, x, y, cx, cy) return sp
def _recalculate_extents(self) -> None: """Adjust position and size to incorporate all contained shapes.
This would typically be called when a contained shape is added, removed, or its position or size updated. """ # ---default behavior is to do nothing, GroupShapes overrides to # produce the distinctive behavior of groups and subgroups.--- pass
class GroupShapes(_BaseGroupShapes): """The sequence of child shapes belonging to a group shape.
Note that this collection can itself contain a group shape, making this part of a recursive, tree data structure (acyclic graph). """
def _recalculate_extents(self) -> None: """Adjust position and size to incorporate all contained shapes.
This would typically be called when a contained shape is added, removed, or its position or size updated. """ self._grpSp.recalculate_extents()
class SlideShapes(_BaseGroupShapes): """Sequence of shapes appearing on a slide.
The first shape in the sequence is the backmost in z-order and the last shape is topmost. Supports indexed access, len(), index(), and iteration. """
parent: Slide # pyright: ignore[reportIncompatibleMethodOverride]
def add_movie( self, movie_file: str | IO[bytes], left: Length, top: Length, width: Length, height: Length, poster_frame_image: str | IO[bytes] | None = None, mime_type: str = CT.VIDEO, ) -> GraphicFrame: """Return newly added movie shape displaying video in `movie_file`.
**EXPERIMENTAL.** This method has important limitations:
* The size must be specified; no auto-scaling such as that provided by :meth:`add_picture` is performed. * The MIME type of the video file should be specified, e.g. 'video/mp4'. The provided video file is not interrogated for its type. The MIME type `video/unknown` is used by default (and works fine in tests as of this writing). * A poster frame image must be provided, it cannot be automatically extracted from the video file. If no poster frame is provided, the default "media loudspeaker" image will be used.
Return a newly added movie shape to the slide, positioned at (`left`, `top`), having size (`width`, `height`), and containing `movie_file`. Before the video is started, `poster_frame_image` is displayed as a placeholder for the video. """ movie_pic = _MoviePicElementCreator.new_movie_pic( self, self._next_shape_id, movie_file, left, top, width, height, poster_frame_image, mime_type, ) self._spTree.append(movie_pic) self._add_video_timing(movie_pic) return cast(GraphicFrame, self._shape_factory(movie_pic))
def add_table( self, rows: int, cols: int, left: Length, top: Length, width: Length, height: Length ) -> GraphicFrame: """Add a |GraphicFrame| object containing a table.
The table has the specified number of `rows` and `cols` and the specified position and size. `width` is evenly distributed between the columns of the new table. Likewise, `height` is evenly distributed between the rows. Note that the `.table` property on the returned |GraphicFrame| shape must be used to access the enclosed |Table| object. """ graphicFrame = self._add_graphicFrame_containing_table(rows, cols, left, top, width, height) return cast(GraphicFrame, self._shape_factory(graphicFrame))
def clone_layout_placeholders(self, slide_layout: SlideLayout) -> None: """Add placeholder shapes based on those in `slide_layout`.
Z-order of placeholders is preserved. Latent placeholders (date, slide number, and footer) are not cloned. """ for placeholder in slide_layout.iter_cloneable_placeholders(): self.clone_placeholder(placeholder)
@property def placeholders(self) -> SlidePlaceholders: """Sequence of placeholder shapes in this slide.""" return self.parent.placeholders
@property def title(self) -> Shape | None: """The title placeholder shape on the slide.
|None| if the slide has no title placeholder. """ for elm in self._spTree.iter_ph_elms(): if elm.ph_idx == 0: return cast(Shape, self._shape_factory(elm)) return None
def _add_graphicFrame_containing_table( self, rows: int, cols: int, x: Length, y: Length, cx: Length, cy: Length ) -> CT_GraphicalObjectFrame: """Return a newly added `p:graphicFrame` element containing a table as specified.""" _id = self._next_shape_id name = "Table %d" % (_id - 1) graphicFrame = self._spTree.add_table(_id, name, rows, cols, x, y, cx, cy) return graphicFrame
def _add_video_timing(self, pic: CT_Picture) -> None: """Add a `p:video` element under `p:sld/p:timing`.
The element will refer to the specified `pic` element by its shape id, and cause the video play controls to appear for that video. """ sld = self._spTree.xpath("/p:sld")[0] childTnLst = sld.get_or_add_childTnLst() childTnLst.add_video(pic.shape_id)
def _shape_factory(self, shape_elm: ShapeElement) -> BaseShape: """Return an instance of the appropriate shape proxy class for `shape_elm`.""" return SlideShapeFactory(shape_elm, self)
class LayoutShapes(_BaseShapes): """Sequence of shapes appearing on a slide layout.
The first shape in the sequence is the backmost in z-order and the last shape is topmost. Supports indexed access, len(), index(), and iteration. """
def _shape_factory(self, shape_elm: ShapeElement) -> BaseShape: """Return an instance of the appropriate shape proxy class for `shape_elm`.""" return _LayoutShapeFactory(shape_elm, self)
class MasterShapes(_BaseShapes): """Sequence of shapes appearing on a slide master.
The first shape in the sequence is the backmost in z-order and the last shape is topmost. Supports indexed access, len(), and iteration. """
def _shape_factory(self, shape_elm: ShapeElement) -> BaseShape: """Return an instance of the appropriate shape proxy class for `shape_elm`.""" return _MasterShapeFactory(shape_elm, self)
class NotesSlideShapes(_BaseShapes): """Sequence of shapes appearing on a notes slide.
The first shape in the sequence is the backmost in z-order and the last shape is topmost. Supports indexed access, len(), index(), and iteration. """
def ph_basename(self, ph_type: PP_PLACEHOLDER) -> str: """Return the base name for a placeholder of `ph_type` in this shape collection.
A notes slide uses a different name for the body placeholder and has some unique placeholder types, so this method overrides the default in the base class. """ return { PP_PLACEHOLDER.BODY: "Notes Placeholder", PP_PLACEHOLDER.DATE: "Date Placeholder", PP_PLACEHOLDER.FOOTER: "Footer Placeholder", PP_PLACEHOLDER.HEADER: "Header Placeholder", PP_PLACEHOLDER.SLIDE_IMAGE: "Slide Image Placeholder", PP_PLACEHOLDER.SLIDE_NUMBER: "Slide Number Placeholder", }[ph_type]
def _shape_factory(self, shape_elm: ShapeElement) -> BaseShape: """Return appropriate shape object for `shape_elm` appearing on a notes slide.""" return _NotesSlideShapeFactory(shape_elm, self)
class BasePlaceholders(_BaseShapes): """Base class for placeholder collections.
Subclasses differentiate behaviors for a master, layout, and slide. By default, placeholder shapes are constructed using |BaseShapeFactory|. Subclasses should override :method:`_shape_factory` to use custom placeholder classes. """
@staticmethod def _is_member_elm(shape_elm: ShapeElement) -> bool: """True if `shape_elm` is a placeholder shape, False otherwise.""" return shape_elm.has_ph_elm
class LayoutPlaceholders(BasePlaceholders): """Sequence of |LayoutPlaceholder| instance for each placeholder shape on a slide layout."""
__iter__: Callable[ # pyright: ignore[reportIncompatibleMethodOverride] [], Iterator[LayoutPlaceholder] ]
def get(self, idx: int, default: LayoutPlaceholder | None = None) -> LayoutPlaceholder | None: """The first placeholder shape with matching `idx` value, or `default` if not found.""" for placeholder in self: if placeholder.element.ph_idx == idx: return placeholder return default
def _shape_factory(self, shape_elm: ShapeElement) -> BaseShape: """Return an instance of the appropriate shape proxy class for `shape_elm`.""" return _LayoutShapeFactory(shape_elm, self)
class MasterPlaceholders(BasePlaceholders): """Sequence of MasterPlaceholder representing the placeholder shapes on a slide master."""
__iter__: Callable[ # pyright: ignore[reportIncompatibleMethodOverride] [], Iterator[MasterPlaceholder] ]
def get(self, ph_type: PP_PLACEHOLDER, default: MasterPlaceholder | None = None): """Return the first placeholder shape with type `ph_type` (e.g. 'body').
Returns `default` if no such placeholder shape is present in the collection. """ for placeholder in self: if placeholder.ph_type == ph_type: return placeholder return default
def _shape_factory( # pyright: ignore[reportIncompatibleMethodOverride] self, placeholder_elm: CT_Shape ) -> MasterPlaceholder: """Return an instance of the appropriate shape proxy class for `shape_elm`.""" return cast(MasterPlaceholder, _MasterShapeFactory(placeholder_elm, self))
class NotesSlidePlaceholders(MasterPlaceholders): """Sequence of placeholder shapes on a notes slide."""
__iter__: Callable[ # pyright: ignore[reportIncompatibleMethodOverride] [], Iterator[NotesSlidePlaceholder] ]
def _shape_factory( # pyright: ignore[reportIncompatibleMethodOverride] self, placeholder_elm: CT_Shape ) -> NotesSlidePlaceholder: """Return an instance of the appropriate placeholder proxy class for `placeholder_elm`.""" return cast(NotesSlidePlaceholder, _NotesSlideShapeFactory(placeholder_elm, self))
class SlidePlaceholders(ParentedElementProxy): """Collection of placeholder shapes on a slide.
Supports iteration, :func:`len`, and dictionary-style lookup on the `idx` value of the placeholders it contains. """
_element: CT_GroupShape
def __getitem__(self, idx: int): """Access placeholder shape having `idx`.
Note that while this looks like list access, idx is actually a dictionary key and will raise |KeyError| if no placeholder with that idx value is in the collection. """ for e in self._element.iter_ph_elms(): if e.ph_idx == idx: return SlideShapeFactory(e, self) raise KeyError("no placeholder on this slide with idx == %d" % idx)
def __iter__(self): """Generate placeholder shapes in `idx` order.""" ph_elms = sorted([e for e in self._element.iter_ph_elms()], key=lambda e: e.ph_idx) return (SlideShapeFactory(e, self) for e in ph_elms)
def __len__(self) -> int: """Return count of placeholder shapes.""" return len(list(self._element.iter_ph_elms()))
def BaseShapeFactory(shape_elm: ShapeElement, parent: ProvidesPart) -> BaseShape: """Return an instance of the appropriate shape proxy class for `shape_elm`.""" tag = shape_elm.tag
if isinstance(shape_elm, CT_Picture): videoFiles = shape_elm.xpath("./p:nvPicPr/p:nvPr/a:videoFile") if videoFiles: return Movie(shape_elm, parent) return Picture(shape_elm, parent)
shape_cls = { qn("p:cxnSp"): Connector, qn("p:grpSp"): GroupShape, qn("p:sp"): Shape, qn("p:graphicFrame"): GraphicFrame, }.get(tag, BaseShape)
return shape_cls(shape_elm, parent) # pyright: ignore[reportArgumentType]
def _LayoutShapeFactory(shape_elm: ShapeElement, parent: ProvidesPart) -> BaseShape: """Return appropriate shape object for `shape_elm` on a slide layout.""" if isinstance(shape_elm, CT_Shape) and shape_elm.has_ph_elm: return LayoutPlaceholder(shape_elm, parent) return BaseShapeFactory(shape_elm, parent)
def _MasterShapeFactory(shape_elm: ShapeElement, parent: ProvidesPart) -> BaseShape: """Return appropriate shape object for `shape_elm` on a slide master.""" if isinstance(shape_elm, CT_Shape) and shape_elm.has_ph_elm: return MasterPlaceholder(shape_elm, parent) return BaseShapeFactory(shape_elm, parent)
def _NotesSlideShapeFactory(shape_elm: ShapeElement, parent: ProvidesPart) -> BaseShape: """Return appropriate shape object for `shape_elm` on a notes slide.""" if isinstance(shape_elm, CT_Shape) and shape_elm.has_ph_elm: return NotesSlidePlaceholder(shape_elm, parent) return BaseShapeFactory(shape_elm, parent)
def _SlidePlaceholderFactory(shape_elm: ShapeElement, parent: ProvidesPart): """Return a placeholder shape of the appropriate type for `shape_elm`.""" tag = shape_elm.tag if tag == qn("p:sp"): Constructor = { PP_PLACEHOLDER.BITMAP: PicturePlaceholder, PP_PLACEHOLDER.CHART: ChartPlaceholder, PP_PLACEHOLDER.PICTURE: PicturePlaceholder, PP_PLACEHOLDER.TABLE: TablePlaceholder, }.get(shape_elm.ph_type, SlidePlaceholder) elif tag == qn("p:graphicFrame"): Constructor = PlaceholderGraphicFrame elif tag == qn("p:pic"): Constructor = PlaceholderPicture else: Constructor = BaseShapeFactory return Constructor(shape_elm, parent) # pyright: ignore[reportArgumentType]
def SlideShapeFactory(shape_elm: ShapeElement, parent: ProvidesPart) -> BaseShape: """Return appropriate shape object for `shape_elm` on a slide.""" if shape_elm.has_ph_elm: return _SlidePlaceholderFactory(shape_elm, parent) return BaseShapeFactory(shape_elm, parent)
class _MoviePicElementCreator(object): """Functional service object for creating a new movie p:pic element.
It's entire external interface is its :meth:`new_movie_pic` class method that returns a new `p:pic` element containing the specified video. This class is not intended to be constructed or an instance of it retained by the caller; it is a "one-shot" object, really a function wrapped in a object such that its helper methods can be organized here. """
def __init__( self, shapes: SlideShapes, shape_id: int, movie_file: str | IO[bytes], x: Length, y: Length, cx: Length, cy: Length, poster_frame_file: str | IO[bytes] | None, mime_type: str | None, ): super(_MoviePicElementCreator, self).__init__() self._shapes = shapes self._shape_id = shape_id self._movie_file = movie_file self._x, self._y, self._cx, self._cy = x, y, cx, cy self._poster_frame_file = poster_frame_file self._mime_type = mime_type
@classmethod def new_movie_pic( cls, shapes: SlideShapes, shape_id: int, movie_file: str | IO[bytes], x: Length, y: Length, cx: Length, cy: Length, poster_frame_image: str | IO[bytes] | None, mime_type: str | None, ) -> CT_Picture: """Return a new `p:pic` element containing video in `movie_file`.
If `mime_type` is None, 'video/unknown' is used. If `poster_frame_file` is None, the default "media loudspeaker" image is used. """ return cls(shapes, shape_id, movie_file, x, y, cx, cy, poster_frame_image, mime_type)._pic
@property def _media_rId(self) -> str: """Return the rId of RT.MEDIA relationship to video part.
For historical reasons, there are two relationships to the same part; one is the video rId and the other is the media rId. """ return self._video_part_rIds[0]
@lazyproperty def _pic(self) -> CT_Picture: """Return the new `p:pic` element referencing the video.""" return CT_Picture.new_video_pic( self._shape_id, self._shape_name, self._video_rId, self._media_rId, self._poster_frame_rId, self._x, self._y, self._cx, self._cy, )
@lazyproperty def _poster_frame_image_file(self) -> str | IO[bytes]: """Return the image file for video placeholder image.
If no poster frame file is provided, the default "media loudspeaker" image is used. """ poster_frame_file = self._poster_frame_file if poster_frame_file is None: return io.BytesIO(SPEAKER_IMAGE_BYTES) return poster_frame_file
@lazyproperty def _poster_frame_rId(self) -> str: """Return the rId of relationship to poster frame image.
The poster frame is the image used to represent the video before it's played. """ _, poster_frame_rId = self._slide_part.get_or_add_image_part(self._poster_frame_image_file) return poster_frame_rId
@property def _shape_name(self) -> str: """Return the appropriate shape name for the p:pic shape.
A movie shape is named with the base filename of the video. """ return self._video.filename
@property def _slide_part(self) -> SlidePart: """Return SlidePart object for slide containing this movie.""" return self._shapes.part
@lazyproperty def _video(self) -> Video: """Return a |Video| object containing the movie file.""" return Video.from_path_or_file_like(self._movie_file, self._mime_type)
@lazyproperty def _video_part_rIds(self) -> tuple[str, str]: """Return the rIds for relationships to media part for video.
This is where the media part and its relationships to the slide are actually created. """ media_rId, video_rId = self._slide_part.get_or_add_video_media_part(self._video) return media_rId, video_rId
@property def _video_rId(self) -> str: """Return the rId of RT.VIDEO relationship to video part.
For historical reasons, there are two relationships to the same part; one is the video rId and the other is the media rId. """ return self._video_part_rIds[1]
class _OleObjectElementCreator(object): """Functional service object for creating a new OLE-object p:graphicFrame element.
It's entire external interface is its :meth:`graphicFrame` class method that returns a new `p:graphicFrame` element containing the specified embedded OLE-object shape. This class is not intended to be constructed or an instance of it retained by the caller; it is a "one-shot" object, really a function wrapped in a object such that its helper methods can be organized here. """
def __init__( self, shapes: _BaseGroupShapes, shape_id: int, ole_object_file: str | IO[bytes], prog_id: PROG_ID | str, x: Length, y: Length, cx: Length | None, cy: Length | None, icon_file: str | IO[bytes] | None, icon_width: Length | None, icon_height: Length | None, ): self._shapes = shapes self._shape_id = shape_id self._ole_object_file = ole_object_file self._prog_id_arg = prog_id self._x = x self._y = y self._cx_arg = cx self._cy_arg = cy self._icon_file_arg = icon_file self._icon_width_arg = icon_width self._icon_height_arg = icon_height
@classmethod def graphicFrame( cls, shapes: _BaseGroupShapes, shape_id: int, ole_object_file: str | IO[bytes], prog_id: PROG_ID | str, x: Length, y: Length, cx: Length | None, cy: Length | None, icon_file: str | IO[bytes] | None, icon_width: Length | None, icon_height: Length | None, ) -> CT_GraphicalObjectFrame: """Return new `p:graphicFrame` element containing embedded `ole_object_file`.""" return cls( shapes, shape_id, ole_object_file, prog_id, x, y, cx, cy, icon_file, icon_width, icon_height, )._graphicFrame
@lazyproperty def _graphicFrame(self) -> CT_GraphicalObjectFrame: """Newly-created `p:graphicFrame` element referencing embedded OLE-object.""" return CT_GraphicalObjectFrame.new_ole_object_graphicFrame( self._shape_id, self._shape_name, self._ole_object_rId, self._progId, self._icon_rId, self._x, self._y, self._cx, self._cy, self._icon_width, self._icon_height, )
@lazyproperty def _cx(self) -> Length: """Emu object specifying width of "show-as-icon" image for OLE shape.""" # --- a user-specified width overrides any default --- if self._cx_arg is not None: return self._cx_arg
# --- the default width is specified by the PROG_ID member if prog_id is one, # --- otherwise it gets the default icon width. return ( Emu(self._prog_id_arg.width) if isinstance(self._prog_id_arg, PROG_ID) else Emu(965200) )
@lazyproperty def _cy(self) -> Length: """Emu object specifying height of "show-as-icon" image for OLE shape.""" # --- a user-specified width overrides any default --- if self._cy_arg is not None: return self._cy_arg
# --- the default height is specified by the PROG_ID member if prog_id is one, # --- otherwise it gets the default icon height. return ( Emu(self._prog_id_arg.height) if isinstance(self._prog_id_arg, PROG_ID) else Emu(609600) )
@lazyproperty def _icon_height(self) -> Length: """Vertical size of enclosed EMF icon within the OLE graphic-frame.
This must be specified when a custom icon is used, to avoid stretching of the image and possible undesired resizing by PowerPoint when the OLE shape is double-clicked to open it.
The correct size can be determined by creating an example PPTX using PowerPoint and then inspecting the XML of the OLE graphics-frame (p:oleObj.imgH). """ return self._icon_height_arg if self._icon_height_arg is not None else Emu(609600)
@lazyproperty def _icon_image_file(self) -> str | IO[bytes]: """Reference to image file containing icon to show in lieu of this object.
This can be either a str path or a file-like object (io.BytesIO typically). """ # --- a user-specified icon overrides any default --- if self._icon_file_arg is not None: return self._icon_file_arg
# --- A prog_id belonging to PROG_ID gets its icon filename from there. A # --- user-specified (str) prog_id gets the default icon. icon_filename = ( self._prog_id_arg.icon_filename if isinstance(self._prog_id_arg, PROG_ID) else "generic-icon.emf" )
_thisdir = os.path.split(__file__)[0] return os.path.abspath(os.path.join(_thisdir, "..", "templates", icon_filename))
@lazyproperty def _icon_rId(self) -> str: """str rId like "rId7" of rel to icon (image) representing OLE-object part.""" _, rId = self._slide_part.get_or_add_image_part(self._icon_image_file) return rId
@lazyproperty def _icon_width(self) -> Length: """Width of enclosed EMF icon within the OLE graphic-frame.
This must be specified when a custom icon is used, to avoid stretching of the image and possible undesired resizing by PowerPoint when the OLE shape is double-clicked to open it. """ return self._icon_width_arg if self._icon_width_arg is not None else Emu(965200)
@lazyproperty def _ole_object_rId(self) -> str: """str rId like "rId6" of relationship to embedded ole_object part.
This is where the ole_object part and its relationship to the slide are actually created. """ return self._slide_part.add_embedded_ole_object_part( self._prog_id_arg, self._ole_object_file )
@lazyproperty def _progId(self) -> str: """str like "Excel.Sheet.12" identifying program used to open object.
This value appears in the `progId` attribute of the `p:oleObj` element for the object. """ prog_id_arg = self._prog_id_arg
# --- member of PROG_ID enumeration knows its progId keyphrase, otherwise caller # --- has specified it explicitly (as str) return prog_id_arg.progId if isinstance(prog_id_arg, PROG_ID) else prog_id_arg
@lazyproperty def _shape_name(self) -> str: """str name like "Object 1" for the embedded ole_object shape.
The name is formed from the prefix "Object " and the shape-id decremented by 1. """ return "Object %d" % (self._shape_id - 1)
@lazyproperty def _slide_part(self) -> SlidePart: """SlidePart object for this slide.""" return self._shapes.part12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182"""Objects shared by pptx modules."""
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING: from pptx.opc.package import XmlPart from pptx.oxml.xmlchemy import BaseOxmlElement from pptx.types import ProvidesPart
class ElementProxy(object): """Base class for lxml element proxy classes.
An element proxy class is one whose primary responsibilities are fulfilled by manipulating the attributes and child elements of an XML element. They are the most common type of class in python-pptx other than custom element (oxml) classes. """
def __init__(self, element: BaseOxmlElement): self._element = element
def __eq__(self, other: object) -> bool: """Return |True| if this proxy object refers to the same oxml element as does *other*.
ElementProxy objects are value objects and should maintain no mutable local state. Equality for proxy objects is defined as referring to the same XML element, whether or not they are the same proxy object instance. """ if not isinstance(other, ElementProxy): return False return self._element is other._element
def __ne__(self, other: object) -> bool: if not isinstance(other, ElementProxy): return True return self._element is not other._element
@property def element(self): """The lxml element proxied by this object.""" return self._element
class ParentedElementProxy(ElementProxy): """Provides access to ancestor objects and part.
An ancestor may occasionally be required to provide a service, such as add or drop a relationship. Provides the :attr:`_parent` attribute to subclasses and the public :attr:`parent` read-only property. """
def __init__(self, element: BaseOxmlElement, parent: ProvidesPart): super(ParentedElementProxy, self).__init__(element) self._parent = parent
@property def parent(self): """The ancestor proxy object to this one.
For example, the parent of a shape is generally the |SlideShapes| object that contains it. """ return self._parent
@property def part(self) -> XmlPart: """The package part containing this object.""" return self._parent.part
class PartElementProxy(ElementProxy): """Provides common members for proxy-objects that wrap a part's root element, e.g. `p:sld`."""
def __init__(self, element: BaseOxmlElement, part: XmlPart): super(PartElementProxy, self).__init__(element) self._part = part
@property def part(self) -> XmlPart: """The package part containing this object.""" return self._part123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498"""Slide-related objects, including masters, layouts, and notes."""
from __future__ import annotations
from typing import TYPE_CHECKING, Iterator, cast
from pptx.dml.fill import FillFormatfrom pptx.enum.shapes import PP_PLACEHOLDERfrom pptx.shapes.shapetree import ( LayoutPlaceholders, LayoutShapes, MasterPlaceholders, MasterShapes, NotesSlidePlaceholders, NotesSlideShapes, SlidePlaceholders, SlideShapes,)from pptx.shared import ElementProxy, ParentedElementProxy, PartElementProxyfrom pptx.util import lazyproperty
if TYPE_CHECKING: from pptx.oxml.presentation import CT_SlideIdList, CT_SlideMasterIdList from pptx.oxml.slide import ( CT_CommonSlideData, CT_NotesSlide, CT_Slide, CT_SlideLayoutIdList, CT_SlideMaster, ) from pptx.parts.presentation import PresentationPart from pptx.parts.slide import SlideLayoutPart, SlideMasterPart, SlidePart from pptx.presentation import Presentation from pptx.shapes.placeholder import LayoutPlaceholder, MasterPlaceholder from pptx.shapes.shapetree import NotesSlidePlaceholder from pptx.text.text import TextFrame
class _BaseSlide(PartElementProxy): """Base class for slide objects, including masters, layouts and notes."""
_element: CT_Slide
@lazyproperty def background(self) -> _Background: """|_Background| object providing slide background properties.
This property returns a |_Background| object whether or not the slide, master, or layout has an explicitly defined background.
The same |_Background| object is returned on every call for the same slide object. """ return _Background(self._element.cSld)
@property def name(self) -> str: """String representing the internal name of this slide.
Returns an empty string (`''`) if no name is assigned. Assigning an empty string or |None| to this property causes any name to be removed. """ return self._element.cSld.name
@name.setter def name(self, value: str | None): new_value = "" if value is None else value self._element.cSld.name = new_value
class _BaseMaster(_BaseSlide): """Base class for master objects such as |SlideMaster| and |NotesMaster|.
Provides access to placeholders and regular shapes. """
@lazyproperty def placeholders(self) -> MasterPlaceholders: """|MasterPlaceholders| collection of placeholder shapes in this master.
Sequence sorted in `idx` order. """ return MasterPlaceholders(self._element.spTree, self)
@lazyproperty def shapes(self): """ Instance of |MasterShapes| containing sequence of shape objects appearing on this slide. """ return MasterShapes(self._element.spTree, self)
class NotesMaster(_BaseMaster): """Proxy for the notes master XML document.
Provides access to shapes, the most commonly used of which are placeholders. """
class NotesSlide(_BaseSlide): """Notes slide object.
Provides access to slide notes placeholder and other shapes on the notes handout page. """
element: CT_NotesSlide # pyright: ignore[reportIncompatibleMethodOverride]
def clone_master_placeholders(self, notes_master: NotesMaster) -> None: """Selectively add placeholder shape elements from `notes_master`.
Selected placeholder shape elements from `notes_master` are added to the shapes collection of this notes slide. Z-order of placeholders is preserved. Certain placeholders (header, date, footer) are not cloned. """
def iter_cloneable_placeholders() -> Iterator[MasterPlaceholder]: """Generate a reference to each cloneable placeholder in `notes_master`.
These are the placeholders that should be cloned to a notes slide when the a new notes slide is created. """ cloneable = ( PP_PLACEHOLDER.SLIDE_IMAGE, PP_PLACEHOLDER.BODY, PP_PLACEHOLDER.SLIDE_NUMBER, ) for placeholder in notes_master.placeholders: if placeholder.element.ph_type in cloneable: yield placeholder
shapes = self.shapes for placeholder in iter_cloneable_placeholders(): shapes.clone_placeholder(cast("LayoutPlaceholder", placeholder))
@property def notes_placeholder(self) -> NotesSlidePlaceholder | None: """the notes placeholder on this notes slide, the shape that contains the actual notes text.
Return |None| if no notes placeholder is present; while this is probably uncommon, it can happen if the notes master does not have a body placeholder, or if the notes placeholder has been deleted from the notes slide. """ for placeholder in self.placeholders: if placeholder.placeholder_format.type == PP_PLACEHOLDER.BODY: return placeholder return None
@property def notes_text_frame(self) -> TextFrame | None: """The text frame of the notes placeholder on this notes slide.
|None| if there is no notes placeholder. This is a shortcut to accommodate the common case of simply adding "notes" text to the notes "page". """ notes_placeholder = self.notes_placeholder if notes_placeholder is None: return None return notes_placeholder.text_frame
@lazyproperty def placeholders(self) -> NotesSlidePlaceholders: """Instance of |NotesSlidePlaceholders| for this notes-slide.
Contains the sequence of placeholder shapes in this notes slide. """ return NotesSlidePlaceholders(self.element.spTree, self)
@lazyproperty def shapes(self) -> NotesSlideShapes: """Sequence of shape objects appearing on this notes slide.""" return NotesSlideShapes(self._element.spTree, self)
class Slide(_BaseSlide): """Slide object. Provides access to shapes and slide-level properties."""
part: SlidePart # pyright: ignore[reportIncompatibleMethodOverride]
@property def follow_master_background(self): """|True| if this slide inherits the slide master background.
Assigning |False| causes background inheritance from the master to be interrupted; if there is no custom background for this slide, a default background is added. If a custom background already exists for this slide, assigning |False| has no effect.
Assigning |True| causes any custom background for this slide to be deleted and inheritance from the master restored. """ return self._element.bg is None
@property def has_notes_slide(self) -> bool: """`True` if this slide has a notes slide, `False` otherwise.
A notes slide is created by :attr:`.notes_slide` when one doesn't exist; use this property to test for a notes slide without the possible side effect of creating one. """ return self.part.has_notes_slide
@property def notes_slide(self) -> NotesSlide: """The |NotesSlide| instance for this slide.
If the slide does not have a notes slide, one is created. The same single instance is returned on each call. """ return self.part.notes_slide
@lazyproperty def placeholders(self) -> SlidePlaceholders: """Sequence of placeholder shapes in this slide.""" return SlidePlaceholders(self._element.spTree, self)
@lazyproperty def shapes(self) -> SlideShapes: """Sequence of shape objects appearing on this slide.""" return SlideShapes(self._element.spTree, self)
@property def slide_id(self) -> int: """Integer value that uniquely identifies this slide within this presentation.
The slide id does not change if the position of this slide in the slide sequence is changed by adding, rearranging, or deleting slides. """ return self.part.slide_id
@property def slide_layout(self) -> SlideLayout: """|SlideLayout| object this slide inherits appearance from.""" return self.part.slide_layout
class Slides(ParentedElementProxy): """Sequence of slides belonging to an instance of |Presentation|.
Has list semantics for access to individual slides. Supports indexed access, len(), and iteration. """
part: PresentationPart # pyright: ignore[reportIncompatibleMethodOverride]
def __init__(self, sldIdLst: CT_SlideIdList, prs: Presentation): super(Slides, self).__init__(sldIdLst, prs) self._sldIdLst = sldIdLst
def __getitem__(self, idx: int) -> Slide: """Provide indexed access, (e.g. 'slides[0]').""" try: sldId = self._sldIdLst.sldId_lst[idx] except IndexError: raise IndexError("slide index out of range") return self.part.related_slide(sldId.rId)
def __iter__(self) -> Iterator[Slide]: """Support iteration, e.g. `for slide in slides:`.""" for sldId in self._sldIdLst.sldId_lst: yield self.part.related_slide(sldId.rId)
def __len__(self) -> int: """Support len() built-in function, e.g. `len(slides) == 4`.""" return len(self._sldIdLst)
def add_slide(self, slide_layout: SlideLayout) -> Slide: """Return a newly added slide that inherits layout from `slide_layout`.""" rId, slide = self.part.add_slide(slide_layout) slide.shapes.clone_layout_placeholders(slide_layout) self._sldIdLst.add_sldId(rId) return slide
def get(self, slide_id: int, default: Slide | None = None) -> Slide | None: """Return the slide identified by int `slide_id` in this presentation.
Returns `default` if not found. """ slide = self.part.get_slide(slide_id) if slide is None: return default return slide
def index(self, slide: Slide) -> int: """Map `slide` to its zero-based position in this slide sequence.
Raises |ValueError| on *slide* not present. """ for idx, this_slide in enumerate(self): if this_slide == slide: return idx raise ValueError("%s is not in slide collection" % slide)
class SlideLayout(_BaseSlide): """Slide layout object.
Provides access to placeholders, regular shapes, and slide layout-level properties. """
part: SlideLayoutPart # pyright: ignore[reportIncompatibleMethodOverride]
def iter_cloneable_placeholders(self) -> Iterator[LayoutPlaceholder]: """Generate layout-placeholders on this slide-layout that should be cloned to a new slide.
Used when creating a new slide from this slide-layout. """ latent_ph_types = ( PP_PLACEHOLDER.DATE, PP_PLACEHOLDER.FOOTER, PP_PLACEHOLDER.SLIDE_NUMBER, ) for ph in self.placeholders: if ph.element.ph_type not in latent_ph_types: yield ph
@lazyproperty def placeholders(self) -> LayoutPlaceholders: """Sequence of placeholder shapes in this slide layout.
Placeholders appear in `idx` order. """ return LayoutPlaceholders(self._element.spTree, self)
@lazyproperty def shapes(self) -> LayoutShapes: """Sequence of shapes appearing on this slide layout.""" return LayoutShapes(self._element.spTree, self)
@property def slide_master(self) -> SlideMaster: """Slide master from which this slide-layout inherits properties.""" return self.part.slide_master
@property def used_by_slides(self): """Tuple of slide objects based on this slide layout.""" # ---getting Slides collection requires going around the horn a bit--- slides = self.part.package.presentation_part.presentation.slides return tuple(s for s in slides if s.slide_layout == self)
class SlideLayouts(ParentedElementProxy): """Sequence of slide layouts belonging to a slide-master.
Supports indexed access, len(), iteration, index() and remove(). """
part: SlideMasterPart # pyright: ignore[reportIncompatibleMethodOverride]
def __init__(self, sldLayoutIdLst: CT_SlideLayoutIdList, parent: SlideMaster): super(SlideLayouts, self).__init__(sldLayoutIdLst, parent) self._sldLayoutIdLst = sldLayoutIdLst
def __getitem__(self, idx: int) -> SlideLayout: """Provides indexed access, e.g. `slide_layouts[2]`.""" try: sldLayoutId = self._sldLayoutIdLst.sldLayoutId_lst[idx] except IndexError: raise IndexError("slide layout index out of range") return self.part.related_slide_layout(sldLayoutId.rId)
def __iter__(self) -> Iterator[SlideLayout]: """Generate each |SlideLayout| in the collection, in sequence.""" for sldLayoutId in self._sldLayoutIdLst.sldLayoutId_lst: yield self.part.related_slide_layout(sldLayoutId.rId)
def __len__(self) -> int: """Support len() built-in function, e.g. `len(slides) == 4`.""" return len(self._sldLayoutIdLst)
def get_by_name(self, name: str, default: SlideLayout | None = None) -> SlideLayout | None: """Return SlideLayout object having `name`, or `default` if not found.""" for slide_layout in self: if slide_layout.name == name: return slide_layout return default
def index(self, slide_layout: SlideLayout) -> int: """Return zero-based index of `slide_layout` in this collection.
Raises `ValueError` if `slide_layout` is not present in this collection. """ for idx, this_layout in enumerate(self): if slide_layout == this_layout: return idx raise ValueError("layout not in this SlideLayouts collection")
def remove(self, slide_layout: SlideLayout) -> None: """Remove `slide_layout` from the collection.
Raises ValueError when `slide_layout` is in use; a slide layout which is the basis for one or more slides cannot be removed. """ # ---raise if layout is in use--- if slide_layout.used_by_slides: raise ValueError("cannot remove slide-layout in use by one or more slides")
# ---target layout is identified by its index in this collection--- target_idx = self.index(slide_layout)
# --remove layout from p:sldLayoutIds of its master # --this stops layout from showing up, but doesn't remove it from package target_sldLayoutId = self._sldLayoutIdLst.sldLayoutId_lst[target_idx] self._sldLayoutIdLst.remove(target_sldLayoutId)
# --drop relationship from master to layout # --this removes layout from package, along with everything (only) it refers to, # --including images (not used elsewhere) and hyperlinks slide_layout.slide_master.part.drop_rel(target_sldLayoutId.rId)
class SlideMaster(_BaseMaster): """Slide master object.
Provides access to slide layouts. Access to placeholders, regular shapes, and slide master-level properties is inherited from |_BaseMaster|. """
_element: CT_SlideMaster # pyright: ignore[reportIncompatibleVariableOverride]
@lazyproperty def slide_layouts(self) -> SlideLayouts: """|SlideLayouts| object providing access to this slide-master's layouts.""" return SlideLayouts(self._element.get_or_add_sldLayoutIdLst(), self)
class SlideMasters(ParentedElementProxy): """Sequence of |SlideMaster| objects belonging to a presentation.
Has list access semantics, supporting indexed access, len(), and iteration. """
part: PresentationPart # pyright: ignore[reportIncompatibleMethodOverride]
def __init__(self, sldMasterIdLst: CT_SlideMasterIdList, parent: Presentation): super(SlideMasters, self).__init__(sldMasterIdLst, parent) self._sldMasterIdLst = sldMasterIdLst
def __getitem__(self, idx: int) -> SlideMaster: """Provides indexed access, e.g. `slide_masters[2]`.""" try: sldMasterId = self._sldMasterIdLst.sldMasterId_lst[idx] except IndexError: raise IndexError("slide master index out of range") return self.part.related_slide_master(sldMasterId.rId)
def __iter__(self): """Generate each |SlideMaster| instance in the collection, in sequence.""" for smi in self._sldMasterIdLst.sldMasterId_lst: yield self.part.related_slide_master(smi.rId)
def __len__(self): """Support len() built-in function, e.g. `len(slide_masters) == 4`.""" return len(self._sldMasterIdLst)
class _Background(ElementProxy): """Provides access to slide background properties.
Note that the presence of this object does not by itself imply an explicitly-defined background; a slide with an inherited background still has a |_Background| object. """
def __init__(self, cSld: CT_CommonSlideData): super(_Background, self).__init__(cSld) self._cSld = cSld
@lazyproperty def fill(self): """|FillFormat| instance for this background.
This |FillFormat| object is used to interrogate or specify the fill of the slide background.
Note that accessing this property is potentially destructive. A slide background can also be specified by a background style reference and accessing this property will remove that reference, if present, and replace it with NoFill. This is frequently the case for a slide master background.
This is also the case when there is no explicitly defined background (background is inherited); merely accessing this property will cause the background to be set to NoFill and the inheritance link will be interrupted. This is frequently the case for a slide background.
Of course, if you are accessing this property in order to set the fill, then these changes are of no consequence, but the existing background cannot be reliably interrogated using this property unless you have already established it is an explicit fill.
If the background is already a fill, then accessing this property makes no changes to the current background. """ bgPr = self._cSld.get_or_add_bgPr() return FillFormat.from_fill_parent(bgPr)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632"""Mappings from the ISO/IEC 29500 spec.
Some of these are inferred from PowerPoint application behavior"""
from __future__ import annotations
from typing import TYPE_CHECKING, TypedDict
from pptx.enum.shapes import MSO_SHAPE
GRAPHIC_DATA_URI_CHART = "http://schemas.openxmlformats.org/drawingml/2006/chart"GRAPHIC_DATA_URI_OLEOBJ = "http://schemas.openxmlformats.org/presentationml/2006/ole"GRAPHIC_DATA_URI_TABLE = "http://schemas.openxmlformats.org/drawingml/2006/table"
if TYPE_CHECKING: from typing_extensions import TypeAlias
AdjustmentValue: TypeAlias = tuple[str, int]
class ShapeSpec(TypedDict): basename: str avLst: tuple[AdjustmentValue, ...]
# ============================================================================# AutoShape type specs# ============================================================================
autoshape_types: dict[MSO_SHAPE, ShapeSpec] = { MSO_SHAPE.ACTION_BUTTON_BACK_OR_PREVIOUS: { "basename": "Action Button: Back or Previous", "avLst": (), }, MSO_SHAPE.ACTION_BUTTON_BEGINNING: { "basename": "Action Button: Beginning", "avLst": (), }, MSO_SHAPE.ACTION_BUTTON_CUSTOM: {"basename": "Action Button: Custom", "avLst": ()}, MSO_SHAPE.ACTION_BUTTON_DOCUMENT: { "basename": "Action Button: Document", "avLst": (), }, MSO_SHAPE.ACTION_BUTTON_END: {"basename": "Action Button: End", "avLst": ()}, MSO_SHAPE.ACTION_BUTTON_FORWARD_OR_NEXT: { "basename": "Action Button: Forward or Next", "avLst": (), }, MSO_SHAPE.ACTION_BUTTON_HELP: {"basename": "Action Button: Help", "avLst": ()}, MSO_SHAPE.ACTION_BUTTON_HOME: {"basename": "Action Button: Home", "avLst": ()}, MSO_SHAPE.ACTION_BUTTON_INFORMATION: { "basename": "Action Button: Information", "avLst": (), }, MSO_SHAPE.ACTION_BUTTON_MOVIE: {"basename": "Action Button: Movie", "avLst": ()}, MSO_SHAPE.ACTION_BUTTON_RETURN: {"basename": "Action Button: Return", "avLst": ()}, MSO_SHAPE.ACTION_BUTTON_SOUND: {"basename": "Action Button: Sound", "avLst": ()}, MSO_SHAPE.ARC: {"basename": "Arc", "avLst": (("adj1", 16200000), ("adj2", 0))}, MSO_SHAPE.BALLOON: { "basename": "Rounded Rectangular Callout", "avLst": (("adj1", -20833), ("adj2", 62500), ("adj3", 16667)), }, MSO_SHAPE.BENT_ARROW: { "basename": "Bent Arrow", "avLst": (("adj1", 25000), ("adj2", 25000), ("adj3", 25000), ("adj4", 43750)), }, MSO_SHAPE.BENT_UP_ARROW: { "basename": "Bent-Up Arrow", "avLst": (("adj1", 25000), ("adj2", 25000), ("adj3", 25000)), }, MSO_SHAPE.BEVEL: {"basename": "Bevel", "avLst": (("adj", 12500),)}, MSO_SHAPE.BLOCK_ARC: { "basename": "Block Arc", "avLst": (("adj1", 10800000), ("adj2", 0), ("adj3", 25000)), }, MSO_SHAPE.CAN: {"basename": "Can", "avLst": (("adj", 25000),)}, MSO_SHAPE.CHART_PLUS: {"basename": "Chart Plus", "avLst": ()}, MSO_SHAPE.CHART_STAR: {"basename": "Chart Star", "avLst": ()}, MSO_SHAPE.CHART_X: {"basename": "Chart X", "avLst": ()}, MSO_SHAPE.CHEVRON: {"basename": "Chevron", "avLst": (("adj", 50000),)}, MSO_SHAPE.CHORD: { "basename": "Chord", "avLst": (("adj1", 2700000), ("adj2", 16200000)), }, MSO_SHAPE.CIRCULAR_ARROW: { "basename": "Circular Arrow", "avLst": ( ("adj1", 12500), ("adj2", 1142319), ("adj3", 20457681), ("adj4", 10800000), ("adj5", 12500), ), }, MSO_SHAPE.CLOUD: {"basename": "Cloud", "avLst": ()}, MSO_SHAPE.CLOUD_CALLOUT: { "basename": "Cloud Callout", "avLst": (("adj1", -20833), ("adj2", 62500)), }, MSO_SHAPE.CORNER: { "basename": "Corner", "avLst": (("adj1", 50000), ("adj2", 50000)), }, MSO_SHAPE.CORNER_TABS: {"basename": "Corner Tabs", "avLst": ()}, MSO_SHAPE.CROSS: {"basename": "Cross", "avLst": (("adj", 25000),)}, MSO_SHAPE.CUBE: {"basename": "Cube", "avLst": (("adj", 25000),)}, MSO_SHAPE.CURVED_DOWN_ARROW: { "basename": "Curved Down Arrow", "avLst": (("adj1", 25000), ("adj2", 50000), ("adj3", 25000)), }, MSO_SHAPE.CURVED_DOWN_RIBBON: { "basename": "Curved Down Ribbon", "avLst": (("adj1", 25000), ("adj2", 50000), ("adj3", 12500)), }, MSO_SHAPE.CURVED_LEFT_ARROW: { "basename": "Curved Left Arrow", "avLst": (("adj1", 25000), ("adj2", 50000), ("adj3", 25000)), }, MSO_SHAPE.CURVED_RIGHT_ARROW: { "basename": "Curved Right Arrow", "avLst": (("adj1", 25000), ("adj2", 50000), ("adj3", 25000)), }, MSO_SHAPE.CURVED_UP_ARROW: { "basename": "Curved Up Arrow", "avLst": (("adj1", 25000), ("adj2", 50000), ("adj3", 25000)), }, MSO_SHAPE.CURVED_UP_RIBBON: { "basename": "Curved Up Ribbon", "avLst": (("adj1", 25000), ("adj2", 50000), ("adj3", 12500)), }, MSO_SHAPE.DECAGON: {"basename": "Decagon", "avLst": (("vf", 105146),)}, MSO_SHAPE.DIAGONAL_STRIPE: { "basename": "Diagonal Stripe", "avLst": (("adj", 50000),), }, MSO_SHAPE.DIAMOND: {"basename": "Diamond", "avLst": ()}, MSO_SHAPE.DODECAGON: {"basename": "Dodecagon", "avLst": ()}, MSO_SHAPE.DONUT: {"basename": "Donut", "avLst": (("adj", 25000),)}, MSO_SHAPE.DOUBLE_BRACE: {"basename": "Double Brace", "avLst": (("adj", 8333),)}, MSO_SHAPE.DOUBLE_BRACKET: { "basename": "Double Bracket", "avLst": (("adj", 16667),), }, MSO_SHAPE.DOUBLE_WAVE: { "basename": "Double Wave", "avLst": (("adj1", 6250), ("adj2", 0)), }, MSO_SHAPE.DOWN_ARROW: { "basename": "Down Arrow", "avLst": (("adj1", 50000), ("adj2", 50000)), }, MSO_SHAPE.DOWN_ARROW_CALLOUT: { "basename": "Down Arrow Callout", "avLst": (("adj1", 25000), ("adj2", 25000), ("adj3", 25000), ("adj4", 64977)), }, MSO_SHAPE.DOWN_RIBBON: { "basename": "Down Ribbon", "avLst": (("adj1", 16667), ("adj2", 50000)), }, MSO_SHAPE.EXPLOSION1: {"basename": "Explosion", "avLst": ()}, MSO_SHAPE.EXPLOSION2: {"basename": "Explosion", "avLst": ()}, MSO_SHAPE.FLOWCHART_ALTERNATE_PROCESS: { "basename": "Alternate process", "avLst": (), }, MSO_SHAPE.FLOWCHART_CARD: {"basename": "Card", "avLst": ()}, MSO_SHAPE.FLOWCHART_COLLATE: {"basename": "Collate", "avLst": ()}, MSO_SHAPE.FLOWCHART_CONNECTOR: {"basename": "Connector", "avLst": ()}, MSO_SHAPE.FLOWCHART_DATA: {"basename": "Data", "avLst": ()}, MSO_SHAPE.FLOWCHART_DECISION: {"basename": "Decision", "avLst": ()}, MSO_SHAPE.FLOWCHART_DELAY: {"basename": "Delay", "avLst": ()}, MSO_SHAPE.FLOWCHART_DIRECT_ACCESS_STORAGE: { "basename": "Direct Access Storage", "avLst": (), }, MSO_SHAPE.FLOWCHART_DISPLAY: {"basename": "Display", "avLst": ()}, MSO_SHAPE.FLOWCHART_DOCUMENT: {"basename": "Document", "avLst": ()}, MSO_SHAPE.FLOWCHART_EXTRACT: {"basename": "Extract", "avLst": ()}, MSO_SHAPE.FLOWCHART_INTERNAL_STORAGE: {"basename": "Internal Storage", "avLst": ()}, MSO_SHAPE.FLOWCHART_MAGNETIC_DISK: {"basename": "Magnetic Disk", "avLst": ()}, MSO_SHAPE.FLOWCHART_MANUAL_INPUT: {"basename": "Manual Input", "avLst": ()}, MSO_SHAPE.FLOWCHART_MANUAL_OPERATION: {"basename": "Manual Operation", "avLst": ()}, MSO_SHAPE.FLOWCHART_MERGE: {"basename": "Merge", "avLst": ()}, MSO_SHAPE.FLOWCHART_MULTIDOCUMENT: {"basename": "Multidocument", "avLst": ()}, MSO_SHAPE.FLOWCHART_OFFLINE_STORAGE: {"basename": "Offline Storage", "avLst": ()}, MSO_SHAPE.FLOWCHART_OFFPAGE_CONNECTOR: { "basename": "Off-page Connector", "avLst": (), }, MSO_SHAPE.FLOWCHART_OR: {"basename": "Or", "avLst": ()}, MSO_SHAPE.FLOWCHART_PREDEFINED_PROCESS: { "basename": "Predefined Process", "avLst": (), }, MSO_SHAPE.FLOWCHART_PREPARATION: {"basename": "Preparation", "avLst": ()}, MSO_SHAPE.FLOWCHART_PROCESS: {"basename": "Process", "avLst": ()}, MSO_SHAPE.FLOWCHART_PUNCHED_TAPE: {"basename": "Punched Tape", "avLst": ()}, MSO_SHAPE.FLOWCHART_SEQUENTIAL_ACCESS_STORAGE: { "basename": "Sequential Access Storage", "avLst": (), }, MSO_SHAPE.FLOWCHART_SORT: {"basename": "Sort", "avLst": ()}, MSO_SHAPE.FLOWCHART_STORED_DATA: {"basename": "Stored Data", "avLst": ()}, MSO_SHAPE.FLOWCHART_SUMMING_JUNCTION: {"basename": "Summing Junction", "avLst": ()}, MSO_SHAPE.FLOWCHART_TERMINATOR: {"basename": "Terminator", "avLst": ()}, MSO_SHAPE.FOLDED_CORNER: {"basename": "Folded Corner", "avLst": ()}, MSO_SHAPE.FRAME: {"basename": "Frame", "avLst": (("adj1", 12500),)}, MSO_SHAPE.FUNNEL: {"basename": "Funnel", "avLst": ()}, MSO_SHAPE.GEAR_6: { "basename": "Gear 6", "avLst": (("adj1", 15000), ("adj2", 3526)), }, MSO_SHAPE.GEAR_9: { "basename": "Gear 9", "avLst": (("adj1", 10000), ("adj2", 1763)), }, MSO_SHAPE.HALF_FRAME: { "basename": "Half Frame", "avLst": (("adj1", 33333), ("adj2", 33333)), }, MSO_SHAPE.HEART: {"basename": "Heart", "avLst": ()}, MSO_SHAPE.HEPTAGON: { "basename": "Heptagon", "avLst": (("hf", 102572), ("vf", 105210)), }, MSO_SHAPE.HEXAGON: { "basename": "Hexagon", "avLst": (("adj", 25000), ("vf", 115470)), }, MSO_SHAPE.HORIZONTAL_SCROLL: { "basename": "Horizontal Scroll", "avLst": (("adj", 12500),), }, MSO_SHAPE.ISOSCELES_TRIANGLE: { "basename": "Isosceles Triangle", "avLst": (("adj", 50000),), }, MSO_SHAPE.LEFT_ARROW: { "basename": "Left Arrow", "avLst": (("adj1", 50000), ("adj2", 50000)), }, MSO_SHAPE.LEFT_ARROW_CALLOUT: { "basename": "Left Arrow Callout", "avLst": (("adj1", 25000), ("adj2", 25000), ("adj3", 25000), ("adj4", 64977)), }, MSO_SHAPE.LEFT_BRACE: { "basename": "Left Brace", "avLst": (("adj1", 8333), ("adj2", 50000)), }, MSO_SHAPE.LEFT_BRACKET: {"basename": "Left Bracket", "avLst": (("adj", 8333),)}, MSO_SHAPE.LEFT_CIRCULAR_ARROW: { "basename": "Left Circular Arrow", "avLst": ( ("adj1", 12500), ("adj2", -1142319), ("adj3", 1142319), ("adj4", 10800000), ("adj5", 12500), ), }, MSO_SHAPE.LEFT_RIGHT_ARROW: { "basename": "Left-Right Arrow", "avLst": (("adj1", 50000), ("adj2", 50000)), }, MSO_SHAPE.LEFT_RIGHT_ARROW_CALLOUT: { "basename": "Left-Right Arrow Callout", "avLst": (("adj1", 25000), ("adj2", 25000), ("adj3", 25000), ("adj4", 48123)), }, MSO_SHAPE.LEFT_RIGHT_CIRCULAR_ARROW: { "basename": "Left Right Circular Arrow", "avLst": ( ("adj1", 12500), ("adj2", 1142319), ("adj3", 20457681), ("adj4", 11942319), ("adj5", 12500), ), }, MSO_SHAPE.LEFT_RIGHT_RIBBON: { "basename": "Left Right Ribbon", "avLst": (("adj1", 50000), ("adj2", 50000), ("adj3", 16667)), }, MSO_SHAPE.LEFT_RIGHT_UP_ARROW: { "basename": "Left-Right-Up Arrow", "avLst": (("adj1", 25000), ("adj2", 25000), ("adj3", 25000)), }, MSO_SHAPE.LEFT_UP_ARROW: { "basename": "Left-Up Arrow", "avLst": (("adj1", 25000), ("adj2", 25000), ("adj3", 25000)), }, MSO_SHAPE.LIGHTNING_BOLT: {"basename": "Lightning Bolt", "avLst": ()}, MSO_SHAPE.LINE_CALLOUT_1: { "basename": "Line Callout 1", "avLst": (("adj1", 18750), ("adj2", -8333), ("adj3", 112500), ("adj4", -38333)), }, MSO_SHAPE.LINE_CALLOUT_1_ACCENT_BAR: { "basename": "Line Callout 1 (Accent Bar)", "avLst": (("adj1", 18750), ("adj2", -8333), ("adj3", 112500), ("adj4", -38333)), }, MSO_SHAPE.LINE_CALLOUT_1_BORDER_AND_ACCENT_BAR: { "basename": "Line Callout 1 (Border and Accent Bar)", "avLst": (("adj1", 18750), ("adj2", -8333), ("adj3", 112500), ("adj4", -38333)), }, MSO_SHAPE.LINE_CALLOUT_1_NO_BORDER: { "basename": "Line Callout 1 (No Border)", "avLst": (("adj1", 18750), ("adj2", -8333), ("adj3", 112500), ("adj4", -38333)), }, MSO_SHAPE.LINE_CALLOUT_2: { "basename": "Line Callout 2", "avLst": ( ("adj1", 18750), ("adj2", -8333), ("adj3", 18750), ("adj4", -16667), ("adj5", 112500), ("adj6", -46667), ), }, MSO_SHAPE.LINE_CALLOUT_2_ACCENT_BAR: { "basename": "Line Callout 2 (Accent Bar)", "avLst": ( ("adj1", 18750), ("adj2", -8333), ("adj3", 18750), ("adj4", -16667), ("adj5", 112500), ("adj6", -46667), ), }, MSO_SHAPE.LINE_CALLOUT_2_BORDER_AND_ACCENT_BAR: { "basename": "Line Callout 2 (Border and Accent Bar)", "avLst": ( ("adj1", 18750), ("adj2", -8333), ("adj3", 18750), ("adj4", -16667), ("adj5", 112500), ("adj6", -46667), ), }, MSO_SHAPE.LINE_CALLOUT_2_NO_BORDER: { "basename": "Line Callout 2 (No Border)", "avLst": ( ("adj1", 18750), ("adj2", -8333), ("adj3", 18750), ("adj4", -16667), ("adj5", 112500), ("adj6", -46667), ), }, MSO_SHAPE.LINE_CALLOUT_3: { "basename": "Line Callout 3", "avLst": ( ("adj1", 18750), ("adj2", -8333), ("adj3", 18750), ("adj4", -16667), ("adj5", 100000), ("adj6", -16667), ("adj7", 112963), ("adj8", -8333), ), }, MSO_SHAPE.LINE_CALLOUT_3_ACCENT_BAR: { "basename": "Line Callout 3 (Accent Bar)", "avLst": ( ("adj1", 18750), ("adj2", -8333), ("adj3", 18750), ("adj4", -16667), ("adj5", 100000), ("adj6", -16667), ("adj7", 112963), ("adj8", -8333), ), }, MSO_SHAPE.LINE_CALLOUT_3_BORDER_AND_ACCENT_BAR: { "basename": "Line Callout 3 (Border and Accent Bar)", "avLst": ( ("adj1", 18750), ("adj2", -8333), ("adj3", 18750), ("adj4", -16667), ("adj5", 100000), ("adj6", -16667), ("adj7", 112963), ("adj8", -8333), ), }, MSO_SHAPE.LINE_CALLOUT_3_NO_BORDER: { "basename": "Line Callout 3 (No Border)", "avLst": ( ("adj1", 18750), ("adj2", -8333), ("adj3", 18750), ("adj4", -16667), ("adj5", 100000), ("adj6", -16667), ("adj7", 112963), ("adj8", -8333), ), }, MSO_SHAPE.LINE_CALLOUT_4: { "basename": "Line Callout 3", "avLst": ( ("adj1", 18750), ("adj2", -8333), ("adj3", 18750), ("adj4", -16667), ("adj5", 100000), ("adj6", -16667), ("adj7", 112963), ("adj8", -8333), ), }, MSO_SHAPE.LINE_CALLOUT_4_ACCENT_BAR: { "basename": "Line Callout 3 (Accent Bar)", "avLst": ( ("adj1", 18750), ("adj2", -8333), ("adj3", 18750), ("adj4", -16667), ("adj5", 100000), ("adj6", -16667), ("adj7", 112963), ("adj8", -8333), ), }, MSO_SHAPE.LINE_CALLOUT_4_BORDER_AND_ACCENT_BAR: { "basename": "Line Callout 3 (Border and Accent Bar)", "avLst": ( ("adj1", 18750), ("adj2", -8333), ("adj3", 18750), ("adj4", -16667), ("adj5", 100000), ("adj6", -16667), ("adj7", 112963), ("adj8", -8333), ), }, MSO_SHAPE.LINE_CALLOUT_4_NO_BORDER: { "basename": "Line Callout 3 (No Border)", "avLst": ( ("adj1", 18750), ("adj2", -8333), ("adj3", 18750), ("adj4", -16667), ("adj5", 100000), ("adj6", -16667), ("adj7", 112963), ("adj8", -8333), ), }, MSO_SHAPE.LINE_INVERSE: {"basename": "Straight Connector", "avLst": ()}, MSO_SHAPE.MATH_DIVIDE: { "basename": "Division", "avLst": (("adj1", 23520), ("adj2", 5880), ("adj3", 11760)), }, MSO_SHAPE.MATH_EQUAL: { "basename": "Equal", "avLst": (("adj1", 23520), ("adj2", 11760)), }, MSO_SHAPE.MATH_MINUS: {"basename": "Minus", "avLst": (("adj1", 23520),)}, MSO_SHAPE.MATH_MULTIPLY: {"basename": "Multiply", "avLst": (("adj1", 23520),)}, MSO_SHAPE.MATH_NOT_EQUAL: { "basename": "Not Equal", "avLst": (("adj1", 23520), ("adj2", 6600000), ("adj3", 11760)), }, MSO_SHAPE.MATH_PLUS: {"basename": "Plus", "avLst": (("adj1", 23520),)}, MSO_SHAPE.MOON: {"basename": "Moon", "avLst": (("adj", 50000),)}, MSO_SHAPE.NON_ISOSCELES_TRAPEZOID: { "basename": "Non-isosceles Trapezoid", "avLst": (("adj1", 25000), ("adj2", 25000)), }, MSO_SHAPE.NOTCHED_RIGHT_ARROW: { "basename": "Notched Right Arrow", "avLst": (("adj1", 50000), ("adj2", 50000)), }, MSO_SHAPE.NO_SYMBOL: {"basename": '"No" Symbol', "avLst": (("adj", 18750),)}, MSO_SHAPE.OCTAGON: {"basename": "Octagon", "avLst": (("adj", 29289),)}, MSO_SHAPE.OVAL: {"basename": "Oval", "avLst": ()}, MSO_SHAPE.OVAL_CALLOUT: { "basename": "Oval Callout", "avLst": (("adj1", -20833), ("adj2", 62500)), }, MSO_SHAPE.PARALLELOGRAM: {"basename": "Parallelogram", "avLst": (("adj", 25000),)}, MSO_SHAPE.PENTAGON: {"basename": "Pentagon", "avLst": (("adj", 50000),)}, MSO_SHAPE.PIE: {"basename": "Pie", "avLst": (("adj1", 0), ("adj2", 16200000))}, MSO_SHAPE.PIE_WEDGE: {"basename": "Pie", "avLst": ()}, MSO_SHAPE.PLAQUE: {"basename": "Plaque", "avLst": (("adj", 16667),)}, MSO_SHAPE.PLAQUE_TABS: {"basename": "Plaque Tabs", "avLst": ()}, MSO_SHAPE.QUAD_ARROW: { "basename": "Quad Arrow", "avLst": (("adj1", 22500), ("adj2", 22500), ("adj3", 22500)), }, MSO_SHAPE.QUAD_ARROW_CALLOUT: { "basename": "Quad Arrow Callout", "avLst": (("adj1", 18515), ("adj2", 18515), ("adj3", 18515), ("adj4", 48123)), }, MSO_SHAPE.RECTANGLE: {"basename": "Rectangle", "avLst": ()}, MSO_SHAPE.RECTANGULAR_CALLOUT: { "basename": "Rectangular Callout", "avLst": (("adj1", -20833), ("adj2", 62500)), }, MSO_SHAPE.REGULAR_PENTAGON: { "basename": "Regular Pentagon", "avLst": (("hf", 105146), ("vf", 110557)), }, MSO_SHAPE.RIGHT_ARROW: { "basename": "Right Arrow", "avLst": (("adj1", 50000), ("adj2", 50000)), }, MSO_SHAPE.RIGHT_ARROW_CALLOUT: { "basename": "Right Arrow Callout", "avLst": (("adj1", 25000), ("adj2", 25000), ("adj3", 25000), ("adj4", 64977)), }, MSO_SHAPE.RIGHT_BRACE: { "basename": "Right Brace", "avLst": (("adj1", 8333), ("adj2", 50000)), }, MSO_SHAPE.RIGHT_BRACKET: {"basename": "Right Bracket", "avLst": (("adj", 8333),)}, MSO_SHAPE.RIGHT_TRIANGLE: {"basename": "Right Triangle", "avLst": ()}, MSO_SHAPE.ROUNDED_RECTANGLE: { "basename": "Rounded Rectangle", "avLst": (("adj", 16667),), }, MSO_SHAPE.ROUNDED_RECTANGULAR_CALLOUT: { "basename": "Rounded Rectangular Callout", "avLst": (("adj1", -20833), ("adj2", 62500), ("adj3", 16667)), }, MSO_SHAPE.ROUND_1_RECTANGLE: { "basename": "Round Single Corner Rectangle", "avLst": (("adj", 16667),), }, MSO_SHAPE.ROUND_2_DIAG_RECTANGLE: { "basename": "Round Diagonal Corner Rectangle", "avLst": (("adj1", 16667), ("adj2", 0)), }, MSO_SHAPE.ROUND_2_SAME_RECTANGLE: { "basename": "Round Same Side Corner Rectangle", "avLst": (("adj1", 16667), ("adj2", 0)), }, MSO_SHAPE.SMILEY_FACE: {"basename": "Smiley Face", "avLst": (("adj", 4653),)}, MSO_SHAPE.SNIP_1_RECTANGLE: { "basename": "Snip Single Corner Rectangle", "avLst": (("adj", 16667),), }, MSO_SHAPE.SNIP_2_DIAG_RECTANGLE: { "basename": "Snip Diagonal Corner Rectangle", "avLst": (("adj1", 0), ("adj2", 16667)), }, MSO_SHAPE.SNIP_2_SAME_RECTANGLE: { "basename": "Snip Same Side Corner Rectangle", "avLst": (("adj1", 16667), ("adj2", 0)), }, MSO_SHAPE.SNIP_ROUND_RECTANGLE: { "basename": "Snip and Round Single Corner Rectangle", "avLst": (("adj1", 16667), ("adj2", 16667)), }, MSO_SHAPE.SQUARE_TABS: {"basename": "Square Tabs", "avLst": ()}, MSO_SHAPE.STAR_10_POINT: { "basename": "10-Point Star", "avLst": (("adj", 42533), ("hf", 105146)), }, MSO_SHAPE.STAR_12_POINT: {"basename": "12-Point Star", "avLst": (("adj", 37500),)}, MSO_SHAPE.STAR_16_POINT: {"basename": "16-Point Star", "avLst": (("adj", 37500),)}, MSO_SHAPE.STAR_24_POINT: {"basename": "24-Point Star", "avLst": (("adj", 37500),)}, MSO_SHAPE.STAR_32_POINT: {"basename": "32-Point Star", "avLst": (("adj", 37500),)}, MSO_SHAPE.STAR_4_POINT: {"basename": "4-Point Star", "avLst": (("adj", 12500),)}, MSO_SHAPE.STAR_5_POINT: { "basename": "5-Point Star", "avLst": (("adj", 19098), ("hf", 105146), ("vf", 110557)), }, MSO_SHAPE.STAR_6_POINT: { "basename": "6-Point Star", "avLst": (("adj", 28868), ("hf", 115470)), }, MSO_SHAPE.STAR_7_POINT: { "basename": "7-Point Star", "avLst": (("adj", 34601), ("hf", 102572), ("vf", 105210)), }, MSO_SHAPE.STAR_8_POINT: {"basename": "8-Point Star", "avLst": (("adj", 37500),)}, MSO_SHAPE.STRIPED_RIGHT_ARROW: { "basename": "Striped Right Arrow", "avLst": (("adj1", 50000), ("adj2", 50000)), }, MSO_SHAPE.SUN: {"basename": "Sun", "avLst": (("adj", 25000),)}, MSO_SHAPE.SWOOSH_ARROW: { "basename": "Swoosh Arrow", "avLst": (("adj1", 25000), ("adj2", 16667)), }, MSO_SHAPE.TEAR: {"basename": "Teardrop", "avLst": (("adj", 100000),)}, MSO_SHAPE.TRAPEZOID: {"basename": "Trapezoid", "avLst": (("adj", 25000),)}, MSO_SHAPE.UP_ARROW: { "basename": "Up Arrow", "avLst": (("adj1", 50000), ("adj2", 50000)), }, MSO_SHAPE.UP_ARROW_CALLOUT: { "basename": "Up Arrow Callout", "avLst": (("adj1", 25000), ("adj2", 25000), ("adj3", 25000), ("adj4", 64977)), }, MSO_SHAPE.UP_DOWN_ARROW: { "basename": "Up-Down Arrow", "avLst": (("adj1", 50000), ("adj1", 50000), ("adj2", 50000), ("adj2", 50000)), }, MSO_SHAPE.UP_DOWN_ARROW_CALLOUT: { "basename": "Up-Down Arrow Callout", "avLst": (("adj1", 25000), ("adj2", 25000), ("adj3", 25000), ("adj4", 48123)), }, MSO_SHAPE.UP_RIBBON: { "basename": "Up Ribbon", "avLst": (("adj1", 16667), ("adj2", 50000)), }, MSO_SHAPE.U_TURN_ARROW: { "basename": "U-Turn Arrow", "avLst": ( ("adj1", 25000), ("adj2", 25000), ("adj3", 25000), ("adj4", 43750), ("adj5", 75000), ), }, MSO_SHAPE.VERTICAL_SCROLL: { "basename": "Vertical Scroll", "avLst": (("adj", 12500),), }, MSO_SHAPE.WAVE: {"basename": "Wave", "avLst": (("adj1", 12500), ("adj2", 0))},}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496"""Table-related objects such as Table and Cell."""
from __future__ import annotations
from typing import TYPE_CHECKING, Iterator
from pptx.dml.fill import FillFormatfrom pptx.oxml.table import TcRangefrom pptx.shapes import Subshapefrom pptx.text.text import TextFramefrom pptx.util import Emu, lazyproperty
if TYPE_CHECKING: from pptx.enum.text import MSO_VERTICAL_ANCHOR from pptx.oxml.table import CT_Table, CT_TableCell, CT_TableCol, CT_TableRow from pptx.parts.slide import BaseSlidePart from pptx.shapes.graphfrm import GraphicFrame from pptx.types import ProvidesPart from pptx.util import Length
class Table(object): """A DrawingML table object.
Not intended to be constructed directly, use :meth:`.Slide.shapes.add_table` to add a table to a slide. """
def __init__(self, tbl: CT_Table, graphic_frame: GraphicFrame): super(Table, self).__init__() self._tbl = tbl self._graphic_frame = graphic_frame
def cell(self, row_idx: int, col_idx: int) -> _Cell: """Return cell at `row_idx`, `col_idx`.
Return value is an instance of |_Cell|. `row_idx` and `col_idx` are zero-based, e.g. cell(0, 0) is the top, left cell in the table. """ return _Cell(self._tbl.tc(row_idx, col_idx), self)
@lazyproperty def columns(self) -> _ColumnCollection: """|_ColumnCollection| instance for this table.
Provides access to |_Column| objects representing the table's columns. |_Column| objects are accessed using list notation, e.g. `col = tbl.columns[0]`. """ return _ColumnCollection(self._tbl, self)
@property def first_col(self) -> bool: """When `True`, indicates first column should have distinct formatting.
Read/write. Distinct formatting is used, for example, when the first column contains row headings (is a side-heading column). """ return self._tbl.firstCol
@first_col.setter def first_col(self, value: bool): self._tbl.firstCol = value
@property def first_row(self) -> bool: """When `True`, indicates first row should have distinct formatting.
Read/write. Distinct formatting is used, for example, when the first row contains column headings. """ return self._tbl.firstRow
@first_row.setter def first_row(self, value: bool): self._tbl.firstRow = value
@property def horz_banding(self) -> bool: """When `True`, indicates rows should have alternating shading.
Read/write. Used to allow rows to be traversed more easily without losing track of which row is being read. """ return self._tbl.bandRow
@horz_banding.setter def horz_banding(self, value: bool): self._tbl.bandRow = value
def iter_cells(self) -> Iterator[_Cell]: """Generate _Cell object for each cell in this table.
Each grid cell is generated in left-to-right, top-to-bottom order. """ return (_Cell(tc, self) for tc in self._tbl.iter_tcs())
@property def last_col(self) -> bool: """When `True`, indicates the rightmost column should have distinct formatting.
Read/write. Used, for example, when a row totals column appears at the far right of the table. """ return self._tbl.lastCol
@last_col.setter def last_col(self, value: bool): self._tbl.lastCol = value
@property def last_row(self) -> bool: """When `True`, indicates the bottom row should have distinct formatting.
Read/write. Used, for example, when a totals row appears as the bottom row. """ return self._tbl.lastRow
@last_row.setter def last_row(self, value: bool): self._tbl.lastRow = value
def notify_height_changed(self) -> None: """Called by a row when its height changes.
Triggers the graphic frame to recalculate its total height (as the sum of the row heights). """ new_table_height = Emu(sum([row.height for row in self.rows])) self._graphic_frame.height = new_table_height
def notify_width_changed(self) -> None: """Called by a column when its width changes.
Triggers the graphic frame to recalculate its total width (as the sum of the column widths). """ new_table_width = Emu(sum([col.width for col in self.columns])) self._graphic_frame.width = new_table_width
@property def part(self) -> BaseSlidePart: """The package part containing this table.""" return self._graphic_frame.part
@lazyproperty def rows(self): """|_RowCollection| instance for this table.
Provides access to |_Row| objects representing the table's rows. |_Row| objects are accessed using list notation, e.g. `col = tbl.rows[0]`. """ return _RowCollection(self._tbl, self)
@property def vert_banding(self) -> bool: """When `True`, indicates columns should have alternating shading.
Read/write. Used to allow columns to be traversed more easily without losing track of which column is being read. """ return self._tbl.bandCol
@vert_banding.setter def vert_banding(self, value: bool): self._tbl.bandCol = value
class _Cell(Subshape): """Table cell"""
def __init__(self, tc: CT_TableCell, parent: ProvidesPart): super(_Cell, self).__init__(parent) self._tc = tc
def __eq__(self, other: object) -> bool: """|True| if this object proxies the same element as `other`.
Equality for proxy objects is defined as referring to the same XML element, whether or not they are the same proxy object instance. """ if not isinstance(other, type(self)): return False return self._tc is other._tc
def __ne__(self, other: object) -> bool: if not isinstance(other, type(self)): return True return self._tc is not other._tc
@lazyproperty def fill(self) -> FillFormat: """|FillFormat| instance for this cell.
Provides access to fill properties such as foreground color. """ tcPr = self._tc.get_or_add_tcPr() return FillFormat.from_fill_parent(tcPr)
@property def is_merge_origin(self) -> bool: """True if this cell is the top-left grid cell in a merged cell.""" return self._tc.is_merge_origin
@property def is_spanned(self) -> bool: """True if this cell is spanned by a merge-origin cell.
A merge-origin cell "spans" the other grid cells in its merge range, consuming their area and "shadowing" the spanned grid cells.
Note this value is |False| for a merge-origin cell. A merge-origin cell spans other grid cells, but is not itself a spanned cell. """ return self._tc.is_spanned
@property def margin_left(self) -> Length: """Left margin of cells.
Read/write. If assigned |None|, the default value is used, 0.1 inches for left and right margins and 0.05 inches for top and bottom. """ return self._tc.marL
@margin_left.setter def margin_left(self, margin_left: Length | None): self._validate_margin_value(margin_left) self._tc.marL = margin_left
@property def margin_right(self) -> Length: """Right margin of cell.""" return self._tc.marR
@margin_right.setter def margin_right(self, margin_right: Length | None): self._validate_margin_value(margin_right) self._tc.marR = margin_right
@property def margin_top(self) -> Length: """Top margin of cell.""" return self._tc.marT
@margin_top.setter def margin_top(self, margin_top: Length | None): self._validate_margin_value(margin_top) self._tc.marT = margin_top
@property def margin_bottom(self) -> Length: """Bottom margin of cell.""" return self._tc.marB
@margin_bottom.setter def margin_bottom(self, margin_bottom: Length | None): self._validate_margin_value(margin_bottom) self._tc.marB = margin_bottom
def merge(self, other_cell: _Cell) -> None: """Create merged cell from this cell to `other_cell`.
This cell and `other_cell` specify opposite corners of the merged cell range. Either diagonal of the cell region may be specified in either order, e.g. self=bottom-right, other_cell=top-left, etc.
Raises |ValueError| if the specified range already contains merged cells anywhere within its extents or if `other_cell` is not in the same table as `self`. """ tc_range = TcRange(self._tc, other_cell._tc)
if not tc_range.in_same_table: raise ValueError("other_cell from different table") if tc_range.contains_merged_cell: raise ValueError("range contains one or more merged cells")
tc_range.move_content_to_origin()
row_count, col_count = tc_range.dimensions
for tc in tc_range.iter_top_row_tcs(): tc.rowSpan = row_count for tc in tc_range.iter_left_col_tcs(): tc.gridSpan = col_count for tc in tc_range.iter_except_left_col_tcs(): tc.hMerge = True for tc in tc_range.iter_except_top_row_tcs(): tc.vMerge = True
@property def span_height(self) -> int: """int count of rows spanned by this cell.
The value of this property may be misleading (often 1) on cells where `.is_merge_origin` is not |True|, since only a merge-origin cell contains complete span information. This property is only intended for use on cells known to be a merge origin by testing `.is_merge_origin`. """ return self._tc.rowSpan
@property def span_width(self) -> int: """int count of columns spanned by this cell.
The value of this property may be misleading (often 1) on cells where `.is_merge_origin` is not |True|, since only a merge-origin cell contains complete span information. This property is only intended for use on cells known to be a merge origin by testing `.is_merge_origin`. """ return self._tc.gridSpan
def split(self) -> None: """Remove merge from this (merge-origin) cell.
The merged cell represented by this object will be "unmerged", yielding a separate unmerged cell for each grid cell previously spanned by this merge.
Raises |ValueError| when this cell is not a merge-origin cell. Test with `.is_merge_origin` before calling. """ if not self.is_merge_origin: raise ValueError("not a merge-origin cell; only a merge-origin cell can be sp" "lit")
tc_range = TcRange.from_merge_origin(self._tc)
for tc in tc_range.iter_tcs(): tc.rowSpan = tc.gridSpan = 1 tc.hMerge = tc.vMerge = False
@property def text(self) -> str: """Textual content of cell as a single string.
The returned string will contain a newline character (`"\\n"`) separating each paragraph and a vertical-tab (`"\\v"`) character for each line break (soft carriage return) in the cell's text.
Assignment to `text` replaces all text currently contained in the cell. A newline character (`"\\n"`) in the assigned text causes a new paragraph to be started. A vertical-tab (`"\\v"`) character in the assigned text causes a line-break (soft carriage-return) to be inserted. (The vertical-tab character appears in clipboard text copied from PowerPoint as its encoding of line-breaks.) """ return self.text_frame.text
@text.setter def text(self, text: str): self.text_frame.text = text
@property def text_frame(self) -> TextFrame: """|TextFrame| containing the text that appears in the cell.""" txBody = self._tc.get_or_add_txBody() return TextFrame(txBody, self)
@property def vertical_anchor(self) -> MSO_VERTICAL_ANCHOR | None: """Vertical alignment of this cell.
This value is a member of the :ref:`MsoVerticalAnchor` enumeration or |None|. A value of |None| indicates the cell has no explicitly applied vertical anchor setting and its effective value is inherited from its style-hierarchy ancestors.
Assigning |None| to this property causes any explicitly applied vertical anchor setting to be cleared and inheritance of its effective value to be restored. """ return self._tc.anchor
@vertical_anchor.setter def vertical_anchor(self, mso_anchor_idx: MSO_VERTICAL_ANCHOR | None): self._tc.anchor = mso_anchor_idx
@staticmethod def _validate_margin_value(margin_value: Length | None) -> None: """Raise ValueError if `margin_value` is not a positive integer value or |None|.""" if not isinstance(margin_value, int) and margin_value is not None: tmpl = "margin value must be integer or None, got '%s'" raise TypeError(tmpl % margin_value)
class _Column(Subshape): """Table column"""
def __init__(self, gridCol: CT_TableCol, parent: _ColumnCollection): super(_Column, self).__init__(parent) self._parent = parent self._gridCol = gridCol
@property def width(self) -> Length: """Width of column in EMU.""" return self._gridCol.w
@width.setter def width(self, width: Length): self._gridCol.w = width self._parent.notify_width_changed()
class _Row(Subshape): """Table row"""
def __init__(self, tr: CT_TableRow, parent: _RowCollection): super(_Row, self).__init__(parent) self._parent = parent self._tr = tr
@property def cells(self): """Read-only reference to collection of cells in row.
An individual cell is referenced using list notation, e.g. `cell = row.cells[0]`. """ return _CellCollection(self._tr, self)
@property def height(self) -> Length: """Height of row in EMU.""" return self._tr.h
@height.setter def height(self, height: Length): self._tr.h = height self._parent.notify_height_changed()
class _CellCollection(Subshape): """Horizontal sequence of row cells"""
def __init__(self, tr: CT_TableRow, parent: _Row): super(_CellCollection, self).__init__(parent) self._parent = parent self._tr = tr
def __getitem__(self, idx: int) -> _Cell: """Provides indexed access, (e.g. 'cells[0]').""" if idx < 0 or idx >= len(self._tr.tc_lst): msg = "cell index [%d] out of range" % idx raise IndexError(msg) return _Cell(self._tr.tc_lst[idx], self)
def __iter__(self) -> Iterator[_Cell]: """Provides iterability.""" return (_Cell(tc, self) for tc in self._tr.tc_lst)
def __len__(self) -> int: """Supports len() function (e.g. 'len(cells) == 1').""" return len(self._tr.tc_lst)
class _ColumnCollection(Subshape): """Sequence of table columns."""
def __init__(self, tbl: CT_Table, parent: Table): super(_ColumnCollection, self).__init__(parent) self._parent = parent self._tbl = tbl
def __getitem__(self, idx: int): """Provides indexed access, (e.g. 'columns[0]').""" if idx < 0 or idx >= len(self._tbl.tblGrid.gridCol_lst): msg = "column index [%d] out of range" % idx raise IndexError(msg) return _Column(self._tbl.tblGrid.gridCol_lst[idx], self)
def __len__(self): """Supports len() function (e.g. 'len(columns) == 1').""" return len(self._tbl.tblGrid.gridCol_lst)
def notify_width_changed(self): """Called by a column when its width changes. Pass along to parent.""" self._parent.notify_width_changed()
class _RowCollection(Subshape): """Sequence of table rows"""
def __init__(self, tbl: CT_Table, parent: Table): super(_RowCollection, self).__init__(parent) self._parent = parent self._tbl = tbl
def __getitem__(self, idx: int) -> _Row: """Provides indexed access, (e.g. 'rows[0]').""" if idx < 0 or idx >= len(self): msg = "row index [%d] out of range" % idx raise IndexError(msg) return _Row(self._tbl.tr_lst[idx], self)
def __len__(self): """Supports len() function (e.g. 'len(rows) == 1').""" return len(self._tbl.tr_lst)
def notify_height_changed(self): """Called by a row when its height changes. Pass along to parent.""" self._parent.notify_height_changed()1234567891011121314151617181920212223<?xml version='1.0' encoding='UTF-8' standalone='yes'?><p:notes xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"> <p:cSld> <p:spTree> <p:nvGrpSpPr> <p:cNvPr id="1" name=""/> <p:cNvGrpSpPr/> <p:nvPr/> </p:nvGrpSpPr> <p:grpSpPr> <a:xfrm> <a:off x="0" y="0"/> <a:ext cx="0" cy="0"/> <a:chOff x="0" y="0"/> <a:chExt cx="0" cy="0"/> </a:xfrm> </p:grpSpPr> </p:spTree> </p:cSld> <p:clrMapOvr> <a:masterClrMapping/> </p:clrMapOvr></p:notes>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352<?xml version='1.0' encoding='UTF-8' standalone='yes'?><p:notesMaster xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" > <p:cSld> <p:bg> <p:bgRef idx="1001"> <a:schemeClr val="bg1"/> </p:bgRef> </p:bg> <p:spTree> <p:nvGrpSpPr> <p:cNvPr id="1" name=""/> <p:cNvGrpSpPr/> <p:nvPr/> </p:nvGrpSpPr> <p:grpSpPr> <a:xfrm> <a:off x="0" y="0"/> <a:ext cx="0" cy="0"/> <a:chOff x="0" y="0"/> <a:chExt cx="0" cy="0"/> </a:xfrm> </p:grpSpPr> <p:sp> <p:nvSpPr> <p:cNvPr id="2" name="Header Placeholder 1"/> <p:cNvSpPr> <a:spLocks noGrp="1"/> </p:cNvSpPr> <p:nvPr> <p:ph type="hdr" sz="quarter"/> </p:nvPr> </p:nvSpPr> <p:spPr> <a:xfrm> <a:off x="0" y="0"/> <a:ext cx="2971800" cy="457200"/> </a:xfrm> <a:prstGeom prst="rect"> <a:avLst/> </a:prstGeom> </p:spPr> <p:txBody> <a:bodyPr vert="horz" lIns="91440" tIns="45720" rIns="91440" bIns="45720" rtlCol="0"/> <a:lstStyle> <a:lvl1pPr algn="l"> <a:defRPr sz="1200"/> </a:lvl1pPr> </a:lstStyle> <a:p> <a:endParaRPr lang="en-US"/> </a:p> </p:txBody> </p:sp> <p:sp> <p:nvSpPr> <p:cNvPr id="3" name="Date Placeholder 2"/> <p:cNvSpPr> <a:spLocks noGrp="1"/> </p:cNvSpPr> <p:nvPr> <p:ph type="dt" idx="1"/> </p:nvPr> </p:nvSpPr> <p:spPr> <a:xfrm> <a:off x="3884613" y="0"/> <a:ext cx="2971800" cy="457200"/> </a:xfrm> <a:prstGeom prst="rect"> <a:avLst/> </a:prstGeom> </p:spPr> <p:txBody> <a:bodyPr vert="horz" lIns="91440" tIns="45720" rIns="91440" bIns="45720" rtlCol="0"/> <a:lstStyle> <a:lvl1pPr algn="r"> <a:defRPr sz="1200"/> </a:lvl1pPr> </a:lstStyle> <a:p> <a:fld id="{0F89C1C7-3DCD-1040-A9CF-14679D8B5DDD}" type="datetimeFigureOut"> <a:rPr lang="en-US" smtClean="0"/> <a:t>10/17/16</a:t> </a:fld> <a:endParaRPr lang="en-US"/> </a:p> </p:txBody> </p:sp> <p:sp> <p:nvSpPr> <p:cNvPr id="4" name="Slide Image Placeholder 3"/> <p:cNvSpPr> <a:spLocks noGrp="1" noRot="1" noChangeAspect="1"/> </p:cNvSpPr> <p:nvPr> <p:ph type="sldImg" idx="2"/> </p:nvPr> </p:nvSpPr> <p:spPr> <a:xfrm> <a:off x="1143000" y="685800"/> <a:ext cx="4572000" cy="3429000"/> </a:xfrm> <a:prstGeom prst="rect"> <a:avLst/> </a:prstGeom> <a:noFill/> <a:ln w="12700"> <a:solidFill> <a:prstClr val="black"/> </a:solidFill> </a:ln> </p:spPr> <p:txBody> <a:bodyPr vert="horz" lIns="91440" tIns="45720" rIns="91440" bIns="45720" rtlCol="0" anchor="ctr"/> <a:lstStyle/> <a:p> <a:endParaRPr lang="en-US"/> </a:p> </p:txBody> </p:sp> <p:sp> <p:nvSpPr> <p:cNvPr id="5" name="Notes Placeholder 4"/> <p:cNvSpPr> <a:spLocks noGrp="1"/> </p:cNvSpPr> <p:nvPr> <p:ph type="body" sz="quarter" idx="3"/> </p:nvPr> </p:nvSpPr> <p:spPr> <a:xfrm> <a:off x="685800" y="4343400"/> <a:ext cx="5486400" cy="4114800"/> </a:xfrm> <a:prstGeom prst="rect"> <a:avLst/> </a:prstGeom> </p:spPr> <p:txBody> <a:bodyPr vert="horz" lIns="91440" tIns="45720" rIns="91440" bIns="45720" rtlCol="0"/> <a:lstStyle/> <a:p> <a:pPr lvl="0"/> <a:r> <a:rPr lang="en-US" smtClean="0"/> <a:t>Click to edit Master text styles</a:t> </a:r> </a:p> <a:p> <a:pPr lvl="1"/> <a:r> <a:rPr lang="en-US" smtClean="0"/> <a:t>Second level</a:t> </a:r> </a:p> <a:p> <a:pPr lvl="2"/> <a:r> <a:rPr lang="en-US" smtClean="0"/> <a:t>Third level</a:t> </a:r> </a:p> <a:p> <a:pPr lvl="3"/> <a:r> <a:rPr lang="en-US" smtClean="0"/> <a:t>Fourth level</a:t> </a:r> </a:p> <a:p> <a:pPr lvl="4"/> <a:r> <a:rPr lang="en-US" smtClean="0"/> <a:t>Fifth level</a:t> </a:r> <a:endParaRPr lang="en-US"/> </a:p> </p:txBody> </p:sp> <p:sp> <p:nvSpPr> <p:cNvPr id="6" name="Footer Placeholder 5"/> <p:cNvSpPr> <a:spLocks noGrp="1"/> </p:cNvSpPr> <p:nvPr> <p:ph type="ftr" sz="quarter" idx="4"/> </p:nvPr> </p:nvSpPr> <p:spPr> <a:xfrm> <a:off x="0" y="8685213"/> <a:ext cx="2971800" cy="457200"/> </a:xfrm> <a:prstGeom prst="rect"> <a:avLst/> </a:prstGeom> </p:spPr> <p:txBody> <a:bodyPr vert="horz" lIns="91440" tIns="45720" rIns="91440" bIns="45720" rtlCol="0" anchor="b"/> <a:lstStyle> <a:lvl1pPr algn="l"> <a:defRPr sz="1200"/> </a:lvl1pPr> </a:lstStyle> <a:p> <a:endParaRPr lang="en-US"/> </a:p> </p:txBody> </p:sp> <p:sp> <p:nvSpPr> <p:cNvPr id="7" name="Slide Number Placeholder 6"/> <p:cNvSpPr> <a:spLocks noGrp="1"/> </p:cNvSpPr> <p:nvPr> <p:ph type="sldNum" sz="quarter" idx="5"/> </p:nvPr> </p:nvSpPr> <p:spPr> <a:xfrm> <a:off x="3884613" y="8685213"/> <a:ext cx="2971800" cy="457200"/> </a:xfrm> <a:prstGeom prst="rect"> <a:avLst/> </a:prstGeom> </p:spPr> <p:txBody> <a:bodyPr vert="horz" lIns="91440" tIns="45720" rIns="91440" bIns="45720" rtlCol="0" anchor="b"/> <a:lstStyle> <a:lvl1pPr algn="r"> <a:defRPr sz="1200"/> </a:lvl1pPr> </a:lstStyle> <a:p> <a:fld id="{BB5E49A5-4136-284D-997B-48E1D791AD67}" type="slidenum"> <a:rPr lang="en-US" smtClean="0"/> <a:t>‹#›</a:t> </a:fld> <a:endParaRPr lang="en-US"/> </a:p> </p:txBody> </p:sp> </p:spTree> <p:extLst> <p:ext uri="{BB962C8B-B14F-4D97-AF65-F5344CB8AC3E}"> <p14:creationId xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="2623252185"/> </p:ext> </p:extLst> </p:cSld> <p:clrMap bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" accent2="accent2" accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/> <p:notesStyle> <a:lvl1pPr marL="0" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"> <a:defRPr sz="1200" kern="1200"> <a:solidFill> <a:schemeClr val="tx1"/> </a:solidFill> <a:latin typeface="+mn-lt"/> <a:ea typeface="+mn-ea"/> <a:cs typeface="+mn-cs"/> </a:defRPr> </a:lvl1pPr> <a:lvl2pPr marL="457200" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"> <a:defRPr sz="1200" kern="1200"> <a:solidFill> <a:schemeClr val="tx1"/> </a:solidFill> <a:latin typeface="+mn-lt"/> <a:ea typeface="+mn-ea"/> <a:cs typeface="+mn-cs"/> </a:defRPr> </a:lvl2pPr> <a:lvl3pPr marL="914400" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"> <a:defRPr sz="1200" kern="1200"> <a:solidFill> <a:schemeClr val="tx1"/> </a:solidFill> <a:latin typeface="+mn-lt"/> <a:ea typeface="+mn-ea"/> <a:cs typeface="+mn-cs"/> </a:defRPr> </a:lvl3pPr> <a:lvl4pPr marL="1371600" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"> <a:defRPr sz="1200" kern="1200"> <a:solidFill> <a:schemeClr val="tx1"/> </a:solidFill> <a:latin typeface="+mn-lt"/> <a:ea typeface="+mn-ea"/> <a:cs typeface="+mn-cs"/> </a:defRPr> </a:lvl4pPr> <a:lvl5pPr marL="1828800" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"> <a:defRPr sz="1200" kern="1200"> <a:solidFill> <a:schemeClr val="tx1"/> </a:solidFill> <a:latin typeface="+mn-lt"/> <a:ea typeface="+mn-ea"/> <a:cs typeface="+mn-cs"/> </a:defRPr> </a:lvl5pPr> <a:lvl6pPr marL="2286000" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"> <a:defRPr sz="1200" kern="1200"> <a:solidFill> <a:schemeClr val="tx1"/> </a:solidFill> <a:latin typeface="+mn-lt"/> <a:ea typeface="+mn-ea"/> <a:cs typeface="+mn-cs"/> </a:defRPr> </a:lvl6pPr> <a:lvl7pPr marL="2743200" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"> <a:defRPr sz="1200" kern="1200"> <a:solidFill> <a:schemeClr val="tx1"/> </a:solidFill> <a:latin typeface="+mn-lt"/> <a:ea typeface="+mn-ea"/> <a:cs typeface="+mn-cs"/> </a:defRPr> </a:lvl7pPr> <a:lvl8pPr marL="3200400" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"> <a:defRPr sz="1200" kern="1200"> <a:solidFill> <a:schemeClr val="tx1"/> </a:solidFill> <a:latin typeface="+mn-lt"/> <a:ea typeface="+mn-ea"/> <a:cs typeface="+mn-cs"/> </a:defRPr> </a:lvl8pPr> <a:lvl9pPr marL="3657600" algn="l" defTabSz="457200" rtl="0" eaLnBrk="1" latinLnBrk="0" hangingPunct="1"> <a:defRPr sz="1200" kern="1200"> <a:solidFill> <a:schemeClr val="tx1"/> </a:solidFill> <a:latin typeface="+mn-lt"/> <a:ea typeface="+mn-ea"/> <a:cs typeface="+mn-cs"/> </a:defRPr> </a:lvl9pPr> </p:notesStyle></p:notesMaster>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321<?xml version='1.0' encoding='UTF-8' standalone='yes'?><a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme" > <a:themeElements> <a:clrScheme name="Office"> <a:dk1> <a:sysClr val="windowText" lastClr="000000"/> </a:dk1> <a:lt1> <a:sysClr val="window" lastClr="FFFFFF"/> </a:lt1> <a:dk2> <a:srgbClr val="1F497D"/> </a:dk2> <a:lt2> <a:srgbClr val="EEECE1"/> </a:lt2> <a:accent1> <a:srgbClr val="4F81BD"/> </a:accent1> <a:accent2> <a:srgbClr val="C0504D"/> </a:accent2> <a:accent3> <a:srgbClr val="9BBB59"/> </a:accent3> <a:accent4> <a:srgbClr val="8064A2"/> </a:accent4> <a:accent5> <a:srgbClr val="4BACC6"/> </a:accent5> <a:accent6> <a:srgbClr val="F79646"/> </a:accent6> <a:hlink> <a:srgbClr val="0000FF"/> </a:hlink> <a:folHlink> <a:srgbClr val="800080"/> </a:folHlink> </a:clrScheme> <a:fontScheme name="Office"> <a:majorFont> <a:latin typeface="Calibri"/> <a:ea typeface=""/> <a:cs typeface=""/> <a:font script="Jpan" typeface="MS Pゴシック"/> <a:font script="Hang" typeface="맑은 고딕"/> <a:font script="Hans" typeface="宋体"/> <a:font script="Hant" typeface="新細明體"/> <a:font script="Arab" typeface="Times New Roman"/> <a:font script="Hebr" typeface="Times New Roman"/> <a:font script="Thai" typeface="Angsana New"/> <a:font script="Ethi" typeface="Nyala"/> <a:font script="Beng" typeface="Vrinda"/> <a:font script="Gujr" typeface="Shruti"/> <a:font script="Khmr" typeface="MoolBoran"/> <a:font script="Knda" typeface="Tunga"/> <a:font script="Guru" typeface="Raavi"/> <a:font script="Cans" typeface="Euphemia"/> <a:font script="Cher" typeface="Plantagenet Cherokee"/> <a:font script="Yiii" typeface="Microsoft Yi Baiti"/> <a:font script="Tibt" typeface="Microsoft Himalaya"/> <a:font script="Thaa" typeface="MV Boli"/> <a:font script="Deva" typeface="Mangal"/> <a:font script="Telu" typeface="Gautami"/> <a:font script="Taml" typeface="Latha"/> <a:font script="Syrc" typeface="Estrangelo Edessa"/> <a:font script="Orya" typeface="Kalinga"/> <a:font script="Mlym" typeface="Kartika"/> <a:font script="Laoo" typeface="DokChampa"/> <a:font script="Sinh" typeface="Iskoola Pota"/> <a:font script="Mong" typeface="Mongolian Baiti"/> <a:font script="Viet" typeface="Times New Roman"/> <a:font script="Uigh" typeface="Microsoft Uighur"/> <a:font script="Geor" typeface="Sylfaen"/> </a:majorFont> <a:minorFont> <a:latin typeface="Calibri"/> <a:ea typeface=""/> <a:cs typeface=""/> <a:font script="Jpan" typeface="MS Pゴシック"/> <a:font script="Hang" typeface="맑은 고딕"/> <a:font script="Hans" typeface="宋体"/> <a:font script="Hant" typeface="新細明體"/> <a:font script="Arab" typeface="Arial"/> <a:font script="Hebr" typeface="Arial"/> <a:font script="Thai" typeface="Cordia New"/> <a:font script="Ethi" typeface="Nyala"/> <a:font script="Beng" typeface="Vrinda"/> <a:font script="Gujr" typeface="Shruti"/> <a:font script="Khmr" typeface="DaunPenh"/> <a:font script="Knda" typeface="Tunga"/> <a:font script="Guru" typeface="Raavi"/> <a:font script="Cans" typeface="Euphemia"/> <a:font script="Cher" typeface="Plantagenet Cherokee"/> <a:font script="Yiii" typeface="Microsoft Yi Baiti"/> <a:font script="Tibt" typeface="Microsoft Himalaya"/> <a:font script="Thaa" typeface="MV Boli"/> <a:font script="Deva" typeface="Mangal"/> <a:font script="Telu" typeface="Gautami"/> <a:font script="Taml" typeface="Latha"/> <a:font script="Syrc" typeface="Estrangelo Edessa"/> <a:font script="Orya" typeface="Kalinga"/> <a:font script="Mlym" typeface="Kartika"/> <a:font script="Laoo" typeface="DokChampa"/> <a:font script="Sinh" typeface="Iskoola Pota"/> <a:font script="Mong" typeface="Mongolian Baiti"/> <a:font script="Viet" typeface="Arial"/> <a:font script="Uigh" typeface="Microsoft Uighur"/> <a:font script="Geor" typeface="Sylfaen"/> </a:minorFont> </a:fontScheme> <a:fmtScheme name="Office"> <a:fillStyleLst> <a:solidFill> <a:schemeClr val="phClr"/> </a:solidFill> <a:gradFill rotWithShape="1"> <a:gsLst> <a:gs pos="0"> <a:schemeClr val="phClr"> <a:tint val="50000"/> <a:satMod val="300000"/> </a:schemeClr> </a:gs> <a:gs pos="35000"> <a:schemeClr val="phClr"> <a:tint val="37000"/> <a:satMod val="300000"/> </a:schemeClr> </a:gs> <a:gs pos="100000"> <a:schemeClr val="phClr"> <a:tint val="15000"/> <a:satMod val="350000"/> </a:schemeClr> </a:gs> </a:gsLst> <a:lin ang="16200000" scaled="1"/> </a:gradFill> <a:gradFill rotWithShape="1"> <a:gsLst> <a:gs pos="0"> <a:schemeClr val="phClr"> <a:tint val="100000"/> <a:shade val="100000"/> <a:satMod val="130000"/> </a:schemeClr> </a:gs> <a:gs pos="100000"> <a:schemeClr val="phClr"> <a:tint val="50000"/> <a:shade val="100000"/> <a:satMod val="350000"/> </a:schemeClr> </a:gs> </a:gsLst> <a:lin ang="16200000" scaled="0"/> </a:gradFill> </a:fillStyleLst> <a:lnStyleLst> <a:ln w="9525" cap="flat" cmpd="sng" algn="ctr"> <a:solidFill> <a:schemeClr val="phClr"> <a:shade val="95000"/> <a:satMod val="105000"/> </a:schemeClr> </a:solidFill> <a:prstDash val="solid"/> </a:ln> <a:ln w="25400" cap="flat" cmpd="sng" algn="ctr"> <a:solidFill> <a:schemeClr val="phClr"/> </a:solidFill> <a:prstDash val="solid"/> </a:ln> <a:ln w="38100" cap="flat" cmpd="sng" algn="ctr"> <a:solidFill> <a:schemeClr val="phClr"/> </a:solidFill> <a:prstDash val="solid"/> </a:ln> </a:lnStyleLst> <a:effectStyleLst> <a:effectStyle> <a:effectLst> <a:outerShdw blurRad="40000" dist="20000" dir="5400000" rotWithShape="0"> <a:srgbClr val="000000"> <a:alpha val="38000"/> </a:srgbClr> </a:outerShdw> </a:effectLst> </a:effectStyle> <a:effectStyle> <a:effectLst> <a:outerShdw blurRad="40000" dist="23000" dir="5400000" rotWithShape="0"> <a:srgbClr val="000000"> <a:alpha val="35000"/> </a:srgbClr> </a:outerShdw> </a:effectLst> </a:effectStyle> <a:effectStyle> <a:effectLst> <a:outerShdw blurRad="40000" dist="23000" dir="5400000" rotWithShape="0"> <a:srgbClr val="000000"> <a:alpha val="35000"/> </a:srgbClr> </a:outerShdw> </a:effectLst> <a:scene3d> <a:camera prst="orthographicFront"> <a:rot lat="0" lon="0" rev="0"/> </a:camera> <a:lightRig rig="threePt" dir="t"> <a:rot lat="0" lon="0" rev="1200000"/> </a:lightRig> </a:scene3d> <a:sp3d> <a:bevelT w="63500" h="25400"/> </a:sp3d> </a:effectStyle> </a:effectStyleLst> <a:bgFillStyleLst> <a:solidFill> <a:schemeClr val="phClr"/> </a:solidFill> <a:gradFill rotWithShape="1"> <a:gsLst> <a:gs pos="0"> <a:schemeClr val="phClr"> <a:tint val="40000"/> <a:satMod val="350000"/> </a:schemeClr> </a:gs> <a:gs pos="40000"> <a:schemeClr val="phClr"> <a:tint val="45000"/> <a:shade val="99000"/> <a:satMod val="350000"/> </a:schemeClr> </a:gs> <a:gs pos="100000"> <a:schemeClr val="phClr"> <a:shade val="20000"/> <a:satMod val="255000"/> </a:schemeClr> </a:gs> </a:gsLst> <a:path path="circle"> <a:fillToRect l="50000" t="-80000" r="50000" b="180000"/> </a:path> </a:gradFill> <a:gradFill rotWithShape="1"> <a:gsLst> <a:gs pos="0"> <a:schemeClr val="phClr"> <a:tint val="80000"/> <a:satMod val="300000"/> </a:schemeClr> </a:gs> <a:gs pos="100000"> <a:schemeClr val="phClr"> <a:shade val="30000"/> <a:satMod val="200000"/> </a:schemeClr> </a:gs> </a:gsLst> <a:path path="circle"> <a:fillToRect l="50000" t="50000" r="50000" b="50000"/> </a:path> </a:gradFill> </a:bgFillStyleLst> </a:fmtScheme> </a:themeElements> <a:objectDefaults> <a:spDef> <a:spPr/> <a:bodyPr/> <a:lstStyle/> <a:style> <a:lnRef idx="1"> <a:schemeClr val="accent1"/> </a:lnRef> <a:fillRef idx="3"> <a:schemeClr val="accent1"/> </a:fillRef> <a:effectRef idx="2"> <a:schemeClr val="accent1"/> </a:effectRef> <a:fontRef idx="minor"> <a:schemeClr val="lt1"/> </a:fontRef> </a:style> </a:spDef> <a:lnDef> <a:spPr/> <a:bodyPr/> <a:lstStyle/> <a:style> <a:lnRef idx="2"> <a:schemeClr val="accent1"/> </a:lnRef> <a:fillRef idx="0"> <a:schemeClr val="accent1"/> </a:fillRef> <a:effectRef idx="1"> <a:schemeClr val="accent1"/> </a:effectRef> <a:fontRef idx="minor"> <a:schemeClr val="tx1"/> </a:fontRef> </a:style> </a:lnDef> </a:objectDefaults> <a:extraClrSchemeLst/></a:theme>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399"""Objects related to system font file lookup."""
from __future__ import annotations
import osimport sysfrom struct import calcsize, unpack_from
from pptx.util import lazyproperty
class FontFiles(object): """A class-based singleton serving as a lazy cache for system font details."""
_font_files = None
@classmethod def find(cls, family_name: str, is_bold: bool, is_italic: bool) -> str: """Return the absolute path to an installed OpenType font.
File is matched by `family_name` and the styles `is_bold` and `is_italic`. """ if cls._font_files is None: cls._font_files = cls._installed_fonts() return cls._font_files[(family_name, is_bold, is_italic)]
@classmethod def _installed_fonts(cls): """ Return a dict mapping a font descriptor to its font file path, containing all the font files resident on the current machine. The font descriptor is a (family_name, is_bold, is_italic) 3-tuple. """ fonts = {} for d in cls._font_directories(): for key, path in cls._iter_font_files_in(d): fonts[key] = path return fonts
@classmethod def _font_directories(cls): """ Return a sequence of directory paths likely to contain fonts on the current platform. """ if sys.platform.startswith("darwin"): return cls._os_x_font_directories() if sys.platform.startswith("win32"): return cls._windows_font_directories() raise OSError("unsupported operating system")
@classmethod def _iter_font_files_in(cls, directory): """ Generate the OpenType font files found in and under *directory*. Each item is a key/value pair. The key is a (family_name, is_bold, is_italic) 3-tuple, like ('Arial', True, False), and the value is the absolute path to the font file. """ for root, dirs, files in os.walk(directory): for filename in files: file_ext = os.path.splitext(filename)[1] if file_ext.lower() not in (".otf", ".ttf"): continue path = os.path.abspath(os.path.join(root, filename)) with _Font.open(path) as f: yield ((f.family_name, f.is_bold, f.is_italic), path)
@classmethod def _os_x_font_directories(cls): """ Return a sequence of directory paths on a Mac in which fonts are likely to be located. """ os_x_font_dirs = [ "/Library/Fonts", "/Network/Library/Fonts", "/System/Library/Fonts", ] home = os.environ.get("HOME") if home is not None: os_x_font_dirs.extend( [os.path.join(home, "Library", "Fonts"), os.path.join(home, ".fonts")] ) return os_x_font_dirs
@classmethod def _windows_font_directories(cls): """ Return a sequence of directory paths on Windows in which fonts are likely to be located. """ return [r"C:\Windows\Fonts"]
class _Font(object): """ A wrapper around an OTF/TTF font file stream that knows how to parse it for its name and style characteristics, e.g. bold and italic. """
def __init__(self, stream): self._stream = stream
def __enter__(self): return self
def __exit__(self, exception_type, exception_value, exception_tb): self._stream.close()
@property def is_bold(self): """ |True| if this font is marked as a bold style of its font family. """ try: return self._tables["head"].is_bold except KeyError: # some files don't have a head table return False
@property def is_italic(self): """ |True| if this font is marked as an italic style of its font family. """ try: return self._tables["head"].is_italic except KeyError: # some files don't have a head table return False
@classmethod def open(cls, font_file_path): """ Return a |_Font| instance loaded from *font_file_path*. """ return cls(_Stream.open(font_file_path))
@property def family_name(self): """ The name of the typeface family for this font, e.g. 'Arial'. The full typeface name includes optional style names, such as 'Regular' or 'Bold Italic'. This attribute is only the common base name shared by all fonts in the family. """ return self._tables["name"].family_name
@lazyproperty def _fields(self): """5-tuple containing the fields read from the font file header.
Also known as the offset table. """ # sfnt_version, tbl_count, search_range, entry_selector, range_shift return self._stream.read_fields(">4sHHHH", 0)
def _iter_table_records(self): """ Generate a (tag, offset, length) 3-tuple for each of the tables in this font file. """ count = self._table_count bufr = self._stream.read(offset=12, length=count * 16) tmpl = ">4sLLL" for i in range(count): offset = i * 16 tag, checksum, off, len_ = unpack_from(tmpl, bufr, offset) yield tag.decode("utf-8"), off, len_
@lazyproperty def _tables(self): """ A mapping of OpenType table tag, e.g. 'name', to a table object providing access to the contents of that table. """ return dict( (tag, _TableFactory(tag, self._stream, off, len_)) for tag, off, len_ in self._iter_table_records() )
@property def _table_count(self): """ The number of tables in this OpenType font file. """ return self._fields[1]
class _Stream(object): """A thin wrapper around a binary file that facilitates reading C-struct values."""
def __init__(self, file): self._file = file
@classmethod def open(cls, path): """Return |_Stream| providing binary access to contents of file at `path`.""" return cls(open(path, "rb"))
def close(self): """ Close the wrapped file. Using the stream after closing raises an exception. """ self._file.close()
def read(self, offset, length): """ Return *length* bytes from this stream starting at *offset*. """ self._file.seek(offset) return self._file.read(length)
def read_fields(self, template, offset=0): """ Return a tuple containing the C-struct fields in this stream specified by *template* and starting at *offset*. """ self._file.seek(offset) bufr = self._file.read(calcsize(template)) return unpack_from(template, bufr)
class _BaseTable(object): """ Base class for OpenType font file table objects. """
def __init__(self, tag, stream, offset, length): self._tag = tag self._stream = stream self._offset = offset self._length = length
class _HeadTable(_BaseTable): """ OpenType font table having the tag 'head' and containing certain header information for the font, including its bold and/or italic style. """
def __init__(self, tag, stream, offset, length): super(_HeadTable, self).__init__(tag, stream, offset, length)
@property def is_bold(self): """ |True| if this font is marked as having emboldened characters. """ return bool(self._macStyle & 1)
@property def is_italic(self): """ |True| if this font is marked as having italicized characters. """ return bool(self._macStyle & 2)
@lazyproperty def _fields(self): """ A 17-tuple containing the fields in this table. """ return self._stream.read_fields(">4s4sLLHHqqhhhhHHHHH", self._offset)
@property def _macStyle(self): """ The unsigned short value of the 'macStyle' field in this head table. """ return self._fields[12]
class _NameTable(_BaseTable): """ An OpenType font table having the tag 'name' and containing the name-related strings for the font. """
def __init__(self, tag, stream, offset, length): super(_NameTable, self).__init__(tag, stream, offset, length)
@property def family_name(self): """ The name of the typeface family for this font, e.g. 'Arial'. """
def find_first(dict_, keys, default=None): for key in keys: value = dict_.get(key) if value is not None: return value return default
# keys for Unicode, Mac, and Windows family name, respectively return find_first(self._names, ((0, 1), (1, 1), (3, 1)))
@staticmethod def _decode_name(raw_name, platform_id, encoding_id): """ Return the unicode name decoded from *raw_name* using the encoding implied by the combination of *platform_id* and *encoding_id*. """ if platform_id == 1: # reject non-Roman Mac font names if encoding_id != 0: return None return raw_name.decode("mac-roman") elif platform_id in (0, 3): return raw_name.decode("utf-16-be") else: return None
def _iter_names(self): """Generate a key/value pair for each name in this table.
The key is a (platform_id, name_id) 2-tuple and the value is the unicode text corresponding to that key. """ table_format, count, strings_offset = self._table_header table_bytes = self._table_bytes
for idx in range(count): platform_id, name_id, name = self._read_name(table_bytes, idx, strings_offset) if name is None: continue yield ((platform_id, name_id), name)
@staticmethod def _name_header(bufr, idx): """ The (platform_id, encoding_id, language_id, name_id, length, name_str_offset) 6-tuple encoded in each name record C-struct. """ name_hdr_offset = 6 + idx * 12 return unpack_from(">HHHHHH", bufr, name_hdr_offset)
@staticmethod def _raw_name_string(bufr, strings_offset, str_offset, length): """ Return the *length* bytes comprising the encoded string in *bufr* at *str_offset* in the strings area beginning at *strings_offset*. """ offset = strings_offset + str_offset tmpl = "%ds" % length return unpack_from(tmpl, bufr, offset)[0]
def _read_name(self, bufr, idx, strings_offset): """Return a (platform_id, name_id, name) 3-tuple for name at `idx` in `bufr`.
The triple looks like (0, 1, 'Arial'). `strings_offset` is the for the name at `idx` position in `bufr`. `strings_offset` is the index into `bufr` where actual name strings begin. The returned name is a unicode string. """ platform_id, enc_id, lang_id, name_id, length, str_offset = self._name_header(bufr, idx) name = self._read_name_text(bufr, platform_id, enc_id, strings_offset, str_offset, length) return platform_id, name_id, name
def _read_name_text( self, bufr, platform_id, encoding_id, strings_offset, name_str_offset, length ): """ Return the unicode name string at *name_str_offset* or |None| if decoding its format is not supported. """ raw_name = self._raw_name_string(bufr, strings_offset, name_str_offset, length) return self._decode_name(raw_name, platform_id, encoding_id)
@lazyproperty def _table_bytes(self): """ The binary contents of this name table. """ return self._stream.read(self._offset, self._length)
@property def _table_header(self): """ The (table_format, name_count, strings_offset) 3-tuple contained in the header of this table. """ return unpack_from(">HHH", self._table_bytes)
@lazyproperty def _names(self): """A mapping of (platform_id, name_id) keys to string names for this font.""" return dict(self._iter_names())
def _TableFactory(tag, stream, offset, length): """ Return an instance of |Table| appropriate to *tag*, loaded from *font_file* with content of *length* starting at *offset*. """ TableClass = {"head": _HeadTable, "name": _NameTable}.get(tag, _BaseTable) return TableClass(tag, stream, offset, length)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325"""Objects related to layout of rendered text, such as TextFitter."""
from __future__ import annotations
from typing import TYPE_CHECKING
from PIL import ImageFont
if TYPE_CHECKING: from pptx.util import Length
class TextFitter(tuple): """Value object that knows how to fit text into given rectangular extents."""
def __new__(cls, line_source, extents, font_file): width, height = extents return tuple.__new__(cls, (line_source, width, height, font_file))
@classmethod def best_fit_font_size( cls, text: str, extents: tuple[Length, Length], max_size: int, font_file: str ) -> int: """Return whole-number best fit point size less than or equal to `max_size`.
The return value is the largest whole-number point size less than or equal to `max_size` that allows `text` to fit completely within `extents` when rendered using font defined in `font_file`. """ line_source = _LineSource(text) text_fitter = cls(line_source, extents, font_file) return text_fitter._best_fit_font_size(max_size)
def _best_fit_font_size(self, max_size): """ Return the largest whole-number point size less than or equal to *max_size* that this fitter can fit. """ predicate = self._fits_inside_predicate sizes = _BinarySearchTree.from_ordered_sequence(range(1, int(max_size) + 1)) return sizes.find_max(predicate)
def _break_line(self, line_source, point_size): """ Return a (line, remainder) pair where *line* is the longest line in *line_source* that will fit in this fitter's width and *remainder* is a |_LineSource| object containing the text following the break point. """ lines = _BinarySearchTree.from_ordered_sequence(line_source) predicate = self._fits_in_width_predicate(point_size) return lines.find_max(predicate)
def _fits_in_width_predicate(self, point_size): """ Return a function taking a text string value and returns |True| if that text fits in this fitter when rendered at *point_size*. Used as predicate for _break_line() """
def predicate(line): """ Return |True| if *line* fits in this fitter when rendered at *point_size*. """ cx = _rendered_size(line.text, point_size, self._font_file)[0] return cx <= self._width
return predicate
@property def _fits_inside_predicate(self): """Return function taking an integer point size argument.
The function returns |True| if the text in this fitter can be wrapped to fit entirely within its extents when rendered at that point size. """
def predicate(point_size): """Return |True| when text in `line_source` can be wrapped to fit.
Fit means text can be broken into lines that fit entirely within `extents` when rendered at `point_size` using the font defined in `font_file`. """ text_lines = self._wrap_lines(self._line_source, point_size) cy = _rendered_size("Ty", point_size, self._font_file)[1] return (cy * len(text_lines)) <= self._height
return predicate
@property def _font_file(self): return self[3]
@property def _height(self): return self[2]
@property def _line_source(self): return self[0]
@property def _width(self): return self[1]
def _wrap_lines(self, line_source, point_size): """ Return a sequence of str values representing the text in *line_source* wrapped within this fitter when rendered at *point_size*. """ text, remainder = self._break_line(line_source, point_size) lines = [text] if remainder: lines.extend(self._wrap_lines(remainder, point_size)) return lines
class _BinarySearchTree(object): """ A node in a binary search tree. Uniform for root, subtree root, and leaf nodes. """
def __init__(self, value): self._value = value self._lesser = None self._greater = None
def find_max(self, predicate, max_=None): """ Return the largest item in or under this node that satisfies *predicate*. """ if predicate(self.value): max_ = self.value next_node = self._greater else: next_node = self._lesser if next_node is None: return max_ return next_node.find_max(predicate, max_)
@classmethod def from_ordered_sequence(cls, iseq): """ Return the root of a balanced binary search tree populated with the values in iterable *iseq*. """ seq = list(iseq) # optimize for usually all fits by making longest first bst = cls(seq.pop()) bst._insert_from_ordered_sequence(seq) return bst
def insert(self, value): """ Insert a new node containing *value* into this tree such that its structure as a binary search tree is preserved. """ side = "_lesser" if value < self.value else "_greater" child = getattr(self, side) if child is None: setattr(self, side, _BinarySearchTree(value)) else: child.insert(value)
def tree(self, level=0, prefix=""): """ A string representation of the tree rooted in this node, useful for debugging purposes. """ text = "%s%s\n" % (prefix, self.value.text) prefix = "%s└── " % (" " * level) if self._lesser: text += self._lesser.tree(level + 1, prefix) if self._greater: text += self._greater.tree(level + 1, prefix) return text
@property def value(self): """ The value object contained in this node. """ return self._value
@staticmethod def _bisect(seq): """ Return a (medial_value, greater_values, lesser_values) 3-tuple obtained by bisecting sequence *seq*. """ if len(seq) == 0: return [], None, [] mid_idx = int(len(seq) / 2) mid = seq[mid_idx] greater = seq[mid_idx + 1 :] lesser = seq[:mid_idx] return mid, greater, lesser
def _insert_from_ordered_sequence(self, seq): """ Insert the new values contained in *seq* into this tree such that a balanced tree is produced. """ if len(seq) == 0: return mid, greater, lesser = self._bisect(seq) self.insert(mid) self._insert_from_ordered_sequence(greater) self._insert_from_ordered_sequence(lesser)
class _LineSource(object): """ Generates all the possible even-word line breaks in a string of text, each in the form of a (line, remainder) 2-tuple where *line* contains the text before the break and *remainder* the text after as a |_LineSource| object. Its boolean value is |True| when it contains text, |False| when its text is the empty string or whitespace only. """
def __init__(self, text): self._text = text
def __bool__(self): """ Gives this object boolean behaviors (in Python 3). bool(line_source) is False if it contains the empty string or whitespace only. """ return self._text.strip() != ""
def __eq__(self, other): return self._text == other._text
def __iter__(self): """ Generate a (text, remainder) pair for each possible even-word line break in this line source, where *text* is a str value and remainder is a |_LineSource| value. """ words = self._text.split() for idx in range(1, len(words) + 1): line_text = " ".join(words[:idx]) remainder_text = " ".join(words[idx:]) remainder = _LineSource(remainder_text) yield _Line(line_text, remainder)
def __nonzero__(self): """ Gives this object boolean behaviors (in Python 2). bool(line_source) is False if it contains the empty string or whitespace only. """ return self._text.strip() != ""
def __repr__(self): return "<_LineSource('%s')>" % self._text
class _Line(tuple): """ A candidate line broken at an even word boundary from a string of text, and a |_LineSource| value containing the text that remains after the line is broken at this spot. """
def __new__(cls, text, remainder): return tuple.__new__(cls, (text, remainder))
def __gt__(self, other): return len(self.text) > len(other.text)
def __lt__(self, other): return not self.__gt__(other)
def __len__(self): return len(self.text)
def __repr__(self): return "'%s' => '%s'" % (self.text, self.remainder)
@property def remainder(self): return self[1]
@property def text(self): return self[0]
class _Fonts(object): """ A memoizing cache for ImageFont objects. """
fonts = {}
@classmethod def font(cls, font_path, point_size): if (font_path, point_size) not in cls.fonts: cls.fonts[(font_path, point_size)] = ImageFont.truetype(font_path, point_size) return cls.fonts[(font_path, point_size)]
def _rendered_size(text, point_size, font_file): """ Return a (width, height) pair representing the size of *text* in English Metric Units (EMU) when rendered at *point_size* in the font defined in *font_file*. """ emu_per_inch = 914400 px_per_inch = 72.0
font = _Fonts.font(font_file, point_size) try: px_width, px_height = font.getsize(text) except AttributeError: left, top, right, bottom = font.getbbox(text) px_width, px_height = right - left, bottom - top
emu_width = int(px_width / px_per_inch * emu_per_inch) emu_height = int(px_height / px_per_inch * emu_per_inch)
return emu_width, emu_height123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681"""Text-related objects such as TextFrame and Paragraph."""
from __future__ import annotations
from typing import TYPE_CHECKING, Iterator, cast
from pptx.dml.fill import FillFormatfrom pptx.enum.dml import MSO_FILLfrom pptx.enum.lang import MSO_LANGUAGE_IDfrom pptx.enum.text import MSO_AUTO_SIZE, MSO_UNDERLINE, MSO_VERTICAL_ANCHORfrom pptx.opc.constants import RELATIONSHIP_TYPE as RTfrom pptx.oxml.simpletypes import ST_TextWrappingTypefrom pptx.shapes import Subshapefrom pptx.text.fonts import FontFilesfrom pptx.text.layout import TextFitterfrom pptx.util import Centipoints, Emu, Length, Pt, lazyproperty
if TYPE_CHECKING: from pptx.dml.color import ColorFormat from pptx.enum.text import ( MSO_TEXT_UNDERLINE_TYPE, MSO_VERTICAL_ANCHOR, PP_PARAGRAPH_ALIGNMENT, ) from pptx.oxml.action import CT_Hyperlink from pptx.oxml.text import ( CT_RegularTextRun, CT_TextBody, CT_TextCharacterProperties, CT_TextParagraph, CT_TextParagraphProperties, ) from pptx.types import ProvidesExtents, ProvidesPart
class TextFrame(Subshape): """The part of a shape that contains its text.
Not all shapes have a text frame. Corresponds to the `p:txBody` element that can appear as a child element of `p:sp`. Not intended to be constructed directly. """
def __init__(self, txBody: CT_TextBody, parent: ProvidesPart): super(TextFrame, self).__init__(parent) self._element = self._txBody = txBody self._parent = parent
def add_paragraph(self): """ Return new |_Paragraph| instance appended to the sequence of paragraphs contained in this text frame. """ p = self._txBody.add_p() return _Paragraph(p, self)
@property def auto_size(self) -> MSO_AUTO_SIZE | None: """Resizing strategy used to fit text within this shape.
Determins the type of automatic resizing used to fit the text of this shape within its bounding box when the text would otherwise extend beyond the shape boundaries. May be |None|, `MSO_AUTO_SIZE.NONE`, `MSO_AUTO_SIZE.SHAPE_TO_FIT_TEXT`, or `MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE`. """ return self._bodyPr.autofit
@auto_size.setter def auto_size(self, value: MSO_AUTO_SIZE | None): self._bodyPr.autofit = value
def clear(self): """Remove all paragraphs except one empty one.""" for p in self._txBody.p_lst[1:]: self._txBody.remove(p) p = self.paragraphs[0] p.clear()
def fit_text( self, font_family: str = "Calibri", max_size: int = 18, bold: bool = False, italic: bool = False, font_file: str | None = None, ): """Fit text-frame text entirely within bounds of its shape.
Make the text in this text frame fit entirely within the bounds of its shape by setting word wrap on and applying the "best-fit" font size to all the text it contains.
:attr:`TextFrame.auto_size` is set to :attr:`MSO_AUTO_SIZE.NONE`. The font size will not be set larger than `max_size` points. If the path to a matching TrueType font is provided as `font_file`, that font file will be used for the font metrics. If `font_file` is |None|, best efforts are made to locate a font file with matchhing `font_family`, `bold`, and `italic` installed on the current system (usually succeeds if the font is installed). """ # ---no-op when empty as fit behavior not defined for that case--- if self.text == "": return # pragma: no cover
font_size = self._best_fit_font_size(font_family, max_size, bold, italic, font_file) self._apply_fit(font_family, font_size, bold, italic)
@property def margin_bottom(self) -> Length: """|Length| value representing the inset of text from the bottom text frame border.
:meth:`pptx.util.Inches` provides a convenient way of setting the value, e.g. `text_frame.margin_bottom = Inches(0.05)`. """ return self._bodyPr.bIns
@margin_bottom.setter def margin_bottom(self, emu: Length): self._bodyPr.bIns = emu
@property def margin_left(self) -> Length: """Inset of text from left text frame border as |Length| value.""" return self._bodyPr.lIns
@margin_left.setter def margin_left(self, emu: Length): self._bodyPr.lIns = emu
@property def margin_right(self) -> Length: """Inset of text from right text frame border as |Length| value.""" return self._bodyPr.rIns
@margin_right.setter def margin_right(self, emu: Length): self._bodyPr.rIns = emu
@property def margin_top(self) -> Length: """Inset of text from top text frame border as |Length| value.""" return self._bodyPr.tIns
@margin_top.setter def margin_top(self, emu: Length): self._bodyPr.tIns = emu
@property def paragraphs(self) -> tuple[_Paragraph, ...]: """Sequence of paragraphs in this text frame.
A text frame always contains at least one paragraph. """ return tuple([_Paragraph(p, self) for p in self._txBody.p_lst])
@property def text(self) -> str: """All text in this text-frame as a single string.
Read/write. The return value contains all text in this text-frame. A line-feed character (`"\\n"`) separates the text for each paragraph. A vertical-tab character (`"\\v"`) appears for each line break (aka. soft carriage-return) encountered.
The vertical-tab character is how PowerPoint represents a soft carriage return in clipboard text, which is why that encoding was chosen.
Assignment replaces all text in the text frame. A new paragraph is added for each line-feed character (`"\\n"`) encountered. A line-break (soft carriage-return) is inserted for each vertical-tab character (`"\\v"`) encountered.
Any control character other than newline, tab, or vertical-tab are escaped as plain-text like "_x001B_" (for ESC (ASCII 32) in this example). """ return "\n".join(paragraph.text for paragraph in self.paragraphs)
@text.setter def text(self, text: str): txBody = self._txBody txBody.clear_content() for p_text in text.split("\n"): p = txBody.add_p() p.append_text(p_text)
@property def vertical_anchor(self) -> MSO_VERTICAL_ANCHOR | None: """Represents the vertical alignment of text in this text frame.
|None| indicates the effective value should be inherited from this object's style hierarchy. """ return self._txBody.bodyPr.anchor
@vertical_anchor.setter def vertical_anchor(self, value: MSO_VERTICAL_ANCHOR | None): bodyPr = self._txBody.bodyPr bodyPr.anchor = value
@property def word_wrap(self) -> bool | None: """`True` when lines of text in this shape are wrapped to fit within the shape's width.
Read-write. Valid values are True, False, or None. True and False turn word wrap on and off, respectively. Assigning None to word wrap causes any word wrap setting to be removed from the text frame, causing it to inherit this setting from its style hierarchy. """ return { ST_TextWrappingType.SQUARE: True, ST_TextWrappingType.NONE: False, None: None, }[self._txBody.bodyPr.wrap]
@word_wrap.setter def word_wrap(self, value: bool | None): if value not in (True, False, None): raise ValueError( # pragma: no cover "assigned value must be True, False, or None, got %s" % value ) self._txBody.bodyPr.wrap = { True: ST_TextWrappingType.SQUARE, False: ST_TextWrappingType.NONE, None: None, }[value]
def _apply_fit(self, font_family: str, font_size: int, is_bold: bool, is_italic: bool): """Arrange text in this text frame to fit inside its extents.
This is accomplished by setting auto size off, wrap on, and setting the font of all its text to `font_family`, `font_size`, `is_bold`, and `is_italic`. """ self.auto_size = MSO_AUTO_SIZE.NONE self.word_wrap = True self._set_font(font_family, font_size, is_bold, is_italic)
def _best_fit_font_size( self, family: str, max_size: int, bold: bool, italic: bool, font_file: str | None ) -> int: """Return font-size in points that best fits text in this text-frame.
The best-fit font size is the largest integer point size not greater than `max_size` that allows all the text in this text frame to fit inside its extents when rendered using the font described by `family`, `bold`, and `italic`. If `font_file` is specified, it is used to calculate the fit, whether or not it matches `family`, `bold`, and `italic`. """ if font_file is None: font_file = FontFiles.find(family, bold, italic) return TextFitter.best_fit_font_size(self.text, self._extents, max_size, font_file)
@property def _bodyPr(self): return self._txBody.bodyPr
@property def _extents(self) -> tuple[Length, Length]: """(cx, cy) 2-tuple representing the effective rendering area of this text-frame.
Margins are taken into account. """ parent = cast("ProvidesExtents", self._parent) return ( Length(parent.width - self.margin_left - self.margin_right), Length(parent.height - self.margin_top - self.margin_bottom), )
def _set_font(self, family: str, size: int, bold: bool, italic: bool): """Set the font properties of all the text in this text frame."""
def iter_rPrs(txBody: CT_TextBody) -> Iterator[CT_TextCharacterProperties]: for p in txBody.p_lst: for elm in p.content_children: yield elm.get_or_add_rPr() # generate a:endParaRPr for each <a:p> element yield p.get_or_add_endParaRPr()
def set_rPr_font( rPr: CT_TextCharacterProperties, name: str, size: int, bold: bool, italic: bool ): f = Font(rPr) f.name, f.size, f.bold, f.italic = family, Pt(size), bold, italic
txBody = self._element for rPr in iter_rPrs(txBody): set_rPr_font(rPr, family, size, bold, italic)
class Font(object): """Character properties object, providing font size, font name, bold, italic, etc.
Corresponds to `a:rPr` child element of a run. Also appears as `a:defRPr` and `a:endParaRPr` in paragraph and `a:defRPr` in list style elements. """
def __init__(self, rPr: CT_TextCharacterProperties): super(Font, self).__init__() self._element = self._rPr = rPr
@property def bold(self) -> bool | None: """Get or set boolean bold value of |Font|, e.g. `paragraph.font.bold = True`.
If set to |None|, the bold setting is cleared and is inherited from an enclosing shape's setting, or a setting in a style or master. Returns None if no bold attribute is present, meaning the effective bold value is inherited from a master or the theme. """ return self._rPr.b
@bold.setter def bold(self, value: bool | None): self._rPr.b = value
@lazyproperty def color(self) -> ColorFormat: """The |ColorFormat| instance that provides access to the color settings for this font.""" if self.fill.type != MSO_FILL.SOLID: self.fill.solid() return self.fill.fore_color
@lazyproperty def fill(self) -> FillFormat: """|FillFormat| instance for this font.
Provides access to fill properties such as fill color. """ return FillFormat.from_fill_parent(self._rPr)
@property def italic(self) -> bool | None: """Get or set boolean italic value of |Font| instance.
Has the same behaviors as bold with respect to None values. """ return self._rPr.i
@italic.setter def italic(self, value: bool | None): self._rPr.i = value
@property def language_id(self) -> MSO_LANGUAGE_ID | None: """Get or set the language id of this |Font| instance.
The language id is a member of the :ref:`MsoLanguageId` enumeration. Assigning |None| removes any language setting, the same behavior as assigning `MSO_LANGUAGE_ID.NONE`. """ lang = self._rPr.lang if lang is None: return MSO_LANGUAGE_ID.NONE return self._rPr.lang
@language_id.setter def language_id(self, value: MSO_LANGUAGE_ID | None): if value == MSO_LANGUAGE_ID.NONE: value = None self._rPr.lang = value
@property def name(self) -> str | None: """Get or set the typeface name for this |Font| instance.
Causes the text it controls to appear in the named font, if a matching font is found. Returns |None| if the typeface is currently inherited from the theme. Setting it to |None| removes any override of the theme typeface. """ latin = self._rPr.latin if latin is None: return None return latin.typeface
@name.setter def name(self, value: str | None): if value is None: self._rPr._remove_latin() # pyright: ignore[reportPrivateUsage] else: latin = self._rPr.get_or_add_latin() latin.typeface = value
@property def size(self) -> Length | None: """Indicates the font height in English Metric Units (EMU).
Read/write. |None| indicates the font size should be inherited from its style hierarchy, such as a placeholder or document defaults (usually 18pt). |Length| is a subclass of |int| having properties for convenient conversion into points or other length units. Likewise, the :class:`pptx.util.Pt` class allows convenient specification of point values::
>>> font.size = Pt(24) >>> font.size 304800 >>> font.size.pt 24.0 """ sz = self._rPr.sz if sz is None: return None return Centipoints(sz)
@size.setter def size(self, emu: Length | None): if emu is None: self._rPr.sz = None else: sz = Emu(emu).centipoints self._rPr.sz = sz
@property def underline(self) -> bool | MSO_TEXT_UNDERLINE_TYPE | None: """Indicaties the underline setting for this font.
Value is |True|, |False|, |None|, or a member of the :ref:`MsoTextUnderlineType` enumeration. |None| is the default and indicates the underline setting should be inherited from the style hierarchy, such as from a placeholder. |True| indicates single underline. |False| indicates no underline. Other settings such as double and wavy underlining are indicated with members of the :ref:`MsoTextUnderlineType` enumeration. """ u = self._rPr.u if u is MSO_UNDERLINE.NONE: return False if u is MSO_UNDERLINE.SINGLE_LINE: return True return u
@underline.setter def underline(self, value: bool | MSO_TEXT_UNDERLINE_TYPE | None): if value is True: value = MSO_UNDERLINE.SINGLE_LINE elif value is False: value = MSO_UNDERLINE.NONE self._element.u = value
class _Hyperlink(Subshape): """Text run hyperlink object.
Corresponds to `a:hlinkClick` child element of the run's properties element (`a:rPr`). """
def __init__(self, rPr: CT_TextCharacterProperties, parent: ProvidesPart): super(_Hyperlink, self).__init__(parent) self._rPr = rPr
@property def address(self) -> str | None: """The URL of the hyperlink.
Read/write. URL can be on http, https, mailto, or file scheme; others may work. """ if self._hlinkClick is None: return None return self.part.target_ref(self._hlinkClick.rId)
@address.setter def address(self, url: str | None): # implements all three of add, change, and remove hyperlink if self._hlinkClick is not None: self._remove_hlinkClick() if url: self._add_hlinkClick(url)
def _add_hlinkClick(self, url: str): rId = self.part.relate_to(url, RT.HYPERLINK, is_external=True) self._rPr.add_hlinkClick(rId)
@property def _hlinkClick(self) -> CT_Hyperlink | None: return self._rPr.hlinkClick
def _remove_hlinkClick(self): assert self._hlinkClick is not None self.part.drop_rel(self._hlinkClick.rId) self._rPr._remove_hlinkClick() # pyright: ignore[reportPrivateUsage]
class _Paragraph(Subshape): """Paragraph object. Not intended to be constructed directly."""
def __init__(self, p: CT_TextParagraph, parent: ProvidesPart): super(_Paragraph, self).__init__(parent) self._element = self._p = p
def add_line_break(self): """Add line break at end of this paragraph.""" self._p.add_br()
def add_run(self) -> _Run: """Return a new run appended to the runs in this paragraph.""" r = self._p.add_r() return _Run(r, self)
@property def alignment(self) -> PP_PARAGRAPH_ALIGNMENT | None: """Horizontal alignment of this paragraph.
The value |None| indicates the paragraph should 'inherit' its effective value from its style hierarchy. Assigning |None| removes any explicit setting, causing its inherited value to be used. """ return self._pPr.algn
@alignment.setter def alignment(self, value: PP_PARAGRAPH_ALIGNMENT | None): self._pPr.algn = value
def clear(self): """Remove all content from this paragraph.
Paragraph properties are preserved. Content includes runs, line breaks, and fields. """ for elm in self._element.content_children: self._element.remove(elm) return self
@property def font(self) -> Font: """|Font| object containing default character properties for the runs in this paragraph.
These character properties override default properties inherited from parent objects such as the text frame the paragraph is contained in and they may be overridden by character properties set at the run level. """ return Font(self._defRPr)
@property def level(self) -> int: """Indentation level of this paragraph.
Read-write. Integer in range 0..8 inclusive. 0 represents a top-level paragraph and is the default value. Indentation level is most commonly encountered in a bulleted list, as is found on a word bullet slide. """ return self._pPr.lvl
@level.setter def level(self, level: int): self._pPr.lvl = level
@property def line_spacing(self) -> int | float | Length | None: """The space between baselines in successive lines of this paragraph.
A value of |None| indicates no explicit value is assigned and its effective value is inherited from the paragraph's style hierarchy. A numeric value, e.g. `2` or `1.5`, indicates spacing is applied in multiples of line heights. A |Length| value such as `Pt(12)` indicates spacing is a fixed height. The |Pt| value class is a convenient way to apply line spacing in units of points. """ pPr = self._p.pPr if pPr is None: return None return pPr.line_spacing
@line_spacing.setter def line_spacing(self, value: int | float | Length | None): pPr = self._p.get_or_add_pPr() pPr.line_spacing = value
@property def runs(self) -> tuple[_Run, ...]: """Sequence of runs in this paragraph.""" return tuple(_Run(r, self) for r in self._element.r_lst)
@property def space_after(self) -> Length | None: """The spacing to appear between this paragraph and the subsequent paragraph.
A value of |None| indicates no explicit value is assigned and its effective value is inherited from the paragraph's style hierarchy. |Length| objects provide convenience properties, such as `.pt` and `.inches`, that allow easy conversion to various length units. """ pPr = self._p.pPr if pPr is None: return None return pPr.space_after
@space_after.setter def space_after(self, value: Length | None): pPr = self._p.get_or_add_pPr() pPr.space_after = value
@property def space_before(self) -> Length | None: """The spacing to appear between this paragraph and the prior paragraph.
A value of |None| indicates no explicit value is assigned and its effective value is inherited from the paragraph's style hierarchy. |Length| objects provide convenience properties, such as `.pt` and `.cm`, that allow easy conversion to various length units. """ pPr = self._p.pPr if pPr is None: return None return pPr.space_before
@space_before.setter def space_before(self, value: Length | None): pPr = self._p.get_or_add_pPr() pPr.space_before = value
@property def text(self) -> str: """Text of paragraph as a single string.
Read/write. This value is formed by concatenating the text in each run and field making up the paragraph, adding a vertical-tab character (`"\\v"`) for each line-break element (`<a:br>`, soft carriage-return) encountered.
While the encoding of line-breaks as a vertical tab might be surprising at first, doing so is consistent with PowerPoint's clipboard copy behavior and allows a line-break to be distinguished from a paragraph boundary within the str return value.
Assignment causes all content in the paragraph to be replaced. Each vertical-tab character (`"\\v"`) in the assigned str is translated to a line-break, as is each line-feed character (`"\\n"`). Contrast behavior of line-feed character in `TextFrame.text` setter. If line-feed characters are intended to produce new paragraphs, use `TextFrame.text` instead. Any other control characters in the assigned string are escaped as a hex representation like "_x001B_" (for ESC (ASCII 27) in this example). """ return "".join(elm.text for elm in self._element.content_children)
@text.setter def text(self, text: str): self.clear() self._element.append_text(text)
@property def _defRPr(self) -> CT_TextCharacterProperties: """The element that defines the default run properties for runs in this paragraph.
Causes the element to be added if not present. """ return self._pPr.get_or_add_defRPr()
@property def _pPr(self) -> CT_TextParagraphProperties: """Contains the properties for this paragraph.
Causes the element to be added if not present. """ return self._p.get_or_add_pPr()
class _Run(Subshape): """Text run object. Corresponds to `a:r` child element in a paragraph."""
def __init__(self, r: CT_RegularTextRun, parent: ProvidesPart): super(_Run, self).__init__(parent) self._r = r
@property def font(self): """|Font| instance containing run-level character properties for the text in this run.
Character properties can be and perhaps most often are inherited from parent objects such as the paragraph and slide layout the run is contained in. Only those specifically overridden at the run level are contained in the font object. """ rPr = self._r.get_or_add_rPr() return Font(rPr)
@lazyproperty def hyperlink(self) -> _Hyperlink: """Proxy for any `a:hlinkClick` element under the run properties element.
Created on demand, the hyperlink object is available whether an `a:hlinkClick` element is present or not, and creates or deletes that element as appropriate in response to actions on its methods and attributes. """ rPr = self._r.get_or_add_rPr() return _Hyperlink(rPr, self)
@property def text(self): """Read/write. A unicode string containing the text in this run.
Assignment replaces all text in the run. The assigned value can be a 7-bit ASCII string, a UTF-8 encoded 8-bit string, or unicode. String values are converted to unicode assuming UTF-8 encoding.
Any other control characters in the assigned string other than tab or newline are escaped as a hex representation. For example, ESC (ASCII 27) is escaped as "_x001B_". Contrast the behavior of `TextFrame.text` and `_Paragraph.text` with respect to line-feed and vertical-tab characters. """ return self._r.text
@text.setter def text(self, text: str): self._r.text = text123456789101112131415161718192021222324252627282930313233343536"""Abstract types used by `python-pptx`."""
from __future__ import annotations
from typing import TYPE_CHECKING
from typing_extensions import Protocol
if TYPE_CHECKING: from pptx.opc.package import XmlPart from pptx.util import Length
class ProvidesExtents(Protocol): """An object that has width and height."""
@property def height(self) -> Length: """Distance between top and bottom extents of shape in EMUs.""" ...
@property def width(self) -> Length: """Distance between left and right extents of shape in EMUs.""" ...
class ProvidesPart(Protocol): """An object that provides access to its XmlPart.
This type is for objects that need access to their part, possibly because they need access to the package or related parts. """
@property def part(self) -> XmlPart: ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214"""Utility functions and classes."""
from __future__ import annotations
import functoolsfrom typing import Any, Callable, Generic, TypeVar, cast
class Length(int): """Base class for length classes Inches, Emu, Cm, Mm, and Pt.
Provides properties for converting length values to convenient units. """
_EMUS_PER_INCH = 914400 _EMUS_PER_CENTIPOINT = 127 _EMUS_PER_CM = 360000 _EMUS_PER_MM = 36000 _EMUS_PER_PT = 12700
def __new__(cls, emu: int): return int.__new__(cls, emu)
@property def inches(self) -> float: """Floating point length in inches.""" return self / float(self._EMUS_PER_INCH)
@property def centipoints(self) -> int: """Integer length in hundredths of a point (1/7200 inch).
Used internally because PowerPoint stores font size in centipoints. """ return self // self._EMUS_PER_CENTIPOINT
@property def cm(self) -> float: """Floating point length in centimeters.""" return self / float(self._EMUS_PER_CM)
@property def emu(self) -> int: """Integer length in English Metric Units.""" return self
@property def mm(self) -> float: """Floating point length in millimeters.""" return self / float(self._EMUS_PER_MM)
@property def pt(self) -> float: """Floating point length in points.""" return self / float(self._EMUS_PER_PT)
class Inches(Length): """Convenience constructor for length in inches."""
def __new__(cls, inches: float): emu = int(inches * Length._EMUS_PER_INCH) return Length.__new__(cls, emu)
class Centipoints(Length): """Convenience constructor for length in hundredths of a point."""
def __new__(cls, centipoints: int): emu = int(centipoints * Length._EMUS_PER_CENTIPOINT) return Length.__new__(cls, emu)
class Cm(Length): """Convenience constructor for length in centimeters."""
def __new__(cls, cm: float): emu = int(cm * Length._EMUS_PER_CM) return Length.__new__(cls, emu)
class Emu(Length): """Convenience constructor for length in english metric units."""
def __new__(cls, emu: int): return Length.__new__(cls, int(emu))
class Mm(Length): """Convenience constructor for length in millimeters."""
def __new__(cls, mm: float): emu = int(mm * Length._EMUS_PER_MM) return Length.__new__(cls, emu)
class Pt(Length): """Convenience value class for specifying a length in points."""
def __new__(cls, points: float): emu = int(points * Length._EMUS_PER_PT) return Length.__new__(cls, emu)
_T = TypeVar("_T")
class lazyproperty(Generic[_T]): """Decorator like @property, but evaluated only on first access.
Like @property, this can only be used to decorate methods having only a `self` parameter, and is accessed like an attribute on an instance, i.e. trailing parentheses are not used. Unlike @property, the decorated method is only evaluated on first access; the resulting value is cached and that same value returned on second and later access without re-evaluation of the method.
Like @property, this class produces a *data descriptor* object, which is stored in the __dict__ of the *class* under the name of the decorated method ('fget' nominally). The cached value is stored in the __dict__ of the *instance* under that same name.
Because it is a data descriptor (as opposed to a *non-data descriptor*), its `__get__()` method is executed on each access of the decorated attribute; the __dict__ item of the same name is "shadowed" by the descriptor.
While this may represent a performance improvement over a property, its greater benefit may be its other characteristics. One common use is to construct collaborator objects, removing that "real work" from the constructor, while still only executing once. It also de-couples client code from any sequencing considerations; if it's accessed from more than one location, it's assured it will be ready whenever needed.
Loosely based on: https://stackoverflow.com/a/6849299/1902513.
A lazyproperty is read-only. There is no counterpart to the optional "setter" (or deleter) behavior of an @property. This is critically important to maintaining its immutability and idempotence guarantees. Attempting to assign to a lazyproperty raises AttributeError unconditionally.
The parameter names in the methods below correspond to this usage example::
class Obj(object)
@lazyproperty def fget(self): return 'some result'
obj = Obj()
Not suitable for wrapping a function (as opposed to a method) because it is not callable. """
def __init__(self, fget: Callable[..., _T]) -> None: """*fget* is the decorated method (a "getter" function).
A lazyproperty is read-only, so there is only an *fget* function (a regular @property can also have an fset and fdel function). This name was chosen for consistency with Python's `property` class which uses this name for the corresponding parameter. """ # --- maintain a reference to the wrapped getter method self._fget = fget # --- and store the name of that decorated method self._name = fget.__name__ # --- adopt fget's __name__, __doc__, and other attributes functools.update_wrapper(self, fget) # pyright: ignore
def __get__(self, obj: Any, type: Any = None) -> _T: """Called on each access of 'fget' attribute on class or instance.
*self* is this instance of a lazyproperty descriptor "wrapping" the property method it decorates (`fget`, nominally).
*obj* is the "host" object instance when the attribute is accessed from an object instance, e.g. `obj = Obj(); obj.fget`. *obj* is None when accessed on the class, e.g. `Obj.fget`.
*type* is the class hosting the decorated getter method (`fget`) on both class and instance attribute access. """ # --- when accessed on class, e.g. Obj.fget, just return this descriptor # --- instance (patched above to look like fget). if obj is None: return self # type: ignore
# --- when accessed on instance, start by checking instance __dict__ for # --- item with key matching the wrapped function's name value = obj.__dict__.get(self._name) if value is None: # --- on first access, the __dict__ item will be absent. Evaluate fget() # --- and store that value in the (otherwise unused) host-object # --- __dict__ value of same name ('fget' nominally) value = self._fget(obj) obj.__dict__[self._name] = value return cast(_T, value)
def __set__(self, obj: Any, value: Any) -> None: """Raises unconditionally, to preserve read-only behavior.
This decorator is intended to implement immutable (and idempotent) object attributes. For that reason, assignment to this property must be explicitly prevented.
If this __set__ method was not present, this descriptor would become a *non-data descriptor*. That would be nice because the cached value would be accessed directly once set (__dict__ attrs have precedence over non-data descriptors on instance attribute lookup). The problem is, there would be nothing to stop assignment to the cached value, which would overwrite the result of `fget()` and break both the immutability and idempotence guarantees of this decorator.
The performance with this __set__() method in place was roughly 0.4 usec per access when measured on a 2.8GHz development machine; so quite snappy and probably not a rich target for optimization efforts. """ raise AttributeError("can't set attribute")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599Metadata-Version: 2.4Name: python-pptxVersion: 0.6.23Summary: Generate and manipulate Open XML PowerPoint (.pptx) filesHome-page: https://github.com/scanny/python-pptxAuthor: Steve CannyAuthor-email: python-pptx@googlegroups.comLicense: MITKeywords: powerpoint ppt pptx office open xmlClassifier: Development Status :: 4 - BetaClassifier: Environment :: ConsoleClassifier: Intended Audience :: DevelopersClassifier: License :: OSI Approved :: MIT LicenseClassifier: Operating System :: OS IndependentClassifier: Programming Language :: PythonClassifier: Programming Language :: Python :: 2Classifier: Programming Language :: Python :: 2.7Classifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3.6Classifier: Topic :: Office/Business :: Office SuitesClassifier: Topic :: Software Development :: LibrariesDescription-Content-Type: text/x-rstLicense-File: LICENSERequires-Dist: lxml>=3.1.0Requires-Dist: Pillow>=3.3.2Requires-Dist: XlsxWriter>=0.5.7Dynamic: authorDynamic: author-emailDynamic: classifierDynamic: descriptionDynamic: description-content-typeDynamic: home-pageDynamic: keywordsDynamic: licenseDynamic: license-fileDynamic: requires-distDynamic: summary
*python-pptx* is a Python library for creating, reading, and updating PowerPoint (.pptx)files.
A typical use would be generating a PowerPoint presentation from dynamic content such asa database query, analytics output, or a JSON payload, perhaps in response to an HTTPrequest and downloading the generated PPTX file in response. It runs on any Pythoncapable platform, including macOS and Linux, and does not require the PowerPointapplication to be installed or licensed.
It can also be used to analyze PowerPoint files from a corpus, perhaps to extract searchindexing text and images.
In can also be used to simply automate the production of a slide or two that would betedious to get right by hand, which is how this all got started.
More information is available in the `python-pptx documentation`_.
Browse `examples with screenshots`_ to get a quick idea what you can do withpython-pptx.
.. _`python-pptx documentation`: https://python-pptx.readthedocs.org/en/latest/
.. _`examples with screenshots`: https://python-pptx.readthedocs.org/en/latest/user/quickstart.html
.. :changelog:
Release History---------------
0.6.24-dev0+++++++++++++++++++
- fix: #943 remove mention of a Px Length subtype
0.6.23 (2023-11-02)+++++++++++++++++++
- fix: #912 Pillow<=9.5 constraint entails security vulnerability
0.6.22 (2023-08-28)+++++++++++++++++++
- Add #909 Add imgW, imgH params to `shapes.add_ole_object()`- fix: #754 _Relationships.items() raises- fix: #758 quote in autoshape name must be escaped- fix: #746 update Python 3.x support in docs- fix: #748 setup's `license` should be short string- fix: #762 AttributeError: module 'collections' has no attribute 'abc' (Windows Python 3.10+)
0.6.21 (2021-09-20)+++++++++++++++++++
- Fix #741 _DirPkgReader must implement .__contains__()
0.6.20 (2021-09-14)+++++++++++++++++++
- Fix #206 accommodate NULL target-references in relationships.- Fix #223 escape image filename that appears as literal in XML.- Fix #517 option to display chart categories/values in reverse order.- Major refactoring of ancient package loading code.
0.6.19 (2021-05-17)+++++++++++++++++++
- Add shapes.add_ole_object(), allowing arbitrary Excel or other binary file to be embedded as a shape on a slide. The OLE object is represented as an icon.
0.6.18 (2019-05-02)+++++++++++++++++++
- .text property getters encode line-break as a vertical-tab (VT, '\v', ASCII 11/x0B). This is consistent with PowerPoint's copy/paste behavior and allows like-breaks (soft carriage-return) to be distinguished from paragraph boundary. Previously, a line-break was encoded as a newline ('\n') and was not distinguishable from a paragraph boundary.
.text properties include Shape.text, _Cell.text, TextFrame.text, _Paragraph.text and _Run.text.
- .text property setters accept vertical-tab character and place a line-break element in that location. All other control characters other than horizontal-tab ('\t') and newline ('\n') in range \x00-\x1F are accepted and escaped with plain-text like "_x001B" for ESC (ASCII 27).
Previously a control character other than tab or newline in an assigned string would trigger an exception related to invalid XML character.
0.6.17 (2018-12-16)+++++++++++++++++++
- Add SlideLayouts.remove() - Delete unused slide-layout- Add SlideLayout.used_by_slides - Get slides based on this slide-layout- Add SlideLayouts.index() - Get index of slide-layout in master- Add SlideLayouts.get_by_name() - Get slide-layout by its str name
0.6.16 (2018-11-09)+++++++++++++++++++
- Feature #395 DataLabels.show_* properties, e.g. .show_percentage- Feature #453 Chart data tolerates None for labels
0.6.15 (2018-09-24)+++++++++++++++++++
- Fix #436 ValueAxis._cross_xAx fails on c:dateAxis
0.6.14 (2018-09-24)+++++++++++++++++++
- Add _Cell.merge()- Add _Cell.split()- Add _Cell.__eq__()- Add _Cell.is_merge_origin- Add _Cell.is_spanned- Add _Cell.span_height- Add _Cell.span_width- Add _Cell.text getter- Add Table.iter_cells()- Move pptx.shapes.table module to pptx.table- Add user documentation 'Working with tables'
0.6.13 (2018-09-10)+++++++++++++++++++
- Add Chart.font- Fix #293 Can't hide title of single-series Chart- Fix shape.width value is not type Emu- Fix add a:defRPr with c:rich (fixes some font inheritance breakage)
0.6.12 (2018-08-11)+++++++++++++++++++
- Add Picture.auto_shape_type- Remove Python 2.6 testing from build- Update dependencies to avoid vulnerable Pillow version- Fix #260, #301, #382, #401- Add _Paragraph.add_line_break()- Add Connector.line
0.6.11 (2018-07-25)+++++++++++++++++++
- Add gradient fill.- Add experimental "turbo-add" option for producing large shape-count slides.
0.6.10 (2018-06-11)+++++++++++++++++++
- Add `shape.shadow` property to autoshape, connector, picture, and group shape, returning a `ShadowFormat` object.- Add `ShadowFormat` object with read/write (boolean) `.inherit` property.- Fix #328 add support for 26+ series in a chart
0.6.9 (2018-05-08)++++++++++++++++++
- Add `Picture.crop_x` setters, allowing picture cropping values to be set, in addition to interrogated.- Add `Slide.background` and `SlideMaster.background`, allowing the background fill to be set for an individual slide or for all slides based on a slide master.- Add option `shapes` parameter to `Shapes.add_group_shape`, allowing a group shape to be formed from a number of existing shapes.- Improve efficiency of `Shapes._next_shape_id` property to improve performance on high shape-count slides.
0.6.8 (2018-04-18)++++++++++++++++++
- Add `GroupShape`, providing properties specific to a group shape, including its `shapes` property.- Add `GroupShapes`, providing access to shapes contained in a group shape.- Add `SlideShapes.add_group_shape()`, allowing a group shape to be added to a slide.- Add `GroupShapes.add_group_shape()`, allowing a group shape to be added to a group shape, enabling recursive, multi-level groups.- Add support for adding jump-to-named-slide behavior to shape and run hyperlinks.
0.6.7 (2017-10-30)++++++++++++++++++
- Add `SlideShapes.build_freeform()`, allowing freeform shapes (such as maps) to be specified and added to a slide.- Add support for patterned fills.- Add `LineFormat.dash_style` to allow interrogation and setting of dashed line styles.
0.6.6 (2017-06-17)++++++++++++++++++
- Add `SlideShapes.add_movie()`, allowing video media to be added to a slide.
- fix #190 Accommodate non-conforming part names having '00' index segment.- fix #273 Accommodate non-conforming part names having no index segment.- fix #277 ASCII/Unicode error on non-ASCII multi-level category names- fix #279 BaseShape.id warning appearing on placeholder access.
0.6.5 (2017-03-21)++++++++++++++++++
- #267 compensate for non-conforming PowerPoint behavior on c:overlay element
- compensate for non-conforming (to spec) PowerPoint behavior related to c:dLbl/c:tx that results in "can't save" error when explicit data labels are added to bubbles on a bubble chart.
0.6.4 (2017-03-17)++++++++++++++++++
- add Chart.chart_title and ChartTitle object- #263 Use Number type to test for numeric category
0.6.3 (2017-02-28)++++++++++++++++++
- add DataLabel.font- add Axis.axis_title
0.6.2 (2017-01-03)++++++++++++++++++
- add support for NotesSlide (slide notes, aka. notes page)- add support for arbitrary series ordering in XML- add Plot.categories providing access to hierarchical categories in an existing chart.- add support for date axes on category charts, including writing a dateAx element for the category axis when ChartData categories are date or datetime.
**BACKWARD INCOMPATIBILITIES:**
Some changes were made to the boilerplate XML used to create new charts. Thiswas done to more closely adhere to the settings PowerPoint uses when creatinga chart using the UI. This may result in some appearance changes in chartsafter upgrading. In particular:
* Chart.has_legend now defaults to True for Line charts.* Plot.vary_by_categories now defaults to False for Line charts.
0.6.1 (2016-10-09)++++++++++++++++++
- add Connector shape type
0.6.0 (2016-08-18)++++++++++++++++++
- add XY chart types- add Bubble chart types- add Radar chart types- add Area chart types- add Doughnut chart types- add Series.points and Point- add Point.data_label- add DataLabel.text_frame- add DataLabel.position- add Axis.major_gridlines- add ChartFormat with .fill and .line- add Axis.format (fill and line formatting)- add ValueAxis.crosses and .crosses_at- add Point.format (fill and line formatting)- add Slide.slide_id- add Slides.get() (by slide id)- add Font.language_id- support blank (None) data points in created charts- add Series.marker- add Point.marker- add Marker.format, .style, and .size
0.5.8 (2015-11-27)++++++++++++++++++
- add Shape.click_action (hyperlink on shape)- fix: #128 Chart cat and ser names not escaped- fix: #153 shapes.title raises on no title shape- fix: #170 remove seek(0) from Image.from_file()
0.5.7 (2015-01-17)++++++++++++++++++
- add PicturePlaceholder with .insert_picture() method- add TablePlaceholder with .insert_table() method- add ChartPlaceholder with .insert_chart() method- add Picture.image property, returning Image object- add Picture.crop_left, .crop_top, .crop_right, and .crop_bottom- add Shape.placeholder_format and PlaceholderFormat object
**BACKWARD INCOMPATIBILITIES:**
Shape.shape_type is now unconditionally `MSO_SHAPE_TYPE.PLACEHOLDER` for allplaceholder shapes. Previously, some placeholder shapes reported`MSO_SHAPE_TYPE.AUTO_SHAPE`, `MSO_SHAPE_TYPE.CHART`,`MSO_SHAPE_TYPE.PICTURE`, or `MSO_SHAPE_TYPE.TABLE` for that property.
0.5.6 (2014-12-06)++++++++++++++++++
- fix #138 - UnicodeDecodeError in setup.py on Windows 7 Python 3.4
0.5.5 (2014-11-17)++++++++++++++++++
- feature #51 - add Python 3 support
0.5.4 (2014-11-15)++++++++++++++++++
- feature #43 - image native size in shapes.add_picture() is now calculated based on DPI attribute in image file, if present, defaulting to 72 dpi.- feature #113 - Add Paragraph.space_before, Paragraph.space_after, and Paragraph.line_spacing
0.5.3 (2014-11-09)++++++++++++++++++
- add experimental feature TextFrame.fit_text()
0.5.2 (2014-10-26)++++++++++++++++++
- fix #127 - Shape.text_frame fails on shape having no txBody
0.5.1 (2014-09-22)++++++++++++++++++
- feature #120 - add Shape.rotation- feature #97 - add Font.underline- issue #117 - add BMP image support- issue #95 - add BaseShape.name setter- issue #107 - all .text properties should return unicode, not str- feature #106 - add .text getters to Shape, TextFrame, and Paragraph
- Rename Shape.textframe to Shape.text_frame. **Shape.textframe property (by that name) is deprecated.**
0.5.0 (2014-09-13)++++++++++++++++++
- Add support for creating and manipulating bar, column, line, and pie charts- Major refactoring of XML layer (oxml)- Rationalized graphical object shape access **Note backward incompatibilities below**
**BACKWARD INCOMPATIBILITIES:**
A table is no longer treated as a shape. Rather it is a graphical objectcontained in a GraphicFrame shape, as are Chart and SmartArt objects.
Example::
table = shapes.add_table(...)
# becomes
graphic_frame = shapes.add_table(...) table = graphic_frame.table
# or
table = shapes.add_table(...).table
As the enclosing shape, the id, name, shape type, position, and size areattributes of the enclosing GraphicFrame object.
The contents of a GraphicFrame shape can be identified using three availableproperties on a shape: has_table, has_chart, and has_smart_art. The enclosedgraphical object is obtained using the properties GraphicFrame.table andGraphicFrame.chart. SmartArt is not yet supported. Accessing one of theseproperties on a GraphicFrame not containing the corresponding object raisesan exception.
0.4.2 (2014-04-29)++++++++++++++++++
- fix: issue #88 -- raises on supported image file having uppercase extension- fix: issue #89 -- raises on add_slide() where non-contiguous existing ids
0.4.1 (2014-04-29)++++++++++++++++++
- Rename Presentation.slidemasters to Presentation.slide_masters. Presentation.slidemasters property is deprecated.- Rename Presentation.slidelayouts to Presentation.slide_layouts. Presentation.slidelayouts property is deprecated.- Rename SlideMaster.slidelayouts to SlideMaster.slide_layouts. SlideMaster.slidelayouts property is deprecated.- Rename SlideLayout.slidemaster to SlideLayout.slide_master. SlideLayout.slidemaster property is deprecated.- Rename Slide.slidelayout to Slide.slide_layout. Slide.slidelayout property is deprecated.- Add SlideMaster.shapes to access shapes on slide master.- Add SlideMaster.placeholders to access placeholder shapes on slide master.- Add _MasterPlaceholder class.- Add _LayoutPlaceholder class with position and size inheritable from master placeholder.- Add _SlidePlaceholder class with position and size inheritable from layout placeholder.- Add Table.left, top, width, and height read/write properties.- Add rudimentary GroupShape with left, top, width, and height properties.- Add rudimentary Connector with left, top, width, and height properties.- Add TextFrame.auto_size property.- Add Presentation.slide_width and .slide_height read/write properties.- Add LineFormat class providing access to read and change line color and width.- Add AutoShape.line- Add Picture.line
- Rationalize enumerations. **Note backward incompatibilities below**
**BACKWARD INCOMPATIBILITIES:**
The following enumerations were moved/renamed during the rationalization ofenumerations:
- ``pptx.enum.MSO_COLOR_TYPE`` --> ``pptx.enum.dml.MSO_COLOR_TYPE``- ``pptx.enum.MSO_FILL`` --> ``pptx.enum.dml.MSO_FILL``- ``pptx.enum.MSO_THEME_COLOR`` --> ``pptx.enum.dml.MSO_THEME_COLOR``- ``pptx.constants.MSO.ANCHOR_*`` --> ``pptx.enum.text.MSO_ANCHOR.*``- ``pptx.constants.MSO_SHAPE`` --> ``pptx.enum.shapes.MSO_SHAPE``- ``pptx.constants.PP.ALIGN_*`` --> ``pptx.enum.text.PP_ALIGN.*``- ``pptx.constants.MSO.{SHAPE_TYPES}`` --> ``pptx.enum.shapes.MSO_SHAPE_TYPE.*``
Documentation for all enumerations is available in the Enumerations sectionof the User Guide.
0.3.2 (2014-02-07)++++++++++++++++++
- Hotfix: issue #80 generated presentations fail to load in Keynote and other Apple applications
0.3.1 (2014-01-10)++++++++++++++++++
- Hotfix: failed to load certain presentations containing images with uppercase extension
0.3.0 (2013-12-12)++++++++++++++++++
- Add read/write font color property supporting RGB, theme color, and inherit color types- Add font typeface and italic support- Add text frame margins and word-wrap- Add support for external relationships, e.g. linked spreadsheet- Add hyperlink support for text run in shape and table cell- Add fill color and brightness for shape and table cell, fill can also be set to transparent (no fill)- Add read/write position and size properties to shape and picture- Replace PIL dependency with Pillow- Restructure modules to better suit size of library
0.2.6 (2013-06-22)++++++++++++++++++
- Add read/write access to core document properties- Hotfix to accomodate connector shapes in _AutoShapeType- Hotfix to allow customXml parts to load when present
0.2.5 (2013-06-11)++++++++++++++++++
- Add paragraph alignment property (left, right, centered, etc.)- Add vertical alignment within table cell (top, middle, bottom)- Add table cell margin properties- Add table boolean properties: first column (row header), first row (column headings), last row (for e.g. totals row), last column (for e.g. row totals), horizontal banding, and vertical banding.- Add support for auto shape adjustment values, e.g. change radius of corner rounding on rounded rectangle, position of callout arrow, etc.
0.2.4 (2013-05-16)++++++++++++++++++
- Add support for auto shapes (e.g. polygons, flowchart symbols, etc.)
0.2.3 (2013-05-05)++++++++++++++++++
- Add support for table shapes- Add indentation support to textbox shapes, enabling multi-level bullets on bullet slides.
0.2.2 (2013-03-25)++++++++++++++++++
- Add support for opening and saving a presentation from/to a file-like object.- Refactor XML handling to use lxml objectify
0.2.1 (2013-02-25)++++++++++++++++++
- Add support for Python 2.6- Add images from a stream (e.g. StringIO) in addition to a path, allowing images retrieved from a database or network resource to be inserted without saving first.- Expand text methods to accept unicode and UTF-8 encoded 8-bit strings.- Fix potential install bug triggered by importing ``__version__`` from package ``__init__.py`` file.
0.2.0 (2013-02-10)++++++++++++++++++
First non-alpha release with basic capabilities:
- open presentation/template or use built-in default template- add slide- set placeholder text (e.g. bullet slides)- add picture- add text box123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502HISTORY.rstLICENSEMANIFEST.inREADME.rstpyproject.tomlsetup.cfgsetup.pytox.inifeatures/act-action.featurefeatures/act-hyperlink.featurefeatures/cht-axis-props.featurefeatures/cht-axistitle-props.featurefeatures/cht-category-access.featurefeatures/cht-category-props.featurefeatures/cht-chart.featurefeatures/cht-charttitle-props.featurefeatures/cht-data-props.featurefeatures/cht-datalabels.featurefeatures/cht-gridlines-props.featurefeatures/cht-legend-access.featurefeatures/cht-legend-props.featurefeatures/cht-marker-props.featurefeatures/cht-plot-props.featurefeatures/cht-point-access.featurefeatures/cht-point-props.featurefeatures/cht-replace-data.featurefeatures/cht-series.featurefeatures/cht-ticklabels-props.featurefeatures/dml-color.featurefeatures/dml-effect.featurefeatures/dml-fill.featurefeatures/dml-line.featurefeatures/environment.pyfeatures/ph-inherit-props.featurefeatures/ph-insert-shape.featurefeatures/ph-phfmt-props.featurefeatures/ph-placeholder-props.featurefeatures/prs-coreprops.featurefeatures/prs-default-template.featurefeatures/prs-open-save.featurefeatures/prs-presentation-props.featurefeatures/shp-autoshape.featurefeatures/shp-connector.featurefeatures/shp-freeform.featurefeatures/shp-graphicframe.featurefeatures/shp-groupshape.featurefeatures/shp-movie-props.featurefeatures/shp-picture.featurefeatures/shp-placeholder.featurefeatures/shp-shapes.featurefeatures/shp-shared.featurefeatures/sld-background.featurefeatures/sld-slide.featurefeatures/sld-slides.featurefeatures/tbl-cell.featurefeatures/tbl-column.featurefeatures/tbl-table.featurefeatures/txt-fit-text.featurefeatures/txt-font-color.featurefeatures/txt-font-props.featurefeatures/txt-paragraph.featurefeatures/txt-text.featurefeatures/txt-textframe.featurefeatures/steps/action.pyfeatures/steps/axis.pyfeatures/steps/background.pyfeatures/steps/category.pyfeatures/steps/chart.pyfeatures/steps/chartdata.pyfeatures/steps/color.pyfeatures/steps/coreprops.pyfeatures/steps/datalabel.pyfeatures/steps/effect.pyfeatures/steps/fill.pyfeatures/steps/font.pyfeatures/steps/font_color.pyfeatures/steps/helpers.pyfeatures/steps/legend.pyfeatures/steps/line.pyfeatures/steps/picture.pyfeatures/steps/placeholder.pyfeatures/steps/plot.pyfeatures/steps/presentation.pyfeatures/steps/series.pyfeatures/steps/shape.pyfeatures/steps/shapes.pyfeatures/steps/slide.pyfeatures/steps/slides.pyfeatures/steps/table.pyfeatures/steps/text.pyfeatures/steps/text_frame.pyfeatures/steps/test_files/72-dpi.tifffeatures/steps/test_files/CVS_LOGO.WMFfeatures/steps/test_files/act-props.pptmfeatures/steps/test_files/calibriz.ttffeatures/steps/test_files/cht-axis-props.pptxfeatures/steps/test_files/cht-category-access.pptxfeatures/steps/test_files/cht-chart-props.pptxfeatures/steps/test_files/cht-chart-type.pptxfeatures/steps/test_files/cht-charts.pptxfeatures/steps/test_files/cht-datalabels.pptxfeatures/steps/test_files/cht-gridlines-props.pptxfeatures/steps/test_files/cht-legend-props.pptxfeatures/steps/test_files/cht-legend.pptxfeatures/steps/test_files/cht-marker-props.pptxfeatures/steps/test_files/cht-plot-props.pptxfeatures/steps/test_files/cht-point-access.pptxfeatures/steps/test_files/cht-point-props.pptxfeatures/steps/test_files/cht-replace-data.pptxfeatures/steps/test_files/cht-series.pptxfeatures/steps/test_files/cht-ticklabels-props.pptxfeatures/steps/test_files/dml-effect.pptxfeatures/steps/test_files/dml-fill.pptxfeatures/steps/test_files/dml-line.pptxfeatures/steps/test_files/ext-rels.pptxfeatures/steps/test_files/font-color.pptxfeatures/steps/test_files/just-two-mice.mp4features/steps/test_files/just-two-mice.pngfeatures/steps/test_files/lyt-shapes.pptxfeatures/steps/test_files/minimal.pptxfeatures/steps/test_files/monty-truth.pngfeatures/steps/test_files/mst-placeholders.pptxfeatures/steps/test_files/mst-shapes.pptxfeatures/steps/test_files/mst-slide-layouts.pptxfeatures/steps/test_files/ph-inherit-props.pptxfeatures/steps/test_files/ph-populated-placeholders.pptxfeatures/steps/test_files/ph-unpopulated-placeholders.pptxfeatures/steps/test_files/pic.emffeatures/steps/test_files/prs-add-slide.pptxfeatures/steps/test_files/prs-notes.pptxfeatures/steps/test_files/prs-properties.pptxfeatures/steps/test_files/prs-slide-masters.pptxfeatures/steps/test_files/python-icon.jpegfeatures/steps/test_files/python-powered.pngfeatures/steps/test_files/python.bmpfeatures/steps/test_files/shp-access-chart.pptxfeatures/steps/test_files/shp-access-ole-object.pptxfeatures/steps/test_files/shp-autoshape-adjustments.pptxfeatures/steps/test_files/shp-autoshape-props.pptxfeatures/steps/test_files/shp-common-props.pptxfeatures/steps/test_files/shp-connector-props.pptxfeatures/steps/test_files/shp-embedded-docx.docxfeatures/steps/test_files/shp-embedded-pptx.pptxfeatures/steps/test_files/shp-embedded-xlsx.xlsxfeatures/steps/test_files/shp-freeform.pptxfeatures/steps/test_files/shp-groupshape.pptxfeatures/steps/test_files/shp-movie-props.pptxfeatures/steps/test_files/shp-picture.pptxfeatures/steps/test_files/shp-pos-and-size.pptxfeatures/steps/test_files/shp-shapes.pptxfeatures/steps/test_files/sld-background.pptxfeatures/steps/test_files/sld-blank.pptxfeatures/steps/test_files/sld-notes.pptxfeatures/steps/test_files/sld-slide.pptxfeatures/steps/test_files/sld-slides.pptxfeatures/steps/test_files/sonic.giffeatures/steps/test_files/tbl-cell.pptxfeatures/steps/test_files/test.pptxfeatures/steps/test_files/txt-fit-text.pptxfeatures/steps/test_files/txt-font-props.pptxfeatures/steps/test_files/txt-font-typeface.pptxfeatures/steps/test_files/txt-paragraph-spacing.pptxfeatures/steps/test_files/txt-text-frame.pptxfeatures/steps/test_files/txt-text.pptxfeatures/steps/test_files/extracted-pptx/[Content_Types].xmlfeatures/steps/test_files/extracted-pptx/_rels/.relsfeatures/steps/test_files/extracted-pptx/docProps/app.xmlfeatures/steps/test_files/extracted-pptx/docProps/core.xmlfeatures/steps/test_files/extracted-pptx/docProps/thumbnail.jpegfeatures/steps/test_files/extracted-pptx/ppt/presProps.xmlfeatures/steps/test_files/extracted-pptx/ppt/presentation.xmlfeatures/steps/test_files/extracted-pptx/ppt/tableStyles.xmlfeatures/steps/test_files/extracted-pptx/ppt/viewProps.xmlfeatures/steps/test_files/extracted-pptx/ppt/_rels/presentation.xml.relsfeatures/steps/test_files/extracted-pptx/ppt/printerSettings/printerSettings1.binfeatures/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout1.xmlfeatures/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout10.xmlfeatures/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout11.xmlfeatures/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout2.xmlfeatures/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout3.xmlfeatures/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout4.xmlfeatures/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout5.xmlfeatures/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout6.xmlfeatures/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout7.xmlfeatures/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout8.xmlfeatures/steps/test_files/extracted-pptx/ppt/slideLayouts/slideLayout9.xmlfeatures/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout1.xml.relsfeatures/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout10.xml.relsfeatures/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout11.xml.relsfeatures/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout2.xml.relsfeatures/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout3.xml.relsfeatures/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout4.xml.relsfeatures/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout5.xml.relsfeatures/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout6.xml.relsfeatures/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout7.xml.relsfeatures/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout8.xml.relsfeatures/steps/test_files/extracted-pptx/ppt/slideLayouts/_rels/slideLayout9.xml.relsfeatures/steps/test_files/extracted-pptx/ppt/slideMasters/slideMaster1.xmlfeatures/steps/test_files/extracted-pptx/ppt/slideMasters/_rels/slideMaster1.xml.relsfeatures/steps/test_files/extracted-pptx/ppt/slides/slide1.xmlfeatures/steps/test_files/extracted-pptx/ppt/slides/_rels/slide1.xml.relsfeatures/steps/test_files/extracted-pptx/ppt/theme/theme1.xmlsrc/pptx/__init__.pysrc/pptx/action.pysrc/pptx/api.pysrc/pptx/exc.pysrc/pptx/media.pysrc/pptx/package.pysrc/pptx/presentation.pysrc/pptx/shared.pysrc/pptx/slide.pysrc/pptx/spec.pysrc/pptx/table.pysrc/pptx/types.pysrc/pptx/util.pysrc/pptx/chart/__init__.pysrc/pptx/chart/axis.pysrc/pptx/chart/category.pysrc/pptx/chart/chart.pysrc/pptx/chart/data.pysrc/pptx/chart/datalabel.pysrc/pptx/chart/legend.pysrc/pptx/chart/marker.pysrc/pptx/chart/plot.pysrc/pptx/chart/point.pysrc/pptx/chart/series.pysrc/pptx/chart/xlsx.pysrc/pptx/chart/xmlwriter.pysrc/pptx/dml/__init__.pysrc/pptx/dml/chtfmt.pysrc/pptx/dml/color.pysrc/pptx/dml/effect.pysrc/pptx/dml/fill.pysrc/pptx/dml/line.pysrc/pptx/enum/__init__.pysrc/pptx/enum/action.pysrc/pptx/enum/base.pysrc/pptx/enum/chart.pysrc/pptx/enum/dml.pysrc/pptx/enum/lang.pysrc/pptx/enum/shapes.pysrc/pptx/enum/text.pysrc/pptx/opc/__init__.pysrc/pptx/opc/constants.pysrc/pptx/opc/oxml.pysrc/pptx/opc/package.pysrc/pptx/opc/packuri.pysrc/pptx/opc/serialized.pysrc/pptx/opc/shared.pysrc/pptx/opc/spec.pysrc/pptx/oxml/__init__.pysrc/pptx/oxml/action.pysrc/pptx/oxml/coreprops.pysrc/pptx/oxml/ns.pysrc/pptx/oxml/presentation.pysrc/pptx/oxml/simpletypes.pysrc/pptx/oxml/slide.pysrc/pptx/oxml/table.pysrc/pptx/oxml/text.pysrc/pptx/oxml/theme.pysrc/pptx/oxml/xmlchemy.pysrc/pptx/oxml/chart/__init__.pysrc/pptx/oxml/chart/axis.pysrc/pptx/oxml/chart/chart.pysrc/pptx/oxml/chart/datalabel.pysrc/pptx/oxml/chart/legend.pysrc/pptx/oxml/chart/marker.pysrc/pptx/oxml/chart/plot.pysrc/pptx/oxml/chart/series.pysrc/pptx/oxml/chart/shared.pysrc/pptx/oxml/dml/__init__.pysrc/pptx/oxml/dml/color.pysrc/pptx/oxml/dml/fill.pysrc/pptx/oxml/dml/line.pysrc/pptx/oxml/shapes/__init__.pysrc/pptx/oxml/shapes/autoshape.pysrc/pptx/oxml/shapes/connector.pysrc/pptx/oxml/shapes/graphfrm.pysrc/pptx/oxml/shapes/groupshape.pysrc/pptx/oxml/shapes/picture.pysrc/pptx/oxml/shapes/shared.pysrc/pptx/parts/__init__.pysrc/pptx/parts/chart.pysrc/pptx/parts/coreprops.pysrc/pptx/parts/embeddedpackage.pysrc/pptx/parts/image.pysrc/pptx/parts/media.pysrc/pptx/parts/presentation.pysrc/pptx/parts/slide.pysrc/pptx/shapes/__init__.pysrc/pptx/shapes/autoshape.pysrc/pptx/shapes/base.pysrc/pptx/shapes/connector.pysrc/pptx/shapes/freeform.pysrc/pptx/shapes/graphfrm.pysrc/pptx/shapes/group.pysrc/pptx/shapes/picture.pysrc/pptx/shapes/placeholder.pysrc/pptx/shapes/shapetree.pysrc/pptx/templates/default.pptxsrc/pptx/templates/docx-icon.emfsrc/pptx/templates/generic-icon.emfsrc/pptx/templates/notes.xmlsrc/pptx/templates/notesMaster.xmlsrc/pptx/templates/pptx-icon.emfsrc/pptx/templates/theme.xmlsrc/pptx/templates/xlsx-icon.emfsrc/pptx/text/__init__.pysrc/pptx/text/fonts.pysrc/pptx/text/layout.pysrc/pptx/text/text.pysrc/python_pptx.egg-info/PKG-INFOsrc/python_pptx.egg-info/SOURCES.txtsrc/python_pptx.egg-info/dependency_links.txtsrc/python_pptx.egg-info/not-zip-safesrc/python_pptx.egg-info/requires.txtsrc/python_pptx.egg-info/top_level.txttests/__init__.pytests/test_action.pytests/test_api.pytests/test_media.pytests/test_package.pytests/test_presentation.pytests/test_shared.pytests/test_slide.pytests/test_table.pytests/test_util.pytests/unitdata.pytests/chart/__init__.pytests/chart/test_axis.pytests/chart/test_category.pytests/chart/test_chart.pytests/chart/test_data.pytests/chart/test_datalabel.pytests/chart/test_legend.pytests/chart/test_marker.pytests/chart/test_plot.pytests/chart/test_point.pytests/chart/test_series.pytests/chart/test_xlsx.pytests/chart/test_xmlwriter.pytests/dml/__init__.pytests/dml/test_chtfmt.pytests/dml/test_color.pytests/dml/test_effect.pytests/dml/test_fill.pytests/dml/test_line.pytests/enum/__init__.pytests/enum/test_base.pytests/enum/test_shapes.pytests/opc/__init__.pytests/opc/test_oxml.pytests/opc/test_package.pytests/opc/test_packuri.pytests/opc/test_serialized.pytests/oxml/__init__.pytests/oxml/test___init__.pytests/oxml/test_dml.pytests/oxml/test_ns.pytests/oxml/test_presentation.pytests/oxml/test_simpletypes.pytests/oxml/test_slide.pytests/oxml/test_table.pytests/oxml/test_theme.pytests/oxml/test_xmlchemy.pytests/oxml/shapes/__init__.pytests/oxml/shapes/test_autoshape.pytests/oxml/shapes/test_graphfrm.pytests/oxml/shapes/test_groupshape.pytests/oxml/shapes/test_picture.pytests/oxml/unitdata/__init__.pytests/oxml/unitdata/dml.pytests/oxml/unitdata/shape.pytests/oxml/unitdata/text.pytests/parts/__init__.pytests/parts/test_chart.pytests/parts/test_coreprops.pytests/parts/test_embeddedpackage.pytests/parts/test_image.pytests/parts/test_media.pytests/parts/test_presentation.pytests/parts/test_slide.pytests/shapes/__init__.pytests/shapes/test_autoshape.pytests/shapes/test_base.pytests/shapes/test_connector.pytests/shapes/test_freeform.pytests/shapes/test_graphfrm.pytests/shapes/test_group.pytests/shapes/test_picture.pytests/shapes/test_placeholder.pytests/shapes/test_shapetree.pytests/test_files/calibriz.ttftests/test_files/cdw-logo.epstests/test_files/dummy.mp4tests/test_files/minimal.pptxtests/test_files/minimal_slide.xmltests/test_files/missing_rels_item.pptxtests/test_files/monty-truth.pngtests/test_files/no-core-props.pptxtests/test_files/no-slides.pptxtests/test_files/presentation.xmltests/test_files/python-icon.jpegtests/test_files/python-powered.pngtests/test_files/python.bmptests/test_files/slideLayout1.xmltests/test_files/test.pptxtests/test_files/test_slides.pptxtests/test_files/expanded_pptx/[Content_Types].xmltests/test_files/expanded_pptx/_rels/.relstests/test_files/expanded_pptx/docProps/app.xmltests/test_files/expanded_pptx/docProps/core.xmltests/test_files/expanded_pptx/docProps/thumbnail.jpegtests/test_files/expanded_pptx/ppt/presProps.xmltests/test_files/expanded_pptx/ppt/presentation.xmltests/test_files/expanded_pptx/ppt/tableStyles.xmltests/test_files/expanded_pptx/ppt/viewProps.xmltests/test_files/expanded_pptx/ppt/_rels/presentation.xml.relstests/test_files/expanded_pptx/ppt/printerSettings/printerSettings1.bintests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout1.xmltests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout10.xmltests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout11.xmltests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout2.xmltests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout3.xmltests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout4.xmltests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout5.xmltests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout6.xmltests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout7.xmltests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout8.xmltests/test_files/expanded_pptx/ppt/slideLayouts/slideLayout9.xmltests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout1.xml.relstests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout10.xml.relstests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout11.xml.relstests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout2.xml.relstests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout3.xml.relstests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout4.xml.relstests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout5.xml.relstests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout6.xml.relstests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout7.xml.relstests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout8.xml.relstests/test_files/expanded_pptx/ppt/slideLayouts/_rels/slideLayout9.xml.relstests/test_files/expanded_pptx/ppt/slideMasters/slideMaster1.xmltests/test_files/expanded_pptx/ppt/slideMasters/_rels/slideMaster1.xml.relstests/test_files/expanded_pptx/ppt/slides/slide1.xmltests/test_files/expanded_pptx/ppt/slides/_rels/slide1.xml.relstests/test_files/expanded_pptx/ppt/theme/theme1.xmltests/test_files/snippets/2x2-area-date.txttests/test_files/snippets/2x2-area-float.txttests/test_files/snippets/2x2-area-stacked-100.txttests/test_files/snippets/2x2-area-stacked.txttests/test_files/snippets/2x2-area.txttests/test_files/snippets/2x2-bar-clustered-date.txttests/test_files/snippets/2x2-bar-clustered-float.txttests/test_files/snippets/2x2-bar-clustered.txttests/test_files/snippets/2x2-bar-stacked-100.txttests/test_files/snippets/2x2-bar-stacked.txttests/test_files/snippets/2x2-column-clustered.txttests/test_files/snippets/2x2-column-stacked-100.txttests/test_files/snippets/2x2-column-stacked.txttests/test_files/snippets/2x2-line-date.txttests/test_files/snippets/2x2-line-float.txttests/test_files/snippets/2x2-line-markers-stacked-100.txttests/test_files/snippets/2x2-line-markers-stacked.txttests/test_files/snippets/2x2-line-markers.txttests/test_files/snippets/2x2-line-stacked-100.txttests/test_files/snippets/2x2-line-stacked.txttests/test_files/snippets/2x2-line.txttests/test_files/snippets/2x3-bubble-3d.txttests/test_files/snippets/2x3-bubble.txttests/test_files/snippets/2x3-xy-lines-no-markers.txttests/test_files/snippets/2x3-xy-lines.txttests/test_files/snippets/2x3-xy-smooth-no-markers.txttests/test_files/snippets/2x3-xy-smooth.txttests/test_files/snippets/2x3-xy.txttests/test_files/snippets/2x5-radar.txttests/test_files/snippets/3x1-pie-exploded.txttests/test_files/snippets/3x1-pie.txttests/test_files/snippets/3x2-doughnut-exploded.txttests/test_files/snippets/3x2-doughnut.txttests/test_files/snippets/4x2-multi-cat-bar.txttests/test_files/snippets/adjust-ser-count.txttests/test_files/snippets/cat-labels.txttests/test_files/snippets/content-types-xml.txttests/test_files/snippets/default-notes.txttests/test_files/snippets/default-notesMaster.txttests/test_files/snippets/default-theme.txttests/test_files/snippets/freeform.txttests/test_files/snippets/package-rels-xml.txttests/test_files/snippets/placeholders.txttests/test_files/snippets/presentation-rels-xml.txttests/test_files/snippets/relationships.txttests/test_files/snippets/rels-load-from-xml.txttests/test_files/snippets/rewrite-ser.txttests/test_files/snippets/timing.txttests/text/__init__.pytests/text/test_fonts.pytests/text/test_layout.pytests/text/test_text.pytests/unitutil/__init__.pytests/unitutil/cxml.pytests/unitutil/file.pytests/unitutil/mock.py1
1
123lxml>=3.1.0Pillow>=3.3.2XlsxWriter>=0.5.71pptx.gitattributes+3
tasks/tasksmith-74f059424102/environment/source/src/pptx/oxml/slide.pyAdded+347
tasks/tasksmith-74f059424102/environment/source/src/pptx/oxml/table.pyAdded+588
tasks/tasksmith-74f059424102/environment/source/src/pptx/oxml/text.pyAdded+618
tasks/tasksmith-74f059424102/environment/source/src/pptx/oxml/theme.pyAdded+29
tasks/tasksmith-74f059424102/environment/source/src/pptx/oxml/xmlchemy.pyAdded+717
tasks/tasksmith-74f059424102/environment/source/src/pptx/package.pyAdded+222
tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/__init__.pyAdded
tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/chart.pyAdded+95
tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/coreprops.pyAdded+167
tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/embeddedpackage.pyAdded+93
tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/image.pyAdded+275
tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/media.pyAdded+37
tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/presentation.pyAdded+126
tasks/tasksmith-74f059424102/environment/source/src/pptx/parts/slide.pyAdded+297
tasks/tasksmith-74f059424102/environment/source/src/pptx/presentation.pyAdded+113
tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/__init__.pyAdded+26
tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/autoshape.pyAdded+355
tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/base.pyAdded+244
tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/connector.pyAdded+297
tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/freeform.pyAdded+338
tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/graphfrm.pyAdded+166
tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/group.pyAdded+69
tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/picture.pyAdded+203
tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/placeholder.pyAdded+407
tasks/tasksmith-74f059424102/environment/source/src/pptx/shapes/shapetree.pyAdded+1190
tasks/tasksmith-74f059424102/environment/source/src/pptx/shared.pyAdded+82
tasks/tasksmith-74f059424102/environment/source/src/pptx/slide.pyAdded+498
tasks/tasksmith-74f059424102/environment/source/src/pptx/spec.pyAdded+632
tasks/tasksmith-74f059424102/environment/source/src/pptx/table.pyAdded+496
tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/default.pptxAdded
tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/docx-icon.emfAdded
Large File Pointer Details
- SHA256: cbfa051aa5f1ec1993f0ce056f67112ce4af3a8c3ac6fccfc219399ed6dc625d
- Pointer size: 131 Bytes
- Size of remote file: 127 kB
tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/generic-icon.emfAdded
tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/notes.xmlAdded+23
tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/notesMaster.xmlAdded+352
tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/pptx-icon.emfAdded
tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/theme.xmlAdded+321
tasks/tasksmith-74f059424102/environment/source/src/pptx/templates/xlsx-icon.emfAdded
Large File Pointer Details
- SHA256: 14e52936cebdf16e5a6629ce707415c26122fe54af322872a2d25fec618a69ee
- Pointer size: 131 Bytes
- Size of remote file: 130 kB
tasks/tasksmith-74f059424102/environment/source/src/pptx/text/__init__.pyAdded
tasks/tasksmith-74f059424102/environment/source/src/pptx/text/fonts.pyAdded+399
tasks/tasksmith-74f059424102/environment/source/src/pptx/text/layout.pyAdded+325
tasks/tasksmith-74f059424102/environment/source/src/pptx/text/text.pyAdded+681
tasks/tasksmith-74f059424102/environment/source/src/pptx/types.pyAdded+36
tasks/tasksmith-74f059424102/environment/source/src/pptx/util.pyAdded+214
tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/PKG-INFOAdded+599
tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/SOURCES.txtAdded+502
tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/dependency_links.txtAdded+1
tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/not-zip-safeAdded+1
tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/requires.txtAdded+3
tasks/tasksmith-74f059424102/environment/source/src/python_pptx.egg-info/top_level.txtAdded+1