본문 바로가기
IT일반

pdf 읽기 python으로

by xavi2019 2022. 7. 5.

이미지 형태가 아닌 pdf의 텍스트 추출하는 소스

페이징 처리도 되어 있음

 

pip3 버전을 최신 버전으로 업그레이드

python3 -m pip install --upgrade pip
#
# 필요한 모듈설치
# pip3 install pdfminer.six 
#

from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from io import StringIO

def convert_pdf_to_txt():
    rsrcmgr = PDFResourceManager()
    retstr = StringIO()
    codec = 'utf-8'
    laparams = LAParams()
    device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
    fp = open('문서이름.pdf', 'rb')
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    password = ""
    maxpages = 0
    caching = True
    pagenos=set()

    for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):
        interpreter.process_page(page)

    text = retstr.getvalue()

    fp.close()
    device.close()
    retstr.close()
    return text

v = convert_pdf_to_txt()
print(v)

댓글