Printing in Adobe AIR - Standalone PDF Generation - apache-flex

Is it possible to generate PDF Documents in an Adobe AIR application without resorting to a round trip web service for generating the PDF? I've looked at the initial Flex Reports on GoogleCode but it requires a round trip for generating the actual PDF.
Given that AIR is supposed to be the Desktop end for RIAs is there a way to accomplish this? I suspect I am overlooking something but my searches through the documentation don't reveal too much and given the target for AIR I can't believe that it's just something they didn't include.

There's AlivePDF, which is a PDF generation library for ActionScript that should work, it was made just for the situation you describe.

Just added a Adobe Air + Javascript + AlivePDF demo:
This demo doesn't require flex and is pretty straight forward.
http://www.drybydesign.com/2010/02/26/adobe-air-alivepdf-without-flex/

One of the other teams where I work is working on a Flex-based drawing application and they were totally surprised that AIR / Flex does not have PDF authoring built-in. They ended up rolling their own simple PDF creator based on the PDF specification.

Yes it is very easy to create PDF using AlivePDF, here is the sample code, first method create a pdf and second method save the pdf on disk and return the path, feel free to ask any question.
public function createFlexPdf() : String
{
pdf = new PDF();
pdf.setDisplayMode (Display.FULL_WIDTH,Layout.ONE_COLUMN,Mode.FIT_TO_PAGE,0.96);
pdf.setViewerPreferences(ToolBar.SHOW,MenuBar.HIDE,WindowUI.SHOW,FitWindow.RESIZED,CenterWindow.CENTERED);
pdf.addPage();
var myFontStyle:IFont = new CoreFont ( FontFamily.COURIER );
pdf.setFont(myFontStyle,10);
pdf.addText('Kamran Aslam',10,20);//String, X-Coord, Y-Coord
return savePDF();
}
private function savePDF():String
{
var fileStream:FileStream = new FileStream();
var file:File = File.createTempDirectory();
file = file.resolvePath("temp.pdf");
fileStream.open(file, FileMode.WRITE);
var bytes:ByteArray = pdf.save(Method.LOCAL);
fileStream.writeBytes(bytes);
fileStream.close();
return file.url;
}

Related

PDFsharp : How can i get rid of Adobe Reader when printing?

When I print a pdf file with PDFsharp in c# with this code below
printDocument1.PrinterSettings = printDialog1.PrinterSettings;
PdfFilePrinter.AdobeReaderPath = #"C:\Program Files\Adobe\Reader 10.0\Reader\AcroRd32.exe";
PdfFilePrinter printer = new PdfFilePrinter(pdfFilename, printDocument1.PrinterSettings.PrinterName);
try
{
printer.Print();
}
catch (Exception ex)
{
throw new NotImplementedException();
}
, everything is fine while printing but one thing I don't like is AdobeReader pops up.
How can I close this pop-up by code?
Please help.
The PdfFilePrinter class uses Process.Start to start Adobe Reader. You can play with the ProcessStartInfo options and maybe you can get the behavior you want (launch minimized or without a window at all etc.).
PDFsharp is open source and the PdfFilePrinter class is included in the source package. IIRC this class was developed in the days of Adobe Reader 5 or 6. Maybe Adobe Reader 10 or XI can do better with a slightly modified way of invoking them.
I don't have time to try this myself, but I would like to hear from you if you managed to improve your issue.
Or is the issue to close Adobe Reader after printing? That would be more difficult as you have to find out when Reader finished printing.

Can't play sound file in flex

I wrote a game in flex and that game has sound. I load the sound from an asset like this to play the sound file, this is the function:
public function playSound(value:String, vol:Number):void
{
mySound=new Sound();
var urlRequest:URLRequest=new URLRequest(value);
mySound.load(urlRequest);
sChannel=mySound.play(0, 0, new SoundTransform(vol, 0));
}
When I'd like to play the sound I call it like this:
playSound("sounds/abc.mp3", 1)
The "sounds" in the package in the current project. It works fine when I build in eclipse, but when I put that game on the web, I can't hear the music.
Could anyone tell me how to fix please
Have you ever tried to modified your sound file by
Remove all metadata in the sound file.
Export it to a new MP3 file.
Is it too large to load? Try to add error event to listen.
var urlRequest:URLRequest=new URLRequest(value);
You're passing this a relative path, so when it's running on a remote machine it's looking there for the sound and obviously not finding it. You need to embed the sound, as detailed in this question:
[Embed(source="myfile.mp3")]
[Bindable] //Not required. Just an example of using multiple meta tags.
public var soundCls:Class;
Then, I'm a bit rusty, but I believe it's
sChannel = new soundCls().play(0, 0, new SoundTransform(vol, 0));
Just try this.
var urlReq:URLRequest = new URLRequest("assets/sound/sound3.mp3");
var sound:Sound= new Sound(urlReq);
sound.play();

