Search This Blog

Friday, July 9, 2010

Working with PDFs on Actionscript using AlivePDF

Recented I came across AlivePDF library for Flex/AIR which allows you to generate PDF's 100% client-side.
There are a bunch of tutorials to get started with AlivePDF. AlivePDF comes with a SWC that you can include in your Flex application, or an Actionscript package you can import to your AS code. Here's a brief, condensed example of how I used AlivePDF in my Flash AIR project.
import org.alivepdf.*;

// setup pdf
var myPDF : PDF = new PDF ( Orientation.PORTRAIT, Unit.MM, Size.LETTER );

myPDF.setDisplayMode( Display.FULL_PAGE, Layout.SINGLE_PAGE );

myPDF.addPage();

// add a background image
myPDF.addImage (myBackgroundMovieClip, 1 , null, null, false, ImageFormat.JPG, 100, 0, 0, 0, 0);

// add headline
myPDF.textStyle ( new RGBColor ( 41, 58, 140 ) );
myPDF.setFont( FontFamily.HELVETICA, Style.BOLD );
myPDF.setFontSize ( 18 );
myPDF.setXY( 10, 40 );
myPDF.addMultiCell ( 300, 1, "This is my PDF Headline" );

// add text message
myPDF.textStyle ( new RGBColor ( 0, 0, 0 ) );
myPDF.setFont( FontFamily.HELVETICA, Style.BOLD );
myPDF.setFontSize ( 14 );
myPDF.setXY( 10, 50 );
myPDF.addMultiCell ( 300, 4, "This is my text….lots of text…" );

// save PDF to the desktop
var f : FileStream = new FileStream();
var file : File = File.desktopDirectory.resolvePath("MyPDF.pdf");
f.open( file, FileMode.WRITE);
var bytes : ByteArray = myPDF.savePDF(Method.LOCAL);
f.writeBytes(bytes);
f.close();     
Notice I'm using the method addMultiCell to add text. This may seem odd, but what this allows me to do is add a block of text that wordwraps. If I use addText then I only get a single line.

AlivePDF is definitely still young and I've run into a few oddities (read bugs). I logged a bug on the Google project site and within no time at all received a note saying the issue had been resolved and would be released in the next build. Nice!

The Google project site provides a few examples in addition to the samples provided in the download. And the documentation is fairly helpful.