Friday, August 26, 2011

Adding multiple images with AlivePDF

Furthur to my work with AlivePDF, I had to add multiple images into the PDF that I was creating. This seemed straight forward at first. So I did it this way,


private function exportToPDF(childrenComponents:Array):void
{
var pdfEncoder:PDF = new PDF(Orientation.PORTRAIT, Unit.MM, Size.A4);
pdfEncoder.setDisplayMode(Display.REAL);

for (var i:uint = 0; i < childrenComponents.length; i++)
{
        pdfEncoder.addPage();
pdfEncoder.addImage(dObj, new Resize(Mode.FIT_TO_PAGE, Position.LEFT);
}
var bytes:ByteArray = pdfEncoder.save(Method.LOCAL);
_fileReference.save(bytes, (this.fileName + ".pdf"));
}

That worked fine but now I needed to bring them into the same page and add new pages dynamically. So here it went,

EDIT: Changed the code below to set margins and give out better resolution in the PDF.

private function exportToPDF(childrenComponents:Array):void
{
var pdfEncoder:PDF = new PDF(Orientation.PORTRAIT, Unit.MM, Size.A4);
pdfEncoder.setDisplayMode(Display.REAL);
pdfEncoder.setMargins(10, 10, 5, 20);

var pageNum:int = 0;
pdfEncoder.addPage();
pageNum++;
var imgY:int = 0;

for (var i:uint = 0; i < this.childrenComponents.length; i++)
{
var pageWidth:Number = pdfEncoder.getCurrentPage().w - 15;
var pageHeight:Number = pdfEncoder.getCurrentPage().h - 30;

var dObj:DisplayObject = this.childrenComponents[i] as DisplayObject;
var imgScaleFactor:Number = dObj.width/dObj.height;


var pw:int = 0;
var ph:int = 0;

if (pageWidth > dObj.width)
{
uiComp = (dObj as UIComponent);
pw = dObj.width;
if(pageHeight > dObj.height)
ph = dObj.height;
else
ph = pw/imgScaleFactor;
}
else
{
pw = pageWidth;
ph = pw/imgScaleFactor;
}

if ((imgY + ph) > pdfEncoder.getCurrentPage().h)
{
pdfEncoder.addPage();
pageNum++;
imgY = 0;
}

pdfEncoder.addImage(dObj, new Resize(Mode.NONE, Position.LEFT), 0, imgY, pw, ph);
imgY = imgY + ph + 10;
}
var bytes:ByteArray = pdfEncoder.save(Method.LOCAL);
_fileReference.save(bytes, (fileName + ".pdf"));
}



And it worked. All the "pw", "ph", "imgScaleFactor" have all been calculated so that I can get proper resolution on the PDF file. If you can better it, be sure to post it here.. :)
If the size exceeds that of the page, it should create a new Page and add it there. I haven't tested this properly, so it might be a bit buggy.
Cheers.


No comments :