Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

파이썬으로 PDF 파일 다루기: PyPDF2 활용 가이드

파이썬은 다양한 요구 사항을 처리할 수 있는 방대한 라이브러리 생태계를 갖춘 매우 유연한 언어입니다. 우리는 업무와 일상에서 PDF(Portable Document Format) 파일을 자주 다루는데, 파이썬은 PDF 파일을 처리할 수 있는 여러 가지 방법을 제공합니다. 이 글에서는 PyPDF2라는 파이썬 라이브러리를 사용해 PDF 파일을 다루는 방법을 살펴보겠습니다.

PyPDF2는 순수 파이썬으로 작성된 PDF 라이브러리로, PDF 페이지를 분할·병합·자르기·변환할 수 있습니다. 또한 PDF 파일에 사용자 정의 데이터나 보기 옵션, 비밀번호를 추가할 수 있으며, 텍스트와 메타데이터를 추출하거나 여러 파일을 하나로 합치는 기능도 지원합니다.

이처럼 PyPDF2 하나만으로 PDF에 대한 다양한 작업을 수행할 수 있기 때문에, 마치 만능 도구인 '스위스 아미 나이프'처럼 활용할 수 있습니다.

시작하기

PyPDF2는 파이썬 기본 패키지에 포함되어 있지 않으므로 먼저 설치해야 합니다. 다행히 pip를 이용하면 아주 간단합니다. 명령 프롬프트(터미널)에서 아래 명령어를 실행하세요.

C:\Users\rajesh>pip install pypdf2
Collecting pypdf2
Downloading https://files.pythonhosted.org/packages/b4/01/68fcc0d43daf4c6bdbc6b33cc3f77bda531c86b174cac56ef0ffdb96faab/PyPDF2-1.26.0.tar.gz (77kB)
100% |████████████████████████████████| 81kB 83kB/s
Building wheels for collected packages: pypdf2
Building wheel for pypdf2 (setup.py) ... done
Successfully built pypdf2
Installing collected packages: pypdf2
Successfully installed pypdf2-1.26.0

설치가 정상적으로 완료되었는지 확인하려면 파이썬 셸에서 PyPDF2를 임포트해 봅니다.

>>> import PyPDF2
>>>

참고: PyPDF2 3.x 버전부터는 클래스와 메서드 이름이 크게 변경되었습니다. 예를 들어 PdfFileReaderPdfReader로, getNumPages()len(reader.pages)로 대체되었습니다. 또한 현재는 PyPDF2 개발이 종료되고 통합 프로젝트인 pypdf로의 전환이 권장되므로, 최신 환경이라면 pip install pypdf를 사용하는 것이 좋습니다.

메타데이터 추출하기

PDF에서는 문서의 저자, 제목, 주제, 전체 페이지 수 같은 중요한 정보를 손쉽게 추출할 수 있습니다.

다음은 pypdf2 패키지를 사용해 PDF 파일에서 유용한 정보를 추출하는 파이썬 프로그램입니다.

from PyPDF2 import PdfFileReader
def extract_pdfMeta(path):
    with open(path, 'rb') as f:
        pdf = PdfFileReader(f)
        info = pdf.getDocumentInfo()
        number_of_pages = pdf.getNumPages()
    print("Author: \t", info.author)
    print()
    print("Creator: \t", info.creator)
    print()
    print("Producer: \t", info.producer)
    print()
    print("Subject: \t", info.subject)
    print()
    print("title: \t", info.title)
    print()
    print("Number of Pages in pdf: \t", number_of_pages)
if __name__ == '__main__':
    path = 'DeepLearning.pdf'
    extract_pdfMeta(path)

실행 결과

Author: Nikhil Buduma,Nicholas Locascio

Creator: AH CSS Formatter V6.2 MR4 for Linux64 : 6.2.6.18551 (2014/09/24 15:00JST)

Producer: Antenna House PDF Output Library 6.2.609 (Linux64)

Subject: None

title: Fundamentals of Deep Learning

Number of Pages in pdf: 298

이렇게 PDF 파일을 직접 열어보지 않고도 저자, 제목, 페이지 수 등 유용한 정보를 빠르게 확인할 수 있습니다.

