Why are my links not clickable?
Because you drew the document with c.Draw. That path discards link annotations, so the
anchors keep their blue underline from the browser’s stylesheet and do nothing when clicked.
Measured on a page with three anchors, an https URL, a mailto: and an in-page #top:
| Path | Links in the output |
|---|---|
Document.WriteToFile | 3 |
GetPdfPages + c.AddPage | 3 |
c.Draw(document) | 0 |
The fix
Take the rendered pages instead of drawing the document:
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
pages, err := doc.GetPdfPages(ctx)
if err != nil {
return err
}
for _, p := range pages {
if err := c.AddPage(p); err != nil {
return err
}
}If the converted HTML is the whole document, doc.WriteToFile("out.pdf") is shorter and keeps
the links too.
Why it happens
c.Draw turns each rendered page into a creator.Block with
creator.NewBlockFromPage. A block holds the page’s content stream, and annotations are not
part of the content stream: they live in the page’s /Annots array beside it. Flattening the
page keeps the marks that draw the link and drops the object that makes it a link.
Adding a document to a creator.Chapter goes through the same code, so links are lost there
as well.
What you give up by switching
c.Draw is the only path that flows the rendered output inline, so creator content can sit on
the same page as the HTML. GetPdfPages hands you whole pages, and anything you add before or
after lands on its own page.
If you need both clickable links and a paragraph on the same sheet as the HTML, put the paragraph in the HTML. That is the only combination that gets both.
Related things that are not this
If the links are missing from the PDF entirely rather than present but dead, the anchors were probably added by JavaScript after the DOM loaded. See why is my JavaScript content blank?
If they are clickable but point somewhere useless, check whether they were relative.
<a href="page2.html"> becomes a link to page2.html, which does not exist once the PDF has
left the directory it was built from.
Links covers all of this with the example.