2014-01-09 7 views
7

Ich möchte einen Hyperlink in PDF hinzufügen, das mit PDFBOX erstellt wurde, so dass ich auf ein Textbeispiel klicke "Click here" wird auf URL umleiten. Ich habe versucht mit PDAnnotationLink und PDActionURI, aber wie man es in contentstream hinzufügen?Wie man einen Hyperlink in pdf mit pdfbox hinzufügt

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

Jede Idee, wie die hinzuzufügen "Hier klicken" zum Link? – decal

Antwort

7

zu contentStream den folgenden Code

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

Dies fügt dem Inhaltsstream nicht etwas hinzu, aber Anmerkungen sind nicht Teil des Inhaltsstroms ... – fabian

1

Es gibt eine Bibliothek PDFBox-Layout genannt hinzuzufügen, die es easier to add hyperlinks macht:

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