Java Code Examples for net.sf.jasperreports.engine.JasperCompileManager

The following are top voted examples for showing how to use net.sf.jasperreports.engine.JasperCompileManager. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: logistimo-web-service   File: JasperClient.java   View source code 9 votes vote down vote up
public PDFResponseModel generatePDF(String fileName, String template, String bucketName,
    Collection<?> items, Map<String, Object> parameters)
    throws ClassNotFoundException, JRException, IOException {

  JasperPrint jasperPrint;
  InputStream inputStream = null;

  JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(items);

  try {
    inputStream = storageUtil.getInputStream(bucketName, template);
    jasperPrint = JasperFillManager.fillReport(JasperCompileManager.compileReport(
        inputStream), parameters, beanColDataSource);
    byte[] pdfBytes = JasperExportManager.exportReportToPdf(jasperPrint);
    return new PDFResponseModel(fileName, pdfBytes);
  } catch (ClassNotFoundException | JRException | IOException e) {
    xLogger.severe("Failed to generate PDF for file name - ", fileName, e);
    throw e;
  } finally {
    if (inputStream != null) {
      inputStream.close();
    }
  }
}
 
Example 2
Project: pitanga-system   File: PgRelatorioDAO.java   View source code 8 votes vote down vote up
@Override
public JasperViewer gerarRelatorioClientesSintetico() {

    Connection connection = PostgreSQLDAOFactory.getConnection();

    try {
        Statement stm = connection.createStatement();
        String query = "SELECT\n"
                + "     cl.\"cod_cliente\" AS codigo,\n"
                + "     cl.\"nome_cliente\" AS nome,\n"
                + "     ci.\"nome_cidade\" AS nome_cidade,\n"
                + "     ci.\"sigla_uf\" AS sigla,\n"
                + "     cl.\"telefone\" AS telefone\n"
                + "FROM\n"
                + "     \"cliente\" cl INNER JOIN \"cidade\" ci "
                + "ON cl.\"cod_cidade\" = ci.\"cod_cidade\"\n"
                + "ORDER BY\n"
                + "     cl.nome_cliente ASC";

        ResultSet rs = stm.executeQuery(query);

        JRResultSetDataSource jrRS = new JRResultSetDataSource(rs);

        InputStream fonte
                = PgRelatorioDAO.class.getResourceAsStream(
                        "/br/com/pitanga/report/RelatorioClientesSintetico.jrxml");

        JasperReport report = JasperCompileManager.compileReport(fonte);

        JasperPrint print = JasperFillManager.fillReport(report, null, jrRS);
        JasperViewer jv = new JasperViewer(print, false);

        return jv;

    } catch (JRException | SQLException ex) {
        throw new DAOException(
                "Falha ao gerar relatório sintético "
                + "de clientes em JDBCRelatorioDAO", ex);
    }
}
 
Example 3
Project: Omoikane   File: EtiquetaGenerator.java   View source code 8 votes vote down vote up
public void generate(String reportURL,Collection<Articulo> articulos)
{
    try {
        InputStream is = loadReport(reportURL);
        JasperDesign design = JRXmlLoader.load(is);
        JasperReport report = JasperCompileManager.compileReport(design);
        jp = JasperFillManager.fillReport(report,new HashMap(),new JRBeanCollectionDataSource(articulos));

        JasperViewer jasperViewer = new JasperViewer(jp, false);
        jasperViewer.setDefaultCloseOperation(JasperViewer.DISPOSE_ON_CLOSE);
        jasperViewer.setTitle("Etiquetas");
        jasperViewer.setZoomRatio((float) 1.25);
        jasperViewer.setExtendedState(JasperViewer.MAXIMIZED_BOTH);
        jasperViewer.setModalExclusionType(Dialog.ModalExclusionType.APPLICATION_EXCLUDE);
        jasperViewer.requestFocus();
        jasperViewer.setVisible(true);
    }catch (Exception e) {
        logger.error("Error al generar etiquetas", e);
    }

}
 
Example 4
Project: jasperreports   File: AbstractTest.java   View source code 7 votes vote down vote up
public JasperReport compileReport(String jrxmlFileName) throws JRException, IOException
{
	JasperReport jasperReport = null;
	
	InputStream jrxmlInput = JRLoader.getResourceInputStream(jrxmlFileName);

	if (jrxmlInput != null)
	{
		JasperDesign design;
		try
		{
			design = JRXmlLoader.load(jrxmlInput);
		}
		finally
		{
			jrxmlInput.close();
		}
		jasperReport = JasperCompileManager.compileReport(design);
	}
	
	return jasperReport;
}
 
