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; }
@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"); }
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 init(){ // JRBeanCollectionDataSource beanCollectionSource=new // JRBeanCollectionDataSource(order.getShoppingCart().getShoppingCartItems()); // JasperFillManager.fillReport(null, null) // } // // public void generateInvoicePDF(int orderId) throws JRException, IOException { order = purchaseOrderService.findById(orderId); // EntityManager em=PerisitenceManager.getEntityManager(); // Query query= em.createQuery("select s from ShoppingCart s"); // List<shoppingcart> listOfShoppingCart=(List<shoppingcart>)query.getResultList(); Map<String, Object> param = new HashMap<String, Object>(); param.put("invoiceNumber", String.valueOf(order.getId())); param.put("customerName", order.getUser().getFirstName() + order.getUser().getLastName()); List<ShoppingCartItem> items = order.getShoppingCart().getShoppingCartItems(); JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(items); String reportPath = FacesContext.getCurrentInstance() .getExternalContext() .getRealPath("/jsfpages/reports/invoice.jasper"); JasperPrint jasperPrint; jasperPrint = JasperFillManager.fillReport(reportPath, param, beanCollectionDataSource); HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse(); httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.pdf"); ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream(); JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream); FacesContext.getCurrentInstance().responseComplete(); }
public static void createXMLReport( InputStream reportFile, GridReportVO gridReportVO, OutputStream os) throws JRException, IOException { gridReportVO.setPagination(true); JasperPrint jasperPrint = createJasperPrint(reportFile, gridReportVO); JasperExportManager.exportReportToXmlStream(jasperPrint, os); }
public static void imprimeRelatorio(String nomeRelatorio, HashMap parametros, List lista) { try { JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(lista); FacesContext facesContext = FacesContext.getCurrentInstance(); ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext(); String path = servletContext.getRealPath("/WEB-INF/relatorios/"); // parametro jasper report parametros.put("SUBREPORT DIR", path + File.separator); JasperPrint jasperPrint = JasperFillManager.fillReport( servletContext.getRealPath("/WEB-INF/relatorios/") + File.separator + nomeRelatorio + ".jasper", parametros, dataSource); byte[] b = JasperExportManager.exportReportToPdf(jasperPrint); HttpServletResponse res = (HttpServletResponse) facesContext.getExternalContext().getResponse(); res.setContentType("application/pdf"); int codigo = (int) (Math.random() * 1000); res.setHeader("Content-disposition", "inline);filename-relatorio_" + codigo + ".pdf"); res.getOutputStream().write(b); facesContext.responseComplete(); } catch (Exception e) { UtilMensagens.mensagemErro("Erro ao imprimir: " + UtilErros.getMensagemErro(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(); } }
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 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); }
@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); }
@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(); } }
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try { HttpSession sesi = request.getSession(); if (sesi.getAttribute("role") == null) { request.getRequestDispatcher("page/index.jsp").forward(request, response); return; } else { String role = (String) sesi.getAttribute("role"); if (role.equals("user")) { User user = (User) sesi.getAttribute("currentUser"); if (user.getLevel() != 1) { response.sendRedirect("logout"); return; } } else { response.sendRedirect("logout"); return; } } List listRuang = new RuangDAO().getAllRuang(); HashMap parameters = new HashMap(); parameters.put("logo", getServletContext().getRealPath("page/images/logo_unpatti.jpg")); JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(listRuang); System.out.println("1 " + getServletContext().getRealPath("report/admin/ruang.jrxml")); // Compile JRXML menjadi Jasper JasperReport jasperReport = JasperCompileManager.compileReport( getServletContext().getRealPath("report/admin/ruang.jrxml")); System.out.println("2"); // Fill report dengan datasource JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource); System.out.println("3"); // Export report byte[] pdfByteArray = JasperExportManager.exportReportToPdf(jasperPrint); System.out.println("length : " + pdfByteArray.length); response.setContentType("application/pdf"); response.setContentLength(pdfByteArray.length); ServletOutputStream ouputStream = response.getOutputStream(); ouputStream.write(pdfByteArray, 0, pdfByteArray.length); ouputStream.flush(); ouputStream.close(); } catch (Exception ex) { Logger.getLogger(PrintAbsensiAction.class.getName()).log(Level.SEVERE, null, ex); // display stack trace in the browser StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); ex.printStackTrace(printWriter); response.setContentType("text/plain"); response.getOutputStream().print(stringWriter.toString()); } }
@SuppressWarnings({"rawtypes", "unchecked"}) private byte[] gerarRelatorioJasperPDF(JasperReport nomeJasper, Map parametros, JRDataSource ds) throws JRException, IOException { JasperPrint report = JasperFillManager.fillReport(nomeJasper, parametros, ds); byte[] pdf = JasperExportManager.exportReportToPdf(report); return pdf; }
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")); }
private byte[] generaPdf(List lista) throws JRException { Map<String, Object> params = new HashMap<>(); JasperDesign jd = JRXmlLoader.load( this.getClass() .getResourceAsStream("/mx/edu/um/mateo/inventario/reportes/almacenes.jrxml")); JasperReport jasperReport = JasperCompileManager.compileReport(jd); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, new JRBeanCollectionDataSource(lista)); byte[] archivo = JasperExportManager.exportReportToPdf(jasperPrint); return archivo; }
public static void exportToXML( InputStream inStream, ServletOutputStream outStream, HashMap<String, Object> parameters, JRDataSource dataSource) throws JRException { JasperPrint jasperPrint = JasperFillManager.fillReport(inStream, parameters, dataSource); JasperExportManager.exportReportToXmlStream(jasperPrint, outStream); return; }
/** * @param jrxmlFileName * @param pdfFileName * @throws Exception */ public static void exportJrxmlToXml(String jrxmlFileName, String xmlFileName) 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.exportReportToXmlFile(URL + tempJrprintFileName, URL + xmlFileName, true); System.out.println("成功创建了一个XML文档"); }
/** * 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(); } }
/** 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(StreamUtils.getInputStream(report)); JasperPrint print = JasperFillManager.fillReport(jasperReport, params, grid); JasperExportManager.exportReportToPdfStream(print, out); }
private void exportPdf_auto(JasperPrint jasperPrint, String defaultFilename) throws IOException, JRException { // response.setContentType("application/pdf"); String defaultname = null; if (defaultFilename.trim() != null && defaultFilename != null) { defaultname = defaultFilename + ".pdf"; } else { defaultname = "export.pdf"; } String fileName = new String(defaultname.getBytes("utf-8"), "ISO8859-1"); /*response.setHeader("Content-disposition", "attachment; filename=" + fileName);*/ // ServletOutputStream ouputStream = response.getOutputStream(); OutputStream ouputStream = new FileOutputStream("D:/" + defaultname); JasperExportManager.exportReportToPdfStream(jasperPrint, ouputStream); ouputStream.flush(); ouputStream.close(); }
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); }
/** * 导出pdf,注意此处中文问题, * * <p>这里应该详细说:主要在ireport里变下就行了。看图 * * <p>1)在ireport的classpath中加入iTextAsian.jar 2)在ireport画jrxml时,看ireport最左边有个属性栏。 * * <p>下边的设置就在点字段的属性后出现。 pdf font name :STSong-Light ,pdf encoding :UniGB-UCS2-H */ private static void exportPdf( JasperPrint jasperPrint, String defaultFilename, HttpServletRequest request, HttpServletResponse response) throws IOException, JRException { response.setContentType("application/pdf"); String defaultname = null; if (defaultFilename.trim() != null && defaultFilename != null) { defaultname = defaultFilename + ".pdf"; } else { defaultname = "export.pdf"; } String fileName = new String(defaultname.getBytes("GBK"), "ISO8859_1"); response.setHeader("Content-disposition", "attachment; filename=" + fileName); ServletOutputStream ouputStream = response.getOutputStream(); JasperExportManager.exportReportToPdfStream(jasperPrint, ouputStream); ouputStream.flush(); ouputStream.close(); }
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:/META-INF/spring/applicationContext.xml"); DataSource dataSource = (DataSource) context.getBean("dataSource"); Connection conn = null; Map<String, Object> parametros = new HashMap<String, Object>(); try { parametros.put("id", Long.parseLong(request.getParameter("id"))); System.out.println( getServletContext().getRealPath("") + " Hello World " + request.getParameter("id")); conn = dataSource.getConnection(); File reportFile = new File(getServletContext().getRealPath("") + "/META-INF/report.jasper"); JasperReport jasperReport = (JasperReport) JRLoader.loadObject(reportFile); // this.preencherRelatorio(request); JasperPrint jasperPrint = null; response.setContentType("application/pdf"); jasperPrint = JasperFillManager.fillReport(jasperReport, parametros, conn); System.out.println(jasperPrint); JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream()); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
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 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