天道酬勤,学无止境

JasperViewer - How to set file name and set the extension (format)?

I am developing Java desktop based application using Swing framework and JasperReports for reporting. I have some problems, when JasperViewer comes up and I want to save the report.

How can I set the name of the file (default is blank) in the save dialog and how to limit only Pdf format?

Here is my code:

JRBeanCollectionDataSource beanCollection=new JRBeanCollectionDataSource(matakuliahs);

Map<String,Object> map=new HashMap<String, Object>();
map.put("namaMahasiswa", mahasiswa.getNama());

InputStream input=getClass().getResourceAsStream("/reportsederhana/reportsederhana.jrxml");
JasperDesign design=JRXmlLoader.load(input);
JasperReport report=JasperCompileManager.compileReport(design);
JasperPrint jasperPrint=JasperFillManager.fillReport(report, map, beanCollection);
jasperPrint.setName("Laporan "+mahasiswa.getNama()); // it doesn't give the name
JasperViewer.viewReport(jasperPrint,false);

评论

For setting the default extension(s) to save to, one idea is that you need to somehow get the JRViewer instance from a JasperViewer (instance) and then, on the void JRViewer instance, you can set some save contributions. Have a look at JRViewer.setSaveContributors(JRSaveContributor[] saveContribs).

For setting the file name, i am not entirely sure, but have a look at JRViewer.JRViewer(String, boolean).

Also check the JRViewer and the JasperViewer source code, it may come in handy.

It is an old post but I ran into the same problem...

I extended my viewer component from net.sf.jasperreports.view.JRViewer. After some code review I saw that it is only possible to control the 'lastFolder' but not the filename from outside. So you can set the last used folder if it is not set already by:

 if (lastFolder == null) {
        this.lastFolder = new File(System.getProperty("user.home"));
    }

But, and thats the hint: All buttons of toolbar are public fields!

So for my solution I removed all ActionListeners of the save button (btnSave):

 for (ActionListener actionListener : this.btnSave.getActionListeners()) {
        this.btnSave.removeActionListener(actionListener);
    }

And then added my own implementation. It is pretty like the original one only with the difference that I control the file name depending to the report name and current timestamp.

... 
File file = new File(lastFolder.getPath() + System.getProperty("file.separator") + DateTime.now().toString() + "_" + jasperPrint.getName());
...

Additionally I set the pre-selected file extension from .jasperprint to .pdf which is more convenient.

...
fileChooser.setFileFilter((FileFilter) saveContributors.get(1));
...

