ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [python-pptx] 파이썬 업무 자동화
    공부/Python 2023. 9. 19. 17:25

    python-pptx Library: PowerPoint(.pptx) 파일을 조작하기 위한 라이브러리

     

    https://python-pptx.readthedocs.io/en/latest/

     

    python-pptx — python-pptx 0.6.22 documentation

    python-pptx Release v0.6.22 (Installation) python-pptx is a Python library for creating, reading, and updating PowerPoint (.pptx) files. A typical use would be generating a PowerPoint presentation from dynamic content such as a database query, analytics ou

    python-pptx.readthedocs.io

     


    해당 하위 경로의 이미지 파일들에 대해서 간단한 작업 거쳐 pptx 를 생성하는 코드.

     

    회사에서 반복적인 이미지 편집이 귀찮아서 좀 더 쉽게 하려고 작성하였다.

     

     

    from pptx import Presentation
    from pptx.dml.color import RGBColor
    from pptx.dml.effect import ShadowFormat
    from pptx.util import Cm, Pt
    from pptx.enum.shapes import MSO_AUTO_SHAPE_TYPE
    import os
    import natsort
    
    IMAGEFORMATS = ["JPG", "JPEG","JFIF", "GIF", "PNG", "JFIF", "BMP"]
    
    RED = RGBColor(255, 0, 0)
    WHITE = RGBColor(255, 255, 255)
    BLACK = RGBColor(0, 0, 0)
    
    def main():
        pwd = get_pwd().replace('\\', '/')
        print("현재 경로: ", pwd)
    
        # 프레젠테이션
        prs = Presentation()
        width = prs.slide_width
        height = prs.slide_height
        print("Presentation Size: ", width, height)
    
        imageList = read_images(pwd)
        imgCnt = 0
    
        for path, subdirs, files in imageList:
            for file in files:
                a = file.split('.')
                if len(a) < 2:
                    continue
                if not (a[-1].upper() in IMAGEFORMATS):
                    continue
                try:
                    # 새로운 빈 슬라이드 추가
                    slide = prs.slides.add_slide(prs.slide_layouts[6])
                    # 이미지 경로
                    imgPath = os.path.join(path, file)
                    # 이미지를 중앙에 추가
                    pic = add_image_center(prs, slide, imgPath)
                    # 빨간색 격자 추가
                    add_red_gird(slide)
                    # 이미지 테두리 설정(3px black)
                    set_image_border(pic)
                    # 슬라이드 노트 추가
                    add_slide_note(slide, imgPath)
                    # 텍스트 박스 추가 14px
                    add_text_box(slide)
    
                    imgCnt += 1
                    print(imgCnt, ": ", file)
                except PermissionError:
                    print("Permission Error: ", file)
    
            # 빈 레이아웃 추가
            #layout = prs.slide_layouts[5]
            #slide = prs.slides.add_slide(layout)
            #slide.shapes[0].text = "경로: " + str(''.join(subdirs[0:]))
    
        # 프레젠테이션 파일 저장
        os.chdir(pwd)
        prs.save("./test.pptx")
    
        print(imgCnt, "개 이미지 작업 완료")
    
    
    # 이미지를 LT 기준으로 추가
    def add_image(_slide, _imgPath, _left, _top, _width=0, _height=0):
        # left top 설정
        left = Cm(_left)
        top = Cm(_top)
        if _width > 0 and _height > 0:
            pic = _slide.shapes.add_picture(_imgPath, left, top, width=_width, height=_height)
        elif _width > 0:
            pic = _slide.shapes.add_picture(_imgPath, left, top, width=_width)
        elif _height > 0:
            pic = _slide.shapes.add_picture(_imgPath, left, top, height=_height)
        else:
            pic = _slide.shapes.add_picture(_imgPath, left, top)
        return pic
    
    
    def add_image_center(_prs, _slide, _imgPath):
        # left top 설정
        pWidth = _prs.slide_width
        pHeight = _prs.slide_height
    
        # 이미지 너비 높이
        pic = _slide.shapes.add_picture(_imgPath, 0, 0)
    
        width = pic.width
        height = pic.height
        _slide.shapes.element.remove(_slide.shapes[0].element)
    
        # 슬라이드 크기 대비 이미지의 크기 비율
        imgHeightRatio = height / pHeight
        imgWidthRatio = width / pWidth
    
        # Height 가 더 길면 1 아니면 0
        checkHeightLonger = 1 if imgHeightRatio > imgWidthRatio else 0
        # 이미지 크기 조정 비율
        imageResizeRatio = 0.96
    
        if checkHeightLonger:
            left = (pWidth - (pHeight * imageResizeRatio / height) * width) // 2
            height = pHeight * imageResizeRatio
            top = (pHeight // 2) - (height // 2)
            pic = _slide.shapes.add_picture(_imgPath, left, top, height=height)
        else:
            top = (pHeight - (pWidth * imageResizeRatio / width) * height) // 2
            width = pWidth * imageResizeRatio
            left = (pWidth // 2) - (width // 2)
            pic = _slide.shapes.add_picture(_imgPath, left, top, width=width)
    
        return pic
    
    def add_slide_note(_slide, _str):
        notes_slide = _slide.notes_slide
        text_frame = notes_slide.notes_text_frame
        text_frame.text = _str
    
    def add_red_gird(_slide):
        shapes = _slide.shapes
        shapes.add_shape(MSO_AUTO_SHAPE_TYPE.RECTANGLE, Pt(0), Pt(0), Pt(100), Pt(40))
        shapes[-1].line.color.rgb = RED
        shapes[-1].line.width = Pt(1.5)
        shapes[-1].fill.background()
        shapes[-1].shadow.inherit = False
    
    def add_text_box(_slide):
        shapes = _slide.shapes
        shapes.add_textbox(Pt(140), Pt(0), Cm(4.68), Cm(0.86))
        shapes[-1].line.color.rgb = BLACK
        shapes[-1].line.width = Pt(1.5)
        shapes[-1].text = "내용을 입력하세요"
        para = shapes[-1].text_frame.paragraphs
        for p in para:
            p.font.size = Pt(14)
            p.font.name = "맑은 고딕"
    def set_image_border(_img):
        _img.line.color.rgb = BLACK
        _img.line.width = Pt(3)
    
    
    def read_images(_pwd):
        path = _pwd + '/images/'
        os.chdir(path)  # 해당 폴더로 이동
        files = os.walk(path)
        files = natsort.natsorted(files)
        print(files)
        return files
    
    
    def get_pwd():
        return os.getcwd()
    
    
    def slide_layout():
        pass
    
    
    if __name__ == '__main__':
        main()

     

     

    '공부 > Python' 카테고리의 다른 글

    [openpyxl] 액셀 파일 조작  (0) 2022.08.07
    openpyxl, 파이썬에서 .xlsx 다루기  (0) 2022.07.27
    pyautogui 마우스 및 키보드 조작  (0) 2021.11.02
Designed by Tistory.