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

2022-07-18 00:00:00 pdf hyperlink javascript pdfbox

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

我想使用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 ); 

解决方案

该操作是一个GoTo操作,它将页面2对象作为目标。并且它有一个"Next"条目,该条目具有Java脚本操作。

此代码复制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({
"
        + "page: 1,
"
        + "type: "Underline",
"
        + "quads: this.getPageNthWordQuads(1, 4),
"
        + "author: "Brad Colin",
"
        + "contents: "Fifth word on page 2"
"
        + "});";
PDActionJavaScript jsAction = new PDActionJavaScript(js);
actionList.add(jsAction);
gotoAction.setNext(actionList);
myLink.setAction(gotoAction);

annotations.add(myLink);

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

相关文章