ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Python/python-pptx 사용자 가이드 - 7. AutoShapes
    코딩/Python 2024. 6. 6. 10:11
    728x90

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

    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. 120 of these have adjustment “handles” you can use to change the shape, sometimes dramatically.

    Many shape types share a common set of properties. We’ll introduce many of them here because several of those shapes are just a specialized form of AutoShape.

    AutoShapes는 일반 도형 도형들이다. 사각형, 원, 삼각형, 별, 그런 것. 선택할 수 있는 AutoShapes은 182개이다. 이들 중 120개에는 도형을 때로는 극적으로 변경하는 데 사용할 수 있는 조정 "핸들"이 있다.

    많은 도형 유형은 공통 속성 세트를 공유한다. 이러한 도형 중 일부는 단지 AutoShape의 특수한 형태이기 때문에 여기서는 그 중 많은 것을 소개한다.

    Adding an auto shape

    The following code adds a rounded rectangle shape, one inch square, and positioned one inch from the top-left corner of the slide:

    다음 코드는 둥근 직사각형 도형, 1인치 정사각형을 추가하고 슬라이드의 왼쪽 상단 모서리에서 1인치 위치에 배치한다.

    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 MSO_AUTO_SHAPE_TYPE enumeration page for a list of all 182 auto shape types.

    182개 자동 도형 유형 전체 목록은 MSO_AUTO_SHAPE_TYPE 페이지를 참조한다.

    Understanding English Metric Units

    In the prior example we set the position and dimension values to the expression 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 an integer unit of length, 914400 to the inch. Most lengths in Office documents are stored in EMU. 914400 has the great virtue that it is evenly divisible by a great many common factors, allowing exact conversion between inches and centimeters, for example. Being an integer, it can be represented exactly across serializations and across platforms.

    As you might imagine, working directly in EMU is inconvenient. To make it easier, python-pptx provides a collection of value types to allow easy specification and conversion into convenient units:

    이전 예에서는 위치 및 치수 값을 인치(1.0) 표현식으로 설정했다.

    내부적으로 PowerPoint에서는 EMU(영국식 미터법 단위)로 길이 값을 저장한다. 이 용어는 빠른 인터넷 검색의 가치가 있을 수 있지만 EMU는 인치당 914400의 정수 단위이다. Office 문서의 대부분의 길이는 EMU에 저장된다. 914400은 예를 들어 인치와 센티미터 사이의 정확한 변환이 가능하여 매우 많은 공통 인수로 균등하게 나눌 수 있다는 큰 장점이 있다. 정수이기 때문에 직렬화와 플랫폼 전반에 걸쳐 정확하게 표현될 수 있다.

    상상할 수 있듯이 EMU에서 직접 작업하는 것은 불편하다. 이를 더 쉽게 만들기 위해 python-pptx는 쉽게 지정하고 편리한 단위로 변환할 수 있는 값 유형 컬렉션을 제공한다.

    >>> 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 API documentation for pptx.util

    자세한 내용은 pptx.util에 대한 API 설명서에서 확인할 수 있다.

    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 size can 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 within that outline is called the shape’s fill.

    The most common type of fill is a solid color. A shape may also be filled with a gradient, a picture, a pattern (like cross-hatching for example), or may have no fill (transparent).

    When a color is used, it may be specified as a specific RGB value or a color from the theme palette.

    Because there are so many options, the API for fill is a bit complex. This code sets the fill of a shape to red:

    도형에는 외부 가장자리 주위에 윤곽선이 있다. 해당 윤곽선 내에 나타나는 것을 도형 채우기라고 한다.

    가장 일반적인 채우기 유형은 단색이다. 도형은 그라디언트, 그림, 패턴(예: 사선 도형)으로 채워질 수도 있고 채우기가 없을 수도 있다(투명).

    색상이 사용되는 경우 특정 RGB 값 또는 테마 팔레트의 색상으로 지정할 수 있다.

    옵션이 너무 많아서 채우기 API가 약간 복잡하다. 이 코드는 도형 채우기를 빨간색으로 설정한다.

    >>> 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’ in the toolbar palette:

    이것은 도구 모음 팔레트에 '악센트 1 - 25% 더 어둡게'로 표시되는 테마 색상이 설정된다.

    >>> 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 the PowerPoint UI:

    이것은 도형 채우기가 투명하게 설정되거나 PowerPoint UI에서 호출되는 '채우기 없음'으로 설정된다.

    >>> shape.fill.background()

    As you can see, the first step is to specify the desired fill type by calling the corresponding method on fill. Doing so actually changes the properties available on the fill object. For example, referencing .fore_color on a fill object after calling its .background() method will raise an exception:

    보시다시피 첫 번째 단계는 채우기 시 해당 메서드를 호출하여 원하는 채우기 유형을 지정하는 것이다. 이렇게 하면 채우기 개체에서 사용할 수 있는 속성이 실제로 변경된다. 예를 들어, .Background() 메서드를 호출한 후 채우기 객체에서 .fore_color를 참조하면 예외가 발생한다.

    >>> fill = shape.fill
    >>> fill.solid()
    >>> fill.fore_color
    
    >>> 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 its color, 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:

    색상, 너비, 대시(실선, 점선, 점선 등), 선 스타일(단일, 이중, 굵은-가늘게 등), 끝 모양, 결합 유형, 그리고 다른 것들을 포함하여 도형의 윤곽선 서식을 지정할 수도 있다. 작성 시 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 shortcut for:

    Shape.line에는 .color 속성이 있다. 이는 기본적으로 다음 항목에 대한 바로가기이다.

    >>> line.fill.solid()
    >>> line.fill.fore_color

    This makes sense for line formatting because a shape outline is most frequently set to a solid color. Accessing the fill directly is required, for example, 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 little yellow diamonds you can drag to change the look of the shape. They’re a little fiddly to work with via a program, but if you have the patience to get them right, you can achieve some remarkable effects with great precision.

    많은 자동 도형에는 조정이 있다. PowerPoint에서는 이러한 도형이 드래그하여 도형의 모양을 변경할 수 있는 작은 노란색 다이아몬드로 표시된다. 프로그램을 통해 작업하기에는 약간 까다롭지만 인내심을 갖고 올바르게 작업하면 매우 정밀하게 놀라운 효과를 얻을 수 있다.

    Shape Adjustment Concepts

    There are a few concepts it’s worthwhile to grasp before trying to do serious work with adjustments.

    First, adjustments are particular to a specific auto shape type. Each auto shape has between zero and eight adjustments. What each of them does is arbitrary and depends on the shape design.

    Conceptually, adjustments are guides, in many ways like the light blue ones you can align to in the PowerPoint UI and other drawing apps. These don’t show, but they operate in a similar way, each defining an x or y value that part of the shape 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 of the shape. So a value of 50,000 for an x-coordinate adjustment corresponds to half the width of the shape; a value of 75,000 for a y-coordinate adjustment corresponds to 3/4 of the shape height.

    Adjustment values can be negative, generally indicating the coordinate is to the left or above the top left corner (origin) of the shape. Values can also be subject to limits, meaning their effective value cannot be outside a prescribed range. In practice this corresponds to a point not being able to extend beyond the left side of the shape, for example.

    Spending some time fooling around with shape adjustments in PowerPoint is time well spent to build an intuitive sense of how they behave. You also might want to have opc-diag installed so you can look at the XML values that are generated by different adjustments as a head start on developing your adjustment code.

    The following code formats a callout shape using its adjustments:

    조정 작업을 본격적으로 수행하기 전에 먼저 알아두어야 할 몇 가지 개념이 있다.

    첫째, 조정은 특정 자동 도형 유형에 따라 다르다. 각 자동 도형에는 0~8개의 조정 사항이 있다. 각각의 기능은 임의적이며 도형 디자인에 따라 다르다.

    개념적으로 조정은 PowerPoint UI 및 기타 그리기 앱에서 정렬할 수 있는 연한 파란색 조정과 마찬가지로 여러 면에서 가이드이다. 표시되지는 않지만 비슷한 방식으로 작동하며 각각 도형의 일부가 정렬될 x 또는 y 값을 정의하여 도형의 비율을 변경한다.

    조정 값은 각각 명목 값 100,000을 기반으로 하는 큰 정수이다. 조정의 유효 값은 도형의 너비 또는 높이에 비례한다. 따라서 x 좌표 조정 값 50,000은 도형 너비의 절반에 해당한다. y 좌표 조정 값 75,000은 도형 높이의 3/4에 해당한다.

    조정 값은 음수일 수 있으며 일반적으로 좌표가 도형의 왼쪽 위 모서리(원점)의 왼쪽 또는 위에 있음을 나타냅니다. 값에는 제한이 적용될 수도 있다. 즉, 유효 값은 미리 정해진 범위를 벗어날 수 없다. 실제로 이는 예를 들어 도형의 왼쪽을 넘어 확장할 수 없는 지점에 해당한다.

    PowerPoint에서 도형 조정을 하면서 시간을 보내는 것은 그들이 어떻게 작동하는지에 대한 직관적인 감각을 구축하는 데 시간을 투자하는 것이다. 또한 조정 코드 개발을 시작하기 전에 다양한 조정에 의해 생성된 XML 값을 볼 수 있도록 opc-diag를 설치할 수도 있다.

    다음 코드는 조정을 사용하여 콜아웃 도형의 형식을 지정한다.

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

     

    Python/python-pptx 사용자 가이드

    728x90

    댓글

Designed by Tistory.