Insert Text Hyperlinks and Image Hyperlinks in PDF with Python

Alice Yang
7 min readSep 20, 2024

--

Hyperlinks play an essential role in PDFs, allowing users to navigate to web pages, internal document locations, or open external files seamlessly. Whether you’re creating a PDF for business, educational, or personal use, hyperlinks enhance the user experience by making documents interactive and easy to navigate. This article will cover how to add text hyperlinks and image hyperlinks to PDF using Python. It includes the following topics:

Python Library to Add Hyperlinks to PDF

To add hyperlinks to PDF with Python, we will use Spire.PDF for Python.

This module offers a comprehensive set of features for working with PDF documents, including creating, reading, editing, and converting them.

You can install Spire.PDF for Python from PyPI using the following pip command:

pip install Spire.Pdf

If you already have Spire.PDF for Python installed and would like to upgrade to the latest version, use the following pip command:

pip install --upgrade Spire.Pdf

Add Web Link to PDF with Python

Adding web links to a PDF document allows users to quickly access external web resources with a simple click. This feature is particularly useful for referencing external content, such as articles, videos, or websites, enhancing the interactivity of the document.

To draw text web links on PDF pages in Python, you can use the PdfTextWebLink class. Here is a simple code example of doing so:

from spire.pdf.common import *
from spire.pdf import *

# Create a PDF document
doc = PdfDocument()

# Add a page
page = doc.Pages.Add()

# Initialize x and y coordinates
x = 10.0
y = 50.0

# Create fonts
label_font = PdfTrueTypeFont("Lucida Sans Unicode", 14.0, PdfFontStyle.Regular, True)
link_font = PdfTrueTypeFont("Lucida Sans Unicode", 14.0, PdfFontStyle.Underline, False)

# Draw label text on the page
label = "Web Link: "
format = PdfStringFormat()
format.MeasureTrailingSpaces = True
page.Canvas.DrawString(label, label_font, PdfBrushes.get_Orange(), x, y, format)
x += label_font.MeasureString(label, format).Width

# Draw a web link on the page
web_link = PdfTextWebLink()
web_link.Text = "Google Homepage"
web_link.Url = "https://www.google.com/"
web_link.Font = link_font
web_link.Brush = PdfBrushes.get_Blue()
web_link.DrawTextWebLink(page.Canvas, PointF(x, y))

# Save the resultant PDF file
doc.SaveToFile("WebLink.pdf")
doc.Close()
Add Web Link to PDF with Python
Add Web Link to PDF with Python

Add Internal File Link to PDF with Python

An internal file link in a PDF enables users to jump to different sections or pages within the same document. It’s ideal for helping readers quickly find relevant content, especially in lengthy or complex files.

To add internal file links to a PDF in Python, you can use the PdfDocumentLinkAnnotation class. Here is a simple code example of doing so:

from spire.pdf.common import *
from spire.pdf import *

# Create a PDF document
doc = PdfDocument()

# Add pages
doc.Pages.Add()
doc.Pages.Add()

# Initialize x and y coordinates
x = 10.0
y = 50.0

# Create fonts
label_font = PdfTrueTypeFont("Lucida Sans Unicode", 14.0, PdfFontStyle.Regular, True)
link_font = PdfTrueTypeFont("Lucida Sans Unicode", 14.0, PdfFontStyle.Underline, False)

# Draw label text on the page
label = "Internal File Link: "
format = PdfStringFormat()
format.MeasureTrailingSpaces = True
doc.Pages[0].Canvas.DrawString(label, label_font, PdfBrushes.get_Orange(), x, y, format)
x += label_font.MeasureString(label, format).Width

# Draw text on the page
text = "Jump to Page 2"
doc.Pages[0].Canvas.DrawString(text, link_font, PdfBrushes.get_Blue(), x, y)

# Create a rectangle
rectangle = RectangleF(x, y, link_font.MeasureString(text).Width, link_font.MeasureString(text).Height)
# Create a document link annotation
documentLinkAnnotation = PdfDocumentLinkAnnotation(rectangle)
# Set the annotation border
documentLinkAnnotation.Border = PdfAnnotationBorder(0.0)
# Specify the destination page index (0-based)
destinationPageIndex = 1
# Set the annotation destination
documentLinkAnnotation.Destination = PdfDestination(destinationPageIndex, PointF(x, y), 1.0)
# Add the annotation to the first page
doc.Pages[0].Annotations.Add(documentLinkAnnotation)

# Save the resultant PDF file
doc.SaveToFile("InternalFileLink.pdf")
doc.Close()
Add Internal File Link to PDF with Python
Add Internal File Link to PDF with Python

Add External File Link to PDF with Python

Inserting an external file link allows users to open files outside of the PDF, such as related documents, spreadsheets, or media. This helps create a more connected and resource-rich document experience.

To add external file links to a PDF in Python, you can use the PdfFileLinkAnnotation class. Here is a simple example of doing so:

from spire.pdf.common import *
from spire.pdf import *

# Create a PDF document
doc = PdfDocument()

# Add a page
page = doc.Pages.Add()

# Initilize x and y coordinates
x = 10.0
y = 50.0

# Create fonts
label_font = PdfTrueTypeFont("Lucida Sans Unicode", 14.0, PdfFontStyle.Regular, True)
link_font = PdfTrueTypeFont("Lucida Sans Unicode", 14.0, PdfFontStyle.Underline, False)

# Draw label text on the page
label = "External File Link: "
format = PdfStringFormat()
format.MeasureTrailingSpaces = True
doc.Pages[0].Canvas.DrawString(label, label_font, PdfBrushes.get_Orange(), x, y, format)
x += label_font.MeasureString(label, format).Width

