Java-Add Hyperlinks to Specific Text in an Existing PDF Document
A hyperlink is a link that allows you to jump to a webpage, email address, or other document in a PDF document. Sometimes you may need to add hyperlinks to specific text in an existing PDF, and this article will share how to accomplish this task programmatically using Free Spire.PDF for Java.
Import Dependency (2 methods)
Method 1: Download the free library and unzip it. Then add the Spire.Pdf.jar file to your project as dependency.
Method 2: Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf.free</artifactId>
<version>5.1.0</version>
</dependency>
</dependencies>
Find text and Add Hyperlinks for Them in PDF in Java
To achieve the task, you’ll need to find all matched text in a specific PDF page and then add hyperlinks to them. The complete sample code is shown below.
import com.spire.pdf.*;
import com.spire.pdf.annotations.*;
import com.spire.pdf.general.find.*;
import com.spire.pdf.graphics.PdfRGBColor;
import java.awt.*;
public class SearchTextAndAddHyperlink {
public static void main(String[] args) {
//Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
//Load a sample PDF document
pdf.loadFromFile("Nicholas.pdf");
//Get the first page
PdfPageBase page = pdf.getPages().get(0);
// Find all matched strings and return a PdfTextFindCollection oject
PdfTextFindCollection collection = page.findText("St. Nicholas", false);
//loop through the find collection
for(PdfTextFind find : collection.getFinds())
{
// Create a PdfUriAnnotation instance to add hyperlinks for the searched text
PdfUriAnnotation uri = new PdfUriAnnotation(find.getBounds());
uri.setUri("https://www.stnicholascenter.org/who-is-st-nicholas");
uri.setBorder(new PdfAnnotationBorder(1f));
uri.setColor(new PdfRGBColor(Color.blue));
page.getAnnotationsWidget().add(uri);
}
//Save the document
pdf.saveToFile("searchTextAndAddHyperlink.pdf");
}
}