본문 바로가기
Python/Common

[Python] PDF를 이미지로 변환하는 법 (Pdf2Image)

by jiyoon_92 2022. 6. 9.
반응형

python

 

Python으로 PDF를 JPEG으로 변환할 때 가장 많이 사용되는 라이브러리로 Pdf2Image 라이브러리가 있다.

오늘은 이 라이브러리를 이용하여 PDF문서를 JPEG으로 한장씩 저장하는 방법 및 배포까지 알아보자.

 


Pdf2Image 설치

command창을 열어 pip를 이용하여 pdf2image 라이브러리를 아래와 같이 설치한다.

>pip install pdf2image 

pip를 이용하여 pdf2image 설치


poppler library 다운로드

pdf2image의 함수 convert_from_path() 사용 시 poppler 라이브러리가 필요 하므로 다운받아 압축을 풀어준다.다운로드 링크 : https://github.com/oschwartz10612/poppler-windows/releases/

본인은 배포까지 하기 위해 프로젝트 내 lib 폴더를 만들어서 내부에 압축을 풀어줬다. 


코드 작성

def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base_path, relative_path)
    
# PDF to Image(JPEG) function
def convert_pdf_to_image(input_path, save_path):
    abs_input_path = os.path.abspath(input_path)
    abs_save_path = os.path.abspath(save_path)
    splits_path = abs_input_path.split('\\')
    file_name = splits_path[len(splits_path) - 1]
                      
    # split 저장할 파일명
    sub_index = len(file_name) - 4
    save_file_name = file_name[:sub_index]
    # convert pdf to images
    path = resource_path('lib\\poppler-22.04.0\\bin')
    images = convert_from_path(abs_input_path, dpi=600, thread_count=4, poppler_path = path)
      
    # 저장할 폴더 없는 경우 생성
    if (os.path.exists(abs_save_path) == False):
        os.mkdir(abs_save_path)
     
    image_count = len(images)
    for i in range(image_count):
      # Save pages as images in the pdf
      images[i].save(abs_save_path + "\\" + save_file_name + '_' + str(i + 1) +'.jpg', 'JPEG')

convert_from_path() 함수를 이용하여 pdf를 image로 변환한다.

convert_from_path(pdf_path=pdf경로, dpi=이미지 해상도(기본값 300이지만 복합기 스캔 기준 600), thread_count=변환할 때 쓸 thread 개수(변환 페이지 수 미만), poppler_path = poppler exe가 설치된 경로)

*resource_path()함수는 poppler의 상대 경로를 절대 경로로 바꿔준다.

*dpi를 줄이거나 thread_count를 늘릴수록 변환 속도가 빨라짐. 


배포 시 유의사항

PyInstaller를 사용하여 배포 시 아래와 같이 datas에 라이브러리 폴더를 복사할 수 있도록 넣어준 후 poppler_path 경로를 참조할 수 있는 상대 경로로 넣어줘야 한다. 

PyInstaller로 배포하기 위한 spec 파일

# convert pdf to images
    path = resource_path('lib\\poppler-22.04.0\\bin')
    images = convert_from_path(abs_input_path, dpi=600, thread_count=4, poppler_path = path)

PyInstaller로 배포하기 위한 설정 값들을 담은 Spec 파일에 대해서는 다음에 포스팅 하도록 하겠다.

반응형

댓글