[信封袋套印]使用Bean DataSource製作report報表

十、撰寫程式來產生報表PDF

輸出成pdf主要的內容在save(String fileName)這個function裡,而jasper檔需放置在class的根目路上。

package com.izero.print.pdf;
import java.io.File;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRExporterParameter;
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.export.JRPdfExporter;
import net.sf.jasperreports.engine.util.JRLoader;
public class ToFile {
    private com.izero.print.datasource.AddressSource cds;
    public ToFile(com.izero.print.beansList.AddressList addrlist)
    {
        cds = new com.izero.print.datasource.AddressSource(addrlist);
        
    }
    public void save(String fileName)throws Exception
    {
        
            
            String root_path = this.getClass().getResource("/").getPath();
            //root_path = root_path.replace('\\', '/');
            String reportFilePath = root_path
                    + "proftk.jasper";
            System.out.println(reportFilePath);
            JRDataSource dataSource = this.createDataSource();

            Map<String, String> parameters = new HashMap<String, String>();
            //parameters.put("SUBREPORT_DIR", root_path
                    //+ "h:/");
            JasperReport report = (JasperReport) JRLoader
                    .loadObject(reportFilePath);
            JasperPrint jasperPrint = JasperFillManager.fillReport(report,
                    parameters, dataSource);

            java.io.File f = new java.io.File(fileName);
            if(f.isDirectory())
                f = new java.io.File(f.getPath()+File.separator+"proftk.pdf");
            System.out.println(f.getPath());
            java.io.OutputStream outputStream = new java.io.FileOutputStream(f);
            // 使用JRPdfExproter導出器導出pdf
            JRPdfExporter exporter = new JRPdfExporter();
            
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
                    outputStream);
            exporter.exportReport();
            
            outputStream.close();

        
    }
    
    private JRDataSource createDataSource() {
        
        if(cds==null)
            cds = new com.izero.print.datasource.AddressSource();
        
        return  cds;
    }
}

以下是操作的畫面,使用Virtual Editor Layout出來的,主要有一個載入檔案的按鈕,來載入檔案,並把檔案顯示在table裡,另一個按鈕來設定輸出路徑,設定好後會自動把報表產生完成。

package com.izero;

