Java如何在iText中创建内部锚点?
com.itextpdf.text.AnchoriText中的类可用于在PDF文档中创建内部链接或外部链接。要创建内部链接,我们必须使用#+格式化锚引用referenceName。另一方面,应使用相同的参考名称(不包括#符号)来命名目标锚。
要设置参考,我们使用setReference()方法。要定义目标锚,我们可以使用setName()方法命名锚。
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 AnchorInternalDemo { public static void main(String[] args) { Document document = new Document(); try { PdfWriter.getInstance(document, new FileOutputStream("AnchorInternal.pdf")); document.open(); Anchor anchor = new Anchor("[Continue Here]"); anchor.setReference("#targetLink"); Paragraph para1 = new Paragraph("The quick brown fox jumps over the lazy dog. "); para1.add(anchor); document.add(para1); Anchor target = new Anchor("The quick onyx goblin jumps over the lazy dwarf."); anchor.setName("targetLink"); Paragraph para2 = new Paragraph(); para2.setSpacingBefore(150); para2.add(target); document.add(para2); document.close(); } catch (DocumentException | FileNotFoundException e) { e.printStackTrace(); } finally { document.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>