Saturday, May 23, 2009

How to generate PDF files from your Air application


There are a number of methods for generating on demand PDF documents from an online Flex application, in many enterprise applications PDF files are required as a part of the reporting layer. In that case it would be useful to incorporate a reporting tool such as Jasper Reports. But what if you are running an Air application that is not using a server? In this case you will need a pure client side solution. I found the following great tool for this: "AlivePDF is an open-source ActionScript 3 (Flash, Flex, AIR) PDF generation library ported from the FPDF PHP project. It allows you to generate PDF's client-side". I tried this very simple tutorial(video) and using the code below generated my PDf file:

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="generatePdf(event)" viewSourceURL="srcview/index.html">

<mx:Script>
<![CDATA[
import org.alivepdf.saving.Method;
import org.alivepdf.layout.Size;
import org.alivepdf.layout.Unit;
import org.alivepdf.layout.Orientation;
import org.alivepdf.pdf.PDF;

private var myPdf:PDF;

public function generatePdf(e:Event):void
{
myPdf = new PDF(Orientation.LANDSCAPE,Unit.MM,Size.A4);
myPdf.addPage();
var stream:FileStream = new FileStream();
var file:File = File.desktopDirectory.resolvePath("tsss.pdf");
stream.open(file,FileMode.WRITE);
var byteArray:ByteArray = myPdf.save(Method.LOCAL);
stream.writeBytes(byteArray);
stream.close();
}

]]>
</mx:Script>
</mx:WindowedApplication>

2 comments:

Shawn Makinson said...

Here is a javascript option. http://code.google.com/p/jspdf/

I have not tried / used it personally, I just thought I'd pass along its existence .

Lior said...

Thanks Shawn, that's interesting, I was not aware of a pure JS solution