Alternative to Excel as ASP.Net Report Generator

I use excel through vb.net/asp.net to generate reports from a web page and then send the file down to the user. We've had some issues with Excel being super slow/inefficient/not closing (even when we keep track of the process id and try to kill it in code...). So I'm looking for some flexible alternatives. We need a replacement that can:
Allow for inidivdual cell formatting including borders (different settings on each side), background colors, font styles/coloring, etc...
Allow for cell merging
Allow for formatting (bolding in this case) of a portion of the text inside of a cell while leaving the rest of the text unchanged
Image insertion/repositioning inside a cell (not crucial)
Multiple Worksheets per Workbook
These are all the features I can think of off hand, any help or suggestiong at alternative libraries to look at would be appreciated. We are running Excel 2007 on the server but we are rolling out Office 2010 to clients so I think that might open the doors for some more supported file formats, if that helps.
After looking through the various options and performing more independent research I ended up using EPPlus, which you can get # http://epplus.codeplex.com.
Thanks for all the suggestions.
I recommend you to use the DevExpress.XtraReports from DevExpress. It is a Licensed product, but offers you a friendly toolkit for generating great and complexity reports. It is well documented and easy to use, once you define a template (REPX) you can populate it with data by assigning to each element a value as well as using [mail merge] feature which will be automatically replaced once you bind with data the report. In the core of such technology is a well OO design of classes. Once you generate the report you can export it to the most common formats: XLS, HTML, PDF, RTF...
public void GenerateReportFile(string rptFileName, string param1, int param2)
{
XtraReport report = null;
try
{
report = new XtraReport();
//-- loads the layout template (repx file)
report.LoadLayout("SomeDirectory\report_template.repx");
//-- assign data to report controls
report.FindControl("Label1", true).Text = string.Format("{0:dd/MM/yyyy}", fecha1);
report.FindControl("Label2", true).Text = string.Format("{0:dd/MM/yyyy}", fecha1);
//-- gets data from some Data Acces Layer method and assig it to the report DataSource property
DALReport dal = new DALReport();
report.DataSource = dal.GetReport1Data(ExpEmp, param1, param2);
report.DataMember = "data";
report.ExportToPdf(rptFileName, options);
}
catch { throw; }
finally { if (report != null) { report.Dispose(); } report = null; }
}
For more information refers to: http://demos.devexpress.com/XtraReportsDemos/
There is another free library for .Net iTextSharp, this library
was originally written for Java, then was translated to C# for .Net
usage. The library is mainly for PDF documents creation but some
versions also supports XLS documents creation.
GNU plot is a little bit of a pain to get to run on windows but it is a an awesome tool
It sounds like you are using a library that opens Excel and uses MS Office Excel objects to create the Excel file. Since you are using 2007 and above, you may want to consider creating the Excel file manually using a library that creates the XML (therefore, Excel doesn't open at all).
Check out ExcelLibrary.
While doing a search on this, I found this page (on StackOverflow) that provides some sample code.
Office Web Components (though dated) is free and has worked for me in the past.
If you want to spend the loot, Aspose Cells is a good way to go also.

How can I convert a PDF file to an image?

I'm giving users the ability to upload an image to my Air app, then displaying this image in an image control. But I need to allow for PDF uploading in the same manner, so I need to convert the PDF to an image. I only care about the first page of the PDF they upload for now.
What I'm doing is:
1) User browses for a file with the file reference control
2) User chooses the image or PDF to upload
3) I encode said image to base64 and store it
4) I then load from that base64 with something like:
public function decodeImage(b64String:String):void{
var decoder:Base64Decoder = new Base64Decoder();
decoder.decode(b64String);
var imgLoader:Loader = new Loader();
imgLoader.loadBytes(decoder.toByteArray());
imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,decodedImageLoaded);
}
private function decodedImageLoaded(event:Event):void{
var imgLoader:Loader = (event.target as LoaderInfo).loader;
var bmp:Bitmap = Bitmap(imgLoader.content);
imgLoader.removeEventListener(Event.COMPLETE, decodedImageLoaded);
var img:Image = new Image();
img.source = bmp;
this.addChild(img);
}
This method is working great for .gif, .jpg, and .png. At some point in my process, probably the initial upload I need to convert the first page of a PDF to a png so that I can use the rest of this process.
I welcome any ideas with the sole requirement being that it has to be a part of the Air app, I can't use something like ImageMagick that runs on a server, but I could use a component that I can compile in to the finished product.
I believe AlivePDF for Flash now has capabilities to read a PDF file. You might try PurePDF, as well. You could potentially use ones of these to get that desired page and convert it to an image.
Have you seen swftools? It has the ability to convert a PDF to a SWF, PNG, JPG, etc...

