如何使用PDFBox创建链接,我可以单击该链接转到同一文档中的另一个页面 [英] How to use PDFBox to create a link i can click to go to another page in the same document

查看:201
本文介绍了如何使用PDFBox创建链接,我可以单击该链接转到同一文档中的另一个页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用PDFBox创建一个链接,我可以单击该链接转到同一文档中的另一个页面。

从这个问题(How to use PDFBox to create a link that goes to *previous view*?)我知道这应该很容易做到,但是当我尝试这样做时,我得到了这个错误:在线程"main"java.lang.IlLegalArgumentException:GoTo操作的目标必须是页面字典对象

我正在使用以下代码:

//Loading an existing document consisting of 3 empty pages.
    File file = new File("C:\Users\Student\Documents\MyPDF\Test_doc.pdf");
    PDDocument document = PDDocument.load(file);
    PDPage page = document.getPage(1);

    PDAnnotationLink link         = new PDAnnotationLink();
    PDPageDestination destination = new PDPageFitWidthDestination();
    PDActionGoTo action           = new PDActionGoTo();

    destination.setPageNumber(2);
    action.setDestination(destination);
    link.setAction(action);
    link.setPage(page);

我正在使用PDFBox 2.0.13,有人能给我一些指导吗?我哪里做错了?

感谢所有答案。

推荐答案

首先,对于本地链接("我可以单击以转到同一文档中的另一页"),destination.setPageNumber是错误的使用方法,cf。其Java文档:

/**
 * Set the page number for a remote destination. For an internal destination, call 
 * {@link #setPage(PDPage) setPage(PDPage page)}.
 *
 * @param pageNumber The page for a remote destination.
 */
public void setPageNumber( int pageNumber )

因此,替换

destination.setPageNumber(2);

destination.setPage(document.getPage(2));

此外,您忘记为链接设置矩形区域,并且忘记将链接添加到页面批注。

全部:

PDPage page = document.getPage(1);

PDAnnotationLink link         = new PDAnnotationLink();
PDPageDestination destination = new PDPageFitWidthDestination();
PDActionGoTo action           = new PDActionGoTo();

destination.setPage(document.getPage(2));
action.setDestination(destination);
link.setAction(action);
link.setPage(page);

link.setRectangle(page.getMediaBox());
page.getAnnotations().add(link);

(AddLink测试testAddLinkToMwb_I_201711)

这篇关于如何使用PDFBox创建链接,我可以单击该链接转到同一文档中的另一个页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