extjs-grid打印插件

<script type="text/javascript">
        Ext.onReady(function() {
            Ext.define('Company', {
                extend: 'Ext.data.Model',
                fields: [
                    {name: 'company'},
                    {name: 'price', type: 'float'},
                    {name: 'change', type: 'float'},
                    {name: 'pctChange', type: 'float'},
                    {name: 'lastChange', type: 'date', dateFormat: 'n/j h:ia'},
                    {name: 'industry'},
                    {name: 'desc'}
                ]
            });
            var myData = [
                ['3m Co',                               71.72, 0.02,  0.03,  '9/1 12:00am'],
                ['Alcoa Inc',                           29.01, 0.42,  1.47,  '9/1 12:00am'],
                ['Altria Group Inc',                    83.81, 0.28,  0.34,  '9/1 12:00am'],
                ['American Express Company',            52.55, 0.01,  0.02,  '9/1 12:00am'],
                ['American International Group, Inc.',  64.13, 0.31,  0.49,  '9/1 12:00am'],
                ['AT&T Inc.',                           31.61, -0.48, -1.54, '9/1 12:00am'],
                ['Boeing Co.',                          75.43, 0.53,  0.71,  '9/1 12:00am'],
                ['Caterpillar Inc.',                    67.27, 0.92,  1.39,  '9/1 12:00am'],
                ['Citigroup, Inc.',                     49.37, 0.02,  0.04,  '9/1 12:00am'],
                ['E.I. du Pont de Nemours and Company', 40.48, 0.51,  1.28,  '9/1 12:00am'],
                ['Exxon Mobil Corp',                    68.1,  -0.43, -0.64, '9/1 12:00am'],
                ['General Electric Company',            34.14, -0.08, -0.23, '9/1 12:00am'],
                ['General Motors Corporation',          30.27, 1.09,  3.74,  '9/1 12:00am'],
                ['Hewlett-Packard Co.',                 36.53, -0.03, -0.08, '9/1 12:00am'],
                ['Honeywell Intl Inc',                  38.77, 0.05,  0.13,  '9/1 12:00am'],
                ['Intel Corporation',                   19.88, 0.31,  1.58,  '9/1 12:00am'],
                ['International Business Machines',     81.41, 0.44,  0.54,  '9/1 12:00am'],
                ['Johnson & Johnson',                   64.72, 0.06,  0.09,  '9/1 12:00am'],
                ['JP Morgan & Chase & Co',              45.73, 0.07,  0.15,  '9/1 12:00am'],
                ['McDonald\'s Corporation',             36.76, 0.86,  2.40,  '9/1 12:00am'],
                ['Merck & Co., Inc.',                   40.96, 0.41,  1.01,  '9/1 12:00am'],
                ['Microsoft Corporation',               25.84, 0.14,  0.54,  '9/1 12:00am'],
                ['Pfizer Inc',                          27.96, 0.4,   1.45,  '9/1 12:00am'],
                ['The Coca-Cola Company',               45.07, 0.26,  0.58,  '9/1 12:00am'],
                ['The Home Depot, Inc.',                34.64, 0.35,  1.02,  '9/1 12:00am'],
                ['The Procter & Gamble Company',        61.91, 0.01,  0.02,  '9/1 12:00am'],
                ['United Technologies Corporation',     63.26, 0.55,  0.88,  '9/1 12:00am'],
                ['Verizon Communications',              35.57, 0.39,  1.11,  '9/1 12:00am'],
                ['Wal-Mart Stores, Inc.',               45.45, 0.73,  1.63,  '9/1 12:00am']
            ];
            var store = Ext.create('Ext.data.ArrayStore', {
                fields: [
                    {name: 'company'},
                    {name: 'price',      type: 'float'},
                    {name: 'change',     type: 'float'},
                    {name: 'pctChange',  type: 'float'},
                    {name: 'lastChange', type: 'date', dateFormat: 'n/j h:ia'}
                ],
                data: myData
            });

            var grid = Ext.create('Ext.grid.Panel', {
                store: store,
                stateful: true,
                stateId: 'stateGrid',
                columns: [
                    {
                        text     : 'Company',
                        flex     : 1,
                        sortable : false,
                        dataIndex: 'company'
                    },
                    {
                        text     : 'Price',
                        width    : 75,
                        sortable : true,
                        renderer : 'usMoney',
                        dataIndex: 'price'
                    },
                    {
                        text     : 'Change',
                        width    : 75,
                        sortable : true,
                        renderer : change,
                        dataIndex: 'change'
                    },
                    {
                        text     : '% Change',
                        width    : 75,
                        sortable : true,
                        renderer : pctChange,
                        dataIndex: 'pctChange'
                    },
                    {
                        text     : 'Last Updated',
                        width    : 85,
                        sortable : true,
                        renderer : Ext.util.Format.dateRenderer('m/d/Y'),
                        dataIndex: 'lastChange'
                    }
                ],
                height: 350,
                width: 600,
                title: 'Array Grid with Print Option',
                tbar: [{
                    text: 'Print',
                    iconCls: 'icon-print',
                    handler : function(){
                        Ext.ux.grid.Printer.printAutomatically = false;
                        Ext.ux.grid.Printer.print(grid);
                    }
                }],
                renderTo: Ext.getBody()
            });
            function change(val) {
                if (val > 0) {
                    return '<span style="color:green;">' + val + '</span>';
                } else if (val < 0) {
                    return '<span style="color:red;">' + val + '</span>';
                }
                return val;
            }
            function pctChange(val) {
                if (val > 0) {
                    return '<span style="color:green;">' + val + '%</span>';
                } else if (val < 0) {
                    return '<span style="color:red;">' + val + '%</span>';
                }
                return val;
            }

            Ext.QuickTips.init();

        });
    </script>

