Python - Traiter le PDF

Python peut lire les fichiers PDF et imprimer le contenu après en avoir extrait le texte. Pour cela, nous devons d'abord installer le module requis qui estPyPDF2. Voici la commande pour installer le module. Vous devriez avoir pip déjà installé dans votre environnement python.

pip install pypdf2

Une fois l'installation réussie de ce module, nous pouvons lire les fichiers PDF en utilisant les méthodes disponibles dans le module.

import PyPDF2
pdfName = 'path\Tutorialspoint.pdf'
read_pdf = PyPDF2.PdfFileReader(pdfName)
page = read_pdf.getPage(0)
page_content = page.extractText()
print page_content

Lorsque nous exécutons le programme ci-dessus, nous obtenons la sortie suivante -

Tutorials Point originated from the idea that there exists a class of readers who respond better 
to online content and prefer to learn new skills at their own pace from the comforts of their 
drawing rooms.
 
The journey commenced with a single tutorial on HTML in 2006 and elated by the response 
it generated, we worked our way to adding fresh tutorials to our repository which now 
proudly flaunts a wealth of tutorials and allied articles on topics ranging from programming
languages to web designing to academics and much more.

Lecture de plusieurs pages

Pour lire un pdf avec plusieurs pages et imprimer chacune des pages avec un numéro de page, nous utilisons la boucle a avec la fonction getPageNumber (). Dans l'exemple ci-dessous, nous avons le fichier PDF qui a deux pages. Le contenu est imprimé sous deux en-têtes de page distincts.

import PyPDF2
pdfName = 'Path\Tutorialspoint2.pdf'
read_pdf = PyPDF2.PdfFileReader(pdfName)
for i in xrange(read_pdf.getNumPages()):
    page = read_pdf.getPage(i)
    print 'Page No - ' + str(1+read_pdf.getPageNumber(page))
    page_content = page.extractText()
    print page_content

Lorsque nous exécutons le programme ci-dessus, nous obtenons la sortie suivante -

Page No - 1
Tutorials Point originated from the idea that there exists a class of readers who respond better to 
online content and prefer to learn new skills at their own pace from the comforts of their drawing 
rooms. 
Page No - 2
 
The journey commenced with a single tutorial on HTML in 2006 and elated by the response it 
generated, we worked our way to adding fresh tutorials to our repository which now proudly flaunts 
a wealth of tutorials and allied articles on topics ranging from p
rogramming languages to web 
designing to academics and much more.