The Wayback Machine - https://web.archive.org/web/20240930190802/https://www.geeksforgeeks.org/check-if-two-pdf-documents-are-identical-with-python/
Open In App

Check if two PDF documents are identical with Python

Last Updated : 17 May, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python is an interpreted and general purpose programming language. It is a Object-Oriented and Procedural paradigms programming language. There are various types of modules imported in python such as difflib, hashlib.

Modules used:

  • difflib : It is a module that contains function that allows to compare set of data.
  • SequenceMatcher : It is used to compare pair of input sequences.

Function Used:

  • hash_file ( string $algo , string $filename , bool $binary = false ): It is a function which has the hash of a file.
  • object.hexdigest(): It is a function which returns string.
  • fileObject.read(size): It is a function that returns the specified number of bytes of a file.

Approach

  • Import module
  • Declare a function with 2 arguments which is for file.
  • Declare two objects for hashlib.sha1()
  • Open files
  • Read the file by breaking the line into smaller chunks
  • Now return both file such as h1.hexdigest() which is of 160 bits.
  • Use hash_file() function to store the hash of a file.
  • Compare and generate appropriate message

Files in Use

comapre pdf 1

Program:

Python3




import hashlib
from difflib import SequenceMatcher
  
  
def hash_file(fileName1, fileName2):
  
    # Use hashlib to store the hash of a file
    h1 = hashlib.sha1()
    h2 = hashlib.sha1()
  
    with open(fileName1, "rb") as file:
  
        # Use file.read() to read the size of file
        # and read the file in small chunks
        # because we cannot read the large files.
        chunk = 0
        while chunk != b'':
            chunk = file.read(1024)
            h1.update(chunk)
              
    with open(fileName2, "rb") as file:
  
        # Use file.read() to read the size of file a
        # and read the file in small chunks
        # because we cannot read the large files.
        chunk = 0
        while chunk != b'':
            chunk = file.read(1024)
            h2.update(chunk)
  
        # hexdigest() is of 160 bits
        return h1.hexdigest(), h2.hexdigest()
  
  
msg1, msg2 = hash_file("pd1.pdf ", "pd1.pdf")
  
if(msg1 != msg2):
    print("These files are not identical")
else:
    print("These files are identical")


Output

These files are not identical



Previous Article
Next Article

Similar Reads