print.css(不需要)

html,body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,p,blockquote,th,td{margin:0;padding:0;}
img,body,html{border:0;}
address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal;}
ol,ul {list-style:none;}caption,th {text-align:left;}h1,h2,h3,h4,h5,h6{font-size:100%;}q:before,q:after{content:'';}

table {
  width: 100%;
  text-align: left;
  font-size: 11px;
  font-family: arial;
  border-collapse: collapse;
}

table th {
  padding: 4px 3px 4px 5px;
  border: 1px solid #d0d0d0;
  border-left-color: #eee;
  background-color: #ededed;
}

table td {
  padding: 4px 3px 4px 5px;
  border-style: none solid solid;
  border-width: 1px;
  border-color: #ededed;
}

print.js

/**
 * @class Ext.ux.grid.Printer
 * @author Ed Spencer (edward@domine.co.uk)
 * Helper class to easily print the contents of a grid. Will open a new window with a table where the first row
 * contains the headings from your column model, and with a row for each item in your grid's store. When formatted
 * with appropriate CSS it should look very similar to a default grid. If renderers are specified in your column
 * model, they will be used in creating the table. Override headerTpl and bodyTpl to change how the markup is generated
 * 
 * Usage:
 * 
 * 1 - Add Ext.Require Before the Grid code
 * Ext.require([
 *   'Ext.ux.grid.GridPrinter',
 * ]);
 * 
 * 2 - Declare the Grid 
 * var grid = Ext.create('Ext.grid.Panel', {
 *   columns: //some column model,
 *   store   : //some store
 * });
 * 
 * 3 - Print!
 * Ext.ux.grid.Printer.mainTitle = 'Your Title here'; //optional
 * Ext.ux.grid.Printer.print(grid);
 * 
 * Original url: http://edspencer.net/2009/07/printing-grids-with-ext-js.html
 * 
 * Modified by Loiane Groner (me@loiane.com) - September 2011 - Ported to Ext JS 4
 * http://loianegroner.com (English)
 * http://loiane.com (Portuguese)
 * 
 * Modified by Paulo D.G. (my classmate of the job) - Março 2012
 * 
 * Modified by Beto Lima - March 2012 - Ported to Ext JS 4
 * 
 * Modified by Beto Lima - 2012-04-02 - Ported to Ext JS 4
 * 
 */