Example 5
Project: Hotel-Properties-Management-System   File: ShowReport.java   View source code 6 votes vote down vote up
public void loadReport(String reportName, ReportObject reportObject) {

		logging = LoggingEngine.getInstance();
		
		try {
			
			final InputStream inputStream = ShowReport.class
					.getResourceAsStream("/com/coder/hms/reportTemplates/" + reportName + ".jrxml");
			JasperReport report = JasperCompileManager.compileReport(inputStream);

			HashMap<String, Object> parameters = new HashMap<String, Object>();	
			List<ReportObject> list = new ArrayList<ReportObject>();
			list.add(reportObject);
			JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(list);
			JasperPrint jasperPrint = JasperFillManager.fillReport(report, parameters, beanColDataSource);
			final JRViewer viewer = new JRViewer(jasperPrint);

			setType(Type.POPUP);
			setResizable(false);
			setModalExclusionType(ModalExclusionType.APPLICATION_EXCLUDE);
			this.setTitle("Reservation [Report]");
			this.setExtendedState(Frame.MAXIMIZED_BOTH);
			this.setAlwaysOnTop(isAlwaysOnTopSupported());
			this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			getContentPane().setLayout(new BorderLayout());
			this.setIconImage(Toolkit.getDefaultToolkit().
					getImage(LoginWindow.class.getResource(LOGOPATH)));
			this.setResizable(false);
			getContentPane().add(viewer, BorderLayout.CENTER);

		} catch (JRException e) {
			logging.setMessage("JRException report error!");
		}

	}
 
Example 6
Project: logistimo-web-service   File: GenerateInvoiceTest.java   View source code 6 votes vote down vote up
@Test
public void testInvoice(){
  List<InvoiceItem> invoiceItems = new ArrayList<>();

  int count = 1;
  for (IDemandItem demandItem : getDemandItems()) {
    InvoiceItem invoiceItem = new InvoiceItem();
    invoiceItem.setItem(demandItem.getMaterialId().toString());
    invoiceItem.setQuantity(demandItem.getQuantity().toString());
    invoiceItem.setRecommended(demandItem.getRecommendedOrderQuantity().toString());
    invoiceItem.setRemarks("Blah");
      invoiceItem.setBatchId("AB/1234/56"+count);
      invoiceItem.setExpiry("11/03/2020");
      invoiceItem.setManufacturer("Serum");
      invoiceItem.setBatchQuantity(BigDecimal.TEN.toPlainString());
    invoiceItem.setSno(String.valueOf(count++));
    invoiceItems.add(invoiceItem);
  }

  JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(invoiceItems);

  try {

    Map<String, Object> hm = new HashMap<>();
    JasperPrint jasperPrint = JasperFillManager.fillReport(
        JasperCompileManager
            .compileReport(Thread.currentThread().getContextClassLoader().getResourceAsStream(
                "test_logistimo_invoice.jrxml")), hm, beanColDataSource);

    JasperExportManager.exportReportToPdfFile(jasperPrint, "/tmp/logistimo_invoice.pdf");


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


}
 
Example 7
Project: Automekanik   File: ShikoPunetPunetoret.java   View source code 6 votes vote down vote up
private void krijoRaport(String pnt){
    btnRaporti.setOnAction(e -> {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Connection conn = DriverManager.getConnection(CON_STR, "test", "test");
                    HashMap hm = new HashMap();
                    hm.put("Folderi", folderi);
                    hm.put("punetori", pnt);
                    JasperReport jreport = JasperCompileManager.compileReport(raportiPunetor);
                    JasperPrint jprint = JasperFillManager.fillReport(jreport, hm, conn);
                    JasperViewer.viewReport(jprint, false);
                    conn.close();
                }catch (Exception ex){ex.printStackTrace();}
            }
        });
        t.start();
    });
}
 
Example 8
Project: ESIPC   File: Menu.java   View source code 6 votes vote down vote up
private void jMenuItem14ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem14ActionPerformed
    // TODO add your handling code here:
   try {
        conectar cc= new conectar();
        
        JasperReport reportes=JasperCompileManager.compileReport("Curso.jrxml");
        JasperPrint print=JasperFillManager.fillReport(reportes, null, cc.conexion());
        JasperViewer.viewReport(print);
        
    } catch (Exception e) {
        System.out.printf(e.getMessage());
    }
}
 
Example 9
Project: openbravo-brazil   File: GridBO.java   View source code 6 votes vote down vote up
private static JasperPrint createJasperPrint(InputStream reportFile,
    org.openbravo.erpCommon.utility.GridReportVO gridReportVO) throws JRException, IOException {
  JasperDesign jasperDesign = JRXmlLoader.load(reportFile);
  if (log4j.isDebugEnabled())
    log4j.debug("Create JasperDesign");
  org.openbravo.erpCommon.utility.ReportDesignBO designBO = new org.openbravo.erpCommon.utility.ReportDesignBO(
      jasperDesign, gridReportVO);
  designBO.define();
  if (log4j.isDebugEnabled())
    log4j.debug("JasperDesign created, pageWidth: " + jasperDesign.getPageWidth()
        + " left margin: " + jasperDesign.getLeftMargin() + " right margin: "
        + jasperDesign.getRightMargin());
  JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
  Map<String, Object> parameters = new HashMap<String, Object>();
  parameters.put("BaseDir", gridReportVO.getContext());
  parameters.put("IS_IGNORE_PAGINATION", gridReportVO.getPagination());

  JasperPrint jasperPrint = JasperFillManager
      .fillReport(
          jasperReport,
          parameters,
          new JRFieldProviderDataSource(gridReportVO.getFieldProvider(), gridReportVO
              .getDateFormat()));
  return jasperPrint;
}
 