import java.awt.BorderLayout;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JFrame;
import java.awt.Dimension;
import javax.swing.JButton;
import java.awt.Rectangle;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class Printer extends JFrame {

    private static final long serialVersionUID = 1L;
    private JPanel jContentPane = null;
    private JButton jButton = null;
    private JScrollPane jScrollPane = null;
    private JTable jTable = null;
    private JButton jButton1 = null;
    /**
     * This is the default constructor
     */
    public Printer() {
        super();
        initialize();
    }

    /**
     * This method initializes this
     * 
     * @return void
     */
    private void initialize() {
        this.setSize(528, 358);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setContentPane(getJContentPane());
        this.setTitle("JFrame");
    }

    /**
     * This method initializes jContentPane
     * 
     * @return javax.swing.JPanel
     */
    private JPanel getJContentPane() {
        if (jContentPane == null) {
            jContentPane = new JPanel();
            jContentPane.setLayout(null);
            jContentPane.add(getJButton(), null);
            jContentPane.add(getJScrollPane(), null);
            jContentPane.add(getJButton1(), null);
        }
        return jContentPane;
    }

    /**
     * This method initializes jButton    
     *     
     * @return javax.swing.JButton    
     */
    private JButton getJButton() {
        if (jButton == null) {
            jButton = new JButton();
            jButton.setBounds(new Rectangle(381, 11, 120, 34));
            jButton.setText("載入檔案");
            jButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent e) {
                    JFileChooser chooser = new JFileChooser();
                    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                    chooser.setApproveButtonText("確定");
                    chooser.showDialog(jButton, null);  //留 null 否則上一行的設定被覆蓋  

                    java.io.File filePath = chooser.getSelectedFile();    
                    if(filePath!=null && !filePath.getPath().equals("")){
                        //jTextField1.setText(filePath.getPath());
                        java.io.BufferedReader reader = null;
                        try
                        {
                            String str = null;
                            reader = new java.io.BufferedReader(new java.io.FileReader(filePath));
                            while((str=reader.readLine())!=null)
                            {
                                String[] rowData = str.split(","); 
                                ((DefaultTableModel)getJTable().getModel())
                                    .addRow(rowData);
                            }

                        }catch(java.io.IOException ex)
                        {
                            ex.printStackTrace();
                        }
                        finally
                        {
                            try
                            {
                                if(reader!=null)
                                    reader.close();
                            }catch(java.io.IOException exx)
                            {
                                
                            }
                        }
                    }
                }
            });
        }
        return jButton;
    }

    /**
     * This method initializes jScrollPane    
     *     
     * @return javax.swing.JScrollPane    
     */
    private JScrollPane getJScrollPane() {
        if (jScrollPane == null) {
            jScrollPane = new JScrollPane();
            jScrollPane.setBounds(new Rectangle(6, 50, 492, 195));
            jScrollPane.setViewportView(getJTable());
        }
        return jScrollPane;
    }
    private DefaultTableModel getModel()
    {
        String[] headers = { "名稱", "郵地區號", "地址" };
        Object[][] cellData = null;
    
        DefaultTableModel model = new DefaultTableModel(cellData, headers) {
    
          public boolean isCellEditable(int row, int column) {
            return false;
          }
        };
    return model;
    }
    /**
     * This method initializes jTable    
     *     
     * @return javax.swing.JTable    
     */
    private JTable getJTable() {
        if (jTable == null) {
            jTable = new JTable();
            
            jTable.setModel(getModel());
        }
        return jTable;
    }

    /**
     * This method initializes jButton1    
     *     
     * @return javax.swing.JButton    
     */
    private JButton getJButton1() {
        if (jButton1 == null) {
            jButton1 = new JButton();
            jButton1.setBounds(new Rectangle(338, 272, 151, 34));
            jButton1.setText("選取目錄");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent e) {
                    JFileChooser chooser = new JFileChooser();
                    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                    chooser.setApproveButtonText("確定");
                    chooser.showDialog(jButton1, null);  //留 null 否則上一行的設定被覆蓋  

                    java.io.File filePath = chooser.getSelectedFile();    
                    if(filePath!=null && !filePath.getPath().equals("")){
                        com.izero.print.beansList.AddressList addrlist = 
                        new com.izero.print.beansList.AddressList();
                        
                        DefaultTableModel tableModel = (DefaultTableModel) getJTable()
                          .getModel();
                        int rowCount=tableModel.getRowCount();
                        for(int i = 0 ; i < rowCount;i++)
                        {
                            addrlist.addBean(new com.izero.print.beans.Address((String)tableModel.getValueAt(i, 0),
                            (String)tableModel.getValueAt(i, 1),(String)tableModel.getValueAt(i, 2)));
                        }
                        com.izero.print.pdf.ToFile save = new com.izero.print.pdf.ToFile(addrlist);
                        try
                        {
                            save.save(filePath.getPath());
                            javax.swing.JOptionPane.showMessageDialog(((JButton)e.getSource()).getParent(),
                            "已輸出pdf完成!\r\n"+filePath.getPath());
                        }catch(Exception ex)
                        {
                            ex.printStackTrace();
                        }
                        
                    }
                }
            });
        }
        return jButton1;
    }
    public static void main(String args[])
    {
        (new Printer()).setVisible(true);
    }

}

檔案格式如下圖姓名、郵遞區號、地址。

19.jpg

20.jpg

選取目錄後,等待一下會告知輸出pdf完成,就可以在剛才選取的路徑看到報表pdf檔的產生了。

21.jpg

大概內容如下,如此就可以把內容輸出至印表機了。

22.jpg

ps.

程式需要的pdf檔列表如下:

  1. commons-beanutils-1.8.0.jar
  2. commons-collections-2.1.1.jar
  3. commons-digester-1.7.jar
  4. commons-javaflow-20060411.jar
  5. commons-logging-1.0.4.jar
  6. groovy-all-1.7.5.jar
  7. iText-2.1.7.jar
  8. iTextAsian.jar
  9. jasperreports-4.0.0.jar

發表迴響