Disclosure: I built the Apify Actor mentioned near the end of this post.
To read a PDF from a URL in Python, download it with requests, wrap resp.content in io.BytesIO, and pass that to pypdf.PdfReader; then call page.extract_text() on each page. No temp file is needed. Before you trust the result, check three things: the response really is a PDF (it starts with %PDF-), the file is not encrypted, and each page actually has a text layer. A scanned page returns an empty string, not an error.
Below is a small script that does all of that, plus page ranges like 1,5-, tested on two public IRS forms on 1 December 2026. At the end there is a short note on a hosted option, if you would rather not run it yourself.
How do I read a PDF from a URL in Python without saving it?
PdfReader accepts a file path or any binary stream. io.BytesIO(resp.content) is a binary stream, so the PDF never touches the disk:
import io import requests from pypdf import PdfReader resp = requests.get("https://www.irs.gov/pub/irs-pdf/fw9.pdf", timeout=60) reader = PdfReader(io.BytesIO(resp.content)) print(len(reader.pages), reader.pages[0].extract_text()[:40]) That is the whole idea. The old answer on Stack Overflow, Opening pdf urls with pyPdf, uses urllib and the long-gone pyPdf package; the modern library is pypdf (lowercase, the successor of PyPDF2).
Install:
pip install "pypdf[fonts]" requests The [fonts] extra installs fontTools. Why it matters is in the traps section below.
A complete script: URL in, text per page out
This version adds the checks that matter when you run it on links you did not make yourself:
import io import sys import requests from pypdf import PdfReader HEADERS = {"User-Agent": "ExampleResearch admin@example.com"} # use your own def fetch_pdf(url): """Download a PDF into memory and make sure it really is a PDF.""" resp = requests.get(url, headers=HEADERS, timeout=60) resp.raise_for_status() data = resp.content if not data.startswith(b"%PDF-"): ctype = resp.headers.get("Content-Type", "?") raise ValueError(f"not a PDF (Content-Type {ctype}, starts with {data[:15]!r})") return data def parse_pages(spec, page_count): """'1-3,5,10-' -> sorted 1-based page numbers that exist in the file.""" if not spec: return list(range(1, page_count + 1)) wanted = set() for part in spec.replace(" ", "").split(","): if "-" in part: start, end = part.split("-", 1) start = int(start or 1) end = int(end) if end else page_count wanted.update(range(start, end + 1)) elif part: wanted.add(int(part)) return sorted(p for p in wanted if 1 <= p <= page_count) def extract(data, pages=None): reader = PdfReader(io.BytesIO(data)) # bytes in memory, no temp file if reader.is_encrypted: # check this first: with a user password even len(reader.pages) raises raise ValueError("encrypted PDF, skipped") selected = parse_pages(pages, len(reader.pages)) rows = [] for n in selected: page = reader.pages[n - 1] text = page.extract_text() or "" rows.append({ "page": n, "chars": len(text.strip()), "images": len(page.images), "text": text, }) meta = reader.metadata or {} return {"pageCount": len(reader.pages), "title": meta.get("/Title"), "pages": rows} if __name__ == "__main__": source = sys.argv[1] pages = sys.argv[2] if len(sys.argv) > 2 else None if source.startswith("https://"): data = fetch_pdf(source) else: data = open(source, "rb").read() doc = extract(data, pages) print(f"{source} | {len(data)} bytes | {doc['pageCount']} pages | {doc['title']}") for p in doc["pages"]: if p["chars"]: first = p["text"].strip().splitlines()[0] print(f" page {p['page']}: {p['chars']} chars | {first}") elif p["images"]: print(f" page {p['page']}: no text layer, {p['images']} image(s): needs OCR") else: print(f" page {p['page']}: empty page") Save it as pdf_text.py. The extract() function takes bytes, so the same code works for a URL or a local file.
What does the output look like?
Run on 1 December 2026 (Python 3.9.6, pypdf 6.21.4, requests 2.32.5):
python pdf_text.py https://www.irs.gov/pub/irs-pdf/fw9.pdf https://www.irs.gov/pub/irs-pdf/fw9.pdf | 140815 bytes | 6 pages | Form W-9 (Rev. March 2024) page 1: 5727 chars | Form W-9 page 2: 8259 chars | Form W-9 (Rev. 3-2024) Page 2 page 3: 7763 chars | Form W-9 (Rev. 3-2024) Page 3 page 4: 7326 chars | Form W-9 (Rev. 3-2024) Page 4 page 5: 5998 chars | Form W-9 (Rev. 3-2024) Page 5 page 6: 3101 chars | Form W-9 (Rev. 3-2024) Page 6 Only some pages, with a range string (5- means page 5 to the end):
python pdf_text.py https://www.irs.gov/pub/irs-pdf/fw9.pdf "1,5-" https://www.irs.gov/pub/irs-pdf/fw9.pdf | 140815 bytes | 6 pages | Form W-9 (Rev. March 2024) page 1: 5727 chars | Form W-9 page 5: 5998 chars | Form W-9 (Rev. 3-2024) Page 5 page 6: 3101 chars | Form W-9 (Rev. 3-2024) Page 6 Note that pypdf still downloads and parses the whole file; the range only limits which pages you extract text from. If you need the first page of a thousand reports, extraction gets cheaper but the downloads do not.
Common traps when extracting PDF text from URLs
1. The URL returns a web page, not a PDF. Many "PDF links" are landing pages, login walls or error pages served with status 200. Checking Content-Type is not enough on its own, because a server can send a real PDF as application/octet-stream. Checking the first bytes is reliable: every PDF starts with %PDF-. Here is what my script says for the IRS page about the W-9 instead of the file itself:
ValueError: not a PDF (Content-Type text/html; charset=UTF-8, starts with b'<!DOCTYPE html>') Without the check, PdfReader fails further down with a less obvious parsing error.
2. Scanned PDFs return empty text, not an error. A scanned page is just an image, so extract_text() returns an empty string. The pypdf docs say so directly: if a page "appears to contain only an image (e.g., a scanned document)", use OCR software such as Tesseract. To test this, I turned the W-7 into an image-only PDF on macOS (sips -s format png fw7.pdf --out fw7.png, then sips -s format pdf fw7.png --out fw7-scan.pdf) and ran both files:
https://www.irs.gov/pub/irs-pdf/fw7.pdf | 97654 bytes | 1 pages | Form W-7 (Rev. December 2024) page 1: 4280 chars | Form W-7 fw7-scan.pdf | 190150 bytes | 1 pages | None page 1: no text layer, 1 image(s): needs OCR "Zero characters and at least one image" is a simple, useful test for "this page needs OCR", which is also the answer to the old question How do I determine programmatically if a PDF is searchable?. It is a heuristic: a page can hold a tiny logo image and still have no text for other reasons. For the OCR step itself, OCRmyPDF adds a text layer to scanned PDFs using Tesseract, after which the same script works.
3. Encrypted PDFs fail early, and in an odd place. I encrypted a copy of the W-7 with a user password using pypdf's own PdfWriter.encrypt(). Without the is_encrypted check, the script did not even get to extract_text(): just calling len(reader.pages) raised
pypdf.errors.FileNotDecryptedError: File has not been decrypted So check reader.is_encrypted right after opening. If the file is yours and you know the password, reader.decrypt(password) is the documented way in; otherwise skip it.
4. A wall of "fontTools is required" warnings. On a plain pip install pypdf, the W-9 run printed 22 lines to stderr like this one (shortened):
fontTools is required to fully parse the encoding of a CFF Type1 font in font dictionary {'/BaseFont': '/OKAJSW+HelveticaNeueLTStd-Roman', ... After pip install fonttools (or the pypdf[fonts] extra) the warnings were gone. On these IRS forms the extracted text was identical either way (I compared a hash of the full text), but on other fonts the encoding can matter, so install it rather than silence the log.
5. Different extractors give different text. pypdf returned 4,280 characters for the W-7 page; a pdf.js-based extractor reported 4,217 for the same file. The words are the same; spacing and line breaks differ. If you compare runs over time, compare with the same library and version. If you need positioned text, pypdf also has extract_text(extraction_mode="layout").
6. Python version. The current pypdf release (7.2.0) needs Python 3.10 or newer. On Python 3.9, pip installs the 6.x line, which is what I used here; the API in this post is the same.
What if I have hundreds of PDF URLs, or want it scheduled?
For a few files, the script above is all you need. For a long list, you will want polite pacing per website, retries for flaky servers, a record of which URLs failed and why, and somewhere to store the output.
I built an Apify Actor for that: PDF to Text Extractor – Page Text & Metadata. You give it a list of direct PDF links and an optional page range (1-3,5,10-), and it returns one row per PDF with the full text, a pages array (pageNumber, text, charCount), pageCount, wordCount and document properties such as title, author, creationDate and hasForm. It reads files with pdf.js, not pypdf. Two ready-made examples: Extract Text from IRS Tax Form PDFs (W-9, W-4, W-7) and Extract the First Page of PDFs to Text in Bulk.
{ "urls": [ "https://www.irs.gov/pub/irs-pdf/fw9.pdf", "https://www.irs.gov/pub/irs-pdf/fw7.pdf" ], "pages": "1-2", "maxItems": 100 } Cost and limits, from the README:
- US$3.50 per 1,000 PDFs plus US$0.0005 per run start, whatever the page count. Apify's free plan includes US$5 of usage a month, about 1,400 PDFs.
- Files that return no text are skipped and not charged: encrypted PDFs, non-PDFs, scanned PDFs without a text layer, files over 50 MB, download errors. The run summary lists each one with the reason.
- No OCR. Scanned pages are skipped, same as trap 2 above; run OCR first if you need them.
- No crawling: the URL must be the PDF itself. A web page that links to a PDF is skipped, and the link is not followed.
- Encrypted and password-protected files are never unlocked.
- At most 2 requests per second per website; one run lasts at most about 55 minutes. The text in one row is capped at 3 MB; use page ranges for very long documents.
- Tables come out as lines of text, not rows and columns.
It is not affiliated with or endorsed by the IRS, Adobe, Mozilla or the pypdf project. Only process files you have the right to use.
FAQ
Can pypdf open a PDF directly from a URL?
Not by itself: PdfReader takes a path or a binary stream, not a URL. Download the bytes with requests (or urllib), wrap them in io.BytesIO, and pass that. Nothing is written to disk.
How do I extract text from specific pages only?
Index reader.pages with zero-based numbers, for example reader.pages[0] for page 1. The parse_pages() helper above turns a string like 1,5- into the page numbers that exist in the file and ignores pages the file does not have.
Why does extract_text() return an empty string?
Usually the page is a scanned image with no text layer. Check len(page.images): if the text is empty and the page has at least one image, it most likely needs OCR. Less often, the PDF uses fonts without a proper Unicode mapping, which gives garbled text rather than empty text.
Does pypdf do OCR?
No. pypdf reads the text layer that is already in the file. The pypdf documentation points to OCR software such as Tesseract for scanned documents; OCRmyPDF wraps Tesseract and writes the text layer back into the PDF.
Can I read an encrypted PDF?
If it has a user password, every page access raises FileNotDecryptedError until you call reader.decrypt(password) with the right password. In my test, a file encrypted with an empty user password (owner password only) opened without any call and returned the same 4,280 characters. Whether you are allowed to process a restricted file is a separate question from whether the library can.
Is extract_text() the same as copying text in a PDF viewer?
Close, but not identical. Each tool decides where to put spaces and line breaks on its own, which is why pypdf and pdf.js gave different character counts for the same W-7 page.
What is the messiest PDF you have had to pull text from, and did OCR or a different extractor fix it?
Disclosure: I built the Apify Actor mentioned in this post.

