- A useful knowledge base must handle multiple document types.
- PDFs vary widely: some contain selectable text, others are scanned images that require OCR.
- This parser extracts selectable text (when present), splits it into context-aware chunks, and emits structured metadata to feed an embedding / vector store pipeline.
PyPDF2 extracts selectable text from PDF files. If your PDF is a scanned image (no selectable text), add an OCR preprocessing step such as Tesseract with pytesseract before feeding the text into the chunker.
pdf_parser.py — reusable PDFParser class
This module provides a compact, reusable class that:- extracts selectable text from PDFs,
- splits text into chunks optimized for RAG ingestion,
- returns structured metadata for each chunk,
- optionally writes a human-readable dump for inspection.
pdf_parser.py.
- The parser raises a clear
FileNotFoundErrorif the PDF path is invalid. PyPDF2.PdfReader().pages[i].extract_text()can returnNonefor pages — these are skipped to avoid errors.- The text splitter prioritizes paragraph and sentence boundaries before falling back to spaces, producing readable chunks for embeddings.
- For scanned/image-only PDFs, add OCR beforehand (see the warning below).
main.py — examples and usage
Createmain.py to demonstrate typical usage of the PDFParser. This script shows:
- parsing and printing a summary,
- saving chunked results to JSON for downstream ingestion,
- writing a human-readable text dump,
- comparing chunking parameter impacts on chunk count.
main.py.
Sample terminal output (cleaned)
This is an example of the console output when runningpython main.py with a small sample PDF that produces 3 chunks.
Final notes
- This parser processes selectable text only. For scanned PDFs you must run OCR before parsing.
- Tune
chunk_sizeandchunk_overlapfor your model/embedding limits — smaller chunks increase recall but reduce context; larger chunks increase context but consume more embedding tokens. - The
chunks.jsonfile is ready to be embedded and stored in your vector DB for RAG use cases.
If a PDF contains no selectable text (for example, scanned pages), PyPDF2 will not extract the content. In that case, perform OCR (Tesseract + pytesseract or a cloud OCR service) to produce text before using this parser. Consider adding an automatic OCR fallback for production pipelines.
- Adding page-level metadata (page numbers, section headings if extractable).
- Detecting image-only pages and automatically running OCR.
- Integrating directly with an embeddings pipeline (e.g., to automatically insert chunks into a vector store).