fullmoon's bright IT blog

[python] ppt에서 pdf 변환 코드 작성하기(수정) 본문

STUDY

[python] ppt에서 pdf 변환 코드 작성하기(수정)

휘영청 2023. 11. 9. 12:14
728x90

ppt만들다가 맨날 다른이름으로 저장하거나 내보내기가 너무 귀찮다

귀찮으면 코드로 짜는게 좋다

 

ppt에서 pdf 코드를 찾는다면 가져다 쓰삼 !

 

1. comtypes 모듈은 COM (Component Object Model) 객체와 상호 작용하기 위한 Python 라이브러리로 설치하기

pip install comtypes

 

2. pywin32 모듈은 Windows API에 액세스하여 Microsoft Office 프로그램을 제어하니 설치하기

pip install pywin32

 

 

3. 변환 코드

import os
import comtypes.client

# PPTX 파일을 PDF로 변환하는 함수 정의
def convert_pptx_to_pdf(input_pptx, output_pdf):
    # PowerPoint 객체를 생성
    powerpoint = comtypes.client.CreateObject("PowerPoint.Application")
    powerpoint.Visible = 1  # PowerPoint 창을 화면에 표시 (1은 표시, 0은 표시하지 않음)

    # 입력 PPTX 파일 열기
    ppt_file = powerpoint.Presentations.Open(input_pptx)

    # PPTX 파일을 PDF로 저장 (32는 PDF 형식을 나타냄)
    ppt_file.SaveAs(output_pdf, 32)

    # PPTX 파일 닫기
    ppt_file.Close()

    # PowerPoint 객체를 종료
    powerpoint.Quit()

    # 변환이 완료되었음을 사용자에게 알림
    print("변환이 완료되었습니다.")  # 변환이 성공하면 출력될 메시지

if __name__ == "__main__":
    # 입력 PPTX 파일의 경로 설정
    input_pptx = r"경로.pptx"

    # 출력 PDF 파일의 경로 설정
    output_pdf = r"경로.pdf"

    # PPTX를 PDF로 변환하는 함수 호출
    convert_pptx_to_pdf(input_pptx, output_pdf)

 

 Windows 파일 경로에서 역슬래시(\)는 이스케이프 문자로 사용되는데, r 접두어를 사용하면 이스케이프 문자로 해석되지 않고 그대로 유지됨 원래 이거 역슬래시 때문에 해석이 안되서 짜증났음.

파일 경로를 나타내는 문자열에서 r을 사용하면 이스케이프 문자를 처리하는 번거로움을 줄여서 사용한다.

 

경로찾기

파워포인트 파일의  오른쪽 클릭 (ctrl + shift + C) 혹은 [경로로 복사]

 

 

적용하기

 

 

볼까나

굿

 

귀찮으면 코드 짜자

배우니까 개편함ㅋㅎㅋㅎ

--- 나의 센세 주영님

 

 

import os
import comtypes.client

def convert_pptx_to_pdf(input_pptx, output_pdf):

    # 사용자로부터 PPTX 파일 경로 입력 받기
    input_pptx = input("PPTX 파일 경로를 입력하세요: ")

    # 사용자로부터 출력 PDF 파일 경로 입력 받기
    output_pdf = input("PDF 파일을 저장할 경로를 입력하세요: ")

    powerpoint = comtypes.client.CreateObject("PowerPoint.Application")
    powerpoint.Visible = 1

    ppt_file = powerpoint.Presentations.Open(input_pptx)

    ppt_file.SaveAs(output_pdf, 32)  # 32는 PDF 형식
    ppt_file.Close()

    powerpoint.Quit()

    print("변환이 완료되었습니다.")  # 변환이 성공하면 출력될 메시지

if __name__ == "__main__":
    convert_pptx_to_pdf(input_pptx, output_pdf)

 

 

[최종]

import os
import comtypes.client

def convert_pptx_to_pdf():

    # 사용자로부터 PPTX 파일 경로 입력 받기
    input_pptx = input("PPTX 파일 경로를 입력하세요: ")

 # 파일 경로에서 확장자를 추출하여 .pdf를 붙이기
    base_path, extension = os.path.splitext(input_pptx)
    output_pdf = base_path + ".pdf"

    powerpoint = comtypes.client.CreateObject("PowerPoint.Application")
    powerpoint.Visible = 1

    ppt_file = powerpoint.Presentations.Open(input_pptx)

    ppt_file.SaveAs(output_pdf, 32)  # 32는 PDF 형식
    ppt_file.Close()

    powerpoint.Quit()

    print("변환이 완료되었습니다.")  # 변환이 성공하면 출력될 메시지

if __name__ == "__main__":
    convert_pptx_to_pdf()

굿

728x90