PDFBox - 如何单击PDF文件中的链接以移动到另一个页面并在其中加下特定文本的下划线?

时间:2017-12-19 12:01:55

标签: javascript pdf hyperlink pdfbox

在Adobe Acrobat中,我可以在PDF文件中定义一个链接,并在点击它以转到另一个页面并设置该页面中特定单词的下划线时设置JavaScript操作,如下图所示: / p>

enter image description here

我想使用Java的PDFBox库做同样的事情。我已经成功定义了一个链接,但是如何设置该链接的JavaScript代码以移动到另一个页面并在该页面中为特定单词加下划线?

这是我目前的代码:

PDAnnotationLink myLink = new PDAnnotationLink();
/*
 * Some code here to define the link, then i should define the link action.
 */
PDActionJavaScript javascriptAction = new PDActionJavaScript( "app.alert(     \"I should now go to page 10 and undeline a word out there.\" );" );
myLink.setAction( javascriptAction );
annotations.add( myLink ); 

1 个答案:

答案 0 :(得分:1)

该操作是GoTo操作,它将第2页对象作为目标。它有一个“下一个”条目,那个人有Javascript动作。

此代码复制了Adobe一直在做的事情:

List<PDAnnotation> annotations = pdfDocument.getPage(0).getAnnotations();
PDAnnotationLink myLink = new PDAnnotationLink();
myLink.setRectangle(new PDRectangle(122.618f, 706.037f, 287.127f-122.618f, 718.255f-706.037f));
myLink.setColor(new PDColor(new float[]{1, 1 / 3f, 0}, PDDeviceRGB.INSTANCE));
PDBorderStyleDictionary bs = new PDBorderStyleDictionary();
bs.setWidth(3);
bs.setStyle(PDBorderStyleDictionary.STYLE_UNDERLINE);            
myLink.setBorderStyle(bs);

PDPageFitRectangleDestination dest = new PDPageFitRectangleDestination();
dest.setLeft(48);
dest.setBottom(401);
dest.setRight(589);
dest.setTop(744);
dest.setPage(pdfDocument.getPage(1));
PDActionGoTo gotoAction = new PDActionGoTo();
gotoAction.setDestination(dest);
List<PDAction> actionList = new ArrayList<>();
String js = "var annot = this.addAnnot({\n"
        + "page: 1,\n"
        + "type: \"Underline\",\n"
        + "quads: this.getPageNthWordQuads(1, 4),\n"
        + "author: \"Brad Colin\",\n"
        + "contents: \"Fifth word on page 2\"\n"
        + "});";
PDActionJavaScript jsAction = new PDActionJavaScript(js);
actionList.add(jsAction);
gotoAction.setNext(actionList);
myLink.setAction(gotoAction);

annotations.add(myLink);

pdfDocument.save("1-new.pdf");