如何使用Java iText 5在已有PDF中添加内部与外部链接?
使用iText 5为现有PDF添加内部链接与外部链接
一、添加外部链接
外部链接用于跳转至PDF以外的网页或资源,核心是创建带URI跳转动作的注释,并将其绑定到PDF页面的指定区域。
实现代码示例
import com.itextpdf.text.DocumentException; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.*; import java.io.FileOutputStream; import java.io.IOException; public class AddExternalLink { public static void main(String[] args) throws IOException, DocumentException { // 读取目标PDF文件 PdfReader reader = new PdfReader("input.pdf"); // 初始化PdfStamper用于编辑PDF并输出结果 PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("output_external_link.pdf")); // 获取要添加链接的页面(示例为第1页,PDF页码从1开始计数) PdfContentByte pageContent = stamper.getOverContent(1); // 定义链接触发区域:x1,y1为左下角坐标,x2,y2为右上角坐标(PDF以左下角为原点) Rectangle linkArea = new Rectangle(100, 700, 300, 720); // 创建外部链接注释,指定点击后的高亮模式与跳转URL PdfAnnotation linkAnnotation = PdfAnnotation.createLink( stamper.getWriter(), linkArea, PdfAnnotation.HIGHLIGHT_INVERT, // 点击时区域反转高亮,可替换为HIGHLIGHT_NONE取消高亮 PdfAction.createURI("https://example.com") ); // 将注释添加到目标页面 stamper.addAnnotation(linkAnnotation, 1); // 关闭资源 stamper.close(); reader.close(); } }
二、添加内部链接
内部链接用于跳转至PDF文件内的其他页面,需要先定义跳转目标位置,再创建指向该位置的链接注释。
实现代码示例
import com.itextpdf.text.DocumentException; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.*; import java.io.FileOutputStream; import java.io.IOException; public class AddInternalLink { public static void main(String[] args) throws IOException, DocumentException { PdfReader reader = new PdfReader("input.pdf"); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("output_internal_link.pdf")); // 1. 定义跳转目标:跳转到第3页并自适应窗口显示 PdfDestination targetDest = new PdfDestination(PdfDestination.FIT); // 2. 在第1页创建链接区域 Rectangle linkArea = new Rectangle(100, 650, 300, 670); PdfAnnotation linkAnnotation = PdfAnnotation.createLink( stamper.getWriter(), linkArea, PdfAnnotation.HIGHLIGHT_PUSH, // 点击时区域凹陷高亮 // 创建跳转到本地页面的动作 PdfAction.gotoLocalPage(3, targetDest, stamper.getWriter()) ); // 将注释添加到第1页 stamper.addAnnotation(linkAnnotation, 1); stamper.close(); reader.close(); } }
内部链接进阶说明
如果需要跳转到页面内的具体坐标,可替换PdfDestination的创建方式:
// 跳转到第3页x=0、y=800的位置,缩放比例100% PdfDestination targetDest = new PdfDestination(PdfDestination.XYZ, 0, 800, 1f);
内容的提问来源于stack exchange,提问作者shubham mahadik
相关产品推荐
相关产品推荐

