java打印表格到打印机

这篇博客介绍了如何使用Java的Printable接口来打印表格。通过链表动态获取表格内容,并将其转换为二维数组,然后利用JTable和Graphics2D进行绘制和打印。在JDialog上展示表格并添加打印按钮,实现点击打印功能。

在这里我我有部分功能是要将一张表格通过java调用打印机打印出来,这里要用到java的Printable接口

Printable 接口由当前页面 painter 的 print 方法实现,该方法由打印系统调用,以呈现页面。构建 Pageable 时,使用 PageFormat 实例和实现此接口的实例构成的实例用于描述每个页面。调用实现 Printable 的实例,以打印页面的图形。

PrinterJob 上可以设置 Printable(..)。当客户端随后通过调用 PrinterJob.print(..) 启动打印时,控制被传送到打印系统,直到所有的页面完成打印。这是通过在文档中所有页面打印完成前一直调用 Printable.print(..) 来实现的。使用 Printable 接口时,只要打印系统请求,该打印就将页面内容提交给图像。

Printable.print(..) 的参数包括描述该页面可打印区域(计算适合该页面的内容所需要的区域)的 PageFormat 和页面索引(它指定请求页面的从 0 开始的打印流索引)。


在这里我通过链表来获取表格内容,以实现动态改变要打印出来的表格的大小,而我在打印方法中是用二维数组来实现打印和定位的,

因此有了个蛋痛的将链表转化为一维数组,然后又将一维数组转化为二维数组的过程。


链表转化为一维数组可以直接用toarray()方法

而一维数组转化为二维数组,int n = 4;//列
        int m = osf.getInfoStrings().length/n;//行
        String[][] data1 = new String[m][n];
        int num = -1;

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                num++;
                data1[i][j] = (String)osf.getInfoStrings()[num];
            }
        }

重要的实现部分就是,画出表格然后打印

为了使打印窗口显示在最前面,这里是在JDialog上画的表格

jdialog = new JDialog();
        jdialog.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e){
                System.exit(0);}});
        TableModel dataModel = new AbstractTableModel() {
            public int getColumnCount() {
                return headers.length; }
            public int getRowCount() { return data.length;}
            public Object getValueAt(int row, int col) {
                return data[row][col];}
            public String getColumnName(int column) {
                return headers[column];}
            public Class getColumnClass(int col) {
                return getValueAt(0,col).getClass();}
            public boolean isCellEditable(int row, int col) {
                return (col==1);}
        };

        tableView = new JTable(dataModel);
        JScrollPane scrollpane = new JScrollPane(tableView);

        scrollpane.setPreferredSize(new Dimension(500, 80));
        jdialog.getContentPane().setLayout(new BorderLayout());
        jdialog.getContentPane().add(BorderLayout.CENTER,scrollpane);
        jdialog.pack();
        printButton= new JButton();
        printButton.setText("打印");
        jdialog.getContentPane().add(BorderLayout.SOUTH,printButton);
        RepaintManager.currentManager(jdialog).setDoubleBufferingEnabled(false);

        printButton.addActionListener(this);
        jdialog.setBounds(300, 100, 650, 500);
        jdialog.setVisible(true);
    }
    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource()== printButton)
        {
            
            PrinterJob pj=PrinterJob.getPrinterJob();
            pj.setPrintable(TablePrint.this);
            pj.printDialog();
            try{
                pj.print();
            }
            catch (Exception PrintException) {}
        }
        jdialog.dispose();
    }

    public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException {
        Graphics2D  g2 = (Graphics2D) g;
        g2.setColor(Color.black);
        int fontHeight=g2.getFontMetrics().getHeight();
        int fontDesent=g2.getFontMetrics().getDescent();

        //leave room for page number
        double pageHeight = pageFormat.getImageableHeight()-fontHeight;
        double pageWidth =  pageFormat.getImageableWidth();
        double tableWidth = (double)
        tableView.getColumnModel().getTotalColumnWidth();
        double scale = 1;
        if (tableWidth >= pageWidth) {
            scale =  pageWidth / tableWidth;
        }

        double headerHeightOnPage= tableView.getTableHeader().getHeight()*scale;
        double tableWidthOnPage=tableWidth*scale;
        double oneRowHeight=(tableView.getRowHeight()+ tableView.getRowMargin())*scale;
        int numRowsOnAPage= (int)((pageHeight-headerHeightOnPage)/ oneRowHeight);
        double pageHeightForTable=oneRowHeight* numRowsOnAPage;
        int totalNumPages= (int)Math.ceil(((double)tableView.getRowCount())/ numRowsOnAPage);
        if(pageIndex>=totalNumPages) {
            return NO_SUCH_PAGE;
        }

        g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
        //bottom center
        g2.drawString("Page: "+(pageIndex+1), (int)pageWidth/2-35, (int)(pageHeight+fontHeight-fontDesent));

        g2.translate(0f,headerHeightOnPage);
        g2.translate(0f,-pageIndex*pageHeightForTable);

        //If this piece of the table is smaller
        //than the size available,
        //clip to the appropriate bounds.
        if (pageIndex + 1 == totalNumPages) {
            int lastRowPrinted = numRowsOnAPage * pageIndex;
            int numRowsLeft = tableView.getRowCount() - lastRowPrinted;
            g2.setClip(0, (int)(pageHeightForTable * pageIndex), (int) Math.ceil(tableWidthOnPage), (int) Math.ceil(oneRowHeight *  numRowsLeft));
        }
        //else clip to the entire area available.
        else{    
            g2.setClip(0, (int)(pageHeightForTable*pageIndex), (int) Math.ceil(tableWidthOnPage), (int) Math.ceil(pageHeightForTable));        
        }

        g2.scale(scale,scale);
        tableView.paint(g2);
        g2.scale(1/scale,1/scale);
        g2.translate(0f,pageIndex*pageHeightForTable);
        g2.translate(0f, -headerHeightOnPage);
        g2.setClip(0, 0, (int) Math.ceil(tableWidthOnPage), (int)Math.ceil(headerHeightOnPage));
        g2.scale(scale,scale);
        tableView.getTableHeader().paint(g2);
        //paint header at top

        return Printable.PAGE_EXISTS;
    }

编程依旧博大精深,在此还是略窥皮毛

在这留个脚印,以后继续踩踩...


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值