Adobe® Flex® 4 Language Reference
Hide Packages and Classes List |  Packages  |  Classes  |  Index  |  Appendixes
flash.printing 
PrintJob 
Packageflash.printing
Classpublic class PrintJob
InheritancePrintJob Inheritance EventDispatcher Inheritance Object

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9

The PrintJob class lets you create content and print it to one or more pages. This class lets you render content that is visible, dynamic or off-screen to the user, prompt users with a single Print dialog box, and print an unscaled document with proportions that map to the proportions of the content. This capability is especially useful for rendering and printing dynamic content, such as database content and dynamic text.

Use the PrintJob() constructor to create a print job.

Additionally, with properties populated by PrintJob.start(), your document can read your user's printer settings, such as page height, width, and image orientation, and you can configure your document to format, dynamically, Flash content that is appropriate for the printer settings. The user layout properties populated by PrintJob.start() are read-only and cannot be changed by Flash Player.

Note: ActionScript 3.0 does not restrict a PrintJob object to a single frame (as did previous versions of ActionScript). However, since the operating system displays print status information to the user after the user has clicked the OK button in the Print dialog box, you should call PrintJob.addPage() and PrintJob.send() as soon as possible to send pages to the spooler. A delay reaching the frame containing the PrintJob.send() call will delay the printing process.

Additionally, a 15 second script timeout limit applies to the following intervals:

  • PrintJob.start() and the first PrintJob.addPage()
  • PrintJob.addPage() and the next PrintJob.addPage()
  • The last PrintJob.addPage() and PrintJob.send()

If any of the above intervals span more than 15 seconds, the next call to PrintJob.start() on the PrintJob instance returns false, and the next PrintJob.addPage() on the PrintJob instance causes the Flash Player or Adobe AIR to throw a runtime exception.

View the examples



Public Properties
 PropertyDefined By
 Inheritedconstructor : Object
A reference to the class object or constructor function for a given object instance.
Object
  orientation : String
[read-only] The image orientation for printing.
PrintJob
  pageHeight : int
[read-only] The height of the actual printable area on the page, in points.
PrintJob
  pageWidth : int
[read-only] The width of the actual printable area on the page, in points.
PrintJob
  paperHeight : int
[read-only] The overall paper height, in points.
PrintJob
  paperWidth : int
[read-only] The overall paper width, in points.
PrintJob
 Inheritedprototype : Object
[static] A reference to the prototype object of a class or function object.
Object
Public Methods
 MethodDefined By
  
Creates a PrintJob object that you can use to print one or more pages.
PrintJob
 Inherited
addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
Registers an event listener object with an EventDispatcher object so that the listener receives notification of an event.
EventDispatcher
  
addPage(sprite:Sprite, printArea:Rectangle = null, options:PrintJobOptions = null, frameNum:int = 0):void
Sends the specified Sprite object as a single page to the print spooler.
PrintJob
 Inherited
Dispatches an event into the event flow.
EventDispatcher
 Inherited
Checks whether the EventDispatcher object has any listeners registered for a specific type of event.
EventDispatcher
 Inherited
Indicates whether an object has a specified property defined.
Object
 Inherited
Indicates whether an instance of the Object class is in the prototype chain of the object specified as the parameter.
Object
 Inherited
Indicates whether the specified property exists and is enumerable.
Object
 Inherited
removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void
Removes a listener from the EventDispatcher object.
EventDispatcher
  
Sends spooled pages to the printer after PrintJob.start() and PrintJob.addPage() have been successful.
PrintJob
 Inherited
Sets the availability of a dynamic property for loop operations.
Object
  
Displays the operating system's Print dialog box, starts spooling, and sets the PrintJob read-only property values.
PrintJob
 Inherited
Returns the string representation of this object, formatted according to locale-specific conventions.
Object
 Inherited
Returns the string representation of the specified object.
Object
 Inherited
Returns the primitive value of the specified object.
Object
 Inherited
Checks whether an event listener is registered with this EventDispatcher object or any of its ancestors for the specified event type.
EventDispatcher
Events
 Event Summary Defined By
 Inherited[broadcast event] Dispatched when the Flash Player or AIR application gains operating system focus and becomes active.EventDispatcher
 Inherited[broadcast event] Dispatched when the Flash Player or AIR application operating loses system focus and is becoming inactive.EventDispatcher
