How to add hyperlink in pdf using pdfbox

java, pdf, pdf-generation, pdfbox

Solution

To add to `contentStream` use the following code

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

Problem

I want to add a hyperlink in PDF created using `PDFBOX`, such that i click on some text example 'Click here' will redirect to URL. I tried using `PDAnnotationLink` and `PDActionURI`, but how to add it in `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(); ```

Original source