Hot questions for Using JasperReports in pdf

Question:

When using different fonts in jasper report, you need to use font-extensions.

However if the font is not rendered correctly is there a way that I can test if the font is supported by pdf so that I can understand if the problem is related to my font-extensions or to my .ttf font?

The incorrect rendering of font when exporting to pdf from jasper reports is a common problem example Jasper Reports PDF doesn't export cyrillic values, as seen in checklist point 1 using font-extensions are not always enough, the font need's also to be supported by pdf generating library and able to render the actual character. This is why I have decided to pass this Q-A style questions, so that future user when hitting checklist 1 can have a reference on how to quickly test the font.


Answer:

Since jasper report use the itext library the easiest way to test if your font will be rendered correctly in pdf is to test it directly with itext.

Example program*, adapted from iText: Chapter 11: Choosing the right font

import java.io.FileOutputStream;
import java.io.IOException;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.ColumnText;
import com.lowagie.text.pdf.PdfWriter;

public class FontTest {

    /** The resulting PDF file. */
    public static final String RESULT = "fontTest.pdf";
    /** the text to render. */
    public static final String TEST = "Test to render this text with the turkish lira character \u20BA";

    public void createPdf(String filename) throws IOException, DocumentException {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        document.open();
        BaseFont bf = BaseFont.createFont(
            "pathToMyFont/myFont.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        Font font = new Font(bf, 20);
        ColumnText column = new ColumnText(writer.getDirectContent());
        column.setSimpleColumn(36, 730, 569, 36);
        column.addElement(new Paragraph(TEST, font));
        column.go();
        document.close();
    }

    public static void main(String[] args) throws IOException, DocumentException {
        new FontTest().createPdf(RESULT);
    }
}

Some notes (seen in example):

  • To render special characters use it's encoded value example \u20BA to avoid problems of encoding type on your file.
  • Consider to always use Unicode encoding, this is recommended approach in the newer PDF standard (PDF/A, PDF/UA) and gives you the possibility to mix different encoding types, with the only dis-advantage of slightly larger file size.

Conclusion:

If your font is rendered correctly in the "fontTest.pdf", you have a problem with your font-extensions in jasper report.

If you font is not rendered correctly in the "fontTest.pdf", there is nothing you can do in jasper reports, you need to find another font.


*Latest jasper-reports distribution use a special version itext-2.1.7, the imports in this version is com.lowagie.text, if you are using later version the imports are com.itextpdf.text as in adapted example.

Question:

I'm using multiple fonts in one of my reports that I export as a PDF, I'm using IREPORT to design my report.

In the preview section the report looks good but when I export it from my web app it looks like I'm using one font for the whole report.

I've searched this issue and I found two solutions for it:

  1. Export the font as .jar file from IREPORT and add it to my project [ Not a Clean way, Since I'm using Maven ].

  2. Use jasperreports_extension.properties [the one I'm having problem with!].

I followed this tutorial step by step but still no result no error no nothing.

Here is the code I'm using:

jasperreports_extension.properties:

net.sf.jasperreports.extension.registry.factory.fonts=net.sf.jasperreports.engine.fonts.SimpleFontExtensionsRegistryFactory
net.sf.jasperreports.extension.simple.font.families.myfamily=fonts/fonts.xml

fonts.xml:

<?xml version="1.0" encoding="UTF-8"?>

<fontFamilies>

    <fontFamily name="Arial">
        <normal><![CDATA[fonts/arial.ttf]]></normal>
        <pdfEmbedded><![CDATA[true]]></pdfEmbedded>
    </fontFamily>

    <fontFamily name="Algerian">
        <normal><![CDATA[fonts/Algerian.ttf]]></normal>
        <pdfEmbedded><![CDATA[true]]></pdfEmbedded>
    </fontFamily>

    <fontFamily name="Bell Mt">
        <normal><![CDATA[fonts/bell-mt.ttf]]></normal>
        <pdfEmbedded><![CDATA[true]]></pdfEmbedded>
    </fontFamily>

    <fontFamily name="Savoye Std">
        <normal><![CDATA[fonts/SavoyeStd.ttf]]></normal>
        <pdfEmbedded><![CDATA[true]]></pdfEmbedded>
    </fontFamily>

    <fontFamily name="Cambria">
        <normal><![CDATA[fonts/Cambria.ttf]]></normal>
        <normal><![CDATA[fonts/cambriab.ttf]]></normal>
        <normal><![CDATA[fonts/cambriai.ttf]]></normal>
        <normal><![CDATA[fonts/cambriaz.ttf]]></normal>
        <pdfEmbedded><![CDATA[true]]></pdfEmbedded>
    </fontFamily>

</fontFamilies>

Since I'm using spring I tried this also fonts.xml:

<?xml version="1.0" encoding="UTF-8"?>

<beans:beans 

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"

    xmlns:jee="http://www.springframework.org/schema/jee"

    xsi:schemaLocation="

        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.3.xsd

        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">

    <beans:bean id="Arial" class="net.sf.jasperreports.engine.fonts.SimpleFontFamily">

        <beans:property name="name" value="Arial"/>
        <beans:property name="normal" value="fonts/arial.ttf"/>       
        <beans:property name="pdfEncoding" value="Identity-H"/>
        <beans:property name="pdfEmbedded" value="true"/>

    </beans:bean>

    <beans:bean id="Algerian" class="net.sf.jasperreports.engine.fonts.SimpleFontFamily">

        <beans:property name="name" value="Algerian"/>
        <beans:property name="normal" value="fonts/Algerian.ttf"/>       
        <beans:property name="pdfEncoding" value="Identity-H"/>
        <beans:property name="pdfEmbedded" value="true"/>

    </beans:bean>

    <beans:bean id="BellMt" class="net.sf.jasperreports.engine.fonts.SimpleFontFamily">

        <beans:property name="name" value="Bell Mt"/>
        <beans:property name="normal" value="fonts/bell-mt.ttf"/>       
        <beans:property name="pdfEncoding" value="Identity-H"/>
        <beans:property name="pdfEmbedded" value="true"/>

    </beans:bean>

    <beans:bean id="SavoyeStd" class="net.sf.jasperreports.engine.fonts.SimpleFontFamily">

        <beans:property name="name" value="Savoye Std"/>
        <beans:property name="normal" value="fonts/SavoyeStd.ttf"/>       
        <beans:property name="pdfEncoding" value="Identity-H"/>
        <beans:property name="pdfEmbedded" value="true"/>

    </beans:bean>

    <beans:bean id="Cambria" class="net.sf.jasperreports.engine.fonts.SimpleFontFamily">

        <beans:property name="name" value="Cambria"/>
        <beans:property name="normal" value="fonts/Cambria.ttf"/>
        <beans:property name="bold" value="fonts/cambriab.ttf"/>
        <beans:property name="italic" value="fonts/cambriai.ttf"/>
        <beans:property name="boldItalic" value="fonts/cambriaz.ttf"/>       
        <beans:property name="pdfEncoding" value="Identity-H"/>
        <beans:property name="pdfEmbedded" value="true"/>

    </beans:bean>

</beans:beans>

And the font files in the font folder in the root package.


Answer:

A big thank you to @Tunaki for helping me to solve this issue.

The problem was solved by putting the jasperreports_extension.properties and the fonts folder in the root of the project like this:

Question:

I am trying to export jasper as pdf but It does not show the cyrillic values. When I export it as excel it does show and the output is fine, but when I try to export is as PDF it does not export the cyrillic values. The cyrillic values are not written in cyrillic font, they are written as cyrillic keyboard.

The code I use to export is:

JRExporter e = new JRPdfExporter();
                e.setParameter(JRPdfExporterParameter.JASPER_PRINT, jasperPrint);
                e.setParameter(JRPdfExporterParameter.OUTPUT_STREAM, outStream);
                e.setParameter(JRPdfExporterParameter.OUTPUT_FILE_NAME, NAME);

I even tried to specift the parameter below:

e.setParameter(JRPdfExporterParameter.CHARACTER_ENCODING, "UTF-8");

but did not succeed. Any suggestions?


Answer:

Jasper report uses iText and always when a char is not rendered in pdf this should be the checklist:

  1. Is my actual .tff supported (OpenType) and can the font actually render the character. Not all fonts render all characters in UTF-8, see How can I test if my font is rendered correctly in pdf?
  2. Do I pass correct encoding to iText. In doubts (or in general) use the encoding Identity-H this is recommend for newer PDF standards and gives you the ability to mix different encoding.
  3. Is my font embedded so that if I share the pdf also computers not having this font can display the content?
How can I ensure this is JasperReport?

The deprecated method was to set attributes on the textElement

<textElement>
  <font pdfFontName="Helvetica" pdfEncoding="Identity-H" isPdfEmbedded="true"/>
  <paragraph lineSpacing="Single"/>
</textElement>

The current non deprecated method v 3-6, is to add Font Extensions and this is easily achieved by using tools like iReport or JasperSoft Studio that can generate a .jar of your font extension so that you can include it in your classpath directly.

How to generate font extension .jar using iReport or JasperSoft Studio.

EDIT: The problem of OP was 1 on checklist (.ttf font could not render), but surely he should consider both 2 and 3 using non deprecated method.

Question:

I'm having some issues with the fonts when I'm deploying the reports in my web app. The fonts I want to have in my result pdfs are Arial, Calibri and Century Gothic.

I followed all the steps pointed here but couldn't get it working.

Here's what I did:

I modified the content of my jasperreports_extension.properties like following:

net.sf.jasperreports.extension.registry.factory.simple.font.families=net.sf.jasperreports.engine.fonts.SimpleFontExtensionsRegistryFactory
net.sf.jasperreports.extension.simple.font.families.dejavu=net/sf/jasperreports/fonts/fonts.xml
net.sf.jasperreports.extension.simple.font.families.arial=net/sf/jasperreports/fonts/fonts.xml
net.sf.jasperreports.extension.simple.font.families.calibri=net/sf/jasperreports/fonts/fonts.xml
net.sf.jasperreports.extension.simple.font.families.centurygothic=net/sf/jasperreports/fonts/fonts.xml

Then at net\sf\jasperreports\fonts I put the three folders for the fonts containing the four styles (normal, bold, italic and bold-italic) for each of the fonts before mentioned.

Also, modified the fonts.xml at net/sf/jasperreports/fonts and it looks like this now:

<?xml version="1.0" encoding="UTF-8"?>

<fontFamilies>

    <fontFamily name="DejaVu Sans">
        <normal>net/sf/jasperreports/fonts/dejavu/DejaVuSans.ttf</normal>
        <bold>net/sf/jasperreports/fonts/dejavu/DejaVuSans-Bold.ttf</bold>
        <italic>net/sf/jasperreports/fonts/dejavu/DejaVuSans-Oblique.ttf</italic>
        <boldItalic>net/sf/jasperreports/fonts/dejavu/DejaVuSans-BoldOblique.ttf</boldItalic>
        <pdfEncoding>Identity-H</pdfEncoding>
        <pdfEmbedded>true</pdfEmbedded>
        <exportFonts>
            <export key="net.sf.jasperreports.html">'DejaVu Sans', Arial, Helvetica, sans-serif</export>
            <export key="net.sf.jasperreports.xhtml">'DejaVu Sans', Arial, Helvetica, sans-serif</export>
        </exportFonts>
        <!--
        <locales>
            <locale>en_US</locale>
            <locale>de_DE</locale>
        </locales>
        -->
    </fontFamily>

    <fontFamily name="DejaVu Serif">
        <normal>net/sf/jasperreports/fonts/dejavu/DejaVuSerif.ttf</normal>
        <bold>net/sf/jasperreports/fonts/dejavu/DejaVuSerif-Bold.ttf</bold>
        <italic>net/sf/jasperreports/fonts/dejavu/DejaVuSerif-Italic.ttf</italic>
        <boldItalic>net/sf/jasperreports/fonts/dejavu/DejaVuSerif-BoldItalic.ttf</boldItalic>
        <pdfEncoding>Identity-H</pdfEncoding>
        <pdfEmbedded>true</pdfEmbedded>
        <exportFonts>
            <export key="net.sf.jasperreports.html">'DejaVu Serif', 'Times New Roman', Times, serif</export>
            <export key="net.sf.jasperreports.xhtml">'DejaVu Serif', 'Times New Roman', Times, serif</export>
        </exportFonts>
    </fontFamily>

    <fontFamily name="DejaVu Sans Mono">
        <normal>net/sf/jasperreports/fonts/dejavu/DejaVuSansMono.ttf</normal>
        <bold>net/sf/jasperreports/fonts/dejavu/DejaVuSansMono-Bold.ttf</bold>
        <italic>net/sf/jasperreports/fonts/dejavu/DejaVuSansMono-Oblique.ttf</italic>
        <boldItalic>net/sf/jasperreports/fonts/dejavu/DejaVuSansMono-BoldOblique.ttf</boldItalic>
        <pdfEncoding>Identity-H</pdfEncoding>
        <pdfEmbedded>true</pdfEmbedded>
        <exportFonts>
            <export key="net.sf.jasperreports.html">'DejaVu Sans Mono', 'Courier New', Courier, monospace</export>
            <export key="net.sf.jasperreports.xhtml">'DejaVu Sans Mono', 'Courier New', Courier, monospace</export>
        </exportFonts>
    </fontFamily>

    <!--
        Mapping Java logical fonts, for the sake of HTML export only.
    -->

    <fontFamily name="SansSerif">
        <exportFonts>
            <export key="net.sf.jasperreports.html">'DejaVu Sans', Arial, Helvetica, sans-serif</export>
            <export key="net.sf.jasperreports.xhtml">'DejaVu Sans', Arial, Helvetica, sans-serif</export>
        </exportFonts>
    </fontFamily>
    <fontFamily name="Serif">
        <exportFonts>
            <export key="net.sf.jasperreports.html">'DejaVu Serif', 'Times New Roman', Times, serif</export>
            <export key="net.sf.jasperreports.xhtml">'DejaVu Serif', 'Times New Roman', Times, serif</export>
        </exportFonts>
    </fontFamily>
    <fontFamily name="Monospaced">
        <exportFonts>
            <export key="net.sf.jasperreports.html">'DejaVu Sans Mono', 'Courier New', Courier, monospace</export>
            <export key="net.sf.jasperreports.xhtml">'DejaVu Sans Mono', 'Courier New', Courier, monospace</export>
        </exportFonts>
    </fontFamily>

    <fontFamily name="Arial">
       <normal>net/sf/jasperreports/fonts/arial/arial.ttf</normal>
       <bold>net/sf/jasperreports/fonts/arial/ArialBold.ttf</bold>
       <italic>net/sf/jasperreports/fonts/arial/ArialItalic.ttf</italic>
       <boldItalic>net/sf/jasperreports/fonts/arial/ArialBoldItalic.ttf</boldItalic>
       <pdfEncoding>Identity-H</pdfEncoding>
       <pdfEmbedded>true</pdfEmbedded>
       <exportFonts>
           <export key="net.sf.jasperreports.html">'Arial'</export>
           <export key="net.sf.jasperreports.xhtml">'Arial'</export>
       </exportFonts>
    </fontFamily>

    <fontFamily name="Calibri">
       <normal>net/sf/jasperreports/fonts/calibri/calibri.ttf</normal>
       <bold>net/sf/jasperreports/fonts/calibri/calibri-bold.ttf</bold>
       <italic>net/sf/jasperreports/fonts/calibri/calibri-italic.ttf</italic>
       <boldItalic>net/sf/jasperreports/fonts/calibri/calibri-bold-italic.ttf</boldItalic>
       <pdfEncoding>Identity-H</pdfEncoding>
       <pdfEmbedded>true</pdfEmbedded>
       <exportFonts>
           <export key="net.sf.jasperreports.html">'Calibri'</export>
           <export key="net.sf.jasperreports.xhtml">'Calibri'</export>
       </exportFonts>
    </fontFamily>

    <fontFamily name="Century Gothic">
       <normal>net/sf/jasperreports/fonts/centurygothic/century-gothic.ttf</normal>
       <bold>net/sf/jasperreports/fonts/centurygothic/century-gothic-bold.ttf</bold>
       <italic>net/sf/jasperreports/fonts/centurygothic/century-gothic-italic.ttf</italic>
       <boldItalic>net/sf/jasperreports/fonts/centurygothic/century-gothic-bold-italic.ttf</boldItalic>
       <pdfEncoding>Identity-H</pdfEncoding>
       <pdfEmbedded>true</pdfEmbedded>
       <exportFonts>
           <export key="net.sf.jasperreports.html">'Century Gothic'</export>
           <export key="net.sf.jasperreports.xhtml">'Century Gothic'</export>
       </exportFonts>
    </fontFamily>   


</fontFamilies>

Note that I just added the last three fonts.

After that I prepared the jar file and put it in my app classpath as mandatory. So far I just got the report exported with normal Sanserif font...

I don't know what I'm doing wrong, any ideas?

Thanks!

Quick informative note: I'm using Jaspersoft Studio Community edition (6.3.0) and my app is deployed in a JBoss server.


Answer:

I finally found out what was happening in my case and now it's working.

When I introduced the fonts (.ttf extension) in Jaspersoft Studio Windows->Preferences->Fonts I selected a wrong value for the PDF Encoding selection combo. I first selected CP1252 (Western European ANSI aka WinAnsi) which is WRONG if you want to export reports in PDF, then I chose Identity-H (Unicode with horizontal writing) instead and it worked fine.

However, what I still don't understand is: if in my report I'm only using Calibri and Century Gothic fonts, why in earth when I go to see the fonts used in my PDF (File->Properties->Fonts) I get also Helvetica in the list of fonts used?

Question:

I am bringing this question from this post. I was not sure if I should create a new question since it seems I was already creating a new topic? Apologies upfront for that.

So here is my problem:

I am trying to dynamically change the format of my report (A book report, with several pages or parts or subreports). What I am doing is loading it first, from an existing template into a JasperDesign Object holder. Then, modifying the size an other parameters of the page itself. Later, I will compile and try to print a PDF format report with the compiled file. Ultimately, I want to print a hole book report with different pages and different templates for each individual pages with a format that I can specify.

Here is what I have done. I was able to point the main report to the other individual pages formats. So, when I export the report to PDF everything looks good(Like you probably imagine it was not that simple to get there. but now is working). So now I want to parametrize the format (A4, LETTER, etc.) on runtime for every single page of the Book Report.

Is this posible? I mean to do this dynamically instead of creating a new static template for each page and format and then creating a mantainence issue? If so which is the way of doing this?

Here is my code for retriving the JasperDesing Object template:

private static JasperDesign getTemplateDesign(String templatePath) throws JRException{

    JasperDesign design = JRXmlLoader.load(templatePath);

    logger.info("Setting Page Dimessions Format to: " + pageFormat);
    if(JRDriver.pageFormat.equals("A3")){
    JRDriver.pageWidth=842; 
    JRDriver.pageHeight=1190;
    JRDriver.columnCount=1;
    JRDriver.columnWidth=802;
    JRDriver.columnSpacing=0;
    JRDriver.leftMargin=20;
    JRDriver.rightMargin=20;
    JRDriver.topMargin=30;
    JRDriver.bottomMargin=30;
    }
    else if (JRDriver.pageFormat.equals("A4")) {
        JRDriver.pageWidth=842; 
        JRDriver.pageHeight=1190;
        JRDriver.columnCount=1;
        JRDriver.columnWidth=555;
        JRDriver.columnSpacing=0;
        JRDriver.leftMargin=20;
        JRDriver.rightMargin=20;
        JRDriver.topMargin=30;
        JRDriver.bottomMargin=30;
    }
    else if (JRDriver.pageFormat.equals("LETTER")) {            
        JRDriver.pageWidth=612; 
        JRDriver.pageHeight=792;
        JRDriver.columnCount=1;
        JRDriver.columnWidth=517;
        JRDriver.columnSpacing=0;
        JRDriver.leftMargin=20;
        JRDriver.rightMargin=20;
        JRDriver.topMargin=30;
        JRDriver.bottomMargin=30;
    }
    //Setting twmplate dimesions
    design.setPageWidth(JRDriver.pageWidth);
    design.setPageHeight(JRDriver.pageHeight);

    design.setColumnCount(JRDriver.columnCount);
    design.setColumnWidth(JRDriver.columnWidth);
    design.setColumnSpacing(JRDriver.columnSpacing);

    design.setLeftMargin(JRDriver.leftMargin);
    design.setRightMargin(JRDriver.rightMargin);
    design.setTopMargin(JRDriver.topMargin);
    design.setBottomMargin(JRDriver.bottomMargin);

    return design;
}

Here is my code fragment for generating the PDF report:

...

logger.info("Retrieving Design Template..." + reportTemplatePath);
    JasperDesign design= getTemplateDesign(reportTemplatePath);

    //jasperReport = JasperCompileManager.compileReport(reportTemplatePath);
    jasperReport = JasperCompileManager.compileReport(design);

    logger.info("Filling Report...");
    jasperPrint = JasperFillManager.fillReport(jasperReport, jasperParameter,new JREmptyDataSource() );//new JREmptyDataSource()


    jasperPrint.setPageWidth(JRDriver.pageWidth);
    jasperPrint.setPageHeight(JRDriver.pageHeight);

    //Create the file dir
    File file = new File(reportOuputPath);
    file.getParentFile().mkdirs();
    //file.delete();

    logger.info("Writing PDF..." + reportOuputPath);
    JasperExportManager.exportReportToPdfFile(jasperPrint, reportOuputPath);

...

I could include the information for my JRXML static template files. But I don't think that is necessary for now. It can be done if you think otherwise

Please help me and thanks in advance


Answer:

Hello and thanks for the quick answer. I couldn't find how to comment on you answer so I guess I will have to include it in this post.

First, you were right about not guaranteeing the whole page layout resizing, by just changing the de page dimensions. However, the formats that I was changing to, were very similar (A4 and LETTER), so the impact on the components and fields size perse, was not that big.

Moreover, what I have to do, to actually change every single individual's page of the book format, was loading every single individual page first into a JasperDesing Object holder and next save it , with the modified size into a jasper field, that will be used in the fillup process. Instead of just doing that for the Report Book page itself.

Here is the code:

    private static JasperDesign getPageTemplateDesign(String templatePath) throws JRException{

    logger.info("Setting format page desing for Template: " + templatePath);

    JasperDesign design = JRXmlLoader.load(templatePath);

    logger.info("Setting Page Dimessions Format to: " + pageFormat);
    if (JRDriver.pageFormat.equals("A4")) {
        JRDriver.pageWidth=595; 
        JRDriver.pageHeight=842;
        JRDriver.columnCount=1;
        JRDriver.columnWidth=555;
        JRDriver.columnSpacing=0;
        JRDriver.leftMargin=20;
        JRDriver.rightMargin=20;
        JRDriver.topMargin=20;
        JRDriver.bottomMargin=20;
    }
    else if (JRDriver.pageFormat.equals("LETTER")) {
        JRDriver.pageWidth=612; 
        JRDriver.pageHeight=792;
        JRDriver.columnCount=1;
        JRDriver.columnWidth=517;
        JRDriver.columnSpacing=0;
        JRDriver.leftMargin=20;
        JRDriver.rightMargin=20;
        JRDriver.topMargin=20;
        JRDriver.bottomMargin=20;
    }
    //Setting twmplate dimesions
    design.setPageWidth(JRDriver.pageWidth);
    design.setPageHeight(JRDriver.pageHeight);

    design.setColumnCount(JRDriver.columnCount);
    design.setColumnWidth(JRDriver.columnWidth);
    design.setColumnSpacing(JRDriver.columnSpacing);

    design.setLeftMargin(JRDriver.leftMargin);
    design.setRightMargin(JRDriver.rightMargin);
    design.setTopMargin(JRDriver.topMargin);
    design.setBottomMargin(JRDriver.bottomMargin);      

    return design;
}

private static void reformattingPageTemplate(String path) throws JRException{

    logger.info("Getting Design Template from: " + path);
    JasperDesign design= getPageTemplateDesign(path);

    String destFile=path.replaceAll("jrxml", "jasper");     
    logger.info("Compiling Re-formated Design Template to: " + destFile);
    JasperCompileManager.compileReportToFile(design, destFile); 
}

private static void formattingALLPage() throws JRException{

    reformattingPageTemplate(reportBookPagesDir + "/FrontCover.jrxml");
    reformattingPageTemplate(reportBookPagesDir + "/Copyright.jrxml");
    reformattingPageTemplate(reportBookPagesDir + "/TableOfContent.jrxml");
    reformattingPageTemplate(reportBookPagesDir + "/Summary.jrxml");
    reformattingPageTemplate(reportBookPagesDir + "/Content.jrxml");
    reformattingPageTemplate(reportBookPagesDir + "/AppendixWarnings.jrxml");
    reformattingPageTemplate(reportBookPagesDir + "/Index.jrxml");
    reformattingPageTemplate(reportBookPagesDir + "/BackCover.jrxml");
    //reformattingPageTemplate(reportTemplatePath);
}

Thanks for the help

Question:

We have migrated to Java 8 and we need to move from v3.5.2 of JasperReports jar to v6.3.0.

In the code we are using FontKey and PdfFont classes, which do not seem to present in the updated jar. Any solution?


Answer:

They both where first deprecated (I saw them last in version 5.5.1) and are now removed from JasperReports library.

The solution is to revert back to 5.5.1 or even better to not use them anymore, change your code accordingly. The documentation points to FontFamily.getExportFont(java.lang.String).

Note: In newer versions of jasper-reports you should use font-extensions, to include and display correctly fonts when exporting to pdf.

Question:

I have this code that only generates one Jasper report at a time to PDF based on a given condition. But what if I want to combine both Jaspers into one PDF file? (i.e. the PDF output should be LoadTagR2R.jasper + LoadTagR2RLandscape.jasper -- which will be one PDF output stream with multiple pages)

        if (fullHalfTag.equalsIgnoreCase("Y")){ //Read FULL_HALF_TAG value (if FULL_HALF_TAG == 'Y')
            logger.debug("Printing FULL tag...");
            reportStream = getServletConfig().getServletContext().getResourceAsStream("/reports/LoadTagR2RLandscape.jasper");

        } else {
            logger.debug("Printing HALF tag...");
            reportStream = getServletConfig().getServletContext().getResourceAsStream("/reports/LoadTagR2R.jasper");

        }

        //Report parameters
        Map parameters = new HashMap();
        parameters.put("PLT_NO", pltNo);
        parameters.put("TICKET_NO", ticketNo);

          try {

             Connection conn = ConnectionUtils.getConnection();

             JasperRunManager.runReportToPdfStream(reportStream,servletOutputStream, parameters, conn);
             response.setContentType("application/pdf");

             servletOutputStream.flush();
             servletOutputStream.close();

I have tried merging the two input streams as shown below but it didn't work. Thoughts?

        new java.io.SequenceInputStream(s1, s2).

Answer:

This is the old way to do this:

JasperPrint jasperPrint1 = JasperFillManager.fillReport(reportStream1,  parameters, conn);
JasperPrint jasperPrint2 = JasperFillManager.fillReport(reportStream2,  parameters, conn);

List<JasperPrint> list = new ArrayList<JasperPrint>();
list.add(jasperPrint1);
list.add(jasperPrint2);

JRPdfExporter exporter = new JRPdfExporter();

exporter.setParameter(JRPdfExporterParameter.JASPER_PRINT_LIST, list);
exporter.setParameter(JRPdfExporterParameter.OUTPUT_STREAM,servletOutputStream); 
exporter.exportReport();

EDIT:

In JasperReports 6.1.1 API JRPdfExporterParameter.JASPER_PRINT_LIST and JRPdfExporterParameter.OUTPUT_STREAM are deprecated adding new method.

Replace:

exporter.setParameter(JRPdfExporterParameter.JASPER_PRINT_LIST, list);
exporter.setParameter(JRPdfExporterParameter.OUTPUT_STREAM,servletOutputStream);

with

exporter.setExporterInput(SimpleExporterInput.getInstance(list));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(servletOutputStream));

Question:

I generate a PDF file with JAVA and jasper. Such jasper file is designed with iReport. Once the pdf file is created, I would like to place a signature with PdfStamper in a concrete position in the pdf. Possible solutions that I have found:

Use PdfSignatureAppearance.setVisibleSignature method. This does not fit my needs since it locates the signature in coordinates based position.

PdfStamper stp = PdfStamper.createSignature(reader, outStream, '\0', fileTmp);
PdfSignatureAppearance sap = stp.getSignatureAppearance();
sap.setVisibleSignature(new Rectangle(100, 100, 200, 200), 1, null);

Use PdfReader.getAcroFields() and then go through the AcroFields, get the coordinates of a predifined form field and insert the signature as shown in the previous option. The problem is that I am not able to define AcroFields with iReport, so I cannot use it either.

My question: is there any way to define fields with iReport and read after the PDF is created with Java?


Answer:

You can use the PdfReaderContentParser to find image and text inside the pdf.

Example (showing how to find location of both text and image in pdf)

PdfReader reader = new PdfReader(src);
int pageILikeToCheck =reader.getNumberOfPages(); //set the page or loop them all        
final String matchStr = "FIND THIS TEXT";

PdfReaderContentParser parser = new PdfReaderContentParser(reader);
parser.processContent(pageILikeToCheck, new RenderListener() {  

    @Override
    public void renderImage(ImageRenderInfo renderInfo) {
        PdfImageObject image;
        try {
            image = renderInfo.getImage();
            if (image == null) return;
            System.out.println("Found image");
            System.out.println(renderInfo.getStartPoint());
        } catch (IOException e) {
            e.printStackTrace();
        }     
    }

    @Override
    public void renderText(TextRenderInfo renderInfo) {

        if(renderInfo.getText().length()>0 && matchStr.contains(renderInfo.getText())){
            System.out.println("FOUND MY TEXT");
            System.out.println(renderInfo.getBaseline().getStartPoint());
            System.out.println(renderInfo.getBaseline().getEndPoint());
        }
    }

    @Override
    public void endTextBlock() {
    }

    @Override
    public void beginTextBlock() {
    }
});

However I normally add the signature in pdf to a pre-defined space (using pageFooter or lastPageFooter band) using the PdfStamper

PdfReader reader = new PdfReader(src);
java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
PdfStamper stamper = new PdfStamper(reader, baos);
int pageSignature=1;
stamper.addSignature("Signature", pageSignature, 320, 570, 550, 620);

and then write baos to file.

Question:

I have a servlet that uses jasper reports to create a pdf. This pdf is displayed in the web browser using the JasperExportManager.exportReportToPdfStream() method. This works fine. However, what I want is to save the file in a folder that resides on the server. I have tried to do this with the following code:

String outputFile = getServletContext().getRealPath("/theFolder");
JasperExportManager.exportReportToPdfFile(jasperPrint, outputFile + "/thePDF.pdf");

This code does not produce any errors and runs to completion, but I can't find the file anywhere on the server. What am I doing wrong? Thanks.


Answer:

If your jasper debug logs are configured well. In the output you will see the path where your report is getting generated.

OR you can use my code

String path=System.getProperty("user.dir");
JasperExportManager.exportReportToPdfFile(this.jp, path + "/reports/Report.pdf");

This will save your file where you want relative to the path of the folder. You can also provide absolute path if necessary.

Also check if the report is present in the target folder of your Project.

Question:

I have an implementation where JasperViewer is used to preview and save reports. The first saving format offered by the viewer is .jrprint and I'm trying to change that to pdf. I'm employing the following method to help me with that

private static void promotePdfSaveFormat(JasperViewer jasperViewer) {
    /* get via reflection (with jOOR) the parameter JasperViewer object's member viewer (of type JRViewer) */
    JRViewer viewer = on(jasperViewer).call("viewer").get();
    /* get via reflection JRViewer object's member tlbToolBar (of type JRViewerToolbar) */
    JRViewerToolbar tlbToolBar = on(viewer).call("tlbToolBar").get();
    /* call tlbToolBar's getSaveContributors() */
    Arrays.stream(tlbToolBar.getSaveContributors()).forEach(
        e -> {
            /* Find the one that is of type JRPdfSaveContributor (using instanceof) */
            if (e instanceof JRPdfSaveContributor){
                /* set JRViewerToolbar object member lastSaveContributor value to the instance of JRPdfSaveContributor */
                on(tlbToolBar).call("lastSaveContributor").get();
            }
        }
    );
}

Everytime a new Object is created inside the class like JasperViewer viewer = new JasperViewer(...), I'm adding promotePdfSaveFormat(viewer) immediately after it. When I run the app, I get an error at JRViewer viewer = on(jasperViewer).call("viewer").get();

The error is as follows

org.joor.ReflectException: java.lang.NoSuchMethodException: No similar method viewer with params [] could be found on type class net.sf.jasperreports.view.JasperViewer.

Answer:

They are called JRSaveContributor.

You can set your own JRViewer.setSaveContributors or an easy way to reorder (remove) is to get the ones that are instanced and then loop them checking the description to see what you like to keep/reorder and then set them back to the JasperViewer.

Quick Example, setting pdf first.

final JRViewer jrv = new JRViewer(report);
JRSaveContributor[] sv = jrv.getSaveContributors();
List<JRSaveContributor> reorded = new ArrayList<JRSaveContributor>();
for (JRSaveContributor s : sv) {
    if (s.getDescription().contains(".pdf")){
        reorded.add(0,s);
    }else{
        reorded.add(s);
    }
}
jrv.setSaveContributors((JRSaveContributor[]) reorded.toArray(new JRSaveContributor[reorded.size()]));

You may also just like to skip .jrprint? if you are using java8 this code can be improved using streams, I leave that exercise to reader.

Result

Question:

in my Java web app I does generate a report, one page every customer detected.

I had create a single JasperReport, and if the list of customer is more than 1 I'll would like to concat the reports generated.

This is my code:

if(myList.size()==1) {
        JasperPrint jp = reportGenerated(myList.get(0).getCustomer());
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        JasperExportManager.exportReportToPdfStream(jp, bos);

        return bos.toByteArray();
    }else {
        for(Object s: myList) {
                                jasperPrints.add(reportGenerated(s.getCustomer()));
            }
        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream(); 

        JRPdfExporter exporter = new JRPdfExporter();
        exporter.setExporterInput(SimpleExporterInput.getInstance(jasperPrints));
        exporter.setExporterOutput(new SimpleOutputStreamExporterOutput("pdf/lettera.pdf")); 
        SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();

        configuration.setCreatingBatchModeBookmarks(true); 
        exporter.setConfiguration(configuration);
        exporter.exportReport();


    }

I want to obtain the merged PDF, but i don't find the function to export a List of JasperPrint in ByteArrayOutputStream.

Any suggestion?


Answer:

Try to change:

exporter.setExporterOutput(new SimpleOutputStreamExporterOutput("pdf/lettera.pdf"))

with:

exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(bos)); 

And add the return statement:

 return bos.toByteArray();

I think this solution can help you.

Question:

While trying to generate PDF that conforms to PDF/A standard using Jasper Reports, I got

net.sf.jasperreports.engine.util.JRPdfaIccProfileNotFoundException. 

This is easily fixed by configuring

<property name="net.sf.jasperreports.export.pdfa.icc.profile.path" value="/stuff/myicc.icc"/>

but I need to bundle the icc profile with rest of the WAR just like the fonts the report embeds. How can this be done? I'm looking something like

<property name="net.sf.jasperreports.export.pdfa.icc.profile.path" value="classpath:/jasper/someicc.icc"/>

But this did not work, nor did icc profile relative to the report itself. Can I pass the InputStream as a parameter to the PDFGenerator?


Answer:

If you are exporting from java code you can use the getClassLoader().getResource() to get the absolute path to file.

Example with JRPdfExporter

JRPdfExporter exporter = new JRPdfExporter();
//... your input and output
SimplePdfExporterConfiguration configuration = new SimplePdfExporterConfiguration();
URL path = this.getClass().getClassLoader().getResource("jasper/someicc.icc");
configuration.setIccProfilePath(path.getFile());
//other settings
exporter.setConfiguration(configuration);
exporter.exportReport();

Question:

I am using these dependencies

implementation ('net.sf.jasperreports:jasperreports:6.9.0')
implementation ('net.sf.jasperreports:jasperreports-fonts:6.9.0')
implementation ('net.sf.jasperreports:jasperreports-functions:6.9.0')
implementation ('net.sf.jasperreports:jasperreports-metadata:6.9.0')
implementation ('net.sf.jasperreports:jasperreports-fonts:6.9.0')
implementation ('net.sf.jasperreports:jasperreports-annotation-processors:6.9.0')
implementation ('net.sf.jasperreports:jasperreports-chart-themes:6.9.0')
implementation ('net.sf.jasperreports:jasperreports-chart-customizers:6.9.0')
implementation ('net.sf.jasperreports:jasperreports-custom-visualization:6.9.0')
compile 'com.lowagie:itext:2.1.7.js5'

with Jasper report for Eclipse 2019.6 . Vietnamese character display in error

Java code

@RequestMapping(value = "/ca_audit/minute_pdf", method = RequestMethod.GET)
public void generatePDFCashAuditMinute() throws JRException {
    JasperReport jasperReport = JasperCompileManager.compileReport("D:/vy/template.jrxml");
    Map<String, Object> parameters = new HashMap<>();
    parameters.put("p1", "Example joint stock company"); // Tên tổ chức
    parameters.put("p2", "EXKK002"); // Số biên bản
    parameters.put("p3", 26); // Ngày
    JRDataSource jrDataSource = new JREmptyDataSource();
    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, jrDataSource);
    JasperExportManager.exportReportToPdfFile(jasperPrint, "D:/foo/out.pdf");
}

The content of file *.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="bien_ban_kiem_ke_quy_a4" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="7098c966-5c92-43e3-a729-b3d486fc858b">
    <parameter name="p1" class="java.lang.String"/>
    <parameter name="p2" class="java.lang.String"/>
    <parameter name="p3" class="java.lang.Integer"/>
    <queryString>
        <![CDATA[select 1 as id]]>
    </queryString>
    <field name="id" class="java.lang.Integer"/>
    <title>
        <band height="84" splitType="Stretch">
            <textField>
                <reportElement x="14" y="6" width="100" height="30" uuid="2106c35d-3d5e-4203-950a-54a87b6952ea"/>
                <textElement>
                    <font fontName="Arial"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{p1}]]></textFieldExpression>
            </textField>
            <staticText>
                <reportElement x="376" y="23" width="64" height="16" uuid="77d41a67-82d2-46d0-9a3e-5327ae3b450b"/>
                <text><![CDATA[Số biên bản:]]></text>
            </staticText>
            <textField>
                <reportElement x="440" y="23" width="50" height="16" uuid="a505da46-48af-4dcb-84bc-f9d27697919d"/>
                <textFieldExpression><![CDATA[$P{p2}]]></textFieldExpression>
            </textField>
            <staticText>
                <reportElement x="260" y="47" width="34" height="13" uuid="541c25ed-4b29-4cc4-a19d-05f295ae0340"/>
                <text><![CDATA[ngày]]></text>
            </staticText>
            <textField>
                <reportElement x="290" y="47" width="40" height="13" uuid="72e64426-d702-4694-bc25-81a2f3e43f82"/>
                <textFieldExpression><![CDATA[$P{p3}]]></textFieldExpression>
            </textField>
        </band>
    </title>
