前言
超鏈接是指鏈接到另一個檔案或物件的圖示、圖形或文本,它是操作檔案最常用的功能之一,Spire.PDF for Java支持創建一個新的PDF檔案并向其添加各種超鏈接,包括普通鏈接、超文本鏈接、電子郵件鏈接和檔案鏈接,本文將告訴你如何在現有的PDF中為特定文本添加超鏈接,
【程式環境】
安裝Spire.PDF for Java
首先,你需要在你的Java程式中添加Spire.Pdf.jar檔案作為一個依賴項,該JAR檔案可以從這個鏈接下載,如果你使用Maven,則可以通過在專案的pom.xml檔案中添加以下代碼輕松匯入JAR檔案,
1 <repositories> 2 <repository> 3 <id>com.e-iceblue</id> 4 <name>e-iceblue</name> 5 <url> https://repo.e-iceblue.cn/repository/maven-public /</url> 6 </repository> 7 </repositories> 8 <dependencies> 9 <dependency> 10 <groupId>e-iceblue</groupId> 11 <artifactId>spire.pdf</artifactId> 12 <version>8.9.1</version> 13 </dependency> 14 </dependencies>
注意:請保持上面代碼中的版本號與下載鏈接中的一致,以體驗新功能或避免BUG
在PDF中查找文本并為其添加超鏈接
【步驟】
- 創建一個PdfDocument實體,并使用PdfDocument.loadFromFile()方法加載一個樣本PDF檔案,
- 使用PdfDocument.getPages().get()方法獲取檔案的一個特定頁面,
- 使用PdfPageBase.findText(String searchPatternText, boolean isSearchWholeWord)方法查找頁面中所有匹配的文本,并回傳一個PdfTextFindCollection物件,
- 根據特定查找結果的邊界,創建一個PdfUriAnnotation實體,
- 使用PdfUriAnnotation.set(String value)方法為注釋設定一個URL地址,并同時設定它的邊框和顏色,
- 使用PdfPageBase.getAnnotationWidget().add()方法將URL注解作為一個新的注解添加到PDF注解集合中,
- 使用PdfDocument.saveToFile()方法保存檔案,
【代碼示例】
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) { //創建一個PdfDocument實體 PdfDocument pdf = new PdfDocument(); //加載一個樣本PDF檔案 pdf.loadFromFile("C:\\Users\\Test1\\Desktop\\sample.pdf"); //得到第一頁 PdfPageBase page = pdf.getPages().get(0); //查找頁面中所有匹配的文本,并回傳一個PdfTextFindCollection物件 PdfTextFindCollection collection = page.findText("Spire.PDF for Java", false); //loop through the find collection回圈瀏覽查找到的集合 for(PdfTextFind find : collection.getFinds()) { //創建一個PdfUriAnnotation實體為搜索到的文本添加超鏈接 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); } //保存檔案 pdf.saveToFile("output/searchTextAndAddHyperlink.pdf"); } }
【效果圖】

注:該JAR包分為免費版和商業版,免費版沒有水印或評估資訊,但是有篇幅和大小限制,商業版有水印或評估資訊,沒有篇幅限制,想要去除這些評估資訊,需要應用license,可以點擊這里獲取30天免費license,
---THE END---
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/514057.html
標籤:Java
上一篇:插入排序演算法步驟和思路
下一篇:Java圖形化學生管理(一)
