Monday, February 8, 2010

Exporting Jasper Reports into Pdf,Excel(.xls) and Text (.txt) format with Save As dialog box

Hi friends,

Way of exporting jasper Reports into .pdf, .xls and .txt format with "Save As" dialog to download at client side

my .jrxml file is like this.( ListOfItems.jrxml)


<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="null" pageWidth="595" pageHeight="842" columnWidth="535" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
<queryString language="SQL">
<![CDATA[select inventory_id,
item_no,
(select item_name from bp_items where item_no= bp_inventory.item_no) as item_name,
quantity,
shelf_time,
optimum_shelf_time
from
bp_inventory
order by item_name]]>
</queryString>
<field name="inventory_id" class="java.lang.Integer">
<fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="item_no" class="java.lang.Integer">
<fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="item_name" class="java.lang.String">
<fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="quantity" class="java.math.BigDecimal">
<fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="shelf_time" class="java.lang.String">
<fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="optimum_shelf_time" class="java.lang.String">
<fieldDescription><![CDATA[]]></fieldDescription>
</field>
<background>
<band/>
</background>
<title>
<band height="55">
<staticText>
<reportElement x="65" y="13" width="424" height="35" backcolor="#0000FF"/>
<textElement textAlignment="Center">
<font size="16" isBold="true"/>
</textElement>
<text><![CDATA[Items Report]]></text>
</staticText>
</band>
</title>
<pageHeader>
<band/>
</pageHeader>
<columnHeader>
<band height="18">
<staticText>
<reportElement mode="Opaque" x="0" y="0" width="79" height="18" forecolor="#FFFFFF" backcolor="#4661C2"/>
<textElement textAlignment="Center">
<font fontName="verdana" size="12" isBold="true"/>
</textElement>
<text><![CDATA[Inventory No]]></text>
</staticText>
<staticText>
<reportElement mode="Opaque" x="79" y="0" width="68" height="18" forecolor="#FFFFFF" backcolor="#4661C2"/>
<textElement textAlignment="Center">
<font fontName="verdana" size="12" isBold="true"/>
</textElement>
<text><![CDATA[Item No]]></text>
</staticText>
<staticText>
<reportElement mode="Opaque" x="147" y="0" width="79" height="18" forecolor="#FFFFFF" backcolor="#4661C2"/>
<textElement textAlignment="Center">
<font fontName="verdana" size="12" isBold="true"/>
</textElement>
<text><![CDATA[Item Name]]></text>
</staticText>
<staticText>
<reportElement mode="Opaque" x="226" y="0" width="77" height="18" forecolor="#FFFFFF" backcolor="#4661C2"/>
<textElement textAlignment="Center">
<font fontName="verdana" size="12" isBold="true"/>
</textElement>
<text><![CDATA[Quantity]]></text>
</staticText>
<staticText>
<reportElement mode="Opaque" x="303" y="0" width="103" height="18" forecolor="#FFFFFF" backcolor="#4661C2"/>
<textElement textAlignment="Center">
<font fontName="verdana" size="12" isBold="true"/>
</textElement>
<text><![CDATA[Shelf Time]]></text>
</staticText>
<staticText>
<reportElement mode="Opaque" x="406" y="0" width="147" height="18" forecolor="#FFFFFF" backcolor="#4661C2"/>
<textElement>
<font fontName="verdana" size="12" isBold="true"/>
</textElement>
<text><![CDATA[OptimumShelfTime]]></text>
</staticText>
</band>
</columnHeader>
<detail>
<band height="20">
<textField>
<reportElement x="0" y="0" width="79" height="20"/>
<textElement textAlignment="Center">
<font fontName="Verdana" size="12"/>
</textElement>
<textFieldExpression class="java.lang.Integer"><![CDATA[$F{inventory_id}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="79" y="0" width="68" height="20"/>
<textElement textAlignment="Center">
<font fontName="Verdana" size="12"/>
</textElement>
<textFieldExpression class="java.lang.Integer"><![CDATA[$F{item_no}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="147" y="0" width="79" height="20"/>
<textElement textAlignment="Center">
<font fontName="Verdana" size="12"/>
</textElement>
<textFieldExpression class="java.lang.String"><![CDATA[$F{item_name}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="226" y="0" width="77" height="20"/>
<textElement textAlignment="Center">
<font fontName="Verdana" size="12"/>
</textElement>
<textFieldExpression class="java.math.BigDecimal"><![CDATA[$F{quantity}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="303" y="0" width="103" height="20"/>
<textElement textAlignment="Center">
<font fontName="Verdana" size="12"/>
</textElement>
<textFieldExpression class="java.lang.String"><![CDATA[$F{shelf_time}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="406" y="0" width="147" height="20"/>
<textElement textAlignment="Center">
<font fontName="Verdana" size="12"/>
</textElement>
<textFieldExpression class="java.lang.String"><![CDATA[$F{optimum_shelf_time}]]></textFieldExpression>
</textField>
</band>
</detail>
<columnFooter>
<band/>
</columnFooter>
<pageFooter>
<band height="54">
<textField>
<reportElement x="410" y="15" width="80" height="20"/>
<textElement textAlignment="Right"/>
<textFieldExpression class="java.lang.String"><![CDATA["Page "+$V{PAGE_NUMBER}+" of"]]></textFieldExpression>
</textField>
<textField evaluationTime="Report">
<reportElement x="490" y="15" width="40" height="20"/>
<textElement/>
<textFieldExpression class="java.lang.String"><![CDATA[" " + $V{PAGE_NUMBER}]]></textFieldExpression>
</textField>
</band>
</pageFooter>
<summary>
<band/>
</summary>
</jasperReport>




Code in Action class


//filename is the .jrxml file ( ListOfItems.jrxml)
String filename=request.getParameter("file");
// title is the title of the report.Here we are passing dynamically.So that this class is useful to remaining reports also.
String title=request.getParameter("title");
Connection con = MMSDB.getConnection();
String jrept = filename;
String reportFileName = JasperCompileManager.compileReportToFile(request.getRealPath("/reports") + "/" + jrept);

java.util.Map parameters = new java.util.HashMap();
parameters.put("ReportTitle", title);

File reportFile = new File(reportFileName);
if (!reportFile.exists()) {
throw new JRRuntimeException("File WebappReport.jasper not found. The report design must be compiled first.");
}
JasperPrint jasperPrint = JasperFillManager.fillReport(reportFileName, parameters, con);



//Maintaining request.----


JRHtmlExporter exporter = new JRHtmlExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
HashMap fontMap = new HashMap();
exporter.setParameter(JRHtmlExporterParameter.FONT_MAP, fontMap);
exporter.setParameter(JRHtmlExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
exporter.setParameter(JRHtmlExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
exporter.setParameter(JRHtmlExporterParameter.IS_WRAP_BREAK_WORD, Boolean.TRUE);

request.setAttribute("exportObject", exporter);

if (!reportFile.exists()) {
throw new JRRuntimeException("File WebappReport.jasper not found. The report design must be compiled first.");
}

if (fileType.equals("PDF"))
{
response.setContentType("application/pdf");

JasperExportManager.exportReportToPdfFile(jasperPrint, request.getRealPath("/reports") + "/" +title+".pdf");
File f=new File(request.getRealPath("/reports") + "/" +title+".pdf");
FileInputStream fin = new FileInputStream(f);
ServletOutputStream outStream = response.getOutputStream();
// SET THE MIME TYPE.
response.setContentType("application/pdf");
// set content dispostion to attachment in with file name.
// case the open/save dialog needs to appear.
response.setHeader("Content-Disposition", "attachment;filename='"+title+"'.pdf");

byte[] buffer = new byte[1024];
int n = 0;
while ((n = fin.read(buffer)) != -1) {
outStream.write(buffer, 0, n);
System.out.println(buffer);
}

outStream.flush();
fin.close();
outStream.close();

}
else
if (fileType.equals("EXCEL"))
{
JRXlsExporter exporterXLS = new JRXlsExporter();
exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
exporterXLS.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE);
exporterXLS.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);
exporterXLS.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
exporterXLS.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
exporterXLS.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, request.getRealPath("/reports") + "/" +title+".xls");
exporterXLS.exportReport();
File f=new File(request.getRealPath("/reports") + "/" +title+".xls");
FileInputStream fin = new FileInputStream(f);
ServletOutputStream outStream = response.getOutputStream();
// SET THE MIME TYPE.
response.setContentType("application/vnd.ms-excel");
// set content dispostion to attachment in with file name.
// case the open/save dialog needs to appear.
response.setHeader("Content-Disposition", "attachment;filename="+title+".xls");

byte[] buffer = new byte[1024];
int n = 0;
while ((n = fin.read(buffer)) != -1) {
outStream.write(buffer, 0, n);
System.out.println(buffer);
}

outStream.flush();
fin.close();
outStream.close();

}
else
if (fileType.equals("TEXT"))
{


JRTextExporter exporterTxt = new JRTextExporter();
exporterTxt.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);

exporterTxt.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, request.getRealPath("/reports") + "/" +title+".txt");
exporterTxt.setParameter(JRTextExporterParameter.CHARACTER_WIDTH, new Integer(7));

exporterTxt.setParameter(JRTextExporterParameter.CHARACTER_HEIGHT, new Integer(11));

exporterTxt.exportReport();

File f=new File(request.getRealPath("/reports") + "/" + title+".txt");
FileInputStream fin = new FileInputStream(f);
ServletOutputStream outStream = response.getOutputStream();
// SET THE MIME TYPE.
response.setContentType("application/text");
// set content dispostion to attachment in with file name.
// case the open/save dialog needs to appear.
response.setHeader("Content-Disposition", "attachment;filename="+title+".txt");

byte[] buffer = new byte[1024];
int n = 0;
while ((n = fin.read(buffer)) != -1) {
outStream.write(buffer, 0, n);
System.out.println(buffer);
}

outStream.flush();
fin.close();
outStream.close();

26 comments:

  1. Im Getting this error. please help me.

    Messages: org.apache.poi.hssf.usermodel.HSSFCellStyle
    org/apache/poi/hssf/usermodel/HSSFCellStyle

    File: org/apache/catalina/loader/WebappClassLoader.java

    ReplyDelete
  2. I have tested my application with this code.It is working fine here. I think it is problem with jasper reports version or library files supported are not included properly to your application .
    Library files included in my application are

    1) iText-2.1.0.jar
    2) jasperreports-3.5.1.jar
    3) jfreechart-1.0.12.jar
    4) commons-collections-2.1.1.jar
    5) displaytag-1.2.jar
    6) jakarta-oro.jar
    7) jxl-2.6.jar
    8) poi-3.2-FINAL.jar
    9) commons-fileupload-1.0.jar

    ReplyDelete
  3. Thanks,This is really helpful.

    I am looking for Custom Datasource like Colleciton of JavaBeans pass to JasperReport which I can use to stream report from JSP or servlet without using struts 2.0 plugin.

    Do you have any idea?

    ReplyDelete
  4. Actually i didn't get the chance to implement jasper Report with this scenario.
    Anyway i will try to implement with this scenario and will post it.

    Meanwhile you can look at the following URL. It may helpful to you.

    http://knol.google.com/k/jasper-reports-working-with-beans-and-sub-report#An_Example_of_Using_An_ArrayList_As_A_Data_Source_For_JasperReports

    Thanks

    ReplyDelete
  5. hi how to increase column width of jrxml cross tab report?

    ReplyDelete
  6. hi,
    how to delete the field in jasper report at dynamic timing.
    1.Actually i created 20 column as default but i am using only 12 column then i want remove temporaly the column at runtime.how to do.

    ReplyDelete
  7. hi how to increase column width of jrxml cross tab report?

    You can change width in jrxml file

    <textField evaluationTime="Report">
    <report Element x="490" y="15" width="40" height="20"/>
    <textElement/>
    <textFieldExpression class="java.lang.String"><![CDATA[" " + $V{PAGE_NUMBER}]]></textFieldExpression>
    </textField>

    ReplyDelete
  8. Hi Viju,

    Do you mean hiding of columns which are unused?

    ReplyDelete
  9. This comment has been removed by a blog administrator.

    ReplyDelete
  10. I want to ask one question.
    I want to response back two pdf reports from Struts ActionForward.

    I can return only one jasper report in pdf file.
    Is there a way to return back multiple pdf (as popups) from the JSP page.

    Thanks.

    ReplyDelete
  11. really good good article.Helped a lot.
    Thank You So much

    ReplyDelete
  12. how to increse size of page based on content

    ReplyDelete
  13. how to get one page in landscape and after that another page in portrait

    ReplyDelete
  14. How I can use parameter "exportObject" correctly in this case?

    ReplyDelete
  15. Hello ,
    i 've created a pdf displaying it on browser with java and not JSP for work reasons.

    here is the code:

    public void provaJasper()throws Exception
    {Connection conn = JPAUtils.getConnection();
    Map parameters = new HashMap();
    String REPORT = null;
    String ReportPDF = null;
    REPORT = "LogSoggetti_parData.jasper";
    ReportPDF = "LogSoggetti_parData.pdf";
    java.sql.Date data1 = new java.sql.Date(sogFakeStampa1.getDataOrigine().getTime());
    java.sql.Date data2 = new java.sql.Date(sogFakeStampa2.getDataOrigine().getTime());
    String data_da = data1.toString();
    String data_a = data2.toString();
    parameters.put("data_da", data_da);
    parameters.put("data_a", data_a);

    InputStream reportTemplate = this.getClass().getClassLoader().getResourceAsStream(REPORT);
    JasperPrint jasperPrint;
    byte[] pdf = null;
    jasperPrint = JasperFillManager.fillReport(reportTemplate, parameters, conn);
    pdf = JasperExportManager.exportReportToPdf(jasperPrint);
    conn.close();
    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletResponse response =(HttpServletResponse) context.getExternalContext().getResponse();
    try {
    OutputStream os = response.getOutputStream();
    response.setContentType("application/pdf");
    response.setContentLength(pdf.length);
    response.addHeader("Content-disposition","inline; filename=/"+ ReportPDF);
    os.write(pdf);
    os.flush();
    os.close();
    context.responseComplete();
    }catch (IOException e){
    log.info("--- ERRORE NELLA GESTIONE DEL FILE .PDF ---");
    }

    }

    the problem is when it is shown on the browser , it doesn't display the name of the file of PDF .
    any ideas ?

    ReplyDelete
  16. I am using struts 2 and struts2jasperreport plugin . Is there any need to use seperate Exporter classes such as JRXlsExporter , JRTextExporter
    or simply add each format in struts.xml
    as param name="format"PDF param ?

    what is the difference between these two approach ?

    ReplyDelete
  17. i tried for xls in struts but giving xls with static text only not data.Why??

    ReplyDelete
  18. Hi

    I have used font extensions . Using verdana font for my pdfs
    When i run in a linux pc there are some alignment issues in the PDF.

    It's working fine in windows PC. Any idea.............

    ReplyDelete
  19. how can i view the single customer data as a report in struts2?

    ReplyDelete
  20. it is very helpful and its works for me.

    ReplyDelete
  21. Hi, I want to display image in xsl while export from jasper report.Now I am getting image in xsl,Please help me

    ReplyDelete
  22. Hi. All I need to export files in Postscript file format using jasper. Can any one help me how to achive this?

    I can export reports using my jrxml in PDF, CSV, XML, XLS, TXT, but not able to export in PS file format.

    Any help will be appreciated.

    ReplyDelete
  23. hey I want to view jasper report when client click on url . and its dependent on client that he will print or not in struts 2 . you have any idea about this senerio . Please give me proper Answer with librery which i will use .

    ReplyDelete
  24. Hi, this is really useful for me.
    Thanks

    ReplyDelete
  25. I am getting an error as pdf is damaged or corrupted..

    ReplyDelete