Programming/Python

PDFMiner 설치: Python에서 pdf를 html이나 text파일로 변환

동건 2016. 4. 30. 19:05

pdf를 쉽게 접근할 수 있는 html이나 text 파일 형식으로 변환하고자 할 때, 그 와중에 웹 상에서 제공하는 변환 서비스를 이용하긴 꺼림칙하고 파이썬 코딩으로 간편하게 할 수 있는 방법이 없을까..? 싶을 때. 결국 최종적으로 당신이 도착할 곳은 PDFMiner일 것이라고 생각한다. 모듈 설치 후 바로 사용할 수 있는 코드도 제공하기 때문에 속도에 크게 신경 쓰지 않고 사용하기에는 큰 불편이 없을 것 같다. 참, PDFMiner 모듈은 Python 2 버젼에서만 사용 가능하다고 하니 참고하자.

1. 설치

pip 명령어를 이용하면 간단히 설치 가능.

pip install pdfminer

다만 한중일 언어 (CJK Languages) 의 pdf 문서도 변환하기 위해서는 별도의 설치 과정이 필요하다. 우선 소스 파일을 여기저기서 다운 받고 압축을 풀자.

* 윈도우를 사용한다면

압축을 푼 폴더 (아마도 pdfminer-20140328이라는 이름일 것이다) 에 가서 명령창을 연다. (모르는 사람이 있다면 꿀팁: 탐색기에서 shift+우클릭을 하면 메뉴에 "여기서 명령창 열기" 라는 새로운 명령을 볼 수 있다) 그리고 아래 명령어들을 입력하자.

mkdir pdfminer
python tools\conv_cmap.py -c B5=cp950 -c UniCNS-UTF8=utf-8 pdfminer\cmap Adobe-CNS1 cmaprsrc\cid2code_Adobe_CNS1.txt
python tools\conv_cmap.py -c GBK-EUC=cp936 -c UniGB-UTF8=utf-8 pdfminer\cmap Adobe-GB1 cmaprsrc\cid2code_Adobe_GB1.txt
python tools\conv_cmap.py -c RKSJ=cp932 -c EUC=euc-jp -c UniJIS-UTF8=utf-8 pdfminer\cmap Adobe-Japan1 cmaprsrc\cid2code_Adobe_Japan1.txt
python tools\conv_cmap.py -c KSC-EUC=euc-kr -c KSC-Johab=johab -c KSCms-UHC=cp949 -c UniKS-UTF8=utf-8 pdfminer\cmap Adobe-Korea1 cmaprsrc\cid2code_Adobe_Korea1.txt

한 줄씩 실행하면 명령창에서 열심히 뭔가 쓰여지는 것을 확인할 수 있다. 위 작업들이 다 끝나고 나면 마지막으로 설치 명령어를 실행하면 된다.

python setup.py install

2. 사용 예제

소스 코드 안에서 제공되는 코드들이 있다. 소스 코드 폴더 내의 tools 폴더 안에 pdf2txt.py라는 파이썬 코드를 실행하면 바로 별도의 코딩 없이 pdf 문서를 변환할 수 있다.

pdf2txt.py -o output.html samples/pdf.pdf

-o 변환될파일이름.html

-o 변환될파일이름.txt

변환될 파일이름의 확장자를 알아서 읽어서 그 형식에 맞게 html 또는 txt파일을 만들어 줄 것이다. 저 pdf2txt.py을 직접 보면 어떤 식으로 작동하는 것인지 대충은 알 수 있을 것이다.

3. 사용 방법

한 줄의 명령으로 pdf 변환을 할 수 있게 해주는 pdf2txt.py 소스코드를 조금만 살펴보면 내가 원하는 설정으로 pdf를 변환할 수 있는 python 코드를 직접 작성할 수 있을 것이다. 다음은 pdf파일을 파일 브라우저로 직접 선택해서 pdf2output.html 파일로 변환하는 코드이다.

# -*- coding: utf-8 -*-
from tkFileDialog import askopenfilename
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfdevice import PDFDevice, TagExtractor
from pdfminer.pdfpage import PDFPage
from pdfminer.converter import XMLConverter, HTMLConverter, TextConverter
from pdfminer.cmapdb import CMapDB
from pdfminer.layout import LAParams
from pdfminer.image import ImageWriter

password = ''
pagenos = set()
maxpages = 0
# output option
outfile = None
outtype = None
imagewriter = None
rotation = 0
layoutmode = 'normal'
codec = 'utf-8'
codec = 'euc-kr'
pageno = 1
scale = 1
caching = True
showpageno = True
laparams = LAParams()

fpname = askopenfilename()
fp = file(fpname, 'rb')

outfpname = 'pdf2output'

rsrcmgr = PDFResourceManager(caching=caching)
outfp = file(outfpname + '.txt', 'w')
device = TextConverter(rsrcmgr, outfp, codec=codec, 
laparams=laparams, imagewriter=imagewriter) interpreter = PDFPageInterpreter(rsrcmgr, device) for page in PDFPage.get_pages(fp, pagenos,                               maxpages=maxpages, password=password,                               caching=caching, check_extractable=True):     page.rotate = (page.rotate+rotation) % 360     interpreter.process_page(page)      outfp.close() rsrcmgr = PDFResourceManager(caching=caching) outfp = file(outfpname + '.html', 'w') device = HTMLConverter(rsrcmgr, outfp, codec=codec, scale=scale,                        layoutmode=layoutmode, laparams=laparams,                        imagewriter=imagewriter) interpreter = PDFPageInterpreter(rsrcmgr, device) for page in PDFPage.get_pages(fp, pagenos,                               maxpages=maxpages, password=password,                               caching=caching, check_extractable=True):     page.rotate = (page.rotate+rotation) % 360     interpreter.process_page(page) outfp.close() fp.close()



참고자료

공식 페이지: 설치법, 사용법 등에 대한 설명을 담고 있고, 웹에서 직접 시범 사용을 할 수도 있다.
http://www.unixuser.org/~euske/python/pdfminer/index.html


반응형