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 from their hosting service 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.

Advertisements

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

  1. 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

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

  3. 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.

  4. 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??

  5. 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 (0x666666), new RGBColor (0xCCCCCC), new RGBColor (0xCCCCCC), true, new RGBColor ( 0xCCCCCC ), 1);

    grid.columns = columns;

    hppPDF.addGrid(grid);

    1. 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.

  6. 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!

  7. 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

    1. 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

  8. 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

  9. 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

  10. 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

  11. 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..

      1. 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..

  12. how to create canvas in to a pdf from a flex application. I have already made pdf for text and images. But if i want to claim for canvas will you please let me know the code for it

  13. For those trying to build a web application with CS4… I was able to get this code working by removing the mdm code and replacing the event dispatched from CreatePDF.as savePDF(); method – using the FileReference class (built into FP9 )

    ex: ( in CreatePDF.as )
    public function savePDF(pdfName:String):void
    {

    var fileReference:FileReference = new FileReference();
    var byteArray:ByteArray = pdf.save(Method.LOCAL);
    fileReference.save(byteArray, pdfName+’.pdf’);

    }

    Works great locally or deployed to the server – pretty good code thanks much!

  14. Nice to see code but i need little bit help that can i create pdf in AS2, Here i have logo and text and want to create pdf when user click on finish. please suggests me in AS2

  15. Can any one help me in understanding, how can I run and generate the pdf using the source files…..

    Many Thanks in advanve.

  16. After creating the PDF in Flex, how can you then get the browser to “open” the PDF using the normal, registered application (Adobe Reader)? I know that if you save the PDF to the server you can then request it from the browser – and if the server sets the correct Content-Type and Content-Disposition headers the browser will know to open it with Adobe Reader. But how can you do that without a round-trip to the server? From Flex can you call a JavaScript function, passing the PDF bytes and then have the JavaScript function set the appropriate parameters on the browser’s Document object so that it’s the same net effect as the browser receiving an HTTP response with those MIME headers set?

  17. Hi,
    i need create PDF from flash cs5.5. I have a problem with definition in Main.as. I have error that “Definition mdm is not found.” And other problems connected with it.
    Sorry for my english.
    Thanks for help.

  18. Hi Lucas,
    Your article is great and your code works well for a small byteArray.
    The pdf I have to save is very big (more than 100 pages with many pictures) and running time is to long so it stop before finish. How can I “cut” the byteArray to save it by using mdm zinc append routine?

    1. I suggest to create a dll or a server side script that make it instead of zinc and Flash because probably you can’t do that only with Zinc without having a worst user experience

  19. Hi Luca..

    Thanks for the article..

    I need some help.. I want to create a PDF with a datagrid. I can able to print but if the number of rows are more, column headers are not coming in the second page. is there anyway to show column headers in the second page.

    and also if i need to give permission to user to print only few columns. how can i do that.

    Thanks in advance,
    Chevi.

    1. You have to create the image you want to print before Save it in the pdf, so in your case you’ll create your image with the borders programmatically and then you pass the bytearray to alivepdf

  20. very interesting tutorial.
    I’m looking into having a flash client generated drawing saved as a pdf along with an online shop order.
    So I will need the pdf to be gerated with a Unique name and “attatched” to the shop order. I guess this and some server side php would do the trick.

    1. Yes, I suggest to use this one only if you are working on desktop application, if you have to do it online, do it only on the server, you’ll have a better control on what’s going on and the process is not dependent by the computer of the user

  21. Hi Lucas!!
    How can i print the new pdf in AS3 once I ‘ve created? i need some help… i tryed use bitmapData, but maybe if not a good idea…

    1. Hi Oscar,
      I don’t think you can do it via actionscript APIs, probably if you are using adobe air you should be able to call an external program or a cli command that allow you to print.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s