Example 10
Project: jasperreports   File: JRFillCrosstab.java   View source code 6 votes vote down vote up
protected void loadEvaluator(JasperReport jasperReport)
{
	try
	{
		JREvaluator evaluator = JasperCompileManager.getInstance(filler.getJasperReportsContext()).getEvaluator(jasperReport, parentCrosstab);
		crosstabEvaluator = new JRCrosstabExpressionEvaluator(evaluator);
	}
	catch (JRException e)
	{
		throw 
			new JRRuntimeException(
				EXCEPTION_MESSAGE_KEY_EVALUATOR_LOADING_ERROR,
				(Object[])null,
				e);
	}
}
 
Example 11
Project: jasperreports   File: Report.java   View source code 6 votes vote down vote up
protected void compileReport() throws JRException, IOException
{
	InputStream jrxmlInput = JRLoader.getResourceInputStream(jrxml);
	JasperDesign design;
	try
	{
		design = JRXmlLoader.load(jrxmlInput);
	}
	finally
	{
		jrxmlInput.close();
	}
	
	report = JasperCompileManager.compileReport(design);
	
	fillManager = JasperFillManager.getInstance(jasperReportsContext);
}
 
Example 12
Project: bamboobsc   File: JReportUtils.java   View source code 6 votes vote down vote up
/**
 * jasperreport compile jrxml 成 jasper
 * 
 * @param sourceFile		如: File[]
 * @param destDir			如: C:/report/     產生一個 test.jasper 到 C:/report/ 中
 * @return
 * @throws JRException
 */
public static String compileReportToJasperFile(File sourceFile[], String destDir) throws JRException {
	String jasperFirst = "";
	for (int ix=0; sourceFile!=null && ix<sourceFile.length; ix++) {
		File srcFile = sourceFile[ix];
		if (!srcFile.exists() || srcFile.getName().indexOf(".jrxml")==-1) {
			srcFile=null;
			continue;
		}
		//String destFileName=srcFile.getName().replaceAll(".jrxml", ".jasper");
		String destFileName=srcFile.getPath().replaceAll(".jrxml", ".jasper");
		if ("".equals(jasperFirst)) {
			jasperFirst = destFileName;
		}
		JasperCompileManager.compileReportToFile(srcFile.getPath(), destFileName);
		logger.info("out process : " + destFileName);
	}
	return jasperFirst;
}
 
Example 13
Project: bamboobsc   File: JReportUtils.java   View source code 6 votes vote down vote up
/**
 * jasperreport compile jrxml 成 jasper
 * 
 * @param sourceFileName	如: new String[]{ "C:/report-source/test.jrxml" }
 * @param destDir			如: C:/report/     產生一個 test.jasper 到 C:/report/ 中
 * @return
 * @throws JRException
 */
public static String compileReportToJasperFile(String sourceFileName[], String destDir) throws JRException {
	String jasperFirst = "";
	for (int ix=0; sourceFileName!=null && ix<sourceFileName.length; ix++) {
		File srcFile = new File(sourceFileName[ix]);
		if (!srcFile.exists() || srcFile.getName().indexOf(".jrxml")==-1) {
			srcFile=null;
			continue;
		}
		//String destFileName=srcFile.getName().replaceAll(".jrxml", ".jasper");
		String destFileName=srcFile.getPath().replaceAll(".jrxml", ".jasper");
		if ("".equals(jasperFirst)) {
			jasperFirst = destFileName;
		}
		JasperCompileManager.compileReportToFile(srcFile.getPath(), destFileName);
		logger.info("out process : " + destFileName);
	}
	return jasperFirst;
}
 
Example 14
Project: maf-desktop-app   File: ReportingUtilsImpl.java   View source code 6 votes vote down vote up
/**
 * Load the report definitions.
 */
@Override
public void loadDefinitions() {

    jasperReports = new HashMap<String, JasperReport>();

    for (Reporting report : ReportingDao.getReportingAsList()) {
        File reportFile = getReportPath(report);
        if (reportFile != null && reportFile.exists()) {
            try {
                JasperDesign jasperDesign = JRXmlLoader.load(reportFile);
                JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
                jasperReports.put(report.template, jasperReport);
                if (log.isDebugEnabled()) {
                    log.debug("the jasper report " + report.template + " has been loaded");
                }
            } catch (Exception e) {
                log.error("Error while loading the report " + report.template, e.getMessage());
            }

        } else {
            log.error("Jasper report " + report.template + " not found !");
        }
    }

}
 
Example 15
Project: genomeartist   File: ResultReportTestReport.java   View source code 6 votes vote down vote up
/**
 * Compilez raportul pentru query
 */