# Draw text on the page
text = "Open Image"
page.Canvas.DrawString(text, link_font, PdfBrushes.get_Blue(), x, y)

# Create a rectangle
rectangle = RectangleF(x, y, link_font.MeasureString(text).Width, link_font.MeasureString(text).Height)
# Create a document link annotation
fileLinkAnnotation = PdfFileLinkAnnotation(rectangle, "C:/Users/Administrator/Desktop/images.png")
# Set the annotation border
fileLinkAnnotation.Border = PdfAnnotationBorder(0.0)
# Add the annotation to the page
page.Annotations.Add(fileLinkAnnotation)

# Save the resultant PDF file
doc.SaveToFile("ExternalFileLink.pdf")
doc.Close()
Add External File Link to PDF with Python
Add External File Link to PDF with Python

Add Hyperlink to Existing Text in PDF with Python

By adding a hyperlink to existing text, you can turn selected words or phrases into clickable links that lead to websites, other parts of the document, or external files, enhancing both navigation and interactivity.

To add hyperlinks to existing text in a PDF in Python, you can use the PdfUriAnnotation class. Here is a simple code example of doing so:

from spire.pdf.common import *
from spire.pdf import *

# Open a PDF document
doc = PdfDocument()
doc.LoadFromFile("Adobe Acrobat.pdf")

# Flag to check if annotation is added
annotation_added = False

# Iterate through all the pages in the document
for i in range(doc.Pages.Count):
if annotation_added:
break # Exit the loop once the first annotation is added
# Get the current page
page = doc.Pages[i]
# Create a PdfTextFinder object
finder = PdfTextFinder(page)
# Find desired text
textFragments = finder.Find("Adobe")
if textFragments: # If text is found
# Get the first instance
textFragment = textFragments[0]
# Create a URL annotation for the first instance
uriAnnotation = PdfUriAnnotation(textFragment.Bounds[0])
# Set annotation URL
uriAnnotation.Uri = "https://www.adobe.com/"
# Set annotation border
uriAnnotation.Border = PdfAnnotationBorder(1.0)
# Set annotation border color
uriAnnotation.Color = PdfRGBColor(Color.get_Navy())
# Add annotation to the page where the first instance of the text exists
page.Annotations.Add(uriAnnotation)
annotation_added = True # Set flag to True once the first annotation is added

# Save the resultant PDF file
doc.SaveToFile("AddHyperlinkToExistingText.pdf")
doc.Close()
Add Hyperlink to Existing Text in PDF with Python
Add Hyperlink to Existing Text in PDF with Python

Insert Hyperlinked Image in PDF with Python

You can insert images with hyperlinks in a PDF to create visual elements that direct users to websites or files when clicked, offering a more engaging way to share information.

The PdfUriAnnotation class can also be used for adding hyperlinks to images in PDF. Here is a simple code example of doing so:

from spire.pdf.common import *
from spire.pdf import *

# Create a PDF document
doc = PdfDocument()

# Add a page
page = doc.Pages.Add()

# Open an image
image = PdfImage.FromFile("C:/Users/Administrator/Downloads/Adobe Acrobat.jpg")
# Create a rectangle
rectange = RectangleF(PointF(100.0, 100.0), SizeF(float(image.Width), float(image.Height)))
# Draw the image on the page
page.Canvas.DrawImage(image, rectange)

# Create a URL annotation for the image
uriAnnotation = PdfUriAnnotation(rectange)
# Set annotation URL
uriAnnotation.Uri = "https://www.adobe.com/"
# Set annotation border
uriAnnotation.Border = PdfAnnotationBorder(0.0)
# Add annotation to the page
page.Annotations.Add(uriAnnotation)

# Save the resultant PDF file
doc.SaveToFile("InsertHyperlinkedImage.pdf")
doc.Close()
Insert Hyperlinked Image to PDF with Python
Insert Hyperlinked Image to PDF with Python

Add Hyperlink to Existing Image in PDF with Python

In addition to inserting hyperlinked images in PDF, you can also add hyperlinks to existing images in PDF. Here is a simple example of doing so:

from spire.pdf.common import *
from spire.pdf import *

# Open a PDF document
doc = PdfDocument()
doc.LoadFromFile("Adobe Acrobat.pdf")

# Get the first page
page = doc.Pages[0]

# Create a PdfImageHelper object
image_helper = PdfImageHelper()
# Get the image information of the first page
image_infos = image_helper.GetImagesInfo(page)

if image_infos:
# Get the first image info
image_info = image_infos[0]
# Create an URL annotation for the first image
uriAnnotation = PdfUriAnnotation(image_info.Bounds)
# Set annotation URL
uriAnnotation.Uri = "https://www.adobe.com/"
# Set annotation border
uriAnnotation.Border = PdfAnnotationBorder(0.0)
# Add annotation to the page
page.Annotations.Add(uriAnnotation)

# Save the resultant PDF file
doc.SaveToFile("AddHyperlinkToExistingImage.pdf")
doc.Close()
Add Hyperlink to Existing Image in PDF with Python
Add Hyperlink to Existing Image in PDF with Python

Conclusion

This article has walked through the process of how to add web links, internal and external file links, as well as hyperlinks to images within PDFs using Python. Whether you’re adding text-based hyperlinks or embedding clickable images, Spire.PDF for Python module provides a comprehensive solution for handling these tasks.

Related Topics

--

--

Alice Yang

Skilled senior software developers with five years of experience in all phases of software development life cycle using .NET, Java and C++ languages.