flash platform! {desktop, mobile, touch screen…}


Create PDF in runtime with Actionscript 3 (AlivePDF, Zinc or AIR, Flex or Flash)

This morning I’ve a new target, create PDF in runtime with Actionscript 3.
Very cool project to accomplished this mission is AlivePDF, an opensource AS3 library that you can download from Google Code.
AlivePDF allow you to generate PDF in runtime with Actionscript 3 and you can add pages, draw in each pages or add images, it’s very powerful library.

In this sample I use Actionscript 3 (with FDT) and Multidmedia Zinc 3, but you can use Flex or Flash and AIR to make this sample.
So first of all I create a simple class that allow you to create a PDF file with multiple pages and to add content in each pages.
This is the code:

package org.mart3.pdfGeneration {
    import flash.events.Event;    
    import flash.utils.ByteArray;    
    
    import org.alivepdf.images.ImageFormat;    
    import org.alivepdf.saving.Method;    
    
    import flash.display.Loader;    
    import flash.events.IEventDispatcher;    
    import flash.events.EventDispatcher;
    
    import org.alivepdf.pdf.PDF;
    import org.alivepdf.layout.Orientation;
    import org.alivepdf.layout.Size;
    import org.alivepdf.layout.Unit;
    import org.alivepdf.display.Display;
    
    /**
     * @author lm
     */
    public class CreatePDF extends EventDispatcher {
        
        private var pdf:PDF;
        public var pdfBA:ByteArray;
        
        public function CreatePDF(target : IEventDispatcher = null) {
            super(target);
            
            pdf = new PDF(Orientation.LANDSCAPE, Unit.MM, Size.A4);
            pdf.setDisplayMode(Display.FULL_PAGE);
        }
        
        public function set totalPages(num:int):void{
                
            for(var i:int = 0; i < num; i++){
            
                pdf.addPage();    
                
            }
    
        }

        public function setData(_l : Loader, _numPage:int) : void {
            
            pdf.gotoPage(_numPage);
            pdf.addImage(_l, 15, 15, 0, 0, ImageFormat.JPG, 100);
        }
        
        public function savePDF():void{
            pdfBA = new ByteArray();
            pdfBA = pdf.save(Method.LOCAL);
            
            var evt : Event = new Event("baReadyEvent");
            dispatchEvent(evt);
        }
    }
}

Obviously if you want, you can create a custom event that pass to the document class the ByteArray but this is a quick sample to show how you can create PDF in runtime!

One of the amazing things that you should do with AlivePDF, it’s that you can decide to save PDF locally or on web! Read documentation because it’s very interesting what you can do with this library!

Ok now, go to document class where we use MDM swc that you can find when install Zinc on your computer (you can find 2 differents SWC, one for Flash and the other one for Flex. Remeber also that Flash SWC works with Flash CS4 also, not only with Flash CS3!).
In this class we do those simple steps:

  • create a PDF object using CreatePDF object
  • set our PDF document
  • pass an external image loaded with Loader object
  • save PDF bytearray with Zinc FileSystem class
package org.mart3.pdfGeneration {

    import flash.display.MovieClip;    
    import flash.net.URLRequest;    
    import flash.display.Loader;    
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.MouseEvent;

    import mdm.*;

    import org.mart3.pdfGeneration.*;

    /**
     * @author lm
     */
    public class Main extends Sprite {
    
        private var pdfObj:CreatePDF;
        private var l : Loader;
    
        public function Main() {
            
            mdm.Application.init(this);            
            
            pdfObj = new CreatePDF();
            pdfObj.totalPages = 2;
            pdfObj.addEventListener("baReadyEvent", saveLocalPDF);
            
            l =  new Loader();
            l.name = "myImg";
            
            l.contentLoaderInfo.addEventListener(Event.COMPLETE, showImage);
            l.load(new URLRequest(mdm.Application.path+"assets/bg.jpg"));
        }
        
        private function saveLocalPDF(e:Event) : void {
        
            mdm.FileSystem.BinaryFile.setDataBA(pdfObj.pdfBA);
            mdm.FileSystem.BinaryFile.writeDataBA(mdm.System.Paths.desktop+"generate.pdf");
    
        }

        private function showImage(event : Event) : void {
            
            l.scaleX = l.scaleY = .4;
            var mc : MovieClip = new MovieClip();
            mc.buttonMode = true;
            mc.addEventListener(MouseEvent.CLICK, savePDF);
            mc.addChild(l);
            this.addChild(mc);
        }
        
        private function savePDF(event : MouseEvent) : void {
            event.currentTarget.alpha = .5;
            pdfObj.setData(l, 1);
            pdfObj.savePDF();

            
        }
    }
}

You can also download source files and test it on your computer.
Feel free to give me any comments about AlivePDF, it’s very interesting to know what you think about this AS3 library



35 Comments so far
Leave a comment

Very nice tutorial! Do you know any other AS3 PDF library?

Comment by Napolux