</jasperReport>

I create file jasperreports.properties in classpath

In Eclipse IDE (with Jaspersoft module)

How to fix it?


Answer:

It's a font issue. Not a PDF encoding problem. Maybe try to use Arial Unicode MS

Inside your tag add the following

<font fontName="Arial Unicode MS" size="11" pdfFontName="Arial Unicode MS" pdfEncoding="Identity-H"/> 

Also make sure that Arial font extension jar in class path. Search internet for arial font extension jar.

Question:

Im trying to generate a pdf using jasper reports. Its generating fine and its storing in the specified path directly. But what I needed is, it has to show the open or save option before downloading directly. Im using struts 1.x

Here is my code which I hve written in the method

String reportsPath = "D:/JasperReports/";
String reportName = "StatisticsReport";
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("statisticsData", map);

// Load JRXML

 JasperDesign mainReportDesign = JRXmlLoader.load(reportsPath + reportName + ".jrxml");
// Compile to generate .Jasper file
   JasperCompileManager.compileReportToFile(mainReportDesign, reportsPath + reportName + ".jasper");

   System.out.println(reportsPath + reportName);
                 // Generate Jasper print
   JasperPrint jasperPrint = JasperFillManager.fillReport(reportsPath + reportName + ".jasper", parameters,
                             new JREmptyDataSource());

   String pdfFileName = "D:/JasperReports/StatisticsrReport.pdf";
                 // Export PDF file
   response.addHeader("Content-disposition", "attachment; filename=StatisticsrReport1.pdf");
                 JasperExportManager.exportReportToPdfFile(jasperPrint,pdfFileName);

Answer:

Browser will prompt to save or open file when response content type is application/x-download. For example:

//String pdfFileName = "D:/JasperReports/StatisticsrReport.pdf";
response.setContentType("application/x-download");
response.addHeader("Content-disposition", "attachment; filename=StatisticsrReport1.pdf");
OutputStream out = response.getOutputStream();
JasperExportManager.exportReportToPdfStream(jasperPrint,out);//export PDF directly
//return null ActionForward, no extra data is appended to output stream

Question:

I'm upgrading a spring application from 4.3.x version to 5.1.x version. When doing this I found an error for JasperReportsPdfView class from the org.springframework.web.servlet.view.jasperreports package.

Also in our application we are using the jasperreports-3.6.0 jar.

Error:
error: package org.springframework.web.servlet.view.jasperreports does not exist
Sample Code:
public class PdfReportView extends JasperReportsPdfView{