public static void compileQueryReport() {
   String subreportFolder,subreportPath;
   String compiledSubFolder, compiledSubPath;

    //Subreport
    subreportFolder = ReadOnlyConfiguration.getString("JASPER_TEMPLATE_FOLDER");
    subreportPath = subreportFolder+ReadOnlyConfiguration.getString("JASPER_TEMPLATE_SUB_QUERY");
    compiledSubFolder = ReadOnlyConfiguration.getString("JASPER_COMPILED_FOLDER");
    compiledSubPath = compiledSubFolder+ReadOnlyConfiguration.getString("JASPER_COMPILED_SUB_QUERY");

    //Compilez si populez subreportul
    try
    {
        JasperCompileManager.compileReportToFile(
                subreportPath,
                compiledSubPath);
    }
    catch (JRException ex)
    {
        ex.printStackTrace();
    }
}
 
Example 16
Project: genomeartist   File: ResultReportTestReport.java   View source code 6 votes vote down vote up
/**
 * Compilez raportul Mapare
 */
public static void compileMapping() {
   String subreportFolder,subreportPath;
   String compiledSubFolder, compiledSubPath;

    //Subreport
    subreportFolder = ReadOnlyConfiguration.getString("JASPER_TEMPLATE_FOLDER");
    subreportPath = subreportFolder+ReadOnlyConfiguration.getString("JASPER_TEMPLATE_SUB_MAPPING");
    compiledSubFolder = ReadOnlyConfiguration.getString("JASPER_COMPILED_FOLDER");
    compiledSubPath = compiledSubFolder+ReadOnlyConfiguration.getString("JASPER_COMPILED_SUB_MAPPING");

    //Compilez si populez subreportul
    try
    {
        JasperCompileManager.compileReportToFile(
                subreportPath,
                compiledSubPath);
    }
    catch (JRException ex)
    {
        ex.printStackTrace();
    }
}
 
Example 17
Project: genomeartist   File: ResultReportTestReport.java   View source code 6 votes vote down vote up
/**
 * Compilez raportul Smith-Waterman
 */
public static void compileSmithReport() {
   String subreportFolder,subreportPath;
   String compiledSubFolder, compiledSubPath;

    //Subreport
    subreportFolder = ReadOnlyConfiguration.getString("JASPER_TEMPLATE_FOLDER");
    subreportPath = subreportFolder+ReadOnlyConfiguration.getString("JASPER_TEMPLATE_SUB_SMITH_WATERMAN");
    compiledSubFolder = ReadOnlyConfiguration.getString("JASPER_COMPILED_FOLDER");
    compiledSubPath = compiledSubFolder+ReadOnlyConfiguration.getString("JASPER_COMPILED_SUB_SMITH_WATERMAN");

    //Compilez si populez subreportul
    try
    {
        JasperCompileManager.compileReportToFile(
                subreportPath,
                compiledSubPath);
    }
    catch (JRException ex)
    {
        ex.printStackTrace();
    }
}
 
Example 18
Project: genomeartist   File: ResultReportTestReport.java   View source code 6 votes vote down vote up
/**
 * Compilez raportul Smith-Waterman
 */
public static void compilePositioning() {
   String subreportFolder,subreportPath;
   String compiledSubFolder, compiledSubPath;

    //Subreport
    subreportFolder = ReadOnlyConfiguration.getString("JASPER_TEMPLATE_FOLDER");
    subreportPath = subreportFolder+ReadOnlyConfiguration.getString("JASPER_TEMPLATE_SUB_POSITIONING");
    compiledSubFolder = ReadOnlyConfiguration.getString("JASPER_COMPILED_FOLDER");
    compiledSubPath = compiledSubFolder+ReadOnlyConfiguration.getString("JASPER_COMPILED_SUB_POSITIONING");

    //Compilez si populez subreportul
    try
    {
        JasperCompileManager.compileReportToFile(
                subreportPath,
                compiledSubPath);
    }
    catch (JRException ex)
    {
        ex.printStackTrace();
    }
}
 
Example 19
Project: genomeartist   File: ResultReportTestReport.java   View source code 6 votes vote down vote up
/**
 * Compilez raportul Smith-Waterman
 */
public static void compileGenes() {
   String subreportFolder,subreportPath;
   String compiledSubFolder, compiledSubPath;

    //Subreport
    subreportFolder = ReadOnlyConfiguration.getString("JASPER_TEMPLATE_FOLDER");
    subreportPath = subreportFolder+ReadOnlyConfiguration.getString("JASPER_TEMPLATE_SUB_GENES");
    compiledSubFolder = ReadOnlyConfiguration.getString("JASPER_COMPILED_FOLDER");
    compiledSubPath = compiledSubFolder+ReadOnlyConfiguration.getString("JASPER_COMPILED_SUB_GENES");

    //Compilez si populez subreportul
    try
    {
        JasperCompileManager.compileReportToFile(
                subreportPath,
                compiledSubPath);
    }
    catch (JRException ex)
    {
        ex.printStackTrace();
    }
}
 
