Working with PDF files in Python?

PythonServer Side ProgrammingProgramming

Python is a very versatile language as it provides huge set of libraries to work on different requirements. We all work on Portable Document Format (PDF) files. Python provides different ways to work with pdf files. In this we are going to use python library called PyPDF2 to work with pdf file.

PyPDF2 is a pure-python PDF library capable of splitting, merging together, cropping, and transforming the pages of PDF files. It can also add custom data, viewing options, and passwords to PDF files. It can retrieve text and metadata from PDFs as well as merge entire files together.

As we can do multiple operations on PDFs with PyPDF2, so it acts like a Swiss-army knife.

Getting Started

Because pypdf2 is an standard python package, so we need to install it. Good thing is it’s very easy, we can use pip to install it. Simply run below command on your command terminal:

C:\Users\rajesh>pip install pypdf2
Collecting pypdf2
Downloading (77kB)
100% |████████████████████████████████| 81kB 83kB/s
Building wheels for collected packages: pypdf2
Building wheel for pypdf2 ( ... done
Stored in directory: C:\Users\rajesh\AppData\Local\pip\Cache\wheels\53\84\19\35bc977c8bf5f0c23a8a011aa958acd4da4bbd7a229315c1b7
Successfully built pypdf2
Installing collected packages: pypdf2
Successfully installed pypdf2-1.26.0

To verify, import pypdf2 from python shell

>>> import PyPDF2
Successful, Great.

Extracting Metadata

We can extract some of the important useful data from any pdf. For example, we can extract the information on author of the document, its title, subject and the number of pages contained in the pdf file.

Below is the python program to extract useful information from the pdf file using pypdf2 package.

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",
   print("Creator: \t", info.creator)
   print("Producer: \t",info.producer)
   print("Subject: \t", info.subject)
   print("title: \t",info.title)
   print("Number of Pages in pdf: \t",number_of_pages)
if __name__ == '__main__':
   path = 'DeepLearning.pdf'


Author: Nikhil Buduma,Nicholas Locascio

Creator: AH CSS Formatter V6.2 MR4 for Linux64 : (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

So without opening pdf files, we are able to get some useful information from the pdf file.

Extracting Text from PDFs

We can extract text from the pdfs. Though it have built-in support for extracting images.

Let’s try to extract text from a particular page (for example: page 50) of the pdfs file we downloaded above.

#Import pypdf2
from PyPDF2 import PdfFileReader
def extract_pdfText(path):
   with open(path, 'rb') as f:
      pdf = PdfFileReader(f)
      # get the 50th page
      page = pdf.getPage(50)
      print('Page type: {}'.format(str(type(page))))
      #Extract text from the 50th page
      text = page.extractText()
if __name__ == '__main__':
   path = 'DeepLearning.pdf'


{'/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,

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ƒ
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 algorithmsto 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

Though we are able to get some text from the page 50 but it’s not that clean. Unfortunately, pypdf2 has a very limited support for extracting text from pdfs.

Rotate particular page of a pdf file

>>> 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()


Published on 08-Apr-2019 09:55:34