5

scris de:
Peter

Create a PDF file with Adobe AIR

09.02.10

In this tutorial we will learn to create a pdf file with Adobe AIR and the help of an external library called AlivePDF. To get things started go to the AlivePDF download page and get the latest version of the API (in this tutorial I use the AlivePDF 0.1.5 RC version) and we can start coding our pdf creator app.Create a new Flash File(Adobe AIR) , add an input TextField with an instance name of “txt” and create a new button with an instance name of “but”; or download the starter files here. Import the classes needed for this example:

import org.alivepdf.pdf.PDF;
import org.alivepdf.layout.Size;
import org.alivepdf.saving.Method;
import org.alivepdf.layout.Unit;
import org.alivepdf.layout.Orientation;

Now we can start creating our pdf file:

var doc:PDF=new PDF(Orientation.PORTRAIT,Unit.MM,Size.A4);

//you can have the orientation either in PORTRAIT or in LANDSCAPE mode
//the unit can be: MM,POINT,CM,INCHES
//Size defines the size of the document page witch can be: //A3,A4,A5,LETTER, LEGAL,TABLOID

To add a new page to the pdf file you simply call the addPage method:

doc.addPage();

Now let’s create the file and filestream, so we can save the pdf:

var stream:FileStream=new FileStream();
var file:File=File.desktopDirectory.resolvePath("mydoc.pdf");
stream.open(file,FileMode.WRITE);

The pdf file will be saved on the user’s desktop as we defined the path. Now it’s time for the function that creates and saves the file:

but.addEventListener(MouseEvent.CLICK,save);

function save(e:MouseEvent):void{
doc.addText(txt.text,5,10);
//add the text from text input field and position it at the x:5 and y:10
var byte:ByteArray=doc.save(Method.LOCAL); //if you are publishing for a web application you should set the Method.REMOTE
stream.writeBytes(byte);
stream.close();
}

If we run our project we should have a little pdf creating app.You can download the finished source files here. The AlivePDF library has a lot of options like: adding an image to the file using the addImage(displayObject) method, or setting the font style, hyperlinks and much more. If you want to learn more about AlivePDF you can visit the official site , or the tutorials page here (tough some of the tutorials were written on an earlier version of the library and may not work with the current version).

Comentarii

Email-ul tau nu va fi publicat. Numele si email-ul sunt obligatorii.