Example 20
Project: eMonocot   File: PdfWritingTest.java   View source code 6 votes vote down vote up
@Test
public final void testBatchReportWriter() throws Exception {

	JasperReport jasperReport = JasperCompileManager.compileReport(
			new ClassPathResource("org/emonocot/job/download/reports/name_report1.jrxml").getInputStream());
	JRVerticalReportWriter writer = new JRVerticalReportWriter(jasperReport);
	writer.setDefaultOutputDir("target");
	StepExecution se = new StepExecution("testStep", new JobExecution(1L));
	writer.beforeStep(se);
	int chunkSize = 10;
	for (int i = 0; i <= (itemsToWrite.size()/chunkSize); i++) {
		List<Taxon> itemList = new ArrayList<Taxon>();
		for (int j = 0; j < chunkSize; j++) {
			try {
				itemList.add(itemsToWrite.get(i*chunkSize+j));
			} catch (IndexOutOfBoundsException e) {
				break;
			}
		}
		writer.write(itemList);

	}
	writer.afterStep(se);

}
 
Example 21
Project: metasfresh   File: JasperCompileClassLoader.java   View source code 6 votes vote down vote up
private URL compileJRXML(final InputStream jrxmlStream)
{
	FileOutputStream jasperStream = null;
	try
	{
		final File jasperFile = File.createTempFile("JasperReport", jasperExtension);
		jasperStream = new FileOutputStream(jasperFile);
		JasperCompileManager.compileReportToStream(jrxmlStream, jasperStream);
		jasperStream.flush();
		jasperStream.close();
		return jasperFile.toURI().toURL();
	}
	catch (Exception e)
	{
		throw new AdempiereException(e);
	}
	finally
	{
		Closeables.closeQuietly(jrxmlStream);
	}
}
 
Example 22
Project: FACE-RECOGNITION-BASED-ATTENDANCE-MANAGEMENT-SYSTEM   File: Report.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
        InputStream inputStream = new FileInputStream (".\\src\\reports\\test_jasper.jrxml");
       
        DataBeanMaker dataBeanMaker = new DataBeanMaker();
        ArrayList<DataBean> dataBeanList = dataBeanMaker.getDataBeanList(null);
       
        JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataBeanList);
       
        Map parameters = new HashMap();
       
JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, beanColDataSource);
//JasperExportManager.exportReportToPdfFile(jasperPrint, "c:/test_jasper.pdf");
    JRViewer jv=new JRViewer(jasperPrint);
JFrame jf = new JFrame();
    jf.getContentPane().add(jv);
    jf.validate();
    jf.setVisible(true);
    jf.setSize(new Dimension(1000,800));
    jf.setLocation(300,100);
    jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
 
Example 23
Project: FACE-RECOGNITION-BASED-ATTENDANCE-MANAGEMENT-SYSTEM   File: Report.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
        InputStream inputStream = new FileInputStream (".\\src\\reports\\test_jasper.jrxml");
       
        DataBeanMaker dataBeanMaker = new DataBeanMaker();
        ArrayList<DataBean> dataBeanList = dataBeanMaker.getDataBeanList(null);
       
        JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataBeanList);
       
        Map parameters = new HashMap();
       
JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, beanColDataSource);
//JasperExportManager.exportReportToPdfFile(jasperPrint, "c:/test_jasper.pdf");
    JRViewer jv=new JRViewer(jasperPrint);
JFrame jf = new JFrame();
    jf.getContentPane().add(jv);
    jf.validate();
    jf.setVisible(true);
    jf.setSize(new Dimension(1000,800));
    jf.setLocation(300,100);
    jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
 
Example 24
Project: AgileAlligators   File: GridUtils.java   View source code 6 votes vote down vote up
/**
 * Writes a Jasper Reports representation of the given Grid to the given OutputStream.
 */
public static void toJasperReport( Grid grid, Map<String, Object> params, OutputStream out )
    throws Exception
{
    if ( grid == null )
    {
        return;
    }
    
    final StringWriter writer = new StringWriter();
    
    render( grid, params, writer, JASPER_TEMPLATE );
    
    String report = writer.toString();

    JasperReport jasperReport = JasperCompileManager.compileReport( IOUtils.toInputStream( report, StandardCharsets.UTF_8 ) );
    
    JasperPrint print = JasperFillManager.fillReport( jasperReport, params, grid );
    
    JasperExportManager.exportReportToPdfStream( print, out );
}
 
Example 25
Project: omr   File: OMRModelTest.java   View source code 6 votes vote down vote up
/**
 * @return
 * @throws JazzOMRException
 * @throws JRException
 */
protected JasperReport getJasperReport() throws JazzOMRException {
	InputStream jasperJRXML = this.getClass().getResourceAsStream("/reports/ExamReport.jrxml");
	
	
	JasperReport jasperReport;
	try {
	
		jasperReport = JasperCompileManager.compileReport(jasperJRXML);

		//jasperReport = (JasperReport) JRLoader.loadObject(jasperReport);
	} catch (JRException e) {
		throw new JazzOMRParseException("Erro ao tentar carregar objeto de relatorio!", e);
	}
	return jasperReport;
}
 
Example 26
Project: OLE-INST   File: ReportGenerationServiceImpl.java   View source code 6 votes vote down vote up
/**
 * complie the report template xml file into a Jasper report file if the compiled file does not exist or is out of update
 * 
 * @param designTemplate the full name of the report template xml file
 * @param jasperReport the full name of the compiled report file
 */
