Harbor format: 14 coding_additions tasks (part 7)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+27
- tasks/tasksmith-74f059424102/tests/source/docs/dev/resources/about_relationships.rstAdded+206
- tasks/tasksmith-74f059424102/tests/source/docs/dev/resources/applescript.rstAdded+46
- tasks/tasksmith-74f059424102/tests/source/docs/dev/resources/index.rstAdded+17
- tasks/tasksmith-74f059424102/tests/source/docs/dev/resources/odds_and_ends.rstAdded+106
- tasks/tasksmith-74f059424102/tests/source/docs/dev/resources/python_packaging.rstAdded+142
- tasks/tasksmith-74f059424102/tests/source/docs/dev/resources/technical_topics.rstAdded+22
- tasks/tasksmith-74f059424102/tests/source/docs/dev/resources/web_resources.rstAdded+89
- tasks/tasksmith-74f059424102/tests/source/docs/dev/runtests.rstAdded+56
- tasks/tasksmith-74f059424102/tests/source/docs/dev/xmlchemy.rstAdded+184
- tasks/tasksmith-74f059424102/tests/source/docs/index.rstAdded+118
- tasks/tasksmith-74f059424102/tests/source/docs/user/autoshapes.rstAdded+247
- tasks/tasksmith-74f059424102/tests/source/docs/user/charts.rstAdded+276
- tasks/tasksmith-74f059424102/tests/source/docs/user/concepts.rstAdded+92
- tasks/tasksmith-74f059424102/tests/source/docs/user/install.rstAdded+25
- tasks/tasksmith-74f059424102/tests/source/docs/user/intro.rstAdded+25
- tasks/tasksmith-74f059424102/tests/source/docs/user/notes.rstAdded+130
- tasks/tasksmith-74f059424102/tests/source/docs/user/placeholders-understanding.rstAdded+128
- tasks/tasksmith-74f059424102/tests/source/docs/user/placeholders-using.rstAdded+243
- tasks/tasksmith-74f059424102/tests/source/docs/user/presentations.rstAdded+99
- tasks/tasksmith-74f059424102/tests/source/docs/user/quickstart.rstAdded+267
- tasks/tasksmith-74f059424102/tests/source/docs/user/slides.rstAdded+104
- tasks/tasksmith-74f059424102/tests/source/docs/user/table.rstAdded+311
- tasks/tasksmith-74f059424102/tests/source/docs/user/text.rstAdded+179
- tasks/tasksmith-74f059424102/tests/source/docs/user/understanding-shapes.rstAdded+89
- tasks/tasksmith-74f059424102/tests/source/docs/user/use-cases.rstAdded+22
- tasks/tasksmith-74f059424102/tests/source/features/act-action.featureAdded+88
- tasks/tasksmith-74f059424102/tests/source/features/act-hyperlink.featureAdded+53
- tasks/tasksmith-74f059424102/tests/source/features/cht-axis-props.featureAdded+187
- tasks/tasksmith-74f059424102/tests/source/features/cht-axistitle-props.featureAdded+44
- tasks/tasksmith-74f059424102/tests/source/features/cht-category-access.featureAdded+72
- tasks/tasksmith-74f059424102/tests/source/features/cht-category-props.featureAdded+24
- tasks/tasksmith-74f059424102/tests/source/features/cht-chart.featureAdded+108
- tasks/tasksmith-74f059424102/tests/source/features/cht-charttitle-props.featureAdded+44
- tasks/tasksmith-74f059424102/tests/source/features/cht-data-props.featureAdded+107
- tasks/tasksmith-74f059424102/tests/source/features/cht-datalabels.featureAdded+208
- tasks/tasksmith-74f059424102/tests/source/features/cht-gridlines-props.featureAdded+11
- tasks/tasksmith-74f059424102/tests/source/features/cht-legend-access.featureAdded+31
- tasks/tasksmith-74f059424102/tests/source/features/cht-legend-props.featureAdded+82
- tasks/tasksmith-74f059424102/tests/source/features/cht-marker-props.featureAdded+59
- tasks/tasksmith-74f059424102/tests/source/features/cht-plot-props.featureAdded+121
- tasks/tasksmith-74f059424102/tests/source/features/cht-point-access.featureAdded+37
- tasks/tasksmith-74f059424102/tests/source/features/cht-point-props.featureAdded+21
- tasks/tasksmith-74f059424102/tests/source/features/cht-replace-data.featureAdded+40
- tasks/tasksmith-74f059424102/tests/source/features/cht-series.featureAdded+144
- tasks/tasksmith-74f059424102/tests/source/features/cht-ticklabels-props.featureAdded+26
- tasks/tasksmith-74f059424102/tests/source/features/dml-color.featureAdded+22
- tasks/tasksmith-74f059424102/tests/source/features/dml-effect.featureAdded+29
- tasks/tasksmith-74f059424102/tests/source/features/dml-fill.featureAdded+106
- tasks/tasksmith-74f059424102/tests/source/features/dml-line.featureAdded+62
90 unmodified lines91929390 unmodified linestasks/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 -text90 unmodified lines91929394959697989910010110210310410510610710810911011111211311411511611711811912090 unmodified linestasks/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 -texttasks/tasksmith-74f059424102/tests/source/features/steps/test_files/act-props.pptm filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/tests/source/features/steps/test_files/calibriz.ttf filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/tests/source/features/steps/test_files/cht-axis-props.pptx filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/tests/source/features/steps/test_files/cht-category-access.pptx filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/tests/source/features/steps/test_files/cht-chart-props.pptx filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/tests/source/features/steps/test_files/cht-chart-type.pptx filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/tests/source/features/steps/test_files/cht-datalabels.pptx filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/tests/source/features/steps/test_files/cht-legend-props.pptx filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/tests/source/features/steps/test_files/cht-legend.pptx filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/tests/source/features/steps/test_files/cht-plot-props.pptx filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/tests/source/features/steps/test_files/cht-point-access.pptx filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/tests/source/features/steps/test_files/cht-point-props.pptx filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/tests/source/features/steps/test_files/cht-replace-data.pptx filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/tests/source/features/steps/test_files/cht-series.pptx filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/tests/source/features/steps/test_files/cht-ticklabels-props.pptx filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/tests/source/features/steps/test_files/dml-fill.pptx filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/tests/source/features/steps/test_files/ph-populated-placeholders.pptx filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/tests/source/features/steps/test_files/shp-access-ole-object.pptx filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/tests/source/features/steps/test_files/shp-movie-props.pptx filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/tests/source/features/steps/test_files/shp-shapes.pptx filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/tests/source/spec/ISO-IEC-29500-1/ISO-IEC-29500-1.pdf filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/tests/source/spec/ISO-IEC-29500-2/ISO-IEC-29500-2.pdf filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/tests/source/spec/ISO-IEC-29500-3/ISO-IEC-29500-3.pdf filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/tests/source/spec/ISO-IEC-29500-4/ISO-IEC-29500-4.pdf filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/tests/source/src/pptx/templates/docx-icon.emf filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/tests/source/src/pptx/templates/xlsx-icon.emf filter=lfs diff=lfs merge=lfs -texttasks/tasksmith-74f059424102/tests/source/tests/test_files/calibriz.ttf filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206========================About Part Relationships========================
Understanding Part Relationships================================
An Open XML package part can have one or more relationships to other parts inthe package. For example, a slide layout has a relationship to the slidemaster it inherits properties from. And if the slide layout includes an image,such as a company logo, it will also have a relationship to the image partcorresponding to that logo's image file.
Conceptually, a part relationship might be stated::
Part x is related to part y of type z.
While these relationships are reciprocal in a way of thinking (e.g. part y isalso related to part x), in Open XML they are generally defined in onedirection only. For example, a slide may have a relationship to an image itcontains, but an image never has a stated relationships to a slide. Oneexception to this is slide masters and slide layouts. A slide layout has arelationship to the slide master it inherits from at the same time the slidemaster has a relationship to each of the slide layouts that inherit from it.
In the example above, part x can be referred to as the *source part* or*from-part*, part y as the *target part* or *to-part*, and type z as the*relationship type*. The relationship type essentially ends up being the parttype of the target part (e.g. image, slide master, etc.).
Inbound and outbound relationships----------------------------------
Each relationship is *outbound* for its source part and *inbound* for itstarget part. The *outbound* relationships of a part are those found in its*part relationship item*, commonly referred to as its "rels file". Onlyoutbound relationships are recorded in the package. Inbound relationships arepurely abstract, although they can be inferred from outbound relationships ifan application had a need for them.
Not all parts can have outbound relationships. For example, image andpresentation properties parts never have outbound relationships. All parts,however, participate in at least one inbound relationship. Any part with noinbound relationships could be removed from the package without consequence,and probably should be. For example, if upon saving it was noticed that aparticular image had no inbound relationships, that image would be better notwritten to the package. *(Makes me wonder whether loading a package by walkingits relationship graph might be a good idea in some instances.)*
Direct and indirect relationship references-------------------------------------------
Each relationship is recorded as a relationship element in the rels filebelonging to a specific part. (The package relationship item ``/_rels/.rels``is the only exception, it belongs to the package, not to any part). Eachrelationship entry specifies a part-local relationship id (rId) for therelationship, the relationship type (essentially the part type of the target,e.g. slide, image), and a path the target part file. The source part is notexplicitly stated in the relationship entry, it is implicitly the partthe .rels file belongs to.
These can be thought of as *external relationship references* in that the relsfile is a separate package item, external to the part itself. However, incertain cases, a relationship may be referenced within the XML of thefrom-part. These can be thought of as *internal relationship references*.
As an example of where an internal relationship reference is required,consider a slide containing images of three different products. Each picturehas a corresponding <p:pic> element in the slide's shape tree, each of whichmust specify the particular image file it displays, distinguishing it from theother two image files related to the slide.
The picture elements specify which of the related images to display using thepart-local relationship id (rId) matching the required image, 'rId2' in theexample below::
<p:blipFill> <a:blip r:embed="rId2"> ... </a:blip> </p:blipFill>
Which is an indirect reference to ``image1.png`` specified as the target of'rId2' in the slide's rels file::
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <Relationships xmlns="http://.../relationships"> <Relationship Id="rId1" Type="http://.../slideLayout" Target=".../slideLayout2.xml"/> <Relationship Id="rId2" Type="http://.../image" Target=".../image1.png"/> </Relationships>
This indirection makes sense as a way to limit the coupling of presentationparts to the mechanics of package composition. For example, when the XML forthe slide part in the example above is being composed, the slide can determinethe reference to the image it's displaying without reference outside its ownnatural scope. In contrast, determining the eventual location and filename ofthat image in any particular package that was saved would require the slidecode to have visibility into the packaging process, which would preventpackaging being delegated to a separate, black-box module.
Implicit and explicit relationships-----------------------------------
There is also a distinction between implicit and explicit relationships whichis described in the spec (ECMA-376-1) in section 9.2. I haven't encounteredthose yet in the context of PresentationML (the spec uses an example offootnotes from WordprocessingML), so I do not discuss them here.
Relationship Mechanics======================
Relationship life-cycle-----------------------
A representation of a relationship must operate effectively in two distinctsituations, in-package and in-memory. They must also support lifecycletransitions from in-package to in-memory and from in-memory back toin-package.
Abstract model--------------
Each relationship has the following abstract attributes
.. attribute:: source
The "from-part" of the relationship.
.. attribute:: id
Source-local unique identifier for this relationship. Each source part's relationship ids should be a sequence of consecutive integers starting from 1.
.. attribute:: target_type
The content type of the relationship's to-part.
.. attribute:: target
A direct reference to the relationship's to-part.
Maintaining relationships by dynamic parts (e.g. Slides)========================================================
How will dynamic parts (like Slide) interact with its relationship list?
? Should it just add items to the relationship list when it creates new things?
? Does it need some sort of lookup capability in order to delete? Or just have a deleterelationship method on _Relationships or something like that.
Need to come up with a plausible set of use cases to think about a design.Right now the only use case is loading a template into a presentation andsaving a presentation.
* Add an image to a slide.
* Change a slide's slide layout
* comment, notesSlide, tag, image, and slideLayout are the only outbound relationship types for a slide, although I expect there are some other DrawingML bits I haven't accounted for yet.
On reflection I'm thinking there's not too much urgency on noodling this outtoo far, the present construction should work fine for now and be able to beextended without disrupting other code too much.
SCRAP=====
Rationale for Relationship to be an association class-----------------------------------------------------
When loaded into memory, each relationship target must be a reference to anactive part object (or at least a part key that can be resolved to areference, but why do this lookup multiple times?). This is both because thoserelationships can change and also because the package path, while it can becalculated at runtime, is not guaranteed to be stable (e.g. a new slide can beinserted between two existing ones) and is not finally resolved until thepresentation is saved.
General description of package relationships items--------------------------------------------------
* Relationships items specify the relationships between parts of the package, although they are not themselves a part.
* All relationship items are XML documents having a filename with the extension '.rels' located in a directory named '_rels' located in the same directory as the part.
* The package relationship item has the URI '/_rels/.rels'.
* Part relationship items have the same filename as the part whose relationships they describe, with the '.rels' extension appended as a suffix. For example, the relationship item for a part named ``/ppt/slides/slide1.xml`` would have the URI ``/ppt/slides/_rels/slide1.xml.rels``.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546=====================AppleScript Resources=====================
In the fullness of time, it might make sense to incorporate some AppleScriptsteps into the acceptance tests, to make sure that PowerPoint isn't barfingafter changes. I've collected some resources here that I discovered duringsome preliminary resource discovery.
Resources=========
* `Outlook archive message shortcut`_* `AppleScript Essentials`_* `AppleScript Essentials: Introduction to Scripting Microsoft PowerPoint`_* `Applescript Microsoft 2011 PowerPoint`_* `Converting VBA Macros to AppleScript in Microsoft Office`_* `How can I use AppleScript to check if PowerPoint is playing a presentation?`_* `AppleScript on Wikipedia`_
.. _`Outlook archive message shortcut`: http://pastebin.com/m5imvA52
.. _`AppleScript Essentials`: http://www.mactech.com/articles/mactech/Vol.23/23.03 /23.03AppleScriptPowerPoint/index.html
.. _`AppleScript Essentials: Introduction to Scripting Microsoft PowerPoint`: http://www.mactech.com/articles/mactech/Vol.23/23.03 /23.03AppleScriptPowerPoint/index.html
.. _`Applescript Microsoft 2011 PowerPoint`: http://answers.microsoft.com/en-us/mac/forum/macoffice2011-macpowerpoint /applescript-microsoft-2011-powerpoint-want-to /2d71b92b-5ab4-4d75-a4fa-ed0b75b5e7b2?auth=1
.. _`Converting VBA Macros to AppleScript in Microsoft Office`: http://www.mactech.com/vba-transition-guide/index-toc.html
.. _`How can I use AppleScript to check if PowerPoint is playing a presentation?`: http://stackoverflow.com/questions/4695836/how-can-i-use-applescript-to -check-if-powerpoint-is-playing-a-presentation
.. _`AppleScript on Wikipedia`: http://en.wikipedia.org/wiki/AppleScript1234567891011121314151617=========Resources=========
... just collected bits and pieces here for now ...
.. toctree:: :maxdepth: 1
python_packaging about_packaging about_relationships web_resources technical_topics applescript odds_and_ends
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106=============Odds and Ends=============
Bits and pieces here without a more specific home
Class Hierarchy===============
::
pptx | +--.packaging | +--_PartCollection | | | +--ImageParts | +--SlideLayoutParts | +--SlideMasterParts | +--SlideParts | +--ThemeParts | +--Part | +--CollectionPart | | | +--ImagePart | +--SlideLayoutPart | +--SlideMasterPart | +--ThemePart | +--PresentationPart +--PresPropsPart +--SlidePart +--TableStylesPart +--ViewPropsPart
Also try something like this::
Exception hierarchy -------------------
The class hierarchy for built-in exceptions is:
.. literalinclude:: ../../Lib/test/exception_hierarchy.txt
Feature adding process:=======================
* Analysis
* Use case * Aspects of the spec and PowerPoint conventions that bear on the feature
* Implementation strategy
* Test Cases
* Documentation
* Implementation
* Commit
Odds and Ends=============
* DOC: Reserved Terms, e.g. package, part, item, element, etc. These have special meaning because of the terminology of Open XML packages and ElementTree XML conventions. Singleton, collection, perhaps tuple.
* DOC: Variable naming conventions. Variables containing XML elements are named the same as the tag name of the element they hold. For example: sldMaster = etree.parse('sldMaster1.xml')
* DOC: Suitable for server-side document generation, database publishing, taking tedium out of building intricate slides that have a distinct pattern, etc.
* DOC: Content Types mapping is discussed in ECMA-376-2 10.1.2 *Mapping Content Types*
* DOC: Explicit vs. Implicit relationships are discussed in section 9.2 of ECMA-376-1. Basically relationships to whole parts are explicit and relationships to one of the elements within another part (like a footnote) are implicit.
* DOC: [Open XML SDK How To's (How do I...)| http://207.46.22.237/en-us/library/cc850828.aspx]
* DOC: [Good hints on where formatting comes from in template|http://openxmldeveloper.org/discussions/formats/f/15/t/1301.aspx]
* Set work template slide layouts to standard type names for better layout re-mapping on theme/template change [http://msdn.microsoft.com/en-us/library/office/cc850846.aspx]
* spTree in cSld is a GroupShape (ShapeGroup?) perhaps Shape and ShapeGroup are ... ? not sure who should inherit from the other. GroupShapes can include other GroupShapes.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142================Python packaging================
Process Steps=============
1. Develop **setup.py** and other `distribution-related files`_#. Test distribution; should pass all `distribution tests`_#. Register project with the Python Package Index (PyPI)#. Upload distribution(s) to PyPI
.. _`distribution tests`:
Distribution tests==================
* ``python setup.py sdist`` does not raise an exception* all expected files are included in the distribution tarball* ``python setup.py test`` works in install environment* acceptance tests pass in install environment* ``python setup.py install`` produces expected footprint in ``site-packages``* easy_install works* ``pip install python-pptx`` works
Test can install with all popular methods-----------------------------------------
* manual* easy_install* pip
.. _`distribution-related files`:
Distribution-related files==========================
* setup.py* MANIFEST.in* setup.cfg
----
Distribution user stories=========================
... some notions about who uses these and for what ...
Roles-----
* naive end-user
Use Cases---------
Test build before distribution^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
"Just-works" installation^^^^^^^^^^^^^^^^^^^^^^^^^
::
In order to enable a new capability in my computing environment As a naive end-user I would like installation to "just work" and not scare me with error messages that don't indicate a real problem.
Install as a dependency^^^^^^^^^^^^^^^^^^^^^^^
Verify installation^^^^^^^^^^^^^^^^^^^
::
In order to verify a new installation As a python developer I want to be able to easily run the test suite without having to invest in any additional discovery or configuration.
Resources=========
* `The Hitchhiker’s Guide to Packaging`_* `Writing a Package in Python`_ by Tarek Ziadé is an extract from his PACKT book *Expert Python Programming* and while being somewhat dated, contains some useful tidbits.* Ian Bicking's blog post `Python's Makefile`_ discusses how to write extensions to setup.py, for perhaps a command like ``coverage`` that would automatically run ``nosetests --with-coverage``.* `tox documentation`_* `virtualenv documentation`_* `How To Package Your Python Code`_* `Python Packaging: Hate, hate, hate everywhere`_* `Building and Distributing Packages with setuptools`_* `A guide to Python packaging`_* `Python Packaging by Tarek Ziade`_
.. _`The Hitchhiker’s Guide to Packaging`: http://guide.python-distribute.org/index.html
.. _`Writing a Package in Python`: http://zetcode.com/articles/packageinpython/
.. _`Python's Makefile`: http://blog.ianbicking.org/pythons-makefile.html
.. _tox documentation: http://tox.readthedocs.org/en/latest/
.. _virtualenv documentation: http://www.virtualenv.org/en/latest/
.. _`Python Packaging: Hate, hate, hate everywhere`: http://lucumr.pocoo.org/2012/6/22/hate-hate-hate-everywhere/
.. _How To Package Your Python Code: http://www.scotttorborg.com/python-packaging/
.. _Building and Distributing Packages with setuptools: http://peak.telecommunity.com/DevCenter/setuptools
.. _`A guide to Python packaging`: http://www.ibm.com/developerworks/opensource/library/os-pythonpackaging/index.html
.. _`Python Packaging by Tarek Ziade`: http://www.aosabook.org/en/packaging.html
12345678910111213141516171819202122================Technical Topics================
Some technical topics that have become relevant to this project ...
Python Metaclasses==================
* `Metaclass programming in Python`_* `Python metaclasses by example`_
.. _`Metaclass programming in Python`: http://www.ibm.com/developerworks/linux/library/l-pymeta/index.html
.. _`Python metaclasses by example`: http://eli.thegreenplace.net/2011/08/14/python-metaclasses-by-example/
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889=============Web Resources=============
... just collected bits and pieces here for now ...
ECMA Spec=========...
Microsoft PowerPoint API documentation======================================
* `PowerPoint 2010 Interop Namespace`_
* `PowerPoint 2013 Object Model Reference`_
* `PowerPoint 2010 Object Model Reference`_
* `Open XML Presentation Namespace on MSDN`_
* `Office 2013 Open XML Presentation Namespace`_
* `Open XML Content Types as an XML Document`_
.. _PowerPoint 2010 Interop Namespace: http://msdn.microsoft.com/en-us/library/ff763170(v=office.14).aspx
.. _PowerPoint 2013 Object Model Reference: http://msdn.microsoft.com/en-us/library/office/ff743835.aspx
.. _PowerPoint 2010 Object Model Reference: http://msdn.microsoft.com/en-us/library/office/ff746846(v=office.14).aspx
.. _Open XML Presentation Namespace on MSDN: http://msdn.microsoft.com/en-us/library/office/cc884925.aspx
.. _Office 2013 Open XML Presentation Namespace: http://msdn.microsoft.com/en-us/library/cc884925.aspx
.. _Open XML Content Types as an XML Document: http://blogs.msdn.com/b/ericwhite/archive/2007/12/11/openxml-content- types-as-an-xml-document.aspx
Sphinx Resources================
* Alternate source for `Sphinx documentation <http://sphinx.readthedocs.org/en/latest/contents.html>`_
* `An example PyPi project <http://packages.python.org/an_example_pypi_project/sphinx.html>`_
Documentation Guides====================
* Nice GitHub Project Style Guide (esp. Commit Style Guide) `textmate / restructuredtext.tmbundle <https://github.com/textmate/restructuredtext.tmbundle>`_
* Python Documentation guide `Documenting Python Guide <http://docs.python.org/devguide/documenting.html>`_
* `Google Python Style Guide <http://google-styleguide.googlecode.com/svn/trunk/pyguide.html>`_
* `Read The Docs (readthedocs.org) <https://docs.readthedocs.org/en/latest/index.html>`_
* `OpenComparison documetation on readthedocs.org <http://opencomparison.readthedocs.org/en/latest/contributing.html>`_
* `The Hitchhiker’s Guide to Packaging <http://guide.python-distribute.org/index.html>`_
Other Resources===============
* `Python Magic Methods <http://www.rafekettler.com/magicmethods.html>`_
* `lxml.etree Tutorial <http://lxml.de/tutorial.html>`_
* `lxml API Reference <http://lxml.de/api/index.html>`_
* `The factory pattern in Python with __new__ <http://whilefalse.net/2009/10/21/factory-pattern-python-__new__/>`_
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
Running the test suite======================
|pp| has a robust test suite, comprising over 600 tests at the time of writing,both at the acceptance test and unit test levels. ``pytest`` is used for unittests, with help from the excellent ``mock`` library. ``behave`` is used foracceptance tests.
You can run the tests from the source working directory using the followingcommands::
$ py.test ============================ test session starts ============================ platform darwin -- Python 2.7.5 -- pytest-2.4.2 plugins: cov collected 301 items
tests/test_oxml.py ......................................... tests/test_presentation.py ................... tests/test_spec.py ........ tests/test_text.py .......................... tests/test_util.py ............... tests/opc/test_packaging.py ..................................................... tests/opc/test_rels.py .............. tests/parts/test_coreprops.py . tests/parts/test_image.py ........... tests/parts/test_part.py ........ tests/parts/test_slides.py .................. tests/shapes/test_autoshape.py .................... tests/shapes/test_picture.py . tests/shapes/test_placeholder.py . tests/shapes/test_shape.py ........... tests/shapes/test_shapetree.py .............. tests/shapes/test_table.py ........................................
======================= 301 passed in 2.00 seconds ======================
$ behave Feature: Add a text box to a slide In order to accommodate a requirement for free-form text on a slide As a presentation developer I need the ability to place a text box on a slide
Scenario: Add a text box to a slide Given I have a reference to a blank slide When I add a text box to the slide's shape collection And I save the presentation Then the text box appears in the slide
# ... more output ...
13 features passed, 0 failed, 0 skipped 30 scenarios passed, 0 failed, 0 skipped 120 steps passed, 0 failed, 0 skipped, 0 undefined Took 0m1.3s123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
Understanding ``xmlchemy``==========================
``xmlchemy`` is an object-XML mapping layer somewhat reminiscent ofSQLAlchemy, hence the name. Mapping XML elements to objects is not nearly aschallenging as mapping to a relational database, so this layer issubstantially more modest. Nevertheless, it provides a powerful and veryuseful abstraction layer around ``lxml``, particularly well-suited toproviding access to the broad schema of XML elements involved in the Open XMLstandard.
Additional topics to add ...----------------------------
* understanding complex types in Open XML* understanding attribute definitions Open XML* understanding simple types in Open XML
Adding support for a new element type-------------------------------------
* add a new custom element mapping to ``pptx.oxml.__init__``* add a new custom element class in the appropriate ``pptx.oxml`` subpackage module* Add element definition members to the class* Add attribute definition members to the class* Add simple type definitions to ``pptx.oxml.simpletype``
Example-------
::
from pptx.oxml.xmlchemy import BaseOxmlElement
class CT_Foobar(BaseOxmlElement): """ Custom element class corresponding to ``CT_Foobar`` complex type definition in pml.xsd or other Open XML schema. """ hlink = ZeroOrOne('a:hlink', successors=('a:rtl', 'a:extLst')) eg_fillProperties = ZeroOrOneChoice( (Choice('a:noFill'), Choice('a:solidFill'), Choice('a:gradFill'), Choice('a:blipFill'), Choice('a:pattFill')), successors=( 'a:effectLst', 'a:effectDag', 'a:highlight', 'a:uLnTx', 'a:uLn', 'a:uFillTx' 'a:extLst' ) )
sz = OptionalAttribute( 'sz', ST_SimpleType, default=ST_SimpleType.OPTION ) anchor = OptionalAttribute('i', XsdBoolean) rId = RequiredAttribute('r:id', XsdString)
Protocol--------
::
>>> assert isinstance(foobar, CT_Foobar) >>> foobar.hlink None >>> hlink = foobar._add_hlink() >>> hlink <pptx.oxml.xyz.CT_Hyperlink object at 0x10ab4b2d0> >>> assert foobar.hlink is hlink
>>> foobar.eg_fillProperties None >>> foobar.solidFill None >>> solidFill = foobar.get_or_change_to_solidFill() >>> solidFill <pptx.oxml.xyz.CT_SolidFill object at 0x10ab4b2d0> >>> assert foobar.eg_fillProperties is solidFill >>> assert foobar.solidFill is solidFill >>> foobar.remove_eg_fillProperties() >>> foobar.eg_fillProperties None >>> foobar.solidFill None
``OneAndOnlyOne`` element declaration-------------------------------------
The ``OneAndOnlyOne`` callable generates the API for a required childelement::
childElement = OneAndOnlyOne('ns:localTagName')
Unlike the other element declarations, the call does not includea ``successors`` argument. Since no API for inserting a new element isgenerated, a successors list is not required.
Generated API~~~~~~~~~~~~~
``childElement`` property (read-only) Holds a reference to the child element object. Raises |InvalidXmlError| on access if the required child element is not present.
Protocol~~~~~~~~
::
>>> foobar.childElement <pptx.oxml.xyz.CT_ChildElement object at 0x10ab4b2d0>
``RequiredAttribute`` attribute declaration-------------------------------------------
::
reqAttr = RequiredAttribute('reqAtr', ST_SimpleType)
Generated API~~~~~~~~~~~~~
``childElement`` property (read/write) Referencing the property returns the type-converted value of the attribute as determined by the ``from_xml()`` method of the simple type class appearing in the declaration (e.g. ST_SimpleType above). Assignments to the property are validated by the ``validate()`` method of the simple type class, potentially raising ``TypeError`` or ``ValueError``. Values are assigned in their natural Python type and are encoded to the appropriate string value by the ``to_xml()`` method of the simple type class.
``ZeroOrOne`` element declaration---------------------------------
::
childElement = ZeroOrOne( 'ns:localTagName', successors=('ns:abc', 'ns:def') )
Generated API~~~~~~~~~~~~~
``childElement`` property (read-only) Holds a reference to the child element object, or None if the element is not present.
``get_or_add_childElement()`` method Returns the child element object, newly added if not present.
``_add_childElement()`` empty element adder method Returns a newly added empty child element having the declared tag name. Adding is unconditional and assumes the element is not already present. This method is called by the ``get_or_add_childElement()`` method as needed and may be called by a hand-coded ``add_childElement()`` method as needed. May be overridden to produce customized behavior.
``_new_childElement()`` empty element creator method Returns a new "loose" child element of the declared tag name. Called by ``_add_childElement()`` to obtain a new child element, it may be overridden to customize the element creation process.
``_insert_childElement(childElement)`` element inserter method Returns the passed ``childElement`` after inserting it before any successor elements, as listed in the ``successors`` argument of the declaration. Called by ``_add_childElement()`` to insert the new element it creates using ``_new_childElement()``.
``_remove_childElement()`` element remover method Removes all instances of the child element. Does not raise an error if no matching child elements are present.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
python-pptx===========
Release v\ |version| (:ref:`Installation <install>`)
.. include:: ../README.rst
Philosophy----------
|pp| aims to broadly support the PowerPoint format (PPTX, PowerPoint 2007 and later),but its primary commitment is to be *industrial-grade*, that is, suitable for use in acommercial setting. Maintaining this robustness requires a high engineering standardwhich includes a comprehensive two-level (e2e + unit) testing regimen. This disciplinecomes at a cost in development effort/time, but we consider reliability to be anessential requirement.
Feature Support---------------
|pp| has the following capabilities:
* Round-trip any Open XML presentation (.pptx file) including all its elements* Add slides* Populate text placeholders, for example to create a bullet slide* Add image to slide at arbitrary position and size* Add textbox to a slide; manipulate text font size and bold* Add table to a slide* Add auto shapes (e.g. polygons, flowchart shapes, etc.) to a slide* Add and manipulate column, bar, line, and pie charts* Access and change core document properties such as title and subject* And many others ...
Even with all |pp| does, the PowerPoint document format is very rich and there are stillfeatures |pp| does not support.
New features/releases---------------------
New features are generally added via sponsorship. If there's a new feature you need foryour use case, feel free to reach out at the email address on the github.com/scannyprofile page. Many of the most used features such as charts were added this way.
User Guide----------
.. toctree:: :maxdepth: 1
user/intro user/install user/quickstart user/presentations user/slides user/understanding-shapes user/autoshapes user/placeholders-understanding user/placeholders-using user/text user/charts user/table user/notes user/use-cases user/concepts
Community Guide---------------
.. toctree:: :maxdepth: 1
community/faq community/support community/updates
.. _api:
API Documentation-----------------
.. toctree:: :maxdepth: 2
api/presentation api/slides api/shapes api/placeholders api/table api/chart-data api/chart api/text api/action api/dml api/image api/exc api/util api/enum/index
Contributor Guide-----------------
.. toctree:: :maxdepth: 1
dev/runtests dev/xmlchemy dev/development_practices dev/philosophy dev/analysis/index dev/resources/index123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
Working with AutoShapes=======================
Auto shapes are regular shape shapes. Squares, circles, triangles, stars,that sort of thing. There are 182 different auto shapes to choose from. 120of these have adjustment "handles" you can use to change the shape, sometimesdramatically.
Many shape types share a common set of properties. We'll introduce many ofthem here because several of those shapes are just a specialized form ofAutoShape.
Adding an auto shape--------------------
The following code adds a rounded rectangle shape, one inch square, andpositioned one inch from the top-left corner of the slide::
from pptx.enum.shapes import MSO_SHAPE
shapes = slide.shapes left = top = width = height = Inches(1.0) shape = shapes.add_shape( MSO_SHAPE.ROUNDED_RECTANGLE, left, top, width, height )
See the :ref:`MsoAutoShapeType` enumeration page for a list of all 182 autoshape types.
.. _`EMU`:
Understanding English Metric Units----------------------------------
In the prior example we set the position and dimension values to theexpression ``Inches(1.0)``. What's that about?
Internally, PowerPoint stores length values in *English Metric Units* (EMU).This term might be worth a quick Googling, but the short story is EMU is aninteger unit of length, 914400 to the inch. Most lengths in Office documentsare stored in EMU. 914400 has the great virtue that it is evenly divisible bya great many common factors, allowing exact conversion between inches andcentimeters, for example. Being an integer, it can be represented exactlyacross serializations and across platforms.
As you might imagine, working directly in EMU is inconvenient. To make iteasier, python-pptx provides a collection of value types to allow easyspecification and conversion into convenient units::
>>> from pptx.util import Inches, Pt >>> length = Inches(1) >>> length 914400 >>> length.inches 1.0 >>> length.cm 2.54 >>> length.pt 72.0 >>> length = Pt(72) >>> length 914400
More details are available in the :ref:`API documentation for pptx.util<util>`
Shape position and dimensions-----------------------------
All shapes have a position on their slide and have a size. In general,position and size are specified when the shape is created. Position and sizecan also be read from existing shapes and changed::
>>> from pptx.enum.shapes import MSO_SHAPE >>> left = top = width = height = Inches(1.0) >>> shape = shapes.add_shape( >>> MSO_SHAPE.ROUNDED_RECTANGLE, left, top, width, height >>> ) >>> shape.left, shape.top, shape.width, shape.height (914400, 914400, 914400, 914400) >>> shape.left.inches 1.0 >>> shape.left = Inches(2.0) >>> shape.left.inches 2.0
Fill----
AutoShapes have an outline around their outside edge. What appears withinthat outline is called the shape's *fill*.
The most common type of fill is a solid color. A shape may also be filledwith a gradient, a picture, a pattern (like cross-hatching for example), ormay have no fill (transparent).
When a color is used, it may be specified as a specific RGB value or a colorfrom the theme palette.
Because there are so many options, the API for fill is a bit complex. Thiscode sets the fill of a shape to red::
>>> fill = shape.fill >>> fill.solid() >>> fill.fore_color.rgb = RGBColor(255, 0, 0)
This sets it to the theme color that appears as 'Accent 1 - 25% Darker' inthe toolbar palette::
>>> from pptx.enum.dml import MSO_THEME_COLOR >>> fill = shape.fill >>> fill.solid() >>> fill.fore_color.theme_color = MSO_THEME_COLOR.ACCENT_1 >>> fill.fore_color.brightness = -0.25
This sets the shape fill to transparent, or 'No Fill' as it's called in thePowerPoint UI::
>>> shape.fill.background()
As you can see, the first step is to specify the desired fill type by callingthe corresponding method on fill. Doing so actually changes the propertiesavailable on the fill object. For example, referencing ``.fore_color`` on afill object after calling its ``.background()`` method will raise anexception::
>>> fill = shape.fill >>> fill.solid() >>> fill.fore_color <pptx.dml.color.ColorFormat object at 0x10ce20910> >>> fill.background() >>> fill.fore_color Traceback (most recent call last): ... TypeError: a transparent (background) fill has no foreground color
Line----
The outline of an AutoShape can also be formatted, including setting itscolor, width, dash (solid, dashed, dotted, etc.), line style (single, double,thick-thin, etc.), end cap, join type, and others. At the time of writing,color and width can be set using python-pptx::
>>> line = shape.line >>> line.color.rgb = RGBColor(255, 0, 0) >>> line.color.brightness = 0.5 # 50% lighter >>> line.width = Pt(2.5)
Theme colors can be used on lines too::
>>> line.color.theme_color = MSO_THEME_COLOR.ACCENT_6
``Shape.line`` has the attribute ``.color``. This is essentially a shortcutfor::
>>> line.fill.solid() >>> line.fill.fore_color
This makes sense for line formatting because a shape outline is mostfrequently set to a solid color. Accessing the fill directly is required, forexample, to set the line to transparent::
>>> line.fill.background()
Line width~~~~~~~~~~
The shape outline also has a read/write width property::
>>> line.width 9525 >>> line.width.pt 0.75 >>> line.width = Pt(2.0) >>> line.width.pt 2.0
Adjusting an autoshape----------------------
Many auto shapes have adjustments. In PowerPoint, these show up as littleyellow diamonds you can drag to change the look of the shape. They're a littlefiddly to work with via a program, but if you have the patience to get themright, you can achieve some remarkable effects with great precision.
Shape Adjustment Concepts~~~~~~~~~~~~~~~~~~~~~~~~~
There are a few concepts it's worthwhile to grasp before trying to do seriouswork with adjustments.
First, adjustments are particular to a specific auto shape type. Each autoshape has between zero and eight adjustments. What each of them does isarbitrary and depends on the shape design.
Conceptually, adjustments are guides, in many ways like the light blue ones youcan align to in the PowerPoint UI and other drawing apps. These don't show, butthey operate in a similar way, each defining an x or y value that part of theshape will align to, changing the proportions of the shape.
Adjustment values are large integers, each based on a nominal value of 100,000.The effective value of an adjustment is proportional to the width or height ofthe shape. So a value of 50,000 for an x-coordinate adjustment corresponds tohalf the width of the shape; a value of 75,000 for a y-coordinate adjustmentcorresponds to 3/4 of the shape height.
Adjustment values can be negative, generally indicating the coordinate is tothe left or above the top left corner (origin) of the shape. Values can also besubject to limits, meaning their effective value cannot be outside a prescribedrange. In practice this corresponds to a point not being able to extend beyondthe left side of the shape, for example.
Spending some time fooling around with shape adjustments in PowerPoint is timewell spent to build an intuitive sense of how they behave. You also might wantto have ``opc-diag`` installed so you can look at the XML values that aregenerated by different adjustments as a head start on developing youradjustment code.
The following code formats a callout shape using its adjustments::
callout_sp = shapes.add_shape( MSO_SHAPE.LINE_CALLOUT_2_ACCENT_BAR, left, top, width, height )
# get the callout line coming out of the right place adjs = callout_sp.adjustments adjs[0] = 0.5 # vert pos of junction in margin line, 0 is top adjs[1] = 0.0 # horz pos of margin ln wrt shape width, 0 is left side adjs[2] = 0.5 # vert pos of elbow wrt margin line, 0 is top adjs[3] = -0.1 # horz pos of elbow wrt shape width, 0 is margin line adjs[4] = 3.0 # vert pos of line end wrt shape height, 0 is top a5 = adjs[3] - (adjs[4] - adjs[0]) * height/width adjs[5] = a5 # horz pos of elbow wrt shape width, 0 is margin line
# rotate 45 degrees counter-clockwise callout_sp.rotation = -45.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
Working with charts===================
|pp| supports adding charts and modifying existing ones. Most chart typesother than 3D types are supported.
Adding a chart--------------
The following code adds a single-series column chart in a new presentation::
from pptx import Presentation from pptx.chart.data import CategoryChartData from pptx.enum.chart import XL_CHART_TYPE from pptx.util import Inches
# create presentation with 1 slide ------ prs = Presentation() slide = prs.slides.add_slide(prs.slide_layouts[5])
# define chart data --------------------- chart_data = CategoryChartData() chart_data.categories = ['East', 'West', 'Midwest'] chart_data.add_series('Series 1', (19.2, 21.4, 16.7))
# add chart to slide -------------------- x, y, cx, cy = Inches(2), Inches(2), Inches(6), Inches(4.5) slide.shapes.add_chart( XL_CHART_TYPE.COLUMN_CLUSTERED, x, y, cx, cy, chart_data )
prs.save('chart-01.pptx')
.. image:: /_static/img/chart-01.png
Customizing things a bit------------------------
The remaining code will leave out code we've already seen and only showimports, for example, when they're used for the first time, just to keep thefocus on the new bits. Let's create a multi-series chart to use for theseexamples::
chart_data = ChartData() chart_data.categories = ['East', 'West', 'Midwest'] chart_data.add_series('Q1 Sales', (19.2, 21.4, 16.7)) chart_data.add_series('Q2 Sales', (22.3, 28.6, 15.2)) chart_data.add_series('Q3 Sales', (20.4, 26.3, 14.2))
graphic_frame = slide.shapes.add_chart( XL_CHART_TYPE.COLUMN_CLUSTERED, x, y, cx, cy, chart_data )
chart = graphic_frame.chart
.. image:: /_static/img/chart-02.png
Notice that we captured the shape reference returned by the:meth:`~.SlideShapes.add_chart` call as ``graphic_frame`` and then extractedthe chart object from the graphic frame using its:attr:`~.GraphicFrame.chart` property. We'll need the chart reference to getto the properties we'll need in the next steps. The:meth:`~.SlideShapes.add_chart` method doesn't directly return the chartobject. That's because a chart is not itself a shape. Rather it's a graphical(DrawingML) object *contained* in the graphic frame shape. Tables work thisway too, also being contained in a graphic frame shape.
XY and Bubble charts--------------------
The charts so far use a *discrete* set of values for the independent variable(the X axis, roughly speaking). These are perfect when your values fall intoa well-defined set of categories. However, there are many cases, particularlyin science and engineering, where the independent variable is a continuousvalue, such as temperature or frequency. These are supported in PowerPoint byXY (aka. scatter) charts. A bubble chart is essentially an XY chart where themarker size is used to reflect an additional value, effectively addinga third dimension to the chart.
Because the independent variable is continuous, in general, the series do notall share the same X values. This requires a somewhat different datastructure and that is provided for by distinct |XyChartData| and|BubbleChartData| objects used to specify the data behind charts of thesetypes::
chart_data = XyChartData()
series_1 = chart_data.add_series('Model 1') series_1.add_data_point(0.7, 2.7) series_1.add_data_point(1.8, 3.2) series_1.add_data_point(2.6, 0.8)
series_2 = chart_data.add_series('Model 2') series_2.add_data_point(1.3, 3.7) series_2.add_data_point(2.7, 2.3) series_2.add_data_point(1.6, 1.8)
chart = slide.shapes.add_chart( XL_CHART_TYPE.XY_SCATTER, x, y, cx, cy, chart_data ).chart
.. image:: /_static/img/chart-08.png
Creation of a bubble chart is very similar, having an additional value for each data point that specifies the bubble size::
chart_data = BubbleChartData()
series_1 = chart_data.add_series('Series 1') series_1.add_data_point(0.7, 2.7, 10) series_1.add_data_point(1.8, 3.2, 4) series_1.add_data_point(2.6, 0.8, 8)
chart = slide.shapes.add_chart( XL_CHART_TYPE.BUBBLE, x, y, cx, cy, chart_data ).chart
.. image:: /_static/img/chart-09.png
Axes----
Let's change up the category and value axes a bit::
from pptx.enum.chart import XL_TICK_MARK from pptx.util import Pt
category_axis = chart.category_axis category_axis.has_major_gridlines = True category_axis.minor_tick_mark = XL_TICK_MARK.OUTSIDE category_axis.tick_labels.font.italic = True category_axis.tick_labels.font.size = Pt(24)
value_axis = chart.value_axis value_axis.maximum_scale = 50.0 value_axis.minor_tick_mark = XL_TICK_MARK.OUTSIDE value_axis.has_minor_gridlines = True
tick_labels = value_axis.tick_labels tick_labels.number_format = '0"%"' tick_labels.font.bold = True tick_labels.font.size = Pt(14)
.. image:: /_static/img/chart-03.png
Okay, that was probably going a bit too far. But it gives us an idea of thekinds of things we can do with the value and category axes. Let's undo thispart and go back to the version we had before.
Data Labels-----------
Let's add some data labels so we can see exactly what the value for each baris::
from pptx.dml.color import RGBColor from pptx.enum.chart import XL_LABEL_POSITION
plot = chart.plots[0] plot.has_data_labels = True data_labels = plot.data_labels
data_labels.font.size = Pt(13) data_labels.font.color.rgb = RGBColor(0x0A, 0x42, 0x80) data_labels.position = XL_LABEL_POSITION.INSIDE_END
.. image:: /_static/img/chart-04.png
Here we needed to access a Plot object to gain access to the data labels.A plot is like a sub-chart, containing one or more series and drawn asa particular chart type, like column or line. This distinction is needed forcharts that combine more than one type, like a line chart appearing on top ofa column chart. A chart like this would have two plot objects, one for theseries appearing as columns and the other for the lines. Most charts onlyhave a single plot and |pp| doesn't yet support creating multi-plot charts,but you can access multiple plots on a chart that already has them.
In the Microsoft API, the name *ChartGroup* is used for this object. I foundthat term confusing for a long time while I was learning about MS Officecharts so I chose the name Plot for that object in |pp|.
Legend------
A legend is often useful to have on a chart, to give a name to each seriesand help a reader tell which one is which::
from pptx.enum.chart import XL_LEGEND_POSITION
chart.has_legend = True chart.legend.position = XL_LEGEND_POSITION.RIGHT chart.legend.include_in_layout = False
.. image:: /_static/img/chart-05.png
Nice! Okay, let's try some other chart types.
Line Chart----------
A line chart is added pretty much the same way as a bar or column chart, themain difference being the chart type provided in the :meth:`add_chart` call::
chart_data = ChartData() chart_data.categories = ['Q1 Sales', 'Q2 Sales', 'Q3 Sales'] chart_data.add_series('West', (32.2, 28.4, 34.7)) chart_data.add_series('East', (24.3, 30.6, 20.2)) chart_data.add_series('Midwest', (20.4, 18.3, 26.2))
x, y, cx, cy = Inches(2), Inches(2), Inches(6), Inches(4.5) chart = slide.shapes.add_chart( XL_CHART_TYPE.LINE, x, y, cx, cy, chart_data ).chart
chart.has_legend = True chart.legend.include_in_layout = False chart.series[0].smooth = True
.. image:: /_static/img/chart-06.png
I switched the categories and series data here to better suit a line chart.You can see the line for the "West" region is *smoothed* into a curve whilethe other two have their points connected with straight line segments.
Pie Chart---------
A pie chart is a little special in that it only ever has a single series anddoesn't have any axes::
chart_data = ChartData() chart_data.categories = ['West', 'East', 'North', 'South', 'Other'] chart_data.add_series('Series 1', (0.135, 0.324, 0.180, 0.235, 0.126))
chart = slide.shapes.add_chart( XL_CHART_TYPE.PIE, x, y, cx, cy, chart_data ).chart
chart.has_legend = True chart.legend.position = XL_LEGEND_POSITION.BOTTOM chart.legend.include_in_layout = False
chart.plots[0].has_data_labels = True data_labels = chart.plots[0].data_labels data_labels.number_format = '0%' data_labels.position = XL_LABEL_POSITION.OUTSIDE_END
.. image:: /_static/img/chart-07.png
Odds & Ends-----------
This should be enough to get you started with adding charts to yourpresentation with |pp|. There are more details in the API documentation forcharts here: :ref:`chart-api`
About colors~~~~~~~~~~~~
By default, the colors assigned to each series in a chart are the themecolors Accent 1 through Accent 6, in that order. If you have more than sixseries, darker and lighter versions of those same colors are used. While it'spossible to assign specific colors to data points (bar, line, pie segment,etc.) for at least some chart types, the best strategy to start with ischanging the theme colors in your starting "template" presentation.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192Concepts========
|pp| is completely object-oriented, and in general any operations you performwith it will be on an object. The root object for a presentation is|Presentation|. API details are provided on the modules pages, but here aresome basics to get you started, especially some relationships you might findsurprising at first.
A presentation is loaded by constructing a new |Presentation| instance,passing in the path to a presentation to be loaded::
from pptx import Presentation
path = 'slide-deck-foo.pptx' prs = Presentation(path)
|pp| also contains a default template, and if you construct a |Presentation|instance without a path, a presentation based on that default template isloaded. This can be handy when you want to get started quickly, and most of theexamples in this documentation use the default template.::
# start with default presentation prs = Presentation()
Note that there is currently no distinction between templates and presentationsin |pp| as there is in the PowerPoint® client, there are only presentations. Touse a "template" for a presentation you simply create a presentation with allthe styles, logo, and layouts you want, delete all the slides (or leave some inif it suits), and then load that as your starting place.
Slide masters-------------
A presentation has a list of slide masters and a list of slides. Let's startwith a discussion of the slide masters.
One fact some find surprising (I did) is that a presentation file can havemore than one slide master. It's quite uncommon in my experience to findpresentations that make use of this feature, but it's entirely supported. Theonly time I've seen this happen is when slides from a "foreign" presentationare pasted into another deck; if you want the formatting and backgrounds fromthe other deck to be preserved on the pasted-in slides, the slide master andits slide layouts need to come with. Consequently, the presentation needs tomaintain a list of slide masters, not just a single one, even though perhaps99% of the time you only ever use the one. To make things a little easier forthe 99% situation, you can refer to the first slide master as though it werethe only one::
prs = Presentation() slide_master = prs.slide_masters[0] # is equivalent to slide_master = prs.slide_master
Slide layouts-------------
Another fact that might be surprising is that slide layouts belong to a slidemaster, not directly to a presentation, so normally you have to access theslide layouts via their slide master. Since this is subject to the same 99%situation described above, the slide layouts belonging to the first slidemaster can also be accessed directly from the presentation via syntacticsugar::
prs = Presentation() title_slide_layout = prs.slide_masters[0].slide_layouts[0] # is equivalent to: title_slide_layout = prs.slide_layouts[0]
Slides------
The slides in a presentation belong to the presentation object and areaccessed using the ``slides`` attribute::
prs = Presentation(path) first_slide = prs.slides[0]
Adding a slide^^^^^^^^^^^^^^
Adding a slide is accomplished by calling the :meth:`add_slide` method on the:attr:`slides` attribute of the presentation. A slide layout must be passedin to specify the layout the new slide should take on::
prs = Presentation() title_slide_layout = prs.slide_layouts[0] new_slide = prs.slides.add_slide(title_slide_layout)12345678910111213141516171819202122232425.. _install:
Installing==========
|pp| is hosted on PyPI, so installing with `pip` is simple::
pip install python-pptx
|pp| depends on the ``lxml`` package and ``Pillow``, the modern version ofthe Python Imaging Library (``PIL``). The charting features depend on``XlsxWriter``. Both ``pip`` and ``easy_install`` will take care ofsatisfying these dependencies for you, but if you use the ``setup.py``installation method you will need to install the dependencies yourself.
Currently |pp| requires Python 2.7 or 3.3 or later. The tests are run against 2.7 and3.8 on Travis CI.
Dependencies------------
* Python 2.6, 2.7, 3.3 or later* lxml* Pillow* XlsxWriter (to use charting features)12345678910111213141516171819202122232425.. _introduction:
Introduction============
*python-pptx* is a Python library for creating and updating PowerPoint (.pptx)files.
A typical use would be generating a customized PowerPoint presentation fromdatabase content, downloadble by clicking a link in a web application. Severaldevelopers have used it to automate production of presentation-readyengineering status reports based on information held in their work managementsystem. It could also be used for making bulk updates to a library ofpresentations or simply to automate the production of a slide or two that wouldbe tedious to get right by hand.
This user guide is tutorial in nature, introducing concepts along with codeexamples that I hope will allow you to learn what you need while addressingthe real-life PowerPoint challenges you're working on.
python-pptx License-------------------
.. include:: ../../LICENSE123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
Working with Notes Slides=========================
A slide can have notes associated with it. These are perhaps most commonlyencountered in the notes pane, below the slide in PowerPoint "Normal" viewwhere it may say "Click to add notes".
The notes added here appear each time that slide is present in the main pane.They also appear in *Presenter View* and in *Notes Page* view, both availablefrom the menu.
Notes can contain rich text, commonly bullets, bold, varying font sizes andcolors, etc. The Notes Page view has somewhat more powerful tools for editingthe notes text than the note pane in Normal view.
In the API and the underlying XML, the object that contains the text is knownas a *Notes Slide*. This is because internally, a notes slide is actuallya specialized instance of a slide. It contains shapes, many of which areplaceholders, and allows inserting of new shapes such as pictures (a logoperhaps) auto shapes, tables, and charts. Consequently, working with a notesslide is very much like working with a regular slide.
Each slide can have zero or one notes slide. A notes slide is created thefirst time it is used, generally perhaps by adding notes text to a slide.Once created, it stays, even if all the text is deleted.
The Notes Master----------------
A new notes slide is created using the *Notes Master* as a template.A presentation has no notes master when newly created in PowerPoint. One iscreated according to a PowerPoint-internal preset default the first time itis needed, which is generally when the first notes slide is created. It'spossible one can also be created by entering the Notes Master view and almostcertainly is created by editing the master found there (haven't tried itthough). A presentation can have at most one notes master.
The notes master governs the look and feel of notes pages, which can beviewed on-screen but are really designed for printing out. So if you wantyour notes page print-outs to look different from the default, you can makea lot of customizations by editing the notes master. You access the notesmaster editor using View > Master > Notes Master on the menu (on my versionat least). Notes slides created using |pp| will have the look and feel of thenotes master in the presentation file you opened to create the presentation.
On creation, certain placeholders (slide image, notes, slide number) arecopied from the notes master onto the new notes slide (if they have not beenremoved from the master). These "cloned" placeholders inherit position, size,and formatting from their corresponding notes master placeholder. If theposition, size, or formatting of a notes slide placeholder is changed, thechanged property is no long inherited (unchanged properties, however,continue to be inherited).
Notes Slide basics------------------
Enough talk, let's show some code. Let's say you have a slide you're workingwith and you want to see if it has a notes slide yet::
>>> slide.has_notes_slide False
Ok, not yet. Good. Let's add some notes::
>>> notes_slide = slide.notes_slide >>> text_frame = notes_slide.notes_text_frame >>> text_frame.text = 'foobar'
Alright, simple enough. Let's look at what happened here:
* ``slide.notes_slide`` gave us the notes slide. In this case, it first created that notes slide based on the notes master. If there was no notes master, it created that too. So a lot of things can happen behind the scenes with this call the first time you call it, but if we called it again it would just give us back the reference to the same notes slide, which it caches, once retrieved.
* ``notes_slide.notes_text_frame`` gave us the |TextFrame| object that contains the actual notes. The reason it's not just ``notes_slide.text_frame`` is that there are potentially more than one. What this is doing behind the scenes is finding the placeholder shape that contains the notes (as opposed to the slide image, header, slide number, etc.) and giving us *that* particular text frame.
* A text frame in a notes slide works the same as one in a regular slide. More precisely, a text frame on a shape in a notes slide works the same as in any other shape. We used the ``.text`` property to quickly pop some text in there.
Using the text frame, you can add an arbitrary amount of text, formattedhowever you want.
Notes Slide Placeholders------------------------
What we haven't explicitly seen so far is the shapes on a slide master. It'seasy to get started with that::
>>> notes_placeholder = notes_slide.notes_placeholder
This notes placeholder is just like a body placeholder we saw a couplesections back. You can change its position, size, and many other attributes,as well as get at its text via its text frame.
You can also access the other placeholders::
>>> for placeholder in notes_slide.placeholders: ... print placeholder.placeholder_format.type ... SLIDE_IMAGE (101) BODY (2) SLIDE_NUMBER (13)
and also the shapes (a superset of the placeholders)::
>>> for shape in notes_slide.shapes: ... print shape ... <pptx.shapes.placeholder.NotesSlidePlaceholder object at 0x11091e890> <pptx.shapes.placeholder.NotesSlidePlaceholder object at 0x11091e750> <pptx.shapes.placeholder.NotesSlidePlaceholder object at 0x11091e990>
In the common case, the notes slide contains only placeholders. However, ifyou added an image, for example, to the notes slide, that would show up aswell. Note that if you added that image to the notes master, perhaps a logo,it would appear on the notes slide "visually", but would not appear asa shape in the notes slide shape collection. Rather, it is visually"inherited" from the notes master.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
Understanding placeholders==========================
Intuitively, a placeholder is a pre-formatted container into which contentcan be placed. By providing pre-set formatting to its content, it places manyof the formatting choices in the hands of the template designer whileallowing the end-user to concentrate on the actual content. This speeds thepresentation development process while encouraging visual consistency inslides created from the same template.
While their typical end-user behaviors are relatively simple, the structuresthat support their operation are more complex. This page is for those whowant to better understand the architecture of the placeholder subsystem andperhaps be less prone to confusion at its sometimes puzzling behavior. If youdon't care why they work and just want to know how to work with them, you maywant to skip forward to the following page :ref:`placeholders-using`.
A placeholder is a shape------------------------
Placeholders are an orthogonal category of shape, which is to say multipleshape types can be placeholders. In particular, the auto shape (`p:sp`element), picture (`p:pic` element), and graphic frame (`p:graphicFrame`)shape types can be a placeholder. The group shape (`p:grpSp`), connector(`p:cxnSp`), and content part (`p:contentPart`) shapes cannot bea placeholder. A graphic frame placeholder can contain a table, a chart, orSmartArt.
Placeholder types-----------------
There are 18 types of placeholder.
Title, Center Title, Subtitle, Body These placeholders typically appear on a conventional "word chart" containing text only, often organized as a title and a series of bullet points. All of these placeholders can accept text only.
Content This multi-purpose placeholder is the most commonly used for the body of a slide. When unpopulated, it displays 6 buttons to allow insertion of a table, a chart, SmartArt, a picture, clip art, or a media clip.
Picture, Clip Art These both allow insertion of an image. The insert button on a clip art placeholder brings up the clip art gallery rather than an image file chooser, but otherwise these behave the same.
Chart, Table, Smart Art These three allow the respective type of rich graphical content to be inserted.
Media Clip Allows a video or sound recording to be inserted.
Date, Footer, Slide Number These three appear on most slide masters and slide layouts, but do not behave as most users would expect. These also commonly appear on the Notes Master and Handout Master.
Header Only valid on the Notes Master and Handout Master.
Vertical Body, Vertical Object, Vertical Title Used with vertically oriented languages such as Japanese.
Unpopulated vs. populated-------------------------
A placeholder on a slide can be empty or filled. This is most evident witha picture placeholder. When unpopulated, a placeholder displays customizableprompt text. A rich content placeholder will also display one or more contentinsertion buttons when empty.
A text-only placeholder enters "populated" mode when the first character oftext is entered and returns to "unpopulated" mode when the last character oftext is removed. A rich-content placeholder enters populated mode whencontent such as a picture is inserted and returns to unpopulated mode whenthat content is deleted. In order to delete a populated placeholder, theshape must be deleted *twice*. The first delete removes the content andrestores the placeholder to unpopulated mode. An additional delete willremove the placeholder itself. A deleted placeholder can be restored byreapplying the layout.
Placholders inherit-------------------
A placeholder appearing on a slide is only part of the overall placeholdermechanism. Placeholder behavior requires three different categories ofplaceholder shape; those that exist on a slide master, those on a slidelayout, and those that ultimately appear on a slide in a presentation.
These three categories of placeholder participate in a property inheritancehierarchy, either as an inheritor, an inheritee, or both. Placeholder shapeson masters are inheritees only. Conversely placeholder shapes on slides areinheritors only. Placeholders on slide layouts are both, a possible inheritorfrom a slide master placeholder and an inheritee to placeholders on slideslinked to that layout.
A layout inherits from its master differently than a slide inherits fromits layout. A layout placeholder inherits from the master placeholder sharingthe same type. A slide placeholder inherits from the layout placeholderhaving the same `idx` value.
In general, all formatting properties are inherited from the "parent"placeholder. This includes position and size as well as fill, line, and font.Any directly applied formatting overrides the corresponding inherited value.Directly applied formatting can be removed be reapplying the layout.
Glossary--------
placeholder shape A shape on a slide that inherits from a layout placeholder.
layout placeholder a shorthand name for the placeholder shape on the slide layout from which a particular placeholder on a slide inherits shape properties
master placeholder the placeholder shape on the slide master which a layout placeholder inherits from, if any.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243.. _placeholders-using:
Working with placeholders=========================
Placeholders can make adding content a lot easier. If you've ever added a newtextbox to a slide from scratch and noticed how many adjustments it took toget it the way you wanted you understand why. The placeholder is in the rightposition with the right font size, paragraph alignment, bullet style, etc.,etc. Basically you can just click and type in some text and you've gota slide.
A placeholder can be also be used to place a rich-content object on a slide.A picture, table, or chart can each be inserted into a placeholder and sotake on the position and size of the placeholder, as well as certainof its formatting attributes.
Access a placeholder--------------------
Every placeholder is also a shape, and so can be accessed using the:attr:`~.Slide.shapes` property of a slide. However, when looking fora particular placeholder, the :attr:`~.Slide.placeholders` property can makethings easier.
The most reliable way to access a known placeholder is by its:attr:`~.PlaceholderFormat.idx` value. The :attr:`idx` value of a placeholderis the integer key of the slide layout placeholder it inherits propertiesfrom. As such, it remains stable throughout the life of the slide and will bethe same for any slide created using that layout.
It's usually easy enough to take a look at the placeholders on a slide andpick out the one you want::
>>> prs = Presentation() >>> slide = prs.slides.add_slide(prs.slide_layouts[8]) >>> for shape in slide.placeholders: ... print('%d %s' % (shape.placeholder_format.idx, shape.name)) ... 0 Title 1 1 Picture Placeholder 2 2 Text Placeholder 3
... then, having the known index in hand, to access it directly::
>>> slide.placeholders[1] <pptx.parts.slide.PicturePlaceholder object at 0x10d094590> >>> slide.placeholders[2].name 'Text Placeholder 3'
.. note:: Item access on the placeholders collection is like that of a dictionary rather than a list. While the key used above is an integer, the lookup is on `idx` values, not position in a sequence. If the provided value does not match the `idx` value of one of the placeholders, |KeyError| will be raised. `idx` values are not necessarily contiguous.
In general, the :attr:`idx` value of a placeholder from a built-in slidelayout (one provided with PowerPoint) will be between 0 and 5. The titleplaceholder will always have :attr:`idx` 0 if present and any otherplaceholders will follow in sequence, top to bottom and left to right.A placeholder added to a slide layout by a user in PowerPoint will receive an:attr:`idx` value starting at 10.
Identify and Characterize a placeholder---------------------------------------
A placeholder behaves differently that other shapes in some ways. Inparticular, the value of its :attr:`~.BaseShape.shape_type` attribute isunconditionally ``MSO_SHAPE_TYPE.PLACEHOLDER`` regardless of what type ofplaceholder it is or what type of content it contains::
>>> prs = Presentation() >>> slide = prs.slides.add_slide(prs.slide_layouts[8]) >>> for shape in slide.shapes: ... print('%s' % shape.shape_type) ... PLACEHOLDER (14) PLACEHOLDER (14) PLACEHOLDER (14)
To find out more, it's necessary to inspect the contents of the placeholder's:attr:`~.BaseShape.placeholder_format` attribute. All shapes have thisattribute, but accessing it on a non-placeholder shape raises |ValueError|.The :attr:`~.BaseShape.is_placeholder` attribute can be used to determinewhether a shape is a placeholder::
>>> for shape in slide.shapes: ... if shape.is_placeholder: ... phf = shape.placeholder_format ... print('%d, %s' % (phf.idx, phf.type)) ... 0, TITLE (1) 1, PICTURE (18) 2, BODY (2)
Another way a placeholder acts differently is that it inherits its positionand size from its layout placeholder. This inheritance is overridden if theposition and size of a placeholder are changed.
Insert content into a placeholder---------------------------------
Certain placeholder types have specialized methods for inserting content. Inthe current release, the `picture`, `table`, and `chart` placeholders havecontent insertion methods. Text can be inserted into `title` and `body`placeholders in the same way text is inserted into an auto shape.
:meth:`.PicturePlaceholder.insert_picture`~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The picture placeholder has an :meth:`~.PicturePlaceholder.insert_picture`method::
>>> prs = Presentation() >>> slide = prs.slides.add_slide(prs.slide_layouts[8]) >>> placeholder = slide.placeholders[1] # idx key, not position >>> placeholder.name 'Picture Placeholder 2' >>> placeholder.placeholder_format.type PICTURE (18) >>> picture = placeholder.insert_picture('my-image.png')
.. note:: A reference to a picture placeholder becomes invalid after its :meth:`~.PicturePlaceholder.insert_picture` method is called. This is because the process of inserting a picture replaces the original `p:sp` XML element with a new `p:pic` element containing the picture. Any attempt to use the original placeholder reference after the call will raise |AttributeError|. The new placeholder is the return value of the :meth:`insert_picture` call and may also be obtained from the placeholders collection using the same `idx` key.
A picture inserted in this way is stretched proportionately and cropped tofill the entire placeholder. Best results are achieved when the aspect ratioof the source image and placeholder are the same. If the picture is tallerin aspect than the placeholder, its top and bottom are cropped evenly to fit.If it is wider, its left and right sides are cropped evenly. Cropping can beadjusted using the crop properties on the placeholder, such as:attr:`~.PlaceholderPicture.crop_bottom`.
:meth:`.TablePlaceholder.insert_table`~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The table placeholder has an :meth:`~.TablePlaceholder.insert_table` method.The built-in template has no layout containing a table placeholder, so thisexample assumes a starting presentation named``having-table-placeholder.pptx`` having a table placeholder with idx 10 onits second slide layout::
>>> prs = Presentation('having-table-placeholder.pptx') >>> slide = prs.slides.add_slide(prs.slide_layouts[1]) >>> placeholder = slide.placeholders[10] # idx key, not position >>> placeholder.name 'Table Placeholder 1' >>> placeholder.placeholder_format.type TABLE (12) >>> graphic_frame = placeholder.insert_table(rows=2, cols=2) >>> table = graphic_frame.table >>> len(table.rows), len(table.columns) (2, 2)
A table inserted in this way has the position and width of the originalplaceholder. Its height is proportional to the number of rows.
Like all rich-content insertion methods, a reference to a table placeholderbecomes invalid after its :meth:`~.TablePlaceholder.insert_table` method iscalled. This is because the process of inserting rich content replaces theoriginal `p:sp` XML element with a new element, a `p:graphicFrame` in thiscase, containing the rich-content object. Any attempt to use the originalplaceholder reference after the call will raise |AttributeError|. The newplaceholder is the return value of the :meth:`insert_table` call and may alsobe obtained from the placeholders collection using the original `idx` key, 10in this case.
.. note:: The return value of the :meth:`~.TablePlaceholder.insert_table` method is a |PlaceholderGraphicFrame| object, which has all the properties and methods of a |GraphicFrame| object along with those specific to placeholders. The inserted table is contained in the graphic frame and can be obtained using its :attr:`~.PlaceholderGraphicFrame.table` property.
:meth:`.ChartPlaceholder.insert_chart`~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The chart placeholder has an :meth:`~.ChartPlaceholder.insert_chart` method.The presentation template built into |pp| has no layout containing a chartplaceholder, so this example assumes a starting presentation named``having-chart-placeholder.pptx`` having a chart placeholder with idx 10 onits second slide layout::
>>> from pptx.chart.data import ChartData >>> from pptx.enum.chart import XL_CHART_TYPE
>>> prs = Presentation('having-chart-placeholder.pptx') >>> slide = prs.slides.add_slide(prs.slide_layouts[1])
>>> placeholder = slide.placeholders[10] # idx key, not position >>> placeholder.name 'Chart Placeholder 9' >>> placeholder.placeholder_format.type CHART (12)
>>> chart_data = ChartData() >>> chart_data.categories = ['Yes', 'No'] >>> chart_data.add_series('Series 1', (42, 24))
>>> graphic_frame = placeholder.insert_chart(XL_CHART_TYPE.PIE, chart_data) >>> chart = graphic_frame.chart >>> chart.chart_type PIE (5)
A chart inserted in this way has the position and size of the originalplaceholder.
Note the return value from :meth:`~.ChartPlaceholder.insert_chart` isa |PlaceholderGraphicFrame| object, not the chart itself.A |PlaceholderGraphicFrame| object has all the properties and methods ofa |GraphicFrame| object along with those specific to placeholders. Theinserted chart is contained in the graphic frame and can be obtained usingits :attr:`~.PlaceholderGraphicFrame.chart` property.
Like all rich-content insertion methods, a reference to a chart placeholderbecomes invalid after its :meth:`~.ChartPlaceholder.insert_chart` method iscalled. This is because the process of inserting rich content replaces theoriginal `p:sp` XML element with a new element, a `p:graphicFrame` in thiscase, containing the rich-content object. Any attempt to use the originalplaceholder reference after the call will raise |AttributeError|. The newplaceholder is the return value of the :meth:`insert_chart` call and may alsobe obtained from the placeholders collection using the original `idx` key, 10in this case.
Setting the slide title-----------------------
Almost all slide layouts have a title placeholder, which any slide based onthe layout inherits when the layout is applied. Accessing a slide's title isa common operation and there's a dedicated attribute on the shape tree forit::
title_placeholder = slide.shapes.title title_placeholder.text = 'Air-speed Velocity of Unladen Swallows'123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
Working with Presentations==========================
|pp| allows you to create new presentations as well as make changes toexisting ones. Actually, it only lets you make changes to existingpresentations; it's just that if you start with a presentation that doesn'thave any slides, it feels at first like you're creating one from scratch.
However, a lot of how a presentation looks is determined by the parts that areleft when you delete all the slides, specifically the theme, the slide master,and the slide layouts that derive from the master. Let's walk through it a stepat a time using examples, starting with the two things you can do witha presentation, open it and save it.
Opening a presentation----------------------
The simplest way to get started is to open a new presentation withoutspecifying a file to open::
from pptx import Presentation
prs = Presentation() prs.save('test.pptx')
This creates a new presentation from the built-in default template and saves itunchanged to a file named 'test.pptx'. A couple things to note:
* The so-called "default template" is actually just a PowerPoint file that doesn't have any slides in it, stored with the installed |pp| package. It's the same as what you would get if you created a new presentation from a fresh PowerPoint install, a 4x3 aspect ratio presentation based on the "White" template. Well, except it won't contain any slides. PowerPoint always adds a blank first slide by default.
* You don't need to do anything to it before you save it. If you want to see exactly what that template contains, just look in the 'test.pptx' file this creates.
* We've called it a *template*, but in fact it's just a regular PowerPoint file with all the slides removed. Actual PowerPoint template files (.potx files) are something a bit different. More on those later maybe, but you won't need them to work with |pp|.
REALLY opening a presentation~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Okay, so if you want any control at all to speak of over the finalpresentation, or if you want to change an existing presentation, you need toopen one with a filename::
prs = Presentation('existing-prs-file.pptx') prs.save('new-file-name.pptx')
Things to note:
* You can open any PowerPoint 2007 or later file this way (.ppt files from PowerPoint 2003 and earlier won't work). While you might not be able to manipulate all the contents yet, whatever is already in there will load and save just fine. The feature set is still being built out, so you can't add or change things like Notes Pages yet, but if the presentation has them |pp| is polite enough to leave them alone and smart enough to save them without actually understanding what they are.
* If you use the same filename to open and save the file, |pp| will obediently overwrite the original file without a peep. You'll want to make sure that's what you intend.
Opening a 'file-like' presentation~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|pp| can open a presentation from a so-called *file-like* object. It can alsosave to a file-like object. This can be handy when you want to get the sourceor target presentation over a network connection or from a database and don'twant to (or aren't allowed to) fuss with interacting with the file system. Inpractice this means you can pass an open file or StringIO/BytesIO stream objectto open or save a presentation like so::
f = open('foobar.pptx') prs = Presentation(f) f.close()
# or
with open('foobar.pptx') as f: source_stream = StringIO(f.read()) prs = Presentation(source_stream) source_stream.close() ... target_stream = StringIO() prs.save(target_stream)
Okay, so you've got a presentation open and are pretty sure you can save itsomewhere later. Next step is to get a slide in there ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267.. _examples:
Getting Started===============
A quick way to get started is by trying out some of the examples below to geta feel for how to use |pp|.
The :ref:`API documentation <api>` can help you with the fine details ofcalling signatures and behaviors.
.. highlight:: python
----
Hello World! example--------------------
.. image:: /_static/img/hello-world.png
|
::
from pptx import Presentation
prs = Presentation() title_slide_layout = prs.slide_layouts[0] slide = prs.slides.add_slide(title_slide_layout) title = slide.shapes.title subtitle = slide.placeholders[1]
title.text = "Hello, World!" subtitle.text = "python-pptx was here!"
prs.save('test.pptx')
----
Bullet slide example--------------------
.. image:: /_static/img/bullet-slide.png
|
::
from pptx import Presentation
prs = Presentation() bullet_slide_layout = prs.slide_layouts[1]
slide = prs.slides.add_slide(bullet_slide_layout) shapes = slide.shapes
title_shape = shapes.title body_shape = shapes.placeholders[1]
title_shape.text = 'Adding a Bullet Slide'
tf = body_shape.text_frame tf.text = 'Find the bullet slide layout'
p = tf.add_paragraph() p.text = 'Use _TextFrame.text for first bullet' p.level = 1
p = tf.add_paragraph() p.text = 'Use _TextFrame.add_paragraph() for subsequent bullets' p.level = 2
prs.save('test.pptx')
Not all shapes can contain text, but those that do always have at least oneparagraph, even if that paragraph is empty and no text is visible within theshape. ``_BaseShape.has_text_frame`` can be used to determine whether a shapecan contain text. (All shapes subclass ``_BaseShape``.) When``_BaseShape.has_text_frame`` is ``True``,``_BaseShape.text_frame.paragraphs[0]`` returns the first paragraph. The textof the first paragraph can be set using ``text_frame.paragraphs[0].text``. Asa shortcut, the writable properties ``_BaseShape.text`` and``_TextFrame.text`` are provided to accomplish the same thing. Note thatthese last two calls delete all the shape's paragraphs except the first onebefore setting the text it contains.
----
``add_textbox()`` example-------------------------
.. image:: /_static/img/add-textbox.png
|
::
from pptx import Presentation from pptx.util import Inches, Pt
prs = Presentation() blank_slide_layout = prs.slide_layouts[6] slide = prs.slides.add_slide(blank_slide_layout)
left = top = width = height = Inches(1) txBox = slide.shapes.add_textbox(left, top, width, height) tf = txBox.text_frame
tf.text = "This is text inside a textbox"
p = tf.add_paragraph() p.text = "This is a second paragraph that's bold" p.font.bold = True
p = tf.add_paragraph() p.text = "This is a third paragraph that's big" p.font.size = Pt(40)
prs.save('test.pptx')
----
``add_picture()`` example-------------------------
.. image:: /_static/img/add-picture.png
|
::
from pptx import Presentation from pptx.util import Inches
img_path = 'monty-truth.png'
prs = Presentation() blank_slide_layout = prs.slide_layouts[6] slide = prs.slides.add_slide(blank_slide_layout)
left = top = Inches(1) pic = slide.shapes.add_picture(img_path, left, top)
left = Inches(5) height = Inches(5.5) pic = slide.shapes.add_picture(img_path, left, top, height=height)
prs.save('test.pptx')
----
``add_shape()`` example-------------------------
.. image:: /_static/img/add-shape.png
|
::
from pptx import Presentation from pptx.enum.shapes import MSO_SHAPE from pptx.util import Inches
prs = Presentation() title_only_slide_layout = prs.slide_layouts[5] slide = prs.slides.add_slide(title_only_slide_layout) shapes = slide.shapes
shapes.title.text = 'Adding an AutoShape'
left = Inches(0.93) # 0.93" centers this overall set of shapes top = Inches(3.0) width = Inches(1.75) height = Inches(1.0)
shape = shapes.add_shape(MSO_SHAPE.PENTAGON, left, top, width, height) shape.text = 'Step 1'
left = left + width - Inches(0.4) width = Inches(2.0) # chevrons need more width for visual balance
for n in range(2, 6): shape = shapes.add_shape(MSO_SHAPE.CHEVRON, left, top, width, height) shape.text = 'Step %d' % n left = left + width - Inches(0.4)
prs.save('test.pptx')
Constants representing each of the available auto shapes (likeMSO_SHAPE.ROUNDED_RECT, MSO_SHAPE.CHEVRON, etc.) are listed on the:ref:`autoshape-types <MsoAutoShapeType>` page.
----
``add_table()`` example-----------------------
.. image:: /_static/img/add-table.png
|
::
from pptx import Presentation from pptx.util import Inches
prs = Presentation() title_only_slide_layout = prs.slide_layouts[5] slide = prs.slides.add_slide(title_only_slide_layout) shapes = slide.shapes
shapes.title.text = 'Adding a Table'
rows = cols = 2 left = top = Inches(2.0) width = Inches(6.0) height = Inches(0.8)
table = shapes.add_table(rows, cols, left, top, width, height).table
# set column widths table.columns[0].width = Inches(2.0) table.columns[1].width = Inches(4.0)
# write column headings table.cell(0, 0).text = 'Foo' table.cell(0, 1).text = 'Bar'
# write body cells table.cell(1, 0).text = 'Baz' table.cell(1, 1).text = 'Qux'
prs.save('test.pptx')
----
Extract all text from slides in presentation--------------------------------------------
::
from pptx import Presentation
prs = Presentation(path_to_presentation)
# text_runs will be populated with a list of strings, # one for each text run in presentation text_runs = []
for slide in prs.slides: for shape in slide.shapes: if not shape.has_text_frame: continue for paragraph in shape.text_frame.paragraphs: for run in paragraph.runs: text_runs.append(run.text)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
Working with Slides===================
Every slide in a presentation is based on a slide layout. Not surprising thenthat you have to specify which slide layout to use when you create a new slide.Let's take a minute to understand a few things about slide layouts that we'llneed so the slide we add looks the way we want it to.
Slide layout basics-------------------
A slide layout is like a template for a slide. Whatever is on the slide layout"shows through" on a slide created with it and formatting choices made on theslide layout are inherited by the slide. This is an important feature forgetting a professional-looking presentation deck, where all the slides areformatted consistently. Each slide layout is based on the slide master ina similar way, so you can make presentation-wide formatting decisions on theslide master and layout-specific decisions on the slide layouts. There canactually be multiple slide masters, but I'll pretend for now there's only one.Usually there is.
The presentation themes that come with PowerPoint have about nine slidelayouts, with names like *Title*, *Title and Content*, *Title Only*, and*Blank*. Each has zero or more placeholders (mostly not zero), preformattedareas into which you can place a title, multi-level bullets, an image, etc.More on those later.
The slide layouts in a standard PowerPoint theme always occur in the samesequence. This allows content from one deck to be pasted into another and beconnected with the right new slide layout:
* Title (presentation title slide)* Title and Content* Section Header (sometimes called Segue)* Two Content (side by side bullet textboxes)* Comparison (same but additional title for each side by side content box)* Title Only* Blank* Content with Caption* Picture with Caption
In |pp|, these are ``prs.slide_layouts[0]`` through ``prs.slide_layouts[8]``.However, there's no rule they have to appear in this order, it's justa convention followed by the themes provided with PowerPoint. If the deckyou're using as your template has different slide layouts or has them ina different order, you'll have to work out the slide layout indices foryourself. It's pretty easy. Just open it up in Slide Master view in PowerPointand count down from the top, starting at zero.
Now we can get to creating a new slide.
Adding a slide--------------
Let's use the Title and Content slide layout; a lot of slides do::
SLD_LAYOUT_TITLE_AND_CONTENT = 1
prs = Presentation() slide_layout = prs.slide_layouts[SLD_LAYOUT_TITLE_AND_CONTENT] slide = prs.slides.add_slide(slide_layout)
A few things to note:
* Using a "constant" value like ``SLD_LAYOUT_TITLE_AND_CONTENT`` is up to you. If you're creating many slides it can be handy to have constants defined so a reader can more easily make sense of what you're doing. There isn't a set of these built into the package because they can't be assured to be right for the starting deck you're using.
* ``prs.slide_layouts`` is the collection of slide layouts contained in the presentation and has list semantics, at least for item access which is about all you can do with that collection at the moment. Using ``prs`` for the Presentation instance is purely conventional, but I like it and use it consistently.
* ``prs.slides`` is the collection of slides in the presentation, also has list semantics for item access, and len() works on it. Note that the method to add the slide is on the slide collection, not the presentation. The ``add_slide()`` method appends the new slide to the end of the collection. At the time of writing it's the only way to add a slide, but sooner or later I expect someone will want to insert one in the middle, and when they post a feature request for that I expect I'll add an ``insert_slide(idx, ...)`` method.
Doing other things with slides------------------------------
Right now, adding a slide is the only operation on the slide collection. On thebacklog at the time of writing is deleting a slide and moving a slide toa different position in the list. Copying a slide from one presentation toanother turns out to be pretty hard to get right in the general case, so thatprobably won't come until more of the backlog is burned down.
Up next ...-----------
Ok, now that we have a new slide, let's talk about how to put something onit ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
Working with tables===================
PowerPoint allows text and numbers to be presented in tabular form (alignedrows and columns) in a reasonably flexible way. A PowerPoint table is notnearly as functional as an Excel spreadsheet, and is definitely less powerfulthan a table in Microsoft Word, but it serves well for most presentationpurposes.
Concepts--------
There are a few terms worth reviewing as a basis for understanding PowerPointtables:
table A table is a matrix of cells arranged in aligned rows and columns. This orderly arrangement allows a reader to more easily make sense of relatively large number of individual items. It is commonly used for displaying numbers, but can also be used for blocks of text.
.. image:: /_static/img/table-01.png :scale: 75%
cell An individual content "container" within a table. A cell has a text-frame in which it holds that content. A PowerPoint table cell can only contain text. I cannot hold images, other shapes, or other tables.
A cell has a background fill, borders, margins, and several other formatting settings that can be customized on a cell-by-cell basis.
row A side-by-side sequence of cells running across the table, all sharing the same top and bottom boundary.
column A vertical sequence of cells spanning the height of the table, all sharing the same left and right boundary.
table grid, also cell grid The underlying cells in a PowerPoint table are strictly regular. In a three-by-three table there are nine grid cells, three in each row and three in each column. The presence of merged cells can obscure portions of the cell grid, but not change the number of cells in the grid. Access to a table cell in |pp| is always via that cell's coordinates in the cell grid, which may not conform to its visual location (or lack thereof) in the table.
merged cell A cell can be "merged" with adjacent cells, horizontally, vertically, or both, causing the resulting cell to look and behave like a single cell that spans the area formerly occupied by those individual cells.
.. image:: /_static/img/table-02.png :scale: 75%
merge-origin cell The top-left grid-cell in a merged cell has certain special behaviors. The content of that cell is what appears on the slide; content of any "spanned" cells is hidden. In |pp| a merge-origin cell can be identified with the :attr:`._Cell.is_merge_origin` property. Such a cell can report the size of the merged cell with its :attr:`.span_height` and :attr:`.span_width` properties, and can be "unmerged" back to its underlying grid cells using its :meth:`.split` method.
spanned-cell A grid-cell other than the merge-origin cell that is "occupied" by a merged cell is called a *spanned cell*. Intuitively, the merge-origin cell "spans" the other grid cells within its area. A spanned cell can be identified with its :attr:`._Cell.is_spanned` property. A merge-origin cell is not itself a spanned cell.
Adding a table--------------
The following code adds a 3-by-3 table in a new presentation::
>>> from pptx import Presentation >>> from pptx.util import Inches
>>> # ---create presentation with 1 slide--- >>> prs = Presentation() >>> slide = prs.slides.add_slide(prs.slide_layouts[5])
>>> # ---add table to slide--- >>> x, y, cx, cy = Inches(2), Inches(2), Inches(4), Inches(1.5) >>> shape = slide.shapes.add_table(3, 3, x, y, cx, cy)
>>> shape <pptx.shapes.graphfrm.GraphicFrame object at 0x1022816d0> >>> shape.has_table True >>> table = shape.table >>> table <pptx.table.Table object at 0x1096f8d90>
.. image:: /_static/img/table-03.png :align: center :scale: 60%
A couple things to note:
* :meth:`.SlideShapes.add_table` returns a shape that contains the table, not the table itself. In PowerPoint, a table is contained in a graphic-frame shape, as is a chart or SmartArt. You can determine whether a shape contains a table using its :attr:`~.BaseShape.has_table` property and you access the table object using the shape's :attr:`~.GraphicFrame.table` property.
Inserting a table into a table placeholder------------------------------------------
A placeholder allows you to specify the position and size of a shape as partof the presentation "template", and to place a shape of your choosing intothat placeholder when authoring a presentation based on that template. Thiscan lead to a better looking presentation, with objects appearing ina consistent location from slide-to-slide.
Placeholders come in different types, one of which is a *table placeholder*.A table placeholder behaves like other placeholders except it can only acceptinsertion of a table. Other placeholder types accept text bullets or charts.
There is a subtle distinction between a *layout placeholder* and a *slideplaceholder*. A layout placeholder appears in a slide layout, and defines theposition and size of the placeholder "cloned" from it onto each slide createdwith that layout. As long as you don't adjust the position or size of theslide placeholder, it will inherit it's position and size from the layoutplaceholder it derives from.
To insert a table into a table placeholder, you need a slide layout thatincludes a table placeholder, and you need to create a slide using thatlayout. These examples assume that the third slide layout in `template.pptx`includes a table placeholder::
>>> prs = Presentation('template.pptx') >>> slide = prs.slides.add_slide(prs.slide_layouts[2])
*Accessing the table placeholder.* Generally, the easiest way to accessa placeholder shape is to know its position in the `slide.shapes` collection.If you always use the same template, it will always show up in the sameposition::
>>> table_placeholder = slide.shapes[1]
*Inserting a table.* A table is inserted into the placeholder by calling its:meth:`~.TablePlaceholder.insert_table` method and providing the desirednumber of rows and columns::
>>> shape = table_placeholder.insert_table(rows=3, cols=4)
The return value is a |GraphicFrame| shape containing the new table, not thetable object itself. Use the :attr:`~.GraphicFrame.table` property of thatshape to access the table object::
>>> table = shape.table
The containing shape controls the position and size. Everything else, likeaccessing cells and their contents, is done from the table object.
Accessing a cell----------------
All content in a table is in a cell, so getting a reference to one of thoseis a good place to start::
>>> cell = table.cell(0, 0) >>> cell.text '' >>> cell.text = 'Unladen Swallow'
.. image:: /_static/img/table-04.png :align: center :scale: 60%
The cell is specified by its row, column coordinates as zero-based offsets.The top-left cell is at row, column (0, 0).
Like an auto-shape, a cell has a text-frame and can contain arbitrary textdivided into paragraphs and runs. Any desired character formatting can beapplied individually to each run.
Often however, cell text is just a simple string. For these cases theread/write :attr:`._Cell.text` property can be the quickest way to set cellcontents.
Merging cells-------------
A merged cell is produced by specifying two diagonal cells. The merged cellwill occupy all the grid cells in the rectangular region specified by thatdiagonal:
.. image:: /_static/img/table-05.png :align: center :scale: 60%
::
>>> cell = table.cell(0, 0) >>> other_cell = table.cell(1, 1) >>> cell.is_merge_origin False >>> cell.merge(other_cell) >>> cell.is_merge_origin True >>> cell.is_spanned False >>> other_cell.is_spanned True >>> table.cell(0, 1).is_spanned True
.. image:: /_static/img/table-06.png :align: center :scale: 60%
A few things to observe:
* The merged cell appears as a single cell occupying the space formerly occupied by the other grid cells in the specified rectangular region.
* The formatting of the merged cell (background color, font etc.) is taken from the merge origin cell, the top-left cell of the table in this case.
* Content from the merged cells was migrated to the merge-origin cell. That content is no longer present in the spanned grid cells (although you can't see those at the moment). The content of each cell appears as a separate paragraph in the merged cell; it isn't concatenated into a single paragraph. Content is migrated in left-to-right, top-to-bottom order of the original cells.
* Calling :attr:`other_cell.merge(cell)` would have the exact same effect. The merge origin is always the top-left cell in the specified rectangular region. There are four distinct ways to specify a given rectangular region (two diagonals, each having two orderings).
Un-merging a cell-----------------
A merged cell can be restored to its underlying grid cells by calling the:meth:`~._Cell.split` method on its merge-origin cell. Calling:meth:`~._Cell.split()` on a cell that is not a merge-origin raises|ValueError|::
>>> cell = table.cell(0, 0) >>> cell.is_merge_origin True >>> cell.split() >>> cell.is_merge_origin False >>> table.cell(0, 1).is_spanned False
.. image:: /_static/img/table-07.png :align: center :scale: 60%
Note that the content migration performed as part of the `.merge()` operationwas not reversed.
A few snippets that might be handy----------------------------------
Use Case: Interrogate table for merged cells::
def iter_merge_origins(table): """Generate each merge-origin cell in *table*.
Cell objects are ordered by their position in the table, left-to-right, top-to-bottom. """ return (cell for cell in table.iter_cells() if cell.is_merge_origin)
def merged_cell_report(cell): """Return str summarizing position and size of merged *cell*.""" return ( 'merged cell at row %d, col %d, %d cells high and %d cells wide' % (cell.row_idx, cell.col_idx, cell.span_height, cell.span_width) )
# ---Print a summary line for each merged cell in *table*.--- for merge_origin_cell in iter_merge_origins(table): print(merged_cell_report(merge_origin_cell))
prints a report like::
merged cell at row 0, col 0, 2 cells high and 2 cells wide merged cell at row 3, col 2, 1 cells high and 2 cells wide merged cell at row 4, col 0, 2 cells high and 1 cells wide
Use Case: Access only cells that display text (are not spanned)::
def iter_visible_cells(table): return (cell for cell in table.iter_cells() if not cell.is_spanned)
Use Case: Determine whether table contains merged cells::
def has_merged_cells(table): for cell in table.iter_cells(): if cell.is_merge_origin: return True return False123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
Working with text=================
Auto shapes and table cells can contain text. Other shapes can't. Text isalways manipulated the same way, regardless of its container.
Text exists in a hierarchy of three levels:
* :attr:`.Shape.text_frame`* :attr:`.TextFrame.paragraphs`* :attr:`._Paragraph.runs`
All the text in a shape is contained in its *text frame*. A text frame hasvertical alignment, margins, wrapping and auto-fit behavior, a rotation angle,some possible 3D visual features, and can be set to format its text intomultiple columns. It also contains a sequence of paragraphs, which alwayscontains at least one paragraph, even when empty.
A paragraph has line spacing, space before, space after, available bulletformatting, tabs, outline/indentation level, and horizontal alignment.A paragraph can be empty, but if it contains any text, that text is containedin one or more runs.
A run exists to provide character level formatting, including font typeface,size, and color, an optional hyperlink target URL, bold, italic, and underlinestyles, strikethrough, kerning, and a few capitalization styles like all caps.
Let's run through these one by one. Only features available in the currentrelease are shown.
Accessing the text frame------------------------
As mentioned, not all shapes have a text frame. So if you're not sure and youdon't want to catch the possible exception, you'll want to check beforeattempting to access it::
for shape in slide.shapes: if not shape.has_text_frame: continue text_frame = shape.text_frame # do things with the text frame ...
Accessing paragraphs--------------------
A text frame always contains at least one paragraph. This causes the processof getting multiple paragraphs into a shape to be a little clunkier than onemight like. Say for example you want a shape with three paragraphs::
paragraph_strs = [ 'Egg, bacon, sausage and spam.', 'Spam, bacon, sausage and spam.', 'Spam, egg, spam, spam, bacon and spam.' ]
text_frame = shape.text_frame text_frame.clear() # remove any existing paragraphs, leaving one empty one
p = text_frame.paragraphs[0] p.text = paragraph_strs[0]
for para_str in paragraph_strs[1:]: p = text_frame.add_paragraph() p.text = para_str
Adding text-----------
Only runs can actually contain text. Assigning a string to the ``.text``attribute on a shape, text frame, or paragraph is a shortcut method for placingtext in a run contained by those objects. The following two snippets producethe same result::
shape.text = 'foobar'
# is equivalent to ...
text_frame = shape.text_frame text_frame.clear() p = text_frame.paragraphs[0] run = p.add_run() run.text = 'foobar'
Applying text frame-level formatting------------------------------------
The following produces a shape with a single paragraph, a slightly wider bottomthan top margin (these default to 0.05"), no left margin, text aligned top, andword wrapping turned off. In addition, the auto-size behavior is set toadjust the width and height of the shape to fit its text. Note that verticalalignment is set on the text frame. Horizontal alignment is set on eachparagraph::
from pptx.util import Inches from pptx.enum.text import MSO_ANCHOR, MSO_AUTO_SIZE
text_frame = shape.text_frame text_frame.text = 'Spam, eggs, and spam' text_frame.margin_bottom = Inches(0.08) text_frame.margin_left = 0 text_frame.vertical_anchor = MSO_ANCHOR.TOP text_frame.word_wrap = False text_frame.auto_size = MSO_AUTO_SIZE.SHAPE_TO_FIT_TEXT
The possible values for ``TextFrame.auto_size`` and``TextFrame.vertical_anchor`` are specified by the enumeration:ref:`MsoAutoSize` and :ref:`MsoVerticalAnchor` respectively.
Applying paragraph formatting-----------------------------
The following produces a shape containing three left-aligned paragraphs, thesecond and third indented (like sub-bullets) under the first::
from pptx.enum.text import PP_ALIGN
paragraph_strs = [ 'Egg, bacon, sausage and spam.', 'Spam, bacon, sausage and spam.', 'Spam, egg, spam, spam, bacon and spam.' ]
text_frame = shape.text_frame text_frame.clear()
p = text_frame.paragraphs[0] p.text = paragraph_strs[0] p.alignment = PP_ALIGN.LEFT
for para_str in paragraph_strs[1:]: p = text_frame.add_paragraph() p.text = para_str p.alignment = PP_ALIGN.LEFT p.level = 1
Applying character formatting-----------------------------
Character level formatting is applied at the run level, using the ``.font``attribute. The following formats a sentence in 18pt Calibri Bold and appliesthe theme color Accent 1.
::
from pptx.dml.color import RGBColor from pptx.enum.dml import MSO_THEME_COLOR from pptx.util import Pt
text_frame = shape.text_frame text_frame.clear() # not necessary for newly-created shape
p = text_frame.paragraphs[0] run = p.add_run() run.text = 'Spam, eggs, and spam'
font = run.font font.name = 'Calibri' font.size = Pt(18) font.bold = True font.italic = None # cause value to be inherited from theme font.color.theme_color = MSO_THEME_COLOR.ACCENT_1
If you prefer, you can set the font color to an absolute RGB value. Note thatthis will not change color when the theme is changed::
font.color.rgb = RGBColor(0xFF, 0x7F, 0x50)
A run can also be made into a hyperlink by providing a target URL::
run.hyperlink.address = 'https://github.com/scanny/python-pptx'1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
Understanding Shapes====================
Pretty much anything on a slide is a shape; the only thing I can think of thatcan appear on a slide that's not a shape is a slide background. There arebetween six and ten different types of shape, depending how you count. I'llexplain some of the general shape concepts you'll need to make sense of how towork with them and then we'll jump right into working with the specific types.
Technically there are six and only six different types of shapes that can beplaced on a slide:
auto shape This is a regular shape, like a rectangle, an ellipse, or a block arrow. They come in a large variety of preset shapes, in the neighborhood of 180 different ones. An auto shape can have a fill and an outline, and can contain text. Some auto shapes have adjustments, the little yellow diamonds you can drag to adjust how round the corners of a rounded rectangle are for example. A text box is also an autoshape, a rectangular one, just by default without a fill and without an outline.
picture A raster image, like a photograph or clip art is referred to as a *picture* in PowerPoint. It's its own kind of shape with different behaviors than an autoshape. Note that an auto shape can have a picture fill, in which an image "shows through" as the background of the shape instead of a fill color or gradient. That's a different thing. But cool.
graphic frame This is the technical name for the container that holds a table, a chart, a smart art diagram, or media clip. You can't add one of these by itself, it just shows up in the file when you add a graphical object. You probably won't need to know anything more about these.
group shape In PowerPoint, a set of shapes can be *grouped*, allowing them to be selected, moved, resized, and even filled as a unit. When you group a set of shapes a group shape gets created to contain those member shapes. You can't actually see these except by their bounding box when the group is selected.
line/connector Lines are different from auto shapes because, well, they're linear. Some lines can be connected to other shapes and stay connected when the other shape is moved. These aren't supported yet either so I don't know much more about them. I'd better get to these soon though, they seem like they'd be very handy.
content part I actually have only the vaguest notion of what these are. It has something to do with embedding "foreign" XML like SVG in with the presentation. I'm pretty sure PowerPoint itself doesn't do anything with these. My strategy is to ignore them. Working good so far.
As for real-life shapes, there are these nine types:
* shape shapes -- auto shapes with fill and an outline* text boxes -- auto shapes with no fill and no outline* placeholders -- auto shapes that can appear on a slide layout or master and be inherited on slides that use that layout, allowing content to be added that takes on the formatting of the placeholder* line/connector -- as described above* picture -- as described above* table -- that row and column thing* chart -- pie chart, line chart, etc.* smart art -- not supported yet, although preserved if present* media clip -- video or audio
Accessing the shapes on a slide-------------------------------
Each slide has a *shape tree* that holds its shapes. It's called a tree becauseit's hierarchical in the general case; a node in the shape tree can be a groupshape which itself can contain shapes and has the same semantics as the shapetree. For most purposes the shape tree has list semantics. You gain access toit like so::
shapes = slide.shapes
We'll see a lot more of the shape tree in the next few sections.
Up next ...-----------
Okay. That should be enough noodle work to get started. Let's move on toworking with AutoShapes.12345678910111213141516171819202122Use cases=========
The use case that drove me to begin work on this library has been to automatethe building of slides that are tedious to compose by hand. As an example,consider the task of composing a slide with an array of 10 headshot images offolks in a particular department, with the person's name and title next totheir picture. After doing this a dozen times and struggling to get all thealignment and sizes to the point where my attention to detail is satisfied,well, my coding fingers got quite itchy.
However I believe a broader application will be server-side documentgeneration on non-Windows server platforms, Linux primarily I expect. In myorganization, I have found an apparently insatiable demand for PowerPointdocuments as a means of communication. Once one rises beyond the level ofproject manager it seems the willingness to interpret text longer than abullet point atrophies quite rapidly and PowerPoint becomes an everydaymedium. I've imagined it might be pretty cool to be able to generate a"presentation-ready" deck for a salesperson that includes a particular subsetof the product catalog they could generate with a few clicks to use in a salespresentation, for example. As you come up with applications I'd love to hearabout them.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788Feature: Get and set click action properties In order to determine the click action of a shape or text run As a developer using python-pptx I need a set of properties on ActionSetting
Scenario Outline: Get ActionSetting.action Given a shape having click action <action> Then click_action.action is <value>
Examples: Click actions | action | value | | none | NONE | | first slide | FIRST_SLIDE | | last slide | LAST_SLIDE | | previous slide | PREVIOUS_SLIDE | | next slide | NEXT_SLIDE | | last slide viewed | LAST_SLIDE_VIEWED | | named slide | NAMED_SLIDE | | end show | END_SHOW | | hyperlink | HYPERLINK | | other presentation | PLAY | | open file | OPEN_FILE | | custom slide show | NAMED_SLIDE_SHOW | | OLE action | OLE_VERB | | run macro | RUN_MACRO | | run program | RUN_PROGRAM | | play media | NONE |
Scenario Outline: Get ActionSetting.hyperlink Given a shape having click action <action> Then click_action.hyperlink is a Hyperlink object
Examples: Click actions | action | | none | | first slide | | last slide | | previous slide | | next slide | | last slide viewed | | named slide | | end show | | hyperlink | | other presentation | | open file | | custom slide show | | OLE action | | run macro | | run program |
Scenario Outline: Get ActionSetting.target_slide Given a shape having click action <action> Then click_action.target_slide is <value>
Examples: Click actions | action | value | | none | None | | first slide | slides[0] | | last slide | slides[4] | | previous slide | slides[1] | | next slide | slides[3] | | last slide viewed | None | | named slide | slides[2] | | end show | None | | hyperlink | None | | other presentation | None | | open file | None | | custom slide show | None | | OLE action | None | | run macro | None | | run program | None |
Scenario Outline: Set ActionSetting.target_slide Given an ActionSetting object having action <action> as click_action And another slide in the deck as slide When I assign <rhs> to click_action.target_slide Then click_action.action is <member> And click_action.target_slide is <value>
Examples: Click actions | action | rhs | member | value | | NONE | slide | NAMED_SLIDE | slide | | NAMED_SLIDE | slide | NAMED_SLIDE | slide | | NAMED_SLIDE | None | NONE | None |1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253Feature: Get or set an external hyperlink on a shape or text run In order to connect a presentation to external resources As a developer using python-pptx I need CRUD operations on the Hyperlink object
Scenario Outline: Get hyperlink URL Given a shape having click action <action> Then click_action.hyperlink.address is <value>
Examples: Click actions | action | value | | none | None | | first slide | None | | last slide viewed | None | | named slide | slide3.xml | | hyperlink | http://yahoo.com | | custom slide show | None | | OLE action | None | | run macro | None | | run program | file:////Applications/Calculator.app |
Scenario Outline: Add hyperlink Given a shape having click action <action> When I assign <value> to click_action.hyperlink.address Then click_action.hyperlink.address is <value>
Examples: Click actions | action | value | | none | http://foobar.com | | first slide | http://barfoo.com | | named slide | http://barbaz.org | | hyperlink | http://hooya.com | | run program | http://booya.com |
Scenario Outline: Remove hyperlink Given a shape having click action <action> When I assign None to click_action.hyperlink.address Then click_action.hyperlink.address is None
Examples: Click actions | action | | none | | first slide | | last slide viewed | | named slide | | hyperlink | | custom slide show | | OLE action | | run macro | | run program |123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187Feature: Axis properties In order to customize the formatting of an axis on a chart As a developer using python-pptx I need read/write properties on Axis
Scenario: Get Axis.axis_title Given an axis Then axis.axis_title is an AxisTitle object
Scenario Outline: Get Axis.category_type Given an axis of type <axis-type> Then axis.category_type is XL_CATEGORY_TYPE.<member>
Examples: axis category type cases | axis-type | member | | CategoryAxis | CATEGORY_SCALE | | DateAxis | TIME_SCALE |
Scenario Outline: Get value_axis.crosses Given a value axis having category axis crossing of <crossing> Then value_axis.crosses is <member>
Examples: value_axis.crosses cases | crossing | member | | automatic | AUTOMATIC | | maximum | MAXIMUM | | minimum | MINIMUM | | 2.75 | CUSTOM |
Scenario Outline: Set value_axis.crosses Given a value axis having category axis crossing of <crossing> When I assign <member> to value_axis.crosses Then value_axis.crosses is <member>
Examples: value_axis.crosses assignment cases | crossing | member | | automatic | MAXIMUM | | maximum | MINIMUM | | minimum | CUSTOM | | 2.75 | CUSTOM |
Scenario Outline: Get value_axis.crosses_at Given a value axis having category axis crossing of <crossing> Then value_axis.crosses_at is <value>
Examples: value_axis.crosses_at cases | crossing | value | | automatic | None | | maximum | None | | minimum | None | | 2.75 | 2.75 | | -1.5 | -1.5 |
Scenario Outline: Set value_axis.crosses_at Given a value axis having category axis crossing of <crossing> When I assign <value> to value_axis.crosses_at Then value_axis.crosses_at is <value>
Examples: value_axis.crosses_at assignment cases | crossing | value | | automatic | 2.75 | | 2.75 | -1.5 | | -1.5 | None | | automatic | None |
Scenario Outline: Get Axis.format Given a <axis-type> axis Then axis.format is a ChartFormat object And axis.format.fill is a FillFormat object And axis.format.line is a LineFormat object
Examples: axis types | axis-type | | category | | value |
Scenario Outline: Get Axis.has_[major/minor]_gridlines Given an axis <having-or-not> <major-or-minor> gridlines Then axis.has_<major-or-minor>_gridlines is <expected-value>
Examples: gridlines presence cases | having-or-not | major-or-minor | expected-value | | having | major | True | | not having | major | False | | having | minor | True | | not having | minor | False |
Scenario Outline: Set Axis.has_[major/minor]_gridlines Given an axis <having-or-not> <major-or-minor> gridlines When I assign <value> to axis.has_<major-or-minor>_gridlines Then axis.has_<major-or-minor>_gridlines is <expected-value>
Examples: has_major/minor_gridlines assignment cases | having-or-not | major-or-minor | value | expected-value | | having | major | False | False | | having | major | True | True | | not having | minor | False | False | | not having | minor | True | True |
Scenario Outline: Get Axis.has_title Given an axis having <a-or-no> title Then axis.has_title is <expected-value>
Examples: axis title presence cases | a-or-no | expected-value | | a | True | | no | False |
Scenario Outline: Set Axis.has_title Given an axis having <a-or-no> title When I assign <value> to axis.has_title Then axis.has_title is <expected-value>
Examples: axis title assignment cases | a-or-no | value | expected-value | | a | True | True | | a | False | False | | no | True | True | | no | False | False |
Scenario Outline: Get Axis.major/minor_unit Given an axis having <major-or-minor> unit of <value> Then axis.<major-or-minor>_unit is <expected-value>
Examples: axis unit cases | major-or-minor | value | expected-value | | major | 20.0 | 20.0 | | major | Auto | None | | minor | 4.2 | 4.2 | | minor | Auto | None |
Scenario Outline: Set Axis.major/minor_unit Given an axis having <major-or-minor> unit of <value> When I assign <new-value> to axis.<major-or-minor>_unit Then axis.<major-or-minor>_unit is <expected-value>
Examples: major/minor_unit assignment cases | major-or-minor | value | new-value | expected-value | | major | 20.0 | 5 | 5.0 | | major | 20.0 | None | None | | major | Auto | 5 | 5.0 | | major | Auto | None | None | | minor | 4.2 | 8.4 | 8.4 | | minor | 4.2 | None | None | | minor | Auto | 8.4 | 8.4 | | minor | Auto | None | None |
Scenario: Get Axis.major_gridlines Given an axis Then axis.major_gridlines is a MajorGridlines object
Scenario Outline: Get Axis.reverse_order Given an axis having reverse-order turned <status> Then axis.reverse_order is <expected-value>
Examples: axis unit cases | status | expected-value | | on | True | | off | False |
Scenario Outline: Set Axis.reverse_order Given an axis having reverse-order turned <status> When I assign <value> to axis.reverse_order Then axis.reverse_order is <expected-value>
Examples: major/minor_unit assignment cases | status | value | expected-value | | off | False | False | | off | True | True | | on | False | False | | on | True | True |1234567891011121314151617181920212223242526272829303132333435363738394041424344Feature: Axis Title properties In order to customize the formatting of an axis title As a developer using python-pptx I need read/write properties on AxisTitle
Scenario: AxisTitle.format Given an axis title Then axis_title.format is a ChartFormat object And axis_title.format.fill is a FillFormat object And axis_title.format.line is a LineFormat object
Scenario Outline: Get AxisTitle.has_text_frame Given an axis title having <a-or-no> text frame Then axis_title.has_text_frame is <value>
Examples: text frame presence cases | a-or-no | value | | a | True | | no | False |
Scenario Outline: Set AxisTitle.has_text_frame Given an axis title having <a-or-no> text frame When I assign <new-value> to axis_title.has_text_frame Then axis_title.has_text_frame is <value>
Examples: axis_title.has_text_frame assignment cases | a-or-no | new-value | value | | no | True | True | | a | False | False | | no | False | False | | a | True | True |
Scenario Outline: Get AxisTitle.text_frame Given an axis title having <a-or-no> text frame Then axis_title.text_frame is a TextFrame object
Examples: text frame presence cases | a-or-no | | a | | no |123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172Feature: Access a category In order to operate on an individual category As a developer using python-pptx I need sequence operations on the Categories object
Scenario: Categories.__len__() Given a Categories object containing 3 categories Then len(categories) is 3
Scenario: Categories.__getitem__() Given a Categories object containing 3 categories Then categories[2] is a Category object
Scenario: Categories.__iter__() Given a Categories object containing 3 categories Then iterating categories produces 3 Category objects And list(categories) == ['Foo', '', 'Baz']
Scenario Outline: Categories.depth Given a Categories object having <depth> category levels Then categories.depth is <depth>
Examples: hierarchical category depths | depth | | 0 | | 1 | | 2 | | 3 |
Scenario Outline: Categories.levels Given a Categories object having <depth> category levels Then categories.levels contains <len> CategoryLevel objects
Examples: hierarchical category depths | depth | len | | 0 | 0 | | 1 | 0 | | 2 | 2 | | 3 | 3 |
Scenario Outline: Categories.flattened_labels Given a Categories object having <leafs> categories and <levels> levels Then categories.flattened_labels is a tuple of <leafs> tuples And each label tuple contains <levels> labels
Examples: hierarchical category combinations | leafs | levels | | 3 | 1 | | 8 | 3 | | 0 | 0 | | 4 | 2 |
Scenario: CategoryLevel.__len__() Given a CategoryLevel object containing 4 categories Then len(category_level) is 4
Scenario: CategoryLevel.__getitem__() Given a CategoryLevel object containing 4 categories Then category_level[2] is a Category object
Scenario: CategoryLevel.__iter__() Given a CategoryLevel object containing 4 categories Then iterating category_level produces 4 Category objects123456789101112131415161718192021222324Feature: Category properties In order to characterize a chart category As a developer using python-pptx I need properties on the Category object
Scenario Outline: Category.idx Given a Category object having idx value <idx> Then category.idx is <idx>
Examples: idx cases | idx | | 1 | | 2 |
Scenario Outline: Category.label Given a Category object having <label> Then category.label is <value>
Examples: label cases | label | value | | label 'Foo' | 'Foo' | | no label | '' |123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108Feature: Chart properties In order to customize the formatting of a chart As a developer using python-pptx I need read/write properties and methods on Chart
Scenario Outline: Chart.chart_title Given a chart having <a-or-no> title Then chart.chart_title is a ChartTitle object
Examples: chart title presence cases | a-or-no | | a | | no |
Scenario Outline: Get Chart.chart_type Given a chart of type <chart-type> Then chart.chart_type is <expected-enum-member>
Examples: chart types | chart-type | expected-enum-member | | Area | AREA | | Stacked Area | AREA_STACKED | | 100% Stacked Area | AREA_STACKED_100 | | 3-D Area | THREE_D_AREA | | 3-D Stacked Area | THREE_D_AREA_STACKED | | 3-D 100% Stacked Area | THREE_D_AREA_STACKED_100 | | Clustered Bar | BAR_CLUSTERED | | Stacked Bar | BAR_STACKED | | 100% Stacked Bar | BAR_STACKED_100 | | Clustered Column | COLUMN_CLUSTERED | | Stacked Column | COLUMN_STACKED | | 100% Stacked Column | COLUMN_STACKED_100 | | Line | LINE | | Stacked Line | LINE_STACKED | | 100% Stacked Line | LINE_STACKED_100 | | Marked Line | LINE_MARKERS | | Stacked Marked Line | LINE_MARKERS_STACKED | | 100% Stacked Marked Line | LINE_MARKERS_STACKED_100 | | Pie | PIE | | Exploded Pie | PIE_EXPLODED | | XY (Scatter) | XY_SCATTER | | XY Lines | XY_SCATTER_LINES | | XY Lines No Markers | XY_SCATTER_LINES_NO_MARKERS | | XY Smooth Lines | XY_SCATTER_SMOOTH | | XY Smooth No Markers | XY_SCATTER_SMOOTH_NO_MARKERS | | Bubble | BUBBLE | | 3D-Bubble | BUBBLE_THREE_D_EFFECT | | Radar | RADAR | | Marked Radar | RADAR_MARKERS | | Filled Radar | RADAR_FILLED |
Scenario Outline: Get Chart.category_axis Given a chart of type <chart-type> Then chart.category_axis is a <type-name> object
Examples: category axis object types | chart-type | type-name | | Stacked Bar | CategoryAxis | | Line (with date categories) | DateAxis | | XY (Scatter) | ValueAxis | | Bubble | ValueAxis |
Scenario: Chart.font Given a Chart object as chart Then chart.font is a Font object
Scenario Outline: Get Chart.has_title Given a chart having <a-or-no> title Then chart.has_title is <expected-value>
Examples: chart title presence cases | a-or-no | expected-value | | a | True | | no | False |
Scenario Outline: Set Chart.has_title Given a chart having <a-or-no> title When I assign <value> to chart.has_title Then chart.has_title is <expected-value>
Examples: chart title assignment cases | a-or-no | value | expected-value | | a | True | True | | a | False | False | | no | True | True | | no | False | False |
Scenario Outline: Get Chart.value_axis Given a chart of type <chart-type> Then chart.value_axis is a ValueAxis object
Examples: value axis object types | chart-type | | Stacked Bar | | XY (Scatter) | | Bubble |
Scenario: Chart.series Given a Chart object as chart Then chart.series is a SeriesCollection object1234567891011121314151617181920212223242526272829303132333435363738394041424344Feature: Chart Title properties In order to customize the formatting of a chart title As a developer using python-pptx I need read/write properties on ChartTitle
Scenario: ChartTitle.format Given a chart title Then chart_title.format is a ChartFormat object And chart_title.format.fill is a FillFormat object And chart_title.format.line is a LineFormat object
Scenario Outline: Get ChartTitle.has_text_frame Given a chart title having <a-or-no> text frame Then chart_title.has_text_frame is <value>
Examples: text frame presence cases | a-or-no | value | | a | True | | no | False |
Scenario Outline: Set ChartTitle.has_text_frame Given a chart title having <a-or-no> text frame When I assign <new-value> to chart_title.has_text_frame Then chart_title.has_text_frame is <value>
Examples: chart_title.has_text_frame assignment cases | a-or-no | new-value | value | | no | True | True | | a | False | False | | no | False | False | | a | True | True |
Scenario Outline: Get ChartTitle.text_frame Given a chart title having <a-or-no> text frame Then chart_title.text_frame is a TextFrame object
Examples: text frame presence cases | a-or-no | | a | | no |123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107Feature: chart_data properties In order to compose data for a chart As a developer using python-pptx I need chart data transfer objects
Scenario: CategoryChartData.categories getter Given a CategoryChartData object Then chart_data.categories is a Categories object
Scenario: CategoryChartData.categories setter Given a CategoryChartData object When I assign ['a', 'b', 'c'] to chart_data.categories Then [c.label for c in chart_data.categories] is ['a', 'b', 'c']
Scenario: CategoryChartData.add_category() Given a CategoryChartData object Then chart_data.add_category(name) is a Category object And chart_data.categories[-1] is the category
Scenario: CategoryChartData.add_series() Given a CategoryChartData object Then chart_data.add_series(name, values) is a CategorySeriesData object And chart_data[-1] is the new series
Scenario: Category.add_sub_category() Given a Category object Then category.add_sub_category(name) is a Category object And category.sub_categories[-1] is the new category
Scenario Outline: CategoryChartData number format Given a CategoryChartData object with number format <cht-nf> When I add a series with number format <ser-nf> And I add a data point with number format <dp-nf> Then chart_data.number_format is <cht-val> And series_data.number_format is <ser-val> And data_point.number_format is <dp-val>
Examples: number format inheritance states | cht-nf | ser-nf | dp-nf | cht-val | ser-val | dp-val | | None | None | None | General | General | General | | None | None | 42 | General | General | 42 | | None | 42 | None | General | 42 | 42 | | None | 42 | 24 | General | 42 | 24 | | 42 | None | None | 42 | 42 | 42 | | 42 | None | 24 | 42 | 42 | 24 | | 42 | 24 | None | 42 | 24 | 24 | | 42 | 24 | 12 | 42 | 24 | 12 |
Scenario Outline: XyChartData number format Given a XyChartData object with number format <cht-nf> When I add a series with number format <ser-nf> And I add an XY data point with number format <dp-nf> Then chart_data.number_format is <cht-val> And series_data.number_format is <ser-val> And data_point.number_format is <dp-val>
Examples: number format inheritance states | cht-nf | ser-nf | dp-nf | cht-val | ser-val | dp-val | | None | None | None | General | General | General | | None | None | 42 | General | General | 42 | | None | 42 | None | General | 42 | 42 | | None | 42 | 24 | General | 42 | 24 | | 42 | None | None | 42 | 42 | 42 | | 42 | None | 24 | 42 | 42 | 24 | | 42 | 24 | None | 42 | 24 | 24 | | 42 | 24 | 12 | 42 | 24 | 12 |
Scenario Outline: BubbleChartData number format Given a BubbleChartData object with number format <cht-nf> When I add a series with number format <ser-nf> And I add a bubble data point with number format <dp-nf> Then chart_data.number_format is <cht-val> And series_data.number_format is <ser-val> And data_point.number_format is <dp-val>
Examples: number format inheritance states | cht-nf | ser-nf | dp-nf | cht-val | ser-val | dp-val | | None | None | None | General | General | General | | None | None | 42 | General | General | 42 | | None | 42 | None | General | 42 | 42 | | None | 42 | 24 | General | 42 | 24 | | 42 | None | None | 42 | 42 | 42 | | 42 | None | 24 | 42 | 42 | 24 | | 42 | 24 | None | 42 | 24 | 24 | | 42 | 24 | 12 | 42 | 24 | 12 |
Scenario Outline: Get Categories.number format Given a Categories object with number format <initial-nf> And the categories are of type <cat-type> Then categories.number_format is <value>
Examples: number format inheritance states | initial-nf | cat-type | value | | left as default | str | General | | left as default | int | General | | left as default | date | yyyy\-mm\-dd | | mmm-dd | date | mmm-dd | | 0.0 | float | 0.0 |123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208Feature: Access and modify data labels properties In order to customize the appearance of data labels on a chart As a developer using python-pptx I need access to data label objects and their properties
# ---DataLabels---
Scenario Outline: DataLabel.show_category_name getter Given a DataLabels object <showing-or-not> category-name as data_labels Then data_labels.show_category_name is <value>
Examples: data_label.show_category_name states | showing-or-not | value | | not showing | False | | showing | True |
Scenario Outline: DataLabel.show_category_name setter Given a DataLabels object <showing-or-not> category-name as data_labels When I assign <value> to data_labels.show_category_name Then data_labels.show_category_name is <value>
Examples: data_label.show_category_name states | showing-or-not | value | | not showing | True | | showing | False | | not showing | False | | showing | True |
Scenario Outline: DataLabel.show_legend_key getter Given a DataLabels object <showing-or-not> legend-key as data_labels Then data_labels.show_legend_key is <value>
Examples: data_label.show_legend_key states | showing-or-not | value | | not showing | False | | showing | True |
Scenario Outline: DataLabel.show_legend_key setter Given a DataLabels object <showing-or-not> legend-key as data_labels When I assign <value> to data_labels.show_legend_key Then data_labels.show_legend_key is <value>
Examples: data_label.show_legend_key states | showing-or-not | value | | not showing | True | | showing | False | | not showing | False | | showing | True |
Scenario Outline: DataLabel.show_percentage getter Given a DataLabels object <showing-or-not> percentage as data_labels Then data_labels.show_percentage is <value>
Examples: data_label.show_percentage states | showing-or-not | value | | not showing | False | | showing | True |
Scenario Outline: DataLabel.show_percentage setter Given a DataLabels object <showing-or-not> percentage as data_labels When I assign <value> to data_labels.show_percentage Then data_labels.show_percentage is <value>
Examples: data_label.show_percentage states | showing-or-not | value | | not showing | True | | showing | False | | not showing | False | | showing | True |
Scenario Outline: DataLabel.show_series_name getter Given a DataLabels object <showing-or-not> series-name as data_labels Then data_labels.show_series_name is <value>
Examples: data_label.show_series_name states | showing-or-not | value | | not showing | False | | showing | True |
Scenario Outline: DataLabel.show_series_name setter Given a DataLabels object <showing-or-not> series-name as data_labels When I assign <value> to data_labels.show_series_name Then data_labels.show_series_name is <value>
Examples: data_label.show_series_name states | showing-or-not | value | | not showing | True | | showing | False | | not showing | False | | showing | True |
Scenario Outline: DataLabel.show_value getter Given a DataLabels object <showing-or-not> value as data_labels Then data_labels.show_series_name is <value>
Examples: data_label.show_value states | showing-or-not | value | | not showing | False | | showing | True |
Scenario Outline: DataLabel.show_value setter Given a DataLabels object <showing-or-not> value as data_labels When I assign <value> to data_labels.show_value Then data_labels.show_value is <value>
Examples: data_label.show_value states | showing-or-not | value | | not showing | True | | showing | False | | not showing | False | | showing | True |
Scenario Outline: DataLabels.position getter Given a DataLabels object with <position> position as data_labels Then data_labels.position is <expected-value>
Examples: data_labels position values | position | expected-value | | inherited | None | | inside-base | INSIDE_BASE |
Scenario Outline: DataLabels.position setter Given a DataLabels object with <position> position as data_labels When I assign <new-value> to data_labels.position Then data_labels.position is <expected-value>
Examples: expected results of assignment to data_labels.position | position | new-value | expected-value | | inherited | INSIDE_END | INSIDE_END | | inside-base | OUTSIDE_END | OUTSIDE_END | | inside-base | None | None |
# ---DataLabel---
Scenario Outline: DataLabel.font Given a data label <having-or-not> custom font as data_label Then data_label.font is a Font object
Examples: data_label.font states | having-or-not | | having a | | having no |
Scenario Outline: DataLabel.has_text_frame getter Given a data label <having-or-not> custom text as data_label Then data_label.has_text_frame is <value>
Examples: text frame presence cases | having-or-not | value | | having | True | | having no | False |
Scenario Outline: DataLabel.has_text_frame setter Given a data label <having-or-not> custom text as data_label When I assign <new-value> to data_label.has_text_frame Then data_label.has_text_frame is <value>
Examples: data_label.has_text_frame assignment cases | having-or-not | new-value | value | | having no | True | True | | having | False | False | | having no | False | False | | having | True | True |
Scenario Outline: DataLabel.position getter Given a data label with <position> position as data_label Then data_label.position is <value>
Examples: data_label.position cases | position | value | | inherited | None | | centered | CENTER |
Scenario Outline: DataLabel.position setter Given a data label with <position> position as data_label When I assign <value> to data_label.position Then data_label.position is <value>
Examples: data_label.position assignment cases | position | value | | inherited | CENTER | | centered | BELOW | | below | None |
Scenario Outline: DataLabel.text_frame Given a data label <having-or-not> custom text as data_label Then data_label.text_frame is a TextFrame object
Examples: text frame presence cases | having-or-not | | having | | having no |1234567891011Feature: Gridlines properties To customize the formatting of chart gridlines As a developer using python-pptx I need read/write properties on major and minor gridlines objects
Scenario: Get gridlines.format Given a major gridlines Then gridlines.format is a ChartFormat object And gridlines.format.fill is a FillFormat object And gridlines.format.line is a LineFormat object12345678910111213141516171819202122232425262728293031Feature: Access chart legend In order to customize the legend for a chart As a developer using python-pptx I need a way to access the chart legend
Scenario Outline: Determine presence of legend Given a chart <having-or-not> a legend Then chart.has_legend is <expected-value>
Examples: chart.has_legend states | having-or-not | expected-value | | having | True | | not having | False |
Scenario Outline: Adding a legend Given a chart <having-or-not> a legend When I assign <value> to chart.has_legend Then chart.has_legend is <expected-value>
Examples: chart.has_legend states | having-or-not | value | expected-value | | having | False | False | | not having | True | True | | having | True | True | | not having | False | False |
Scenario: Access legend object of chart Given a chart having a legend Then chart.legend is a legend object12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182Feature: Get and set legend properties In order to customize the appearance of the legend on a chart As a developer using python-pptx I need a way to get and set legend properties
Scenario: Access legend font Given a legend Then legend.font is a Font object
Scenario Outline: Determine legend horizontal offset Given a legend having horizontal offset of <value> Then legend.horz_offset is <expected-value>
Examples: legend horizontal offset values | value | expected-value | | none | 0.0 | | -0.5 | -0.5 | | 0.42 | 0.42 |
Scenario Outline: Change legend horizontal offset Given a legend having horizontal offset of <value> When I assign <new-value> to legend.horz_offset Then legend.horz_offset is <expected-value>
Examples: expected results of changing horz_offset | value | new-value | expected-value | | none | -1.0 | -1.0 | | -0.5 | 0.5 | 0.5 | | 0.42 | -0.5 | -0.5 | | -0.5 | 0 | 0.0 |
Scenario Outline: Determine whether the legend is beside or overlays the chart Given a legend with overlay setting of <setting> Then legend.include_in_layout is <expected-value>
Examples: legend.include_in_layout expected values | setting | expected-value | | no explicit setting | True | | True | True | | False | False |
Scenario Outline: Change whether the legend is beside or overlays the chart Given a legend with overlay setting of <setting> When I assign <value> to legend.include_in_layout Then legend.include_in_layout is <expected-value>
Examples: expected results of changing legend.include_in_layout | setting | value | expected-value | | no explicit setting | True | True | | no explicit setting | False | False | | True | False | False | | True | True | True | | False | True | True | | False | False | False |
Scenario Outline: Determine legend position Given a legend positioned <location> the chart Then legend.position is <expected-value>
Examples: legend position values | location | expected-value | | at an unspecified location of | RIGHT | | below | BOTTOM | | to the right of | RIGHT |
Scenario Outline: Change legend position Given a legend positioned <location> the chart When I assign <new-value> to legend.position Then legend.position is <expected-value>
Examples: expected results of changing legend.position | location | new-value | expected-value | | at an unspecified location of | RIGHT | RIGHT | | below | TOP | TOP | | to the right of | BOTTOM | BOTTOM |1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859Feature: Get and set marker properties In order to customize the visual display of a data point marker As a developer using python-pptx I need a way to get and set marker properties
Scenario: Get Marker.format Given a marker Then marker.format is a ChartFormat object And marker.format.fill is a FillFormat object And marker.format.line is a LineFormat object
Scenario Outline: Get Marker.size Given a marker having size of <size> Then marker.size is <value>
Examples: Marker size value cases | size | value | | no explicit value | None | | 24 points | 24 | | 36 points | 36 |
Scenario Outline: Set Marker.size Given a marker having size of <size> When I assign <value> to marker.size Then marker.size is <value>
Examples: Marker size value cases | size | value | | no explicit value | 24 | | 24 points | 36 | | 36 points | None | | no explicit value | None |
Scenario Outline: Get Marker.style Given a marker having style of <shape> Then marker.style is <value>
Examples: Marker shape value cases | shape | value | | no explicit value | None | | circle | CIRCLE | | triangle | TRIANGLE |
Scenario Outline: Set Marker.style Given a marker having style of <style> When I assign <value> to marker.style Then marker.style is <value>
Examples: Marker style value cases | style | value | | no explicit value | CIRCLE | | circle | TRIANGLE | | triangle | None | | no explicit value | None |123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121Feature: Plot properties To customize the formatting of a plot on a chart As a developer using python-pptx I need read/write properties on plot objects
Scenario Outline: Get bubble_plot.bubble_scale Given a bubble plot having bubble scale of <percent> Then bubble_plot.bubble_scale is <value>
Examples: bubble_plot.bubble_scale values | percent | value | | no explicit value | 100 | | 70% | 70 |
Scenario Outline: Set bubble_plot.bubble_scale Given a bubble plot having bubble scale of <percent> When I assign <new-value> to bubble_plot.bubble_scale Then bubble_plot.bubble_scale is <value>
Examples: bubble_plot.bubble_scale assignment cases | percent | new-value | value | | no explicit value | 70 | 70 | | 70% | 150 | 150 | | 70% | None | 100 | | no explicit value | None | 100 |
Scenario: Get category_plot.categories Given a category plot Then plot.categories is a Categories object
Scenario Outline: Get plot.has_data_labels Given a bar plot <having-or-not> data labels Then plot.has_data_labels is <expected-value>
Examples: having data labels or not | having-or-not | expected-value | | having | True | | not having | False |
Scenario Outline: Set plot.has_data_labels Given a bar plot <having-or-not> data labels When I assign <value> to plot.has_data_labels Then plot.has_data_labels is <expected-value>
Examples: expected results of changing has_data_labels | having-or-not | value | expected-value | | having | False | False | | having | True | True | | not having | False | False | | not having | True | True |
Scenario Outline: Get bar_plot.gap_width Given a bar plot having gap width of <gap-width> Then plot.gap_width is <expected-value>
Examples: bar plot gap widths | gap-width | expected-value | | no explicit value | 150 | | 300 | 300 |
Scenario Outline: Set bar_plot.gap_width Given a bar plot having gap width of <gap-width> When I assign <new-value> to plot.gap_width Then plot.gap_width is <expected-value>
Examples: expected results of changing gap width | gap-width | new-value | expected-value | | no explicit value | 300 | 300 | | 300 | 275 | 275 |
Scenario Outline: Get bar_plot.overlap Given a bar plot having overlap of <overlap> Then plot.overlap is <expected-value>
Examples: expected bar plot overlap values | overlap | expected-value | | no explicit value | 0 | | 42 | 42 | | -42 | -42 |
Scenario Outline: Set bar_plot.overlap Given a bar plot having overlap of <overlap> When I assign <new-value> to plot.overlap Then plot.overlap is <expected-value>
Examples: expected results of changing overlap | overlap | new-value | expected-value | | no explicit value | 42 | 42 | | 42 | -42 | -42 |
Scenario Outline: Get plot.vary_by_categories Given a bar plot having vary color by category set to <setting> Then plot.vary_by_categories is <expected-value>
Examples: expected Plot.vary_by_categories values | setting | expected-value | | no explicit setting | True | | True | True | | False | False |
Scenario Outline: Set plot.vary_by_categories Given a bar plot having vary color by category set to <setting> When I assign <value> to plot.vary_by_categories Then plot.vary_by_categories is <expected-value>
Examples: expected Plot.vary_by_categories values | setting | value | expected-value | | no explicit setting | False | False | | True | False | False | | False | True | True |12345678910111213141516171819202122232425262728293031323334353637Feature: Access a point In order to operate on an individual data point As a developer using python-pptx I need sequence operations on xPoints objects
Scenario Outline: Points.__len__() Given a <type> object containing 3 points Then len(points) is 3
Examples: point container types | type | | XyPoints | | BubblePoints | | CategoryPoints |
Scenario Outline: Points.__getitem__() Given a <type> object containing 3 points Then points[2] is a Point object
Examples: point container types | type | | XyPoints | | BubblePoints | | CategoryPoints |
Scenario Outline: Points.__iter__() Given a <type> object containing 3 points Then iterating points produces 3 Point objects
Examples: point container types | type | | XyPoints | | BubblePoints | | CategoryPoints |123456789101112131415161718192021Feature: Get and set point properties In order to customize the formatting of a data point As a developer using python-pptx I need a way to get and set point properties
Scenario: Get Point.data_label Given a point Then point.data_label is a DataLabel object
Scenario: Get Point.format Given a point Then point.format is a ChartFormat object And point.format.fill is a FillFormat object And point.format.line is a LineFormat object
Scenario: Get Point.marker Given a point Then point.marker is a Marker object12345678910111213141516171819202122232425262728293031323334353637383940Feature: Replace chart data In order to update the data for a chart while retaining its formatting As a developer using python-pptx I need a way to replace the data of a chart
Scenario Outline: Replace category chart data Given a chart of size and type <spec> When I replace its data with <cats> categories and <sers> series Then len(plot.categories) is <cats> And len(chart.series) is <sers> And len(series.values) is <cats> for each series And each series has a new name And the chart has new chart data
Examples: Replacement chart data | spec | cats | sers | | 2x2 Clustered Bar | 3 | 3 | | 2x2 100% Stacked Bar | 3 | 3 | | 2x2 Clustered Column | 3 | 3 | | 4x3 Line | 3 | 2 | | 3x1 Pie | 5 | 1 |
Scenario: Replace XY chart data Given a chart of size and type 3x2 XY When I replace its data with 3 series of 3 points each Then len(chart.series) is 3 And len(series.values) is 3 for each series And each series has a new name And the chart has new chart data
Scenario: Replace Bubble chart data Given a chart of size and type 3x2 Bubble When I replace its data with 3 series of 3 bubble points each Then len(chart.series) is 3 And len(series.values) is 3 for each series And each series has a new name And the chart has new chart data123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144Feature: Chart series In order to customize the formatting of a series on a chart As a developer using python-pptx I need access to series objects and their properties
Scenario Outline: SeriesCollection.__len__() Given a SeriesCollection object for a <container> having <count> series Then len(series_collection) is <count>
Examples: series container types | container | count | | single-plot chart | 3 | | multi-plot chart | 5 | | plot | 3 |
Scenario Outline: SeriesCollection.__getitem__() Given a SeriesCollection object for a <container> having <count> series Then series_collection[2] is a Series object
Examples: series container types | container | count | | single-plot chart | 3 | | multi-plot chart | 5 | | plot | 3 |
Scenario Outline: SeriesCollection.__iter__() Given a SeriesCollection object for a <container> having <count> series Then iterating series_collection produces <count> Series objects
Examples: series container types | container | count | | single-plot chart | 3 | | multi-plot chart | 5 | | plot | 3 |
Scenario Outline: series.data_labels Given a <series-type>Series object as series Then series.data_labels is a DataLabels object
Examples: Series types | series-type | | Area | | Bar | | Doughnut | | Line | | Pie | | Radar |
Scenario Outline: BarSeries.invert_if_negative value Given a BarSeries object having invert_if_negative of <setting> as series Then series.invert_if_negative is <expected-value>
Examples: invert_if_negative settings | setting | expected-value | | no explicit setting | True | | True | True | | False | False |
Scenario Outline: BarSeries.invert_if_negative setter Given a BarSeries object having invert_if_negative of <setting> as series When I assign <new-value> to series.invert_if_negative Then series.invert_if_negative is <expected-value>
Examples: invert_if_negative settings | setting | new-value | expected-value | | no explicit setting | True | True | | no explicit setting | False | False | | True | True | True | | False | False | False |
Scenario: series.format Given a series Then series.format is a ChartFormat object
Scenario Outline: series.format.fill.type Given a BarSeries object having <fill> fill as series Then series.format.fill.type is <expected-fill-type>
Examples: Fill types | fill | expected-fill-type | | Automatic | None | | No Fill | MSO_FILL_TYPE.BACKGROUND | | Accent 1 | MSO_FILL_TYPE.SOLID | | Orange | MSO_FILL_TYPE.SOLID |
Scenario: series.format.fill.fore_color.rgb Given a BarSeries object having Orange fill as series Then series.format.fill.fore_color.rgb is FF6600
Scenario: series.format.fill.fore_color.theme_color Given a BarSeries object having Accent 1 fill as series Then series.format.fill.fore_color.theme_color is Accent 1
Scenario Outline: series.format.line.width Given a BarSeries object having <width> line as series Then series.format.line.width is <expected-width>
Examples: line widths | width | expected-width | | no | 0 | | 1 point | 12700 |
Scenario Outline: series.marker Given a <series-type>Series object as series Then series.marker is a Marker object
Examples: Series types having .marker property | series-type | | Line | | Xy | | Radar |
Scenario Outline: series.points Given a <series-type>Series object as series Then series.points is a <type-name> object
Examples: series points classes | series-type | type-name | | Xy | XyPoints | | Bubble | BubblePoints | | Category | CategoryPoints |
Scenario Outline: series.values Given a BarSeries object having values <values> as series Then series.values is <expected-value>
Examples: series values | values | expected-value | | 1.2, 2.3, 3.4 | (1.2, 2.3, 3.4) | | 4.5, None, 6.7 | (4.5, None, 6.7) |1234567891011121314151617181920212223242526Feature: Get and set tick label properties In order to customize the appearance of the tick labels on a chart As a developer using python-pptx I need a way to get and set tick label properties
Scenario Outline: Access tick label offset for an axis Given tick labels having an offset of <xml-value> Then tick_labels.offset is <expected-value>
Examples: expected values of TickLabels.offset | xml-value | expected-value | | no explicit setting | 100 | | 420 | 420 |
Scenario Outline: Change tick label offset Given tick labels having an offset of <xml-value> When I assign <new-value> to tick_labels.offset Then tick_labels.offset is <new-value>
Examples: expected values of TickLabels.offset | xml-value | new-value | | no explicit setting | 100 | | no explicit setting | 420 | | 420 | 100 |12345678910111213141516171819202122Feature: Control color In order to fine-tune the color of filled areas and lines As a developer using python-pptx I need properties and methods on ColorFormat
Scenario: ColorFormat.rgb Given a ColorFormat object as color When I assign RGBColor(12, 34, 56) to color.rgb Then color.rgb is RGBColor(12, 34, 56)
Scenario: ColorFormat.theme_color Given a ColorFormat object as color When I assign MSO_THEME_COLOR.ACCENT_6 to color.theme_color Then color.theme_color is MSO_THEME_COLOR.ACCENT_6
Scenario: ColorFormat.brightness Given a ColorFormat object as color When I assign 0.42 to color.brightness Then color.brightness is 0.421234567891011121314151617181920212223242526272829Feature: ShadowFormat In order to adjust a shadow effect As a developer using python-pptx I need properties and methods on ShadowFormat
Scenario Outline: ShadowFormat.inherit getter Given a ShadowFormat object that <inherits-or-not> as shadow Then shadow.inherit is <value>
Examples: shadow inheritance cases | inherits-or-not | value | | inherits | True | | does not inherit | False |
Scenario Outline: ShadowFormat.inherit setter Given a ShadowFormat object that <inherits-or-not> as shadow When I assign <new-value> to shadow.inherit Then shadow.inherit is <value>
Examples: shadow inheritance assignment cases | inherits-or-not | new-value | value | | inherits | False | False | | does not inherit | True | True | | inherits | None | False | | inherits | True | True | | does not inherit | None | False | | does not inherit | False | False |123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106Feature: Control fill In order to fine-tune the visual experience of filled areas As a developer using python-pptx I need properties and methods on FillFormat
Scenario Outline: FillFormat type getters Given <type> FillFormat object as fill Then fill.type == <value>
Examples: Fill types | type | value | | an inheriting | None | | a no-fill | MSO_FILL.BACKGROUND | | a solid | MSO_FILL.SOLID | | a picture | MSO_FILL.PICTURE | | a gradient | MSO_FILL.GRADIENT | | a patterned | MSO_FILL.PATTERNED |
Scenario Outline: FillFormat type setters Given a FillFormat object as fill When I call fill.<type-setter>() Then fill.type == <value>
Examples: Fill types | type-setter | value | | background | MSO_FILL.BACKGROUND | | gradient | MSO_FILL.GRADIENT | | solid | MSO_FILL.SOLID | | patterned | MSO_FILL.PATTERNED |
Scenario: FillFormat.back_color Given a FillFormat object as fill When I call fill.patterned() Then fill.back_color is a ColorFormat object
Scenario Outline: FillFormat.fore_color Given a FillFormat object as fill When I call fill.<type-setter>() Then fill.fore_color is a ColorFormat object
Examples: Fill types | type-setter | | patterned | | solid |
Scenario: FillFormat.gradient_angle getter Given a gradient FillFormat object as fill Then fill.gradient_angle == 90.0
Scenario Outline: FillFormat.gradient_angle setter Given a gradient FillFormat object as fill When I assign <new-value> to fill.gradient_angle Then fill.gradient_angle == <value>
Examples: angle value cases | new-value | value | | 42.42 | 42.42 | | 270.0 | 270.0 | | 480.0 | 120.0 | | -90.0 | 270.0 | | -942.4 | 137.6 |
Scenario: FillFormat.gradient_stops Given a gradient FillFormat object as fill Then fill.gradient_stops is a _GradientStops object
Scenario Outline: FillFormat.pattern getter Given a FillFormat object as fill having <pattern> fill Then fill.pattern is <value>
Examples: Pattern fill types | pattern | value | | no pattern | None | | MSO_PATTERN.DIVOT | MSO_PATTERN.DIVOT | | MSO_PATTERN.WAVE | MSO_PATTERN.WAVE |
Scenario: FillFormat.pattern setter Given a FillFormat object as fill When I call fill.patterned() And I assign MSO_PATTERN.CROSS to fill.pattern Then fill.pattern is MSO_PATTERN.CROSS
Scenario: _GradientStop.color Given a _GradientStop object as stop Then stop.color is a ColorFormat object
Scenario: _GradientStop.position getter Given a _GradientStop object as stop Then stop.position == 0.20
Scenario: _GradientStop.position setter Given a _GradientStop object as stop When I assign 0.42 to stop.position Then stop.position == 0.421234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162Feature: Get and change line properties In order to format a shape outline and other line elements As a developer using python-pptx I need a set of read/write line properties on line elements
Scenario: LineFormat.color Given a LineFormat object as line Then line.color is a ColorFormat object
Scenario Outline: LineFormat.dash_style getter Given a LineFormat object as line having <current> dash style Then line.dash_style is <dash-style>
Examples: Line dash styles | current | dash-style | | no explicit | None | | solid | MSO_LINE.SOLID | | dashed | MSO_LINE.DASH | | dash-dot | MSO_LINE.DASH_DOT |
Scenario Outline: LineFormat.width setter Given a LineFormat object as line having <current> dash style When I assign <dash-style> to line.dash_style Then line.dash_style is <dash-style>
Examples: Line dash style assignment scenarios | current | dash-style | | no explicit | MSO_LINE.DASH | | dashed | MSO_LINE.SOLID | | solid | None |
Scenario: LineFormat.fill Given a LineFormat object as line Then line.fill is a FillFormat object
Scenario Outline: LineFormat.width getter Given a LineFormat object as line having <line width> width Then line.width is <reported line width>
Examples: Line widths | line width | reported line width | | no explicit | 0 | | 1 pt | 1 pt |
Scenario Outline: LineFormat.width setter Given a LineFormat object as line having <line width> width When I assign <new line width> to line.width Then line.width is <reported line width>
Examples: Line widths | line width | new line width | reported line width | | no explicit | None | 0 | | no explicit | 1 pt | 1 pt | | 1 pt | None | 0 | | 1 pt | 1 pt | 1 pt | | 1 pt | 2.34 pt | 2.34 pt |.gitattributes+27
tasks/tasksmith-74f059424102/tests/source/docs/dev/resources/about_relationships.rstAdded+206
tasks/tasksmith-74f059424102/tests/source/docs/dev/resources/applescript.rstAdded+46
tasks/tasksmith-74f059424102/tests/source/docs/dev/resources/index.rstAdded+17
tasks/tasksmith-74f059424102/tests/source/docs/dev/resources/odds_and_ends.rstAdded+106
tasks/tasksmith-74f059424102/tests/source/docs/dev/resources/python_packaging.rstAdded+142
tasks/tasksmith-74f059424102/tests/source/docs/dev/resources/technical_topics.rstAdded+22
tasks/tasksmith-74f059424102/tests/source/docs/dev/resources/web_resources.rstAdded+89
tasks/tasksmith-74f059424102/tests/source/docs/dev/runtests.rstAdded+56
tasks/tasksmith-74f059424102/tests/source/docs/dev/xmlchemy.rstAdded+184
tasks/tasksmith-74f059424102/tests/source/docs/index.rstAdded+118
tasks/tasksmith-74f059424102/tests/source/docs/user/autoshapes.rstAdded+247
tasks/tasksmith-74f059424102/tests/source/docs/user/charts.rstAdded+276
tasks/tasksmith-74f059424102/tests/source/docs/user/concepts.rstAdded+92
tasks/tasksmith-74f059424102/tests/source/docs/user/install.rstAdded+25
tasks/tasksmith-74f059424102/tests/source/docs/user/intro.rstAdded+25
tasks/tasksmith-74f059424102/tests/source/docs/user/notes.rstAdded+130
tasks/tasksmith-74f059424102/tests/source/docs/user/placeholders-understanding.rstAdded+128
tasks/tasksmith-74f059424102/tests/source/docs/user/placeholders-using.rstAdded+243
tasks/tasksmith-74f059424102/tests/source/docs/user/presentations.rstAdded+99
tasks/tasksmith-74f059424102/tests/source/docs/user/quickstart.rstAdded+267
tasks/tasksmith-74f059424102/tests/source/docs/user/slides.rstAdded+104
tasks/tasksmith-74f059424102/tests/source/docs/user/table.rstAdded+311
tasks/tasksmith-74f059424102/tests/source/docs/user/text.rstAdded+179
tasks/tasksmith-74f059424102/tests/source/docs/user/understanding-shapes.rstAdded+89
tasks/tasksmith-74f059424102/tests/source/docs/user/use-cases.rstAdded+22
tasks/tasksmith-74f059424102/tests/source/features/act-action.featureAdded+88
tasks/tasksmith-74f059424102/tests/source/features/act-hyperlink.featureAdded+53
tasks/tasksmith-74f059424102/tests/source/features/cht-axis-props.featureAdded+187
tasks/tasksmith-74f059424102/tests/source/features/cht-axistitle-props.featureAdded+44
tasks/tasksmith-74f059424102/tests/source/features/cht-category-access.featureAdded+72
tasks/tasksmith-74f059424102/tests/source/features/cht-category-props.featureAdded+24
tasks/tasksmith-74f059424102/tests/source/features/cht-chart.featureAdded+108
tasks/tasksmith-74f059424102/tests/source/features/cht-charttitle-props.featureAdded+44
tasks/tasksmith-74f059424102/tests/source/features/cht-data-props.featureAdded+107
tasks/tasksmith-74f059424102/tests/source/features/cht-datalabels.featureAdded+208
tasks/tasksmith-74f059424102/tests/source/features/cht-gridlines-props.featureAdded+11
tasks/tasksmith-74f059424102/tests/source/features/cht-legend-access.featureAdded+31
tasks/tasksmith-74f059424102/tests/source/features/cht-legend-props.featureAdded+82
tasks/tasksmith-74f059424102/tests/source/features/cht-marker-props.featureAdded+59
tasks/tasksmith-74f059424102/tests/source/features/cht-plot-props.featureAdded+121
tasks/tasksmith-74f059424102/tests/source/features/cht-point-access.featureAdded+37
tasks/tasksmith-74f059424102/tests/source/features/cht-point-props.featureAdded+21
tasks/tasksmith-74f059424102/tests/source/features/cht-replace-data.featureAdded+40
tasks/tasksmith-74f059424102/tests/source/features/cht-series.featureAdded+144
tasks/tasksmith-74f059424102/tests/source/features/cht-ticklabels-props.featureAdded+26
tasks/tasksmith-74f059424102/tests/source/features/dml-color.featureAdded+22
tasks/tasksmith-74f059424102/tests/source/features/dml-effect.featureAdded+29
tasks/tasksmith-74f059424102/tests/source/features/dml-fill.featureAdded+106
tasks/tasksmith-74f059424102/tests/source/features/dml-line.featureAdded+62