在 Java 中创建 PDF 链接
Contents
[
Hide
]
Aspose.PDF for Java 使用 LinkAnnotation 以及一个操作对象来定义链接行为。
创建启动操作链接
当链接批注应启动外部文件或目标时请使用此示例。
- 打开源 PDF Document 并选择目标页面。
- 创建 LinkAnnotation 并配置其边框和颜色。
- 分配 a LaunchAction 并保存文档。
public static void createLinkAnnotationLaunchAction(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
Page page = document.getPages().get_Item(1);
LinkAnnotation link = new LinkAnnotation(page, new Rectangle(10, 580, 120, 600, true));
Border border = new Border(link);
border.setWidth(5);
border.setDash(new Dash(1, 1));
link.setBorder(border);
link.setColor(Color.getGreen());
link.setAction(new LaunchAction(document, inputFile.toString()));
page.getAnnotations().add(link);
document.save(outputFile.toString());
}
}
创建一个远程跳转链接
当链接应在另一个 PDF 文档中打开页面时,请使用此示例。
- 打开源 PDF Document。
- 在目标页面上创建 LinkAnnotation。
- 分配 a GoToRemoteAction 并保存输出文件。
public static void createLinkAnnotationGoToRemoteAction(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
Page page = document.getPages().get_Item(1);
LinkAnnotation link = new LinkAnnotation(page, new Rectangle(10, 580, 120, 600, true));
link.setColor(Color.getGreen());
link.setAction(new GoToRemoteAction(inputFile.toString(), 1));
page.getAnnotations().add(link);
document.save(outputFile.toString());
}
}
创建内部跳转链接
在链接应在同一 PDF 文档的另一页之间导航时,请使用此示例。
- 打开源 PDF Document。
- 创建 LinkAnnotation 并配置其外观。
- 分配 a GoToAction 转到目标页面并保存文档。
public static void createLinkAnnotationGoToAction(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
Page page = document.getPages().get_Item(1);
LinkAnnotation link = new LinkAnnotation(page, new Rectangle(10, 580, 120, 600, true));
Border border = new Border(link);
border.setWidth(5);
border.setDash(new Dash(1, 1));
link.setBorder(border);
link.setColor(Color.getGreen());
if (document.getPages().size() >= 4) {
link.setAction(new GoToAction(document.getPages().get_Item(4)));
} else {
link.setAction(new GoToAction(document.getPages().get_Item(document.getPages().size())));
}
page.getAnnotations().add(link);
document.save(outputFile.toString());
}
}
创建 URI 链接
当链接应通过 URI 操作打开 Web 资源时,请使用此示例。
- 打开源 PDF Document。
- 在页面上创建 LinkAnnotation。
- 分配 a GoToURIAction 并保存输出文件。
public static void createLinkAnnotationGoToUriAction(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
Page page = document.getPages().get_Item(1);
LinkAnnotation link = new LinkAnnotation(page, new Rectangle(10, 580, 120, 600, true));
link.setColor(Color.getGreen());
link.setAction(new GoToURIAction("https://docs.aspose.com/pdf/python"));
page.getAnnotations().add(link);
document.save(outputFile.toString());
}
}