Python
Every class, method and function in the prasasti Python package, with the errors each one raises.
import prasasti
doc = prasasti.Document("report.pdf")
pages = doc.extract_text(threads=0)Install with pip install prasasti. Wheels ship for Linux (x86_64, aarch64), macOS (Intel, Apple silicon) and Windows (x64). Type hints are included.
Document
prasasti.Document(source, password=None)Opens a document and detects its format from the content.
source: a path (stroros.PathLike), or the file's contents asbytesorbytearray.password: the user or owner password of an encrypted PDF. Leave it out when the file has an empty user password.
| Property | Type | What it holds |
|---|---|---|
format | str | "pdf" or "txt" |
page_count | int | Number of pages. len(doc) gives the same number. |
is_encrypted | bool | True when the file was encrypted and opened with the password |
was_recovered | bool | True when the file was damaged and prasasti rebuilt its structure |
metadata | dict[str, str] | PDF document info (Title, Author, ...). For a text file, {"Encoding": "Utf8"} and so on. |
| Method | Returns | What it does |
|---|---|---|
extract_text(threads=1) | list[str] | The text of every page, in reading order |
text(threads=1) | str | Every page joined by a form feed (\f) |
page_text(index) | str | The text of one page, counting from 0 |
threads=0 uses every core. Any other number uses that many threads.
Functions
For a quick one-off, these open the file, do one thing and close it.
text = prasasti.extract_text("report.pdf", password=None, threads=1) # str, pages joined by \f
pages = prasasti.page_count("report.pdf", password=None) # int
print(prasasti.__version__) # "0.1.0"Both take the same source as Document, so bytes work too.
Threads and the GIL
prasasti releases the GIL while it opens files and extracts text. Two Python threads working on two documents run at the same time, and an async app can hand the work to asyncio.to_thread without blocking the event loop.
import asyncio
import prasasti
async def read(path):
return await asyncio.to_thread(prasasti.extract_text, path)Errors
| Exception | When |
|---|---|
OSError | The file can't be read |
ValueError | The file can't be parsed, the password is wrong, or the format isn't supported |
IndexError | page_text got a page number past the last page |
TypeError | source is neither a path nor bytes |
try:
doc = prasasti.Document("locked.pdf")
except ValueError as e:
print(e) # encrypted: ...