protected void compileReportTemplate(String designTemplate, String jasperReport) throws JRException {
    File jasperFile = new File(jasperReport);
    File designFile = new File(designTemplate);

    if (!jasperFile.exists() && !designFile.exists()) {
        throw new RuntimeException("Both the design template file and jasper report file don't exist: (" + designTemplate + ", " + jasperReport + ")");
    }

    if (!jasperFile.exists() && designFile.exists()) {
        JasperCompileManager.compileReportToFile(designTemplate, jasperReport);
    }
    else if (jasperFile.exists() && designFile.exists()) {
        if (jasperFile.lastModified() < designFile.lastModified()) {
            JasperCompileManager.compileReportToFile(designTemplate, jasperReport);
        }
    }
}
 
Example 27
Project: kfs   File: ReportGenerationServiceImpl.java   View source code 6 votes vote down vote up
/**
 * complie the report template xml file into a Jasper report file if the compiled file does not exist or is out of update
 * 
 * @param template the name of the template file, without an extension
 * @return an input stream where the intermediary report was written
 */
protected File compileReportTemplate(String template) throws JRException, IOException {
    ClassPathResource designTemplateResource = new ClassPathResource(template);

    if (!designTemplateResource.exists()) {
        throw new RuntimeException("The design template file does not exist: "+template);
    }

    File tempJasperDir = new File(System.getProperty("java.io.tmpdir")+File.separator+template.replaceAll("\\/[^\\/]+$", ""));
    if (!tempJasperDir.exists()) {
        FileUtils.forceMkdir(tempJasperDir);
    }

    File tempJasperFile = new File(System.getProperty("java.io.tmpdir")+File.separator+template.replace(ReportGeneration.DESIGN_FILE_EXTENSION,"").concat(ReportGeneration.JASPER_REPORT_EXTENSION));
    if (!tempJasperFile.exists()) {
        JasperCompileManager.compileReportToStream(designTemplateResource.getInputStream(), new FileOutputStream(tempJasperFile));
    }

    return tempJasperFile;
}
 
Example 28
Project: jasper-service   File: JasperProcess.java   View source code 6 votes vote down vote up
/**
 * Compile jasper .jrxml source file if compiled .jasper is missing or older than source
 * 
 * @param filename
 * @return JasperReport
 * @throws IOException
 * @throws JRException
 */
private void compileReport(String jasperFileName) throws IOException, JRException {
    if (!jasperFileName.endsWith(".jasper")) {
    	throw new JRException("Bad file extension, should be .jasper: " + jasperFileName);
    }
    String sourceFileName = jasperFileName.substring(0, jasperFileName.length()-7) + ".jrxml";
    File source = new File(sourceFileName);
    File compiled = new File(jasperFileName);
    if (!source.exists()) {
        throw new IOException("Missing source JRXML file " + sourceFileName);
    }
    
    if(!compiled.exists() || (compiled.lastModified() < source.lastModified())) {
    	log.debug("compiling source report: " + sourceFileName);
        JasperCompileManager.compileReportToFile(sourceFileName, jasperFileName);
    } else {
    	log.debug("source report compilation not needed");        	
    }
}
 
Example 29
Project: gnvc-ims   File: ReportGenerator.java   View source code 6 votes vote down vote up
/**
 * Compile Template Design and produce .jasper file
 *
 * @throws IDXReportException
 */
private void compileToFile() {
    try {
        log.info("JRXML_FILE:" + JRXML_FILENAME);
        setJasperDesign(JRXmlLoader.load(new FileInputStream(JRXML_FILENAME)));
     
        /*
         * JasperDesign design = JRXmlLoader.load(
        new LegacyJasperInputStream(new FileInputStream("MyXsdBasedDesign.jrxml"))
        );
     
         */
        if (getJasperDesign() == null) {
            log.error("jasper design is null");
        }
        setJasperReport(JasperCompileManager.compileReport(getJasperDesign()));
        JRSaver.saveObject(getJasperReport(), JASPER_FILENAME);
    } catch (FileNotFoundException ex) {
        log.error(ex);
    } catch (JRException jre) {
        jre.printStackTrace();
    }
}
 
Example 30
Project: gnvc-ims   File: ReportGenerator.java   View source code 6 votes vote down vote up
private void compileToFile(InputStream is) {
    try {
        setJasperDesign(JRXmlLoader.load(is));
     
        /*
         * JasperDesign design = JRXmlLoader.load(
        new LegacyJasperInputStream(new FileInputStream("MyXsdBasedDesign.jrxml"))
        );
     
         */
        if (getJasperDesign() == null) {
            log.error("jasper design is null");
        }
        Boolean compileStatus = compileSubReport();
        if(!compileStatus)
            log.error("subreport compilation failed");
        setJasperReport(JasperCompileManager.compileReport(getJasperDesign()));
        JRSaver.saveObject(getJasperReport(), JASPER_FILENAME);
    } catch (JRException jre) {
        jre.printStackTrace();
    }
}
 
Example 31
Project: VaadinUtils   File: JasperReportCompiler.java   View source code 6 votes vote down vote up
public JasperReport compileReport( final File sourcePath, final File outputPath,
		String reportName) throws Throwable
{
	String name = reportName;
	if (!name.contains(".jasper"))
	{
		name = name+".jasper";
	}
	JasperReport jasperReport = null;
	JasperDesign jasperDesign = getDesignFile(sourcePath, reportName);
	File outputReport = new File(outputPath.getAbsolutePath() + "/" + name);
	jasperReport = JasperCompileManager.compileReport(jasperDesign);
	JRSaver.saveObject(jasperReport, outputReport);
	logger.warn("Saving compiled report : " + outputReport.getName());

	// Compile sub reports
	JRElementsVisitor.visitReport(jasperReport, createVisitor(sourcePath, outputPath));

	if (subReportException != null)
		throw new RuntimeException(subReportException);
	return jasperReport;
}
 
Example 32
Project: VaadinUtils   File: JasperReportCompiler.java   View source code 6 votes vote down vote up
public JasperReport compileReport(JasperDesign jasperDesign, final File sourcePath, final File outputPath,
		String reportName) throws Throwable
{
	JasperReport jasperReport = null;
	File outputReport = new File(outputPath.getAbsolutePath() + "/" + reportName + ".jasper");
	jasperReport = JasperCompileManager.compileReport(jasperDesign);
	JRSaver.saveObject(jasperReport, outputReport);
	logger.warn("Saving compiled report : " + outputReport.getAbsolutePath());

	// Compile sub reports
	JRElementsVisitor.visitReport(jasperReport, createVisitor(sourcePath, outputPath));

	if (subReportException != null)
		throw new RuntimeException(subReportException);
	return jasperReport;
}
 
Example 33
Project: acal   File: TelaRelatoriosEntradas.java   View source code 6 votes vote down vote up
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
 new Thread() {
        @Override
        public void run() {
            try {
                Connection conn = HibernateUtil.getConnection();
                JasperReport report = JasperCompileManager.compileReport(getClass().getResourceAsStream("/relatorios/rc_entrada.jrxml"));
                Map<String, Object> p = new HashMap<>();
                p.put("complementos"," where e.data = curdate() ");
                JasperPrint jasper = JasperFillManager.fillReport(report, p, conn);
                JasperViewer.viewReport(jasper, false);

            } catch (Exception ex) {
                Logger.getLogger(TelaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }.start();
 this.dispose();
}
 
Example 34
Project: opencps-v2   File: JRReportTemplate.java   View source code 5 votes vote down vote up
public static JRReportTemplate getJRReportTemplate(String jrxmlTemplate) throws JRException, IOException {

		InputStream isTemplate = new ByteArrayInputStream(jrxmlTemplate.getBytes(StandardCharsets.UTF_8));
		JRReportTemplate reportTemplate = (JRReportTemplate) JasperCompileManager.compileReport(isTemplate);

		if (isTemplate != null) {
			isTemplate.close();
		}

		return reportTemplate;
	}
 
Example 35
Project: java-swing-template   File: ReportsModel.java   View source code 5 votes vote down vote up
public static JasperPrint prepareReport(String reportpath) throws Exception {
    HashMap<String, Object> params = new HashMap<>();
    File f = new File("reports");
    String SUBREPORT_DIR = f.getAbsolutePath() + "\\";
    params.put("SUBREPORT_DIR", SUBREPORT_DIR);
    JasperReport jr = JasperCompileManager.compileReport(reportpath);
    return JasperFillManager.fillReport(jr, params, con);
}
 
Example 36
Project: Proyecto2017Seguros   File: ReporteMenu.java   View source code 5 votes vote down vote up
@Action(semantics = SemanticsOf.SAFE)
   @ActionLayout(bookmarking = BookmarkPolicy.AS_ROOT)
   @MemberOrder(sequence = "3")
public Blob imprimirClientesActivos() throws JRException, IOException {
	
	ClientesActivosDataSource datasource = new ClientesActivosDataSource();
	
	for (Cliente cli : clientesRepository.listarActivos()){
	
		ClientesActivosReporte reporteClientesActivos=new ClientesActivosReporte();
		
		reporteClientesActivos.setClienteNombre(cli.getClienteNombre());
		reporteClientesActivos.setClienteApellido(cli.getClienteApellido());
		reporteClientesActivos.setClienteDni(cli.getClienteDni());
		reporteClientesActivos.setClienteTipoDocumento(cli.getClienteTipoDocumento().toString());
		reporteClientesActivos.setPersonaMail(cli.getPersonaMail());
		reporteClientesActivos.setPersonaTelefono(cli.getPersonaTelefono());
		
		datasource.addParticipante(reporteClientesActivos);
	}
	String jrxml = "ClientesActivos.jrxml";
	String nombreArchivo = "Listado Clientes Activos ";
	
	InputStream input = ReporteRepository.class.getResourceAsStream(jrxml);
	JasperDesign jd = JRXmlLoader.load(input);
	
	JasperReport reporte = JasperCompileManager.compileReport(jd);
	Map<String, Object> parametros = new HashMap<String, Object>();
	JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, parametros, datasource);
	
	return ReporteRepository.imprimirReporteLista(jasperPrint, jrxml, nombreArchivo);
	
}
 
Example 37
Project: Proyecto2017Seguros   File: ReporteMenu.java   View source code 5 votes vote down vote up
@Action(semantics = SemanticsOf.SAFE)
   @ActionLayout(bookmarking = BookmarkPolicy.AS_ROOT)
   @MemberOrder(sequence = "5")
public Blob imprimirFacturacionAnualPorCompania() throws JRException, IOException {
   	
   	FacturacionDataSource datasource = new FacturacionDataSource();
	
	for (FacturacionCompaniasViewModel fac : facturacionRepository.facturacion()){
	
		FacturacionReporte facturacionCompania =new FacturacionReporte();
		
		facturacionCompania.setCompania(fac.getCompania().getCompaniaNombre().toString());
		facturacionCompania.setPrimaTotal(fac.getPrimaTotal());
		
		datasource.addParticipante(facturacionCompania);
	}
	String jrxml = "FacturacionCompanias.jrxml";
	String nombreArchivo = "Facturacion companias ";
	
	InputStream input = ReporteRepository.class.getResourceAsStream(jrxml);
	JasperDesign jd = JRXmlLoader.load(input);
	
	JasperReport reporte = JasperCompileManager.compileReport(jd);
	Map<String, Object> parametros = new HashMap<String, Object>();
	JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, parametros, datasource);
	
	return ReporteRepository.imprimirReporteLista(jasperPrint, jrxml, nombreArchivo);
   	
   }
 