    /**
     * Creating constructor
     * @param contractList
     */
    public PdfReportView(List contractList) throws JRException
    {
    }
    ;
    ;
    ;

}
POM.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.wellpoint.ewpd</groupId>
        <artifactId>ewpd-aggregator</artifactId>
        <version>1.0.0-SNAPSHOT</version>
        <relativePath>../ewpd-aggregator</relativePath>
    </parent>
    <artifactId>ebx-war</artifactId>
    <packaging>war</packaging>
    <name>ebx-war Project</name>
    <description>ebx-war Project</description>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <!-- Set to the Context Root - DO NOT REMOVE -->
                    <warName>ebx-war</warName>

                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
        <finalName>CrossWalks</finalName>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.class</include>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>

            <resource>
                <directory>src/main/resources</directory>
                <includes>                  
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>src/test/java</directory>
                <includes>
                    <include>**/*.class</include>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </testResource>
        </testResources>
    </build>
    <properties>
        <springframework.version>5.1.6.RELEASE</springframework.version>
    </properties>
    <dependencies>  
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>

        </dependency>
        <dependency>
            <groupId>bsh</groupId>
            <artifactId>bsh</artifactId>
            <version>1.2b7</version>

        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.2</version>

        </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.2</version>

        </dependency>
        <dependency>
            <groupId>commons-digester</groupId>
            <artifactId>commons-digester</artifactId>
            <version>2.1</version>

        </dependency>
        <dependency>
            <groupId>commons-discovery</groupId>
            <artifactId>commons-discovery</artifactId>
            <version>0.4</version>

        </dependency>       

        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.4</version>
        </dependency>

        <dependency>
            <groupId>net.sf.ezmorph</groupId>
            <artifactId>ezmorph</artifactId>
            <version>1.0.6</version>

        </dependency>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.28</version>

        </dependency>

        <dependency> 
            <groupId>com.wellpoint.eps.ewpd.tools.xmlbeans</groupId> 
            <artifactId>Get27XBenefitAccums5010-jar</artifactId> 
            <version>2.0.2</version> 
            <classifier>sources</classifier> 
        </dependency>

        <dependency>
            <groupId>org.owasp.esapi</groupId>
            <artifactId>esapi</artifactId>
            <version>2.1.0.1</version>
                    <exclusions>
                           <exclusion>
                                  <groupId>org.owasp.antisamy</groupId>
                                  <artifactId>antisamy</artifactId>
                             </exclusion>
                           <exclusion>
                                <groupId>org.apache.xmlgraphics</groupId>
                                  <artifactId>batik-css</artifactId>
                           </exclusion>
                      <exclusion>
                           <groupId>xom</groupId>
                           <artifactId>xom</artifactId>
                      </exclusion>
                     <exclusion>
                           <groupId>commons-beanutils</groupId>
                           <artifactId>commons-beanutils-core</artifactId>
                      </exclusion>
                     </exclusions> 

        </dependency>
        <dependency>
            <groupId>com.wellpoint.ets.ebx.schemas.V4</groupId>
            <artifactId>Get27XBenefitAccumsV4</artifactId>
            <version>1.0.0</version>
            <classifier>mystery</classifier>

        </dependency>

        <dependency>
             <groupId>com.lowagie</groupId>
                <artifactId>itext</artifactId>
             <version>2.1.7</version>  
             <exclusions>
             <exclusion>
                  <groupId>bouncycastle</groupId>
                  <artifactId>bcmail-jdk14</artifactId>
             </exclusion>
             <exclusion>
                  <groupId>bouncycastle</groupId>
                  <artifactId>bctsp-jdk14</artifactId>
             </exclusion>
             <exclusion>
                  <groupId>bouncycastle</groupId>
                  <artifactId>bcprov-jdk14</artifactId>
             </exclusion>
           </exclusions>
       </dependency>    

        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk14</artifactId>
            <version>1.60</version>
            </dependency>

        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcmail-jdk14</artifactId>
            <version>1.60</version>
            </dependency>   

        <dependency>
            <groupId>com.wellpoint.libraries.eps.epds.business</groupId>
            <artifactId>jakarta-poi</artifactId>
            <version>1.0.0</version>            
        </dependency>

        <dependency>
          <groupId>net.sf.jasperreports</groupId>
          <artifactId>jasperreports</artifactId>
          <version>3.6.0</version>

        </dependency>

        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>          
            <classifier>jdk13</classifier>          
        </dependency>

        <dependency>
            <groupId>com.wellpoint.libraries.eps.epds.web</groupId>
            <artifactId>jsr173_1.0_api</artifactId>
            <version>1.0</version>
        </dependency>

        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jsr173_api</artifactId>
            <version>1.0</version>
            <scope>provided</scope>
        </dependency>

<dependency>
            <groupId>com.keyoti</groupId>
            <artifactId>RapidSpellWeb</artifactId>
            <version>2.4.2</version>
        </dependency>
        <dependency>
            <groupId>apache-xerces</groupId>
            <artifactId>resolver</artifactId>
            <version>2.9.1</version>

        </dependency>

        <dependency>
            <groupId>com.ibm.faces</groupId>
            <artifactId>jsf-ibm</artifactId>
            <version>3.0.10</version>
        </dependency>

        <dependency>
            <groupId>xmlbeans</groupId>
            <artifactId>xbean_xpath</artifactId>
            <version>2.2.0</version>

        </dependency>
        <dependency>
            <groupId>org.apache.xmlbeans</groupId>
            <artifactId>xmlbeans-qname</artifactId>
            <version>2.5.0</version>

        </dependency>

        <dependency>
            <groupId>com.thoughtworks.xstream</groupId>
            <artifactId>xstream</artifactId>
            <version>1.4.10</version>

        </dependency>
        <dependency>
            <groupId>org.apache.xbean</groupId>
            <artifactId>xbean</artifactId>
            <version>3.15</version>
             <type>pom</type>
        </dependency>
        <dependency>
            <groupId>javax.activation</groupId>
            <artifactId>activation</artifactId>
            <version>1.1.1</version>

        </dependency>

        <dependency>
            <groupId>org.apache.taglibs</groupId>
            <artifactId>taglibs-standard-impl</artifactId>
            <version>1.2.5</version>

        </dependency>
        <dependency>
            <groupId>xmlbeans</groupId>
            <artifactId>xmlpublic</artifactId>
            <version>2.2.0</version>

        </dependency>

        <dependency>
            <groupId>xpp3</groupId>
            <artifactId>xpp3_min</artifactId>
            <version>1.1.4c</version>

        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.3</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.jndi</groupId>
            <artifactId>springutil</artifactId>
            <version>1.0.0</version>
        </dependency>


        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>2.5.6</version>

        </dependency>

        <!-- <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring</artifactId>
            <version>2.5.6</version>
        </dependency>
         -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>xml-apis</groupId>
            <artifactId>xml-apis</artifactId>
            <version>1.3.02</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>stax</groupId>
            <artifactId>stax-api</artifactId>
            <version>1.0.1</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>xerces</groupId>
            <artifactId>xercesImpl</artifactId>
            <version>2.12.0</version>
            <scope>provided</scope>
        </dependency>


        <dependency>
            <groupId>com.wellpoint.ewpd</groupId>
            <artifactId>ewpd-jar</artifactId>
            <version>1.0.0-SNAPSHOT</version>
            <scope>provided</scope>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.5.4</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.15</version>
        </dependency>

        <dependency>
            <groupId>jexcelapi</groupId>
            <artifactId>jxl</artifactId>
            <version>2.6</version>
        </dependency>

        <dependency>
            <groupId>com.wellpoint</groupId>
            <artifactId>adapter</artifactId>
            <version>1.4.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.wellpoint.ets.ewpd</groupId>
            <artifactId>admin-method-validation</artifactId>
            <version>1.0</version>
            <classifier>mystery</classifier>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.ajaxanywhere</groupId>
            <artifactId>ajaxanywhere</artifactId>
            <version>1.1.0.6</version>
            <classifier>mystery</classifier>
        </dependency>
        <!--  
        <dependency>
            <groupId>com.blazesoft.oes</groupId>
            <artifactId>benefitRule</artifactId>
            <version>1.0</version>
            <classifier>mystery</classifier>
        </dependency>-->
                <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.5</version>
        </dependency>


        <dependency>
            <groupId>com.wellpoint.wpd</groupId>
            <artifactId>ecidrep</artifactId>
            <version>1.0</version>
            <classifier>mystery</classifier>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>jdom</groupId>
            <artifactId>jdom</artifactId>
            <version>1.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
            <type>jar</type>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>myfaces</groupId>
            <artifactId>tomahawk</artifactId>
            <version>1.1.3</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>   

        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.2.1</version>

        </dependency>

    </dependencies>
</project>

Also I can see jasperreports package in spring 4.3.24.RELEASE.

https://docs.spring.io/spring/docs/4.3.24.RELEASE/javadoc-api/

But I'm not able to see from 5.0.0.RELEASE onwards.

https://docs.spring.io/spring/docs/5.0.0.RELEASE/javadoc-api/

  1. Please help me to solve this issue.

  2. Also please suggest some example url's to get knowledge on this.

  3. Also suggest some steps that I can follow to upgrade this jar from 3.6.0 to 6.7.1 version.


Answer:

Generally, while upgrading from the Spring lower versions to higher versions( Ex: Spring-4.x.x to Spring-5.x.x ) we need to consider the below points.

  • New Features
  • Supported existing features
  • Removed Packages, Classes and Methods
  • Dropped Support Features

From the Spring Framework github wiki and from other articles, it is confirmed that support for JasperReports has been dropped from Spring 5.x versions. So it is recommended to remove the code that are using the Japser reports from the application code or to support them by using the core-jasper reports libraries.

Reference links : Spring-5.x-github-wiki

Spring-guru-5.x-link

Dzone-Spring-5.x-features and Support

Question:


Answer:

The com.lowagie.text.pdf.FontMapper class does exist in the 2.1.7 version of com.lowagie.itext jar.

Are you using this exact version as a dependency? In my working example this is the version I use.

<dependency>
   <groupId>com.lowagie</groupId>
   <artifactId>itext</artifactId>
   <version>2.1.7</version>
</dependency>

If you are already doing that, I would make sure your runtime environment has only this 2.1.7 version of the itext jar. Is it possible another version of itext is getting included in the deployed jar library?

I pushed a working example to https://github.com/cameronhurd/simple-jasper-report

Question:


Answer:

I'm using maven, so adding groovy as a dependency made the trick

<dependency>
    <groupId>org.codehaus.groovy</groupId>
    <artifactId>groovy-all</artifactId>
    <version>2.4.10</version>
</dependency>

Question:

I am using JasperReport 6.1.0 for creating PDF report in Java. In JasperReport's standart configuration has some problems. Some characters does not appear after exporting to PDF. For example Ə,İ,Ğ and Ş.

After googling I found that I must add different font. Also JasperReport show this message: PDF Font name is now deprecated. You should use a font extension when using non-standart font.

Now I want to add Windows Comis Sans MS for displaying hidden letters in PDF. When I added any *.ttf to JasperReport I got Unable to file the file: null.

How can I fix this peoblem?


Answer:

I have just solved the problem but I do not know my solution is exact solution. In IReport I changed Font name as Dejavu Serif and Pdf Embedded checked as true. Now I can create report with Ə,İ,Ğ and Ş letters.

Question:

When i print report commenting JasperExportManager.exportReportToPdf(JasperPrint) report gets shown fine in Jar file. Otherwise report gets stuck in this function and report viewer doesnt come , even not giving any error. In Netbeans it is working fine. i am working in JDK8u25(32bits). Here is my code for Report Printing:

public void PrepareReport(ResultSet rs) {
       try{
             String reportName ="/com/mmts/reports/challan.jasper";
             InputStream st = getClass().getResourceAsStream(reportName);
             JasperReport jr= (JasperReport) JRLoader.loadObject(st); 
             JasperPrint jp = 
            JasperFillManager.fillReport(jr,new HashMap<>(),new JRResultSetDataSource(rs));
            JRViewer jv = new JRViewer(jp);  
            JFrame jf = new JFrame();
            jf.getContentPane().add(jv);
            JasperExportManager.exportReportToPdf(jp);
            jf.validate();
            jf.setVisible(true);
            jf.setTitle("Challan");
            jf.setSize(new Dimension(1200,600));
            jf.setLocation(20,20);
            jf.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
            }catch(JRException ex){
                        JOptionPane.showMessageDialog(null, ex);
                    }
            }        

Here is my console output for Packaging:

ant -f D:\\Metro\\MMTS\\NetBeansProjects\\MMTS -Djar.archive.disabled=true -Dnative.bundling.type=image build-native
Detected JavaFX Ant API version 1.3
init:
deps-clean:
Updating property file: D:\Metro\MMTS\NetBeansProjects\MMTS\build\built-clean.properties
Deleting directory D:\Metro\MMTS\NetBeansProjects\MMTS\build
clean:
deps-jar:
Created dir: D:\Metro\MMTS\NetBeansProjects\MMTS\build
Updating property file: D:\Metro\MMTS\NetBeansProjects\MMTS\build\built-jar.properties
Created dir: D:\Metro\MMTS\NetBeansProjects\MMTS\build\classes
Created dir: D:\Metro\MMTS\NetBeansProjects\MMTS\build\empty
Created dir: D:\Metro\MMTS\NetBeansProjects\MMTS\build\generated-sources\ap-source-output
Compiling 24 source files to D:\Metro\MMTS\NetBeansProjects\MMTS\build\classes
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Copying 5 files to D:\Metro\MMTS\NetBeansProjects\MMTS\build\classes
Copied 2 empty directories to 1 empty directory under D:\Metro\MMTS\NetBeansProjects\MMTS\build\classes
compile:
Created dir: D:\Metro\MMTS\NetBeansProjects\MMTS\dist
Copying 33 files to D:\Metro\MMTS\NetBeansProjects\MMTS\dist\lib
Launching <fx:jar> task from C:\Program Files (x86)\Java\jdk1.8.0_25\jre\..\lib\ant-javafx.jar
Launching <fx:deploy> task from C:\Program Files (x86)\Java\jdk1.8.0_25\jre\..\lib\ant-javafx.jar
Note: To create native bundles the <fx:deploy> task may require external tools. See JavaFX 2.2+ documentation for details.

Launching <fx:deploy> in native packager mode...
No base JDK. Package will use system JRE.
Creating app bundle: MMTS in D:\Metro\MMTS\NetBeansProjects\MMTS\dist\bundles
Result application bundle: D:\Metro\MMTS\NetBeansProjects\MMTS\dist\bundles
Deleting: D:\Metro\MMTS\NetBeansProjects\MMTS\dist\MMTS.html
Deleting: D:\Metro\MMTS\NetBeansProjects\MMTS\dist\MMTS.jnlp
Deleting: D:\Metro\MMTS\NetBeansProjects\MMTS\dist\MMTS_browser.jnlp
build-native:
BUILD SUCCESSFUL (total time: 17 seconds)   

Saving the generated report in pdf formatt is a must for me. Please Help.


Answer:

Ok...now i got the solution. Problem was in the version of itextpdf and lowagie jars. Earlier i was having the jars included as follows:

(1)itextpdf-2.1.7.jar
(2)com.springsource.com.lowagie.text-2.0.8.jar    

Now i have changed them to the following :

(1)itextpdf-5.5.3.jar
(2)com.lowagie.text-2.1.7

and due to this i can view my report in report viewer print to printer or can save in pdf

Now final code is as follows:

public void PrepareReport(ResultSet rs){
        try{
             String reportName ="/com/mmts/reports/challan.jasper";
             InputStream st = getClass().getResourceAsStream(reportName);
             JasperReport jr= (JasperReport) JRLoader.loadObject(st); 
             Map parameters = new HashMap();
             JasperPrint jp = JasperFillManager.fillReport(jr,parameters,new JRResultSetDataSource(rs));

                JasperExportManager.exportReportToPdf(jp);     
                JasperViewer jv=new JasperViewer(jp,false);
                jv.setTitle("Challan");
                jv.setVisible(true);

                }catch(JRException ex)
                {
                   JOptionPane.showMessageDialog(null, ex);
                }
    }

thanks

Question:

I'm using DynamicReports API to create a PDF report displaying the results of my Java application (tables and charts). One of the chart I have to display is a 3D Surface Plot build using jzy3d 0.9.0.

Here is my code:

import static net.sf.dynamicreports.report.builder.DynamicReports.*;
import net.sf.dynamicreports.examples.Templates;
import net.sf.dynamicreports.examples.complex.invoice.InvoiceDesign;
import net.sf.dynamicreports.examples.complex.sales.SalesDesign;
import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
import net.sf.dynamicreports.report.constant.HorizontalImageAlignment;
import net.sf.dynamicreports.report.constant.HorizontalTextAlignment;
import net.sf.dynamicreports.report.constant.PageType;
import net.sf.dynamicreports.report.constant.VerticalImageAlignment;
import net.sf.dynamicreports.report.constant.VerticalTextAlignment;
import net.sf.dynamicreports.report.builder.chart.PieChartBuilder;
import net.sf.dynamicreports.report.builder.component.ComponentBuilder;
import net.sf.dynamicreports.report.builder.component.ComponentBuilders;
import net.sf.dynamicreports.report.builder.component.TextFieldBuilder;
import net.sf.dynamicreports.report.builder.style.FontBuilder;
import net.sf.dynamicreports.report.builder.style.StyleBuilder;
import net.sf.dynamicreports.report.constant.PageOrientation;
import net.sf.dynamicreports.report.datasource.DRDataSource;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.dynamicreports.jasper.builder.export.Exporters;
import net.sf.dynamicreports.report.builder.column.TextColumnBuilder;
import net.sf.dynamicreports.report.builder.component.HorizontalListBuilder;
import javax.swing.JFrame;
import com.fairdynamics.components.FDPalette;
import com.fairdynamics.components.FDGlassPane;
import com.fairdynamics.components.FDOptionPane;
import fairdynamics.lyrica.UI_VisualAnalytics.UIRespondersHeatMap.HeatMapDetails;
import javax.swing.ImageIcon;
import org.jzy3d.maths.*;
import org.jzy3d.plot3d.builder.*;
import org.jzy3d.plot3d.builder.concrete.OrthonormalGrid;
import org.jzy3d.colors.ColorMapper;
import org.jzy3d.colors.colormaps.ColorMapRainbow;
import org.jzy3d.plot3d.primitives.Shape;
import org.jzy3d.chart.Chart;
import org.jzy3d.plot3d.rendering.canvas.Quality;
import org.jzy3d.chart.ChartLauncher;
import org.jzy3d.plot3d.builder.Mapper;

public class UI_ReportBuilder3 extends JasperReportBuilder{
    protected final FontBuilder font18 = stl.font("Roboto Light",false,false,18);
    protected final FontBuilder font16 = stl.font("Roboto Light",false,false,16);
    protected final FontBuilder font14 = stl.font("Roboto Light",false,false,14);
    protected final FontBuilder font12 = stl.font("Roboto Light",false,false,12);
    protected final FontBuilder font10 = stl.font("Roboto Light",false,false,10);
    protected final StyleBuilder titleStyle = stl.style(font12).setVerticalTextAlignment(VerticalTextAlignment.TOP).setForegroundColor(FDPalette.primaryColor);
    protected final StyleBuilder mainTitleStyle = stl.style(font18).setVerticalTextAlignment(VerticalTextAlignment.TOP).setForegroundColor(FDPalette.primaryColor);
    protected final StyleBuilder subTitleStyle = stl.style(font14).setVerticalTextAlignment(VerticalTextAlignment.TOP).setForegroundColor(FDPalette.primaryColor);
    protected final StyleBuilder footerStyle = stl.style(font10).setVerticalTextAlignment(VerticalTextAlignment.MIDDLE).setForegroundColor(FDPalette.secondaryText);
    protected final StyleBuilder colStyle = stl.style(font12).setVerticalTextAlignment(VerticalTextAlignment.MIDDLE);   

    public UI_ReportBuilder3() {        
        try{
            this
            .setTemplate(Templates.reportTemplate)
            .setPageFormat(PageType.A4,PageOrientation.PORTRAIT)
            .setPageMargin(margin(40))
            .pageFooter(
                    cmp.text("Footer").setStyle(footerStyle).setHorizontalTextAlignment(HorizontalTextAlignment.CENTER)
                )
            .title(
                    cmp.horizontalList().add(
                        cmp.text("TITLE").setStyle(mainTitleStyle).setHorizontalTextAlignment(HorizontalTextAlignment.LEFT)
                    )
                    .setFixedHeight(32)
                )
            .summary(
                    cmp.multiPageList(cmp.image(createHeatMap().screenshot())
                        )
                )
            .show()
            ;
        }catch(Exception e){
            e.printStackTrace();
        }
    }


    private org.jzy3d.chart.Chart createHeatMap(){          
        // Define a function to plot
        Mapper mapper = new Mapper() {
            public double f(double x, double y) {
                return 10 * Math.sin(x / 10) * Math.cos(y / 20) * x;
            }
        };

        // Define range and precision for the function to plot
        Range range = new Range(-150, 150);
        int steps = 50;

        // Create a surface drawing that function
        org.jzy3d.plot3d.primitives.Shape surface = Builder.buildOrthonormal(new OrthonormalGrid(range, steps, range, steps), mapper);
        surface.setColorMapper(new ColorMapper(new ColorMapRainbow(), surface.getBounds().getZmin(), surface.getBounds().getZmax(), new org.jzy3d.colors.Color(1, 1, 1, .5f)));
        surface.setFaceDisplayed(true);
        surface.setWireframeDisplayed(false);
        surface.setWireframeColor(org.jzy3d.colors.Color.BLACK);

        // Create a chart and add the surface
        org.jzy3d.chart.Chart chart = new org.jzy3d.chart.Chart(Quality.Advanced);
        chart.getScene().getGraph().add(surface);

        return chart;
    }

}

This code works only if I call the method ChartLauncher.openChart(chart) (consequently opening a frame with the chart displayed in) from createHeatMap() before returning chart, otherwise createHeatMap().screenshot() always returns null. But what if I need to create and export a PDF of this chart without displaying the chart itself in my java application?

NOTE: if possible, I'd prefer to use jzy3d 0.9.0 and not jzy3d 0.9.1 because otherwise I should modify a lot of code already written and tested.


Answer:

Able to capture the screenshot in this way:

Chart c = AWTChartComponentFactory.chart(Quality.Nicest,org.jzy3d.chart.factories.IChartComponentFactory.Toolkit.offscreen);
c.screenshot();
BufferedImage i = ((OffscreenCanvas)c.getCanvas()).getRenderer()).getLastScreenshotImage();

Question:


Answer:

Solved, I had to add false argument to viewReport

JasperViewer.viewReport(JASP_PRINT, false);

Question:

this error is blowing my mind away, so any help is appreciated. So the thing is, I'm dealing with a web application using JSF where there's a need to generate a report so that the user can download it. BUT, whenever I try to generate the report, I get this stack trace:

java.lang.NoClassDefFoundError: Could not initialize class net.sf.jasperreports.engine.util.JRStyledTextParser
    net.sf.jasperreports.engine.fill.JRBaseFiller.<init>(JRBaseFiller.java:110)
    net.sf.jasperreports.engine.fill.JRVerticalFiller.<init>(JRVerticalFiller.java:69)
    net.sf.jasperreports.engine.fill.JRVerticalFiller.<init>(JRVerticalFiller.java:57)
    net.sf.jasperreports.engine.fill.JRFiller.createBandReportFiller(JRFiller.java:200)
    net.sf.jasperreports.engine.fill.JRFiller.createReportFiller(JRFiller.java:215)
    net.sf.jasperreports.engine.fill.JRFiller.fill(JRFiller.java:84)
    net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:456)
    net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:863)
    br.com.ead.jasper.RelatorioUtil.geraRelatorio(RelatorioUtil.java:43)
    br.com.ead.web.RelatorioBean.gerarRelatorio(RelatorioBean.java:31)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:498)
    javax.el.BeanELResolver.invoke(BeanELResolver.java:158)
    javax.el.CompositeELResolver.invoke(CompositeELResolver.java:79)
    org.apache.el.parser.AstValue.getValue(AstValue.java:159)
    org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:184)
    com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
    org.primefaces.component.filedownload.FileDownloadActionListener.processAction(FileDownloadActionListener.java:53)
    javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
    javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:813)
    javax.faces.component.UICommand.broadcast(UICommand.java:300)
    javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
    br.com.ead.filter.CharsetFilter.doFilter(CharsetFilter.java:26)
    br.com.ead.filter.ConexaoHibernateFilter.doFilter(ConexaoHibernateFilter.java:42)
    br.com.ead.filter.LoginFilterProfessor.doFilter(LoginFilterProfessor.java:35)

The error seems to be pretty straightfoward. Looks like this class class net.sf.jasperreports.engine.util.JRStyledTextParser is missing, but it actually is in my classpath. I just can't find a way to make this work! I'm using maven as a dependecy manager, so here are my dependencies:

<dependencies>

        <!-- https://mvnrepository.com/artifact/joda-time/joda-time -->
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.8</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/org.primefaces/primefaces -->
        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>5.0</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.11.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.23</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/net.sf.jasperreports/jasperreports -->
        <dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports</artifactId>
            <version>5.0.0</version>
        </dependency>


        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-api</artifactId>
            <version>2.2.9</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.itextpdf/itext-pdfa -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-pdfa</artifactId>
            <version>5.5.11</version>
        </dependency>


        <dependency>
            <groupId>com.sun.faces</groupId>
            <artifactId>jsf-impl</artifactId>
            <version>2.2.9</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.primefaces.extensions/all-themes -->
        <dependency>
            <groupId>org.primefaces.extensions</groupId>
            <artifactId>all-themes</artifactId>
            <version>1.0.8</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/javax.servlet.jsp.jstl-api -->
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>javax.servlet.jsp.jstl-api</artifactId>
            <version>1.2.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.2.6.RELEASE</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.3</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/commons-collections/commons-collections -->
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-digester/commons-digester -->
        <dependency>
            <groupId>commons-digester</groupId>
            <artifactId>commons-digester</artifactId>
            <version>2.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.11</version>
        </dependency>




        <!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-servlet-api -->
        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-servlet-api</artifactId>
            <version>9.0.0.M26</version>
        </dependency>

        <dependency>
            <groupId>xml-apis</groupId>
            <artifactId>xml-apis</artifactId>
            <version>1.4.01</version>
        </dependency>



        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

Once again, any help is appreciated.


Answer:

So based on your pom, you are using version 5.0.0 of Jasper Reports. Based on this version of the class in question, the static block that is causing this error doesn't log or print any errors that may have been thrown during static initialization.

You have two options:

  1. Look at the source I linked and see if you can determine what might be throwing an exception in that static initialization block, fix it, then proceed
  2. Upgrade your jasper reports version to at least 6.3.0. As of this version of the class in question, they have at least started printing the stack trace of the underlying issue. This ought to give you a better idea of what the actual error is.

Question:

I have a jasper report that is already working for the user to download. But now there is a need to save a copy of this PDF to a specific folder on the server, I have the following code, but it generates an error.

            JasperDesign design = JRXmlLoader.load(jrxPath);
            JasperReport report = JasperCompileManager.compileReport(design);                
            JasperPrint print = JasperFillManager.fillReport(report, getParametros());           

            //String pojectPath = "http://localhost:9080/ProjectName/";
            String exportPath = projectPath + "reports/saida/" + "reportName.pdf";
            JasperExportManager.exportReportToPdfFile(print, exportPath);

net.sf.jasperreports.engine.JRRuntimeException: java.io.FileNotFoundException: http:\localhost:9080\RelatoriosDPOC\reports\saida\reportName.pdf (The syntax for the file name, directory name, or volume label is incorrect.)

I already tried to change the path out. But I get the same error.

 String exportPath = projectPath + "reports/saida/";

and

String exportPath = projectPath + "reports/saida";

My project folders:


Answer:

Try to create a dir and get the absolut path of this dir:

  String realPath = getServletContext().getRealPath("/");

  File file = new File(realPath+"/reports/saida/output/");
  file.mkdirs();

  JasperExportManager.exportReportToPdfFile(print, file.getAbsolutePath +"reportName.pdf");

Question:

I am using JasperReport to export a report to a PDF. The code runs fine with no exception messages showing up in the console/log. However, the report does not export to the browser. In other words, the report is being created, I just cannot download or gain access to it.

Here is the export code:

public void generatePDFReport(Map<String, Object> parameters, JRDataSource jrDataSource, String resource, String filename)
{
    OutputStream os = null;
    try{
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
        os = response.getOutputStream();

        InputStream reportTemplate = this.getClass().getClassLoader().getResourceAsStream(resource);
        byte[] pdf = null;

        try {
            JasperDesign masterDesign = JRXmlLoader.load(reportTemplate);
            masterReport = JasperCompileManager.compileReport(masterDesign);
            masterReport.setWhenNoDataType(WhenNoDataTypeEnum.ALL_SECTIONS_NO_DETAIL);
            JasperPrint masterPrint = JasperFillManager.fillReport(masterReport, parameters, jrDataSource);
            pdf = JasperExportManager.exportReportToPdf(masterPrint);
        } catch (JRException e) {
            log.error(e);
        }
        response.setContentType("application/pdf");
        response.setContentLength(pdf.length);
        response.setHeader("Content-disposition", "attachment; filename=\""+filename+"\"");

        context.responseComplete();

        os.write(pdf);

        pdf = null;
    }catch(Exception e){
        log.error(e);
    }finally{
        try{
            os.flush();
            os.close();
        }catch(IOException e){
            log.error(e);
        }
    }
}

I am almost 100% certain that there is nothing wrong with the code as it works fine for different reports (I run the same export code for several other reports and it works as expected for all of them except for this one).

Knowing this, I figured it must have something to do with the report itself. The report is a jrxml JasperReport file. The report was created using iReport. However, I modified the above code to simply save it to the downloads folder and the report is being created perfectly fine.

So, the problem is that the report is successfully being created in the backend but it is not being sent to the front-end (browser) as expected.

I am open to any suggestions as to why this report would not be working.


Answer:

Running the code inside a bean is problematic because:

  • only one call to getOutputStream is allowed per HTTP request
  • the web framework (J2EE/JSF) has likely already written HTTP headers
  • the JSF page has likely already been written as HTML inside a temporary buffer (flushed upon calling responseComplete()).
  • the headers could be reset, but that won't help with the getOutputStream issue
  • calling responseComplete() flushes any HTML along with PDF content to the browser

Use a servlet. The send method of the servlet needn't be any more complex than:

protected void send(final byte[] content) throws IOException {
    setContentLength(content.length);

    try (final OutputStream out = getOutputStream()) {
        out.write(content);
    }
}

Also consider setting the cache so that stale reports are not possible:

protected void disableCache() {
    // https://tools.ietf.org/html/rfc7234#section-7.1.3
    setHeader(CACHE_CONTROL, "private, no-store, no-cache, must-revalidate");

    // https://tools.ietf.org/html/rfc7234#section-5.3
    setHeader(EXPIRES, "Thu, 01 Dec 1994 16:00:00 GMT");

    // https://tools.ietf.org/html/rfc7234#section-5.4
    setHeader(PRAGMA, "no-cache");

    // https://tools.ietf.org/html/rfc7232#section-2.2
    setHeader(LAST_MODIFIED, getServerTimestamp());
}

private String getServerTimestamp() {
    final SimpleDateFormat rfc1123 = new SimpleDateFormat(DATE_RFC_1123, getDefault());

    rfc1123.setTimeZone(getTimeZone("GMT"));

    final Calendar calendar = Calendar.getInstance();
    return rfc1123.format(calendar.getTime());
}

This implies, for example:

@WebServlet(
        name = "ReportServlet",
        urlPatterns = {PATH_SERVLET + "ReportServlet"}
)
public class ReportServlet extends AbstractServlet {
}

And then use a regular anchor link:

<h:outputLink value="/app/path/servlet/Reportservlet">Run Report</h:outputLink>

In summary, don't send binary report data by intercepting a request to a JSF page; use a servlet, instead.

Communications between servlets and JSF pages can be made via:

  • Session variables (HTTPSession on the servlet side)
  • URL parameters

Servlets have the advantage that the JSF overhead is completely avoided, which will make the report run faster from the user's perspective. Also, don't compile the report -- use the .jasper file directly, which will also have performance improvements. (I did not mean to imply using the .jrxml file was the problem, merely that it isn't a necessary step.)

Question:

i want my Jasper Report to support something like 5 or 6 languages dynamically.

i wish to use the google noto-sans font (www.google.com/get/noto) and google noto, have a single file for each language, (beside the main font file )

should i create a couple of font extensions and add them to my classpath ?

following my previous question How to get non-english support when exporting to PDF?


Answer:

In the jasper report you have

<font fontName="google_noto"/>

Related to this font you can only have 1 font-extension with the family name google_noto (containing the font for normal, bold, italic etc).

You can't switch this font extension dynamically the solution would be:

  1. Use a font that contains all relative language.

  2. Create a different jrxml (reports) for the different language with different fontName and the create font-extension with all the different family names:

    //report in English
    <font fontName="google_noto_en"/>
    //report in Italian        
    <font fontName="google_noto_it"/>
    

A work around would be to indicate fake font, disable errors for missing font and switch the default font as you like before generating report.

net.sf.jasperreports.awt.ignore.missing.font="true"
net.sf.jasperreports.default.font.name="google_en"

This question is about setting properties JRProperties became deprecated, recommended way of replacing

However, I would strong recommend and choose: "1. Use a font that contains all relative language"

Question:

I'm setting up a subreport in my main report jrmxl for my java application. I'm currently developing using iReports 2.0.5 and I can't use a further version.

When I run the test in order to generate a pdf whith my report, in the log it seems recognize it and run the stringquery and set the parameteres in the output, but in the pdf only appears the main report data.

This is the main report subreport tag

<jasperReport
         name="triageSummary"
         columnCount="1"
         printOrder="Vertical"
         orientation="Portrait"
         pageWidth="595"
         pageHeight="842"
         columnWidth="519"
         columnSpacing="0"
         leftMargin="51"
         rightMargin="25"
         topMargin="20"
         bottomMargin="20"
         whenNoDataType="NoPages"
         isTitleNewPage="false"
         isSummaryNewPage="false">
    <property name="ireport.scriptlethandling" value="0" />
    <property name="ireport.encoding" value="UTF-8" />
    <import value="java.util.*" />
    <import value="net.sf.jasperreports.engine.*" />
    <import value="net.sf.jasperreports.engine.data.*" />

    <parameter name="SubRel_Cabecalho" isForPrompting="false" class="java.net.URL"/>

    <subreport  isUsingCache="true">
        <reportElement
            x="1"
            y="3"
            width="481"
            height="18"
            key="subreport-1"/>
        <subreportParameter  name="I_LANG">
            <subreportParameterExpression><![CDATA[$P{ID_LANGUAGE}]]></subreportParameterExpression>
        </subreportParameter>
        <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
        <subreportExpression  class="java.net.URL"><![CDATA[$P{SubRel_Cabecalho}]]></subreportExpression>
    </subreport>

</jasperReport>

In my java I configure an Hibertante connection in order to generate the report and pass the parameter as a resource

this.putParameterResource("SubRel_Cabecalho", "/reports/audit/edis_audit_cabecalho_analise.jasper");

My main problem Is when I generate the report, only show the data of the main report and doesn't print the subreport. I am missing some configuration in order to show the subreport?


Answer:

try with this,

defined SubRel_Cabecalho as a parameter with data type `class="java.lang.String"

<parameter name="SubRel_Cabecalho" isForPrompting="false" class="java.lang.String/>

then use it to pass the sub report file path

HashMap<String, Object> parameterMap = new HashMap<String, Object>();
parameterMap.put("SubRel_Cabecalho", "/reports/audit/edis_audit_cabecalho_analise.jasper");

Question:

I have a report that is exported to XLSX and PDF. The code of both exporters is pretty similar at the same time encoding is lost during PDF export.

For instance, the following symbols are simply skipped in the end result: "Č", "ć". At the same time "ü", "ß" are printed correctly.

In XLSx exporter (working part) I use pretty simple code:

try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
    JRXlsxExporter xlsExporter = new JRXlsxExporter();
    xlsExporter.setExporterInput(new SimpleExporterInput(jasperPrint));
    xlsExporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outputStream));
    xlsExporter.exportReport();
    return outputStream.toByteArray();
}

In case of PDF I use pretty the same code (doesn't work):

try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
    JRPdfExporter exporter = new JRPdfExporter();
    exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
    exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outputStream));
    exporter.exportReport();
    return outputStream.toByteArray();
}

But it doesn't work. In both cases I pass the same instance of jasperPrint.

I tried playing around with PdfExporterConfiguration to set up some parameters, but unfortunately haven't found any encoding related configuration.

Q: What might cause the problem? Any idea how to fix it?


Answer:

My suspision is that the problem comes from the fonts you are using. Are you sure both XLSX and PDF support the font you have set in your report? In the generated PDF you can check the used font by right-clicking and choosing document properties - there is a tab with fonts. Does the font in PDF support those symbols?

If I remember correctly sometimes when exporting to PDF the exporter will use some different font (if the one you wanted is not found/supported or something).

Question:


Answer:

I will answer myself. I just use Dejavu Sans in the report and put a maven dependency to the basic jasper fonts and that was it.

<!-- Fonts for special characters -->
    <dependency>
        <groupId>net.sf.jasperreports</groupId>
        <artifactId>jasperreports-fonts</artifactId>
        <version>6.0.0</version>
    </dependency>

That's a fragment of my pom.xml

Thanks to the guys in the comments who made it posible.

Question:

Im using Eclipse below are part of the code

<!--menu.jsp-->
<h1>Pass parameter to jasper report(CI_ID)</h1>
<form action = "call.jsp" target="_blank">
<input type= "text" name = "CI_ID" value = ""/><br/> 
<input type="submit" value="Print"/>
</form>

<!--call.jsp-->
<%Connection conn = null;
int id=Integer.parseInt(request.getParameter("CI_ID"));
try{
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","1234");
File reportFile = new File(application.getRealPath("//Report.jasper"));
Map parameters = new HashMap();
parameters.put("CI_ID",id);

byte[] bytes = JasperRunManager.runReportToPdf(reportFile.getPath(),parameters,conn);
response.setContentType("application/pdf");
response.setContentLength(bytes.length);
ServletOutputStream outStream = response.getOutputStream();
outStream.write(bytes, 0 , bytes.length);
response.getOutputStream().flush();
response.getOutputStream().close();
} catch (Exception e){
    e.printStackTrace();
}%>

I preview on the Jasper report without any problem but when I use the JSP to pass the parameter to Jasper report on Eclipse and i get this error "File does not begin with '%PDF-'." pop up window for adobe reader.

I tried below solution, but still not working

1)Change to

response.setContentType("application/pdf");

response.setContentType("application/x-pdf");

2)Update adobe reader

3)Import all related .jar for jasper


Answer:

First thing is you have session attributes and request.getParameters so that you can send those parameters to the jasper report.I will show an example for better understanding. I have a jsp page such as searchData.jsp

 <form action="searchResult.jsp" method="POST">
                    <table border="0" width="" cellspacing="15" cellpadding="1">
                        <thead>
                            <tr>
                                <th>Search Using:</th>
                                <th><select name="search">
                                        <option value=""> Select</option>
                                        <option value="Company Name">Company Name</option>
                                        <option value="Contact Person">Contact Person</option>
                                        <option value="Phone">Phone Number</option>
                                    </select></th>


                                <th><input type="text" name="search_tf" /></th>
                                <th><input type="submit" value=" " class="search_btn"/></th>
                            </tr>
                        </thead>
                        <tr>
                            <td></td><td></td><td></td><td></td>
                            <td><small>(Blank Search will result in Full Search Result)</small></td>
                        </tr>
                    </table>
                </form>

After clicking submit button as i have action as "searchResult.jsp" it will go to searchResult.jsp

In searchResult.jsp page i used request.getParameter so that the data entered in the previous jsp page will now enter into current jsp page and then i used session attributes so as it can used in the further jsp pages until session gets ended.It is as shown below

Search Result for <u><%= request.getParameter("search_tf")%></u> in <u><%= request.getParameter("search")%></u> is :

 Object o2 = session.getAttribute("email");
                                    String email = o2.toString();
                                    String category = request.getParameter("category");
                                    String search = request.getParameter("search");
                                    session.setAttribute("search",search);
                                    String search_tf = request.getParameter("search_tf");
                                    session.setAttribute("search_tf",search_tf);

and then my sql query,i am giving an example of sql query

if(search.equals("")&& search_tf.equals("")){
                                        sqlPgintn="SELECT SQL_CALC_FOUND_ROWS Id,Company_name,Contact_Person,Address,Phone,Company_Email,Review,Status,Lead_Date,Lead_Details,Lead_Value,followup_Date,Category from marketing_database.lead limit "+iPagNo+","+iSwRws+"";
}
 else if(search.equals("Company Name"))
                                    {   
                                        sqlPgintn="SELECT SQL_CALC_FOUND_ROWS Id,Company_name,Contact_Person,Address,Phone,Company_Email,Review,Status,Lead_Date,Lead_Details,Lead_Value,followup_Date,Category from marketing_database.lead where Company_Name ='"+search_tf+"' limit "+iPagNo+","+iSwRws+"";

And now using javascript i did this

<script type="text/javascript">
 function generateReport() {
  var e = document.getElementById("idOfYourSelectYouNeedToAddedIt");
  var strPage = e.options[e.selectedIndex].value;
  window.open(strPage);
 return false; //This make you stay on this page;
  //return true; //Set the action tag in the form to the page you like to go to!
 }
</script>
<center>       <form name="myForm" onsubmit="return generateReport()">
               <select id = "idOfYourSelectYouNeedToAddedIt">
<option value=''> Generate Report </option>
<option value='samplePDF.jsp'> PDF</option>
<option value='sampleDOC.jsp'> DOC </option>
<option value='sampleXLS.jsp'> XLS</option>
<option value='sampleXLSX.jsp'> XLSX </option>
</select>
<br/>

<input type="submit" value="Submit">
</form></center>

when i click on suppose "samplePDF.jsp" it will go that page and there i did this samplePDF.jsp

<%
Connection conn = null;
Object o2 = session.getAttribute("email");
String email = o2.toString();
String category=(String)session.getAttribute("category");
String status=(String)session.getAttribute("status");
String startDate=(String)session.getAttribute("startDate");
String endDate=(String)session.getAttribute("endDate");

try 
{
    Class.forName("com.mysql.jdbc.Driver");
    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/marketing_database","root","root");
    String sql = "select * from lead where Email = '" + email + "' AND Status LIKE '%" + status + "%' AND Category LIKE '%" + category + "%' AND STR_TO_DATE(`Lead_Date`, '%d-%m-%Y') BETWEEN '"+startDate+"' AND '"+endDate+"'";
    ServletContext context = request.getServletContext(); 
    String fullPath = context.getRealPath("/WEB-INF/reports/report10.jrxml");
    InputStream input = new FileInputStream(new File(fullPath));
    JasperDesign jasperDesign = JRXmlLoader.load(input);

    System.out.println("Compiling Report Designs");
    JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

    System.out.println("Creating JasperPrint Object");
    HashMap<String,Object> map = new HashMap<String,Object>();
    map.put("sql",sql);
            byte[] bytes = JasperRunManager.runReportToPdf(jasperReport, map, conn);

            response.setContentType("application/pdf");
            response.setContentLength(bytes.length);
            ServletOutputStream outStream = response.getOutputStream();
            outStream.write(bytes, 0, bytes.length);
            outStream.flush();
            outStream.close();
            conn.close();
}
catch(Exception e) 
{e.printStackTrace();} 

        %>

Question:

I'm new to Jasper Report. I'm trying to display Thai characters in PDF using font extensions but for some reason the characters are not displayed. I've researched on this issue and followed the official documentation (http://jasperreports.sourceforge.net/sample.reference/fonts/) but it didn't work.

I use TIBCO JasperSoft studio to do the design and everything is displayed correctly when I preview the design via JasperSoft studio. However, when I applied the generated jrxml file to my Java code the Thai characters were not displayed in PDF file. I also tried in Html file and everything worked just fine.

Following the official documentation to generate a PDF, i'm recommended to export the JAR file containing the TTF files, the jasperreports_extension.properties and fonts.xml files.

Please look at my code snippets

fontsfamily1445966397265.xml

<?xml version="1.0" encoding="UTF-8"?>
<fontFamilies>
  <fontFamily name="tahoma">
    <normal>fonts/tahoma/Tahoma.ttf</normal>
    <bold>fonts/tahoma/tahomabd.ttf</bold>
    <pdfEncoding>Identity-H</pdfEncoding>
    <pdfEmbedded>true</pdfEmbedded>
    <exportFonts>
  <export key="xhtml">tahoma</export>
  <export key="html">tahoma</export>
</exportFonts>

jasperreports_extension.properties

net.sf.jasperreports.extension.registry.factory.simple.font.families=net.sf.jasperreports.engine.fonts.SimpleFontExtensionsRegistryFactory
net.sf.jasperreports.extension.simple.font.families.ireportfamily1445966397265=fonts/fontsfamily1445966397265.xml

Java Code

JasperCompileManager.compileReportToFile(JRXML_FILE);
String printFileName = JasperFillManager.fillReportToFile(JASPER_FILE, params, conn);
JasperExportManager.exportReportToPdfFile(printFileName, PDF_FILE);

jrxml file

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.1.1.final using JasperReports Library version 6.1.1  -->
<!-- 2015-10-28T01:17:50 -->
<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="receipt" pageWidth="595" pageHeight="842" whenNoDataType="AllSectionsNoDetail" columnWidth="535" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="4eedbb89-b4f6-4469-9ab6-f642a1688cf7">
<property name="template.engine" value="tabular_template"/>
<style name="Title" forecolor="#FFFFFF" fontName="tahoma" fontSize="50" isBold="false"/>
<style name="SubTitle" forecolor="#CCCCCC" fontName="tahoma" fontSize="18" isBold="false"/>
<style name="Column header" forecolor="#666666" fontName="tahoma" fontSize="14" isBold="false"/>
<style name="Detail" mode="Transparent" fontName="tahoma"/>
<style name="Row" mode="Transparent" fontName="tahoma">
    <conditionalStyle>
        <conditionExpression><![CDATA[$V{REPORT_COUNT}%2 == 0]]></conditionExpression>
        <style mode="Opaque" backcolor="#EEEFF0"/>
    </conditionalStyle>
</style>
<style name="Table">
    <box>
        <pen lineWidth="1.0" lineColor="#000000"/>
        <topPen lineWidth="1.0" lineColor="#000000"/>
        <leftPen lineWidth="1.0" lineColor="#000000"/>
        <bottomPen lineWidth="1.0" lineColor="#000000"/>
        <rightPen lineWidth="1.0" lineColor="#000000"/>
    </box>
</style>
<style name="Table_TH" mode="Opaque" backcolor="#FFFFFF">
    <box>
        <pen lineWidth="0.5" lineColor="#000000"/>
        <topPen lineWidth="0.5" lineColor="#000000"/>
        <leftPen lineWidth="0.5" lineColor="#000000"/>
        <bottomPen lineWidth="0.5" lineColor="#000000"/>
        <rightPen lineWidth="0.5" lineColor="#000000"/>
    </box>
</style>
<style name="Table_CH" mode="Opaque" backcolor="#CACED0">
    <box>
        <pen lineWidth="0.5" lineColor="#000000"/>
        <topPen lineWidth="0.5" lineColor="#000000"/>
        <leftPen lineWidth="0.5" lineColor="#000000"/>
        <bottomPen lineWidth="0.5" lineColor="#000000"/>
        <rightPen lineWidth="0.5" lineColor="#000000"/>
    </box>
</style>
<style name="Table_TD" mode="Opaque" backcolor="#FFFFFF">
    <box>
        <pen lineWidth="0.5" lineColor="#000000"/>
        <topPen lineWidth="0.5" lineColor="#000000"/>
        <leftPen lineWidth="0.5" lineColor="#000000"/>
        <bottomPen lineWidth="0.5" lineColor="#000000"/>
        <rightPen lineWidth="0.5" lineColor="#000000"/>
    </box>
    <conditionalStyle>
        <conditionExpression><![CDATA[$V{REPORT_COUNT}%2 == 0]]></conditionExpression>
        <style backcolor="#D8D8D8"/>
    </conditionalStyle>
</style>
<subDataset name="tableDataset" uuid="6590503c-ab84-4f89-80d9-38ac71dd1404">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="New Data Adapter "/>
    <property name="com.jaspersoft.studio.data.sql.tables" value=""/>
    <parameter name="customer_id" class="java.lang.Long"/>
    <queryString>
        <![CDATA[SELECT l.name, lbd.buy_type, lbd.buy_price, (lbd.buy_price - down_payment) AS debt FROM land l INNER JOIN land_buy_detail lbd ON l.id = lbd.land_id  WHERE lbd.customer_id = $P{customer_id}]]>
    </queryString>
    <field name="name" class="java.lang.String"/>
    <field name="buy_type" class="java.lang.String"/>
    <field name="buy_price" class="java.lang.Float"/>
    <field name="debt" class="java.lang.Float"/>
</subDataset>
<parameter name="customer_id" class="java.lang.Long">
    <parameterDescription><![CDATA[]]></parameterDescription>
    <defaultValueExpression><![CDATA[$P{customer_id}]]></defaultValueExpression>
</parameter>
<queryString>
    <![CDATA[SELECT firstname, lastname, address, tel FROM customer WHERE id = $P{customer_id}]]>
</queryString>
<field name="firstname" class="java.lang.String"/>
<field name="lastname" class="java.lang.String"/>
<field name="address" class="java.lang.String"/>
<field name="tel" class="java.lang.String"/>
<title>
    <band height="357" splitType="Stretch">
        <staticText>
            <reportElement x="0" y="90" width="84" height="25" uuid="57aed2b1-4f4e-40a3-a6ad-54dae8dd4c5a">
                <property name="local_mesure_unitheight" value="pixel"/>
                <property name="com.jaspersoft.studio.unit.height" value="px"/>
            </reportElement>
            <textElement>
                <font size="16" isBold="true"/>
            </textElement>
            <text><![CDATA[Bill to:]]></text>
        </staticText>
        <line>
            <reportElement x="0" y="80" width="556" height="1" uuid="806ce5df-1219-4876-ae0c-ca7405b1f246">
                <property name="local_mesure_unitheight" value="pixel"/>
                <property name="com.jaspersoft.studio.unit.height" value="px"/>
            </reportElement>
        </line>
        <staticText>
            <reportElement x="415" y="10" width="50" height="20" uuid="0f86baff-6386-4f3f-b3fe-2388707babe8"/>
            <box rightPadding="4"/>
            <textElement textAlignment="Right"/>
            <text><![CDATA[Date:]]></text>
        </staticText>
        <textField pattern="EEEEE dd MMMMM yyyy">
            <reportElement x="465" y="10" width="84" height="20" uuid="bb10dbe1-0a4f-4722-9953-c163b63cf979"/>
            <textFieldExpression><![CDATA[new java.util.Date()]]></textFieldExpression>
        </textField>
        <image hAlign="Center">
            <reportElement x="0" y="0" width="65" height="60" uuid="94883631-a913-43e2-b182-ab8d77d0181e"/>
            <imageExpression><![CDATA["invoice_logo.png"]]></imageExpression>
        </image>
        <textField pattern="EEEEE dd MMMMM yyyy">
            <reportElement x="465" y="30" width="84" height="20" uuid="3836ce65-eca3-4cad-a6de-b1818def0a2b"/>
            <textFieldExpression><![CDATA["INV0001"]]></textFieldExpression>
        </textField>
        <staticText>
            <reportElement x="415" y="30" width="50" height="20" uuid="0b3f9342-da78-4cfa-9fc5-2301c4749678"/>
            <box rightPadding="4"/>
            <textElement textAlignment="Right"/>
            <text><![CDATA[Invoice:]]></text>
        </staticText>
        <staticText>
            <reportElement x="95" y="0" width="205" height="25" uuid="e622555d-198b-4ccd-a4a1-c59c53304058">
                <property name="local_mesure_unitheight" value="pixel"/>
                <property name="com.jaspersoft.studio.unit.height" value="px"/>
            </reportElement>
            <textElement>
                <font size="19" isBold="true"/>
            </textElement>
            <text><![CDATA[BP Property]]></text>
        </staticText>
        <staticText>
            <reportElement x="95" y="55" width="205" height="15" uuid="b8cc42fd-b569-497d-834d-7e854040ad18"/>
            <textElement>
                <font fontName="tahoma"/>
            </textElement>
            <text><![CDATA[08-19595-240]]></text>
        </staticText>
        <staticText>
            <reportElement x="95" y="25" width="205" height="15" uuid="c226e44d-3bb5-4145-b0b3-903bf1d79fde"/>
            <textElement markup="none">
                <font fontName="tahoma" size="11" isBold="false"/>
            </textElement>
            <text><![CDATA[1174 ถ. เพชรเกษม อ. หาดใหญ่]]></text>
        </staticText>
        <staticText>
            <reportElement positionType="FixRelativeToBottom" x="95" y="40" width="205" height="15" uuid="b96f7183-44f8-43ad-ba60-43d8fbf50b6e"/>
            <textElement>
                <font fontName="tahoma"/>
            </textElement>
            <text><![CDATA[ต. หาดใหญ่ จ. สงขลา  90110]]></text>
        </staticText>
        <textField>
            <reportElement x="0" y="115" width="120" height="15" uuid="0e5185a4-3292-4051-927f-7e07f549bceb"/>
            <textFieldExpression><![CDATA[new String($F{firstname} + " " + $F{lastname})]]></textFieldExpression>
        </textField>
        <textField>
            <reportElement x="0" y="130" width="120" height="15" uuid="0925d7fe-e543-4225-b44e-ff1828d6cb8a"/>
            <textFieldExpression><![CDATA[$F{address}]]></textFieldExpression>
        </textField>
        <textField>
            <reportElement x="0" y="145" width="120" height="15" uuid="199db39e-5210-4d3a-a0c5-baf4543d9d49"/>
            <textFieldExpression><![CDATA[$F{tel}]]></textFieldExpression>
        </textField>
        <componentElement>
            <reportElement x="0" y="166" width="555" height="130" uuid="b8e9c2ed-feb3-408c-b9be-6aebbeb6af52"/>
            <jr:table xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd">
                <datasetRun subDataset="tableDataset" uuid="6ea978fd-ffe0-40bb-84a7-f09b1f220cfa">
                    <datasetParameter name="customer_id">
                        <datasetParameterExpression><![CDATA[$P{customer_id}]]></datasetParameterExpression>
                    </datasetParameter>
                    <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
                </datasetRun>
                <jr:column width="190" uuid="06d1364f-8060-496c-ac0c-b44946e09dd0">
                    <jr:columnHeader style="Table_CH" height="30">
                        <staticText>
                            <reportElement key="" style="Column header" x="0" y="0" width="190" height="30" forecolor="#000000" uuid="93321529-b12d-4528-8316-4e6e94a6c476">
                                <property name="com.jaspersoft.studio.unit.x" value="pixel"/>
                            </reportElement>
                            <box leftPadding="2"/>
                            <textElement textAlignment="Center" verticalAlignment="Middle">
                                <font fontName="tahoma" size="12" isBold="true"/>
                            </textElement>
                            <text><![CDATA[รายการ]]></text>
                        </staticText>
                    </jr:columnHeader>
                    <jr:detailCell style="Table_TD" height="30">
                        <textField>
                            <reportElement style="Detail" x="0" y="0" width="190" height="30" uuid="4be9692f-e0bf-4a89-9f21-b579d46c9adf">
                                <property name="com.jaspersoft.studio.unit.x" value="pixel"/>
                            </reportElement>
                            <box leftPadding="2"/>
                            <textElement textAlignment="Left" verticalAlignment="Middle">
                                <font fontName="tahoma" size="12"/>
                            </textElement>
                            <textFieldExpression><![CDATA["   " + $F{name}]]></textFieldExpression>
                        </textField>
                    </jr:detailCell>
                </jr:column>
                <jr:column width="90" uuid="25357c6d-7a1a-4bcb-ac60-8d18805b681c">
                    <jr:columnHeader style="Table_CH" height="30">
                        <staticText>
                            <reportElement x="0" y="0" width="90" height="30" forecolor="#000000" uuid="c8f288aa-8d2e-48ce-8ee7-d710740d7b52"/>
                            <box leftPadding="2"/>
                            <textElement textAlignment="Center" verticalAlignment="Middle">
                                <font fontName="tahoma" size="12" isBold="true"/>
                            </textElement>
                            <text><![CDATA[ประเภท]]></text>
                        </staticText>
                    </jr:columnHeader>
                    <jr:detailCell style="Table_TD" height="30">
                        <textField>
                            <reportElement style="Detail" x="0" y="0" width="90" height="30" uuid="6735552d-0796-499f-af74-e308260bc5e0"/>
                            <box leftPadding="2"/>
                            <textElement textAlignment="Left" verticalAlignment="Middle">
                                <font fontName="tahoma" size="12"/>
                            </textElement>
                            <textFieldExpression><![CDATA[($F{buy_type}.equals("C")) ? "   สด" : "   ผ่อน"]]></textFieldExpression>
                        </textField>
                    </jr:detailCell>
                </jr:column>
                <jr:column width="120" uuid="18cfa391-26d8-4a47-8e88-a7d1bef16d74">
                    <jr:columnHeader style="Table_CH" height="30">
                        <staticText>
                            <reportElement key="" style="Column header" x="0" y="0" width="120" height="30" forecolor="#000000" uuid="fc75656e-008d-47b4-ab25-2cdb62acb876"/>
                            <box leftPadding="2"/>
                            <textElement textAlignment="Center" verticalAlignment="Middle">
                                <font fontName="tahoma" size="12" isBold="true"/>
                            </textElement>
                            <text><![CDATA[ราคาซื้อ]]></text>
                        </staticText>
                    </jr:columnHeader>
                    <jr:detailCell style="Table_TD" height="30">
                        <textField>
                            <reportElement style="Detail" x="0" y="0" width="120" height="30" uuid="db5ac821-df67-42ec-8f12-c3cbce27a8fd"/>
                            <box leftPadding="2"/>
                            <textElement textAlignment="Left" verticalAlignment="Middle">
                                <font fontName="tahoma" size="12"/>
                            </textElement>
                            <textFieldExpression><![CDATA["   " + $F{buy_price}]]></textFieldExpression>
                        </textField>
                    </jr:detailCell>
                </jr:column>
                <jr:column width="155" uuid="c192f0f1-d7f3-4362-8149-f9d592cdac30">
                    <jr:columnHeader style="Table_CH" height="30">
                        <staticText>
                            <reportElement key="" style="Column header" stretchType="RelativeToTallestObject" x="0" y="0" width="155" height="30" forecolor="#000000" uuid="2c3771ca-3b46-4bae-837b-88fac22baff7"/>
                            <box leftPadding="2"/>
                            <textElement textAlignment="Center" verticalAlignment="Middle">
                                <font fontName="tahoma" size="12" isBold="false"/>
                            </textElement>
                            <text><![CDATA[ยอดคงค้าง]]></text>
                        </staticText>
                    </jr:columnHeader>
                    <jr:detailCell style="Table_TD" height="30">
                        <textField pattern="#,###.##">
                            <reportElement style="Detail" x="10" y="0" width="145" height="30" uuid="94659f20-5913-48a2-b64c-683d0584936c"/>
                            <box leftPadding="2"/>
                            <textElement textAlignment="Left" verticalAlignment="Middle">
                                <font size="12"/>
                            </textElement>
                            <textFieldExpression><![CDATA[$F{debt}]]></textFieldExpression>
                        </textField>
                    </jr:detailCell>
                </jr:column>
            </jr:table>
        </componentElement>
        <staticText>
            <reportElement positionType="Float" mode="Opaque" x="0" y="290" width="556" height="30" backcolor="#E6E8E9" uuid="36aa233d-4305-48e6-974a-1bbf89bb3c8f"/>
            <textElement textAlignment="Center" verticalAlignment="Middle">
                <font fontName="tahoma" size="9" isItalic="true"/>
            </textElement>
            <text><![CDATA[THANKYOU FOR YOUR BUSINESS]]></text>
        </staticText>
    </band>
</title>
<summary>
    <band height="293" splitType="Stretch">
        <property name="local_mesure_unitheight" value="pixel"/>
    </band>
</summary>

I'm sure that the JAR file is in my Maven classpath.

I'm using Jaspersoft Studio version 6.1.1.final using JasperReports Library version 6.1.1.


Answer:

I solved the issue. I just forgot to point JASPER_FILE variable to the right file. This solution for displaying international characters already worked :)

Question:

I want to view the jasper report that i created when i run "PDFLEAD.jsp" page. But it is showing like"getWriter() has already been called for this response." and it is displaying as the image given below.The code i tried is as follows

PDFLEAD.jsp

<%@page import = "net.sf.jasperreports.engine.design.JRDesignQuery"%>
<%@page import = "net.sf.jasperreports.engine.xml.JRXmlLoader"%>
<%@page import = "net.sf.jasperreports.engine.design.JasperDesign"%>
<%@page import = "net.sf.jasperreports.view.JasperViewer"%>
<%@page import = "net.sf.jasperreports.engine.JRException"%>
<%@page import = "net.sf.jasperreports.engine.JRResultSetDataSource"%>
<%@page import = "net.sf.jasperreports.engine.JasperCompileManager"%>
<%@page import = "net.sf.jasperreports.engine.JasperExportManager"%>
<%@page import = "net.sf.jasperreports.engine.JasperFillManager"%>
<%@page import = "net.sf.jasperreports.engine.JasperPrint"%>
<%@page import = "net.sf.jasperreports.engine.JasperReport"%>
<%@page import = "net.sf.jasperreports.engine.data.JRCsvDataSource"%>
<%@page import = "net.sf.jasperreports.engine.export.ooxml.JRDocxExporter"%>
<%@page import = "net.sf.jasperreports.engine.export.JRPdfExporter"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<%@ include file="/Purchase.jsp" %>

<%@ page import="net.sf.jasperreports.engine.*" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.text.ParseException" %>
<%@ page import="java.io.File" %>
<%@ page import="java.io.FileInputStream" %>
<%@ page import="java.io.FileNotFoundException" %>
<%@ page import="java.io.InputStream" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.io.FileOutputStream" %>
<%@ page import="java.io.ByteArrayOutputStream" %>
<%@ page import="java.io.OutputStream" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.Map" %>
<%@ page import="net.sf.jasperreports.engine.util.*" %> 
<%@ page import="net.sf.jasperreports.engine.export.*" %>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title></title>
</head>
<body>
<% 
Connection conn = null;
String sear=(String)session.getAttribute("sea");
String cate=(String)session.getAttribute("cat");
String comp=(String)session.getAttribute("com");

System.out.println("1 is:"+sear);
System.out.println("2 is:"+cate);
System.out.println("3 is:"+comp);

try 
{
    Class.forName("com.mysql.jdbc.Driver");
    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/marketing_database","root","root");
    String jrxmlFile ="D:/dev/tools/jasper files/report10.jrxml";
    InputStream input = new FileInputStream(new File(jrxmlFile));
    JasperDesign jasperDesign = JRXmlLoader.load(input);

    System.out.println("Compiling Report Designs");
    JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

    System.out.println("Creating JasperPrint Object");
    HashMap<String,Object> map = new HashMap<String,Object>();
    map.put("complan",comp);
    map.put("search",sear);
    map.put("category",cate);

    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport,map,conn);
    byte bytes[] = new byte[10000]; 
    JRPdfExporter exporter = new JRPdfExporter();
    ByteArrayOutputStream Stream = new ByteArrayOutputStream(); 
    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); 
    exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, Stream); 
    exporter.exportReport(); 
    System.out.println("Size of byte array:"+Stream.size()); 
    bytes = Stream.toByteArray(); 
    response.setContentType("application/pdf"); 
    System.out.println("After JasperPrint = 1"); 
    response.setContentLength(bytes.length); 
    System.out.println("After JasperPrint = 2"); 
    Stream.close(); 
    System.out.println("After JasperPrint = 3"); 

    OutputStream outputStream = response.getOutputStream(); 
    System.out.println("After JasperPrint = 4"); 
    outputStream.write(bytes, 0, bytes.length); 
    outputStream.flush(); 
    outputStream.close(); 

}
catch(Exception e) 
{e.printStackTrace();} 


%>
</body>
</html>

Answer:

The error is that you already used the writer to send <!DOCTYPE and other html tags (including System.out)

Remove all html tags as <html>,<head>,<title> ecc.

Remove System.out.println (this can not be used if your streaming the pdf content)

Replace

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

With

<%@ page contentType="application/pdf" %>
<%@ page trimDirectiveWhitespaces="true"%>

and stream your pdf (I would do like this):

JasperExportManager.exportReportToPdfStream(jasperPrint,    
response.getOutputStream());

Hence only these 3 commands can be sent to browser...

Question:

I am using JasperReports 5.6 I generate pdf using PDFCreator. My pdf is generated successfully, but i can't set name to that PDF file.

PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
printRequestAttributeSet.add(MediaSizeName.ISO_A4);
PrintServiceAttributeSet printServiceAttributeSet = new HashPrintServiceAttributeSet();
printServiceAttributeSet.add(new PrinterName("PDFCreator", null));   
JRPrintServiceExporter exporter = new JRPrintServiceExporter(); 
exporter.setExporterInput(new SimpleExporterInput(tempFileName));
SimplePrintServiceExporterConfiguration configuration = new SimplePrintServiceExporterConfiguration();
configuration.setPrintRequestAttributeSet(printRequestAttributeSet);
configuration.setPrintServiceAttributeSet(printServiceAttributeSet);
configuration.setDisplayPageDialog(false);
configuration.setDisplayPrintDialog(false);
exporter.setConfiguration(configuration);   
exporter.exportReport();

My pdf name are set using that PDFCreator tool I want to pass the name to that pdf file. Since exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, "d:/adc.pdf"); method is now deprecated. Please tell me solution how to set that out file name


Answer:

I don't think there's a way to pass a file name to PDFCreator, because the whole idea is that it is a virtual printer. So to the program that sending the document, it could be being printed on a physical printer somewhere, hence an output file name would be irrelevant.

Whenever I need to output reports as PDFs I use JasperExportManager, which is a much simpler solution. The exportReportToPdfFile method accepts the output file path as a string. Example:

JasperPrint filledReport = JasperFillManager.fillReport("report.jrxml", params);
JasperExportManager.exportReportToPdfFile(filledReport, "report.pdf");

Alternatively, you can keep your code largely the same but change your JRPrintServiceExporter to a JRPdfExporter. The new way to set the output format (now that setParameter is deprecated) is to construct an ExporterOutput and then call setExporterOutput on your exporter.

Question:

I'm trying to export the List<JapserPrint> into a single PDF file. Because I'm dealing with multiple JapserPrint objects, I need to change the page number dynamically in java code.

I tried the following solution

I've made one parent JapserPrint object out of List

private void overridePageNumbers(final JasperPrint parentJapserPrint) {

    final int totalPages = jasperPrints.getPages().size();

    final AtomicInteger currentPageNumber = new AtomicInteger(1);

    final List<JRPrintPage> listPages = parentJapserPrint.getPages();

    for (final JRPrintPage currentPage : listPages) {
        final List listElements = currentPage.getElements();

        for (final Object element : listElements) {
            if (element instanceof JRTemplatePrintText) {
                final JRTemplatePrintText templatePrintText = (JRTemplatePrintText) element;

                // set currrent page
                if (templatePrintText.getKey() != null &&
                        templatePrintText.getKey().equalsIgnoreCase("textFieldCurrentPage")) {
                    LOGGER.info(templatePrintText.getFullText());
                    templatePrintText.setText("Page " + currentPageNumber.getAndIncrement() + " of ");
                    LOGGER.info(templatePrintText.getFullText());
                }

                // set total number of pages
                if (templatePrintText.getKey() != null &&
                        templatePrintText.getKey().equalsIgnoreCase("textFieldNumberOfPages")) {
                    LOGGER.info(templatePrintText.getFullText());
                    templatePrintText.setText(String.valueOf(totalPages));
                    LOGGER.info(templatePrintText.getFullText());
                }
            }
        }
    }
}

    <pageFooter>
    <band height="17">
        <property name="com.jaspersoft.studio.unit.height" value="px"/>
        <textField pattern="EEEEE dd MMMMM yyyy">
            <reportElement mode="Transparent" x="0" y="4" width="100" height="13" uuid="4e52ad3d-806e-45fa-ba2c-0d026ce60568"/>
            <textFieldExpression><![CDATA[new java.util.Date()]]></textFieldExpression>
        </textField>
        <textField>
            <reportElement key="textFieldCurrentPage" mode="Opaque" x="573" y="4" width="192" height="13" uuid="d4f96443-350c-49fe-a0af-60ad86fb0f30"/>
            <textElement textAlignment="Right"/>
            <textFieldExpression><![CDATA["${CURRENT_PAGE_NUMBER}"]]></textFieldExpression>
        </textField>
        <textField evaluationTime="Report">
            <reportElement key="textFieldNumberOfPages" mode="Opaque" x="768" y="4" width="31" height="13" uuid="81bfe333-c59e-415c-b570-9136c4ddf6d7"/>
            <textFieldExpression><![CDATA[" " + $V{PAGE_NUMBER}]]></textFieldExpression>
        </textField>
    </band>
</pageFooter>

With the help of log, It seems like the text value is being set. But the final output PDF file doesn't show overridden value.

18:42:05.967 INFO  com.company.service.ReportService - [n/a] Page 1 of
18:42:05.968 INFO  com.company.service.ReportService - [n/a] Page 1 of 
18:42:05.970 INFO  com.company.service.ReportService - [n/a] Page 2 of
18:42:05.971 INFO  com.company.service.ReportService - [n/a] Page 2 of 
18:42:05.975 INFO  com.company.service.ReportService - [n/a] Page 1 of
18:42:05.975 INFO  com.company.service.ReportService - [n/a] Page 3 of 
18:42:05.977 INFO  com.company.service.ReportService - [n/a] Page 2 of
18:42:05.978 INFO  com.company.service.ReportService - [n/a] Page 4 of 

Answer:

I found what the problem is, on my own

In my code, I'm using virtualizer to minimize the memory utilization and to avoid the system to run into out of memory exception. You can read about it more here

final JRGzipVirtualizer virtualizer = new JRGzipVirtualizer(10);
.
. // other code
.
virtualizer.setReadOnly(true);

new JRGzipVirtualizer(10) means it only keeps 10 pages at a time in the memory and remaining it stores in a compressed form. I'm also overriding virtualizer's read-only mode to true. This is what leads to my problem. It doesn't allow us to override the JasperPrint object once it has been generated

Solution: remove the code virtualizer.setReadOnly(true);

Question:

I am setting up a Servlet to generate PDF from jaspersoft studio. How can I generate filled PDF?

I have already tried many solutions to generate PDF but PDF is generating with empty result.

Here is the code for my servlet:

     @WebServlet("/JasperServlet")
        public class JasperServlet extends HttpServlet {
            private static final long serialVersionUID = 1L;

    /**
     * Default constructor.
     */
    public JasperServlet() {
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            InputStream jrxmlInput = this.getClass().getClassLoader().getResource("payment_receipt_ar_new.jrxml").openStream();

            JasperDesign design = JRXmlLoader.load(jrxmlInput);
            JasperReport jasperReport = JasperCompileManager.compileReport(design);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap());
            JRPdfExporter pdfExporter = new JRPdfExporter();
            pdfExporter.setExporterInput(new SimpleExporterInput(jasperPrint));
            ByteArrayOutputStream pdfReportStream = new ByteArrayOutputStream();
            pdfExporter.setExporterOutput(new SimpleOutputStreamExporterOutput(pdfReportStream));
            pdfExporter.exportReport();
            System.out.println("size: " + String.valueOf(pdfReportStream.size()) );
            response.setContentType("application/pdf");
            response.setHeader("Content-Length", String.valueOf(pdfReportStream.size()));
            response.addHeader("Content-Disposition", "inline; filename=jasper.pdf;");

            OutputStream responseOutputStream = response.getOutputStream();
            responseOutputStream.write(pdfReportStream.toByteArray());
            responseOutputStream.close();
            pdfReportStream.close();



        } catch (JRException e) { // TODO Auto-generated
            e.printStackTrace();
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub


    }

}

