The Wayback Machine - https://web.archive.org/web/20240723213018/https://www.geeksforgeeks.org/parsing-pdfs-in-python-with-tika/
Open In App

Parsing PDFs in Python with Tika

Last Updated : 17 Aug, 2020
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

Apache Tika is a library that is used for document type detection and content extraction from various file formats. Using this, one can develop a universal type detector and content extractor to extract both structured text and metadata from different types of documents such as spreadsheets, text documents, images, PDF’s, and even multimedia input formats to a certain extent. Tika-Python is Python binding to the Apache TikaTM REST services allowing tika to be called natively in python language.

Installation:

To install Tika type the below command in the terminal. 

pip install tika

Note: Tika is written in Java, so you need a java(7 or 7+) runtime installed

For extracting contents from the PDF files we will use from_file() method of parser object. So let’s see the description first.

Syntax: parser.from_file(filename, additional)

Parameters:

  • filename: This is location of file, it is opened in rb mode i.e. read binary mode
  • additional: param service: service requested from the tika server, Default value is ‘all’, which results in recursive text content+metadata.
    • ‘meta’ returns only metadata. ‘text’ returns only content.
    • param xmlContent: You can have XML content, default value- False

Return type: dictionary.

Now, Let’s see the python program for Extracting pdf’s data:

Example 1: Extracting contents of the pdf file.

Python3




# import parser object from tike
from tika import parser  
  
# opening pdf file
parsed_pdf = parser.from_file("sample.pdf")
  
# saving content of pdf
# you can also bring text only, by parsed_pdf['text'] 
# parsed_pdf['content'] returns string 
data = parsed_pdf['content'] 
  
# Printing of content 
print(data)
  
# <class 'str'>
print(type(data))


Output:

pdf content

Example 2: Extracting Meta-Data of pdf file.

Python3




# import parser object from tike
from tika import parser  
  
parsed_pdf = parser.from_file("sample.pdf")
  
# ['metadata'] attribute returns 
# key-value pairs of meta-data 
print(parsed_pdf['metadata']) 
  
# <class 'dict'>
print(type(parsed_pdf['metadata']))


Output:

Meta data

Example 3: Extract keys.

Python3




from tika import parser
  
parsed_pdf=parser.from_file("sample.pdf")
  
# Returns keys applicable for given pdf.
print(parsed_pdf.keys())


Output:

keys of the paresed dictionary

Example 4: Know the tika server status.

Python3




from tika import parser
  
# You can also know the 
# status returned from tika 
# server, 200 for success 
parsed_pdf= parser.from_file("sample.pdf")
  
print(parsed_pdf['status'],type(parsed_pdf['status'] ))


Output:

200 <class 'int'>


Similar Reads

Downloading PDFs with Python using Requests and BeautifulSoup
BeautifulSoup object is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. The BeautifulSoup object represents the parsed document as a whole. For most purposes, you can treat it as a Tag object. Requests library i
2 min read
Convert Images to PDFs using Tkinter - Python
Prerequisite: Tkinter, img2pdf Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. In this article
3 min read
Parsing XML with DOM APIs in Python
The Document Object Model (DOM) is a programming interface for HTML and XML(Extensible markup language) documents. It defines the logical structure of documents and the way a document is accessed and manipulated. Parsing XML with DOM APIs in python is pretty simple. For the purpose of example we will create a sample XML document (sample.xml) as bel
2 min read
Argparse VS Docopt VS Click - Comparing Python Command-Line Parsing Libraries
Before knowing about the Python parsing libraries we must have prior knowledge about Command Line User Interface. A Command Line Interface (CLI) provides a user-friendly interface for the Command-line programs, which is most commonly favored by the developers or the programmers who prefer keyboard programming, instead of using the mouse. By buildin
4 min read
Parsing and Processing URL using Python - Regex
Prerequisite: Regular Expression in Python URL or Uniform Resource Locator consists of many information parts, such as the domain name, path, port number etc. Any URL can be processed and parsed using Regular Expression. So for using Regular Expression we have to use re library in Python. Example: URL: https://www.geeksforgeeks.org/courses When we
3 min read
Parsing DateTime strings containing microseconds in Python
Most of the applications require a precision of up to seconds but there are also some critical applications that require nanosecond precision, especially the ones which can perform extremely fast computations. It can help provide insights on certain factors related to time space for the application. Let us see how can we parse DateTime strings that
3 min read
Parsing and converting HTML documents to XML format using Python
In this article, we are going to see how to parse and convert HTML documents to XML format using Python. It can be done in these ways: Using Ixml module.Using Beautifulsoup module.Method 1: Using the Python lxml library In this approach, we will use Python's lxml library to parse the HTML document and write it to an encoded string representation of
3 min read
JSON Parsing Errors in Python
JSON is a widely used format for exchanging data between systems and applications. Python provides built-in support for working with JSON data through its JSON module. However, JSON parsing errors can occur due to various reasons such as incorrect formatting, missing data, or data type mismatches. There are different JSON parsing errors that can oc
6 min read
Command-Line Option and Argument Parsing using argparse in Python
Command line arguments are those values that are passed during the calling of the program along with the calling statement. Usually, python uses sys.argv array to deal with such arguments but here we describe how it can be made more resourceful and user-friendly by employing argparse module. Python Argparse ModuleThe 'argparse' module in Python hel
5 min read
XML parsing in Python
This article focuses on how one can parse a given XML file and extract some useful data out of it in a structured way. XML: XML stands for eXtensible Markup Language. It was designed to store and transport data. It was designed to be both human- and machine-readable.That's why, the design goals of XML emphasize simplicity, generality, and usability
7 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg