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

我想在使用PDFBOX创建的PDF中添加一个超链接,这样我点击一些文本示例“点击此处”将重定向到URL。 我尝试使用PDAnnotationLinkPDActionURI ,但如何在contentstream添加它?

 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(); 

要添加到contentStream使用以下代码

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

有一个名为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);