LaTeX/HyperlinksWikibooks,openbooksforanopenworld
LaTeX/Hyperlinks
LaTeXenablestypesettingofhyperlinks,usefulwhentheresultingformatisPDF,andthehyperlinkscanbe
followed.Itdoessousingthepackagehyperref.
Contents
1Hyperref
2Usage
2.1Commands
2.1.1\hyperref
2.1.2\url
2.1.3\href
2.2Otherpossibilities
2.2.1Emailaddress
2.2.2Localfile
2.2.3HyperlinkandHypertarget
3Customization
4Troubleshooting
4.1ProblemswithLinksandEquations1
4.2ProblemswithLinksandEquations2
4.3ProblemswithLinksandPages
4.4Problemswithbookmarks
4.5Problemswithtablesandfigures
4.6Problemswithlongcaptionand\listoffiguresorlongtitle
4.7Problemswithalreadyexisting.toc,.lofandsimilarfiles
4.8Problemswithfootnotesandspecialcharacters
4.9ProblemswithBeamer
4.10Problemswithdraftmode
5NotesandReferences
Hyperref
Thepackagehyperref[1]providesLaTeXtheabilitytocreatehyperlinkswithinthedocument.Itworkswith
pdflatexandalsowithstandard"latex"usedwithdvipsandghostscriptordvipdfmtobuildaPDFfile.Ifyouload
it,youwillhavethepossibilitytoincludeinteractiveexternallinksandallyourinternalreferenceswillbeturned
tohyperlinks.ThecompilerpdflatexmakesitpossibletocreatePDFfilesdirectlyfromtheLaTeXsource,and
PDFsupportsmorefeaturesthanDVI.InparticularPDFsupportshyperlinks,andtheonlywaytointroducethem
inLaTeXisusinghyperref.Moreover,PDFcancontainotherinformationaboutadocumentsuchasthetitle,the
author,etc.,whichcanbeeditedusingthissamepackage.
Usage
Thebasicusagewiththestandardsettingsisstraightforward.Justloadthepackageinthepreamble:
\usepackage{hyperref}
https://en.wikibooks.org/wiki/LaTeX/Hyperlinks#Hyperref
1/11
12/08/2015
LaTeX/HyperlinksWikibooks,openbooksforanopenworld
Thiswillautomaticallyturnallyourinternalreferencesintohyperlinks.Itwon'taffectthewaytowriteyour
documents:justkeeponusingthestandard\label\refsystem(discussedinthechapteronLabelsandCross
referencing)withhyperrefthose"connections"willbecomelinksandyouwillbeabletoclickonthemtobe
redirectedtotherightpage.Moreoverthetableofcontents,listoffigures/tablesandindexwillbemadeof
hyperlinks,too.Thehyperlinkswillnotshowupifyouareworkingindraftmode.
Commands
Thepackageprovidessomeusefulcommandsforinsertinglinkspointingoutsidethedocument.
\hyperref
Usage:
\hyperref[label_name]{''linktext''}
Thiswillhavethesameeffectas\ref{label_name}butwillmakethetextlinktextafulllink,instead.Thetwo
canbecombined.Ifthelemmalabelledasmainlemmawasnumber4.1.1thefollowingexamplewouldresultin
Weuse\hyperref[mainlemma]{lemma\ref*{mainlemma}}.
Weuselemma4.1.1.
withthehyperlinkasexpected.Notethe"*"after\refforavoidingnestedhyperlinks.
\url
Usage:
\url{<my_url>}
ItwillshowtheURLusingamonospacedfontand,ifyouclickonit,yourbrowserwillbeopenedpointingatit.
\href
Usage:
\href{<my_url>}{<description>}
Itwillshowthestringdescriptionusingstandarddocumentfontbut,ifyouclickonit,yourbrowserwillbe
openedpointingatmy_url.Hereisanexample:
\url{http://www.wikibooks.org}
\href{http://www.wikibooks.org}{Wikibookshome}
https://en.wikibooks.org/wiki/LaTeX/Hyperlinks#Hyperref
2/11
12/08/2015
LaTeX/HyperlinksWikibooks,openbooksforanopenworld
Bothpointatthesamepage,butinthefirstcasetheURLwillbeshown,whileinthesecondcasetheURLwill
behidden.Notethat,ifyouprintyourdocument,thelinkstoredusing\hrefwillnotbeshownanywhereinthe
document.
Otherpossibilities
Apartfromlinkingtowebsitesdiscussedabove,hyperrefcanbeusedtoprovidemailtolinks,linkstolocalfiles,
andlinkstoanywherewithinthePDFoutputfile.
Emailaddress
Apossiblewaytoinsertemaillinksisby
\href{mailto:my_address@wikibooks.org}{my\_address@wikibooks.org}
Itjustshowsyouremailaddress(sopeoplecanknowitevenifthedocumentisprintedonpaper)but,ifthereader
clicksonit,(s)hecaneasilysendyouanemail.Or,toincorporatetheurlpackage'sformattingandlinebreaking
abilitiesintothedisplayedtext,use[2]
\href{mailto:my_address@wikibooks.org}{\nolinkurl{my_address@wikibooks.org}}
Whenusingthisform,notethatthe\nolinkurlcommandisfragileandifthehyperlinkisinsideofamoving
argument,itmustbepreceededbya\protectcommand.
Localfile
Filescanalsobelinkedusingtheurlorthehrefcommands.Yousimplyhavetoaddthestringrun:atthe
beginningofthelinkstring:
\url{run:/path/to/my/file.ext}
\href{run:/path/to/my/file.ext}{textdisplayed}
Followinghttp://tex.stackexchange.com/questions/46488/linktolocalpdffiletheversionwithurldoesnot
alwayswork,buthrefdoes.
Itispossibletouserelativepathstolinkdocumentsnearthelocationofyourcurrentdocumentinordertodoso,
usethestandardUnixlikenotation(./isthecurrentdirectory,../isthepreviousdirectory,etc.)
HyperlinkandHypertarget
Itisalsopossibletocreateananchoranywhereinthedocument(withorwithoutcaption)andtolinktoit.To
createananchor,use:
https://en.wikibooks.org/wiki/LaTeX/Hyperlinks#Hyperref
3/11
12/08/2015
LaTeX/HyperlinksWikibooks,openbooksforanopenworld
\hypertarget{label}{targetcaption}
andtolinktoit,use:
\hyperlink{label}{linkcaption}
wherethetargetcaptionandlinkcaptionarethetextthatisdisplayedatthetargetlocationandlinklocation
respectively.
Customization
Thestandardsettingsshouldbefineformostusers,butifyouwanttochangesomething,thatisalsopossible.
Thereareseveralvariablesandtwomethodstopassthosetothepackage.Optionscanbepassedasanargument
ofthepackagewhenitisloaded(thestandardwaypackageswork),orthe\hypersetupcommandcanbeusedas
follows:
\hypersetup{<option1>[,...]}
youcanpassasmanyoptionsasyouwantseparatethemwithacomma.Optionshavetobeintheform:
variable_name=new_value
exactlythesameformathastobeusedifyoupassthoseoptionstothepackagewhileloadingit,likethis:
\usepackage[<option1,option2>]{hyperref}
Hereisalistofthepossiblevariablesyoucanchange(forthecompletelist,seetheofficialdocumentation).The
defaultvaluesarewritteninanuprightfont:
Checkout3.8Biglistathyperrefmanualattug.org(http://www.tug.org/applications/hyperref/manual.html#x1
120003.8)
https://en.wikibooks.org/wiki/LaTeX/Hyperlinks#Hyperref
4/11
12/08/2015
LaTeX/HyperlinksWikibooks,openbooksforanopenworld
variable
values
comment
bookmarks
=true,false
showorhidethebookmarksbarwhendisplayingthedocument
unicode
=false,true
allowstousecharactersofnonLatinbasedlanguagesin
Acrobatsbookmarks
pdfborder
setthestyleoftheborderaroundalink.Thefirsttwoparameters
(RadiusH,RadiusV)havenoeffectinmostpdfviewers.Width
definesthethicknessoftheborder.DashPatternisaseriesof
numbersseparatedbyspaceandenclosedbyboxbrackets.Itisan
={RadiusHRadiusV
optionalparametertospecifythelengthofeachline&gapinthe
Width[DashPattern]} dashpattern.Forexample,{000.5[33]}issupposedtodrawa
squarebox(noroundedcorners)ofwidth0.5andadashpattern
withadashoflength3followedbyagapoflength3.Thereisno
uniformityinwhether/howdifferentpdfviewersrenderthedash
pattern.
pdftoolbar
=true,false
showorhideAcrobatstoolbar
pdfmenubar
=true,false
showorhideAcrobatsmenu
pdffitwindow
=true,false
resizedocumentwindowtofitdocumentsize
pdfstartview
={FitH},{FitV},etc[3].
fitthewidthofthepagetothewindow
pdftitle
={text}
definethetitlethatgetsdisplayedinthe"DocumentInfo"window
ofAcrobat
pdfauthor
={text}
thenameofthePDFsauthor,itworksliketheoneabove
pdfsubject
={text}
subjectofthedocument,itworksliketheoneabove
pdfcreator
={text}
creatorofthedocument,itworksliketheoneabove
pdfproducer
={text}
producerofthedocument,itworksliketheoneabove
pdfkeywords
={text}
listofkeywords,separatedbycommas,examplebelow
pdfnewwindow
(=true,false)
defineifanewPDFwindowshouldgetopenedwhenalinkleads
outofthecurrentdocument.NB:Thisoptionisignoredifthelink
leadstoanhttp/httpsaddress.
pagebackref
(=false,true)
activatebackreferencesinsidebibliography.Mustbespecifiedas
partofthe\usepackage{}statement.
(=false,true)
surroundthelinksbycolorframes(false)orcolorsthetextofthe
links(true).Thecoloroftheselinkscanbeconfiguredusingthe
followingoptions(defaultcolorsareshown):
colorlinks
hidelinks(removingcolorandborder)
hidelinks
linkcolor
=red
colorofinternallinks(sections,pages,etc.)
linktoc
=none,section,page,all
defineswhichpartofanentryinthetableofcontentsismadeinto
alink
citecolor
=green
colorofcitationlinks(bibliography)
filecolor
=cyan
coloroffilelinks
urlcolor
=magenta
colorofURLlinks(mail,web)
linkbordercolor ={100}
colorofframearoundinternallinks(ifcolorlinks=false)
citebordercolor ={010}
colorofframearoundcitations
urlbordercolor
colorofframearoundURLlinks
={011}
Pleasenote,thatexplicitRGBspecificationisonlyallowedforthebordercolors(likelinkbordercoloretc.),while
theothersmayonlyassignedtonamedcolors(whichyoucandefineyourown,seeColors).Inordertospeedup
yourcustomizationprocess,hereisalistwiththevariableswiththeirdefaultvalue.Copyitinyourdocumentand
makethechangesyouwant.Nexttothevariables,thereisashortexplanationsoftheirmeaning:
https://en.wikibooks.org/wiki/LaTeX/Hyperlinks#Hyperref
5/11
12/08/2015
LaTeX/HyperlinksWikibooks,openbooksforanopenworld
\hypersetup{
bookmarks=true,%showbookmarksbar?
unicode=false,%nonLatincharactersinAcrobatsbookmarks
pdftoolbar=true,%showAcrobatstoolbar?
pdfmenubar=true,%showAcrobatsmenu?
pdffitwindow=false,%windowfittopagewhenopened
pdfstartview={FitH},%fitsthewidthofthepagetothewindow
pdftitle={Mytitle},%title
pdfauthor={Author},%author
pdfsubject={Subject},%subjectofthedocument
pdfcreator={Creator},%creatorofthedocument
pdfproducer={Producer},%producerofthedocument
pdfkeywords={keyword1,key2,key3},%listofkeywords
pdfnewwindow=true,%linksinnewPDFwindow
colorlinks=false,%false:boxedlinks;true:coloredlinks
linkcolor=red,%colorofinternallinks(changeboxcolorwithlinkbordercolor)
citecolor=green,%coloroflinkstobibliography
filecolor=magenta,%coloroffilelinks
urlcolor=cyan%colorofexternallinks
}
Ifyoudon'tneedsuchahighcustomization,herearesomesmallerbutusefulexamples.WhencreatingPDFs
destinedforprinting,coloredlinksarenotagoodthingastheyendupingrayinthefinaloutput,makingit
difficulttoread.Youcanusecolorframes,whicharenotprinted:
\usepackage{hyperref}
\hypersetup{colorlinks=false}
ormakelinksblack:
\usepackage[hidelinks]{hyperref}
WhenyoujustwanttoprovideinformationfortheDocumentInfosectionofthePDFfile,aswellasenabling
backreferencesinsidebibliography:
\usepackage[pdfauthor={Author'sname},%
pdftitle={DocumentTitle},%
pagebackref=true,%
pdftex]{hyperref}
Bydefault,URLsareprintedusingmonospacedfonts.Ifyoudon'tlikeitandyouwantthemtobeprintedwith
thesamestyleoftherestofthetext,youcanusethis:
\urlstyle{same}
Troubleshooting
ProblemswithLinksandEquations1
https://en.wikibooks.org/wiki/LaTeX/Hyperlinks#Hyperref
6/11
12/08/2015
LaTeX/HyperlinksWikibooks,openbooksforanopenworld
Messageslikethefollowing
!pdfTeXwarning(ext4):destinationwiththesameidentifier(name{
equation.1.7.7.30})hasbeenalreadyused,duplicateignored
appear,whenyouhavemadesomethinglike
\begin{eqnarray}a=b\nonumber\end{eqnarray}
Theerrordisappears,ifyouuseinsteadthisform:
\begin{eqnarray*}a=b\end{eqnarray*}
Bewarethattheshownlinenumberisoftencompletelydifferentfromtheerroneousline.
Possiblesolution:Placetheamsmathpackagebeforethehyperrefpackage.
ProblemswithLinksandEquations2
Messageslikethefollowing
!Runawayargument?
{\@firstoffive}\fi),Sometextfromyourdocumenthere(\ref{re\ETC.
LatexError:Paragraphendedbefore\Hy@setref@linkwascomplete.
appearwhenyouuse\labelinsideanalignenvironment.
Possiblesolution:Addthefollowingtoyourpreamble:
\AtBeginDocument{\let\textlabel\label}
ProblemswithLinksandPages
Messageslikethefollowing:
!pdfTeXwarning(ext4):destinationwiththesame
identifier(name{page.1})hasbeenalreadyused,
duplicateignored
appearwhenacountergetsreinitialized,forexamplebyusingthecommand\mainmatterprovidedbythebook
documentclass.Itresetsthepagenumbercounterto1priortothefirstchapterofthebook.Butastheprefaceof
thebookalsohasapagenumber1alllinksto"page1"wouldnotbeuniqueanymore,hencethenoticethat
"duplicatehasbeenignored."Thecountermeasureconsistsofputtingplainpages=falseintothehyperref
options.Thisunfortunatelyonlyhelpswiththepagecounter.Anevenmoreradicalsolutionistousetheoption
hypertexnames=false,butthiswillcausethepagelinksintheindextostopworking.
Thebestsolutionistogiveeachpageauniquenamebyusingthe\pagenumberingcommand:
https://en.wikibooks.org/wiki/LaTeX/Hyperlinks#Hyperref
7/11
12/08/2015
LaTeX/HyperlinksWikibooks,openbooksforanopenworld
\pagenumbering{alph}%a,b,c,...
...titlepage,otherfrontmatter...
\pagenumbering{roman}%i,ii,iii,iv,...
...tableofcontents,tableoffigures,...
\pagenumbering{arabic}%1,2,3,4,...
...beginningofthemainmatter(chapter1)...
Anothersolutionistouse\pagenumbering{alph}beforethecommand\maketitle,whichwillgivethetitlepage
thelabelpage.a.Sincethepagenumberissuppressed,itwon'tmakeadifferencetotheoutput.
Bychangingthepagenumberingeverytimebeforethecounterisreset,eachpagegetsauniquename.Inthis
case,thepageswouldbenumbereda,b,c,i,ii,iii,iv,v,1,2,3,4,5,...
Ifyoudon'twantthepagenumberstobevisible(forexample,duringthefrontmatterpart),use
\pagestyle{empty}...\pagestyle{plain}.Theimportantpointisthatalthoughthenumbersarenotvisible,each
pagewillhaveauniquename.
Anothermoreflexibleapproachistosetthecountertosomethingnegative:
\setcounter{page}{100}
...titlepage,otherfrontmatter...
\pagenumbering{roman}%i,ii,iii,iv,...
...tableofcontents,tableoffigures,...
\pagenumbering{arabic}%1,2,3,4,...
...beginningofthemainmatter(chapter1)...
whichwillgivethefirstpagesauniquenegativenumber.
Theproblemcanalsooccurwiththealgorithmspackage:becauseeachalgorithmusesthesamelinenumbering
scheme,thelineidentifiersforthesecondandfollowonalgorithmswillbeduplicatesofthefirst.
Theproblemoccurswithequationidentifiersifyouuse\nonumberoneverylineofaneqnarrayenvironment.In
thiscase,usethe*'edforminstead,e.g.\begin{eqnarray*}...\end{eqnarray*}(whichisanunnumbered
equationarray),andremovethenowunnecessary\nonumbercommands.
Ifyoururl'saretoolongandrunningoffofthepage,tryusingthebreakurlpackagetosplittheurlovermultiple
lines.Thisisespeciallyimportantinamulticolumnenvironmentwherethelinewidthisgreatlyshortened.
Problemswithbookmarks
Thetextdisplayedbybookmarksdoesnotalwayslooklikeyouexpectittolook.Becausebookmarksare"just
text",muchfewercharactersareavailableforbookmarksthanfornormalLaTeXtext.Hyperrefwillnormally
noticesuchproblemsandputupawarning:
PackagehyperrefWarning:
TokennotallowedinaPDFDocEncodedstring:
Youcannowworkaroundthisproblembyprovidingatextstringforthebookmarks,whichreplacesthe
offendingtext:
\texorpdfstring{''TEXtext''}{''BookmarkText''}
https://en.wikibooks.org/wiki/LaTeX/Hyperlinks#Hyperref
8/11
12/08/2015
LaTeX/HyperlinksWikibooks,openbooksforanopenworld
Mathexpressionsareaprimecandidateforthiskindofproblem:
\section{\texorpdfstring{$E=mc^2$}{E=mc2}}
whichturns\section{$E=mc^2$}toE=mc2inthebookmarkarea.Colorchangesalsodonottravelwellinto
bookmarks:
\section{\textcolor{red}{Red!}}
producesthestring"redRed!".Thecommand\textcolorgetsignoredbutitsargument(red)getsprinted.Ifyou
use:
\section{\texorpdfstring{\textcolor{red}{Red!}}{Red\!}}
theresultwillbemuchmorelegible.
Ifyouwriteyourdocumentinunicodeandusetheunicodeoptionforthehyperrefpackageyoucanuseunicode
charactersinbookmarks.Thiswillgiveyouamuchlargerselectionofcharacterstopickfromwhenusing
\texorpdfstring.
Problemswithtablesandfigures
Thelinkscreatedbyhyperrefpointtothelabelcreatedwithinthefloatenvironment,which,aspreviously
described,mustalwaysbesetafterthecaption.Sincethecaptionisusuallybelowafigureortable,thefigureor
tableitselfwillnotbevisibleuponclickingthelink[4].Aworkaroundexistsbyusingthepackagehypcap[1]
(http://www.ctan.org/texarchive/macros/latex/contrib/oberdiek/hypcap.pdf)with:
\usepackage[all]{hypcap}
Besuretocallthispackageafterloadinghyperref.
Ifyouusethewrapfigpackage[5]mentionedinthe"Wrappingtextaroundfigures"sectionofthe"Floats,Figures
andCaptions"chapter,orothersimilarpackagesthatdefinetheirownenvironments,youwillneedtomanually
include\capstartinthoseenvironments,e.g.:
\begin{wrapfigure}{R}{0.5\textwidth}
\capstart
\begin{center}
\includegraphics[width=0.48\textwidth]{filename}
\end{center}
\caption{\label{labelname}afigure}
\end{wrapfigure}
https://en.wikibooks.org/wiki/LaTeX/Hyperlinks#Hyperref
9/11
12/08/2015
LaTeX/HyperlinksWikibooks,openbooksforanopenworld
Problemswithlongcaptionand\listoffiguresorlongtitle
Thereisanissuewhenusing\listoffigureswithhyperrefforlongcaptionsorlongtitles.Thishappenswhen
thecaptions(orthetitles)arelongerthanthepagewidth(about79wordsdependingonyoursettings).Tofix
this,youneedtousetheoptionbreaklinkswhenfirstdeclaring:
\usepackage[breaklinks]{hyperref}
Thiswillthencausethelinksinthe\listoffigurestowordwrapproperly.
Problemswithalreadyexisting.toc,.lofandsimilarfiles
Theformatofsomeoftheauxilliaryfilesgeneratedbylatexchangeswhenyouincludethehyperrefpackage.
Onecanthereforeencountererrorslike
!Argumentof\Hy@setref@linkhasanextra}.
whenthedocumentistypesetwithhyperrefforthefirsttimeandthesefilesalreadyexist.Thesolutiontothe
problemistodeleteallthefilesthatlatexusestogetreferencesrightandtypesetagain.
Problemswithfootnotesandspecialcharacters
Seetherelevantsection.
ProblemswithBeamer
Usingthecommand
\hyperref[some_label]{sometext}
isbrokenwhenpointedatalabel.Insteadofsendingtheusertothedesiredlabel,uponclickingtheuserwillbe
senttothefirstframe.Asimpleworkaroundexistsinsteadofusing
\phantomsection\label{some_label}
tolabelyourframes,use
\hypertarget{some_label}{}
andreferenceitwith
https://en.wikibooks.org/wiki/LaTeX/Hyperlinks#Hyperref
10/11
12/08/2015
LaTeX/HyperlinksWikibooks,openbooksforanopenworld
\hyperlink{some_label}{sometext}
Problemswithdraftmode
WARNING!Pleasenotethatifyouhaveactivatedthe"draft"optioninyour\documentclassdeclarationthe
hyperlinkswillnotshowupinthetableofcontents!!!
NotesandReferences
1. HyperrefpackagewebpageinCTAN(http://www.ctan.org/texarchive/macros/latex/contrib/hyperref)
2. "Emaillinkwithhyperref,urlpackages".comp.text.texUserGroup.
http://groups.google.com/group/comp.text.tex/browse_thread/thread/ae160fd2fc5680a5/71a5a7c7bfceb3cb?
lnk=gst&q=email+url+hyperref#71a5a7c7bfceb3cb.Retrieved2008.
3. Otherpossiblevaluesaredefinedinthehyperrefmanual
(http://mirror.switch.ch/ftp/mirror/tex/macros/latex/contrib/hyperref/doc/manual.html#TBL7401)
4. http://www.ctan.org/texarchive/macros/latex/contrib/hyperref/README
5. WrapfigpackagewebpageinCTAN(http://www.ctan.org/texarchive/macros/latex/contrib/wrapfig)
Retrievedfrom"https://en.wikibooks.org/w/index.php?title=LaTeX/Hyperlinks&oldid=2981645"
Thispagewaslastmodifiedon2August2015,at12:33.
TextisavailableundertheCreativeCommonsAttributionShareAlikeLicense.additionaltermsmay
apply.Byusingthissite,youagreetotheTermsofUseandPrivacyPolicy.
https://en.wikibooks.org/wiki/LaTeX/Hyperlinks#Hyperref
11/11