and here is payment_receipt_ar_new.jrxml:

       <?xml version="1.0" encoding="UTF-8"?>
        <!-- Created with Jaspersoft Studio version 6.10.0.final using 
         JasperReports Library version 6.10.0-unknown  -->
       <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="payment_receipt_ar_new" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="ace94295-a399-4efe-bad7-5bf5d0e0b3d6">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
    <parameter name="logoURL" class="java.lang.String"/>
    <parameter name="paymentConfirmationNumberValue" class="java.lang.String"/>
    <parameter name="civilIdValue" class="java.lang.String"/>
    <parameter name="nameValue" class="java.lang.String"/>
    <parameter name="mobileNumberValue" class="java.lang.String"/>
    <parameter name="dateOfPaymentValue" class="java.lang.String"/>
    <parameter name="paymentTransferValue" class="java.lang.String"/>
    <parameter name="totalAmountPaidValue" class="java.lang.String"/>
    <parameter name="documentNumberValue" class="java.lang.String"/>
    <parameter name="copyrightsYearPeriodAndYear" class="java.lang.String"/>
    <parameter name="companyName" class="java.lang.String"/>
    <parameter name="footerArabicLine" class="java.lang.String"/>
    <parameter name="footerEnglishLine" class="java.lang.String"/>
    <parameter name="footerLink1Middle" class="java.lang.String"/>
    <parameter name="footerLink2Right" class="java.lang.String"/>
    <parameter name="memberCompanyNameFooter" class="java.lang.String"/>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band height="136" splitType="Stretch">
            <image>
                <reportElement x="455" y="0" width="100" height="103" uuid="6e4a551a-60b2-4eb8-91b6-9e7d22520cce"/>
                <imageExpression><![CDATA[$P{logoURL}]]></imageExpression>
            </image>
            <staticText>
                <reportElement x="190" y="103" width="165" height="32" uuid="c1897c62-e37e-4009-a0e9-27559519e4e9"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font fontName="gss two light" size="14" isBold="true" isUnderline="true"/>
                </textElement>
                <text><![CDATA[إﻳﺼﺎل اﻟﺪﻓﻊ
]]></text>
            </staticText>
        </band>
    </title>
    <detail>
        <band height="445" splitType="Stretch">
            <staticText>
                <reportElement x="436" y="12" width="100" height="20" forecolor="#000000" uuid="3b15c799-76c2-4896-9c48-40e4b261bf65"/>
                <textElement textAlignment="Right" verticalAlignment="Middle">
                    <font fontName="gss two light" size="14"/>
                </textElement>
                <text><![CDATA[رﻗﻢ ﺗﺄﻛﻴﺪ اﻟﺪﻓﻊ:
]]></text>
            </staticText>
            <staticText>
                <reportElement x="436" y="45" width="100" height="20" uuid="09200ee0-1c47-4c28-9f9e-fabc013363b6"/>
                <textElement textAlignment="Right" verticalAlignment="Middle">
                    <font fontName="gss two light" size="14"/>
                </textElement>
                <text><![CDATA[رﻗﻢ اﻟﺒﻄﺎﻗﺔ اﻟﻤﺪﻧﻴﺔ:
]]></text>
            </staticText>
            <staticText>
                <reportElement x="436" y="79" width="100" height="20" uuid="7261f6bf-aab1-4492-9823-69e265a6e395"/>
                <textElement textAlignment="Right" verticalAlignment="Middle">
                    <font fontName="gss two light" size="14"/>
                </textElement>
                <text><![CDATA[اﻻﺳﻢ:]]></text>
            </staticText>
            <staticText>
                <reportElement x="436" y="113" width="100" height="20" uuid="f2bd6cf8-0c9d-4872-aca5-049e3335af79"/>
                <textElement textAlignment="Right" verticalAlignment="Middle">
                    <font fontName="gss two light" size="14"/>
                </textElement>
                <text><![CDATA[رﻗﻢ اﻟﻤﺤﻤﻮل:
]]></text>
            </staticText>
            <staticText>
                <reportElement x="436" y="148" width="100" height="20" uuid="43bf8d62-2683-4fcb-a51e-8543ade937ce"/>
                <textElement textAlignment="Right" verticalAlignment="Middle">
                    <font fontName="gss two light" size="14"/>
                </textElement>
                <text><![CDATA[ﺗﺎرﻳﺦ اﻟﺪﻓﻊ:
]]></text>
            </staticText>
            <staticText>
                <reportElement x="436" y="183" width="100" height="20" uuid="24437f8d-abce-4d11-9b72-11daca325dc4"/>
                <textElement textAlignment="Right" verticalAlignment="Middle">
                    <font fontName="gss two light" size="14"/>
                </textElement>
                <text><![CDATA[رﻗﻢ ﺗﺤﻮﻳﻞ اﻟﺪﻓﻊ:
]]></text>
            </staticText>
            <staticText>
                <reportElement x="409" y="218" width="127" height="20" uuid="f1691a8d-8f9d-4263-975d-36dfb9b8aacd"/>
                <textElement textAlignment="Right" verticalAlignment="Middle">
                    <font fontName="gss two light" size="14"/>
                </textElement>
                <text><![CDATA[إﺟﻤﺎﻟﻲ اﻟﻤﺒﻠﻎ اﻟﻤﺪﻓﻮع:
]]></text>
            </staticText>
            <staticText>
                <reportElement x="436" y="255" width="100" height="20" uuid="1fe7b546-c1f3-4ef9-a912-14a9fd8a17b4"/>
                <textElement textAlignment="Right" verticalAlignment="Middle">
                    <font fontName="gss two light" size="14" isBold="false"/>
                </textElement>
                <text><![CDATA[رﻗﻢ اﻟﻮﺛﻴﻘﺔ:
]]></text>
            </staticText>
            <textField>
                <reportElement x="175" y="12" width="180" height="20" uuid="1471f822-9142-4510-9913-b662bc8cd5d5"/>
                <textElement textAlignment="Right" verticalAlignment="Middle">
                    <font fontName="FrieghtSansMedium" size="14"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{paymentConfirmationNumberValue}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="175" y="45" width="180" height="20" uuid="f12577d5-1206-4296-9ca3-b3dd935ad0f6"/>
                <textElement textAlignment="Right">
                    <font fontName="FrieghtSansMedium" size="14"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{civilIdValue}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="175" y="79" width="180" height="20" uuid="13e14a71-57a7-4d4d-a0c2-3ccb192f7cdc"/>
                <textElement textAlignment="Right">
                    <font fontName="gss two light" size="14"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{nameValue}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="175" y="113" width="180" height="20" uuid="6c034d11-ad89-4e5d-883f-573fd316bb7f"/>
                <textElement textAlignment="Right">
                    <font fontName="FrieghtSansMedium" size="14"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{mobileNumberValue}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="175" y="148" width="180" height="20" uuid="0834469d-0336-4b9f-9046-bbfd5d90bbaf"/>
                <textElement textAlignment="Right">
                    <font fontName="FrieghtSansMedium" size="14"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{dateOfPaymentValue}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="175" y="183" width="180" height="20" uuid="789c5215-1ade-4571-9f97-535e8ec56652"/>
                <textElement textAlignment="Right">
                    <font fontName="FrieghtSansMedium" size="14"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{paymentTransferValue}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="175" y="218" width="180" height="20" uuid="2a4590fd-623d-464e-bc8e-9ac6afead097"/>
                <textElement textAlignment="Right">
                    <font fontName="FrieghtSansMedium" size="14"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{totalAmountPaidValue}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="175" y="255" width="180" height="35" uuid="e04d44a7-e628-43c4-b33d-21b28a065323"/>
                <textElement textAlignment="Right" markup="html">
                    <font fontName="FrieghtSansMedium" size="14"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{documentNumberValue}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="126" y="405" width="283" height="20" uuid="eb66e88c-45ad-4ab7-bb8c-10d581410293"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font fontName="gss two light" size="16" isBold="true"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{copyrightsYearPeriodAndYear}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="114" y="425" width="311" height="20" uuid="aafa90a1-86a2-4281-95c6-d09b696adb29"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font fontName="gss two light" size="16" isBold="true"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{companyName}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
    <pageFooter>
        <band height="65" splitType="Stretch">
            <textField>
                <reportElement x="0" y="0" width="555" height="20" uuid="ee1bd043-02d8-406a-8cd7-9f14349fec45"/>
                <textElement textAlignment="Right" verticalAlignment="Middle">
                    <font fontName="gss two light"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{footerArabicLine}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="0" y="20" width="555" height="20" uuid="d5fb4ff4-6f94-4161-a3ab-0e35b8702fe9"/>
                <textElement verticalAlignment="Middle">
                    <font fontName="FrieghtSansMedium"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{footerEnglishLine}]]></textFieldExpression>
            </textField>
            <line>
                <reportElement x="0" y="40" width="555" height="1" uuid="012d5907-5d65-4b3c-926f-5bf08a05b3a1"/>
            </line>
            <textField>
                <reportElement x="0" y="41" width="263" height="20" uuid="05943f07-7173-449b-a658-8f14476097c4"/>
                <textElement verticalAlignment="Top" markup="html">
                    <font fontName="FrieghtSansMedium"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{memberCompanyNameFooter}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="209" y="41" width="184" height="20" uuid="6b234eeb-bd9c-46db-aa3a-4f242fd0b286"/>
                <textElement textAlignment="Center" verticalAlignment="Top">
                    <font fontName="FrieghtSansMedium"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{footerLink1Middle}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="393" y="41" width="162" height="20" uuid="482ba13a-d3c8-44fd-87e6-590bd8b2b1b6"/>
                <textElement textAlignment="Right" verticalAlignment="Top">
                    <font fontName="FrieghtSansMedium"/>
                </textElement>
                <textFieldExpression><![CDATA[$P{footerLink2Right}]]></textFieldExpression>
            </textField>
        </band>
    </pageFooter>
