Java如何在iText中创建锚点或链接?
本示例向您展示如何使用com.itextpdf.text.Anchor该类在PDF文档中创建外部链接。您可以创建一个Anchor带有字符串短语的实例,并通过调用setReference()此对象的方法来设置其引用(在本例中为网站URL)。
package org.nhooo.example.itextpdf; import com.itextpdf.text.Anchor; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; import java.io.FileNotFoundException; import java.io.FileOutputStream; public class AnchorDemo { public static void main(String[] args) { Document doc = new Document(); try { PdfWriter.getInstance(doc, new FileOutputStream("AnchorDemo.pdf")); doc.open(); String content = "You can learn Java programming on the " + "following website: "; Paragraph paragraph = new Paragraph(content); //创建一个链接到外部网站的新锚点 //并将此锚点添加到段落中。 Anchor anchor = new Anchor("Learn Java by Examples"); anchor.setReference("https://nhooo.org"); paragraph.add(anchor); doc.add(paragraph); } catch (DocumentException | FileNotFoundException e) { e.printStackTrace(); } finally { doc.close(); } } }
Maven依赖
<!-- http://repo1.maven.org/maven2/com/itextpdf/itextpdf/5.5.10/itextpdf-5.5.10.jar --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.10</version> </dependency>