I was doing some research in PDF exporting yesterday which gave me the opportunity to mess around with AlivePDF . This is a library was built by Thibault Imbert to enable Flex to generate PDF and is based on FPDF, a php library.

As a proof of concept i grabbed a quick drawing app to see if i could print out what ever i draw to a PDF. By the looks of the library this test only scratches the surface of its functionality, but it serves my needs at the moment.

Out of pure laziness i grabbed the simple drawing app from here http://www.munkiihouse.com/?p=4 (Thanks!) and added in the AlivePDF generation.

SOURCE

Draw on the canvas with your mouse, and then click Generate PDF

The first thing you need to do in order to make this work is download the latest AlivePDF SWC and add it to your Flex project. You could find that here http://code.google.com/p/alivepdf/downloads/list

Flex Code:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application  xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:mh="mh.components.*"
	 viewSourceURL="srcview/index.html">
 
	<mx:Style source="styles/obsidian/obsidian.css" />
	<mx:Script>
		<![CDATA[
			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;
			import org.alivepdf.saving.Method;
			import org.alivepdf.fonts.FontFamily;
			import org.alivepdf.fonts.Style;
			import org.alivepdf.colors.RGBColor;
 
			private var myPDF:PDF;
 
			function generatePDF ( e:MouseEvent )
			{
				// we create the PDF
				myPDF = new PDF(  Orientation.LANDSCAPE, Unit.MM, Size.LETTER );
				// we set the zoom to 100%
				myPDF.setDisplayMode ( Display.FULL_WIDTH ); 
 
 
				// we add a page
				myPDF.addPage();
				myPDF.addImage(dc_main);
 
				// to save the PDF your specificy the path to the create.php script
				// alivepdf takes care of the rest, if you are using AIR and want to save the PDF locally just use Method.LOCAL
				// and save the returned bytes on the disk through the FileStream class
				myPDF.save( Method.REMOTE, "http://project.unthinkmedia.com/un/createPDF/create.php", "drawing.pdf" );
 
			}
		]]>
	</mx:Script>
		<mx:Button horizontalCenter="0" click="generatePDF(event)" label="Generate PDF" id="generate_btn" />
 
		<mx:Panel layout="absolute" title="Draw On Me" backgroundColor="#ffffff" borderThicknessBottom="10" left="20" right="20" top="20" bottom="20">
			<mx:Canvas x="0" y="0" width="100%" height="100%" backgroundColor="#ffffff">
				<mh:DrawableCanvas id="dc_main" backgroundColor="#ffff80" backgroundAlpha="0" width="100%" height="100%" y="0" x="0">
				</mh:DrawableCanvas>
			</mx:Canvas>
 
		</mx:Panel>
 
</mx:Application>

Along with the swc you will also need to add this PHP code to your server. It is supplies on the AlivePDF site, and I believe he mentioned that he has the same code in different languages if you need it. Here is the PHP code.

<?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.';
 
?>

Post to Twitter


Subscribe to comments Comment | Trackback |
Post Tags:

Browse Timeline


This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

Comments ( 35 )

Exporting PDFs in Flex using AlivePDF http://blog.unthinkmedia.com/?p=53

otakurzo (Otaku RzO) added these pithy words on May 07 09 at 5:40 pm

[...] PDF en Flex y, particularmente, como guardar texto en archivos de este tipo y me topé con un popular ejemplo en el que se presenta una pantalla donde es posible dibujar garabatos con el mouse para luego [...]

RIA212 » Blog Archive » Sobre AlivePDF y la clase FileReference added these pithy words on Jan 20 10 at 8:54 am

[...] library, with which one can create PDFs in Flash and Flex. I searched for tutorials and found this. As you can see in this example one can download a PDF file by opening a new browser page. I wanted [...]

Flash AS3: PDF attachment with email « Flashscript.biz added these pithy words on Feb 01 10 at 2:05 am

[...] the … equal in capacity, with a total volume of 68 billion cubic neters of gas per annum. …unthink media Exporting PDFs in Flex using AlivePDFI was doing some research in PDF exporting yesterday which gave me the opportunity to … Are there [...]

neters added these pithy words on Mar 04 10 at 11:56 pm

It is not working in Linux.

Dan added these pithy words on Sep 18 08 at 5:06 pm

Thank you so much. Worked perfectly!

Regards from Brazil,

Ved

