Build your audiobook from any PDF with Python

Stokry - Apr 28 '21 - - Dev Community

Did you know that you can build your audiobook with Python from any PDF? Sounds cool, isn't it?
In this quick tutorial, I will show you how to build an audiobook with Python.

In our example, we will be using PyPDF2 and pyttsx3.

PyPDF2 is a pure-Python library built as a PDF toolkit. It is capable of:

  • extracting document information (title, author, …)
  • splitting documents page by page
  • merging documents page by page
  • cropping pages
  • merging multiple pages into a single page
  • encrypting and decrypting PDF files
  • and more!

By being Pure-Python, it should run on any Python platform without any dependencies on external libraries. It can also work entirely on StringIO objects rather than file streams, allowing for PDF manipulation in memory. It is therefore a useful tool for websites that manage or manipulate PDFs.

Pyttsx3 is a text-to-speech conversion library in Python. Unlike alternative libraries, it works offline, and is compatible with both Python 2 and 3.

Let's jump to the code:

First we need to import our dependencies:

import PyPDF2
import pyttsx3
Enter fullscreen mode Exit fullscreen mode

Then we need to open our pdf

pdf_file =  open('test.pdf', 'rb')
Enter fullscreen mode Exit fullscreen mode

where mode='rb' is used for open the file in binary format for reading.

We define PDF file reader:

pdf_read = PyPDF2.PdfFileReader(pdf_file)
Enter fullscreen mode Exit fullscreen mode

Then we need to give number of pages in PDF file:

num_pages = pdf_read.numPages
Enter fullscreen mode Exit fullscreen mode

Then we define our init and we also can do a print :

engine = pyttsx3.init()
print('Read PDF')
Enter fullscreen mode Exit fullscreen mode

After that, we define our loop that will read all pages one by one:

for n in range(0, num_pages):
    page = pdf_read.getPage(n)
    text = page.extractText()
    x = n + 1
    print(f"Reading page {x}/{num_pages}.")
    engine.say(text)
    engine.save_to_file(text, 'book.mp3')
    engine.runAndWait()
Enter fullscreen mode Exit fullscreen mode

This part of the code retrieves a page by the number from this PDF file, extracts text from the page, and reads text from the page. Also we save to mp3 file.

Thank you all.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .