private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { try { JOptionPane.showMessageDialog(rootPane, "Creando Pdf "); InputStream marca_agua; marca_agua = new FileInputStream("plantilla-para-programa02.jpg"); int añoi = fechai.getCalendar().get(Calendar.YEAR); int mesi = fechai.getCalendar().get(Calendar.MONTH) + 1; int diai = fechai.getCalendar().get(Calendar.DAY_OF_MONTH); fi = añoi + "-" + mesi + "-" + diai; int añof = fechaf.getCalendar().get(Calendar.YEAR); int mesf = fechaf.getCalendar().get(Calendar.MONTH) + 1; int diaf = fechaf.getCalendar().get(Calendar.DAY_OF_MONTH); ff = añof + "-" + mesf + "-" + diaf; System.out.println(fi); System.out.println(ff); System.out.println(idc); n.conectar(); Map parameters = new HashMap(); parameters.put("fechai", fi); parameters.put("fechaf", ff); parameters.put("cliente", idc); parameters.put("marca", marca_agua); JasperReport report = JasperCompileManager.compileReport("estado_cuenta.jrxml"); JasperPrint print = JasperFillManager.fillReport(report, parameters, n.coneccion); // Exporta el informe a PDF JasperExportManager.exportReportToPdfFile(print, "estado_cuenta.pdf"); JOptionPane.showMessageDialog(rootPane, "Pdf creado correctamente enviando mail "); if (email.getText().length() == 0) { JOptionPane.showMessageDialog(rootPane, "Ingrese Un correo para poder enviar mail "); } else { JOptionPane.showMessageDialog(rootPane, "Enviando mail "); enviar(); } // Para visualizar el pdf directamente desde java // JasperViewer.viewReport(print, false); } catch (ClassNotFoundException ex) { Logger.getLogger(estados_cuenta.class.getName()).log(Level.SEVERE, null, ex); } catch (JRException ex) { Logger.getLogger(estados_cuenta.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException ex) { Logger.getLogger(estados_cuenta.class.getName()).log(Level.SEVERE, null, ex); } }
public void imprimir(List<Produto> produtos) throws IOException { try { // Projeto do Relatorio feito no iReport ou outro programa // OBS: Para evitar erros, colocar o projeto do Relatorio no mesmo diretorio desta classe, ou // seja, ambos devem estar juntos. InputStream is = getClass().getResourceAsStream("RelVenda.jrxml"); System.out.println(is); JasperReport report = JasperCompileManager.compileReport(is); // passar a lista recebida no método JasperPrint print = JasperFillManager.fillReport( report, null, new JRBeanCollectionDataSource(produtos, false)); // Diretorio que deseja salvar o relatorio JasperExportManager.exportReportToPdfFile(print, "c:/RelatorioVendas.pdf"); // Para abrir o relatorio na pasta que vc salvou, utilizar o comando abaixo Runtime.getRuntime().exec("cmd /c start C:/RelatorioVendas.pdf"); } catch (JRException e) { e.printStackTrace(); } }
public void SimpleReportDiretoPdf() { JasperPrint jp = null; try { JRDataSource customDs = new CustomBs(); jp = JasperFillManager.fillReport(arq, null, customDs); JasperViewer jasperViewer = new JasperViewer(jp); jasperViewer.setBounds(50, 50, 320, 240); jasperViewer.setLocationRelativeTo(null); jasperViewer.setExtendedState(JFrame.MAXIMIZED_BOTH); jasperViewer.setVisible(true); JasperExportManager.exportReportToPdfFile(jp, OUT_PDF); JOptionPane.showMessageDialog( null, "<html>Arquivo exportado para PDF!<br><br>A aplicação vai pedir" + " ao Sistema operacional <br>para abrir com o visualizador" + " padrão."); Desktop.getDesktop().open(new File(OUT_PDF)); } catch (JRException ex) { ex.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
@SuppressWarnings("unchecked") @EventListener public void apply(RichiestaServizioApprovata event) throws JRException, IOException { // Genero il report RichiestaNuovoServizioView uv = (RichiestaNuovoServizioView) sessionFactory .getCurrentSession() .createQuery("from RichiestaNuovoServizioView where richiestanuovoservizioId = :id") .setParameter("id", event.getId()) .uniqueResult(); List<RichiestaNuovoServizioView> data1 = new ArrayList<RichiestaNuovoServizioView>(); data1.add(uv); JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(data1); InputStream inputStream = this.getClass().getResourceAsStream("report_richiesta.jrxml"); @SuppressWarnings("rawtypes") Map parameters = new HashMap(); parameters.put("logo", ImageIO.read(getClass().getResource("RAI_logo.png"))); parameters.put("idRichiesta", event.getId().toString()); JasperDesign jasperDesign = JRXmlLoader.load(inputStream); JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, beanColDataSource); String nomeFile = "report_" + event.getId().toString() + "_approvato.pdf"; new java.io.File("static_assets/files/").mkdirs(); JasperExportManager.exportReportToPdfFile(jasperPrint, "static_assets/files/" + nomeFile); }
public static void createPDFReport( InputStream reportFile, GridReportVO gridReportVO, String path, String fileName) throws JRException, IOException { gridReportVO.setPagination(false); JasperPrint jasperPrint = createJasperPrint(reportFile, gridReportVO); JasperExportManager.exportReportToPdfFile(jasperPrint, path + "/" + fileName); }
@Transactional @Override public void generateStatementPdf(final Long billId) { try { BillMaster billMaster = this.billMasterRepository.findOne(billId); final String fileLocation = FileUtils.MIFOSX_BASE_DIR; /** Recursively create the directory if it does not exist * */ if (!new File(fileLocation).isDirectory()) { new File(fileLocation).mkdirs(); } final String statementDetailsLocation = fileLocation + File.separator + "StatementPdfFiles"; if (!new File(statementDetailsLocation).isDirectory()) { new File(statementDetailsLocation).mkdirs(); } final String printStatementLocation = statementDetailsLocation + File.separator + "Bill_" + billMaster.getId() + ".pdf"; final String jpath = fileLocation + File.separator + "jasper"; final String tenant = ThreadLocalContextUtil.getTenant().getTenantIdentifier(); final String jfilepath = jpath + File.separator + "Statement_" + tenant + ".jasper"; File destinationFile = new File(jfilepath); if (!destinationFile.exists()) { File sourceFile = new File( this.getClass().getClassLoader().getResource("Files/Statement.jasper").getFile()); FileUtils.copyFileUsingApacheCommonsIO(sourceFile, destinationFile); } final Connection connection = this.dataSource.getConnection(); Map<String, Object> parameters = new HashMap<String, Object>(); final Integer id = Integer.valueOf(billMaster.getId().toString()); parameters.put("param1", id); parameters.put("SUBREPORT_DIR", jpath + "" + File.separator); final JasperPrint jasperPrint = JasperFillManager.fillReport(jfilepath, parameters, connection); JasperExportManager.exportReportToPdfFile(jasperPrint, printStatementLocation); billMaster.setFileName(printStatementLocation); this.billMasterRepository.save(billMaster); connection.close(); System.out.println("Filling report successfully..."); } catch (final DataIntegrityViolationException ex) { LOGGER.error("Filling report failed..." + ex.getLocalizedMessage()); System.out.println("Filling report failed..."); ex.printStackTrace(); } catch (final JRException | JRRuntimeException e) { LOGGER.error("Filling report failed..." + e.getLocalizedMessage()); System.out.println("Filling report failed..."); e.printStackTrace(); } catch (final Exception e) { LOGGER.error("Filling report failed..." + e.getLocalizedMessage()); System.out.println("Filling report failed..."); e.printStackTrace(); } }
public byte[] getBytes( String valor, String fechaIni, String fechaFin, String dependen, String funcionario, String IdEstudia) throws JRException, SQLException { String bd = "Sigepex"; String login = "******"; String password = "******"; String url = "jdbc:mysql://localhost/" + bd; Connection con = null; try { Class.forName("com.mysql.jdbc.Driver").newInstance(); con = (Connection) DriverManager.getConnection(url, login, password); if (!con.isClosed()) { System.out.println("Successfully connected to " + "MySQL server using TCP/IP..."); } } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); } HashMap jasperParameter = new HashMap(); jasperParameter.put("FECHAINICIO", fechaIni); jasperParameter.put("FECHAFIN", fechaFin); jasperParameter.put("DEPENDENCIA", dependen); jasperParameter.put("FUNCIONARIO", funcionario); jasperParameter.put("IDESTUDIANTE", IdEstudia); JasperReport report = null; try { report = JasperCompileManager.compileReport(valor); } catch (Exception t) { String h = ""; } JasperPrint print = null; try { print = JasperFillManager.fillReport(report, jasperParameter, con); } catch (Exception eeee) { String ee = ""; } // Exporta el informe a PDF String destFileNamePdf = "C:\\reporte1.pdf"; // Creación del PDF JasperExportManager.exportReportToPdfFile(print, destFileNamePdf); byte[] pdfByteArray = JasperExportManager.exportReportToPdf(print); try { if (con != null) { con.close(); } } catch (SQLException e) { } return pdfByteArray; }
public static void generatePDFReport(JasperPrint jp, String path) throws Exception { JasperExportManager.exportReportToPdfFile(jp, path); Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Document PDF exporté"); alert.setContentText( "Le fichier PDF a bien été généré.\n" + "Il se trouve à l'emplacement suivant :\n" + path); alert.showAndWait(); }
@Transactional @Override public String generateInovicePdf(final Long invoiceId) { final String fileLocation = FileUtils.MIFOSX_BASE_DIR; /** Recursively create the directory if it does not exist * */ if (!new File(fileLocation).isDirectory()) { new File(fileLocation).mkdirs(); } final String InvoiceDetailsLocation = fileLocation + File.separator + "InvoicePdfFiles"; if (!new File(InvoiceDetailsLocation).isDirectory()) { new File(InvoiceDetailsLocation).mkdirs(); } final String printInvoiceLocation = InvoiceDetailsLocation + File.separator + "Invoice_" + invoiceId + ".pdf"; final Integer id = Integer.valueOf(invoiceId.toString()); try { final String jpath = fileLocation + File.separator + "jasper"; final String tenant = ThreadLocalContextUtil.getTenant().getTenantIdentifier(); final String jasperfilepath = jpath + File.separator + "Invoicereport_" + tenant + ".jasper"; File destinationFile = new File(jasperfilepath); if (!destinationFile.exists()) { File sourceFile = new File( this.getClass() .getClassLoader() .getResource("Files/Invoicereport.jasper") .getFile()); FileUtils.copyFileUsingApacheCommonsIO(sourceFile, destinationFile); } final Connection connection = this.dataSource.getConnection(); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("param1", id); final JasperPrint jasperPrint = JasperFillManager.fillReport(jasperfilepath, parameters, connection); JasperExportManager.exportReportToPdfFile(jasperPrint, printInvoiceLocation); connection.close(); System.out.println("Filling report successfully..."); } catch (final DataIntegrityViolationException ex) { LOGGER.error("Filling report failed..." + ex.getLocalizedMessage()); System.out.println("Filling report failed..."); ex.printStackTrace(); } catch (final JRException | JRRuntimeException e) { LOGGER.error("Filling report failed..." + e.getLocalizedMessage()); System.out.println("Filling report failed..."); e.printStackTrace(); } catch (final Exception e) { LOGGER.error("Filling report failed..." + e.getLocalizedMessage()); System.out.println("Filling report failed..."); e.printStackTrace(); } return printInvoiceLocation; }
public void imprimir(List<ComissaoRepresModel> itens) throws Exception { JasperReport report = JasperCompileManager.compileReport(this.getPathToReportPackage() + "ComisRep.jrxml"); JasperPrint print = JasperFillManager.fillReport(report, null, new JRBeanCollectionDataSource(itens)); JasperExportManager.exportReportToPdfFile( print, this.getPathToReportPackage() + "RelatorioComisRep.pdf"); Desktop desktop = Desktop.getDesktop(); desktop.open(new File(this.getPathToReportPackage() + "RelatorioComisRep.pdf")); }
@Test public void testReport() throws IOException, JRException, SQLException { ClassPathResource resource = new ClassPathResource("reports/jdbcReport.jrxml"); InputStream inputStream = resource.getInputStream(); JasperReport jasperReport = JasperCompileManager.compileReport(inputStream); Connection conn = dataSource.getConnection(); JasperPrint jasperPrint = JasperUtils.fillReport(jasperReport, new HashMap<String, Object>(), conn); JasperExportManager.exportReportToPdfFile(jasperPrint, "target/jdbcReport.pdf"); JasperExportManager.exportReportToXmlFile(jasperPrint, "target/jdbcReport.xml", false); JasperExportManager.exportReportToHtmlFile(jasperPrint, "target/jdbcReport.html"); }
/** * @param jrxmlFileName * @param pdfFileName * @throws Exception */ public static void exportJrxmlToPdf(String jrxmlFileName, String pdfFileName) throws Exception { String tempJasperFileName = getJasperFileName(jrxmlFileName); String tempJrprintFileName = getJrprintFileName(jrxmlFileName); // 编译static.jrxml报表设计文件,生成一个static.jasper报表文件 JasperCompileManager.compileReportToFile(URL + jrxmlFileName, URL + tempJasperFileName); // 编译static.jasper报表设计文件,生成一个static.jrprint报表文件 // 填充时,直接指定一个Connection作为数据库连接 JasperFillManager.fillReportToFile(URL + tempJasperFileName, PARAMS, CONN); // 使用JasperExportManager将一个JasperPrint导出成PDF文档 JasperExportManager.exportReportToPdfFile(URL + tempJrprintFileName, URL + pdfFileName); System.out.println("成功创建了一个PDF文档"); }
/** * Método encargado de cargar los reportes y crear el PDF con los datos * * @param archivo URL del archivo jrxml * @param parametros Mapa que contiene los Parámetros para llenar los reportes * @param nombreArchivo URL del destino del archivo */ private void guardarPDF(String archivo, Map parametros, String nombreArchivo) { try { FacesContext facesContext = FacesContext.getCurrentInstance(); String direccionReportes = facesContext.getExternalContext().getInitParameter("direccionReportes"); /*JasperDesign jasperDesign =JRXmlLoader.load(direccionReportes + archivo); JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);*/ JasperPrint jasperPrintPDF = JasperFillManager.fillReport(direccionReportes + archivo, parametros, conexion); String direccionGuardar = facesContext.getExternalContext().getInitParameter("direccionGuardar"); JasperExportManager.exportReportToPdfFile( jasperPrintPDF, direccionGuardar + nombreArchivo + ".pdf"); } catch (Exception e) { } }
/** * Envía un xls como respuesta al cliente. * * @param jasperPrint con el reporte xls. * @throws Exception Se genera cuando se presenta un error al exportar el reporte como archivo * xls. */ private void enviarPDF(JasperPrint jasperPrint, String nombreReporte) throws Exception { String fileName = ConvertidorUtils.convertirEspaciosAUnderscore( reporteList.get(ReporteConstants.RUTA) + newObject.getEmpresa().getRazonSocial() + "//" + newObject.getUbicacion() + "//"); boolean archvoCreado = false; File archivo = new File(fileName); if (!archivo.exists()) { archvoCreado = archivo.mkdirs(); } if (archvoCreado || archivo.exists()) { JasperExportManager.exportReportToPdfFile(jasperPrint, fileName + nombreReporte + ".pdf"); } }
// @Test public void testarImpressaoRelatorioEvento() { JasperReport jasperReport; JasperPrint jasperPrint; try { jasperReport = JasperCompileManager.compileReport(URL_REPORT + "relatorioTeste.jrxml"); Map<String, Object> parameters = new HashMap<>(); List<VoRelatorioTeste> participantes = new ArrayList<>(); preencherListaParticipantes(participantes); JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(participantes); jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource); JasperExportManager.exportReportToPdfFile(jasperPrint, URL_REPORT + "relatorio.pdf"); } catch (Exception e) { e.printStackTrace(); } }
public void onClick$btnImprimir() throws JRException { JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(almacenes); Map parameters = new HashMap(); parameters.put("FECHA", new java.util.Date()); JasperReport report = JasperCompileManager.compileReport( "C:\\Users\\Reinaldo López\\Documents\\workspace entrega viernes 13\\fundalara\\WebContent\\Logistica\\Reportes\\ReporteListadoAlmacenes.jrxml"); JasperPrint print = JasperFillManager.fillReport(report, parameters, ds); // Exporta el informe a PDF JasperExportManager.exportReportToPdfFile( print, "C:\\Users\\Reinaldo López\\Documents\\workspace entrega viernes 13\\fundalara\\WebContent\\Logistica\\Reportes\\ReporteListadoAlmacenes.pdf"); // Para visualizar el pdf directamente desde java JasperViewer.viewReport(print, false); }
public static void main(String[] args) { // - Paramètres de connexion à la base de données Connection connection; try { // - Connexion à la base connection = MyConnection.getInstance(); // - Chargement et compilation du rapport (charger le fichier jrxml déjà généré) JasperDesign jasperDesign = JRXmlLoader.load("/pdf/report.jrxml"); JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign); // - Paramètres à envoyer au rapport Map parameters = new HashMap(); parameters.put("Titre", "Titre"); // - Execution du rapport JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, connection); // - Création du rapport au format PDF JasperExportManager.exportReportToPdfFile(jasperPrint, "report.pdf"); System.out.println("success"); } catch (JRException e) { System.out.println("erreur de compilation" + e.getMessage()); } }
private byte[] geraRelatorio(Map<String, Object> map, String relatorio) { try { Connection conn = DataSourceUtils.getConnection(dataSource); SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); String id = format.format(new Date()); JasperReport pathRxml = JasperCompileManager.compileReport(rb.getString("relOrigin") + relatorio); JasperPrint printReport = JasperFillManager.fillReport(pathRxml, map, conn); if (printReport.getPages().isEmpty()) { return null; } JasperExportManager.exportReportToPdfFile( printReport, rb.getString("relDestiny") + id + ".pdf"); File file = new File(rb.getString("relDestiny") + id + ".pdf"); FileInputStream fis = new FileInputStream(file); byte[] data = new byte[fis.available()]; fis.read(data); fis.close(); return data; } catch (Exception e) { e.printStackTrace(); return null; } }
protected void createReport2(HttpServletRequest req, HttpServletResponse resp, String strNoSTS) throws ServletException, IOException { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String strDSN = jvCommonClass.fnGetProperty("DSN"); java.sql.Connection con = DriverManager.getConnection("jdbc:odbc:" + strDSN); String strFileJRXML = "report5.jrxml"; String strFileJasper = (new StringBuilder(String.valueOf(JRXML_LOCAL_PATH))).append(strFileJRXML).toString(); String strTglAnggaran = req.getSession().getAttribute("strTglAnggaran").toString(); Date dtTglAnggaran = null; try { dtTglAnggaran = (new SimpleDateFormat("dd/MM/yyyy")).parse(strTglAnggaran); } catch (ParseException e) { e.printStackTrace(); } String strNamaPemda = req.getParameter("hidNamaPemda").toString(); String strNamaBidang = req.getParameter("hidNamaBidang").toString(); String strAlamatPemda = req.getParameter("hidAlamatPemda").toString(); String strKotamadyaPemda = req.getParameter("hidKotamadyaPemda").toString(); String strKodePos = req.getParameter("hidKodePos").toString(); String strTelepon = req.getParameter("hidTelepon").toString(); String strFacsimile = req.getParameter("hidFacsimile").toString(); String strNamaUser = req.getParameter("hidNamaUser").toString(); String strKdJabatanUser = req.getParameter("hidKdJabatanUser").toString(); String strNIPUser = req.getParameter("hidNIPUser").toString(); String strJabatanUser = req.getParameter("hidJabatanUser").toString(); String strAngka = req.getParameter("hidTotal").toString(); String strTerbilang = req.getParameter("hidTerbilang").toString(); String strNamaPejabat = req.getParameter("hidNamaPejabat").toString(); String strJabatanPejabat = req.getParameter("hidJabatanPejabat").toString(); String strNIPPejabat = req.getParameter("hidNIPPejabat").toString(); Map parameters = new HashMap(); parameters.put("pNamaPemda", strNamaPemda); parameters.put("pNamaDinas", strNamaBidang); parameters.put("pNoSTS", strNoSTS); parameters.put("pAngka", strAngka); parameters.put("pTerbilang", strTerbilang); parameters.put("pNamaAtasan", strNamaPejabat); parameters.put("pJabatanAtasan", strJabatanPejabat); parameters.put("pNIP", strNIPPejabat); String strNamaBendahara = ""; String strNIPBendahara = ""; Hashtable htInfoPejabat1 = jvg.fnGetInfoPejabat(); int intHtInfoPejabat = htInfoPejabat1.size(); for (int a = 1; a <= intHtInfoPejabat; a++) { String strArray[] = (String[]) htInfoPejabat1.get(String.valueOf(a)); if (strArray[0].equals("31100")) { strNamaBendahara = strArray[1]; strNIPBendahara = strArray[2]; } } parameters.put("pNamaBendahara", strNamaBendahara); parameters.put("pNIPBendahara", strNIPBendahara); SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy"); Date todayDate = new Date(); String strToday = sdf.format(todayDate); net.sf.jasperreports.engine.JasperReport jasperReport = JasperCompileManager.compileReport(strFileJasper); net.sf.jasperreports.engine.JasperPrint print = JasperFillManager.fillReport(jasperReport, parameters, con); String strFilePDF = (new StringBuilder("STS_")).append(strToday).append(".pdf").toString(); String strOutput = (new StringBuilder(String.valueOf(REPORT_LOCAL_PATH))).append(strFilePDF).toString(); JasperExportManager.exportReportToPdfFile(print, strOutput); String strPDFOutput = (new StringBuilder(String.valueOf(OUTPUT_LOCAL_PATH))).append(strFilePDF).toString(); resp.sendRedirect(strPDFOutput); } catch (ClassNotFoundException cnfe) { cnfe.printStackTrace(); } catch (SQLException sqle) { sqle.printStackTrace(); } catch (JRException jre) { jre.printStackTrace(); } }
public void generateOrderConfirmation(final OrderCustomer order) { try { final MarketArea marketArea = marketService.getMarketAreaById(order.getMarketAreaId()); final Localization localization = localizationService.getLocalizationById(order.getLocalizationId()); final Locale locale = localization.getLocale(); // WE SET TO NULL USELESS DATA - BETTER WAY SHOULD BE TO USE A SPECIFIC DOZER RULE for (Iterator<OrderItem> iterator = order.getOrderItems().iterator(); iterator.hasNext(); ) { OrderItem orderItem = (OrderItem) iterator.next(); orderItem.getProductSku().setPrices(null); orderItem.getProductSku().setStocks(null); orderItem.getProductSku().setProductMarketing(null); orderItem.getProductSku().setRetailers(null); } final OrderCustomerPojo orderCustomerPojo = orderPojoService.handleOrderMapping(order); final String jrxml = getOrderConfirmationTemplateByMarketArea(marketArea); File fileJrxml = new File(jrxml); final String resourcePath = jrxml.replace(fileJrxml.getName(), ""); final JasperReport jasperReport = JasperCompileManager.compileReport(jrxml); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("RESOURCE_PATH", resourcePath); parameters.put("RECORD_DELIMITER", "\r\n"); parameters.put("order", orderCustomerPojo); Object[] orderInformationsParams = {orderCustomerPojo.getOrderNum()}; parameters.put( "orderInformations", coreMessageSource.getDocumentMessage( ScopeDocumentMessage.ORDER_CONFIRMATION, "header_order_informations", orderInformationsParams, locale)); parameters.put("date", orderCustomerPojo.getDateUpdate().toString()); parameters.put("billingAddress", orderCustomerPojo.getBillingAddress()); parameters.put("shippingAddress", orderCustomerPojo.getShippingAddress()); Map<String, String> wording = coreMessageSource.loadWording(I18nKeyValueUniverse.DOCUMENT.getPropertyKey(), locale); parameters.put("wording", wording); List<OrderItem> orderItems = new ArrayList<OrderItem>(); Set<OrderShipment> orderShipments = orderCustomerPojo.getOrderShipments(); for (Iterator<OrderShipment> iterator = orderShipments.iterator(); iterator.hasNext(); ) { OrderShipment orderShipment = (OrderShipment) iterator.next(); orderItems.addAll(orderShipment.getOrderItems()); } // TODO : denis : one page/table by OrderShipment JRDataSource datasource = new JRBeanCollectionDataSource(orderItems, true); final JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, datasource); String fullFilePath = getOrderConfirmationFilePath(order); JasperExportManager.exportReportToPdfFile(jasperPrint, fullFilePath); } catch (Exception e) { logger.error("", e); } }
public static void main(String args[]) { // [pdf/printlangusng] [directoryREPORT] [directoryPDF] [filereport] [filepdf] [kondisi] // path di pak edy "F:/SERVERLAMA/wamp/www/potensi/dist/logoNU.png" String direktoryReport = "/media/apps/pakedy/depak/potensi/dist/"; String directoyPDF = "/media/apps/pakedy/depak/potensi/pdf/"; if (!debugging) { direktoryReport = args[1]; directoyPDF = args[2]; } String fileReport = "", qryData = "", thisCondition = "", pdfDestination = "", forAwhile = ""; java.util.Map parameter = new java.util.HashMap(); fileReport = direktoryReport + args[3] + ".jasper"; if (args[3].equalsIgnoreCase("rincianKabupaten") || args[3].equalsIgnoreCase("rincianKecamatan") || args[3].equalsIgnoreCase("rincianDesa")) { fileReport = direktoryReport + "rincianPropinsi.jasper"; } if (args[3].equalsIgnoreCase("newaasetLaporan")) { try { if (args[5] != null) { if (args[5].length() > 0) { thisCondition += " propid = " + args[5] + " "; } } } catch (Exception ex) { } try { if (args[6] != null) { if (args[6].length() > 0) { if (thisCondition.length() > 0) { thisCondition += " and "; } thisCondition += " kabid = " + args[6] + " "; } } } catch (Exception ex) { } try { if (args[7] != null) { if (args[7].length() > 0) { if (thisCondition.length() > 0) { thisCondition += " and "; } thisCondition += " kecid = " + args[7] + " "; } } } catch (Exception ex) { } if (thisCondition.length() > 0) { thisCondition = " where " + thisCondition; } qryData = "select id,jenis_aset,ket_jenis,nama_aset,lokasi,ranting,kecid" + ",(select b.namaKota from tbkota b where b.kotaID=kabid) as namaKabupaten" + ",(select a.namaKecamatan from tbkecamatan a where a.kecamatanID=kecid) as namaKecamatan" + ",(select c.namaKelurahan from tbkelurahan c where c.kelurahanID=kelid ) as namaKelurahan" + " from newaset" + thisCondition + " order by kecid,id"; } else if (args[3].equalsIgnoreCase("rincianPropinsi")) { qryData = "SELECT newaset.jenis_aset, klasifikasi_aset.jenis, golongan.golongan,format(count(*),0) as jmlView, " + "count(*) as jumlah " + "FROM (newaset) " + "JOIN klasifikasi_aset ON newaset.jenis_aset = klasifikasi_aset.kode_klasifikasi " + "JOIN golongan ON klasifikasi_aset.golongan = golongan.id WHERE newaset.propid = " + args[5] + " GROUP BY newaset.jenis_aset, klasifikasi_aset.jenis, golongan.golongan ORDER BY jenis_aset asc"; } else if (args[3].equalsIgnoreCase("rincianKabupaten")) { qryData = "SELECT newaset.jenis_aset, klasifikasi_aset.jenis, golongan.golongan,format(count(*),0) as jmlView, " + "count(*) as jumlah " + "FROM (newaset) " + "JOIN klasifikasi_aset ON newaset.jenis_aset = klasifikasi_aset.kode_klasifikasi " + "JOIN golongan ON klasifikasi_aset.golongan = golongan.id WHERE newaset.kabid = " + args[5] + " GROUP BY newaset.jenis_aset, klasifikasi_aset.jenis, golongan.golongan ORDER BY jenis_aset asc"; } else if (args[3].equalsIgnoreCase("rincianKecamatan")) { qryData = "SELECT newaset.jenis_aset, klasifikasi_aset.jenis, golongan.golongan,format(count(*),0) as jmlView, " + "count(*) as jumlah " + "FROM (newaset) " + "JOIN klasifikasi_aset ON newaset.jenis_aset = klasifikasi_aset.kode_klasifikasi " + "JOIN golongan ON klasifikasi_aset.golongan = golongan.id WHERE newaset.kecid = " + args[5] + " GROUP BY newaset.jenis_aset, klasifikasi_aset.jenis, golongan.golongan ORDER BY jenis_aset asc"; } else if (args[3].equalsIgnoreCase("rincianDesa")) { qryData = "SELECT newaset.jenis_aset, klasifikasi_aset.jenis, golongan.golongan,format(count(*),0) as jmlView, " + "count(*) as jumlah " + "FROM (newaset) " + "JOIN klasifikasi_aset ON newaset.jenis_aset = klasifikasi_aset.kode_klasifikasi " + "JOIN golongan ON klasifikasi_aset.golongan = golongan.id WHERE newaset.kelid = " + args[5] + " GROUP BY newaset.jenis_aset, klasifikasi_aset.jenis, golongan.golongan ORDER BY jenis_aset asc"; } else if (args[3].equalsIgnoreCase("levelKabupaten")) { qryData = "select a.kabid,b.namaKota,count(*) as jumlah,format(count(*),0) as jmlView " + "from newaset a inner join tbkota b on a.kabid = b.kotaID where a.propid = " + args[5] + " group by a.kabid,b.namaKota order by b.namaKota"; } else if (args[3].equalsIgnoreCase("levelKecamatan")) { qryData = "select a.kecid,b.namaKecamatan,count(*) as jumlah," + "format(count(*),0) as jmlView from newaset a " + "inner join tbkecamatan b on a.kecid = b.kecamatanID where a.kabid = " + args[5] + " group by a.kecid,b.namaKecamatan " + "order by b.namaKecamatan"; } else if (args[3].equalsIgnoreCase("levelDesa")) { qryData = "select a.kelid,b.namaKelurahan,count(*) as jumlah,format(count(*),0) as jmlView " + "from newaset a " + "inner join tbkelurahan b on a.kelid = b.kelurahanID where a.kecid =" + args[5] + " group by a.kelid,b.namaKelurahan order by b.namaKelurahan"; } else if (args[3].equalsIgnoreCase("rekapEntry")) { qryData = "select createdby,count(*) as jumlah,format(count(*),0) as jmlView " + " from newaset group by createdby order by createdby"; } else if (args[3].equalsIgnoreCase("rekapEntryPerson")) { int i = 6; boolean ada = true; while (ada) { try { if (i < 7) forAwhile += args[i]; else forAwhile += " " + args[i]; i++; } catch (Exception ex) { ada = false; } } qryData = "select DATE_FORMAT(created, '%d/%m/%Y') as created," + "count(*) as jumlah,format(count(*),0) as jmlView " + "from newaset where createdby = '" + forAwhile + "' group by created order by created"; } String klaSS = "jdbc:mysql://localhost/potensi?user=nujatim&password=klaser"; try { Class.forName("com.mysql.jdbc.Driver").newInstance(); java.sql.Connection conec = java.sql.DriverManager.getConnection(klaSS); parameter.put("qryData", qryData); if (args[3].equalsIgnoreCase("rincianPropinsi")) { String namaPropinsi = args[6]; int i = 7; boolean ada = true; while (ada) { try { namaPropinsi += " " + args[i]; i++; } catch (Exception ex) { ada = false; } } parameter.put( "rinciTitel", "Rincian Jumlah masing-masing obyek di Propinsi " + namaPropinsi); } else if (args[3].equalsIgnoreCase("rincianKabupaten")) { String namaKabupaten = args[6]; int i = 7; boolean ada = true; while (ada) { try { namaKabupaten += " " + args[i]; i++; } catch (Exception ex) { ada = false; } } parameter.put("rinciTitel", "Rincian Jumlah masing-masing obyek di " + namaKabupaten); } else if (args[3].equalsIgnoreCase("rincianKecamatan")) { String namaKecamatan = args[6]; int i = 7; boolean ada = true; while (ada) { try { namaKecamatan += " " + args[i]; i++; } catch (Exception ex) { ada = false; } } parameter.put("rinciTitel", "Rincian Jumlah masing-masing obyek di " + namaKecamatan); } else if (args[3].equalsIgnoreCase("rincianDesa")) { String namaDesa = args[6]; int i = 7; boolean ada = true; while (ada) { try { namaDesa += " " + args[i]; i++; } catch (Exception ex) { ada = false; } } parameter.put("rinciTitel", "Rincian Jumlah masing-masing obyek di Desa " + namaDesa); } else if (args[3].equalsIgnoreCase("levelKabupaten")) { String namaPropinsi = args[6]; int i = 7; boolean ada = true; while (ada) { try { namaPropinsi += " " + args[i]; i++; } catch (Exception ex) { ada = false; } } parameter.put("namaPropinsi", namaPropinsi); } else if (args[3].equalsIgnoreCase("levelKecamatan")) { String namaKabupaten = args[6]; int i = 7; boolean ada = true; while (ada) { try { namaKabupaten += " " + args[i]; i++; } catch (Exception ex) { ada = false; } } parameter.put("namaKabupaten", namaKabupaten); } else if (args[3].equalsIgnoreCase("levelDesa")) { String namaKecamatan = args[6]; int i = 7; boolean ada = true; while (ada) { try { namaKecamatan += " " + args[i]; i++; } catch (Exception ex) { ada = false; } } parameter.put("namaKecamatan", namaKecamatan); } else if (args[3].equalsIgnoreCase("rekapEntryPerson")) { parameter.put("person", forAwhile); parameter.put("total", args[5]); } parameter.put("imgPath", direktoryReport + "logoNU.png"); net.sf.jasperreports.engine.JasperPrint jasperPrint = net.sf.jasperreports.engine.JasperFillManager.fillReport(fileReport, parameter, conec); if (debugging) { net.sf.jasperreports.view.JasperViewer jasperViewer = new net.sf.jasperreports.view.JasperViewer(jasperPrint, false); jasperViewer.setDefaultCloseOperation(javax.swing.JFrame.HIDE_ON_CLOSE); jasperViewer.setExtendedState(javax.swing.JFrame.MAXIMIZED_BOTH); jasperViewer.setTitle("Laporan Aset"); jasperViewer.setVisible(true); } if (args[0].equalsIgnoreCase("pdf")) { pdfDestination = directoyPDF + args[4] + ".pdf"; net.sf.jasperreports.engine.JasperExportManager.exportReportToPdfFile( jasperPrint, pdfDestination); } else if (args[0].equalsIgnoreCase("cetak")) { net.sf.jasperreports.engine.JasperPrintManager.printReport(jasperPrint, false); } System.exit(0); } catch (Exception ex) { System.out.println(" error " + ex.getMessage()); System.exit(0); } }
public static void main(String[] args) { String jenisReport = args[0]; String FilePDF = args[1]; String fileName = getPath() + "rpStokbarang.jasper"; java.sql.Connection konek = konek(); java.util.Map parameter = new java.util.HashMap(); try { // untuk stok barang tabel // java Main stokbarangtabel stokBarang01012003004739o.pdf 2 44463 ctmtx25-9012 if (jenisReport.equalsIgnoreCase("stokbarangtabel")) { fileName = getPath() + "rpStokbarang.jasper"; String jumlah = args[2]; int jmlBarang = Integer.valueOf(jumlah).intValue() + 2; int i = 0; String kondisi = "where "; for (i = 3; i <= jmlBarang; i++) { if (i == 3) kondisi += " kd_brg='" + args[i] + "' "; else kondisi += " or kd_brg='" + args[i] + "' "; } parameter.put("kondisi", kondisi); String querynya = "select kd_brg,hrg_beli from tb_barang " + kondisi; java.sql.Statement sta = konek.createStatement(); java.sql.Statement sta1 = konek.createStatement(); java.sql.ResultSet rs = sta.executeQuery(querynya); querynya = ""; while (rs.next()) { querynya = "update tb_barang set kd_hrgbeli='" + ubahkode(rs.getString("hrg_beli")) + "' where kd_brg='" + rs.getString("kd_brg") + "';"; if (debugginfg) System.out.println(querynya); sta1.executeUpdate(querynya); } querynya = "select format(sum(stok*hrg_beli),0) as total from tb_barang " + kondisi; rs = sta.executeQuery(querynya); if (rs.next()) parameter.put("jml", rs.getString("total")); else parameter.put("jml", "0"); rs.close(); sta.close(); sta1.close(); } // ----------------end untuk stok barang tabel net.sf.jasperreports.engine.JasperPrint jasperPrint = net.sf.jasperreports.engine.JasperFillManager.fillReport(fileName, parameter, konek); // buat bikin pdf file net.sf.jasperreports.engine.JasperExportManager.exportReportToPdfFile(jasperPrint, FilePDF); // buat print // net.sf.jasperreports.engine.JasperPrintManager.printReport(jasperPrint,false); /* net.sf.jasperreports.view.JasperViewer jasperViewer=new net.sf.jasperreports.view.JasperViewer(jasperPrint,false); jasperViewer.setDefaultCloseOperation(javax.swing.JFrame.HIDE_ON_CLOSE); jasperViewer.setExtendedState(javax.swing.JFrame.MAXIMIZED_BOTH); jasperViewer.setTitle("Laporan"); jasperViewer.setVisible(true); */ konek.close(); } catch (Exception w) { System.out.println(" salah " + w.getMessage()); } }
public static File generate(HrReport report, String outputFormat, String jrxmlUrl) throws IOException { String url = Context.getRuntimeProperties().getProperty("connection.url", null); Connection conn; try { conn = connect(url); } catch (SQLException e) { log.error("Error connecting to DB.", e); return null; } Map<String, Object> map = new HashMap<String, Object>(); for (HrReportParameter reportParameter : report.getParameters()) { if (reportParameter != null) if (reportParameter.getName() != null) map.put(reportParameter.getName(), reportParameter.getValue()); } log.debug("Report parameter map: " + map); String exportPath = OpenmrsUtil.getApplicationDataDirectory(); URL resourceUrl = new URL(jrxmlUrl); InputStream is = resourceUrl.openStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); FileWriter appDirJrxml = new FileWriter(new File(exportPath + report.getFileName())); BufferedWriter bw = new BufferedWriter(appDirJrxml); String line; while ((line = br.readLine()) != null) { bw.write(line); bw.write("\n"); } bw.flush(); bw.close(); JasperPrint jasperPrint = null; try { JasperDesign jasperDesign = JRXmlLoader.load(exportPath + report.getFileName()); JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign); jasperPrint = JasperFillManager.fillReport(jasperReport, map, conn); if (outputFormat.equals("PDF")) { File pdfFile = new File( exportPath + report.getName() + new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss").format(new Date()) + ".pdf"); JasperExportManager.exportReportToPdfFile(jasperPrint, pdfFile.getAbsolutePath()); return pdfFile; } else if (outputFormat.equals("Excel")) { ByteArrayOutputStream output = new ByteArrayOutputStream(); File outputfile = new File( exportPath + report.getName() + new SimpleDateFormat("dd-MM-yyyy-HH-mm-ss").format(new Date()) + ".xls"); OutputStream outputfileStream = new FileOutputStream(outputfile); JRXlsExporter exporterXLS = new JRXlsExporter(); exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint); exporterXLS.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, output); exporterXLS.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE); exporterXLS.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE); exporterXLS.setParameter( JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE); exporterXLS.exportReport(); outputfileStream.write(output.toByteArray()); outputfileStream.flush(); outputfileStream.close(); return outputfile; } } catch (JRException e) { log.error("Error generating report", e); } finally { try { if (!conn.isClosed()) { conn.close(); } } catch (SQLException e) { log.error("Exception closing report connection.", e); } } return null; }
public void pdf() throws JRException { long start = System.currentTimeMillis(); JasperExportManager.exportReportToPdfFile("build/reports/DataSourceReport.jrprint"); System.err.println("PDF creation time : " + (System.currentTimeMillis() - start)); }
public void pdf() throws JRException { long start = System.currentTimeMillis(); JasperExportManager.exportReportToPdfFile( TMP_DIR + ALL_CHARTS_REPORT_JRPRINT, TMP_DIR + System.currentTimeMillis() + ".pdf"); System.err.println("PDF creation time : " + (System.currentTimeMillis() - start)); }
public void pdf() throws JRException { long start = System.currentTimeMillis(); JasperExportManager.exportReportToPdfFile(m_jasperPrint, "target/reports/AllChartsReport.pdf"); System.err.println("PDF creation time : " + (System.currentTimeMillis() - start)); }
/** * 使用JasperExportManager将一个JasperPrint导出成PDF文档 * * @param jrprintFileName * @param pdfFileName * @throws Exception */ public static void exportToPdf(String jrprintFileName, String pdfFileName) throws Exception { JasperExportManager.exportReportToPdfFile(URL + jrprintFileName, URL + pdfFileName); System.out.println("成功创建了一个PDF文档"); }
private String saveReport(JasperPrint jasperPrint, String format, String destFileName) throws JRException, Exception { String reportName = null; switch (Format.valueOf(format)) { case pdf: JasperExportManager.exportReportToPdfFile(jasperPrint, destFileName); reportName = destFileName; break; case html: JasperExportManager.exportReportToHtmlFile(jasperPrint, destFileName); reportName = createZip(destFileName); break; case xml: JasperExportManager.exportReportToXmlFile(jasperPrint, destFileName, true); reportName = createZip(destFileName); break; case csv: JRCsvExporter exporter = new JRCsvExporter(); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, destFileName); exporter.exportReport(); reportName = destFileName; break; default: LogUtils.errorf(this, "Error Running Report: Unknown Format: %s", format); } return reportName; }
private void jButtonReporteActionPerformed( java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jButtonReporteActionPerformed GestorBD bd = new GestorBD(); // bd.getConnection(); Connection conn = bd.getConnection(); try { Map parameters = new HashMap(); parameters.put("Estudiantes", "ID"); parameters.put("FECHA", new java.util.Date()); JasperReport report = JasperCompileManager.compileReport( "C:\\Users\\danrocar\\Desktop\\Reportes\\report1.jrxml"); // + "C:\\informes JAsper\\JRXML\\InformeMySql.jrxml"); // JasperPrint print = JasperFillManager.fillReport JasperPrint print = JasperFillManager.fillReport(report, parameters, conn); // Exporta el informe a PDF JasperExportManager.exportReportToPdfFile( print, "C:\\Users\\danrocar\\Desktop\\Reportes\\InformeEstudiantesMySQL.pdf"); // Para visualizar el pdf directamente desde java JasperViewer.viewReport(print, false); } catch (Exception e) { e.printStackTrace(); } /*finally { //Cleanup antes de salir try { if (conn != null) { conn.rollback(); System.out.println("ROLLBACK EJECUTADO"); conn.close(); } } catch (Exception e) { e.printStackTrace(); } }*/ } // GEN-LAST:event_jButtonReporteActionPerformed