Ved added these pithy words on Sep 25 08 at 1:26 pm

@Dan,
Sorry it has taken me so long to get back to you, been really busy at work.

I’m not too familiar with Linux, but check out this http://alivepdf.bytearray.org/?p=17 .There is a comment there that has some PERL code that may help. Let me know if that helps, if not i try my best to get an answer for you on Monday.

Alex Britez added these pithy words on Sep 25 08 at 8:19 pm

@Ved

No problem, it was actually quite simple, AlivePDF did all the work. I just made it do something interesting to spark some creativity from flash/flex folks.

I live in a Brazilian area, so not exactly Brazil, but at least I get some good food.

Alex Britez added these pithy words on Sep 25 08 at 8:25 pm

Hi Alex,

It’s really good application u have done. You have nearly solve my problem but can u please suggest me jsp code to replace your php code of create.php as I’m using java environment.
Eagerly waiting for ur reply.

Regards,
Vivek

Vivek added these pithy words on Sep 29 08 at 2:27 am

@Vivek,

I found this on the AlivePDF Forum from a user named java_rule, See if this works:

java_rule’s environment:
AlivePDF v. 0.1.4.4
Adobe Reader 8.1.2
JDK 1.5
Flex 3

package javaPDF;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class CreatePDF extends HttpServlet {

public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}

public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
int i = 0;
int k = 0;
int maxLength = req.getContentLength();
byte[] bytes = new byte[maxLength];
String method = req.getParameter(”method”);
String name = req.getParameter(”name”);
ServletInputStream si = req.getInputStream();
while (true) {
k = si.read(bytes, i, maxLength);
i += k;
if (k == -1){
break;
}
}
if (bytes != null) {
ServletOutputStream stream = resp.getOutputStream();
resp.setContentType(”application/pdf”);
resp.setContentLength(bytes.length);
resp.setHeader(”Content-Disposition”,method + “;filename=” + name);
stream.write(bytes);
stream.flush();
stream.close();
} else {
resp.setContentType(”text”);
resp.getWriter().write(”bytes is null”);
}
}
}

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

myPDF.setDisplayMode( Display.FULL_PAGE, Layout.SINGLE_PAGE );

myPDF.addPage();
myPDF.addImage(pie,
1,
1,
100,
100,
ImageFormat.JPG ,
100,
160,
ResizeMode.FIT_TO_PAGE,
BlendMode.DARKEN,
true,
“”);

myPDF.save(
Method.REMOTE,
‘http://localhost:8080/JSP_PDF_Generator/CreatePDF’,
Download.ATTACHMENT,
‘myPDF.pdf’ );
Alex Britez added these pithy words on Sep 29 08 at 4:20 am

This is great!

Are there any .NETers out there that could post an ASPX equivalent of the PHP script?

Greg added these pithy words on Oct 20 08 at 6:47 pm

hi, do you have a page made in coldfusion?

regards,

Gustavo

gustavo Duenas added these pithy words on Oct 21 08 at 1:12 pm

do you have something for coldfusion, and also how could I convert a flex form into pdf…regards.

Gus

gustavo Duenas added these pithy words on Oct 24 08 at 9:43 am

Can the create.php screipt be replaced by a coldfusion implementation?

phil added these pithy words on Oct 24 08 at 3:16 pm

The demo doesn’t seem to work. The generated pdf is saved but will not open in Acrobat or preview. I’m using Firefox 3.0.3 on Mac OSX 10.4.11

Chris added these pithy words on Oct 29 08 at 5:06 pm

@Chris Interesting, I ran it on Firefox 3.0.3 on Mac OSX 10.5.5 and it seems to work. Out of curiosity could you try to open it using Preview and see if that works?

Alex Britez added these pithy words on Oct 29 08 at 7:48 pm

@Chris just realized you did try Preview. Hmmm… Have you tried any other AlivePDF examples? Let me know if that. Thanks

Alex Britez added these pithy words on Oct 29 08 at 7:51 pm

@phil & @ gustavo sorry i don’t have any Coldfusion examples, if i happen to run into one i will post it.

Alex Britez added these pithy words on Oct 29 08 at 7:52 pm

Any ideas how we could rewrite your php file onto coldfusion?

gustavo Duenas added these pithy words on Nov 03 08 at 9:49 am

how can I save files without the create.pdf file is this really necessary?

Regards,

Gustavo