Creating PDF Documents With Python
In this article, we will be learning how to create PDFs in Python. A very famous module named pypdf2 is used to modify and read existing pdfs but its major disadvantage is that it cannot create new pdf files. So Today we are looking to learn about another python module named report lab that helps us to create new pdf files and edit our heart's cont
5 min read
Python | Check whether two lists are circularly identical
Given two lists, check if they are circularly identical or not. Examples: Input : list1 = [10, 10, 0, 0, 10] list2 = [10, 10, 10, 0, 0] Output : Yes Explanation: yes they are circularly identical as when we write the list1 last index to second last index, then we find it is circularly same with list1 Input : list1 = [10, 10, 10, 0, 0] list2 = [1, 1
5 min read
Python List Equality | Program to check if two given matrices are identical
We are given two square matrices of same order. Check if two given matrices are identical. Examples: Input : A = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] B = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] Output: Matrices are identical We have existing solution for this problem please refer C Program to check if two give
3 min read
Python | Check if two lists are identical
This article deals with the task of ways to check if two unordered list contains exact similar elements in exact similar position, i.e to check if two lists are exactly equal. This is quite a useful utility and can be used in day-day programming. Method 1: Using list.sort() and == operator sort() coupled with == operator can achieve this task. We f
7 min read
Send PDF File through Email using pdf-mail module
pdf_mail module is that library of Python which helps you to send pdf documents through your Gmail account. Installing Library This module does not come built-in with Python. You need to install it externally. To install this module type the below command in the terminal. pip install pdf-mail Function of pdf_mail This module only comes with a singl
2 min read
Create XML Documents using Python
Extensible Markup Language(XML), is a markup language that you can use to create your own tags. It was created by the World Wide Web Consortium (W3C) to overcome the limitations of HTML, which is the basis for all Web pages. XML is based on SGML - Standard Generalized Markup Language. It is used for storing and transporting data. XML doesn’t depend
3 min read
Count the number of Documents in MongoDB using Python
MongoDB is a document-oriented NoSQL database that is a non-relational DB. MongoDB is a schema-free database that is based on Binary JSON format. It is organized with a group of documents (rows in RDBMS) called collection (table in RDBMS). The collections in MongoDB are schema-less. PyMongo is one of the MongoDB drivers or client libraries. Using t
2 min read
Working with Documents - Python .docx Module
Prerequisite: Working with .docx module Word documents contain formatted text wrapped within three object levels. The lowest level- run objects, middle level- paragraph objects, and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the pytho
2 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
Python | Pandas TimedeltaIndex.identical
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas TimedeltaIndex.identical() function determines if two Index objects contain the same elements. If the two objects under considera
2 min read
Python | Pandas Index.identical()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Index.identical() function determine if two Index objects contains the same elements. If they contain the same elements then the
2 min read
Python | Identical Consecutive Grouping in list
Sometimes, while working with Python list we can have problems in which we need to perform grouping. There can be a particular problem in which we need to group consecutive occurring elements. Having solution to this problem is useful. Let's discuss the certain way in which this can be done. Method 1: Using groupby() + list comprehension This task
8 min read
Update all Documents in a Collection using PyMongo
MongoDB is an open-source document-oriented database. MongoDB stores data in the form of key-value pairs and is a NoSQL database program. The term NoSQL means non-relational. PyMongo contains tools which are used to interact with the MongoDB database. Now let's see how to update all the documents in a collection. Updating all Documents in a Collect
3 min read
Get all the Documents of the Collection using PyMongo
To get all the Documents of the Collection use find() method. The find() method takes a query object as a parameter if we want to find all documents then pass none in the find() method. To include the field in the result the value of the parameter passed should be 1, if the value is 0 then it will be excluded from the result. Note: If we pass no pa
1 min read
Outer join Spark dataframe with non-identical join column
In PySpark, data frames are one of the most important data structures used for data processing and manipulation. The outer join operation in PySpark data frames is an important operation to combine data from multiple sources. However, sometimes the join column in the two DataFrames may not be identical, which may result in missing values. In this a
4 min read
Check if a string exists in a PDF file in Python
In this article, we'll learn how to use Python to determine whether a string is present in a PDF file. In Python, strings are essential for Projects, applications software, etc. Most of the time, we have to determine whether a string is present in a PDF file or not. Here, we'll discuss how to check f a string exists in a PDF file in Python. Here, w
2 min read
Read a Particular Page from a PDF File in Python
Document processing is one of the most common use cases for the Python programming language. This allows the language to process many files, such as database files, multimedia files and encrypted files, to name a few. This article will teach you how to read a particular page from a PDF (Portable Document Format) file in Python. Method 1: Using Pymu
4 min read
Python Convert Html to PDF
Convert HTML/webpage to PDF There are many websites that do not allow to download the content in form of pdf, they either ask to buy their premium version or don't have such download service in form of pdf. Conversion in 3 Steps from Webpage/HTML to PDF Step1: Download library pdfkit $ pip install pdfkit Step2: Download wkhtmltopdf For Ubuntu/Debia
1 min read
Convert Excel to PDF Using Python
Python is a high-level, general-purpose, and very popular programming language. Python programming language (latest Python 3) is being used in web development, Machine Learning applications, along with all cutting-edge technology in Software Industry. In this article, we will learn how to convert an Excel File to PDF File Using Python Here we will
2 min read
How to Convert Image to PDF in Python?
img2pdf is an open source Python package to convert images to pdf format. It includes another module Pillow which can also be used to enhance image (Brightness, contrast and other things) Use this command to install the packages pip install img2pdf Below is the implementation: Image can be converted into pdf bytes using img2pdf.convert() functions
1 min read
Python | Reading contents of PDF using OCR (Optical Character Recognition)
Python is widely used for analyzing the data but the data need not be in the required format always. In such cases, we convert that format (like PDF or JPG, etc.) to the text format, in order to analyze the data in a better way. Python offers many libraries to do this task. There are several ways of doing this, including using libraries like PyPDF2
6 min read
Save multiple matplotlib figures in single PDF file using Python
In this article, we will discuss how to save multiple matplotlib figures in a single PDF file using Python. We can use the PdfPages class's savefig() method to save multiple plots in a single pdf. Matplotlib plots can simply be saved as PDF files with the .pdf extension. This saves Matplotlib-generated figures in a single PDF file named Save multip
3 min read
Convert Text and Text File to PDF using Python
PDFs are one of the most important and widely used digital media. PDF stands for Portable Document Format. It uses .pdf extension. It is used to present and exchange documents reliably, independent of software, hardware, or operating system. Converting a given text or a text file to PDF (Portable Document Format) is one of the basic requirements in
3 min read
Python | Scipy stats.halfgennorm.pdf() method
With the help of stats.halfgennorm.pdf() method, we can get the value of probability density function by using stats.halfgennorm.pdf() method. The probability density function for halfgennorm is Syntax : stats.halfgennorm.pdf(x, beta) Return : Return the value of probability density function. Example #1 : In this example we can see that by using st
1 min read
Python | Scipy stats.hypsecant.pdf() method
With the help of stats.hypsecant.pdf() method, we can get the value of probability density function by using stats.hypsecant.pdf() method. The probability density function for hypsecant is Syntax : stats.hypsecant.pdf(x, beta) Return : Return the value of probability density function. Example #1 : In this example we can see that by using stats.hyps
1 min read
Exporting PDF Data using Python
Sometimes, we have to extract data from PDF. we have to copy & paste the data from PDF. It is time-consuming. In Python, there are packages that we can use to extract data from a PDF and export it in a different format using Python. We will learn how to extract data from PDFs. Extracting Text With PDFMiner PDFMiner is a text extraction tool for
2 min read
Merge PDF stored in Remote server using Python
Prerequisites: Working with PDF files in Python There are many libraries for manipulating PDF files in Python but all are using when that all PDF files already downloaded in your local machine. But what if your target PDF files are in Remote server, you have only URLs of files and no required download in your machine or compute server. Here We will
2 min read
PDF Redaction using Python
So, let's just start with what exactly does Redaction mean. So, Redaction is a form of editing in which multiple sources of texts are combined and altered slightly to make a single document. In simple words, whenever you see any part in any document which is blackened out to hide some information, it is known as Redaction. To perform the same task
4 min read
Build an Application to extract URL and Metadata from a PDF using Python
The PDF (Portable Document Format) is the most common use platform-independent file format developed by Adobe to present documents. There are lots of PDF-related packages for Python, one of them is the pdfx module. The pdfx module is used to extract URL, MetaData, and Plain text from a given PDF or PDF URL. Features: Extract references and metadata
3 min read
Add Watermark to PDF using PyPDF4 in Python
We are quite familiar with the most commonly used data format of PDF (Portable Document Format), with an extension .pdf. While the PDF was originally invented by Adobe, though maintained by ISO now, is used to present and exchange documents across various OSs. Installation It could be installed using pip or conda depending on whether you are using
2 min read