PDF에서 텍스트 추출하기

PyPDF2는 PDF에서 텍스트를 추출하는 기능도 제공합니다. 참고로 이미지 추출 역시 기본적으로 지원합니다.

그럼 앞서 사용한 PDF 파일의 특정 페이지(예: 50페이지)에서 텍스트를 추출해 보겠습니다.

# Import pypdf2
from PyPDF2 import PdfFileReader
def extract_pdfText(path):
    with open(path, 'rb') as f:
        pdf = PdfFileReader(f)
        # 50번째 페이지 가져오기
        page = pdf.getPage(50)
        print(page)
        print('Page type: {}'.format(str(type(page))))
        # 50번째 페이지에서 텍스트 추출
        text = page.extractText()
        print(text)
if __name__ == '__main__':
    path = 'DeepLearning.pdf'
    extract_pdfText(path)

실행 결과

{'/Annots': IndirectObject(1421, 0),
'/Contents': IndirectObject(179, 0),
'/CropBox': [0, 0, 595.3, 841.9],
'/Group': {'/CS': '/DeviceRGB', '/S': '/Transparency', '/Type': '/Group'},
'/MediaBox': [0, 0, 504, 661.5],
'/Parent': IndirectObject(4863, 0),
'/Resources': IndirectObject(1423, 0),
'/Rotate': 0,
'/Type': '/Page'
}

Page type: <class 'PyPDF2.pdf.PageObject'>
time. In inverted dropout, any neuron whose activation hasn†t been silenced has its
output divided by p before the value is propagated to the next layer. With this
fix, Eoutput=p⁄xp+1ƒ
p⁄0=
x, and we can avoid arbitrarily scaling neuronal
output at test time.

SummaryIn this chapter, we†ve learned all of the basics involved in training feed-forward neural
networks. We†ve talked about gradient descent, the backpropagation algorithm, as
well as various methods we can use to prevent overfitting. In the next chapter, we†ll
put these lessons into practice when we use the TensorFlow library to efficiently
implement our first neural networks. Then in Chapter 4, we†ll return to the problem
of optimizing objective functions for training neural networks and design algorithms
to significantly improve performance. These improvements will enable us to process
much more data, which means we†ll be able to build more comprehensive models.
Summary | 37

50페이지에서 텍스트를 일부 가져올 수는 있지만 결과가 그리 깔끔하지 않습니다. 안타깝게도 PyPDF2는 PDF 텍스트 추출 기능에 대한 지원이 상당히 제한적입니다. 더 정확한 텍스트 추출이 필요하다면 pdfplumber, pdfminer.six 같은 대안 라이브러리를 함께 고려해 보는 것도 좋습니다.

PDF 특정 페이지 회전하기

PyPDF2를 사용하면 PDF의 특정 페이지를 회전할 수도 있습니다. 아래 예제는 첫 번째 페이지를 시계 방향으로 90도 회전한 뒤 새 파일로 저장하는 코드입니다.

>>> import PyPDF2
>>> deeplearningFile = open('DeepLearning.pdf', 'rb')
>>> pdfReader = PyPDF2.PdfFileReader(deeplearningFile)
>>> page = pdfReader.getPage(0)
>>> page.rotateClockwise(90)
{
'/Contents': [IndirectObject(4870, 0), IndirectObject(4871, 0), IndirectObject(4872, 0), IndirectObject(4873, 0), IndirectObject(4874, 0), IndirectObject(4875, 0), IndirectObject(4876, 0), IndirectObject(4877, 0)],

'/CropBox': [0, 0, 595.3, 841.9],

'/MediaBox': [0, 0, 504, 661.5], '/Parent': IndirectObject(4862, 0), '/Resources': IndirectObject(4889, 0),
'/Rotate': 90,
'/Type': '/Page'
}
>>> pdfWriter = PyPDF2.PdfFileWriter()
>>> pdfWriter.addPage(page)
>>> resultPdfFile = open('rotatedPage.pdf', 'wb')
>>> pdfWriter.write(resultPdfFile)
>>> resultPdfFile.close()
>>> deeplearningFile.close()

실행 결과

파이썬으로 PDF 파일 다루기: PyPDF2 활용 가이드