gustavo Duenas added these pithy words on Nov 03 08 at 9:50 am

Does anyone know if Thibault Imbert or anyone else has a ruby on rails version of the server side script?

jason added these pithy words on Nov 11 08 at 1:30 pm

Thanks for the example! :)

BTW the name needs to be forth parameter,

alivePDF.save( Method.REMOTE, “PDF.php”, Download.ATTACHMENT, “drawing.pdf” );

As of Flash Player 10 you can save files locally without going to the server using the FireReference class but it takes a bit to setup. This article covers how to, Develop for Flash Player 10 in Flex Builder 3,
http://www.communitymx.com/content/article.cfm?page=1&cid=105CF

Then you would target Flash Player 10 and use something like this,

var f:FileReference = new FileReference();
var bytes:ByteArray = alivePDF.save(Method.LOCAL);
f.save(bytes, “drawing.pdf”);

Note: the save method is not available on players before 10.

judah added these pithy words on Nov 15 08 at 1:18 pm

hi alex that very good for example and if we have a word document how to export to pdf.

you have any idea?

thanks!

nueng added these pithy words on Nov 21 08 at 9:23 am

Great example and this is what I need..!!
How can I install alivePDF to flex?
I downloaded zip file but should i copy this folder somewhere???
I don’t have PHP install in my server, do I need it? I don’t think I can install PHP, can I use something else.
I’m using coldfusion cfc’s to extract data to flex.
Thanks
JFB

JFB added these pithy words on Dec 02 08 at 2:32 pm

To JFB:

Copy the AlivePDF.swc in the bin folder from the zip filer folder to the libs in your Flex project. The server needs to support PHP.

I wonder how to set the page output size(Letter, Legal or 11×17 for example) and orgintation.

Hope this helps.

yijia lai added these pithy words on Dec 12 08 at 1:09 pm

RubyOnRails server side script.

send_data( request.raw_post, :type => ‘application/pdf’, :filename => params[:name])

Thanks.

Zendy added these pithy words on Jan 07 09 at 1:16 am

wonderful opst))

Luna added these pithy words on Jan 18 09 at 1:58 pm

such a rewal stlry..

Nice added these pithy words on Jan 22 09 at 7:12 am

I have created a demo app for generating pdf from a VBox with dynamic child….it
doesn’t work either. Take a look. I am using Flex4 SDK to save the PDF locally in FP 10.

<![CDATA[
import org.alivepdf.images.ResizeMode;
import org.alivepdf.saving.Method;
import org.alivepdf.images.ImageFormat;
import org.alivepdf.pages.Page;
import org.alivepdf.display.*;
import org.alivepdf.layout.*
import org.alivepdf.pdf.PDF;

private var mPDF:PDF;

private function onPDFCreate():void
{
mPDF = new PDF(Orientation.PORTRAIT, Unit.MM, Size.A4 );
mPDF.setDisplayMode( Display.FULL_PAGE, Layout.SINGLE_PAGE );
mPDF.setTitle(‘Module’);
for(var i:int=0; i

Need a quick solution…please help!!

sunpatel added these pithy words on Mar 03 09 at 9:29 am

Hi,
I am using AlivePDF to generate a PDF for a VBox container, containing chart controls. The issue is I am getting the first child of the container generated in the PDF but not the later one. I tried adding more pages to PDF with each page containing an individual child, but I could see only the first child in the first page of generated PDF….rest all pages being blank.
Can anybody help me getting the complete content of the container to be generated in the PDF?

Thanx,
Amit

Amit Goel added these pithy words on Apr 27 09 at 5:12 am

Hi,
Is any one having any idea on how i can print multiple pages using alive pdf

Regards’
Saurabh

saurabh added these pithy words on May 31 09 at 10:08 pm

simply superb.

bluerain added these pithy words on Jun 02 09 at 10:46 am

hi all,
I have chart which i want to print as a pdf using alivePDF but when the pdf come yhe image and text in it blur,any help
reagrds
jakir

jakir added these pithy words on Nov 24 09 at 10:46 am

Does it seem odd that i get the following error when adding the parameter Download.ATTACHMENT:

Access of undefined property Download.

Is there a way to save the pdf right to the shared folder without having the browser popup?

Tom M added these pithy words on Jul 08 10 at 12:15 am

Add a Comment


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">


© Copyright 2007 unthink media . Thanks for visiting!