</jasperReport>

Please help me out it is generating empty pdf.

I expect output to show filled pdf with some static and parametric data. But right now it is generating empty PDF.


Answer:

If you want title, headers, etc, but no Detail Band if there is an empty resulse, then set the WhenNoDataType=AllSectionsNoDetail attribute. This will confirm the problem is due to no resultset being returned from the datasource. https://community.jaspersoft.com/wiki/empty-report-problem

Question:

I am trying to create table in jrxml. Number of columns in table may very , when I am trying to export report in PDF format ,data becomes unreadable due high number of column. Is there any way we can export report in larger page size like A3 or can add scrolling feature to A4 size. Note: Report need to be exported only in pdf not CSV or any other format.

Thanks , Any Help appreciated.


Answer:

Either you change your report page to A3 Landscape or you can set custom page size. You can find this option in Jasperstudio Properties so you can fit more column.

Question:

I am trying to build a sample web application which loads a pdf report generated through jasper reports (.jasper file). However the report does not open as a pdf with the message "This PDF document might not be displayed correctly". The code snippets are as below. There is no exception log coming in the server log. Any help would be great. Thanks.

Servlet Controller Class

@WebServlet("/generateReport")
public class JasperReportsExample extends HttpServlet{

    final String deviceJasper = "SampleReport.jasper";
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
    response.setContentType("application/pdf");
    response.setCharacterEncoding("UTF-8");
    try{
    List<SampleReportBean> sampleReportBeanList = new ArrayList<SampleReportBean>();
    SampleReportBean bean = new SampleReportBean();
    bean.setName("Hello");
    sampleReportBeanList.add(bean);
    InputStream is = this.getClass().getClassLoader().getResourceAsStream(deviceJasper);
    JasperReport jasperReport = (JasperReport) JRLoader.loadObject(is);
    JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(sampleReportBeanList);
    Map<String, Object> parameters = new HashMap<String, Object>();
    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, beanCollectionDataSource);
    JasperExportManager.exportReportToPdfFile(jasperPrint, deviceJasper);
    }catch(Exception e) {
        System.out.println("Error:while creating jasper report....");
        e.printStackTrace();
    }
    }

}

