`

extjs4 gird打印插件

 
阅读更多

Ed Spencer created a plugin that is capable of creating a print version of an ExtJS grid . This plugin was originally created for ExtJS 3.x. I ported it to ExtJS 4, in case someone need it.

The plugin can be downloaded on the following link:  https://github.com/loiane/extjs4-ux-gridprinter/archives/master

The zip file contains the source code of the plugin plus an example of how to use it. To run the example page, simply open it on any browser (you will need an internet connection).

To use the plugin in your project, copy the ux folder and paste it on your project, as the following sample project I created:

Plugin Code:

/**
 * @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.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)
 */
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) {
				var convertedData = [];

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

					Ext.each(columns, function(column) {
						if (column.dataIndex == key) {
							convertedData[key] = column.renderer ? column.renderer(value) : 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);

			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" />',
				    '<link href="' + this.stylesheetPath + '" rel="stylesheet" type="text/css" media="screen,print" />',
				    '<title>' + grid.title + '</title>',
				  '</head>',
				  '<body>',
				    '<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
			var win = window.open('', 'printgrid');

			win.document.write(html);

			if (this.printAutomatically){
				win.print();
				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 true)
		 */
		printAutomatically: true,

		/**
		 * @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>'
		]
	}
});

 

Usage:

To use the plugin you can create a button and in the handler function you can call the static function of the plugin (you need to pass a grid instance as argument to the print function).

 

Ext.Loader.setConfig({enabled: true});

Ext.require([
    'Ext.grid.*',
    'Ext.data.*',
    'Ext.ux.grid.Printer',
]);

Ext.onReady(function() {

    // sample static data for the store
    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'],
        ['McDonalds 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']
    ];

    /**
     * Custom function used for column renderer
     * @param {Object} val
     */
    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;
    }

    /**
     * Custom function used for column renderer
     * @param {Object} 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;
    }

    // create the data store
    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
    });

    // create the Grid
    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',
        renderTo: Ext.getBody(),
        tbar: [{
            text: 'Print',
            iconCls: 'icon-print',
            handler : function(){
            	Ext.ux.grid.Printer.printAutomatically = false;
            	Ext.ux.grid.Printer.print(grid);
            }
        }]
    });
});
 

There are some options you can customize, such as the stylesheet path and the printAutomatically.

And when we execute the code above, we will get a grid with a print button like the following:

And when we click on the Print button, a new page will be opened with the following content:

Demo

Demo:  http://loianegroner.com/extjs/examples/extjs4-ux-gridprinter/

Github repository:  https://github.com/loiane/extjs4-ux-gridprinter

The original plugin (ExtJS 3.x) – by Ed Spencer:   http://edspencer.net/2009/07/printing-grids-with-ext-js.html

Happy Coding! :)

 

分享到:
评论

相关推荐

    extjs4打印grid插件

    ExtJS4是一款强大的JavaScript框架,用于构建富客户端Web应用程序。Grid是ExtJS中的核心组件,它提供了一种灵活的方式来展示和操作数据集。在ExtJS4中,有时我们需要实现打印Grid的功能,以便用户能够将屏幕上的数据...

    extjs中利用htmleditor与第三方打印插件Lodop结合使用WEB打印功能

    在EXTJS 3.4版本的应用中,集成第三方打印插件Lodop可以实现便捷的Web打印功能。Lodop是一款高效、易用的网页打印控件,它提供了丰富的打印选项和灵活的操作方式,适用于各种复杂的打印需求。本文将详细介绍如何在...

    spket extjs4提示的插件

    spket 安装 extjs4.0提示的 插件

    Eclipse安装Extjs3.2的spket插件(附插件和Ext文件)

    在本文中,我们将详细介绍如何在Eclipse环境中安装适用于ExtJS 3.2的Spket插件,以便于JavaScript开发和代码提示。首先,让我们了解一下Eclipse、ExtJS和Spket这三个关键概念。 Eclipse是一款开源的集成开发环境...

    extJs3升级extjs4方案

    ExtJS3 升级到 ExtJS4 方案 ExtJS3 升级到 ExtJS4 需要修改大量代码,主要是因为 ExtJS4 配备了一类新的系统,不向后兼容。在 ExtJS 3 里生成表的几个框架组件,ExtJS4 大多生成 div,这使得 CSS classes 将会失败...

    ExtJs搜索控件、插件

    在ExtJS中,搜索控件和插件是提升用户体验、实现高效数据查找的关键元素。本篇将深入探讨这些知识点,以帮助你更好地理解和应用。 首先,我们要了解`SearchField.js`在这个上下文中的作用。通常,这是一个自定义...

    EXTJS4.1计算器插件

    由于开发WEB需要一个WEB计算器插件,在网上找EXTJS4计算器插件没有一个,找extjs4.0计算器找到一个,但由于代码太多,在主界面上写太多代码,自我感觉以后看起来吃力,思路一下子不好摸到。因此写了这个插件,分享给...

    完整的Extjs4 htmleditor上传图片插件(包括实例和用法)

    本资源提供了一个完整的ExtJS4 htmleditor图片上传插件,包括前端和后端的实现代码,对于开发者来说是一份非常有价值的参考资料。 首先,我们来看`htmleditor`组件。在ExtJS4中,`Ext.form.field.HtmlEditor`是HTML...

    ExtJS4 Spekt代码补全插件

    请下载的朋友注意看软件说明哦。 1,官方下载最新的ExtJS4.0.2版本,地址:http://extjs.cachefly.net/ext-4.0.2-gpl.zip 2,解压缩ExtJS4.0.2 ...4,Eeclipse中Spket关联这个文件即可实现代码提示。 Good luck.

    简洁的EXTJS日期选择插件.rar

    一款简洁的外观基于EXTJS的日期选择插件,日历插件,在网页上选择日期使用的小插件,按照ext DatePicker素材及思想简化重新实现日历选择器,尚未实现:键盘导航,小时分钟选择,  1.Date api ,某日属于周几,某月...

    extjs-ux, EXT JS 4的一些插件和扩展.zip

    extjs-ux, EXT JS 4的一些插件和扩展 插件和 EXT JS 4扩展 Ext.ux. aceeditor.Panel 演示( 简单): 链接演示( 流 语法): 链接演示:链接论坛:链接 Ext.ux. grid.feature.Tileview 演示:链接

    eclipse安装extjs插件

    4. **配置插件**: 安装完成后,可能需要进行一些配置。这可能包括设置ExtJS库的位置,以便插件可以正确识别和提供代码补全、错误检查等功能。在Eclipse的首选项或首选项设置中,找到与新安装插件相关的配置选项。 ...

    extjs插件开发教程

    本教程将深入探讨如何开发ExtJS插件,以及通过实例来理解插件的运用。 首先,我们要明白什么是ExtJS插件。插件是包含特定功能的一段代码,它可以注入到ExtJS的组件中,以添加新的行为或修改现有组件的功能。开发...

    js jquery extjs myeclipse 代码提示插件安装及安装步骤

    js jquery extjs myeclipse 代码提示插件安装及安装步骤js jquery extjs myeclipse 代码提示插件安装及安装步骤js jquery extjs myeclipse 代码提示插件安装及安装步骤js jquery extjs myeclipse 代码提示插件安装及...

    Extjs相关插件

    4. 树形插件:`Ext.tree.plugin.TreeDragDrop`允许在树形结构中进行拖放操作,实现节点的移动和排序。 5. 动画插件:如`Ext.fx.Anim`,为组件添加动画效果,提升用户体验。 三、如何使用ExtJS 插件 1. 引入插件:在...

    extjs2.0.2及eclipse插件spket

    在实际开发过程中,利用Eclipse的Spket插件和ExtJS 2.0.2库,开发者可以构建出具有复杂交互和美观界面的Web应用。例如,可以通过ExtJS的GridPanel展示数据,使用FormPanel处理用户输入,结合Store和Proxy进行数据的...

    EXTJS4自学手册

    目录: 一 Extjs 基础 EXTJS4自学手册——EXT文件目录,本地加载文档,命名规范 ...EXTJS4自学手册——页面控件(表格的插件) EXTJS4自学手册——页面控件(树形控件) EXTJS4自学手册——页面控件(表单控件)

    包含各种类型的extjs小图标,Extjs4小图标

    在标题和描述中提到的“Extjs4小图标”指的是ExtJS 4版本中使用的一系列图形图标,这些图标用于增强应用程序的视觉效果,提供用户友好的操作指示。 1. **图标分类**: - 图标通常分为不同的类别,如操作图标(比如...

    ExtJS4多文件上传,带进度条及管理

    在ExtJS4中,可以使用自定义组件或者第三方插件来实现文件上传功能。uploadPanel是一个常见的组件,它提供了一个用户友好的界面,包括文件选择、上传按钮、取消和暂停选项,以及关键的进度条展示。 **四、swfupload...

    extjs grid 多表头插件

    多表头插件是ExtJS Grid的一个重要特性,它允许我们创建具有多层次、复杂结构的表头,以便更好地组织和呈现数据。在ExtJS Grid中,多表头能够帮助用户更清晰地理解列的分组和关系,提高数据的可读性和分析性。 首先...

Global site tag (gtag.js) - Google Analytics