Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 28, 2021 11:45 am GMT

Build your audiobook from any PDF with Python

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 PyPDF2import pyttsx3

Then we need to open our pdf

pdf_file =  open('test.pdf', 'rb')

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)

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

num_pages = pdf_read.numPages

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

engine = pyttsx3.init()print('Read PDF')

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()

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.


Original Link: https://dev.to/stokry/build-your-audiobook-from-any-pdf-with-python-3807

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To