html page

<form action="/samplejasperreport/generateReport" method="get">
<div>
<input type="submit" name="Generate Report" value="Generate Report">
</div>
</form>

SampleReport.jrxml

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.6.0.final using JasperReports Library version 6.6.0  -->
<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="SampleReport" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="038b20ef-43f5-4f05-8318-627e403a7110">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="JavaBean Adapter"/>
    <queryString>
        <![CDATA[]]>
    </queryString>
    <field name="name" class="java.lang.String">
        <fieldDescription><![CDATA[name]]></fieldDescription>
    </field>
    <background>
        <band splitType="Stretch"/>
    </background>
    <title>
        <band splitType="Stretch"/>
    </title>
    <pageHeader>
        <band splitType="Stretch"/>
    </pageHeader>
    <columnHeader>
        <band splitType="Stretch"/>
    </columnHeader>
    <detail>
        <band height="31" splitType="Stretch">
            <textField>
                <reportElement x="150" y="0" width="140" height="30" isPrintWhenDetailOverflows="true" uuid="f6eec303-affe-4804-bb6a-e5c07516a46f"/>
                <textElement textAlignment="Center">
                    <font size="22"/>
                </textElement>
                <textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
    <columnFooter>
        <band splitType="Stretch"/>
    </columnFooter>
    <pageFooter>
        <band height="1" splitType="Stretch"/>
    </pageFooter>
    <summary>
        <band splitType="Stretch"/>
    </summary>
