Eric
Eric

Reputation: 837

Python: PyLaTeX hyperlink to a URL

I would like to add a text with a hyperlink to my document being generated via pyLaTeX. In LaTeX this would be performed by using:

\href{http://www.sharelatex.com}{Something Linky}

I have found the labelref documentation containing the Marker object as well as the Hyperref Object but i cannot seem to get it working.

from pylatex import Document, Hyperref

doc = Document()
doc.append("Example text a link should go ")
# i was hoping the hyperlink would work like i'm showing below
doc.append(Hyperref("https://jeltef.github.io/PyLaTeX", "here"))
doc.generate_pdf("Example_document", clean_tex=True)

Running the following code produces the a pdf document without errors. image of the document produced

While what i would expect is that the word "here" is a hyperlink and shown in blue.

Upvotes: 1

Views: 1781

Answers (1)

JeffHeaton
JeffHeaton

Reputation: 3278

Here is how I do it. I created a class that gives you the needed hyperlink functionality. There is also an issue on GitHub where I contributed this as well. https://github.com/JelteF/PyLaTeX/issues/264

    from pylatex import Document, Hyperref, Package
    from pylatex.utils import escape_latex, NoEscape

    def hyperlink(url,text):
        text = escape_latex(text)
        return NoEscape(r'\href{' + url + '}{' + text + '}')

    doc = Document()
    doc.packages.append(Package('hyperref'))
    doc.append("Example text a link should go ")
    # i was hoping the hyperlink would work like i'm showing below
    doc.append(hyperlink("https://jeltef.github.io/PyLaTeX", "here"))
    doc.generate_pdf("Example_document", clean_tex=True)

Upvotes: 4

Related Questions