Yes, you can find them here:
APdf => http://code.google.com/p/apdf/
AS3 pdfreader => http://code.google.com/p/as3-pdfreader/

The last one is very interesting because you can parse an existing PDF document and retrieve all contents

Comment by lucamezzalira

[...] Create PDF in runtime with Actionscript 3 (AlivePDF, Zinc or AIR … [...]

Pingback by Create PDF in runtime with Actionscript 3 (AlivePDF, Zinc or AIR …

Cool! Thanks for the links! ;)

Comment by Napolux

[...] C­o­­nti­nued­ here: C­reate PD­F in runtim­e with Ac­tio­ns­c­ript 3 (Aliv­ePD&#… [...]

Pingback by Create PDF in runtime with Actionscript 3 (AlivePDF, Zinc or AIR … « Downloads

Hi Luca, this article is wondeerful, I’ve been using zinc since one month for a project of an installation in a shop using flash as a client. Now I’m working on a video annotator, implemented in flex, flash and zinc and these feaure can be very useful. thank you so much

Comment by Gianpaolo

You are welcome Gianpaolo! thank you for your comment

Comment by lucamezzalira

I’m not very good in English, but your post seems good to me )

Comment by Фильмограф

Very nice…good!!

Comment by Nando Fox

Is there a way to export a paginated grid to PDF using Zinc or AlivePDF? Also, does the export support all fonts and locales?

Comment by flexuser

Thanks for the tutorial and I am using AlivePDF in my flex application and using Server component Java to save my PDF.
I face 2 issues in my application.
1. When I say savetoPdf() from my flex, I get my content exported to PDF and it’s missing from my original application page. I mean the chart gets exported to the PDF and I cannot view it in the application page. I need to a solution to this and also why it happens that way.
2. When my application is minimized and I say save to PDF, then the content I see on the PDF is just only the part I see on the minimized applciation rather than the full chart.

Please provide solutions to my problems.

Thanks.

Comment by Lakshmi

Did you try to make a bitmapdata of your chart before export and then pass a bitmpadata or a bitmap object to SWFAddress?

Comment by lucamezzalira

Hi,
i have Flex application in which i want to export image and datagrid in PDF using alive PDF.Image should be on first page and datagrid should be on First and all the remaining pages.DataGrid data is not hard coded ,its changing,Can anybody help me??

Comment by suhas

drop me an email man :-)

Comment by lucamezzalira

what is emailId??

Comment by suhas

luca [at] mart3 [.] org

Comment by lucamezzalira

Hello, I was wondering if anyone can throw some help my way. Using AlivePDF I was able to create a dataGrid and populate with data from an arrayCollection no problem.

The issue I’m having is that the first column needs to be an image, and currently I can’t find a way to get that to happen with alivePDF. The array data that actually populates the first column (“THUMB” in the code below) is an actual link to the image.

Does anyone know of a solution with this or another library? Thanks a lot, the code that shows the working grid is below:

hppPDF = new PDF (Orientation.PORTRAIT, Unit.MM, Size.A4);

hppPDF.addPage();

var lightboxData:ArrayCollection = Application.application.lightboxHeadshots;

hppPDF.textStyle( new RGBColor(0), 1 );
hppPDF.setFont ( FontFamily.ARIAL,Style.BOLD, 12 );

var gridColumnImage:GridColumn = new GridColumn(“Image”, “THUMB”, 50);
var gridColumnID:GridColumn = new GridColumn(“ID Number”, “id”, 20);
var gridColumnName:GridColumn = new GridColumn(“Name”, “NAME”, 20);
var gridColumnAge:GridColumn = new GridColumn(“Date of Birth”, “DOB”, 25);
var gridColumnSex:GridColumn = new GridColumn(“Sex”, “SEX”, 10);
var gridColumnHeight:GridColumn = new GridColumn(“Height”, “HEIGHT”, 10);
var gridColumnWeight:GridColumn = new GridColumn(“Weight”, “WEIGHT”, 10);

var columns:Array = new Array ( gridColumnImage, gridColumnID, gridColumnName, gridColumnAge, gridColumnSex, gridColumnHeight, gridColumnWeight );

var grid:Grid = new Grid ( lightboxData.toArray(), 200, 120, new RGBColor (0×666666), new RGBColor (0xCCCCCC), new RGBColor (0xCCCCCC), true, new RGBColor ( 0xCCCCCC ), 1);

grid.columns = columns;

hppPDF.addGrid(grid);

Comment by Austin

Hi Austin,

Do you know about “drop-in item renderer” in Flex 3?

As i see in your code, the thing you need to do to display image column (and printing it then) is to add the “itemrenderer” property to the corresponding column. For example:

dataGrid1.columns[1].itemrenderer = new ClassFactory(mx.controls.Image);
dataGrid1.columns[1].dataField = "thump";

For more information, search the Flex 3 online Help by keyword “itemrenderer and itemeditor”.

Hope this useful.

Comment by Alan

I not able to save as PDF in loacal machine.
Am using Flex sdk3.2, FlashPlayer9 & not AIR.

Comment by Abdul

Hi! Thanks for your code.
I´ve a question.
I´m doing an application with flash cs3 (as3)+ alivePDF + Zinc, but i can´t generate pdf in .exe compiled program with zinc or .swf in flash player, i need to embed swf in html page to generate pdf…

Can you help me? can i generate this? thanks!

Comment by kaiscender

Could you drop me an email with your code?
thank you in advance

Comment by lucamezzalira

hey
great writing. very useful.

But I was looking for articles about runtime loading vector assets, like .pdf .ai etc. I am aware that we can import to flash and make a .swf.
But my client has a print shop and we investigating if we could meake a tool for the customers to design their prints and typically they have logos etc, in vector format. So my challenge is is there a way to import vectors in fx. .ai or .pdf

If you have heard about please let me know

cheers and Merry X-mas / lasse

Comment by Lasse

For me a good solution could be a local webserver with PHP or Coldfusion or Java that take your vector assets and convert it to swf file, so you can work with it with Flash Platform

Comment by lucamezzalira

GREAT Blog….really appreciate your patience to respond and your professionalism

Comment by avi

Hello
Is awsome AlivePDF but I have many problems to add a Grid, For me is not clear do you have a complete example of this, We are creating in flash, thanks for all

Comment by Emilio

How to add page numbers to the generated PDF, if it has multiple paes.

Also when I am using Tab navigator, which is based on ViewStack and my creation policy is auto. When I am not selecting the other tabs, they are not created and so how can I generate their data in PDF?

Also can someone please send me if there are any good examples,as there is no much information or ful exaples on net.
I am using new release 0.1.5

I really appreciate your help in this regard

Comment by ren

Hi!
How can I make this work with flash cs4? Do I need other swc instead of mdm.swc? If I do where can i find that?
Thx a lot

Comment by Gabriell

Great tutorial. Easy to do. Thank you.

Comment by FlashJuggler

Hi guys,

Thanks for the article. I have a question though.
I am developing a web application in Flex and I would like to generate PDF on my application. I managed to use AlivePDF by using PHP server file which I found on here: http://blog.unthinkmedia.com/2008/09/05/exporting-pdfs-in-flex-using-alivepdf/

But The problem is that my client doesn’t want the application call any server files adn they asked me to do every thing in AS3 and do not use the php file. I have searched for such a feature but i had no luck so far.

Could your please help me out here?

Thanks in advance..

Comment by Bob

Hi Bob, that’s a good question.
Take a look at PurePDF by Sephirot: http://code.google.com/p/purepdf/
I think that it solves your problem :D

cheers

Comment by lucamezzalira

Hi,

Thanks for your reply. I have tried to use purePDF as u recomended. I have downloaded the lib and a helloworld example but i seriously cannot get it work. can u send me an example project file that works with purepdf? idonno how to run it.

I’m using a class file called helloworld which i bring it here:

package
{
import flash.events.Event;

import org.purepdf.elements.Paragraph;

public class HelloWorld extends DefaultBasicExample
{
public function HelloWorld(d_list:Array=null)
{
super(["This example shows how to add a simple text to the document","using a Paragraph element"]);
registerDefaultFont();

}

override protected function execute(event:Event=null) : void
{
super.execute();

createDocument( “Hello World” );
document.open();
document.add( new Paragraph(“Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent vel lectus lorem. Phasellus convallis, tortor a venenatis mattis, erat mi euismod tellus, in fermentum sapien nibh sit amet urna. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Praesent tellus libero, lacinia ac egestas eget, interdum quis purus. Donec ut nisl metus, sit amet viverra turpis. Mauris ultrices dapibus lacus non ultrices. Cras elementum luctus mauris, vitae eleifend diam accumsan ut. Aliquam erat volutpat. Suspendisse placerat nibh in libero tincidunt a elementum mi vehicula. Donec lobortis magna vel nibh mollis tempor. Maecenas et elit nunc. Nam non auctor orci. Aliquam vel velit vel mi adipiscing semper in ac orci. Vestibulum commodo sem eget tortor lobortis semper. Ut sit amet sapien non velit rutrum egestas sollicitudin in elit. Fusce laoreet leo a sem mattis iaculis”) );
document.close();
save();
}

}
}

and here is my mxml file:

but after clicking the button nothing happens.

Could you please help me out?

Many thanks in advance..

Comment by Bob

download this zip file: http://code.google.com/p/purepdf/downloads/detail?name=purePDF_Examples.zip&can=2&q=
you can find tons of samples.
In this zip file the base class where everything start is DefaultBasicExample.as and, for example, HelloWorld is a good sample to create text in a PDF file and save it with FileReference.
If you need more infos you can also write in PurePDF list: http://code.google.com/p/purepdf/issues/list or drop me an email

Comment by lucamezzalira




Leave a comment
Line and paragraph breaks automatic, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>