Search code examples
jasper-reports

Create an external URL hyperlink with JasperReports


How do you include a hyperlink (URL) in a PDF that links to an external site?

Using a simple string like "http://www.stackoverflow.com", a link is automatically generated. But, how can I use a URL like <a href="http://www.stackoverflow.com">Click here</a>?

If I use this HTML string, Jaspers create a link but also shows the code.

Using JasperReports 4.0.4 and iReport 4.5.1.


Solution

  • To make a textField a hyperlink to an external URL, you need to add the attribute hyperlinkType="Reference" to the element, and add a <hyperlinkReferenceExpression> tag within it. The reference expression is where you put the URL.

    For example:

    <textField hyperlinkType="Reference" hyperlinkTarget="Blank">
        <reportElement x="5" y="5" width="200" height="15"/>
        <textElement/>
        <textFieldExpression class="java.lang.String"><![CDATA["Click Here!"]]></textFieldExpression>
        <hyperlinkReferenceExpression><![CDATA["http://www.google.com"]]></hyperlinkReferenceExpression>
    </textField>
    

    The hyperlinkTarget attribute behaves in the same way as the target attribute in HTML.

    Note that only textFields, images, and charts can be hyperlinked in this way.