Sunday, January 15, 2012

Flash AS3 + PHP: Publishing your flash contents into a PDF file

With the release of Flash Player 10, you can easily create an image file to display all the contents into an image on the fly. But with the help of 'Alive PDF' and Php, you can actually create PDF on the fly.

The following would be a simple demo that I have created. The generated PDF will display 2 blocks of text. The first text would be a capture of the text view in the Flex Application and the second text was inserted into the PDF using the functions provided in the 'Alive PDF' API.

So let us take a look at some coding. :D
<?php

$method = $_GET['method'];
$name = $_GET['name'];

if ( isset ( $GLOBALS["HTTP_RAW_POST_DATA"] )) {
 
 // get bytearray
 $pdf = $GLOBALS["HTTP_RAW_POST_DATA"];
 
 // add headers for download dialog-box
 header('Content-Type: application/pdf');
 header('Content-Length: '.strlen($pdf));
 header('Content-disposition:'.$method.'; filename="'.$name.'"');
 echo $pdf;
 
}  else echo 'An error occured.';

?>
The above Php script was taken from the Alive PDF website.

The following would be the source file of my Main Application in Flex.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
    creationComplete="creationCompleteHandler(event)"
    width="100%" height="100%">
 <mx:Script>
  <![CDATA[
   import mx.events.FlexEvent;
   
   import org.alivepdf.colors.RGBColor;
   import org.alivepdf.display.Display;
   import org.alivepdf.fonts.CodePage;
   import org.alivepdf.fonts.EmbeddedFont;
   import org.alivepdf.layout.Layout;
   import org.alivepdf.layout.Mode;
   import org.alivepdf.layout.Orientation;
   import org.alivepdf.layout.Position;
   import org.alivepdf.layout.Resize;
   import org.alivepdf.layout.Size;
   import org.alivepdf.layout.Unit;
   import org.alivepdf.pages.Page;
   import org.alivepdf.pdf.PDF;
   import org.alivepdf.saving.Method;
   
   //Some Dummy Text
   [Bindable]
   private var msg:String = "Lorem ipsum dolor sit amet, " +
    "consectetur adipiscing elit. Cras nec eros sit amet " +
    "dui sagittis volutpat pharetra et est. Curabitur " +
    "ultricies suscipit volutpat. Aenean feugiat " +
    "ullamcorper pellentesque. Nulla ut venenatis ligula. " +
    "Nam ornare est a odio condimentum bibendum. Sed " +
    "lorem est, tristique at gravida in, blandit vitae leo. " +
    "Etiam lobortis mi vel magna porta tempus. Suspendisse " +
    "in tortor non magna hendrerit vulputate id quis justo. " +
    "Integer vehicula tortor tortor. Cras consequat, tortor " +
    "in cursus consequat, risus justo vehicula arcu, eu " +
    "consequat dolor leo sed felis. In euismod mollis blandit. " +
    "Vivamus tempus rutrum lorem quis commodo. Suspendisse " +
    "condimentum lorem at risus eleifend porttitor. Nulla " +
    "molestie ipsum nec lacus convallis semper sed ut enim. " +
    "Curabitur arcu justo, imperdiet ac rutrum eget, porta " +
    "eget orci. Nulla aliquet tristique rutrum.";
   
   //Path to the Php file used to generate the pdf file
   private var phpUrl:String = "http://bestkirdape.freeiz.com/php/create.php";
   
   //File Name that I'm giving the pdf file
   private var strFilename:String = "PrintOut_Of_PlayingWithAlivePDF.pdf";
   
   //Specify the Embedded font used by the label, lblText
   [Embed( source="fonts/jokerman.TTF", mimeType="application/x-font", fontName="jokermanFont")]
   public var jokermanFont:Class;
   
   //Specify the Embedded font that I'm using in the print out
   [Embed( source="fonts/jokerman.TTF", mimeType="application/octet-stream")]
   public var jokerman_ttf:Class;
   [Embed( source="fonts/jokerman.afm", mimeType="application/octet-stream" )]
   public var jokerman_afm:Class;
   
   //Specify the Font Color
   private var textColor:uint = 0x000000;
   
   //Open up the pdf upon clicking on the button 'Print Content Now!'.
   protected function btnPrint_clickHandler(event:MouseEvent):void
   {
    printContent();
   }
   
   private function printContent():void
   {
    //This variable is needed to specify the Embedded font that
    //we are using
    var font:EmbeddedFont = new EmbeddedFont(
     new jokerman_ttf() as ByteArray
     , new jokerman_afm() as ByteArray
     , CodePage.CP1252
    );
    //Specify the settings of the PDF
    //In my case, I'm using a PORTRAIT view, a size of A4
    //and everything will be calculated in POINT.
    var myPDF:PDF = new PDF(Orientation.PORTRAIT, 
     Unit.POINT, Size.A4);
    //Set the Display Mode of the PDF when it was opened.
    myPDF.setDisplayMode ( Display.FULL_WIDTH );
    //Set the Margins (left, top, right, bottom)
    myPDF.setMargins(10,20,10,20);
    //Add a Page to the PDF
    myPDF.addPage();
    //Change the size of the view,, lblText and ...    
    lblText.width = (myPDF.getCurrentPage().w - 20);
    resizeMe(lblText);
    lblText.validateNow();
    //add it to the PDF
    myPDF.addImage(lblText,null,0,0); 
    //Set the Font of the PDF
    myPDF.setFont(font, lblText.getStyle("fontSize"));
    //Set the Color of the Text of the PDF
    myPDF.textStyle(new RGBColor(Number(textColor)));
    //Change the XY coordinates of the view that
    //I'm going to add
    myPDF.setXY(10, lblText.height + 20 + 10);
    //Create a Cell to display my text and centralised it
    myPDF.addMultiCell(myPDF.getMargins().width,
     lblText.getStyle("fontSize") + 6, msg, 0, "C", 0);
    //*********UPDATED***********
    //Download the PDF file
    //Need to add Download.ATTACHMENT as one of the parameters 
    //in order to download the pdf file.
    myPDF.save( Method.REMOTE, phpUrl, Download.ATTACHMENT, strFilename);
    //Revert the width of the view, lblText.
    lblText.width = 400;
    resizeMe(lblText);
    lblText.validateNow();
   }
   
   protected function creationCompleteHandler(event:FlexEvent):void
   {
    resizeMe(lblText);
   }
   
   //Used to resize the TextArea so that all the text
   //will be shown.
   private function resizeMe(field:TextArea) :void
   {
    field.validateNow();
    field.mx_internal::getTextField().autoSize = 
     TextFieldAutoSize.CENTER;
    field.height = field.mx_internal::getTextField().height;
   }   
   
  ]]>
 </mx:Script>
 <mx:VBox width="100%" verticalAlign="middle" 
    horizontalAlign="center" height="100%">
  <mx:TextArea id="lblText" wordWrap="true"
      backgroundAlpha="0"
      borderThickness="0"
      fontFamily="jokermanFont"
      color="{textColor}"
      text="{msg}" width="400" textAlign="center"/>
  <mx:Button click="btnPrint_clickHandler(event)"
       label="Print Content Now!"/>
 </mx:VBox>
</mx:Application>

* Click here to view the demo of this example.
^ Click here for the source files of this demo.

~ Click here for the website of 'Alive PDF'.
- Click here for the Documentation of the classes of 'Alive PDF'.
** Click here for the .adm file generator.
(Note: you need to upload a .ttf file before you can generate the .adm file.

No comments:

Post a Comment