Ext.define("Ext.ux.grid.Printer", {
    
    requires: 'Ext.XTemplate',

    statics: {
        /**
         * Prints the passed grid. Reflects on the grid's column model to build a table, and fills it using the store
         * @param {Ext.grid.Panel} grid The grid to print
         */
        print: function(grid) {
            //We generate an XTemplate here by using 2 intermediary XTemplates - one to create the header,
            //the other to create the body (see the escaped {} below)
            var columns = grid.columns;

            //build a useable array of store data for the XTemplate
            var data = [];
            grid.store.data.each(function(item, row) {
                var convertedData = [];

                //apply renderers from column model
                for (var key in item.data) {
                    var value = item.data[key];

                    Ext.each(columns, function(column, col) {
                        if (column.dataIndex == key) {
                             /*
                             * TODO: add the meta to template
                             */
                            var meta = {item: '', tdAttr: '', style: ''};
                            convertedData[key] = column.renderer ? column.renderer.call(grid, value, meta, item, row, col, grid.store, grid.view) : value;
                        }
                    }, this);
                }

                data.push(convertedData);
            });

            //use the headerTpl and bodyTpl markups to create the main XTemplate below
            var headings = Ext.create('Ext.XTemplate', this.headerTpl).apply(columns);
            var body     = Ext.create('Ext.XTemplate', this.bodyTpl).apply(columns);
            
            //Button print and close at the page (optional)
            var btnPrint = '<button type="button" οnclick="javascript:window.location.reload(true);window.print(true);">Print</button> <button type="button" οnclick="javascript:window.close();">Close</button><hr />';
            
            //Here because inline styles using CSS, the browser did not show the correct formatting of the data the first time that loaded
            var stylesInLine = 
                    'html,body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,p,blockquote,th,td{margin:0;padding:0;}' +
                    'img,body,html{border:0;margin:10px}' +
                    'address,caption,cite,code,dfn,em,strong,th,var{font-style:normal;font-weight:normal;}' +
                    'ol,ul {list-style:none;}caption,th {text-align:left;}h1,h2,h3,h4,h5,h6{font-size:100%;}q:before,q:after{content:"";}' +
                    'table {' +
                    '  width: 100%;' +
                    '  text-align: left;' +
                    '  font-size: 11px;' +
                    '  font-family: arial;' +
                    '  border-collapse: collapse;' +
                    '}' +
                    'table th {' +
                    '  padding: 4px 3px 4px 5px;' +
                    '  border: 1px solid #d0d0d0;' +
                    '  border-left-color: #eee;' +
                    '  background-color: #ededed;' +
                    '}' +
                    'table td {' +
                    '  padding: 4px 3px 4px 5px;' +
                    '  border-style: none solid solid;' +
                    '  border-width: 1px;' +
                    '  border-color: #ededed;' +
                    '}' +
                    '@media print{#noprint{display:none;}body{background:#fff;}}';
            
            var htmlMarkup = [
                '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
                '<html>',
                  '<head>',
                    '<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />',
                    '<style type="text/css">',
                        stylesInLine,
                    '</style>',
                    '<title>' + grid.title + '</title>',
                  '</head>',
                  '<body>',
                  '<div id="noprint">' + btnPrint + '</div>',
                  '<div>' + this.mainTitle + '</div>',
                    '<table>',
                      headings,
                      '<tpl for=".">',
                        body,
                      '</tpl>',
                    '</table>',
                  '</body>',
                '</html>'           
            ];

            var html = Ext.create('Ext.XTemplate', htmlMarkup).apply(data); 

            //open up a new printing window, write to it, print it and close
            // use: window.open('') if you want to always open in a new window
            var win = window.open('', 'printgrid');
            
            //fixed the problem that every call to print, the content is duplicated on the page.
            win.document.body.innerHTML = "";

            win.document.write(html);
            
            //force stop the document
            //fixed the problem where the page stayed loading without stop the content already downloaded with the screen.
            if(win.stop !== undefined) {
                 //Mozilla
                 win.stop();
            } else if(document.execCommand !== undefined) {
                 //Internet Explorer
                 window.document.execCommand('Stop');
            }            

            //An attempt to correct the print command to the IE browser
            if (this.printAutomatically){
                if(Ext.isIE){
                    window.print();
                } else {
                    win.print();
                }
            }
            
            //Another way to set the closing of the main
            if (this.closeAutomaticallyAfterPrint){
                if(Ext.isIE){
                    window.close();
                } else {
                    win.close();
                }                
            }
        },

        /**
         * @property stylesheetPath
         * @type String
         * The path at which the print stylesheet can be found (defaults to 'ux/grid/gridPrinterCss/print.css')
         */
        stylesheetPath: 'ux/grid/gridPrinterCss/print.css',
        
        /**
         * @property printAutomatically
         * @type Boolean
         * True to open the print dialog automatically and close the window after printing. False to simply open the print version
         * of the grid (defaults to false)
         */
        printAutomatically: false,
        
        /**
         * @property closeAutomaticallyAfterPrint
         * @type Boolean
         * True to close the window automatically after printing.
         * (defaults to false)
         */
        closeAutomaticallyAfterPrint: false,        
        
        /**
         * @property mainTitle
         * @type String
         * Title to be used on top of the table
         * (defaults to empty)
         */
        mainTitle: '',        
        
        /**
         * @property headerTpl
         * @type {Object/Array} values
         * The markup used to create the headings row. By default this just uses <th> elements, override to provide your own
         */
        headerTpl: [ 
            '<tr>',
                '<tpl for=".">',
                    '<th>{text}</th>',
                '</tpl>',
            '</tr>'
        ],

        /**
         * @property bodyTpl
         * @type {Object/Array} values
         * The XTemplate used to create each row. This is used inside the 'print' function to build another XTemplate, to which the data
         * are then applied (see the escaped dataIndex attribute here - this ends up as "{dataIndex}")
         */
        bodyTpl: [
            '<tr>',
                '<tpl for=".">',
                    '<td>\{{dataIndex}\}</td>',
                '</tpl>',
            '</tr>'
        ]
    }
});
View Code

 

转载于:https://www.cnblogs.com/zfzf1/p/6690818.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值