The full ActionListener code is as follows:

  this.btnSave.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setLocale(getLocale());
            fileChooser.updateUI();
            File file = new File(lastFolder.getPath() + System.getProperty("file.separator") + DateTime.now().toString() + "_" + jasperPrint.getName());
            fileChooser.setSelectedFile(file);
            for (int i = 0; i < saveContributors.size(); i++)
                fileChooser.addChoosableFileFilter((FileFilter) saveContributors.get(i));

            if (saveContributors.contains(lastSaveContributor))
                fileChooser.setFileFilter(lastSaveContributor);
            else if (saveContributors.size() > 1)
                fileChooser.setFileFilter((FileFilter) saveContributors.get(1));
            if (lastFolder != null)
                fileChooser.setCurrentDirectory(lastFolder);
            int retValue = fileChooser.showSaveDialog(JasperViewer.this);
            if (retValue == 0) {
                FileFilter fileFilter = fileChooser.getFileFilter();
                file = fileChooser.getSelectedFile();
                lastFolder = file.getParentFile();
                JRSaveContributor contributor = null;
                if (fileFilter instanceof JRSaveContributor) {
                    contributor = (JRSaveContributor) fileFilter;
                } else {
                    int i = 0;
                    do {
                        if (contributor != null || i >= saveContributors.size())
                            break;
                        contributor = (JRSaveContributor) saveContributors.get(i++);
                        if (!contributor.accept(file))
                            contributor = null;
                    } while (true);
                    if (contributor == null)
                        contributor = new JRPrintSaveContributor(jasperReportsContext, getLocale(), null);
                }
                lastSaveContributor = contributor;
                try {
                    contributor.save(jasperPrint, file);
                } catch (JRException ex) {
                    logger.error("Could not save report.", ex);
                    JOptionPane.showMessageDialog(JasperViewer.this, trc("JasperViewer.error.save", "Could not save report."));
                }
            }
        }
    });

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • 作为Web应用程序的一部分在Tomcat上运行JasperViewer(Running JasperViewer on Tomcat as part of a web application)
    问题 我了解到JasperViewer ( JasperReports的默认预览组件)是一个Swing组件,那么有什么方法可以将其转换或嵌入到Web应用程序中? 有人说我应该使用Java Web Start ,但是从我从此链接中学到的知识中, JWS对于在客户端计算机上下载和安装应用程序很有用,而我们的情况并非如此。 可能可行的其他解决方案(也许只是从理论上来说)是将jFrame转换为jApplet ,如本链接中所述 您是否尝试过这些解决方案中的任何一种,它们是否起作用? 您是否知道其他解决此问题的方法? 回答1 如果您知道如何生成报告,则可以轻松地在servlet内完成报告,并将生成的文件发送给客户端。 使用JWS应用程序或Applet很有可能意味着该报告是在客户端生成的,并且原始数据以及所有依赖项也可供客户端使用。 以下代码假定您正在生成PDF文件 public class ReportServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { // initialize your report objects here
  • 如何将 JasperViewer 与基于 Swing 的应用程序集成(How to integrate JasperViewer with Swing based application)
    问题 我可以将 JasperReports 查看器集成到我的 Swing 应用程序中,就像我单击应用程序中的查看报告按钮一样,然后应该打开查看器。 如果是这样,您能否为我提供有关此集成的代码片段的建议,并且在此查看器中,保存类型应仅限于 PDF 而不是所有其他可用的下载选项过滤器。 请在这方面给我建议。 回答1 是的,您可以,Jasper Reports 带有一个可用(虽然简单)的报告查看器: ... JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport...); JasperViewer.viewReport(jasperPrint); ... 最后一行是显示查看器的内容。 不过,我不确定您是否可以将可用的输出格式限制为 PDF。 回答2 假设该报告包含您的报告文件的名称 (*.jrxml)。 该程序将使用来自 mysql 数据库的数据填充报告。 我希望这能解决你的问题。 public void generate(String report) { // report will contain the name of your file try {
  • NoClassDefFoundError: com/itextpdf/text/DocumentException 将 jasper 导出为 pdf 时(NoClassDefFoundError: com/itextpdf/text/DocumentException when exporting jasper to pdf)
    问题 我创建了一个jasper报告,现在我需要将该报告导出为pdf格式。 这是我的代码。 // compiles jrxml JasperCompileManager.compileReportToFile(reportName + ".jrxml"); // fills compiled report with parameters and a connection JasperPrint print = JasperFillManager.fillReport(reportName + ".jasper", parameters, connection); // to view the report //JasperViewer.viewReport(print, false); // export repor to pdf JasperExportManager.exportReportToPdfFile(print, "fromXml.pdf"); 当我使用JasperViewer查看报告时,它工作正常。 但是当我将报告导出为pdf格式时,它给了我以下异常。 Exception in thread "main" java.lang.NoClassDefFoundError: com/itextpdf/text/DocumentException 但我已将 iText jar
  • JasperReport-换行以在文本字段中显示长文本(JasperReport - wrap text to show long text in textfield)
    问题 我在应用程序中使用jasper report作为报告工具。 我想知道如何通过将reportElement动态扩展到垂直方向(扩展行大小,而不是列宽)来包装长文本。 还是有什么办法可以做到这一点? 我下面的方法是截断长文本“ Some very long name ”。 你能给我一些建议吗? 输出 : import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.jasperreports.engine.JasperCompileManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; import net.sf.jasperreports.engine.design
  • 当出现JasperViewer并关闭它时,主框架/父级也关闭了[重复](When a JasperViewer appear and I close it, the main frame/parent also closed [duplicate])
    问题 这个问题已经在这里有了答案: 关闭子框架(Java + iReport)时如何防止父框架关闭? (1个答案) 3年前关闭。 当JasperViewer出现并且我关闭它时,主框架/父框架也关闭了。 如何预防呢? 这是我的代码。 private void cmdprintidMouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: try { JasperDesign jasperDesign = JRXmlLoader.load("report12.jrxml"); String sql = "select * from db1 where Company LIKE '" + txtcompany.getText() + "%'"; JRDesignQuery newQuery = new JRDesignQuery(); newQuery.setText(sql); jasperDesign.setQuery(newQuery); JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign); JasperPrint jasperPrint = JasperFillManager
  • 在运行 JasperViewer.viewReport(JasperPrint) 方法时获取 java.awt.HeadlessException(Getting java.awt.HeadlessException on running JasperViewer.viewReport(JasperPrint) method)
    问题 我在Ubuntu 11上运行此代码时遇到错误: JasperReport jasperReport = JasperCompileManager.compileReport("/resources/etiquetas/etiquetaEndereco.jrxml"); JasperPrint print = JasperFillManager.fillReport(jasperReport, parametros); JasperViewer.viewReport(print); 堆: GRAVE: java.awt.HeadlessException at java.awt.GraphicsEnvironment.checkHeadless(GraphicsEnvironment.java:159) at java.awt.Window.<init>(Window.java:432) at java.awt.Frame.<init>(Frame.java:403) at java.awt.Frame.<init>(Frame.java:368) at javax.swing.JFrame.<init>(JFrame.java:158) at net.sf.jasperreports.view.JasperViewer.<init>(JasperViewer.java:264
  • 制作jar文件后,Jasper报告无法正常工作(Jasper report is not working after making jar file [closed])
    问题 关闭。 这个问题需要调试细节。 它当前不接受答案。 想要改善这个问题吗? 更新问题,使它成为Stack Overflow的主题。 4年前关闭。 改善这个问题 我已经编写了以下用于创建jasper报告的代码,该代码在NetBeans IDE中可以正常工作,但是在创建该项目的jar文件后,该报告无法打开。 它也没有显示任何错误。 可能是什么问题? 用于创建jasper报告的代码 //Path to your .jasper file in your package String reportSource = "src/report/Allvendor_personal_info.jrxml"; try { jasperReport = (JasperReport) JasperCompileManager.compileReport(reportSource); jasperPrint = JasperFillManager.fillReport(jasperReport, null, con); //view report to UI JasperViewer.viewReport(jasperPrint, false); con.close(); } catch(Exception e) { JOptionPane.showMessaxgeDialog(null,
  • When a JasperViewer appear and I close it, the main frame/parent also closed [duplicate]
    This question already has an answer here: How to prevent parent frame closed when closing child frame (Java + iReport)? (1 answer) Closed 3 years ago. When a JasperViewer appear and I close it, the main frame / parent also closed. How to prevent this? This is my code.. private void cmdprintidMouseClicked(java.awt.event.MouseEvent evt) { // TODO add your handling code here: try { JasperDesign jasperDesign = JRXmlLoader.load("report12.jrxml"); String sql = "select * from db1 where Company LIKE '" + txtcompany.getText() + "%'"; JRDesignQuery newQuery = new JRDesignQuery(); newQuery.setText(sql)
  • 使用JasperViewer或Web应用程序中的其他内容查看报告(View report using JasperViewer or something else in web application)
    问题 我是JasperReports的新手,我想在Web应用程序中使用JasperViewer获得报告预览。 Web应用程序(没有PDF和XLSX)中是否可能或任何其他查看方法? 回答1 您可以导出到html文件,然后可以将其作为输出或ServletOutputStream发送,并在框架中显示 String htmlpath="E:/JASPER/OUTPUT/test_jasper.html"; JasperDesign jasperDesign = JRXmlLoader.load(inputStream); JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn); JasperExportManager.exportReportToHtmlFile(jasperPrint,htmlpath); InputStream in=new FileInputStream(htmlpath); int len = -1; byte[] byt = new byte[1024]; ServletOutputStream
  • NoClassDefFoundError: com/itextpdf/text/DocumentException when exporting jasper to pdf
    I created a jasper report and now I need to export that report to pdf format. This is my code for that. // compiles jrxml JasperCompileManager.compileReportToFile(reportName + ".jrxml"); // fills compiled report with parameters and a connection JasperPrint print = JasperFillManager.fillReport(reportName + ".jasper", parameters, connection); // to view the report //JasperViewer.viewReport(print, false); // export repor to pdf JasperExportManager.exportReportToPdfFile(print, "fromXml.pdf"); When I view the report using JasperViewer, it works fine. But When I exporting the report into pdf format
  • How to display DynamicReports in browser without download to cliend drive?
    I have to display some reports with Dynamic Reports. I use NetBeans and Tomcat 7. Eventually, all must be uploaded to cloud OpenShift. I used DynamicReports to create simple report (code snippet): Connection conn=null; try { Class.forName(DBConnStrings.driver); conn = DriverManager.getConnection(DBConnStrings.url + DBConnStrings.dbName+DBConnStrings.sslState, DBConnStrings.userName, DBConnStrings.password); } catch (Exception e) { e.printStackTrace(); } JasperReportBuilder report = DynamicReports.report(); report .columns( Columns.column("Tank Id", "id", DataTypes.integerType()), Columns
  • java.lang.NoClassDefFoundError:org / apache / commons / collections / ReferenceMap(java.lang.NoClassDefFoundError: org/apache/commons/collections/ReferenceMap)
    问题 Java真的是新手,还是讲西班牙语的人,所以,请尽我所能帮助您理解我:)。 我制作了一个程序,该程序管理用于存储客户端,有关客户端的信息等的mysql数据库。并生成(或尝试...)报告。 我从Eclipse Market(BTW,使用Eclipse Kepler)安装了JasperReports。 在学习了一些教程之后,我进入了通过参数创建报告的方式。 它只是识别一个客户端的一个参数。 那不是问题。 当我单击我的按钮以生成报告时出现问题,该报告包含以下代码: JButton btnOk = new JButton("OK"); btnOk.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String doc = jftxtDni.getText(); String sql; boolean respuesta = false; ConexionBaseDatos cc = new ConexionBaseDatos(); sql = "SELECT * FROM clientes WHERE DNI = '"+doc+"'"; rs = cc.Consultar(sql); try { while (rs.next()) { respuesta =
  • 如何在不下载到客户端驱动器的情况下在浏览器中显示 DynamicReports?(How to display DynamicReports in browser without download to cliend drive?)
    问题 我必须使用Dynamic Reports显示一些报告。 我使用 NetBeans 和 Tomcat 7。最终,所有都必须上传到云 OpenShift。 我使用DynamicReports创建简单的报告(代码片段): Connection conn=null; try { Class.forName(DBConnStrings.driver); conn = DriverManager.getConnection(DBConnStrings.url + DBConnStrings.dbName+DBConnStrings.sslState, DBConnStrings.userName, DBConnStrings.password); } catch (Exception e) { e.printStackTrace(); } JasperReportBuilder report = DynamicReports.report(); report .columns( Columns.column("Tank Id", "id", DataTypes.integerType()), Columns.column("Tank Name", "name", DataTypes.stringType()), Columns.column("Label", "label"
  • 如何将 JasperReport 导出为 HTML?(How to export JasperReport to HTML?)
    问题 我为我的项目创建了一个.jasper文件。 我在 JasperViewer 窗口中得到一个输出,但我想以 HTML 输出形式查看它。 我怎样才能做到这一点? 回答1 Jasper 报表项目附带了一个示例代码,用于将报表导出为 HTML。 它不仅是一个单独的 HTML 文件,而且至少需要一个 1x1 的透明 gif 用于装饰。 由于可移植性和打印问题,将报告导出为 HTML 文件并不是一个好主意。 但是,您可以使用该示例代码在您的网络服务器中显示 HTML 报告(这很常见)。 有关更多详细信息,请参阅 \demo\samples\webapp 应用程序。 回答2 以下代码将生成一个 HTML 报告: private DataSource jasperDataSource; private String jasperReportDir; public void generateHtmlReport(String reportPath, String reportCode, String outputLocation, Map<String, Object> params) throws Exception { Connection connection=null; try { connection = jasperDataSource.getConnection()
  • Running JasperViewer on Tomcat as part of a web application
    I have learned that JasperViewer (default preview component of JasperReports) is a Swing component, so is there any way to convert or embed it in a web application? Some say I should use Java Web Start, but from what i have learned from this link JWS is useful to download and install an application on client machine and this is not our case. the other work around that it may work (maybe just in theory) is converting jFrame to jApplet as briefly described in this link Have you tried any of these solutions and did they work? Do you know any other solution to this problem?
  • Getting java.awt.HeadlessException on running JasperViewer.viewReport(JasperPrint) method
    I'm getting the error with this code running on Ubuntu 11: JasperReport jasperReport = JasperCompileManager.compileReport("/resources/etiquetas/etiquetaEndereco.jrxml"); JasperPrint print = JasperFillManager.fillReport(jasperReport, parametros); JasperViewer.viewReport(print); Stack: GRAVE: java.awt.HeadlessException at java.awt.GraphicsEnvironment.checkHeadless(GraphicsEnvironment.java:159) at java.awt.Window.<init>(Window.java:432) at java.awt.Frame.<init>(Frame.java:403) at java.awt.Frame.<init>(Frame.java:368) at javax.swing.JFrame.<init>(JFrame.java:158) at net.sf.jasperreports.view
  • JAVA 报表工具 iReport(JAVA Reporting Tool iReport)
    问题 我们可以使用 iReport 获得类似于 .Net 的 Crystal 报告的报告页面吗? 那就是我需要在框架内获取报告。 回答1 假设您正在使用 Swing,这里是一个如何执行的示例。 编辑: 尝试获取 JasperViewer 容器并将其添加到主 JFrame 或 JPanel。 有点黑客工作,但它应该可以解决问题。 JasperDesign jd = JRXMLoader.load("FilePath"); JasperReport jr = JasperCompileManager.compileReport(jd); JasperPrint jp = JasperFillManager.fillReport((jr),null,con); // Create an instance of the JasperViewer instead of using the static call JasperViewer viewer=new JasperViewer(jp,false); // Get the viewers container and add that to the main frame or panel Container container = viewer.getContentPane(); myMainJFrame.add(container);
  • View report using JasperViewer or something else in web application
    I'm new to JasperReports and I want to get report preview using JasperViewer in web application. Is this possible or any other viewing method in web application (without PDF and XLSX)?
  • java.lang.NoClassDefFoundError: org/apache/commons/collections/ReferenceMap
    Really newbie in java, Spanish-speaker, so, ill do my best for you to understand me :). I made a program which manages a mysql database for storing clientes, information about clients, etc. And generates (or trying too...) reports. I installed JasperReports from Eclipse Market (BTW, using Eclipse Kepler). Following some tutorials, i made my way into creating a report by parameters. Its just one parameter to identify one client. Thats not the problem. The problem comes when i click my button to generate the report, which contains the code below: JButton btnOk = new JButton("OK"); btnOk
  • Jasper 报告导出到 pdf 给出异常:java.lang.ClassNotFoundException:com.lowagie.text.pdf.PdfContentByte [重复](Jasper report export to pdf gives exception: java.lang.ClassNotFoundException: com.lowagie.text.pdf.PdfContentByte [duplicate])
    问题 这个问题在这里已经有了答案: 为什么我在 Java 中收到 NoClassDefFoundError 错误? (30 个回答) NoClassDefFoundError 和 ClassNotFoundException 的原因和区别是什么? (15 个回答) 3年前关闭。 我已经研究了几个小时,但我没有找到任何有用的资源 我试图在 spring boot 应用程序中将 Jasper 报告导出为 pdf,但出现异常(显示在问题的末尾) 我不太确定,但我发现了一个链接,指出出口商正在使用旧版本的 itext 依赖项(称为 com.lowagie.text;根据链接,新版本是 com.itextpdf.text)但它仍然没有' t 提到如何解决这个问题 我的代码是这样的: public void getRpt2(HttpServletResponse response) throws JRException, IOException, SQLException { System.out.println("get resource!!! ..."); InputStream appCreatedReportStream = getClass().getResourceAsStream("/jasperReports/App_created_en.jrxml"); System.out