Spire.PDF for Java 是一款专门对 PDF 文档进行操作的 Java 类库。该类库的主要功能在于帮助开发人员在 Java 应用程序(J2SE和J2EE)中生成 PDF 文档和操作现有 PDF 文档,并且运行环境无需安装 Adobe Acrobat。
可点击此处下载最新版测试。
为 Java 安装 Spire.PDF
首先,您需要在 Java 程序中添加 Spire.PDF.jar 文件作为依赖项。JAR 文件可以从此链接下载。如果您使用 Maven,则可以通过将以下代码添加到项目的 pom.xml 文件来轻松导入 JAR 文件。
<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>4.11.1</version> </dependency></dependencies>
在 PDF 中查找文本并为其添加超链接
使用 Spire PDF for Java,您可以在特定的 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) { //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"); }}

整合所有格式API处理套包Spire.office for Java正在 火热销售中!联系客服立马1分钟了解全部咨询!
标签:
声明:本站部分文章及图片源自用户投稿,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!