2012-11-28 22 views
4

我使用ireport設計器設計了一個jasper報告,其中我在報告的標題中添加了徽標圖像。該圖像是從本地機器上的硬編碼路徑添加的。我需要從我的項目類路徑中添加徽標圖像。爲此,我在程序提供的報告中爲圖像創建了一個參數。如何添加圖像作爲jasper報告中項目classpath的參數

InputStream imgInputStream = this.getClass().getResourceAsStream("header.png"); 

HashMap<String, Object> parameters = new HashMap<String, Object>(); 
parameters.put("dateFrom", datum1); 
parameters.put("dateTo", datum2); 
parameters.put("logo", imgInputStream); 


strQuery = "Select calldate,src,dst,duration,disposition,cdrcost from cdrcost where date(calldate) between '" + datum1 + "' and '" + datum2 + "'"; 

rs = conexiondb.Consulta(strQuery); 
JRResultSetDataSource resultSetDataSource = new JRResultSetDataSource(rs); 
//JasperPrint jasperPrint = JasperFillManager.fillReport(reportStream, parameters); 

JasperRunManager.runReportToPdfStream(reportStream, fos, parameters, resultSetDataSource); 

而且下面是報告中的圖像片段:

<image> 
    <reportElement x="0" y="1" width="555" height="61"/> 
    <imageExpression><![CDATA[$P{logo}]]> 
    </imageExpression> 
</image> 

回答

22

我們總是傳遞圖像,而不是爲InputStream英寸首先加載圖像,並將其設置在參數圖:

BufferedImage image = ImageIO.read(getClass().getResource("/images/IMAGE.png")); 
parameters.put("logo", image); 

則該參數僅僅是這樣定義:

<parameter name="logo" class="Object" isForPrompting="false"> 
    <parameterDescription><![CDATA[The letterhead image]]></parameterDescription> 
    <defaultValueExpression><![CDATA[]]></defaultValueExpression> 
</parameter> 

,並放置在報告時的模樣:

<image> 
    <reportElement x="324" y="16" width="154" height="38"/> 
    <imageExpression><![CDATA[$P{logo}]]></imageExpression> 
</image> 
+1

先生,我也一樣,但它並沒有發生圖像不從classpath和PDF報告加載不產生 – Amit

+0

圖像爵士沒有與加載此代碼並獲取錯誤「java.lang.IllegalArgumentException:input == null!」 – Amit

+0

我假設你用'「header.png」'替換'「/images/IMAGE.png」'?如果它在jar的默認包中,請嘗試'「/header.png」'。 –

0

您可以輕鬆地從classpath/classloader獲取URL。這是<imageExpression>的有效輸入,因此您可以使用它將圖像嵌入到您的PDF中。以下爲我工作:

設置參數:

URL url = this.getClass().getClassLoader().getResource("pdf/my_image.tif"); 
parameters.put("logo", url); 

宣言報告:報告

<parameter name="logo" class="java.net.URL"> 
    <defaultValueExpression><![CDATA[]]></defaultValueExpression> 
</parameter> 

用法。

<image> 
    <reportElement x="100" y="30" width="135" height="30"/> 
    <imageExpression><![CDATA[$P{logo}]]></imageExpression> 
</image> 

一些補充意見

  • 我使用InputStream和顯示圖像時只有一次它工作得很好了。當我需要重複該圖像時,InputStream不起作用,因爲該流在第一個顯示屏上消耗完畢,因此無法在此之後使用。我沒有找到一個簡單的方法來重置它。
  • 我發現網址,可能會從這裏被使用:http://jasperreports.sourceforge.net/sample.reference/images/index.html
相關問題