Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
3234 mandeep.dh 1
/* Compile using: mxmlc --target-player=10.0.0 -static-link-runtime-shared-libraries=true -library-path+=lib ZeroClipboardPdf.as */
2
package {
3
	import flash.display.Stage;
4
	import flash.display.Sprite;
5
	import flash.display.LoaderInfo;
6
	import flash.display.StageScaleMode;
7
	import flash.events.*;
8
	import flash.display.StageAlign;
9
	import flash.display.StageScaleMode;
10
	import flash.external.ExternalInterface;
11
	import flash.system.Security;
12
	import flash.utils.*;
13
	import flash.system.System;
14
	import flash.net.FileReference;
15
	import flash.net.FileFilter;
16
 
17
	/* PDF imports */
18
	import org.alivepdf.pdf.PDF;
19
	import org.alivepdf.data.Grid;
20
	import org.alivepdf.data.GridColumn;
21
	import org.alivepdf.layout.Orientation;
22
	import org.alivepdf.layout.Size;
23
	import org.alivepdf.layout.Unit;
24
	import org.alivepdf.display.Display;
25
	import org.alivepdf.saving.Method;
26
	import org.alivepdf.fonts.FontFamily;
27
	import org.alivepdf.fonts.Style;
28
	import org.alivepdf.fonts.CoreFont;
29
	import org.alivepdf.colors.RGBColor;
30
 
31
	public class ZeroClipboard extends Sprite {
32
 
33
		private var domId:String = '';
34
		private var button:Sprite;
35
		private var clipText:String = 'blank';
36
		private var fileName:String = '';
37
		private var action:String = 'copy';
38
		private var incBom:Boolean = true;
39
		private var charSet:String = 'utf8';
40
 
41
 
42
		public function ZeroClipboard() {
43
			// constructor, setup event listeners and external interfaces
44
			stage.scaleMode = StageScaleMode.EXACT_FIT;
45
			flash.system.Security.allowDomain("*");
46
 
47
			// import flashvars
48
			var flashvars:Object = LoaderInfo( this.root.loaderInfo ).parameters;
49
			domId = flashvars.id;
50
 
51
			// invisible button covers entire stage
52
			button = new Sprite();
53
			button.buttonMode = true;
54
			button.useHandCursor = true;
55
			button.graphics.beginFill(0x00FF00);
56
			button.graphics.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
57
			button.alpha = 0.0;
58
			addChild(button);
59
 
60
			button.addEventListener(MouseEvent.CLICK, function(event:Event):void {
61
				clickHandler(event);
62
			} );
63
			button.addEventListener(MouseEvent.MOUSE_OVER, function(event:Event):void {
64
				ExternalInterface.call( 'ZeroClipboard.dispatch', domId, 'mouseOver', null );
65
			} );
66
			button.addEventListener(MouseEvent.MOUSE_OUT, function(event:Event):void {
67
				ExternalInterface.call( 'ZeroClipboard.dispatch', domId, 'mouseOut', null );
68
			} );
69
			button.addEventListener(MouseEvent.MOUSE_DOWN, function(event:Event):void {
70
				ExternalInterface.call( 'ZeroClipboard.dispatch', domId, 'mouseDown', null );
71
			} );
72
			button.addEventListener(MouseEvent.MOUSE_UP, function(event:Event):void {
73
				ExternalInterface.call( 'ZeroClipboard.dispatch', domId, 'mouseUp', null );
74
			} );
75
 
76
			/* External functions
77
			 * This is extremely nasty, and I'm far from proud of this, however, when a Flash
78
			 * movie is hidden in IE (i.e. display:none) then all callbacks are removed, and there
79
			 * is no way to tell that this has happened! Javascript can't tell us since there are
80
			 * no callbacks - so we need to add them again and again... Fortunatly Flash doesn't
81
			 * allow multiple callback functions to be used with each callback name, it just uses
82
			 * the provided function, so the only thing we use for this workaround is a couple of
83
			 * clock cycles.
84
			 */
85
			addCallbacks();
86
			setInterval( addCallbacks, 1000 );
87
 
88
			// signal to the browser that we are ready
89
			ExternalInterface.call( 'ZeroClipboard.dispatch', domId, 'load', null );
90
		}
91
 
92
		public function addCallbacks ():void {
93
			ExternalInterface.addCallback("setHandCursor", setHandCursor);
94
			ExternalInterface.addCallback("clearText", clearText);
95
			ExternalInterface.addCallback("setText", setText);
96
			ExternalInterface.addCallback("appendText", appendText);
97
			ExternalInterface.addCallback("setFileName", setFileName);
98
			ExternalInterface.addCallback("setAction", setAction);
99
			ExternalInterface.addCallback("setCharSet", setCharSet);
100
			ExternalInterface.addCallback("setBomInc", setBomInc);
101
		}
102
 
103
 
104
		public function setCharSet(newCharSet:String):void {
105
			if ( newCharSet == 'UTF16LE' ) {
106
				charSet = newCharSet;
107
			} else {
108
				charSet = 'UTF8';
109
			}
110
		}
111
 
112
		public function setBomInc(newBomInc:Boolean):void {
113
			incBom = newBomInc;
114
		}
115
 
116
		public function clearText():void {
117
			clipText = '';
118
		}
119
 
120
		public function appendText(newText:String):void {
121
			clipText += newText;
122
		}
123
 
124
		public function setText(newText:String):void {
125
			clipText = newText;
126
		}
127
 
128
		public function setFileName(newFileName:String):void {
129
			fileName = newFileName;
130
		}
131
 
132
		public function setAction(newAction:String):void {
133
			action = newAction;
134
		}
135
 
136
		public function setHandCursor(enabled:Boolean):void {
137
			// control whether the hand cursor is shown on rollover (true)
138
			// or the default arrow cursor (false)
139
			button.useHandCursor = enabled;
140
		}
141
 
142
 
143
		private function clickHandler(event:Event):void {
144
			var fileRef:FileReference = new FileReference();
145
			fileRef.addEventListener(Event.COMPLETE, saveComplete);
146
 
147
			if ( action == "save" ) {
148
				/* Save as a file */
149
				if ( charSet == 'UTF16LE' ) {
150
					fileRef.save( strToUTF16LE(clipText), fileName );
151
				} else {
152
					fileRef.save( strToUTF8(clipText), fileName );
153
				}
154
			} else if ( action == "pdf" ) {
155
				/* Save as a PDF */
156
				var pdf:PDF = configPdf();
157
				fileRef.save( pdf.save( Method.LOCAL ), fileName );
158
			} else {
159
				/* Copy the text to the clipboard. Note charset and BOM have no effect here */
160
				System.setClipboard( clipText );
161
				ExternalInterface.call( 'ZeroClipboard.dispatch', domId, 'complete', clipText );
162
			}
163
		}
164
 
165
 
166
		private function saveComplete(event:Event):void {
167
			ExternalInterface.call( 'ZeroClipboard.dispatch', domId, 'complete', clipText );
168
		}
169
 
170
 
171
		private function getProp( prop:String, opts:Array ):String
172
		{
173
			var i:int, iLen:int;
174
			for ( i=0, iLen=opts.length ; i<iLen ; i++ )
175
			{
176
				if ( opts[i].indexOf( prop+":" ) != -1 )
177
				{
178
					return opts[i].replace( prop+":", "" );
179
				}
180
			}
181
			return "";
182
		}
183
 
184
 
185
		private function configPdf():PDF
186
		{
187
			var
188
				pdf:PDF,
189
				i:int, iLen:int,
190
				splitText:Array    = clipText.split("--/TableToolsOpts--\n"),
191
				opts:Array         = splitText[0].split("\n"),
192
				dataIn:Array       = splitText[1].split("\n"),
193
				aColRatio:Array    = getProp( 'colWidth', opts ).split('\t'),
194
				title:String       = getProp( 'title', opts ),
195
				message:String     = getProp( 'message', opts ),
196
				orientation:String = getProp( 'orientation', opts ),
197
				size:String        = getProp( 'size', opts ),
198
				iPageWidth:int     = 0,
199
				dataOut:Array      = [],
200
				columns:Array      = [],
201
				headers:Array,
202
				y:int = 0;
203
 
204
			/* Create the PDF */
205
			pdf = new PDF( Orientation[orientation.toUpperCase()], Unit.MM, Size[size.toUpperCase()] );
206
			pdf.setDisplayMode( Display.FULL_WIDTH );
207
			pdf.addPage();
208
			iPageWidth = pdf.getCurrentPage().w-20;
209
			pdf.textStyle( new RGBColor(0), 1 );
210
 
211
			/* Add the title / message if there is one */
212
			pdf.setFont( new CoreFont(FontFamily.HELVETICA), 14 );
213
			if ( title != "" )
214
			{
215
				pdf.writeText(11, title+"\n");
216
			}
217
 
218
			pdf.setFont( new CoreFont(FontFamily.HELVETICA), 11 );
219
			if ( message != "" )
220
			{
221
				pdf.writeText(11, message+"\n");
222
			}
223
 
224
			/* Data setup. Split up the headers, and then construct the columns */
225
			for ( i=0, iLen=dataIn.length ; i<iLen ; i++ )
226
			{
227
				if ( dataIn[i] != "" )
228
				{
229
					dataOut.push( dataIn[i].split("\t") );
230
				}
231
			}
232
			headers = dataOut.shift();
233
 
234
			for ( i=0, iLen=headers.length ; i<iLen ; i++ )
235
			{
236
				columns.push( new GridColumn( " \n"+headers[i]+"\n ", i.toString(), aColRatio[i]*iPageWidth, 'C' ) );
237
			}
238
 
239
			var grid:Grid = new Grid(
240
				dataOut,                  /* 1. data */
241
				iPageWidth,               /* 2. width */
242
				100,                      /* 3. height */
243
				new RGBColor (0xE0E0E0),  /* 4. headerColor */
244
				new RGBColor (0xFFFFFF),  /* 5. backgroundColor */
245
				true,                     /* 6. alternateRowColor */
246
				new RGBColor ( 0x0 ),     /* 7. borderColor */
247
				.1,                       /* 8. border alpha */
248
				null,                     /* 9. joins */
249
				columns                   /* 10. columns */
250
			);
251
 
252
			pdf.addGrid( grid, 0, y );
253
			return pdf;
254
		}
255
 
256
 
257
		/*
258
		 * Function: strToUTF8
259
		 * Purpose:  Convert a string to the output utf-8
260
		 * Returns:  ByteArray
261
		 * Inputs:   String
262
		 */
263
		private function strToUTF8( str:String ):ByteArray {
264
			var utf8:ByteArray = new ByteArray();
265
 
266
			/* BOM first */
267
			if ( incBom ) {
268
				utf8.writeByte( 0xEF );
269
				utf8.writeByte( 0xBB );
270
				utf8.writeByte( 0xBF );
271
			}
272
			utf8.writeUTFBytes( str );
273
 
274
			return utf8;
275
		}
276
 
277
 
278
		/*
279
		 * Function: strToUTF16LE
280
		 * Purpose:  Convert a string to the output utf-16
281
		 * Returns:  ByteArray
282
		 * Inputs:   String
283
		 * Notes:    The fact that this function is needed is a little annoying. Basically, strings in
284
		 *   AS3 are UTF-16 (with surrogate pairs and everything), but characters which take up less
285
		 *   than 8 bytes appear to be stored as only 8 bytes. This function effective adds the 
286
		 *   padding required, and the BOM
287
		 */
288
		private function strToUTF16LE( str:String ):ByteArray {
289
			var utf16:ByteArray = new ByteArray();
290
			var iChar:uint;
291
			var i:uint=0, iLen:uint = str.length;
292
 
293
			/* BOM first */
294
			if ( incBom ) {
295
				utf16.writeByte( 0xFF );
296
				utf16.writeByte( 0xFE );
297
			}
298
 
299
			while ( i < iLen ) {
300
				iChar = str.charCodeAt(i);
301
 
302
				if ( iChar < 0xFF ) {
303
					/* one byte char */
304
					utf16.writeByte( iChar );
305
					utf16.writeByte( 0 );
306
				} else {
307
					/* two byte char */
308
					utf16.writeByte( iChar & 0x00FF );
309
					utf16.writeByte( iChar >> 8 );
310
				}
311
 
312
				i++;
313
			}
314
 
315
			return utf16;
316
		}
317
	}
318
}