Example 38
Project: Proyecto2017Seguros   File: ReporteMenu.java   View source code 5 votes vote down vote up
@Action(semantics = SemanticsOf.SAFE)
   @ActionLayout(bookmarking = BookmarkPolicy.AS_ROOT)
   @MemberOrder(sequence = "6")
public Blob imprimirPolizasPorCompania(
           @ParameterLayout(named="Compania: ") final Compania companiaSeleccionada) throws JRException, IOException {
   	
   	PolizaPorCompaniaDataSource datasource = new PolizaPorCompaniaDataSource();
	
	for (Poliza pol : polizaRepository.buscarPorCompania(companiaSeleccionada)){
	
		PolizaPorCompaniaReporte reportePolizaPorCompania =new PolizaPorCompaniaReporte();
		
		reportePolizaPorCompania.setPolizasCliente(pol.getPolizaCliente().toString());
		reportePolizaPorCompania.setPolizasCompania(pol.getPolizaCompania().getCompaniaNombre());
		reportePolizaPorCompania.setPolizaNumero(pol.getPolizaNumero());
		reportePolizaPorCompania.setPolizaFechaVigencia(pol.getPolizaFechaVigencia());
		reportePolizaPorCompania.setPolizaFechaVencimiento(pol.getPolizaFechaVencimiento());
		reportePolizaPorCompania.setPolizaFechaEmision(pol.getPolizaFechaEmision());
		reportePolizaPorCompania.setPolizaImporteTotal(pol.getPolizaImporteTotal());
		
		
		datasource.addParticipante(reportePolizaPorCompania);
	}
	String jrxml = "PolizasPorCompania.jrxml";
	String nombreArchivo = "Listado de polizas por compania"+" "+companiaSeleccionada.getCompaniaNombre()+" ";
	
	InputStream input = ReporteRepository.class.getResourceAsStream(jrxml);
	JasperDesign jd = JRXmlLoader.load(input);
	
	JasperReport reporte = JasperCompileManager.compileReport(jd);
	Map<String, Object> parametros = new HashMap<String, Object>();
	parametros.put("compania", companiaSeleccionada.getCompaniaNombre());
	JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, parametros, datasource);
	
	return ReporteRepository.imprimirReporteLista(jasperPrint, jrxml, nombreArchivo);
   }
 
Example 39
Project: Automekanik   File: ShikoKonsumatoret.java   View source code 5 votes vote down vote up
private void raporti(){
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Connection conn = DriverManager.getConnection(CON_STR, "test", "test");
                JasperReport jreport = JasperCompileManager.compileReport(raporti);
                JasperPrint jprint = JasperFillManager.fillReport(jreport, new HashedMap(), conn);
                JasperViewer.viewReport(jprint, false);
                conn.close();
            }catch (Exception ex){ex.printStackTrace();}
        }
    });
    btnRaport.setOnAction(e -> t.start());
}
 
Example 40
Project: Automekanik   File: ShikoPunetoret.java   View source code 5 votes vote down vote up
private void raporti(){
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Connection conn = DriverManager.getConnection(CON_STR, "test", "test");
                JasperReport jreport = JasperCompileManager.compileReport(raporti);
                JasperPrint jprint = JasperFillManager.fillReport(jreport, new HashMap(), conn);
                JasperViewer.viewReport(jprint, false);
                conn.close();
            }catch (Exception ex){ex.printStackTrace();}
        }
    }).start();
}