### Install pptxlib using pip Source: https://daizutabi.github.io/pptxlib/getting-started/installation Installs the pptxlib package using the standard 'pip' package manager. This serves as an alternative installation method. Successful installation is the primary outcome. ```shell pip install pptxlib ``` -------------------------------- ### Install pptxlib using uv Source: https://daizutabi.github.io/pptxlib/getting-started/installation Installs the pptxlib package using the 'uv' package manager. This is the recommended method for installation. No specific input or output is detailed beyond successful package installation. ```shell uv pip install pptxlib ``` -------------------------------- ### Initialize pptxlib App Source: https://daizutabi.github.io/pptxlib/getting-started/quickstart Initializes the PowerPoint application using the App class. This is the first step to interact with the library. ```python from pptxlib import App app = App() app ``` -------------------------------- ### Create New Presentation Source: https://daizutabi.github.io/pptxlib/getting-started/quickstart Creates a new presentation using the `add` method on the presentations collection. This returns a Presentation object. ```python pr = app.presentations.add() pr ``` -------------------------------- ### View Slides Collection Source: https://daizutabi.github.io/pptxlib/getting-started/quickstart Displays the collection of slides within a presentation. The output indicates the number of slides. ```python pr.slides ``` -------------------------------- ### Quit pptxlib App Source: https://daizutabi.github.io/pptxlib/getting-started/quickstart Properly quits the PowerPoint application instance, ensuring all resources are released and cleanup is performed. ```python app.quit() ``` -------------------------------- ### Add Title Slide Source: https://daizutabi.github.io/pptxlib/getting-started/quickstart Adds a title slide to the presentation using the 'Title' layout and sets its title text. ```python slide = pr.slides.add(layout="Title") slide.title = "Welcome to pptxlib" ``` -------------------------------- ### Access Presentation by Index Source: https://daizutabi.github.io/pptxlib/getting-started/quickstart Retrieves a specific presentation from the collection by its index. Presentations are zero-indexed. ```python app.presentations[0] ``` -------------------------------- ### Verify pptxlib installation and PowerPoint availability Source: https://daizutabi.github.io/pptxlib/getting-started/installation Verifies that the pptxlib package is installed correctly and checks if Microsoft PowerPoint is accessible on the system. It takes no explicit input but relies on the environment where the code is run. The output is a boolean value indicating PowerPoint's availability. ```python from pptxlib import is_powerpoint_available is_powerpoint_available() ``` -------------------------------- ### Add Content Slide with Layout Source: https://daizutabi.github.io/pptxlib/getting-started/quickstart Adds a content slide to the presentation using the 'TitleOnly' layout and sets its title. ```python slide = pr.slides.add(layout="TitleOnly") slide.title = "First Slide" ``` -------------------------------- ### Select Slide for Display Source: https://daizutabi.github.io/pptxlib/getting-started/quickstart Selects a specific slide for display. This action might highlight the slide or bring it into focus within the application. ```python slide.select() ``` -------------------------------- ### Add Content Slide (Default Layout) Source: https://daizutabi.github.io/pptxlib/getting-started/quickstart Adds a content slide to the presentation. If no layout is specified, it defaults to the previous slide's layout. ```python slide = pr.slides.add() slide.title = "Second Slide" ``` -------------------------------- ### Access Slide Title Source: https://daizutabi.github.io/pptxlib/getting-started/quickstart Retrieves the title text of a specific slide by its index within the presentation's slide collection. ```python pr.slides[0].title ``` -------------------------------- ### Access Presentations Collection Source: https://daizutabi.github.io/pptxlib/getting-started/quickstart Accesses the collection of presentations managed by the App instance. This attribute holds all open or created presentations. ```python app.presentations ``` -------------------------------- ### Quick Start: Create a PowerPoint Presentation with pptxlib Source: https://daizutabi.github.io/pptxlib/index This Python snippet demonstrates the basic usage of pptxlib to create a new presentation, add a slide, and insert a rectangle shape. It requires the pptxlib library to be installed. ```python from pptxlib import App app = App() presentation = app.presentations.add() slide = presentation.slides.add() shape = slide.shapes.add("Rectangle", 100, 100, 200, 100) ``` -------------------------------- ### Clear Slide Selection Source: https://daizutabi.github.io/pptxlib/getting-started/quickstart Deselects any currently selected slide, effectively clearing the current focus or selection within the application. ```python app.unselect() ``` -------------------------------- ### Install pptxlib using pip Source: https://daizutabi.github.io/pptxlib/index This command installs the pptxlib library, which is necessary for automating PowerPoint operations. Ensure you have pip installed and a compatible Python version. ```shell pip install pptxlib ``` -------------------------------- ### Add Rectangle Shape Source: https://daizutabi.github.io/pptxlib/getting-started/quickstart Adds a rectangle shape to the currently selected slide. Requires position (x, y) and dimensions (width, height). ```python shape = slide.shapes.add("Rectangle", 100, 100, 200, 100) shape ``` -------------------------------- ### Layouts Collection Source: https://daizutabi.github.io/pptxlib/api/pptxlib/slide Manages a collection of layouts within a presentation. Supports adding, getting, and copying layouts. ```APIDOC ## Layouts Collection ### Description Manages a collection of available slide layouts within a presentation. Offers functionality to add new layouts, retrieve existing ones, and copy layouts from existing slides. ### Bases - Collection[Layout] ### Methods - **add(name: str) -> Layout** Adds a new layout to the collection with the specified name. - **get(name: str) -> Layout | None** Retrieves a layout from the collection by its name. Returns None if not found. - **get_api(layout: int | str | Layout | None) -> int | DispatchBaseClass** Gets the API object associated with a specific layout. - **copy_from(slide: Slide, name: str) -> Layout** Copies an existing slide's layout and assigns it a new name within the collection. ``` -------------------------------- ### Check PowerPoint Availability (Python) Source: https://daizutabi.github.io/pptxlib/src/pptxlib/app This function, 'is_powerpoint_available', checks if the Microsoft PowerPoint application can be launched on the system. It attempts to create an instance of the 'App' class within a try-except block to catch COM errors, indicating that PowerPoint is not installed or accessible. It returns a boolean value. ```python @cache def is_powerpoint_available() -> bool: """Check if PowerPoint application is available on the system. This function attempts to create a PowerPoint application instance to verify if PowerPoint is installed and accessible. Returns: bool: True if PowerPoint is available, False otherwise. """ try: with App(): pass except com_error: # no cov return False return True ``` -------------------------------- ### Check PowerPoint Availability Source: https://daizutabi.github.io/pptxlib/api/pptxlib Checks if the Microsoft PowerPoint application is installed and available on the system. This function is crucial for ensuring that subsequent operations requiring PowerPoint will succeed. It has no external dependencies beyond the pptxlib installation itself. ```python from pptxlib import is_powerpoint_available if is_powerpoint_available(): print("PowerPoint is available.") else: print("PowerPoint is not available.") ``` -------------------------------- ### Table Dimensions and Cell Access Source: https://daizutabi.github.io/pptxlib/src/pptxlib/table This snippet demonstrates how to get the dimensions of a table (number of rows and columns) and access individual cells using various indexing methods provided by the Table class. ```python from pptxlib.table import Table # Assuming 'table' is a Table object # # Get table dimensions # num_rows, num_cols = table.shape # print(f"Table dimensions: {num_rows} rows, {num_cols} columns") # # Access cell using row and column indices # cell_0_0 = table[0, 0] # # Access cell using a single index (row-major order) # cell_linear = table[5] # Assumes table has at least 6 cells in linear order # # Access an entire row # first_row = table[0] # # Access an entire column # second_column = table[:, 1] # This syntax might vary based on implementation details ``` -------------------------------- ### Row Height Management in Python Source: https://daizutabi.github.io/pptxlib/src/pptxlib/table Allows getting and setting the height of rows in a PowerPoint table. Supports individual row height adjustments and bulk setting of heights for multiple rows. ```Python @property def height(self) -> float: return self.api.Height @height.setter def height(self, value: float) -> None: self.api.Height = value ``` ```Python @property def height(self) -> list[float]: return [row.height for row in self] @height.setter def height(self, value: list[float]) -> None: for row, height in zip(self, value, strict=True): row.height = height ``` -------------------------------- ### Python: Manage Shape Dash Styles Source: https://daizutabi.github.io/pptxlib/src/pptxlib/shape This Python code defines methods to get and set the dash style for shapes. It allows setting the style using integer constants or string representations (e.g., 'Dash'), converting string inputs to appropriate constants from the 'constants' module. It's part of a class that interacts with a PowerPoint API. ```python def dash_style(self) -> int: return self.api.DashStyle @dash_style.setter def dash_style(self, value: int | str) -> None: if isinstance(value, str): value = getattr(constants, f"msoLine{value}") self.api.DashStyle = value def dash(self, dash_style: int | str = "Dash") -> Self: self.dash_style = dash_style return self ``` -------------------------------- ### Initialize and Manage PowerPoint Application Instance (Python) Source: https://daizutabi.github.io/pptxlib/src/pptxlib/app This code defines the 'App' class, which serves as the main interface to the PowerPoint application. It handles the initialization of the COM object, provides access to collections of presentations, and manages the application lifecycle through context management. Dependencies include 'win32com.client', 'pywintypes.com_error', and internal modules like 'base', 'client', and 'presentation'. ```python from __future__ import annotations from dataclasses import dataclass, field from functools import cache from typing import TYPE_CHECKING, Self import win32com.client from pywintypes import com_error from .base import Base from .client import ensure_modules from .presentation import Presentations if TYPE_CHECKING: from win32com.client import DispatchBaseClass @dataclass(repr=False) class App(Base): """PowerPoint application interface. This class provides a high-level interface to interact with Microsoft PowerPoint application. It manages the PowerPoint application instance and provides access to presentations and other PowerPoint features. Attributes: api: The underlying PowerPoint COM object. app: Reference to self for consistency with PowerPoint's object model. """ api: DispatchBaseClass = field(init=False) app: App = field(init=False) def __post_init__(self) -> None: """Initialize the PowerPoint application instance.""" ensure_modules() self.api = win32com.client.Dispatch("PowerPoint.Application") # type: ignore self.app = self @property def presentations(self) -> Presentations: """Get the collection of presentations. Returns: Presentations: A collection of all open presentations. """ return Presentations(self.api.Presentations, self) def quit(self) -> None: """Quit the PowerPoint application.""" self.api.Quit() def __enter__(self) -> Self: """Context manager entry point. Returns: Self: The App instance. """ return self def __exit__(self, exc_type, exc_value, traceback) -> None: # noqa: ANN001 """Context manager exit point. Args: exc_type: The exception type if an exception was raised. exc_value: The exception value if an exception was raised. traceback: The traceback if an exception was raised. """ self.quit() def unselect(self) -> None: """Unselect any selected objects in the active window.""" self.api.ActiveWindow.Selection.Unselect() ``` -------------------------------- ### pptxlib.base Classes and Methods Source: https://daizutabi.github.io/pptxlib/api/pptxlib/base Details on the Base, Element, and Collection classes, including their properties and methods. ```APIDOC ## pptxlib.base Classes ### Base Class * **Description**: The foundational class for other components in the library. * **Methods**: None explicitly defined in this snippet. ### Element Class * **Description**: Represents an element within the presentation structure, inheriting from Base. * **Inherits from**: Base * **Properties**: * `name` (str): The name of the element. * **Methods**: * `select()`: Selects the element. Returns `None`. * `delete()`: Deletes the element. Returns `None`. ### Collection Class * **Description**: Represents a collection of elements, inheriting from Base and Generic[E]. * **Inherits from**: Base, Generic[E] * **Methods**: None explicitly defined in this snippet. ``` -------------------------------- ### Import pptxlib Package Components Source: https://daizutabi.github.io/pptxlib/src/pptxlib Imports core components from the pptxlib package, making them available for use. This includes classes for applications, presentations, shapes, slides, and tables, as well as a utility function to check for PowerPoint availability. ```python from .app import App, is_powerpoint_available from .presentation import Presentation, Presentations from .shape import Shape, Shapes from .slide import Layout, Layouts, Slide, Slides from .table import Table __all__ = [ "App", "Layout", "Layouts", "Presentation", "Presentations", "Shape", "Shapes", "Slide", "Slides", "Table", "is_powerpoint_available", ] ``` -------------------------------- ### Create and Format PowerPoint Table Source: https://daizutabi.github.io/pptxlib/src/pptxlib/gantt This snippet demonstrates the creation and formatting of a table within a PowerPoint slide. It sets column widths, row heights, font sizes, and merges cells, also assigning names to the table and slide. ```python size = index_font_size table.rows[k].text(["", *columns], size=size, bold=True, merge=True) for cell in table.rows[-1]: cell.shape.font.set(size=font_size) table.cell(0, 0).merge(table.cell(1, 0)) table.minimize_height() table.rows[-1].height = height - sum(table.rows.height[:-1]) slide.name = self.frame.name table.name = self.frame.name self.slide = slide self.table = table return self.table ``` -------------------------------- ### Presentation Class Source: https://daizutabi.github.io/pptxlib/src/pptxlib/presentation Represents a single PowerPoint presentation. It allows access to slides, layouts, and modification of presentation dimensions. ```APIDOC ## Class: Presentation ### Description Represents a single PowerPoint presentation. It allows access to slides, layouts, and modification of presentation dimensions. ### Method N/A (Class Definition) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (N/A) N/A #### Response Example N/A ## Methods: ### `close()` #### Description Closes the presentation. #### Method `None` (Python method) ### `delete()` #### Description Deletes the presentation. This is an alias for the `close()` method. #### Method `None` (Python method) ### `slides` (property) #### Description Returns a `Slides` object for managing the slides within the presentation. #### Method `None` (Python property getter) ### `width` (property) #### Description Gets or sets the width of the presentation slide. #### Method `None` (Python property getter/setter) ### `height` (property) #### Description Gets or sets the height of the presentation slide. #### Method `None` (Python property getter/setter) ### `size(width: float, height: float)` #### Description Sets the width and height of the presentation slide. #### Parameters - **width** (float) - Required - The desired width of the slide. - **height** (float) - Required - The desired height of the slide. #### Method `None` (Python method) ### `layouts` (property) #### Description Returns a `Layouts` object for managing the slide layouts within the presentation. #### Method `None` (Python property getter) ``` -------------------------------- ### Presentations Class Source: https://daizutabi.github.io/pptxlib/src/pptxlib/presentation Represents a collection of presentations. It allows adding new presentations and accessing the active presentation. ```APIDOC ## Class: Presentations ### Description Represents a collection of presentations. It allows adding new presentations and accessing the active presentation. ### Method N/A (Class Definition) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (N/A) N/A #### Response Example N/A ## Methods: ### `add()` #### Description Adds a new presentation to the collection. #### Method `None` (Python method) ### `close()` #### Description Closes all presentations within the collection. #### Method `None` (Python method) ### `active` (property) #### Description Returns the currently active presentation. #### Method `None` (Python property getter) ``` -------------------------------- ### Calculate Fiscal Year (Python) Source: https://daizutabi.github.io/pptxlib/src/pptxlib/gantt The `fiscal_year` function determines the fiscal year for a given date. It assumes the fiscal year starts in April, so dates from January to March belong to the previous calendar year's fiscal year. ```python def fiscal_year(date: datetime) -> str:[docs] if 1 <= date.month <= 3: return f"FY{date.year - 1}" return f"FY{date.year}" ``` -------------------------------- ### Manage PowerPoint Application Instance Source: https://daizutabi.github.io/pptxlib/api/pptxlib Provides an interface to the PowerPoint application, allowing for the management of open presentations and application-level operations. It holds a reference to the COM object and provides access to collections of presentations. Key methods include quitting the application and unselecting objects. ```python from pptxlib import App # Initialize the App class to interact with PowerPoint app = App() # Access the collection of presentations presentations = app.presentations # Quit the PowerPoint application # app.quit() ``` -------------------------------- ### Gantt Chart Frame Definition (Python) Source: https://daizutabi.github.io/pptxlib/src/pptxlib/gantt The `GanttFrame` class represents the structure of the Gantt chart's time axis. It uses `GanttKind` enum to specify the time interval and calculates columns for years, months, weeks, or days based on the provided start and end dates. ```python class GanttKind(Enum):[docs] MONTH = "month" WEEK = "week" DAY = "day" class GanttFrame:[docs] kind: GanttKind date_index: list[datetime] columns: list[list[str]] def __init__(self, kind: str, start: datetime, end: datetime) -> None: self.date_index = date_index(kind, start, end) years = [fiscal_year(date) for date in self.date_index] months = [str(date.month) for date in self.date_index] days = [str(date.day) for date in self.date_index] if kind in ["month", "monthly"]: self.columns = [years, months] self.kind = GanttKind.MONTH elif kind in ["week", "weekly"]: weeks = [f"{m}/{d}" for m, d in zip(months, days, strict=True)] self.columns = [years, weeks] self.kind = GanttKind.WEEK elif kind in ["day", "daily"]: self.columns = [months, days] self.kind = GanttKind.DAY else: raise NotImplementedError @property def name(self) -> str:[docs] start = self.date_index[0].strftime("%Y/%m/%d") end = self.date_index[-1].strftime("%Y/%m/%d") return f"{start}-{end}-{self.kind.value}" @property def days(self) -> int:[docs] return (self.date_index[-1] - self.date_index[0]).days ``` -------------------------------- ### Utility Functions Source: https://daizutabi.github.io/pptxlib/api/pptxlib Utility functions for checking PowerPoint availability. ```APIDOC ## GET /websites/daizutabi_github_io_pptxlib/is_powerpoint_available ### Description Checks if the PowerPoint application is available on the system. This function attempts to create a PowerPoint application instance to verify its accessibility. ### Method GET ### Endpoint /websites/daizutabi_github_io_pptxlib/is_powerpoint_available ### Response #### Success Response (200) - **available** (bool) - True if PowerPoint is available, False otherwise. ``` -------------------------------- ### Generate Date Index for Gantt Charts (Python) Source: https://daizutabi.github.io/pptxlib/src/pptxlib/gantt The `date_index` function generates a list of datetime objects representing specific intervals (monthly, weekly, or daily) between a start and end date. It utilizes `dateutil.relativedelta` for accurate date calculations. This function is essential for defining the time axis of a Gantt chart. ```python from __future__ import annotations from datetime import datetime from enum import Enum from functools import cached_property from typing import TYPE_CHECKING from dateutil.relativedelta import relativedelta if TYPE_CHECKING: from pptxlib.shape import Shape from pptxlib.slide import Slide from pptxlib.table import Table [docs] def date_index(kind: str, start: datetime, end: datetime) -> list[datetime]: if kind in ["month", "monthly"]: start = datetime(start.year, start.month, 1) end = datetime(end.year, end.month, 1) delta = relativedelta(end, start) n = 12 * delta.years + delta.months return [start + relativedelta(months=k) for k in range(n + 1)] if kind in ["week", "weekly"]: start -= relativedelta(days=start.weekday()) end -= relativedelta(days=end.weekday()) n = (end - start).days // 7 return [start + relativedelta(days=7 * k) for k in range(n + 1)] if kind in ["day", "daily"]: n = (end - start).days return [start + relativedelta(days=k) for k in range(n + 1)] msg = f"Unsupported kind: {kind}" raise ValueError(msg) ``` -------------------------------- ### Define Base Class for COM Objects in Python Source: https://daizutabi.github.io/pptxlib/src/pptxlib/base The Base class serves as the foundation for all pptxlib objects that interact with COM. It holds a reference to the COM API object, enabling access to PowerPoint's functionality. The __repr__ method provides a simple string representation of the class instance. ```python from pywintypes import com_error from win32com.client import CoClassBaseClass, DispatchBaseClass @dataclass(repr=False) class Base: api: DispatchBaseClass | CoClassBaseClass def __repr__(self) -> str: return f"<{self.__class__.__name__}>" ``` -------------------------------- ### Layouts Collection Source: https://daizutabi.github.io/pptxlib/src/pptxlib/slide Manages a collection of Layout objects. Allows adding new layouts, retrieving layouts by name, and copying layouts from existing slides. ```APIDOC ## Layouts Collection ### Description Manages a collection of Layout objects. Allows adding new layouts, retrieving layouts by name, and copying layouts from existing slides. ### Attributes - **parent** (Presentation): The parent presentation object. - **type** (ClassVar[type[Element]]): Specifies that this collection holds Layout objects. ### Methods - **add(name: str) -> Layout**: Adds a new layout to the presentation with the given name. - **get(name: str) -> Layout | None**: Retrieves a Layout object by its name. Returns None if not found. - **get_api(layout: int | str | Layout | None) -> int | DispatchBaseClass**: Internal helper to get the underlying API object for a layout, supporting various input types. - **copy_from(slide: Slide, name: str) -> Layout**: Copies the layout from a given slide and assigns it a new name. ### Example ```python from pptxlib import Presentation pres = Presentation("my_presentation.pptx") # Add a new custom layout new_layout = pres.layouts.add("My Custom Layout") # Get an existing layout content_layout = pres.layouts.get("Title and Content") # Copy layout from an existing slide if len(pres.slides) > 0: copied_layout = pres.layouts.copy_from(pres.slides[0], "Copied Slide Layout") ``` ``` -------------------------------- ### Python: Get and Set Shape Position and Dimensions Source: https://daizutabi.github.io/pptxlib/src/pptxlib/shape This Python code defines properties and setters for the position (left, top) and dimensions (width, height) of a Shape object. It allows setting position to 'center' or using negative values for relative positioning. The setters ensure values are correctly calculated based on the slide's dimensions, providing flexibility in shape placement. ```python @property def left(self) -> float: return self.api.Left @property def top(self) -> float: return self.api.Top @property def width(self) -> float: return self.api.Width @property def height(self) -> float: return self.api.Height @left.setter def left(self, value: float | Literal["center"]) -> float: slide = self.parent if value == "center": value = (slide.width - self.width) / 2 elif value < 0: value = slide.width - self.width + value self.api.Left = value return value @top.setter def top(self, value: float | Literal["center"]) -> float: slide = self.parent if value == "center": value = (slide.height - self.height) / 2 elif value < 0: value = slide.height - self.height + value self.api.Top = value return value @width.setter def width(self, value: float) -> None: self.api.Width = value @height.setter def height(self, value: float) -> None: self.api.Height = value ``` -------------------------------- ### Slide API Source: https://daizutabi.github.io/pptxlib/api/pptxlib Operations related to individual slides, including exporting, setting titles and layouts, and accessing slide properties. ```APIDOC ## GET /websites/daizutabi_github_io_pptxlib/slide/export ### Description Exports the current slide to a specified file format and name. ### Method GET ### Endpoint /websites/daizutabi_github_io_pptxlib/slide/export ### Parameters #### Query Parameters - **file_name** (str | Path) - Required - The name of the file to save the slide to. - **fmt** (str | None) - Optional - The format to export the slide in (e.g., 'png', 'jpg'). ### Response #### Success Response (200) - None (Operation completes successfully). ``` ```APIDOC ## GET /websites/daizutabi_github_io_pptxlib/slide/png ### Description Returns the current slide as a PNG image in bytes format. ### Method GET ### Endpoint /websites/daizutabi_github_io_pptxlib/slide/png ### Response #### Success Response (200) - **png_data** (bytes) - The PNG image data of the slide. ``` ```APIDOC ## PUT /websites/daizutabi_github_io_pptxlib/slide/set ### Description Sets the title and/or layout of the current slide. ### Method PUT ### Endpoint /websites/daizutabi_github_io_pptxlib/slide/set ### Parameters #### Query Parameters - **title** (str | None) - Optional - The new title for the slide. - **layout** (int | str | Layout | None) - Optional - The new layout for the slide. Can be an integer, string name, or Layout object. ### Response #### Success Response (200) - **self** (Self) - Returns the modified slide object. ``` -------------------------------- ### Define Layouts Class and Methods in Python Source: https://daizutabi.github.io/pptxlib/src/pptxlib/slide Defines the Layouts class for managing a collection of slide layouts. It includes methods for adding new layouts, retrieving layouts by name, and copying layouts from existing slides. Dependencies include Collection, Presentation, Element, Layout, and win32com.client constants. ```python @dataclass(repr=False) class Layouts(Collection[Layout]): parent: Presentation type: ClassVar[type[Element]] = Layout def add(self, name: str) -> Layout: api = self.api.Add(self.api.Count + 1) api.Name = name return Layout(api, self.parent, self) def get(self, name: str) -> Layout | None: for layout in self: if layout.name == name: return layout return None def get_api(self, layout: int | str | Layout | None) -> int | DispatchBaseClass: if isinstance(layout, int): return layout if isinstance(layout, Layout): return layout.api # type: ignore if isinstance(layout, str): if layout_ := self.get(layout): return layout_.api # type: ignore return getattr(constants, f"ppLayout{layout}") return constants.ppLayoutTitleOnly def copy_from(self, slide: Slide, name: str) -> Layout: slide.api.CustomLayout.Copy() api = self.api.Paste() api.Name = name return Layout(api, self.parent, self) ``` -------------------------------- ### Define Layout and Slides Classes in Python Source: https://daizutabi.github.io/pptxlib/src/pptxlib/slide Defines the Layout and Slides classes, both inheriting from Collection, for managing slide layouts and collections of slides respectively. The Layout class represents a specific slide layout, while Slides manages adding, accessing, and identifying the active slide. Dependencies include Element, Presentation, and other internal modules. ```python @dataclass(repr=False) class Layout(Slide): parent: Presentation collection: Layouts @dataclass(repr=False) class Slides(Collection[Slide]): parent: Presentation type: ClassVar[type[Element]] = Slide def add( self, index: int | None = None, layout: int | str | Layout | None = None, ) -> Slide: if index is None: index = len(self) if layout is None and index: layout_ = self[index - 1].api.CustomLayout else: layout_ = self.parent.layouts.get_api(layout) if isinstance(layout_, int): api = self.api.Add(index + 1, layout_) else: api = self.api.AddSlide(index + 1, layout_) return Slide(api, self.parent, self) @property def active(self) -> Slide: index = self.app.api.ActiveWindow.Selection.SlideRange.SlideIndex - 1 return self[index] ``` -------------------------------- ### pptxlib.color.rgb Source: https://daizutabi.github.io/pptxlib/api/pptxlib/color Creates an RGB color integer from various input formats including integers, tuples, color names, and hex strings. ```APIDOC ## rgb ### Description Return the RGB color integer. ### Method PYTHON FUNCTION ### Endpoint N/A (Python function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **color** (int | tuple[int, int, int] | str) - Required - The color or red value. * **green** (int) - Optional - The green value. * **blue** (int) - Optional - The blue value. ### Request Example ```python rgb(4) rgb((100, 200, 40)) rgb("pink") rgb("#123456") ``` ### Response #### Success Response * **return_value** (int) - The RGB color integer. #### Response Example ```python 4 2672740 13353215 5649426 ``` ### Raises * ValueError ``` -------------------------------- ### Layout Class Source: https://daizutabi.github.io/pptxlib/src/pptxlib/slide Represents a slide layout. It inherits from Slide but is specifically used for defining and managing slide master layouts. ```APIDOC ## Layout Class ### Description Represents a slide layout. It inherits from Slide but is specifically used for defining and managing slide master layouts. ### Attributes - **parent** (Presentation): The parent presentation object. - **collection** (Layouts): The collection of layouts this layout belongs to. ### Example ```python from pptxlib import Presentation pres = Presentation("my_presentation.pptx") # Access a specific layout by name title_layout = pres.layouts.get("Title Slide") # You can potentially use layout objects similar to slides, though direct manipulation might be less common. ``` ``` -------------------------------- ### Python: Fill, Line, and Select Shape Properties Source: https://daizutabi.github.io/pptxlib/src/pptxlib/shape Provides access to shape properties like Fill and Line, and allows for selecting shapes within a presentation. These are fundamental for retrieving and manipulating shape characteristics. ```python def fill(self) -> Fill: return Fill(self.api.Fill) @property def line(self) -> Line: return Line(self.api.Line) def select(self, *, replace: bool = True) -> ShapeRange: self.api.Select(replace) api = self.app.api.ActiveWindow.Selection.ShapeRange return ShapeRange(api, self.parent, self.collection) ``` -------------------------------- ### Font Class Set and Update Methods in Python Source: https://daizutabi.github.io/pptxlib/src/pptxlib/font Provides methods for conveniently setting multiple font properties at once ('set') and for updating the current font object with the properties of another Font object ('update'). The 'set' method allows optional parameters for name, size, bold, italic, and color. The 'update' method performs a full property copy from a given Font instance. ```python def set( self, name: str | None = None, size: float | None = None, bold: bool | None = None, italic: bool | None = None, color: int | str | tuple[int, int, int] | None = None, ) -> Self: if name is not None: self.name = name if size is not None: self.size = size if bold is not None: self.bold = bold if italic is not None: self.italic = italic if color is not None: self.color = color return self def update(self, font: Font) -> Self: self.name = font.name self.size = font.size self.bold = font.bold self.italic = font.italic self.color = font.color return self ``` -------------------------------- ### Iterate Office Type Library Specs - Python Source: https://daizutabi.github.io/pptxlib/src/pptxlib/client Iterates through available COM type libraries and yields specifications matching the pattern for Microsoft Office Object Libraries (Excel, PowerPoint). This function is crucial for identifying the correct type libraries to generate Python bindings for. ```python from __future__ import annotations import re from typing import TYPE_CHECKING from win32com.client import gencache, selecttlb # type: ignore if TYPE_CHECKING: from collections.abc import Iterator from win32com.client.selecttlb import TypelibSpec def iter_typelib_specs() -> Iterator[TypelibSpec]: pattern = r"Microsoft (Office|Excel|PowerPoint) \S+? Object Library" for tlb in selecttlb.EnumTlbs(): if re.match(pattern, tlb.desc): yield tlb ``` -------------------------------- ### Ensure All Office Modules - Python Source: https://daizutabi.github.io/pptxlib/src/pptxlib/client Ensures that all relevant Microsoft Office COM modules are generated. This function iterates through all identified type library specifications using iter_typelib_specs() and then calls ensure_module() for each one. ```python from __future__ import annotations import re from typing import TYPE_CHECKING from win32com.client import gencache, selecttlb # type: ignore if TYPE_CHECKING: from collections.abc import Iterator from win32com.client.selecttlb import TypelibSpec def iter_typelib_specs() -> Iterator[TypelibSpec]: pattern = r"Microsoft (Office|Excel|PowerPoint) \S+? Object Library" for tlb in selecttlb.EnumTlbs(): if re.match(pattern, tlb.desc): yield tlb def ensure_module(tlb: TypelibSpec) -> None: major = int(tlb.major, 16) minor = int(tlb.minor, 16) gencache.EnsureModule(tlb.clsid, tlb.lcid, major, minor) # type: ignore def ensure_modules() -> None: for tlb in iter_typelib_specs(): ensure_module(tlb) ``` -------------------------------- ### Slides Collection API Source: https://daizutabi.github.io/pptxlib/api/pptxlib Methods for managing the collection of slides within a presentation, including adding new slides. ```APIDOC ## POST /websites/daizutabi_github_io_pptxlib/slides/add ### Description Adds a new slide to the presentation. You can specify the index and layout for the new slide. ### Method POST ### Endpoint /websites/daizutabi_github_io_pptxlib/slides/add ### Parameters #### Query Parameters - **index** (int | None) - Optional - The index at which to add the new slide. Defaults to the end. - **layout** (int | str | Layout | None) - Optional - The layout for the new slide. ### Response #### Success Response (200) - **slide** (Slide) - The newly added slide object. ``` -------------------------------- ### Slide Class Source: https://daizutabi.github.io/pptxlib/api/pptxlib/slide Represents a single slide within a presentation. Provides methods for exporting, setting properties, and accessing slide content. ```APIDOC ## Slide Class ### Description Represents a single slide within a presentation. Provides methods for exporting, setting properties, and accessing slide content like shapes, title, dimensions, and layout. ### Properties - **shapes** (Shapes) - Accesses the shapes collection of the slide. - **title** (str) - Gets or sets the title of the slide. - **width** (float) - Gets the width of the slide. - **height** (float) - Gets the height of the slide. - **layout** (Layout) - Gets or sets the layout of the slide. ### Methods - **export(file_name: str | Path, fmt: str | None = None) -> None** Exports the slide to a specified file format. - **png() -> bytes** Returns the slide as a PNG image in bytes. - **set(title: str | None = None, layout: int | str | Layout | None = None) -> Self** Sets the title and/or layout of the slide. ``` -------------------------------- ### Layout Class Source: https://daizutabi.github.io/pptxlib/api/pptxlib/slide Represents a slide layout within a presentation. Inherits from Slide. ```APIDOC ## Layout Class ### Description Represents a slide layout within a presentation. This class inherits from the Slide class, implying it shares some functionalities but is specialized for layout definitions. ### Bases - Slide ``` -------------------------------- ### Python: Control Arrowhead Styles, Length, and Width Source: https://daizutabi.github.io/pptxlib/src/pptxlib/shape This Python code provides methods to manage the style, length, and width of both the beginning and ending arrowheads of shapes. It supports setting these properties using integer values or string representations (e.g., 'Stealth'), converting string inputs to corresponding constants. The code includes methods to set all arrowhead properties simultaneously for the beginning and end arrows. ```python @property def begin_arrowhead_style(self) -> int: return self.api.BeginArrowheadStyle @begin_arrowhead_style.setter def begin_arrowhead_style(self, value: int | str) -> None: if isinstance(value, str): value = getattr(constants, f"msoArrowhead{value}") self.api.BeginArrowheadStyle = value @property def end_arrowhead_style(self) -> int: return self.api.EndArrowheadStyle @end_arrowhead_style.setter def end_arrowhead_style(self, value: int | str) -> None: if isinstance(value, str): value = getattr(constants, f"msoArrowhead{value}") self.api.EndArrowheadStyle = value @property def begin_arrowhead_length(self) -> int: return self.api.BeginArrowheadLength @begin_arrowhead_length.setter def begin_arrowhead_length(self, value: int | str) -> None: if isinstance(value, str): value = getattr(constants, f"msoArrowhead{value}") self.api.BeginArrowheadLength = value @property def end_arrowhead_length(self) -> int: return self.api.EndArrowheadLength @end_arrowhead_length.setter def end_arrowhead_length(self, value: int | str) -> None: if isinstance(value, str): value = getattr(constants, f"msoArrowhead{value}") self.api.EndArrowheadLength = value @property def begin_arrowhead_width(self) -> int: return self.api.BeginArrowheadWidth @begin_arrowhead_width.setter def begin_arrowhead_width(self, value: int | str) -> None: if isinstance(value, str): value = getattr(constants, f"msoArrowhead{value}") self.api.BeginArrowheadWidth = value @property def end_arrowhead_width(self) -> int: return self.api.EndArrowheadWidth @end_arrowhead_width.setter def end_arrowhead_width(self, value: int | str) -> None: if isinstance(value, str): value = getattr(constants, f"msoArrowhead{value}") self.api.EndArrowheadWidth = value def begin_arrow(self, style: int | str | None = None, length: int | str | None = None, width: int | str | None = None) -> Self: if style is not None: self.begin_arrowhead_style = style if length is not None: self.begin_arrowhead_length = length if width is not None: self.begin_arrowhead_width = width return self def end_arrow(self, style: int | str | None = None, length: int | str | None = None, width: int | str | None = None) -> Self: if style is not None: self.end_arrowhead_style = style if length is not None: self.end_arrowhead_length = length if width is not None: self.end_arrowhead_width = width return self ``` -------------------------------- ### Table API Source: https://daizutabi.github.io/pptxlib/api/pptxlib Methods for interacting with table shapes, including accessing cells, managing height, and resetting styles. ```APIDOC ## GET /websites/daizutabi_github_io_pptxlib/table/cell ### Description Retrieves a specific cell from a table. ### Method GET ### Endpoint /websites/daizutabi_github_io_pptxlib/table/cell ### Parameters #### Query Parameters - **row** (int) - Required - The row index of the cell. - **column** (int | None) - Optional - The column index of the cell. If None, returns the entire row. ### Response #### Success Response (200) - **cell** (Cell) - The requested cell object. ``` ```APIDOC ## POST /websites/daizutabi_github_io_pptxlib/table/minimize_height ### Description Minimizes the height of the table to fit its content. ### Method POST ### Endpoint /websites/daizutabi_github_io_pptxlib/table/minimize_height ### Response #### Success Response (200) - None (Operation completes successfully). ``` ```APIDOC ## PUT /websites/daizutabi_github_io_pptxlib/table/reset_style ### Description Resets the style of the table, allowing customization of border weight, color, and fill. ### Method PUT ### Endpoint /websites/daizutabi_github_io_pptxlib/table/reset_style ### Parameters #### Query Parameters - **weight** (float) - Optional - The weight of the outer borders. Defaults to 2. - **weight_inside** (float) - Optional - The weight of the inner borders. Defaults to 1. - **color** (int | str | tuple[int, int, int]) - Optional - The color of the outer borders. Defaults to 'black'. - **color_inside** (int | str | tuple[int, int, int]) - Optional - The color of the inner borders. Defaults to 'black'. ### Response #### Success Response (200) - None (Operation completes successfully). ``` -------------------------------- ### Manage Presentations Source: https://daizutabi.github.io/pptxlib/api/pptxlib Represents a PowerPoint presentation and provides methods for its management, such as closing and deleting. It also offers access to its properties like dimensions and collections of slides and layouts. This class is typically accessed via the `App.presentations` collection. ```python from pptxlib import App app = App() presentations = app.presentations # Assuming 'my_presentation' is an existing Presentation object # my_presentation.close() # my_presentation.delete() # Access slides and layouts # slides = my_presentation.slides # layouts = my_presentation.layouts ``` -------------------------------- ### Collection Class for Grouping Elements Source: https://daizutabi.github.io/pptxlib/src/pptxlib/base The Collection class, inheriting from Base and acting as a Generic, manages a group of Element objects. It provides standard Python collection behaviors like length checking (__len__) and item access (__getitem__), mapping COM collection indices to Python indices. It also supports iteration (__iter__) over its contained elements. The 'app' instance is automatically set during initialization. ```python from dataclasses import dataclass, field from typing import TYPE_CHECKING, ClassVar, Generic, TypeVar from win32com.client import CoClassBaseClass, DispatchBaseClass if TYPE_CHECKING: from collections.abc import Iterator # Assume App and Element are defined elsewhere class App: pass class Element: def __init__(self, api, parent, collection): self.api = api self.parent = parent self.collection = collection self.app = parent.app @property def name(self) -> str: return "" E = TypeVar("E", bound=Element) @dataclass(repr=False) class Collection(Base, Generic[E]): parent: Element type: ClassVar[type[Element]] app: App = field(init=False) def __post_init__(self) -> None: self.app = self.parent.app def __repr__(self) -> str: return f"<{self.__class__.__name__} ({len(self)})>" def __len__(self) -> int: # Assuming self.api has a Count attribute for the number of items return self.api.Count def __getitem__(self, index: int) -> E: if index < 0: index = len(self) + index # Assuming self.api is callable with an index to get a specific COM object # and self.type is a class that can wrap this COM object. return self.type(self.api(index + 1), self.parent, self) # type: ignore def __iter__(self) -> Iterator[E]: yield from [self[index] for index in range(len(self))] ```