如何使用pdfbox在pdf中添加超链接

2022-09-03 02:09:02

我想在PDF中添加一个超链接,使用,这样我点击一些文本示例“点击这里”将重定向到URL。我尝试使用 和 ,但如何将其添加到?PDFBOXPDAnnotationLinkPDActionURIcontentstream

PDBorderStyleDictionary borderULine = new PDBorderStyleDictionary();
borderULine.setStyle(PDBorderStyleDictionary.STYLE_UNDERLINE);
PDAnnotationLink txtLink = new PDAnnotationLink();
txtLink.setBorderStyle(borderULine);
txtLink.setColour(colourBlue);

// add an action
PDActionURI action = new PDActionURI();
action.setURI("www.google.com");
txtLink.setAction(action);

contentStream.beginText();
contentStream.moveTextPositionByAmount(400, y-30);
contentStream.drawString(txtLink);----error
contentStream.endText();

答案 1

添加以使用以下代码contentStream

    PDRectangle position = new PDRectangle();
    position.setLowerLeftX(10);
    position.setLowerLeftY(20); 
    position.setUpperRightX(100); 
    position.setUpperRightY(10); 
    txtLink.setRectangle(position);
    page.getAnnotations().add(txtLink);

答案 2

有一个名为PDFBox-Layout的库,可以更轻松地添加超链接

Document document = new Document();

Paragraph paragraph = new Paragraph();
paragraph.addMarkup(
   "This is a link to {link[https://github.com/ralfstuckert/pdfbox-layout]}PDFBox-Layout{link}",
 18f, BaseFont.Helvetica);
document.add(paragraph);

final OutputStream outputStream = new FileOutputStream("link.pdf");
document.save(outputStream);

推荐