Scheduled broken-link and redirect checks that tell you the moment a link breaks — linkbruno.com
PDFs are where links go to die quietly. A whitepaper from 2022, a product manual, a conference handout, a signed contract with a "see our terms at..." line. The file gets downloaded, emailed, attached to tickets and stored in shared drives for years. Every URL inside it is frozen at the moment it was exported.
And almost no link checker looks inside them. Crawlers follow HTML links, see a .pdf, check that the PDF itself returns 200, and move on. The 40 links inside it never get tested.
Here's a short Python script that opens every PDF in a folder, pulls out the links, checks them, and tells you which page each broken one is on.
Two kinds of links in a PDF
A PDF can contain a URL in two different ways, and you need both:
-
Link annotations. The clickable areas. In the file, each page has an
/Annotsarray; link annotations have/Subtype /Linkand an action dictionary with a/URI. This is what you get when you export a document with hyperlinks from Word, Google Docs or LaTeX. - Bare URLs in the text. A URL typed as plain text, which some PDF viewers make clickable on the fly and others don't. Readers still copy and paste them.
The script extracts both.
Setup
python3 -m venv .venv && . .venv/bin/activate
pip install pypdf requests
The script
#!/usr/bin/env python3
"""Find broken links in every PDF in a folder."""
import re, sys, pathlib
import requests
from pypdf import PdfReader
URL_RE = re.compile(r'https?://[^\s<>"\)\]]+')
session = requests.Session()
session.headers["User-Agent"] = "pdf-link-check/1.0"
cache = {}
def links_in(path):
reader = PdfReader(path)
for n, page in enumerate(reader.pages, 1):
for annot in page.get("/Annots") or []:
a = annot.get_object()
if a.get("/Subtype") != "/Link":
continue
action = a.get("/A")
uri = action.get_object().get("/URI") if action else None
if uri:
yield n, str(uri), "link"
text = page.extract_text() or ""
for m in URL_RE.finditer(text):
yield n, m.group(0).rstrip(".,;:"), "text"
def status(url):
if url in cache:
return cache[url]
try:
r = session.head(url, allow_redirects=True, timeout=15)
if r.status_code in (403, 405) or r.status_code >= 500:
r = session.get(url, allow_redirects=True, timeout=15, stream=True)
result = r.status_code
except requests.RequestException as e:
result = type(e).__name__
cache[url] = result
return result
def main(folder):
bad = 0
for pdf in sorted(pathlib.Path(folder).rglob("*.pdf")):
seen = set()
for page, url, kind in links_in(pdf):
if (page, url) in seen:
continue
seen.add((page, url))
s = status(url)
if not (isinstance(s, int) and s < 400):
bad += 1
print(f"{pdf} p.{page} [{kind}] {s} {url}")
print(f"{bad} broken link(s)")
return 1 if bad else 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1] if len(sys.argv) > 1 else "."))
Run it on a folder:
python3 pdf_links.py ./downloads
downloads/whitepaper-2022.pdf p.3 [link] 404 https://www.example.com/resources/benchmark-2022
downloads/whitepaper-2022.pdf p.11 [text] ConnectionError https://beta.example-partner.io/signup
downloads/user-manual-v4.pdf p.27 [link] 404 https://docs.example.com/v4/setup
3 broken link(s)
Things the script handles (and why)
A cache of URLs. The same link often appears on every page footer. Checking it once instead of 40 times is faster and polite to the server.
HEAD, then GET as a fallback. HEAD is fast, but some servers return 403 or 405 for it, or misbehave. Retrying with GET (streamed, so it doesn't download whole files) avoids false positives.
Redirects are followed. A link that redirects to a working page isn't broken. If you want to find redirecting links too (they often point to the homepage after a site migration), record r.history and report anything with more than one hop.
Trailing punctuation. Text extraction often captures the full stop after a URL at the end of a sentence. The rstrip removes it.
Limitations to know about
- Text extraction isn't perfect. URLs that wrap onto a second line in the PDF come out as two fragments. If a text URL looks truncated in the report, check the page by eye.
-
Some links aren't URI actions. Links to other pages in the same document (
/GoTo) and links to other files (/GoToR) are skipped here, which is usually what you want. - Scanned PDFs have no text. If a document is just images, there are no links to find without OCR.
- Rate limits and bot protection. Sites that block automated requests will show up as 403s. Treat those as "check by hand", not "broken".
A PDF can't be fixed once it's on someone's laptop, but the URLs inside it can be kept alive. linkbruno.com keeps checking the pages those documents point to, on a schedule, so a docs move that breaks the links in last year's manual gets noticed before readers do.
What to do with the results
You usually can't fix a PDF that's already out in the world. You can fix the destination:
- Add a redirect from the dead URL to its current equivalent. This fixes every copy of the PDF at once, including the ones in people's inboxes. It's the most valuable thing you can do with this report.
- Re-export and re-upload the PDF if it's still being distributed from your site, so new downloads get working links.
-
Use URLs you control in future documents. A short, stable path on your own domain (
example.com/go/benchmark) that redirects to wherever the content lives today is far more durable than a deep link into a docs site that will be restructured.
That last point is the one that pays off long term. Then keep the destination URLs on your regular link checks, with linkbruno.com or your own scheduled script.
Related reading
- Check links in Markdown docs with a 60-line Python script
- How to find broken outbound links and replace them (using the Wayback Machine)
- How to check a website for broken links for free (5 methods that actually work)
- Switching static site generators (Jekyll to Hugo, Gatsby to Astro, anything to anything)? A 12-point checklist so your URLs survive
Do you check the links inside your PDFs at all? I'm curious how many teams have a list of the URLs printed in documents they've sent out.
Top comments (4)
This is a really useful script — and the distinction you draw at the start is the important one. Most tools only read the link annotations, so a URL typed as plain text in the body just never gets checked at all. Extracting both, like you do, is what makes this actually complete.
The part I'd underline is your "check by hand" bucket for 403s. I built a PDF extractor recently (pdf-slice) and the lesson that kept coming back was the same one you land on here: a tool that quietly drops the uncertain cases is worse than one that flags them. A 403, a URL split across two lines, or a scanned page with no text at all should come back as "unknown, needs a human", not as "fine" and not as "broken". Silent wrong answers are how bad PDFs stay in circulation for years.
Your point about fixing the destination, not the file, is also spot on — once a PDF is downloaded and forwarded around, the redirect is the only fix that reaches every copy. Using short stable URLs you control in future documents is the long-term version of the same idea.
To answer your closing question: I don't think most teams have that list at all, which is exactly why the links inside PDFs go stale unnoticed.
— Kamal
You're right, and the script as posted doesn't quite live up to that: a 403 that survives the GET retry still gets printed right next to the real 404s. Splitting the output into "broken" and "check by hand" (403s, 429s, timeouts, and text URLs that look cut off at a line wrap) would make it do what the post says it should. Did scanned pages with no text layer come up often in the PDFs you were working with?
Often enough that I had to design around them. The extractor I built (pdf-slice) runs two routes — native text layer first, OCR when the page comes back thin — precisely because image-only pages are common in real collections: scanned contracts, reports exported as images, that whole class. And a page that yields nothing from either route gets labelled low-confidence rather than returned as an empty success, because an empty result and a verified-empty document are different facts. I benchmarked a popular converter that returned a completely empty file for a scanned PDF — exit code 0, no warning. That's the same failure as a 403 printed as 'broken', just at the other end: the tool states a conclusion it didn't earn.
On your split: I'd add a third bucket next to 'broken' and 'check by hand' — 'not checked'. A scanned page and a URL split across a line wrap aren't uncertain results, they're missing coverage, and folding them into 'check by hand' hides how much of the document was actually verified. Reporting the counts per bucket (checked / uncertain / not checked) is what turns the output from a list into a measurement. The wrapped URLs especially: please don't auto-join the fragments — a guessed URL that returns 200 is worse than an honest 'unknown'.
Yes — often, and it is the case that quietly breaks tools like this. In the corpora I have worked with (bank statements, scanned contracts, older manuals), a meaningful share of pages have no text layer at all, so the extractor finds nothing and the page reports as 'no links' — which reads as 'no broken links' unless the tool says otherwise. The rule I use in pdf-slice: a page with zero extractable text is never a pass. It is a third bucket next to your two — 'not checked: no text layer, needs OCR'. Broken / check-by-hand / not-checked keeps the report honest; it is the difference between a link checker and a link guesser. If you add the split, I would put the not-checked count in the summary line, not a footnote — that is the number people actually need.