How to efficiently scale and crop images in an ASP.NET app?

We're having problems with an ASP.NET application which allows users to upload, and crop images. The images are all scaled to fixed sizes afterwards. We basically run out of memory when a large file is processed; it seems that the handling of JPEG is rather inefficient -- we're using System.Drawing.BitMap. Do you have any general advice, and perhaps some pointers to a more efficient image handling library? What experiences do you have?
I had the same problem, the solution was to use System.Drawing.Graphics to do the transformations and dispose every bitmap object as soon as I was finished with it. Here's a sample from my library (resizing) :
public Bitmap ApplyTo(Bitmap bitmap)
{
using (bitmap)
{
Bitmap newBitmap = new Bitmap(bitmap, CalculateNewSize(bitmap));
using (Graphics graphics = Graphics.FromImage(newBitmap))
{
graphics.SmoothingMode =
SmoothingMode.None;
graphics.InterpolationMode =
InterpolationMode.HighQualityBicubic;
graphics.CompositingQuality =
CompositingQuality.HighQuality;
graphics.DrawImage(
bitmap,
new Rectangle(0, 0, newBitmap.Width, newBitmap.Height));
}
return newBitmap;
}
}
I found imageresizer and its great. and good API. Works Great.
Downloaded from Visual studio 2010 Extension Manager: http://nuget.org/.
Easy Steps to download API in VS-2010:
1). Install Extension http://nuget.org/.
3). Find and Install ImageResizing
4).Then Code: (I m using here cropping. you can use any) Documentation on imageresizing.net
string uploadFolder = Server.MapPath(Request.ApplicationPath + "images/");
FileUpload1.SaveAs(uploadFolder + FileUpload1.FileName);
//The resizing settings can specify any of 30 commands.. See http://imageresizing.net for details.
ResizeSettings resizeCropSettings = new ResizeSettings("width=200&height=200&format=jpg&crop=auto");
//Generate a filename (GUIDs are safest).
string fileName = Path.Combine(uploadFolder, System.Guid.NewGuid().ToString());
//Let the image builder add the correct extension based on the output file type (which may differ).
fileName = ImageBuilder.Current.Build(uploadFolder + FileUpload1.FileName, fileName, resizeCropSettings, false, true);
Try!!! its very awsumm and easy to use. thanks.
A couple of thoughts spring to mind -
What size of images do you allow
your users to upload and can you
impose restrictions on this?
When you're using the
System.Drawing.Bitmap class, are you
remembering to dispose of it
correctly? We found one of the primary causes of System.OutOfMemoryException exceptions on our shared hosting platform was users not disposing of Bitmap objects correctly.
Kev
There was an older bug with .net that all images would default to 32 bits per pixel - at this size you can exhaust your memory pretty fast. Please use PixelFormat structure to make sure this is not the case for your problem.
This link might help: http://msdn.microsoft.com/en-us/library/aa479306.aspx
Do you perhaps have a stack trace to look at?
I have also done some image editing after a user has uploaded an image. The only problems that I ran into were restrictions on file upload size on the browsers and timeouts. But nothing related to .Net's libraries.
Something else to consider. If you are doing multiple images or have some dangerous looping somewhere then are you making sure to flush() and dispose() things.

Resources