</jasperReport>

Directory structure image

Error screen:


Answer:

Thanks to AlexK:

JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());//send the pdfstream to the browser

Question:

I have a Restful API (JAX-RS) and I need return a PDF file using the JasperReport library.

But when I run the URL in browser the Jasper generation method gives null in FacesContext.getCurrentInstance().getExternalContext() line. Can I catch the external context by HttpServletRequest?

Can anybody help me?

Bellow my "RestClass"

@Path("/Integracao")
public class Integracao {

@GET
@Path("/teste")
public void teste(){
    TrCboServiceImpl cS = new TrCboServiceImpl();
    List datasource = null;
    try {
        datasource = cS.listAll();
    } catch (ServiceException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    AbstractApplicationBean aab = new AbstractApplicationBean() {       
        @Override
        public boolean useMultiempresaService() {               
            return false;
        }
    }; 


    try {
        aab.gerarJasper("RelTrCbo", TipoRelatorioEnum.PDF.getType(), datasource, new HashMap<>());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

and my generator jasper

public void gerarJasper(String name, String type, List data, Map params) throws IllegalArgumentException, RuntimeException, Exception {

    boolean found = false;
    for (int i = 0; i < VALID_TYPES.length; i++) {
        if (VALID_TYPES[i].equals(type)) {
            found = true;
            break;
        }
    }
    if (!found) {
        throw new IllegalArgumentException("Tipo solicitado '" + type + "' inválido");
    }

    // Procurar recurso de design de relatório compilado
    // NullPointerException OCCURS HERE!!!
    ExternalContext econtext = FacesContext.getCurrentInstance().getExternalContext();

    InputStream stream = econtext.getResourceAsStream(PREFIX + name + SUFFIX);
    if (stream == null) {
        throw new IllegalArgumentException("O relatório '" + name + "' não existe");
    }

    FacesContext fc = FacesContext.getCurrentInstance(); 
    ServletContext context = (ServletContext)fc.getExternalContext().getContext();
    String path = context.getRealPath(File.separator) + "resources/jasper" + File.separator;
    String logo = context.getRealPath(File.separator) + "resources/imagens" + File.separator;
    params.put("SUBREPORT_DIR", path);
    params.put("LOGO_DIR", logo);                

    JRDataSource ds = new JRBeanArrayDataSource(data.toArray());
    JasperPrint jasperPrint = null;
    try {
        jasperPrint = JasperFillManager.fillReport(stream, params, ds);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new FacesException(e);
    } finally {
        try {
            stream.close();
        } catch (IOException e) {
        }
    }

    JRExporter exporter = null;
    HttpServletResponse response = (HttpServletResponse) econtext.getResponse();
    FacesContext fcontext = FacesContext.getCurrentInstance();
    try {
        response.setContentType(type);
        if ("application/pdf".equals(type)) {
            exporter = new JRPdfExporter();
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
        } else if ("text/html".equals(type)) {
            exporter = new JRHtmlExporter();
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, response.getWriter());

            HttpServletRequest request = (HttpServletRequest) fcontext.getExternalContext().getRequest();
            request.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint);
            exporter.setParameter(JRHtmlExporterParameter.IMAGES_MAP, new HashMap());

            exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, request.getContextPath() + "/image?image=");
        }else if("application/xlsx".equals(type)){
            exporter = new JRXlsxExporter();
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
        }else if("application/docx".equals(type)){
            exporter = new JRDocxExporter();
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
        } else if("application/rtf".equals(type)){
            exporter = new JRRtfExporter();
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
        }
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new FacesException(e);
    }

    try {
        exporter.exportReport();
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new FacesException(e);
    }
    fcontext.responseComplete();
}

Answer:

I solved the problem!!! I need import iReport, barbecue-1.5, barcode4j-2.0, jasperserver-ireport-plugin-2.0.1, jdt-compiler-3.1.1 jars in lib folder on my project (Restful API)

below my code

@Path("/Integracao")
public class Integracao {

@Context
private HttpServletRequest httpServletRequest;

@GET
@Path("/gerarPdf")
public Response geraPDF(@QueryParam("relatorio") String arquivoJrxml,
                        @QueryParam("autorizacao") String autorizacao){

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    Map fillParams = new HashMap(); 
    fillParams.put("IMPRAUTORIZACAO", autorizacao);
    PdfGenerator pdf = new PdfGenerator();
    byte[] bytes= pdf.generateJasperReportPDF(httpServletRequest, arquivoJrxml, outputStream, fillParams);

    String nomeRelatorio= arquivoJrxml + ".pdf";
    return Response.ok(bytes).type("application/pdf").header("Content-Disposition", "filename=\"" + nomeRelatorio + "\"").build();
}

}

and my util class

public class PdfGenerator {

public byte[]  generateJasperReportPDF(HttpServletRequest httpServletRequest, String jasperReportName, ByteArrayOutputStream outputStream, Map parametros) {
    JRPdfExporter exporter = new JRPdfExporter();
    try {
        String reportLocation = httpServletRequest.getRealPath("/") +"resources\\jasper\\" + jasperReportName + ".jrxml";

        InputStream jrxmlInput = new FileInputStream(new File(reportLocation)); 
        //this.getClass().getClassLoader().getResource("data.jrxml").openStream();
        JasperDesign design = JRXmlLoader.load(jrxmlInput);
        JasperReport jasperReport = JasperCompileManager.compileReport(design);
        //System.out.println("Report compiled");

        //JasperReport jasperReport = JasperCompileManager.compileReport(reportLocation);
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parametros, HibernateUtils.currentSession().connection()); // datasource Service

        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);   
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream);
        exporter.exportReport();
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Error in generate Report..."+e);
    } finally {
    }
    return outputStream.toByteArray();
}
}

Question:

I'm using JasperReports to generate a PDF and HttpServlet to send binary data to the browser. The issue is that the generated PDF downloaded from the client side, ends up being a corrupted pdf, hence the PDF viewer displays a blank PDF.

At first, I thought it could be a JasperReports issue but I saved the PDF to a file and it worked like a charm.

JasperExportManager.exportReportToPdfFile(jasperPrint, "/home/user/Desktop/Example.pdf");
// jasperPrint is the rendered JasperReport

So it might be a problem related to HttpServlet. The way I send data is as follows:

    HttpServletResponse response;
    byte[] out = JasperExportManager.exportReportToPdf(jasperPrint); 
    // jasperPrint is the rendered JasperReport

    response.reset();

    response.setHeader("Content-disposition", "attachment;filename=\"Example.pdf\"");
    response.setContentType("application/pdf");
    response.setHeader("Cache-Control", "max-age=0");
    response.setContentLength(out.length);
    response.setHeader("Content-Length", String.valueOf(out.length));
    response.getOutputStream().write(out, 0, out.length);
    response.getOutputStream().flush();
    response.getOutputStream().close();
    // Right after that, the browser asks me to download the file
    // and this is the moment when I got a blank PDF

On top of that, I've checked this answer before I asked this question Blank PDF while downloading

One more thing: downloading a PDF works perfectly fine ( no blank PDF) on QA environment , running a JBoss Server on a Windows Machine. On my local environment I get a blank PDF as I mentioned before, running a JBoss Server on a Linux Machine.

So I was wondering : How can I check my Jboss settings to fix the problem? According to the previous question, it could be a matter of binary data that the server might be ignoring or compressing, I'm not quite sure.

Should I check out as well my web.xml file?

Thanks for any help!


Answer:

I've finally found the solution! My code had nothing to do with this, it was a Grunt issue all along. For some reason, Grunt was converting the PDF sent to the browser to a wrong encoding. I had to change

"grunt-contrib-connect": "^0.8.0" to "grunt-contrib-connect": "~0.5.0".

Then I ran

npm install

That solved my problem. The solution was found here

https://github.com/drewzboto/grunt-connect-proxy/issues/73#issuecomment-59532082

I can't explain why the newest version of grunt-contrib-connect was encoding the PDF file on a wrong way. Now I'd like to know the reason why this works.

Question:


Answer:

I solve it change the JREmptyDataSource as Alex K mentioned, changed this:

print = JasperFillManager.fillReport(reporteJasper, datosReporte, new JREmptyDataSource());

for this

print = JasperFillManager.fillReport(reporteJasper, datosReporte, new JRMapArrayDataSource(new Object[] { datosReporte }));

Question:

Is it possible to stream the result directly to a pdf file instead of creating the JasperPrint object first? My JasperPrint object can get really big and java.lang.OutOfMemoryError occurs...

JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, reportparameter.getAll(), dataSource);
// dead end
OutputStream output = new FileOutputStream(new File("C:/Users/bla/Desktop/test/JasperReport.pdf"));
JasperExportManager.exportReportToPdfStream(jasperPrint, output);

Answer:

Well I kind of found a solution... First you write the JasperPrint object to disk and then you can stream the content and create PDF via streams. No memory problems anymore but you need to save the result first on the disk.

    OutputStream printOut = new FileOutputStream(new File("C:/Users/bla/Desktop/test/jasperprint.jasperprint"));
    JasperFillManager.fillReportToStream(jasperReport, printOut, reportparameter.getAll(), dataSource);
    printOut.close();

    OutputStream output = new FileOutputStream(new File("C:/Users/bla/test/JasperReport.pdf"));
    JasperExportManager.exportReportToPdfStream(new FileInputStream(new File("C:/Users/bla/Desktop/test/jasperprint.jasperprint")), output);
    output.close();

Question:

I am creating api for downloading my report in pdf format. For that I am using java (spark framework) and jasper reporting tool everything is working fine.

Problem is that when I am hitting my api from postman the default name for the PDF is "response.pdf.pdf" and I want it to be "report.pdf"

here is my method.

private Route getReport = (req,res)->{
        try{
            res.raw().setHeader("Content-Disposition", "attachment; filename= \"report.pdf\"");
            res.raw().setContentType("application/pdf");
            JRDataSource dataSource = new JREmptyDataSource();
            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("cin", "556293-9982");
            dataMap.put("financialYear","2009-05-01 - 2010-04-30");
            JasperPrint jasperPrint = JasperFillManager.fillReport("reports/front-page.jasper", dataMap,dataSource);
            JasperExportManager.exportReportToPdfStream(jasperPrint,res.raw().getOutputStream());
        }catch(Exception ex){
            res.type(ApplicationConstants.JSON_APPLICATION_CONTENT_TYPE);
            throw new BusinessExceptions(ex, ApiErrorEnumerations.ERR_DOWNLOADING_REPORT);
        }finally{
            res.raw().flushBuffer();
            res.raw().getOutputStream().close();
        }
        return res.raw();
    };

Please suggest where I am going wrong.


Answer:

  • For jasper report API

If you are using JasperReports API you should set report name with help of JasperPrint.setName(java.lang.String name) method.

  • For iReport (editing report template) set report name in report template with help of name attribute: jasperReport .. name="Sample report name to print"

Question:

JasperReports library seems to be miscalculating how many new lines the text field need to fit all its contents. In JasperReports Studio (in preview) everything looks fine, but not when exporting to PDF from my application.

I've read PDF FAQ from JasperReports and I tried setting PROPERTY_FORCE_LINEBREAK_POLICY in the report to true, but this didn't make any difference. I also experimented with various fonts, but then in runtime Java complained about missing font in AWT, so I guess my default font (SansSerif) is just fine.

When I print "english only" version of the report, then everything looks okay, because all texts are about a half in length, but when using longer texts (like in example below) then this line miscalculation happens.

Here is how it looks right now and I marked unwanted extra lines with red:

Since I've tried with both hints from JasperReport's PDF FAQ, what else can I do?


Answer:

I found the solution:

  1. Switch all fonts to Dejavu (I used to use default fonts)
  2. Have a jasperreports-fonts extension included in the project.

The new font is a tiny bit wider, but that's okay. Other than that it looks very alike.

Question:

I need to send a pdf jasper directly to the printer, the current code PDF is delegated to the browser and therefore the user can print as many copies as desired. Must allow only print one copy, so I thought I'd send directly to printing. I searched the forum but did not understand what would be the best solution to the issue.

Take a look at my code:

public class UtilRelatorios {

public static void imprimeRelatorio(String relatorioNome,
        HashMap parametros) throws IOException, JRException {
        FacesContext fc = FacesContext.getCurrentInstance();
        ServletContext context = (ServletContext) fc.getExternalContext().getContext();
        HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        JasperPrint jasperPrint = 
                JasperFillManager.fillReport(
                        context.getRealPath("/relatorios")+ File.separator+relatorioNome+".jasper",
                        parametros);    
        //int finalPag = jasperPrint.getPages().size();
        //System.out.println("page: "+finalPag);
        //JasperPrintManager.printPage(jasperPrint,finalPag,false);
        byte[] b = null;
        //JasperPrintManager.printPage(jasperPrint, 0, false);

        try {
            b = JasperExportManager.exportReportToPdf(jasperPrint);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }    

            if (b != null && b.length > 0) {
                // Envia o relatório em formato PDF para o browser
                response.setContentType("application/pdf");
                int codigo = (int) (Math.random()*1000);
                response.setHeader("Content-disposition","inline);filename=relatorio_"+codigo+".pdf");
                response.setContentLength(b.length);
                ServletOutputStream ouputStream = response.getOutputStream();
                ouputStream.write(b, 0, b.length);
                ouputStream.flush();
                ouputStream.close();
            }   
 }

}


Answer:

If as seems in question you like to send the report directly to user's printer via web application, browser.

This can not be done!, you can not control the web users printer directly from the browser (excluding the use of activeX or other home made plugins)

Probably this is luck since otherwise while navigating on internet you would have people printing alot of advertising on your printer....

If instead you like to send it to a printer attached to server, this can be done!

If its the server printer please let me know and I can pass you some code.

Question:

I have been exporting jasper report to pdf but it opens in the same window which is a problem to me because if i want to go to previous page i cant be able to go to previous page so i thought of opening pdf page in a new window but i dont have any idea of how to open it in a new window.

sample1.jsp

<%@ page  import="java.io.*"%> 
<%@ page  import="java.sql.Connection"%> 
<%@ page  import="java.sql.DriverManager"%>
<%@ page  import="java.util.HashMap"%>
<%@ page  import="java.util.Map"%>
<%@ page  import="net.sf.jasperreports.engine.*"%>
<%@ page import="net.sf.jasperreports.engine.*" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.text.ParseException" %>
<%@ page import="java.io.File" %>
<%@ page import="java.io.FileInputStream" %>
<%@ page import="java.io.FileNotFoundException" %>
<%@ page import="java.io.InputStream" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.io.FileOutputStream" %>
<%@ page import="java.io.ByteArrayOutputStream" %>
<%@ page import="java.io.OutputStream" %>
<%@ page import="java.util.HashMap" %>
<%@ page import="java.util.Map" %>
<%@ page import="net.sf.jasperreports.engine.util.*" %> 
<%@ page import="net.sf.jasperreports.engine.export.*" %>
<%@page import = "net.sf.jasperreports.engine.design.JRDesignQuery"%>
<%@page import = "net.sf.jasperreports.engine.xml.JRXmlLoader"%>
<%@page import = "net.sf.jasperreports.engine.design.JasperDesign"%>
<%@page import = "net.sf.jasperreports.view.JasperViewer"%>
<%@page import = "net.sf.jasperreports.engine.JRException"%>
<%@page import = "net.sf.jasperreports.engine.JRResultSetDataSource"%>
<%@page import = "net.sf.jasperreports.engine.JasperCompileManager"%>
<%@page import = "net.sf.jasperreports.engine.JasperExportManager"%>
<%@page import = "net.sf.jasperreports.engine.JasperFillManager"%>
<%@page import = "net.sf.jasperreports.engine.JasperPrint"%>
<%@page import = "net.sf.jasperreports.engine.JasperReport"%>
<%@page import = "net.sf.jasperreports.engine.data.JRCsvDataSource"%>
<%@page import = "net.sf.jasperreports.engine.export.ooxml.JRDocxExporter"%>
<%@page import = "net.sf.jasperreports.engine.export.JRPdfExporter"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
Connection conn = null;
String cate=(String)session.getAttribute("cat");
String stat=(String)session.getAttribute("sta");
String dayy=(String)session.getAttribute("da");
String monthh=(String)session.getAttribute("mon");
String yearr=(String)session.getAttribute("yea");
String dayy1=(String)session.getAttribute("da1");
String monthh1=(String)session.getAttribute("mon1");
String yearr1=(String)session.getAttribute("yea1");
System.out.println("2 is:"+cate);
System.out.println("4 is:"+stat);
System.out.println("5 is:"+dayy);
System.out.println("6 is:"+monthh);
System.out.println("7 is:"+yearr);
System.out.println("8 is:"+dayy1);
System.out.println("9 is:"+monthh1);
System.out.println("10 is:"+yearr1);
try 
{
    Class.forName("com.mysql.jdbc.Driver");
    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/marketing_database","root","root");
    String sql="select * from lead where Status='" + stat.replaceAll("\\'","''") + "'";
           sql+=" AND Category='" + cate.replaceAll("\\'","''") + "'";
           sql+=" AND DATE(Lead_Date)>='" + yearr + "-" + monthh + "-" + dayy + "'"; 
           sql+=" AND DATE(Lead_Date)<='" + yearr1 + "-" + monthh1 + "-" + dayy1 + "'";
    String jrxmlFile ="D:/dev/tools/jasper files/report3.jrxml";
    InputStream input = new FileInputStream(new File(jrxmlFile));
    JasperDesign jasperDesign = JRXmlLoader.load(input);

    System.out.println("Compiling Report Designs");
    JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

    System.out.println("Creating JasperPrint Object");
    HashMap<String,Object> map = new HashMap<String,Object>();
    map.put("sql",sql);
            byte[] bytes = JasperRunManager.runReportToPdf(jasperReport, map, conn);

            response.setContentType("application/pdf");
            response.setContentLength(bytes.length);
            ServletOutputStream outStream = response.getOutputStream();
            outStream.write(bytes, 0, bytes.length);
            outStream.flush();
            outStream.close();
}
catch(Exception e) 
{e.printStackTrace();} 

        %>
</body>
</html>

view.jsp

 <script type="text/javascript">

    function setAction(nPage){

        document.forms[0].action = nPage;
    }
</script>
</head>
<body>
<form>
<%
String category=request.getParameter("category");
session.setAttribute("cat",category);
String status=request.getParameter("status");
session.setAttribute("sta",status);
System.out.println("status is:"+status);
String day=request.getParameter("day");
session.setAttribute("da",day);
String month=request.getParameter("month");
session.setAttribute("mon",month);
String year=request.getParameter("year");
session.setAttribute("yea",year);
String day1=request.getParameter("day1");
session.setAttribute("da1",day1);
String month1=request.getParameter("month1");
session.setAttribute("mon1",month1);
String year1=request.getParameter("year1");
session.setAttribute("yea1",year1);
%>
<select onchange="setAction(this.value)">
<option value=''> Make a selection </option>
<option value='sample1.jsp'> PDF</option>
<option value='XLS_LEAD.jsp'> XLS </option>
<option value='DOC_LEAD.jsp'> DOC </option>
<option value='XLSX_LEAD.jsp'> XLSX </option>
</select>
<br/>

