pdf 를 txt 로 converting 하는 방법. xpdf - pdftotxt

새로 투입된 프로젝트에서 기존 레거시 소스를 수정해야 하는 일을 맡았다.
그런데 소스를 pdf 파일로 주는것이 아닌가.... ㅜㅜ
한두개도 아니고 그많은 소스를 손으로 칠수도 없고...

pdf 를 txt 형태로 바꾸는 방법을 찾아 보았다.
python 의 pyPdf 모듈을 쓰면된다고 한다.

================================
import pyPdf

def getPDFContent(path):
    content = ""
    # Load PDF into pyPDF
    print path
    pdf = pyPdf.PdfFileReader(file(path, "rb"))
    # Iterate pages   
    for i in range(0, pdf.getNumPages()):
        # Extract text from page and add to content
        content += pdf.getPage(i).extractText() + "\n"
    # Collapse whitespace
    #content = " ".join(content.replace(u"\xa0", " ").strip().split())
    return conten
====================================

이방법엔 한가지 문제가 있다.
소스 아웃라인을 무시하고 그냥 쭈욱~ 연결한 변환파일을 만들어 낸다.

다시 해결책을 찾다가 더 손쉬운 방법을 찾았다.
pdftotext 라는 편리한 툴!!!

xpdf 라는 pdf 관련툴의 한 부분인것 같다.
명령어는 다음과 같다.

pdftotext -layout -nopgbrk source_pdf_file_name dest_txt_file_name

python 으로 system 모듈을 이용 약 122여개의 pdf 소스를 txt 로 변환하였다.
깔끔하게 잘된다.....

=======================================================
import os
import sys, os

def getFileList(theDir):
    theDir = os.path.abspath(theDir)
    flist  = os.listdir((theDir))
    returnList =[]
    for i in flist:
        i = theDir + '/' + i
        returnList.append(i)
    return returnList

def Usage():
    print "Usage : %s directory" % sys.argv[0]
if __name__ == '__main__':
    if len(sys.argv) != 2:
        Usage()
    theDir = sys.argv[1]
    flist =  getFileList(theDir)
    for i in flist:
        newFile = ''
        if i.endswith('py'): continue
        if i.find('.h') != -1:
            newFile = i.replace('.h.pdf','.h')
        else:
            newFile = i.replace('.pdf','.c')
        os.system("pdftotext -layout -nopgbrk %s %s" % (i, newFile))
==============================================================

댓글

이 블로그의 인기 게시물

구어체 표현 85가지

Debian Lenny install-including wireless