- Slides¶
- Slide objects¶
- SlideLayouts objects¶
- SlideLayout objects¶
- SlideMasters objects¶
- SlideMaster objects¶
- SlidePlaceholders objects¶
- NotesSlide objects¶
- Getting Started¶
- Hello World! example¶
- Bullet slide example¶
- add_textbox() example¶
- add_picture() example¶
- add_shape() example¶
- add_table() example¶
- Extract all text from slides in presentation¶
- Table of Contents
- Как установить размер слайда с помощью pptx-python?
- 1 ответ
Slides¶
The Slides object is accessed using the slides property of Presentation . It is not intended to be constructed directly.
Sequence of slides belonging to an instance of Presentation , having list semantics for access to individual slides. Supports indexed access, len(), and iteration.
Return a newly added slide that inherits layout from slide_layout.
Return the slide identified by integer slide_id in this presentation, or default if not found.
Map slide to an integer representing its zero-based position in this slide collection. Raises ValueError on slide not present.
Slide objects¶
An individual Slide object is accessed by index from Slides or as the return value of add_slide() .
Slide object. Provides access to shapes and slide-level properties.
_Background object providing slide background properties.
This property returns a _Background object whether or not the slide overrides the default background or inherits it. Determining which of those conditions applies for this slide is accomplished using the follow_master_background property.
The same _Background object is returned on every call for the same slide object.
The lxml element proxied by this object.
True if this slide inherits the slide master background.
Assigning False causes background inheritance from the master to be interrupted; if there is no custom background for this slide, a default background is added. If a custom background already exists for this slide, assigning False has no effect.
Assigning True causes any custom background for this slide to be deleted and inheritance from the master restored.
Return True if this slide has a notes slide, False otherwise. A notes slide is created by notes_slide when one doesn’t exist; use this property to test for a notes slide without the possible side effect of creating one.
String representing the internal name of this slide. Returns an empty string ( ‘’ ) if no name is assigned. Assigning an empty string or None to this property causes any name to be removed.
Return the NotesSlide instance for this slide. If the slide does not have a notes slide, one is created. The same single instance is returned on each call.
Instance of SlidePlaceholders containing sequence of placeholder shapes in this slide.
Instance of SlideShapes containing sequence of shape objects appearing on this slide.
The integer value that uniquely identifies this slide within this presentation. The slide id does not change if the position of this slide in the slide sequence is changed by adding, rearranging, or deleting slides.
SlideLayout object this slide inherits appearance from.
SlideLayouts objects¶
The SlideLayouts object is accessed using the slide_layouts property of SlideMaster , typically:
>>> from pptx import Presentation >>> prs = Presentation() >>> slide_layouts = prs.slide_master.slide_layouts
As a convenience, since most presentations have only a single slide master, the SlideLayouts collection for the first master may be accessed directly from the Presentation object:
>>> slide_layouts = prs.slide_layouts
This class is not intended to be constructed directly.
class pptx.slide. SlideLayouts [source] ¶
Sequence of slide layouts belonging to a slide-master.
Supports indexed access, len(), iteration, index() and remove().
Return SlideLayout object having name or default if not found.
Return zero-based index of slide_layout in this collection.
Raises ValueError if slide_layout is not present in this collection.
The package part containing this object
Remove slide_layout from the collection.
Raises ValueError when slide_layout is in use; a slide layout which is the basis for one or more slides cannot be removed.
SlideLayout objects¶
Slide layout object. Provides access to placeholders, regular shapes, and slide layout-level properties.
Instance of LayoutPlaceholders containing sequence of placeholder shapes in this slide layout, sorted in idx order.
Instance of LayoutShapes containing the sequence of shapes appearing on this slide layout.
Slide master from which this slide layout inherits properties.
Tuple of slide objects based on this slide layout.
SlideMasters objects¶
The SlideMasters object is accessed using the slide_masters property of Presentation , typically:
>>> from pptx import Presentation >>> prs = Presentation() >>> slide_masters = prs.slide_masters
As a convenience, since most presentations have only a single slide master, the first master may be accessed directly from the Presentation object without indexing the collection:
>>> slide_master = prs.slide_master
This class is not intended to be constructed directly.
class pptx.slide. SlideMasters [source] ¶
Sequence of SlideMaster objects belonging to a presentation.
Has list access semantics, supporting indexed access, len(), and iteration.
The package part containing this object
SlideMaster objects¶
Slide master object. Provides access to slide layouts. Access to placeholders, regular shapes, and slide master-level properties is inherited from _BaseMaster .
SlideLayouts object providing access to this slide-master’s layouts.
SlidePlaceholders objects¶
Collection of placeholder shapes on a slide. Supports iteration, len() , and dictionary-style lookup on the idx value of the placeholders it contains.
NotesSlide objects¶
Provides access to slide notes placeholder and other shapes on the notes handout page.
_Background object providing slide background properties.
This property returns a _Background object whether or not the slide, master, or layout has an explicitly defined background.
The same _Background object is returned on every call for the same slide object.
The lxml element proxied by this object.
String representing the internal name of this slide. Returns an empty string ( ‘’ ) if no name is assigned. Assigning an empty string or None to this property causes any name to be removed.
Return the notes placeholder on this notes slide, the shape that contains the actual notes text. Return None if no notes placeholder is present; while this is probably uncommon, it can happen if the notes master does not have a body placeholder, or if the notes placeholder has been deleted from the notes slide.
Return the text frame of the notes placeholder on this notes slide, or None if there is no notes placeholder. This is a shortcut to accommodate the common case of simply adding “notes” text to the notes “page”.
The package part containing this object
An instance of NotesSlidePlaceholders containing the sequence of placeholder shapes in this notes slide.
An instance of NotesSlideShapes containing the sequence of shape objects appearing on this notes slide.
Getting Started¶
A quick way to get started is by trying out some of the examples below to get a feel for how to use python-pptx .
The API documentation can help you with the fine details of calling signatures and behaviors.
Hello World! example¶
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¶
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 one paragraph, even if that paragraph is empty and no text is visible within the shape. _BaseShape.has_text_frame can be used to determine whether a shape can contain text. (All shapes subclass _BaseShape .) When _BaseShape.has_text_frame is True , _BaseShape.text_frame.paragraphs[0] returns the first paragraph. The text of the first paragraph can be set using text_frame.paragraphs[0].text . As a shortcut, the writable properties _BaseShape.text and _TextFrame.text are provided to accomplish the same thing. Note that these last two calls delete all the shape’s paragraphs except the first one before setting the text it contains.
add_textbox() example¶
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¶
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¶
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 (like MSO_SHAPE.ROUNDED_RECT, MSO_SHAPE.CHEVRON, etc.) are listed on the autoshape-types page.
add_table() example¶
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)
Table of Contents
Как установить размер слайда с помощью pptx-python?
Я работаю с pptx-python, и я хочу установить размер слайда по умолчанию в панорамный размер (16: 9). К настоящему времени я могу создавать только слайды размером 4: 3, по умолчанию. Как я могу изменить размер слайда?
Я попытался получить доступ к атрибутам width и height слайда, но объект Slide не имеет ни одного из этих атрибутов.
presentation = Presentation() title_only_slide_layout = presentation.slide_layouts[5] slide = presentation.slides.add_slide(title_only_slide_layout) print(slide.height)
AttributeError: ‘SlideShapes’ object has no attribute ‘height’
1 ответ
В найденной здесь документации python-pptx Documentation говорится, что » Объект «Презентация» имеет атрибут «slide_height», но я не видел документации по объектам «Slide», имеющим атрибут height. Вместо этого кажется, что «Слайд» наследует высоту и ширину от «Презентации».
Попробуйте изменить свое заявление на печать следующим образом.
print(presentation.slide_height)
Спасибо, теперь я могу изменить размер слайда с помощью следующего кода python presentation = Presentation() presentation.slide_height = Inches(9) presentation.slide_width = Inches(16)
Вам также следует подумать о том, чтобы начать с файла шаблона 16×9 по вашему выбору, что позволит избежать других проблем с макетами слайдов и т. д.: prs = Presentation(«my-blank-16×9-deck.pptx») . Вы можете создать один из них из файла PPTX 16×9, удалив все слайды и сохранив его.