파이썬2021. 6. 17. 14:04
728x90

pdftotree를 이용해서 pdf를 html(tree구조)로 변경해야 하는 일이 있었다.

하지만 잘 쓰이지 않는지 코드가 나와있는 블로그가 거의 없었다.

나와 같이 헤멨던 분들에게 이 글이 도움이 되었으면 좋겠다. (도움이 되면 공감버튼 꾹!!)

 

[ pdftotree 깃허브 ]

https://github.com/HazyResearch/pdftotree

 

HazyResearch/pdftotree

:evergreen_tree: A tool for converting PDF into hOCR with text, tables, and figures being recognized and preserved. - HazyResearch/pdftotree

github.com

(사실 봐도 잘 모르겠다.. 설치 방법 외에는..)

 

 

* pycharm에서 install을 했더니 잘 되지 않는 것 같아 jupyter notebook을 이용했다.

(이용방법은 더보기 참고)

더보기

--------------------(더보기)--------------------

[jupyter notbook 이용해서 하는 법]

 

우선 anaconda prompt를 실행한다.

 

 

jupyternotebook을 실행하고 싶은 폴더로 이동 후 실행한다.

그리고 이 폴더에 변환 할 pdf파일을 넣을 것이다.

#원하는폴더로 이동
(base) C:\Users\min>cd 폴더명

# jupyter notebook 실행
(base) C:\Users\min\jupyter>jupyter notebook
나는 이름을 그냥 jupyter로 했는데 폴더명은 마음대로 해도 된다

 

코드를 입력하고 엔터치면 새 인터넷 창이 뜨면서 jupyter notebook이 실행된다.

 

여기 보이는 ipynb 파일을 클릭해서 코드를 입력해주면 된다.

 

코드 입력 후 Ctrl+Enter를 누르면 해당 셀이 실행된다.

--------------------(더보기)--------------------

 

 

1) pdf 준비

* hwp(한글)파일을 이용할 때는 을 이용하자! (추천사이트 https://allinpdf.com/hwp-to-pdf )

한글프로그램에서 pdf로 출력/저장 이렇게 해서 pdf를 만들면 에러가 많이 발생하는 것 같다.

 

준비한 pdfjupyter notebook 파일(ipynb)이 있는 폴더에 넣는다. (위의 예시에서는 C:\Users\min\jupyter )

 

 

 

2) pdftotree 코드 실행

 

pdftotree 설치

pip install pdftotree

 

import 해오기

import pdftotree

* pip install pdftotree와 import pdftotree는 따로 하는 걸 추천한다.

   jupyter notebook(아래참고)에서 같은 셀에 하면 에러가 발생하기도 함.

이렇게 따로 실행시키는 것을 추천한다.

코드

f_name='파일이름' #확장자는 필요없음
f_name_pdf=f_name+'.pdf'
#table을 포함 한 문서의 경우 model_type='table'로 해주는게 좋음
result = pdftotree.parse(f_name_pdf,html_path=None, model_type='table',model_path=None,visualize=False)

# 변경할 html 파일이름 생성
f_name_html=f_name+'.html'

# 유니코드 문제 해결
with open('out.html','w',-1,'utf-8') as f:
    f.write(result)
    
#전처리 코드(테이블 가시성 높임)
import re
file = open('out.html', 'r', encoding='utf-8')
text = file.read()

text = text.replace('\\n\\t', ' ')
text = text.replace('\\t', '')

text = text.replace('<table', '<table border=\'1\'')

new_file = open(f_name_html, 'w', encoding='utf-8')
new_file.write(text)
new_file.close()

file.close()

 

---------------------------------------------

 

약간 파일 이름을 하나하나 입력하기가 귀찮아서

폴더 내에 있는 파일들을 list로 읽어와서 변환해주는 코드를 짜봤다.

 

[ 폴더 내 pdf파일들을 html로 전환하기 ]

#-------를 기준으로 jupyternotebook에서 셀을 나눴다.

# pdftotree설치
pip install pdftotree
#-------------------------------------------
#import 해주기
import pdftotree
#-------------------------------------------

# [파일 이름 읽어오기]
import os
#path_dir할 때 \ -> / 바꿔주기
#이 코드가 위치 한 디렉토리로 설정해주기!
path_dir='C:/Users/min/jupyter'
file_list=os.listdir(path_dir)
print(file_list)
#-------------------------------------------

# [ pdf 파일만 골라서 html로 ]
for f_name_pdf in file_list:
    idx=file_list.index(f_name_pdf)    
    
    # 파일명 (.pdf) '' 인 것들만 고르기!
    fn=f_name_pdf.split('.pdf')
    if(len(fn)<2 or fn[1]!=''): # .oldPdf 이렇게 확장자 다른 애들은 len(fn)==1
        print('continue: ',fn)
        continue
    f_name_html=fn[0]+'.html'
    
    try:
        result = pdftotree.parse(f_name_pdf,html_path=None, model_type='table',model_path=None,visualize=False)
    except:
        print('continue')
        continue 
        
    with open('out.html','w',-1,'utf-8') as f:
        f.write(result)
    
    #전처리 코드
    import re
    file = open('out.html', 'r', encoding='utf-8')
    text = file.read()

    text = text.replace('\\n\\t', ' ')
    text = text.replace('\\t', '')

    text = text.replace('<table', '<table border=\'1\'')
	
    # f_name_html.html파일에 출력
    new_file = open(f_name_html, 'w', encoding='utf-8')
    new_file.write(text)
    new_file.close()

    file.close()

 

* 실행 전

이렇게 3개의 pdf가 있다.

 

* 실행 후

각각에 해당하는 html 파일들이 생성되었다.

 

 

※ 제 글이 도움이 되었다면 공감 부탁드려요 :)

반응형
Posted by mminky