Skip to content

PDF

Extract text from a downloaded PDF (pypdf)

A generated PDF is a binary response rather than HTML text. Path.write_bytes() first stores those bytes as a local artifact. PdfReader parses the PDF structure, reader.pages exposes each page object, and page.extract_text() returns the text content pypdf can recover from that page.

Extracted text follows the PDF’s internal text objects rather than necessarily matching its visual layout. Tabs are normalized to spaces before parsing. A regular expression with re.DOTALL then isolates text between two stable labels; DOTALL allows the . wildcard to cross page-extracted newline characters.

from pypdf import PdfReader
from pathlib import Path
import re

# download, then persist the binary response
r = s.get(url=f"{URL}/<PDF_ENDPOINT>", verify=False, timeout=10, proxies=PROXIES)
pdf_file = Path("output.pdf")
pdf_file.write_bytes(r.content)

reader = PdfReader(pdf_file)
pdf_text = ""
for page in reader.pages:
    page_text = page.extract_text()
    pdf_text += page_text + "\n"
pdf_text = pdf_text.replace("\t", " ")

# isolate the text between two stable labels
match = re.search(r"<START_LABEL>\s*(.*?)\s*<END_LABEL>", pdf_text, re.DOTALL)
if match:
    output = match.group(1)
    output = output.strip()
    print(output)
else:
    print("[-] output not found in PDF")

Find by: pdf, pypdf, PdfReader, extract_text, download pdf, certificate, invoice, ssti pdf, cmdi pdf, command output, parse pdf, pages, pure python, write_bytes · Source: CWEE/PDF RCE