Property Detail

orientation

property
orientation:String  [read-only]

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9.

The image orientation for printing. This property is a value from the PrintJobOrientation class. This property is available only after a call to the PrintJob.start() method has been made.



Implementation
    public function get orientation():String

See also

pageHeight

property 
pageHeight:int  [read-only]

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9.

The height of the actual printable area on the page, in points. Any user-set margins are ignored. This property is available only after a call to the PrintJob.start() method has been made.



Implementation
    public function get pageHeight():int

pageWidth

property 
pageWidth:int  [read-only]

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9.

The width of the actual printable area on the page, in points. Any user-set margins are ignored. This property is available only after a call to the PrintJob.start() method has been made.



Implementation
    public function get pageWidth():int

paperHeight

property 
paperHeight:int  [read-only]

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9.

The overall paper height, in points. This property is available only after a call to the PrintJob.start() method has been made.



Implementation
    public function get paperHeight():int

paperWidth

property 
paperWidth:int  [read-only]

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9.

The overall paper width, in points. This property is available only after a call to the PrintJob.start() method has been made.



Implementation
    public function get paperWidth():int
Constructor Detail

PrintJob

()Constructor
public function PrintJob()

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9

Creates a PrintJob object that you can use to print one or more pages. After you create a PrintJob object, you need to use (in the following sequence) the PrintJob.start(), PrintJob.addPage(), and then PrintJob.send() methods to send the print job to the printer.

For example, you can replace the [params] placeholder text for the my_pj.addPage() method calls with custom parameters as shown in the following code:

 // create PrintJob object
 var my_pj:PrintJob = new PrintJob();
  
 // display Print dialog box, but only initiate the print job
 // if start returns successfully.
 if (my_pj.start()) {
  
    // add specified page to print job
    // repeat once for each page to be printed
    try {
      my_pj.addPage([params]);
    }
    catch(e:Error) {
      // handle error 
    }
    try {
      my_pj.addPage([params]);
    }
    catch(e:Error) {
      // handle error 
    }
 
    // send pages from the spooler to the printer, but only if one or more
    // calls to addPage() was successful. You should always check for successful 
    // calls to start() and addPage() before calling send().
    my_pj.send();
 }
 

You cannot create a second PrintJob object while the first one is still active. If you create a second PrintJob object (by calling new PrintJob()) while the first PrintJob object is still active, the second PrintJob object will not be created. So, you may check for the my_pj value before creating a second PrintJob.


Throws
IllegalOperationError — Throws an exception if another PrintJob object is still active.

See also

Method Detail

addPage

()method
public function addPage(sprite:Sprite, printArea:Rectangle = null, options:PrintJobOptions = null, frameNum:int = 0):void

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9.

Sends the specified Sprite object as a single page to the print spooler. Before using this method, you must create a PrintJob object and then use PrintJob.start(). Then, after calling PrintJob.addPage() one or more times for a print job, you use PrintJob.send() to send the spooled pages to the printer. In other words, after you create a PrintJob object, use (in the following sequence) PrintJob.start(), PrintJob.addPage(), and then PrintJob.send() to send the print job to the printer. You can use PrintJob.addPage() multiple times after a single call to PrintJob.start() to print several pages at once.