<input type="submit" value="Submit">
</form>
</body>

Answer:

Considering your view.jsp

I can see that you already have put all variables into the session you are only using the form to select to which page you need to go.

You can do something like this...

<script type="text/javascript">
 function generateReport() {
  var e = document.getElementById("idOfYourSelectYouNeedToAddedIt");
  var strPage = e.options[e.selectedIndex].value;
  window.open(strPage);
  return false; //This make you stay on this page;
  //return true; //Set the action tag in the form to the page you like to go to!
 }
</script>


 <form name="myForm"  onsubmit="return generateReport()">
      <select id = "idOfYourSelectYouNeedToAddedIt">
      <option value=''> Make a selection </option>
      ..... the other option values
 </form>

Note if you like to go to another page you can simple add action tag to your form tag and return true in the generateReport() function

example

 <form name="myForm" action="thisIsWhereILikeToGo.jsp"  onsubmit="return generateReport()">

Note: You should remove the onchange="setAction(this.value) code, it has no use anymore and consider checking that strPage is not empty, no selection...

Question:

I'm developing a reports feature which exports data to XLS, DOC and PDF using Jasper and Java.

For some reason I cant export to PDF while using Hebrew, I keep getting this error :

net.sf.jasperreports.engine.JRRuntimeException: Could not load the following font : 
pdfFontName   : Times-Roman
pdfEncoding   : Identity-H
isPdfEmbedded : false

I've tried to embed the font in the report using Jasper Studio and added the Jasper Fonts jar and configured the font there as well.

Any ideas how to solve this one?

Thanks in advance ! :)


Answer:

I have never worked with Hebrew but whenever I am having trouble with Cyrillic fonts I switch to Arial and it usually does the trick.

Question:

So ultimately I need to write a large number of PDFs (40,000) on disk on a UNIX server and I'm trying to figure out a way to do this efficiently(faster/consuming less memory).

I have been using JasperReports to create a template which recieves as Parameters(meaning the report doesn't hit the database) all the information needed on the report.

Then I have a simple Java app that queries the DB and brings the dataset and for each record it fills the .jasper and writes the PDF to disk.

Now this works fine for a couple hundred of records but I'm thinking that it won't work for production where the number scales to 40.000 records and the output of the process will be an equal number of PDF files. Doing some testing I'm estimating that the process will take at least 3 hours and I'm also beginning to worry about memory consumption.

So what I would like to know is if there is an efficient way to do this:

  • Should I be using parallelism/multiple threads for this process?
  • Can anyone point me towards a knonw pattern/example for this kind of job?

Thank you for your time


Answer:

Unfortunately you cannot use less memory and use multithreading to render different PDFs, each thread would allocate memory to work on its PDF, memory usage would be linear to the number of threads. It's a completely different story if you can work on the same PDF(same data) with multiple threads, but i don't think it would easy to do since thread would require frequent synchronization making multithreading meaningless.

It will be trivial to implement multithreading if they don't need to share any information, you can just implement Runnable interface, create new thread passing the implementation of Runnable, and wait them to end with Thread.join().

If i were you i would use jasper virtualizer to load only a part of the dataset at the time, this would probably allow you to use multiple threads.

Question:

I am trying to export the report to PDF format, but it generates a blank PDF.

I am filling the report from JRDatasource method. The .show() method shows the filled report with all columns formatted and filled, but when I export it in PDF format with .toPdf() method it generates a blank report.

Here is the code for the whole process:

1) Generate columns for report

InvoiceData data = new InvoiceData();
        AggregationSubtotalBuilder<BigDecimal> totalSum;

        StyleBuilder boldStyle         = stl.style().bold();
        StyleBuilder boldCenteredStyle = stl.style(boldStyle)
                                                    .setHorizontalAlignment(HorizontalAlignment.CENTER);
        StyleBuilder titleStyle         = stl.style(boldStyle).setFontSize(15);
        StyleBuilder CenteredStyle = stl.style().setHorizontalAlignment(HorizontalAlignment.CENTER);
        StyleBuilder columnTitleStyle  = stl.style(boldCenteredStyle)       
                                                    .setBorder(stl.pen1Point()).setBackgroundColor(Color.LIGHT_GRAY);
        TextColumnBuilder<Integer> rowNumberColumn = col.reportRowNumberColumn("No.").setFixedColumns(2).setStyle(CenteredStyle);
        TextColumnBuilder<String>    columnItem = col.column("Item Name", "itemname", type.stringType()).setFixedColumns(10).setStyle(CenteredStyle);
        TextColumnBuilder<String>    columnpkg = col.column("Pkg Date", "pkgdate", type.stringType()).setFixedColumns(7).setStyle(CenteredStyle);
        TextColumnBuilder<String>    columnmanf = col.column("Manft Date", "manftdate", type.stringType()).setFixedColumns(7).setStyle(CenteredStyle);
        TextColumnBuilder<String>    columnexp = col.column("Exp Date", "expdate", type.stringType()).setFixedColumns(7).setStyle(CenteredStyle);
        TextColumnBuilder<String>    columnbatch = col.column("Batch No", "batch", type.stringType()).setFixedColumns(5).setStyle(CenteredStyle);
        TextColumnBuilder<Double>    columnunit = col.column("Unit Price", "unit", type.doubleType()).setFixedColumns(5).setStyle(CenteredStyle);
        TextColumnBuilder<Integer>    columnqty = col.column("Qty", "qty", type.integerType()).setFixedColumns(2).setStyle(CenteredStyle);
        TextColumnBuilder<BigDecimal>    columnsub = columnqty.multiply(columnunit).setTitle("Subtotal").setFixedColumns(5).setStyle(CenteredStyle);
        totalSum = sbt.sum(columnsub)
                         .setLabel("Total:")
                         .setLabelStyle(Templates.boldStyle);

2) Build report for view

        try {
            DateFormat dateformat = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
            java.util.Date date = new java.util.Date();
            JasperReportBuilder report = DynamicReports.report();

            report.setColumnTitleStyle(columnTitleStyle)
            .highlightDetailEvenRows()
            .title(cmp.text("MEDICAL STORE").setStyle(titleStyle).setHorizontalAlignment(HorizontalAlignment.LEFT),
                   cmp.text("Invoice No:").setStyle(titleStyle).setHorizontalAlignment(HorizontalAlignment.RIGHT),
                   cmp.text("Address of the shop").setHorizontalAlignment(HorizontalAlignment.JUSTIFIED),
                    Components.horizontalList().setStyle(stl.style(10)).setGap(50).add(Components.hListCell(createCustomerComponent("Bill To",data.getInvoice().getBillTo(),person,contact)).heightFixedOnTop(),
                             cmp.hListCell(createDoctorComponent("Prescribed By", data.getInvoice().getShipTo(),doctorregno,doctor)).heightFixedOnTop()),
                                         cmp.verticalGap(10))
                  .columns(rowNumberColumn,
                          columnItem,
                          columnpkg,
                          columnmanf,
                          columnexp,
                          columnbatch,
                          columnunit,
                          columnqty,
                          columnsub)
                  .setDataSource(populatereport(prod,pkgdate,manufact,exp,batch,unit,qty))
                  .subtotalsAtSummary(totalSum)
                  .pageFooter(Templates.footerComponent)
                  .summary(Components.horizontalList(
                          Components.verticalGap(100),                    
                          Components.text("Thank you for your business").setStyle(Templates.bold12CenteredStyle)
                          ))
                          .pageFooter(cmp.text("Address for Medical Store here"))
                    .show();

3) Export the report to pdf

                 report.toPdf(new FileOutputStream("/home/kunal/Medicam reports/Customer Bill/"+String.valueOf(dateformat.format(date))+".pdf"));
                 //Here is some problem when exporting to pdf

            } catch(DRException e) {
            e.printStackTrace();
            log.error("Exception in Report");
        }

Filling the Report

private JRDataSource populatereport(String[] prod, String[] pkgdate,
            String[] manufact, String[] exp, String[] batch, String[] unit,
            String[] qty) {
        DRDataSource dataSource = new DRDataSource("itemname", "pkgdate", "manftdate", "expdate", "batch", "unit", "qty");
        for (int i = 0; i < prod.length; i++) {

            dataSource.add(prod[i], pkgdate[i], manufact[i], exp[i], batch[i], Double.parseDouble(unit[i]), Integer.parseInt(qty[i]));
        }
        return dataSource;
    }

Answer:

Answering my own question

A jar file and an import was missing

So added the jar

com.lowagie.text-2.1.7.jar

and imported the class

import com.lowagie.text.DocumentException;

and now everything works fine!!!!

Question:

When the of a row of my reports gets too long for a single page, it gets continued on the next page, however, the border gets cut off as seen in this image.

Any ideas?

I'm using JRPdfExporter for exporting reports to PDF.

UPDATED:

        DynamicReport dynamicReport;
        ...
        fastReportBuilder.setPageSizeAndOrientation(Page.Page_A4_Landscape());
        fastReportBuilder.setUseFullPageWidth(true);

        //margin 50
        fastReportBuilder.setMargins(MARGIN, MARGIN, MARGIN, MARGIN);

        fastReportBuilder.setDefaultStyles(getTitleStyle(), null, getColumnHeaderStyle(), getColumnDetailsStyle());

   private Style getColumnHeaderStyle() {
        Style hStyle = new Style();
        hStyle.setBorder(Border.THIN());
        hStyle.setTransparent(false);
        hStyle.setBackgroundColor(new Color(0, 142, 175));
        hStyle.setTextColor(Color.WHITE);
        hStyle.setHorizontalAlign(HorizontalAlign.CENTER);
        hStyle.setVerticalAlign(VerticalAlign.MIDDLE);
        hStyle.setFont(new Font(10, MY_FONT, false));
        return hStyle;
    }

    private Style getColumnDetailsStyle() {
        Style cStyle = new Style();
        cStyle.setBorder(Border.THIN());
        cStyle.setFont(new Font(10, MY_FONT, false));
        cStyle.setVerticalAlign(VerticalAlign.TOP);
        return cStyle;
    }

Answer:

Border Artifacts in JasperReport PDF Designed with iReport 5.1.0 gave me an idea.

I ended up extending the JRPdfExporter. For some reason, when the data gets cut and continued on the next page, the cell box border's height and bottom where the data gets cut off are mismatched on its neighbor cell on the left. To fix this, I'm storing the previous cell borders data, so when it reached the mismatched cell border data, it can be corrected.

import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfContentByte;
import net.sf.jasperreports.engine.JRLineBox;
import net.sf.jasperreports.engine.JRPrintElement;
import net.sf.jasperreports.engine.export.JRPdfExporter;

import java.awt.*;

public class CustomPdfExporter extends JRPdfExporter {

    private float previousTop;
    private float previousHeight;
    private float prevY1;
    private float prevY2;

    private static final float FLOAT_ZERO = 0F;

    protected void exportBox(JRLineBox box, JRPrintElement element) {

        if (!isBoxVisible(box)) return;

        pdfContentByte.setLineCap(PdfContentByte.LINE_CAP_PROJECTING_SQUARE);

        float x1 = element.getX() + getOffsetX();
        float y1 = jasperPrint.getPageHeight() - element.getY() - getOffsetY();
        float x2 = element.getX() + getOffsetX() + element.getWidth();
        float y2 = jasperPrint.getPageHeight() - element.getY() - getOffsetY() - element.getHeight();

        Rectangle r = new Rectangle(x1, y2, x2, y1);

        if (previousTop == r.getTop() && previousHeight != r.getHeight()) {
            r.setBottom(prevY2);
        } else {
            prevY2 = y2;
            prevY1 = y1;
            previousHeight = r.getHeight();
            previousTop = r.getTop();
        }

        int borderFlag = 0;

        float lineWidth = 0;
        Color lineColor = null;

        if (box.getLeftPen().getLineWidth().floatValue() > FLOAT_ZERO) {
            borderFlag |= Rectangle.LEFT;
            lineWidth = box.getLeftPen().getLineWidth().floatValue();
            lineColor = box.getLeftPen().getLineColor();
        }

        if (box.getTopPen().getLineWidth().floatValue() > FLOAT_ZERO) {
            borderFlag |= Rectangle.TOP;
            if (lineWidth == 0) {
                lineWidth = box.getTopPen().getLineWidth().floatValue();
                lineColor = box.getTopPen().getLineColor();
            }
        }

        if (box.getRightPen().getLineWidth().floatValue() > FLOAT_ZERO) {
            borderFlag |= Rectangle.RIGHT;
            if (lineWidth == 0) {
                lineWidth = box.getRightPen().getLineWidth().floatValue();
                lineColor = box.getRightPen().getLineColor();
            }
        }

        if (box.getBottomPen().getLineWidth().floatValue() > FLOAT_ZERO) {
            borderFlag |= Rectangle.BOTTOM;
            if (lineWidth == 0) {
                lineWidth = box.getBottomPen().getLineWidth().floatValue();
                lineColor = box.getBottomPen().getLineColor();
            }
        }
        r.setBorder(borderFlag);
        r.setBorderColor(lineColor);
        r.setBorderWidth(lineWidth);

        pdfContentByte.rectangle(r);
        pdfContentByte.stroke();

        pdfContentByte.setLineDash(FLOAT_ZERO);
        pdfContentByte.setLineCap(PdfContentByte.LINE_CAP_ROUND);
    }

    private boolean isBoxVisible(JRLineBox box) {
        return box.getLeftPen().getLineWidth().floatValue() > FLOAT_ZERO
                || box.getTopPen().getLineWidth().floatValue() > FLOAT_ZERO
                || box.getRightPen().getLineWidth().floatValue() > FLOAT_ZERO
                || box.getBottomPen().getLineWidth().floatValue() > FLOAT_ZERO
                ;
    }
}

Question:

When I download a pdf file generated with JasperReports, its name is document.pdf. I tried to set name with JasperPrint.setName(); but it doesn't work.

How can I change solve the task?

public class JaspereQueCaMarche {
    public static enum Export {
        PDF, HTML
    };

    private String cheminSource;
    private JasperReport jasperReport;
    private String nomRapport;

    private List<ParametreJasper> parametres = new ArrayList<ParametreJasper>();

    private static List<JaspereQueCaMarche> rapports = new ArrayList<JaspereQueCaMarche>();

    protected JaspereQueCaMarche() {
    }

    public String getCheminSource() {
        return cheminSource;
    }

    public String getNomRapport() {
        return nomRapport;
    }

    public List<ParametreJasper> getParametres() {
        return parametres;
    }

    public ParametreJasper getParametre(String nom) {
        for (ParametreJasper pa : this.parametres) {
            if (pa.getNom().equals(nom)) {
                return pa;
            }
        }
        return null;
    }

    public static List<JaspereQueCaMarche> getRapports() {
        return rapports;
    }

    public static void setRapports(List<JaspereQueCaMarche> rapports) {
        JaspereQueCaMarche.rapports = rapports;
    }

    public static JaspereQueCaMarche getFromHashCode(int hash) {
        for (JaspereQueCaMarche jp : JaspereQueCaMarche.getRapports()) {
            if (jp.hashCode() == hash) {
                return jp;
            }
        }
        return null;
    }

    public static void chargerListe(String repertoire) {
        for (final File fic : new File(repertoire).listFiles()) {
            if (!fic.isDirectory() && fic.getName().endsWith(".jrxml")) {
                long dateModifSource = fic.lastModified();

                String nomJasper = fic.getAbsolutePath();
                nomJasper = nomJasper.substring(0, nomJasper.length() - 5) + "jasper";

                File jasper = new File(nomJasper);
                long dateModifObjet = jasper.exists() ? jasper.lastModified() : 0;

                JaspereQueCaMarche jp = new JaspereQueCaMarche();
                jp.cheminSource = fic.getAbsolutePath();
                jp.nomRapport = fic.getName();

                JasperReport jr = (dateModifObjet < dateModifSource) ? jp.compilerRapport() : jp.chargerRapport(jasper);

                if (jr != null) {
                    jp.jasperReport = jr;

                    jp.extraireParametres();
                    JaspereQueCaMarche.rapports.add(jp);
                }
            }
        }
    }

    public static JaspereQueCaMarche getEtat(String nom) {
        String jrxml = nom + ".jrxml";

        for (JaspereQueCaMarche jqcm : JaspereQueCaMarche.rapports) {
            if (jqcm.nomRapport.equals(jrxml)) {
                return jqcm;
            }
        }
        return null;
    }

    private void extraireParametres() {
        org.jdom2.Document document = null;
        Element racine;

        SAXBuilder sxb = new SAXBuilder();
        try {
            document = sxb.build(new File(this.getCheminSource()));
        } catch (Exception e) {
            Log.getLogGeneral().msgtest("erreur xml", e);
        }

        racine = document.getRootElement();

        @SuppressWarnings("rawtypes")
        List listeParametres = racine.getChildren();
        @SuppressWarnings("rawtypes")
        Iterator it = listeParametres.iterator();

        while (it.hasNext()) {
            Element courant = (Element) it.next();
            if (courant.getName().equals("parameter")) {
                String nom = courant.getAttributeValue("name");
                String classe = courant.getAttributeValue("class");
                String valeurParDefaut = "";
                String description = "";

                List<?> details = courant.getChildren();
                Iterator<?> itDetails = details.iterator();
                while (itDetails.hasNext()) {
                    Element detail = (Element) itDetails.next();
                    if (detail.getName().equals("defaultValueExpression")) {
                        valeurParDefaut = detail.getText();
                    } else if detail.getName().equals("parameterDescription")) {
                        description = detail.getText();
                    }
                }
                ParametreJasper pj = new ParametreJasper(nom, description, classe, valeurParDefaut);
                this.parametres.add(pj);
            }
        }
    }

    public JasperPrint genererRapport(String transporteurConnecte) {
        return genererRapport(transporteurConnecte, new HashMap<String, Object>());
    }

    public JasperPrint genererRapport(String transporteurConnecte, HashMap<String, Object> parametres) {
        Connection conn = null;
        JasperPrint jasperPrint = null;

        try {
            conn = new ConnexionJDBC(transporteurConnecte).getInstance();
        } catch (SQLException | ClassNotFoundException e) {
            Log.getMapLog().get(transporteurConnecte).msgtest("impossible d'obtenir une connexion", e);
        }

        try {
            if (this.jasperReport != null) {
                jasperPrint = JasperFillManager.fillReport(jasperReport, parametres, conn);
            }
        } catch (JRException e) {
            Log.getMapLog().get(transporteurConnecte).msgtest("erreur fillReport", e);
        }

        return jasperPrint;
    }

    public void exporterRapport(JasperPrint jasperPrint, OutputStream outputStream, String transporteurConnecte) {
        exporterRapport(jasperPrint, Export.PDF, outputStream, transporteurConnecte);
    }

    public void exporterRapport(JasperPrint jasperPrint, Export format, OutputStream outputStream, String transporteurConnecte) {
        try {
            if (format == Export.PDF) {
                JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
            }
        } catch (JRException e) {
            Log.getMapLog().get(transporteurConnecte).msgtest(" erreur exportReportToPdfStream", e);
        }
    }

    public void sauvegarderRapport(JasperPrint jasperPrint, Export format, String emplacement, String transporteurConnecte) {
        try {
            if (format == Export.PDF) {
                JasperExportManager.exportReportToPdfFile(jasperPrint, "test.pdf");
            } else if (format == Export.HTML) {
                JasperExportManager.exportReportToHtmlFile(jasperPrint, emplacement);
            }
        } catch (JRException e) {
            Log.getMapLog().get(transporteurConnecte).msgtest("erreur exportReport", e);
        }
    }

    protected JasperReport compilerRapport() {
        JasperReport jr = null;
        try {
            String cheminRapportCompile = JasperCompileManager.compileReportToFile(this.cheminSource);
            jr = chargerRapport(new File(cheminRapportCompile));
        } catch (JRException e) {
            Log.getLogGeneral().msgprod("Impossible de compiler le rapport " + this.cheminSource, e);
        }
        return jr;
    }

    protected JasperReport chargerRapport(File fJasper) {
        JasperReport jr = null;
        try {
            jr = (JasperReport) JRLoader.loadObject(fJasper);
        } catch (JRException e) {
            Log.getLogGeneral().msgprod("Impossible de charger le rapport " + fJasper.getAbsolutePath(), e);
        }
        return jr;
    }
}

Answer:

You may use exportReportToPdfFile from JasperExportManager, (report being your JasperPrint object)

JasperExportManager.exportReportToPdfFile(report, fileName);

Question:

I am trying to implement jasper to pdf report in java. After setting parameter to jasper report, I'm getting null value to pdf.

Report's design:

Generated PDF file looks like:

My code is :

String outputFile = "D://Test.pdf";
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("name", "raju");
JRDataSource datasource = new JREmptyDataSource();
JasperReport jasperReport = JasperCompileManager.compileReport("report1.jrxml");
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, datasource);
JasperExportManager.exportReportToPdfFile(jasperPrint, "D://Test.pdf");

Answer:

Use $P{name} instead of $F{name} in that TextField expression.

$P{...} is used for parameters and $F{...} for fields (values provided by data source).