Sunday, June 5, 2011

Printing in AS3: Part 2

Today we will continue learning about printing in AS3.

Last time we've learned the basic methods of the PrintJob class.

We've learned that we need to create the PrintJob object, then call start(), addPage() and send() methods in that order. This works alright, but what if the user decides to cancel the print job? We need to see if the PrintJob.start() method returns true before we call addPage() and send() methods, in case that user actually cancels the printing.

This is done with a simple if conditional:

if (myPrintJob.start()){
myPrintJob.addPage(mySprite);
myPrintJob.send();
}
else{
trace("Print job canceled.");
}

This way, we will see if the start() method is successful (the user doesn't cancel the print job) before calling the other 2 functions.

The addPage() method can cause problems too. For example, if the object that we're passing as the parameter doesn't extend Sprite class, the method will throw an error. We can handle it using the try..catch operator.

if (myPrintJob.start()){

try{
myPrintJob.addPage(mySprite);
}
catch (error:Error){
trace("An error occured.");
}

myPrintJob.send();
}
else{
trace("Print job canceled.");
}

Now, moving forward.

We can manually set the way of printing the pages - print it as a bitmap, or print it as vector graphics. What's the difference between the two? Vectors in some cases generate a lighter file to pass to the spooler and results in better quality image on paper, but sometimes it is better to use bitmaps, if the image that is going to be printed includes a bitmap image, for instance. An advantage of printing as bitmaps is that this way we can keep alpha transparency.

To set the printing type, we'll need to create a new PrintJobOptions object and set its printAsBitmap property either to true or false. Then, we pass this object as the third parameter for our addPage() method.

var opt:PrintJobOptions = new PrintJobOptions();
opt.printAsBitmap = true;
myPrintJob.addPage(mySprite, null, opt);

This is all for today.

Thanks for reading!

Related:

Printing in AS3: Part 1
Printing in AS3: Part 3
Printing in AS3: Part 4

No comments:

Post a Comment