Ask Anvil

Answers to questions about automating PDFs, e-signatures, Webforms, and other paperwork problems.
PDFs
Categories

Why are the links in my HTML-to-PDF output broken, and how do I fix them?

You convert an HTML page to PDF, the links look right on screen, and then the ones that use relative paths do nothing useful in the PDF. The absolute ones work fine.

The cause: relative hrefs have no base

In a browser, href="/pricing" resolves against the page's address. A PDF has no such address, so the renderer has to be told what to resolve against. If you hand WeasyPrint a string of HTML and give it no base URL, it cannot do that. Its docs note that with HTML(string=foo), relative URLs will be invalid if base_url is not provided. Here is the fix next to the failing case:

from weasyprint import HTML

html = '<p><a href="/pricing">Pricing</a> and <a href="https://example.com/terms">Terms</a></p>'

# Relative href with no base_url: WeasyPrint cannot resolve it
HTML(string=html).write_pdf("no-base.pdf")

# Relative href with base_url: it becomes an absolute URI in the PDF
HTML(string=html, base_url="https://example.com/").write_pdf("with-base.pdf")

In the first file the link target is stored as the bare string /pricing, which has no host to open. In the second it is stored as https://example.com/pricing.

How to confirm it in your own PDF

Read the link annotations and look at the targets:

from pypdf import PdfReader

reader = PdfReader("no-base.pdf")
for annot in reader.pages[0].get("/Annots", []):
    action = annot.get_object().get("/A", {})
    print(action.get("/URI"))

Any target that does not start with a scheme such as https:// is the problem.

Caveats

Set base_url on the HTML() constructor, not on write_pdf(). The same idea applies to other HTML-to-PDF tools that take a string of HTML, so check how yours sets its base URL. The simplest way to avoid the whole class of bug is to write absolute URLs into the template in the first place.

Back to All Questions

The fastest way to build software for documents

Anvil Document SDK is a comprehensive toolbox for product teams launching document flows where PDF filling, signing, and complex conditional scenarios are necessary.
Explore Anvil
Anvil Webforms
Marketing Mode