If PrintJob.addPage() causes Flash Player to throw an exception (for example, if you haven't called PrintJob.start() or the user canceled the print job), any subsequent calls to PrintJob.addPage() will fail. However, if previous calls to PrintJob.addPage() were successful, the concluding PrintJob.send() command sends the successfully spooled pages to the printer.

If the print job takes more than 15 seconds to complete a PrintJob.addPage() operation, Flash Player will throw an exception on the next Print.addPage() call.

If you pass a value for the printArea parameter, the x and y coordinates of the printArea object map to the upper-left corner (0,0 coordinates) of the printable area on the page. The printable area is described by the read-only pageHeight and pageWidth properties set by PrintJob.start(). Because the printout aligns with the upper-left corner of the printable area on the page, when the area defined in printArea is bigger than the printable area on the page, the printout is cropped to the right or bottom (or both) of the area defined by printArea. If you don't pass a value for printArea and the Stage is larger than the printable area, the same type of clipping occurs. If you don't pass a value for printArea and the screen is larger than the printable area, the same type of clipping takes place.

If you want to scale a Sprite object before you print it, set scale properties (see flash.display.DisplayObject.scaleX and flash.display.DisplayObject.scaleY) before calling this method, and set them back to their original values after printing. The scale of a Sprite object has no relation to printArea. That is, if you specify a print area that is 50 x 50 pixels, 2500 pixels are printed. If you scale the Sprite object, the same 2500 pixels are printed, but the Sprite object is printed at the scaled size.

The Flash Player printing feature supports PostScript and non-PostScript printers. Non-PostScript printers convert vectors to bitmaps.

Parameters

sprite:Sprite — The instance name of the Sprite to print.
 
printArea:Rectangle (default = null) — A Rectangle object that specifies the area to print.

A rectangle's width and height are pixel values. A printer uses points as print units of measurement. Points are a fixed physical size (1/72 inch), but the size of a pixel, onscreen, depends on the resolution of the particular screen. So, the conversion rate between pixels and points depends on the printer settings and whether the sprite is scaled. An unscaled sprite that is 72 pixels wide will print out one inch wide, with one point equal to one pixel, independent of screen resolution.

You can use the following equivalencies to convert inches or centimeters to twips or points (a twip is 1/20 of a point):

  • 1 point = 1/72 inch = 20 twips
  • 1 inch = 72 points = 1440 twips
  • 1 cm = 567 twips

If you omit the printArea parameter, or if it is passed incorrectly, the full area of sprite is printed.

If you don't want to specify a value for printArea but want to specify a value for options or frameNum, pass null for printArea.

 
options:PrintJobOptions (default = null) — An optional parameter that specifies whether to print as vector or bitmap. The default value is null, which represents a request for vector printing. To print sprite as a bitmap, set the printAsBitmap property of the PrintJobOptions object to true. Remember the following suggestions when determining whether to set printAsBitmap to true:
  • If the content that you're printing includes a bitmap image, set printAsBitmap to true to include any alpha transparency and color effects.
  • If the content does not include bitmap images, omit this parameter to print the content in higher quality vector format.

If options is omitted or is passed incorrectly, vector printing is used. If you don't want to specify a value for options but want to specify a value for frameNumber, pass null for options.

Note:Adobe AIR does not support vector printing on Mac OS.

 
frameNum:int (default = 0)An optional number that lets you specify which frame to print; passing a frameNum does not cause the ActionScript on that frame to be invoked. If you omit this parameter, the current frame in sprite is printed. An optional number that is used in the Flash authoring environment. When writing Flex applications, you should omit this parameter or pass a value of 0.

Note: If you previously used print(), printAsBitmap(), printAsBitmapNum(), or printNum() to print from Flash, you might have used a #p frame label on multiple frames to specify which pages to print. To use PrintJob.addPage() to print multiple frames, you must use a PrintJob.addPage() method for each frame; #p frame labels are ignored. For one way to do this programmatically, see the Example section.


Throws
Error — Throws an exception if you haven't called PrintJob.start() or the user canceled the print job

See also

send

()method 
public function send():void

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9.

Sends spooled pages to the printer after PrintJob.start() and PrintJob.addPage() have been successful. Calls to PrintJob.send() will not be successful if the call to PrintJob.start() fails, or PrintJob.addpage() throws an exception. So, you should check for PrintJob.start() to return true, and catch any PrintJob.addpage() exceptions before calling PrintJob.send(). For example:

     var my_pj:PrintJob = new PrintJob();
     if (my_pj.start()) {
       try {
         my_pj.addPage([params]);
       }
       catch(e:Error) {
          // handle error 
       }
     
       my_pj.send();
     }
     

See also

start

()method 
public function start():Boolean

Language Version: ActionScript 3.0
Runtime Versions: AIR 1.0 Flash Player 9., Flash Player 9.

Displays the operating system's Print dialog box, starts spooling, and sets the PrintJob read-only property values. The Print dialog box lets the user change print settings. When the PrintJob.start() method returns successfully (the user clicks OK in the Print dialog box), the following read-only properties are populated, representing the user's current print settings:

PropertyTypeUnitsNotes
PrintJob.paperHeightNumberPointsOverall paper height.
PrintJob.paperWidthNumberPointsOverall paper width.
PrintJob.pageHeightNumberPointsHeight of actual printable area on the page; any user-set margins are ignored.
PrintJob.pageWidthNumberPointsWidth of actual printable area on the page; any user-set margins are ignored.
PrintJob.orientationString"portrait" (flash.printing.PrintJobOrientation.PORTRAIT) or "landscape" (flash.printing.PrintJobOrientation.LANDSCAPE).

Note: If the user cancels the Print dialog box, the properties are not populated.

After the user clicks OK in the Print dialog box, the player begins spooling a print job to the operating system. Because the operating system then begins displaying information to the user about the printing progress, you should call the PrintJob.addPage() and PrintJob.send() calls as soon as possible to send pages to the spooler. You can use the read-only height, width, and orientation properties this method populates to format the printout.

Test to see if this method returns true (when the user clicks OK in the operating system's Print dialog box) before any subsequent calls to PrintJob.addPage() and PrintJob.send():

     var my_pj:PrintJob = new PrintJob();
        if(my_pj.start()) {
          // addPage() and send() statements here
        }
     

For the given print job instance, if any of the following intervals last more than 15 seconds the next call to PrintJob.start() will return false:

  • PrintJob.start() and the first PrintJob.addPage()
  • One PrintJob.addPage() and the next PrintJob.addPage()
  • The last PrintJob.addPage() and PrintJob.send()

Returns
Boolean — A value of true if the user clicks OK when the Print dialog box appears; false if the user clicks Cancel or if an error occurs.

See also

PrintJobExample.as

The following example uses the class PrintJobExample to create a small document and then send the document to the printer. This is accomplished using the following steps:
  1. Declare two variables of type Sprite named sheet1 and sheet2.
  2. Call init(), which assigns a new Sprite instance to both sheet1 and sheet2 and then calls createSheet() using different arguments.
  3. createSheet() does the following:
    1. The Sprite object passed in is used to draw a rectangle with a light-gray background, a one-pixel black border, and that is 100 pixels wide by 200 pixels high at x = 0, y = 0.
    2. A new TextField object is created named txt with the same dimensions as the Sprite, the wordWrap property set to true, and the text property set to the String passed as an argument to createSheet().
    3. If the Object argument passed is not null, create a new Sprite instance named img that is used to draw a white rectangle using the coordinate and dimension properties of the Object passed. The white rectangle is added to the display list of the Sprite object using addChild().
    4. The txt TextField is added to the display list of the Sprite object using addChild().
  4. Back in the constructor, the print method that is enabled (not commented out) is called. Since the methods are very similar, printOnePerPage() is described below.
  5. printOnePerPage() does the following:
    1. Declare a new PrintJob object named pj and pagesToPrint as a uint.
    2. Open the operating system's native print dialog box and wait for user to click OK.
    3. Check the orientation and if Landscape is selected, throw an error and exit.
    4. Set up the page height and width for sheet1 and sheet2.
    5. Send sheet1 and sheet2 to the print spooler using addPage().
    6. If the number of pages to print is > 0, print all spooled pages.
  6. The draw() method is called, which re-sizes the two Sprite properties to fit on the stage and re-positions sheet2 such that it is just right of sheet1.

Note: the constructor is set up such that one of three printing methods (one sheet per page, two sheets per page, or printing on the top half of the page) can be selected, based on preference. This example will not work correctly unless exactly two of the print methods are disabled using code comments. The example is set up such that printOnePerPage() will be called.

package {
    import flash.printing.PrintJob;
    import flash.printing.PrintJobOrientation;
    import flash.display.Stage;
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.geom.Rectangle;
       
    public class PrintJobExample extends Sprite {
        private var sheet1:Sprite;
        private var sheet2:Sprite;
           
        public function PrintJobExample() {
            init();
            printOnePerPage();
//            printTwoPerPage();
//            printTopHalf();
            draw();
        }
        
        private function init():void {
            sheet1 = new Sprite();
            createSheet(sheet1, "Once upon a time...", {x:10, y:50, width:80, height:130});

            sheet2 = new Sprite();
            createSheet(sheet2, "There was a great story to tell, and it ended quickly.\n\nThe end.", null);
        }
        
        private function createSheet(sheet:Sprite, str:String, imgValue:Object):void {
            sheet.graphics.beginFill(0xEEEEEE);
            sheet.graphics.lineStyle(1, 0x000000);
            sheet.graphics.drawRect(0, 0, 100, 200);
            sheet.graphics.endFill();
            
            var txt:TextField = new TextField();
            txt.height = 200;
            txt.width = 100;
            txt.wordWrap = true;
            txt.text = str;
            
            if(imgValue != null) {
                var img:Sprite = new Sprite();
                img.graphics.beginFill(0xFFFFFF);
                img.graphics.drawRect(imgValue.x, imgValue.y, imgValue.width, imgValue.height);
                img.graphics.endFill();
                sheet.addChild(img);
            }
            sheet.addChild(txt);
        }
        
        private function printOnePerPage():void {
            var pj:PrintJob = new PrintJob();
            var pagesToPrint:uint = 0;
            if(pj.start()) {                
                if(pj.orientation == PrintJobOrientation.LANDSCAPE) {    
                    throw new Error("Without embedding fonts you must print one sheet per page with an orientation of portrait.");
                }
                
                sheet1.height = pj.pageHeight;
                sheet1.width = pj.pageWidth;
                sheet2.height = pj.pageHeight;
                sheet2.width = pj.pageWidth;

                try {
                    pj.addPage(sheet1);
                    pagesToPrint++;
                }
                catch(e:Error) {
                    // do nothing
                }

                try {
                    pj.addPage(sheet2);
                    pagesToPrint++;
                }
                catch(e:Error) {
                    // do nothing
                }

                if(pagesToPrint > 0) {
                    pj.send();
                }
            }
        }
        
        private function printTwoPerPage():void {
            var pj:PrintJob = new PrintJob();
            var pagesToPrint:uint = 0;
            if(pj.start()) {                
                if(pj.orientation == PrintJobOrientation.PORTRAIT) {
                    throw new Error("Without embedding fonts you must print two sheets per page with an orientation of landscape.");
                }
                
                sheet1.height = pj.pageHeight;
                sheet1.width = pj.pageWidth/2;
                sheet2.height = pj.pageHeight;
                sheet2.width = pj.pageWidth/2;

                var sheets:Sprite = new Sprite();
                sheets.addChild(sheet1);
                sheets.addChild(sheet2);
                sheets.getChildAt(1).x = sheets.getChildAt(0).width;
                try {
                    pj.addPage(sheets);
                    pagesToPrint++;
                }
                catch(e:Error) {
                    // do nothing
                }

                if(pagesToPrint > 0) {
                    pj.send();
                }
            }
        }

        private function printTopHalf():void {
            var pj:PrintJob = new PrintJob();
            var pagesToPrint:uint = 0;
            if(pj.start()) {                
                if(pj.orientation == PrintJobOrientation.PORTRAIT) {
                    throw new Error("Without embedding fonts you must print the top half with an orientation of landscape.");
                }
                
                sheet1.height = pj.pageHeight;
                sheet1.width = pj.pageWidth/2;
                sheet2.height = pj.pageHeight;
                sheet2.width = pj.pageWidth/2;

                var sheets:Sprite = new Sprite();
                sheets.addChild(sheet1);
                sheets.addChild(sheet2);
                sheets.getChildAt(1).x = sheets.getChildAt(0).width;
                try {
                    pj.addPage(sheets, new Rectangle(0, 0, sheets.width, sheets.height/2));
                    pagesToPrint++;
                }
                catch(e:Error) {
                    // do nothing
                }

                if(pagesToPrint > 0) {
                    pj.send();
                }
            }
        }


        private function draw():void {
            var sheetWidth:Number = this.stage.stageWidth/2;
            var sheetHeight:Number = this.stage.stageHeight;
            
            addChild(sheet1);
            sheet1.width = sheetWidth;
            sheet1.height = sheetHeight;
            
            addChild(sheet2);
            sheet2.width = sheetWidth;
            sheet2.height = sheetHeight;
            sheet2.x = sheet1.width;
        }        
    }
}