Java: Find Text and Add Hyperlinks for Them in PDF
A hyperlink refers to an icon, graphic, or text that links to another file or object. It is one of the most commonly used features for manipulating documents. Spire.PDF for Java supports creating a new PDF document and adding various hyperlinks to it, including ordinary links, hypertext links, email links and document links. This article will show you how to add hyperlinks to specific text in an existing PDF.
Install Spire.PDF for Java
First of all, you need to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file by adding the following code to your project's pom.xml file.
<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</artifactId> <version>10.3.4</version> </dependency> </dependencies>
Find Text and Add Hyperlinks for Them in PDF
With Spire PDF for Java, you can find all matched text in a specific PDF page and add hyperlinks to them. Here are the detailed steps to follow.
- Create a PdfDocument instance and load a sample PDF document using PdfDocument.loadFromFile()method.
- Get a specific page of the document using PdfDocument.getPages().get() method.
- Find all matched text in the page using PdfPageBase.findText(String searchPatternText, boolean isSearchWholeWord) method, and return a PdfTextFindCollection object.
- Create a PdfUriAnnotation instance based on the bounds of a specific find result.
- Set a URL address for the annotation using PdfUriAnnotation.set(String value) method and set its border and color as well.
- Add the URL annotation to the PDF annotation collection as a new annotation using PdfPageBase.getAnnotationWidget().add() method.
- Save the document using PdfDocument.saveToFile() method.
- Java
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("C:\\Users\\Test1\\Desktop\\sample.pdf"); //Get the first page PdfPageBase page = pdf.getPages().get(0); // Find all matched strings and return a PdfTextFindCollection oject PdfTextFindCollection collection = page.findText("Spire.PDF for Java", 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.e-iceblue.com/Introduce/pdf-for-java.html"); uri.setBorder(new PdfAnnotationBorder(1f)); uri.setColor(new PdfRGBColor(Color.blue)); page.getAnnotationsWidget().add(uri); } //Save the document pdf.saveToFile("output/searchTextAndAddHyperlink.pdf"); } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Java: Update or Remove Hyperlinks in PDF
Hyperlinks in PDF documents provide convenient navigation and access to external resources. However, there are scenarios where you may need to remove or update these hyperlinks to maintain document integrity or reflect changes in the linked content. In this article, we will explore how to efficiently update or remove hyperlinks in PDF using Spire.PDF for Java.
Install Spire.PDF for Java
First of all, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.
<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</artifactId> <version>10.3.4</version> </dependency> </dependencies>
Update Hyperlinks in PDF in Java
Spire.PDF for Java provides the PdfUriAnnotationWidget.setUri() method to assist you in resetting the URL. The following are the detailed steps.
- Create a PdfDocument object.
- Load the sample PDF file using PdfDocument.loadFromFile() method.
- Get the first page of the document using PdfDocument.getPages().get() method.
- Get annotation collection using PdfPageBase.getAnnotationsWidget() method.
- Get the first url annotation widget using PdfAnnotationCollection.get() method and reset the url using PdfUriAnnotationWidget.setUri() method.
- Save the document using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; import com.spire.pdf.annotations.PdfAnnotationCollection; import com.spire.pdf.annotations.PdfUriAnnotationWidget; public class UpdateHyperlinks { public static void main(String[] args) throws Exception { //Create a PdfDocument object PdfDocument document = new PdfDocument(); //Load the sample PDF file document.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.pdf"); //Get the first page PdfPageBase page = document.getPages().get(0); //Get annotation collection PdfAnnotationCollection widgetCollection = page.getAnnotationsWidget(); //Get the first url annotation widget PdfUriAnnotationWidget uriWidget = (PdfUriAnnotationWidget)widgetCollection.get(0); //Reset the url uriWidget.setUri("https://www.e-iceblue.com/Introduce/pdf-for-java.html"); //Save to file document.saveToFile("output.pdf"); document.close(); } }
Remove Hyperlinks in PDF in Java
Spire.PDF for Java also offers the PdfAnnotationCollection.removeAt() method, which allows users to delete hyperlinks. When you use this method to remove a hyperlink, the visual appearance of the hyperlink will remain unchanged, but the underlying link will be deleted. The following steps demonstrate how to delete hyperlinks in a PDF.
- Create a PdfDocument object.
- Load the sample PDF file using PdfDocument.loadFromFile() method.
- Get the first page of the document using PdfDocument.getPages().get() method.
- Get annotation collection using PdfPageBase.getAnnotationsWidget() method.
- Remove the second annotation which is a hyperlink in the document using PdfAnnotationCollection.removeAt() method.
- Save the document using PdfDocument.saveToFile() method.
- Java
import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; import com.spire.pdf.annotations.PdfAnnotationCollection; public class RemoveHyperlinks { public static void main(String[] args) throws Exception { //Create a PdfDocument object PdfDocument document = new PdfDocument(); //Load the sample PDF file document.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.pdf"); //Get the first page PdfPageBase page = document.getPages().get(0); //Get annotation collection PdfAnnotationCollection widgetCollection = page.getAnnotationsWidget(); //Remove the second annotation which is a hyperlink in the document widgetCollection.removeAt(1); //Save to file document.saveToFile("Result.pdf"); document.close(); } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Add Links to PDF in Java
This article demonstrates how to add links, including ordinary link, hypertext link, email link and document link, to a PDF document by using Spire.PDF for Java.
import com.spire.pdf.annotations.*; import com.spire.pdf.graphics.*; import java.awt.*; import java.awt.font.TextAttribute; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.util.HashMap; public class AddLinksToPdf { public static void main(String[] args) throws Exception { //create a pdf document PdfDocument doc = new PdfDocument(); PdfPageBase page = doc.getPages().add(); //initialize x, y coordinates float y = 30; float x = 0; //create a plain font PdfTrueTypeFont plainFont = new PdfTrueTypeFont(new Font("Arial Unicode MS",Font.PLAIN,13),true); //create a underlined font HashMap<TextAttribute, Object> hm = new HashMap<TextAttribute, Object>(); hm.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON); hm.put(TextAttribute.SIZE, 13); hm.put(TextAttribute.FAMILY, "Arial"); Font font = new Font(hm); PdfTrueTypeFont underlineFont = new PdfTrueTypeFont(font); //add a simply link to pdf String label = "Simply Link: "; PdfStringFormat format = new PdfStringFormat(); format.setMeasureTrailingSpaces(true); page.getCanvas().drawString(label, plainFont, PdfBrushes.getOrange(), 0, y,format); x = (float)plainFont.measureString(label,format).getWidth(); page.getCanvas().drawString("https://www.e-iceblue.com", underlineFont, PdfBrushes.getBlue(), x, y+2); y = y + 26; //add a hyper text link to pdf label= "Hypertext Link: "; page.getCanvas().drawString(label, plainFont, PdfBrushes.getOrange(), 0, y, format); x = (float)plainFont.measureString(label,format).getWidth(); PdfTextWebLink webLink = new PdfTextWebLink(); webLink.setText("Home Page"); webLink.setUrl("https://www.e-iceblue.com"); webLink.setFont(plainFont); webLink.setBrush(PdfBrushes.getBlue()); webLink.drawTextWebLink(page.getCanvas(), new Point2D.Float(x, y)); y= y + 26; //add an email link to pdf label = "Email Link: "; page.getCanvas().drawString(label, plainFont, PdfBrushes.getOrange(), 0, y, format); x = (float)plainFont.measureString(label, format).getWidth(); webLink = new PdfTextWebLink(); webLink.setText("Contact Us"); webLink.setUrl("mailto:support@e-iceblue.com"); webLink.setFont(plainFont); webLink.setBrush(PdfBrushes.getBlue()); webLink.drawTextWebLink(page.getCanvas(), new Point2D.Float(x, y)); y = y + 26; //add a document link to pdf label = "Document Link: "; page.getCanvas().drawString(label, plainFont, PdfBrushes.getOrange(), 0, y, format); x = (float)plainFont.measureString(label, format).getWidth(); page.getCanvas().drawString("Open File", plainFont, PdfBrushes.getBlue(), x, y, format); Rectangle2D rect = new Rectangle2D.Float(x,y+2,60,15); PdfFileLinkAnnotation fileLinkAnnotation = new PdfFileLinkAnnotation(rect,"C:\\Users\\Administrator\\Desktop\\Image.png"); fileLinkAnnotation.setBorder(new PdfAnnotationBorder(0f)); ((PdfNewPage) ((page instanceof PdfNewPage) ? page : null)).getAnnotations().add(fileLinkAnnotation); //save to file doc.saveToFile("output/AddLinks.pdf"); doc.close(); } }
Output: