ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Python/python-pptx 사용자 가이드 - 9. Placeholder 2
    코딩/Python 2024. 6. 12. 15:05
    728x90

    https://python-pptx.readthedocs.io/en/latest/user/placeholders-using.html

    Working with placeholders

    Placeholders can make adding content a lot easier. If you’ve ever added a new textbox to a slide from scratch and noticed how many adjustments it took to get it the way you wanted you understand why. The placeholder is in the right position with the right font size, paragraph alignment, bullet style, etc., etc. Basically you can just click and type in some text and you’ve got a 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 so take on the position and size of the placeholder, as well as certain of its formatting attributes.

    자리 표시자를 사용하면 콘텐츠를 훨씬 쉽게 추가할 수 있다. 슬라이드에 새 텍스트 상자를 처음부터 추가하고 원하는 대로 만들기 위해 얼마나 많은 조정이 필요한지 알아차렸다면 그 이유를 이해하게 될 것이다. 자리 표시자는 올바른 글꼴 크기, 단락 정렬, 글머리 기호 스타일 등을 갖춘 올바른 위치에 있다. 기본적으로 일부 텍스트를 클릭하고 입력하기만 하면 슬라이드가 생성된다.

    자리 표시자를 사용하여 슬라이드에 풍부한 콘텐츠 개체를 배치할 수도 있다. 그림, 표 또는 차트를 각각 자리 표시자에 삽입할 수 있으므로 자리 표시자의 위치와 크기는 물론 특정 서식 속성도 그대로 적용된다.

    Access a placeholder

    Every placeholder is also a shape, and so can be accessed using the shapes property of a slide. However, when looking for a particular placeholder, the placeholders property can make things easier.

    The most reliable way to access a known placeholder is by its idx value. The idx value of a placeholder is the integer key of the slide layout placeholder it inherits properties from. As such, it remains stable throughout the life of the slide and will be the same for any slide created using that layout.

    It’s usually easy enough to take a look at the placeholders on a slide and pick out the one you want:

    모든 자리 표시자는 도형이므로 슬라이드의 도형 속성을 사용하여 액세스할 수 있다. 그러나 특정 자리 표시자를 찾을 때 placeholders 속성을 사용하면 작업이 더 쉬워질 수 있다.

    알려진 자리 표시자에 액세스하는 가장 안정적인 방법은 해당 idx 값을 사용하는 것이다. 자리 표시자의 idx 값은 속성을 상속하는 슬라이드 레이아웃 자리 표시자의 정수 키이다. 따라서 슬라이드 수명 전체에 걸쳐 안정적으로 유지되며 해당 레이아웃을 사용하여 만든 모든 슬라이드에 대해 동일하다.

    일반적으로 슬라이드의 자리 표시자를 살펴보고 원하는 것을 선택하는 것은 쉽다.

    >>> 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]
    
    >>> 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.

    자리 표시자 컬렉션의 항목 액세스는 리스트가 아닌 딕셔너리의 액세스와 비슷하다. 위에서 사용된 키는 정수이지만 조회는 시퀀스의 위치가 아닌 idx 값에서 이루어진다. 제공된 값이 자리 표시자 중 하나의 idx 값과 일치하지 않으면 KeyError가 발생한다. idx 값은 반드시 연속적일 필요는 없다.

    In general, the idx value of a placeholder from a built-in slide layout (one provided with PowerPoint) will be between 0 and 5. The title placeholder will always have idx 0 if present and any other placeholders 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 idx value starting at 10.

    일반적으로 내장 슬라이드 레이아웃(PowerPoint와 함께 제공되는 레이아웃)의 자리 표시자의 idx 값은 0에서 5 사이이다. 제목 자리 표시자는 있는 경우 항상 idx 0을 가지며 다른 자리 표시자는 위에서부터 아래쪽과 왼쪽에서 오른쪽의 순서대로 따른다. 사용자가 PowerPoint에서 슬라이드 레이아웃에 추가한 자리 표시자는 10부터 시작하는 idx 값을 받는다.

    Identify and Characterize a placeholder

    A placeholder behaves differently that other shapes in some ways. In particular, the value of its shape_type attribute is unconditionally MSO_SHAPE_TYPE.PLACEHOLDER regardless of what type of placeholder it is or what type of content it contains:

    자리 표시자는 어떤 면에서 다른 도형과 다르게 동작한다. 특히, 해당 shape_type 속성의 값은 자리 표시자의 유형이나 포함된 콘텐츠 유형에 관계없이 무조건 MSO_SHAPE_TYPE.PLACEHOLDER이다.

    >>> 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 placeholder_format attribute. All shapes have this attribute, but accessing it on a non-placeholder shape raises ValueError. The is_placeholder attribute can be used to determine whether a shape is a placeholder:

    자세한 내용을 알아보려면 자리 표시자의 placeholder_format 속성 내용을 검사해야 한다. 모든 도형에는 이 속성이 있지만 자리 표시자가 아닌 도형에 액세스하면 ValueError가 발생한다. is_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 position and size from its layout placeholder. This inheritance is overridden if the position and size of a placeholder are changed.

    자리 표시자가 다르게 작동하는 또 다른 방법은 레이아웃 자리 표시자에서 위치와 크기를 상속받는 것이다. 자리 표시자의 위치와 크기가 변경되면 이 상속이 재정의된다.

    Insert content into a placeholder

    Certain placeholder types have specialized methods for inserting content. In the current release, the picture, table, and chart placeholders have content insertion methods. Text can be inserted into title and body placeholders in the same way text is inserted into an auto shape.

    특정 자리 표시자 유형에는 콘텐츠 삽입을 위한 특수한 방법이 있다. 현재 릴리스에서는 그림, 표 및 차트 자리 표시자에 콘텐츠 삽입 방법이 있다. 자동 도형에 텍스트를 삽입하는 것과 같은 방식으로 제목 및 본문 자리 표시자에 텍스트를 삽입할 수 있다.

    PicturePlaceholder.insert_picture()

    The picture placeholder has an insert_picture() method:

    그림 자리 표시자에는 insert_picture() 메서드가 있다:

    >>> 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 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 insert_picture() call and may also be obtained from the placeholders collection using the same idx key.

    insert_picture() 메서드가 호출된 후에는 그림 자리 표시자에 대한 참조가 유효하지 않게 된다. 이는 그림을 삽입하는 과정에서 원본 p:sp XML 요소가 그림이 포함된 새 p:pic 요소로 대체되기 때문이다. 호출 후 원래 자리 표시자 참조를 사용하려고 하면 AttributeError가 발생한다. 새 자리 표시자는 insert_picture() 호출의 반환 값이며 동일한 idx 키를 사용하여 자리 표시자 컬렉션에서 얻을 수도 있다.

    A picture inserted in this way is stretched proportionately and cropped to fill the entire placeholder. Best results are achieved when the aspect ratio of the source image and placeholder are the same. If the picture is taller in 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 be adjusted using the crop properties on the placeholder, such as crop_bottom.

    이런 방식으로 삽입된 그림은 전체 자리 표시자를 채우도록 비례적으로 늘어나고 잘린다. 원본 이미지와 자리 표시자의 가로 세로 비율이 동일할 때 최상의 결과를 얻을 수 있다. 그림의 가로 세로 방향이 개체 틀보다 크면 위쪽과 아래쪽이 균일하게 잘려서 맞춰진다. 폭이 더 넓으면 왼쪽과 오른쪽이 균등하게 잘린다. 자르기는 Crop_bottom과 같은 자리 표시자의 자르기 속성을 사용하여 조정할 수 있다.

    TablePlaceholder.insert_table()

    The table placeholder has an insert_table() method. The built-in template has no layout containing a table placeholder, so this example assumes a starting presentation named having-table-placeholder.pptx having a table placeholder with idx 10 on its second slide layout:

    테이블 자리 표시자에는 insert_table() 메서드가 있다. 기본 제공 템플릿에는 테이블 자리 표시자를 포함하는 레이아웃이 없으므로 이 예에서는 두 번째 슬라이드 레이아웃에 idx 10인 테이블 자리 표시자가 있는 have-table-placeholder.pptx라는 시작 프레젠테이션을 가정한다.

    >>> 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 original placeholder. Its height is proportional to the number of rows.

    Like all rich-content insertion methods, a reference to a table placeholder becomes invalid after its insert_table() method is called. This is because the process of inserting rich content replaces the original p:sp XML element with a new element, a p:graphicFrame in this case, containing the rich-content object. Any attempt to use the original placeholder reference after the call will raise AttributeError. The new placeholder is the return value of the insert_table() call and may also be obtained from the placeholders collection using the original idx key, 10 in this case.

    이런 방식으로 삽입된 표는 원래 자리 표시자의 위치와 너비를 갖는다. 높이는 행 수에 비례한다.

    모든 리치 콘텐츠 삽입 메서드와 마찬가지로 테이블 자리 표시자에 대한 참조는 insert_table() 메서드가 호출된 후에 유효하지 않게 된다. 이는 리치 콘텐츠를 삽입하는 프로세스에서 원본 p:sp XML 요소가 리치 콘텐츠 개체가 포함된 새 요소(이 경우 p:graphicFrame)로 대체되기 때문이다. 호출 후 원래 자리 표시자 참조를 사용하려고 하면 AttributeError가 발생한다. 새 자리 표시자는 insert_table() 호출의 반환 값이며 이 경우 원래 idx 키인 10을 사용하여 자리 표시자 컬렉션에서 얻을 수도 있다.

    Note

    The return value of the 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 table property.

    insert_table() 메서드의 반환 값은 자리 표시자 관련 속성과 함께 GraphicFrame 개체의 모든 속성과 메서드를 포함하는 PlaceholderGraphicFrame 개체이다. 삽입된 테이블은 그래픽 프레임에 포함되며 해당 테이블 속성을 사용하여 얻을 수 있다.

    ChartPlaceholder.insert_chart()

    The chart placeholder has an insert_chart() method. The presentation template built into python-pptx has no layout containing a chart placeholder, so this example assumes a starting presentation named having-chart-placeholder.pptx having a chart placeholder with idx 10 on its second slide layout:

    차트 자리 표시자에는 insert_chart() 메서드가 있다. python-pptx에 내장된 프레젠테이션 템플릿에는 차트 자리 표시자를 포함하는 레이아웃이 없다. 따라서 이 예에서는 두 번째 슬라이드 레이아웃에 idx 10인 차트 자리 표시자가 있는 have-chart-placeholder.pptx라는 시작 프레젠테이션을 가정한다.

    >>> 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 original placeholder.

    Note the return value from insert_chart() is a PlaceholderGraphicFrame object, not the chart itself. A PlaceholderGraphicFrame object has all the properties and methods of a GraphicFrame object along with those specific to placeholders. The inserted chart is contained in the graphic frame and can be obtained using its chart property.

    Like all rich-content insertion methods, a reference to a chart placeholder becomes invalid after its insert_chart() method is called. This is because the process of inserting rich content replaces the original p:sp XML element with a new element, a p:graphicFrame in this case, containing the rich-content object. Any attempt to use the original placeholder reference after the call will raise AttributeError. The new placeholder is the return value of the insert_chart() call and may also be obtained from the placeholders collection using the original idx key, 10 in this case.

    이런 방식으로 삽입된 차트는 원래 자리 표시자의 위치와 크기를 갖는다.

    insert_chart()의 반환 값은 차트 자체가 아니라 PlaceholderGraphicFrame 개체이다. PlaceholderGraphicFrame 개체에는 자리 표시자 관련 속성과 함께 GraphicFrame 개체의 모든 속성과 메서드가 포함되어 있다. 삽입된 차트는 그래픽 프레임에 포함되며 해당 차트 속성을 사용하여 얻을 수 있다.

    모든 리치 콘텐츠 삽입 방법과 마찬가지로 차트 자리 표시자에 대한 참조는 insert_chart() 메서드가 호출된 후에 유효하지 않게 된다. 이는 리치 콘텐츠를 삽입하는 프로세스에서 원본 p:sp XML 요소가 리치 콘텐츠 개체가 포함된 새 요소(이 경우 p:graphicFrame)로 대체되기 때문이다. 호출 후 원래 자리 표시자 참조를 사용하려고 하면 AttributeError가 발생한다. 새 자리 표시자는 insert_chart() 호출의 반환 값이며 이 경우 원래 idx 키인 10을 사용하여 자리 표시자 컬렉션에서 얻을 수도 있다.

    Setting the slide title

    Almost all slide layouts have a title placeholder, which any slide based on the layout inherits when the layout is applied. Accessing a slide’s title is a common operation and there’s a dedicated attribute on the shape tree for it:

    거의 모든 슬라이드 레이아웃에는 레이아웃 적용 시 레이아웃을 기반으로 하는 모든 슬라이드가 상속되는 제목 자리 표시자가 있다. 슬라이드 제목에 액세스하는 것은 일반적인 작업이며 도형 트리에는 이에 대한 전용 속성이 있다.

    title_placeholder = slide.shapes.title
    title_placeholder.text = 'Air-speed Velocity of Unladen Swallows'

     

    Python/python-pptx 사용자 가이드

    728x90

    댓글

Designed by Tistory.