AI Hints
Home›RAG Tutorial›Loading Documents
RAG · Lesson 15 of 120

Loading PDFs

Page by page.

⏱ 2 min read▶ Video at 14:29🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

Lots of company knowledge lives in PDFs, like manuals and reports. We can pull the text out of a PDF, one page at a time, and keep the page number as metadata.

Loading PDFs
From the video: Loading PDFs
  • Manuals and reports
  • Text from each page
  • Page numbers kept

Reading the e-bike manual

PDF reader opens the Volt Pro owner's manual. For each page, extract text pulls out the words. We make one document per page, with the page number in its metadata. Run it. Four pages, each with its own text.

load_pdf.pypython
from pypdf import PdfReader
from langchain_core.documents import Document

reader = PdfReader("data/rag/volt_pro_manual.pdf")
pages = [
    Document(page_content=page.extract_text(), metadata={"source": "volt_pro_manual.pdf", "page": i + 1})
    for i, page in enumerate(reader.pages)
]
for p in pages:
    print(p.metadata["page"], "|", p.page_content[:60].replace("\n", " "))
Output
1 | Volt Pro Owner's Manual Northwind Bikes, edition 3, January
2 | 1. Before your first ride Check the tyre pressure is between
3 | 2. Assist modes The Volt Pro has four assist modes: Eco, Tou
4 | 3. Cleaning Clean the bike with a soft brush and warm soapy

PDF gotchas

PDFs are made for printing, not reading by computers. Text can come out with odd characters, broken lines, headers and footers repeated on every page, and tables scrambled. Look closely at page two's output. The f i in first became one special character. We'll clean that next.

keyvalue
Odd charactersligatures
Broken linesmid-sentence
Headers, footersrepeated
Tablesscrambled

Summary

Read PDFs page by page, and keep the page number as metadata. Always check the extracted text. Next, cleaning text.

Key takeaways
  • PdfReader
  • extract_text
  • page number
Next up: Cleaning Text — tidy before you split