Overview
In this tutorial, you will learn how to an audio book from a given PDF in Python. We will be using the PyPDF2 module for exctracting the text from PDF files. pyttsx3 module for text to speech conversion.
Installing the module
To install the PyPDF2 and pyttsx3 module and some other related dependencies, we can use the pip command:
pip install pypdf2
pip install pyttsx3
Explaination
- Import all the libraries
- Create a PDF file object
- Create a PDF reader object
- Print number of pages in PDF file
- Convert Text to speech using pyttsx3
- Count the number of pages and run the loop till the page you want to read.
The Code
import pyttsx3
import PyPDF2
book = open('sample.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(book)
pages = pdfReader.numPages
print(f"Total Pages: {pages}")
print("\n\n")
speaker = pyttsx3.init()
for num in range(1, pages):
page = pdfReader.getPage(num)
text = page.extractText()
print(f"Page: {num}\n")
print(text)
print("\n\n")
speaker.say(text)
speaker.runAndWait()