Flash CS5.5-AIR i cant write HTML tags with writeUTFBytes - actionscript-3

i need to write some XML using AIR from Flash CS5.5
My code works, but i dont know how to write some html tags without flash converting < to ; & gt;
I want to write HTML code for a .
How can i achieve that?
This is the type of code i am using, im working into an AIR from Flash CS5.5
Everything works fine except i dont get the "<" but the ;& gt; in the outputfile and the same for many of the HTML signs like > etc.
function SaveFile(event:MouseEvent){
var objs:XML = new XML( <objects /> );
var ball1:XML = <ball />.appendChild(input_text.text);
// In the input i want to write the CDATA and the HTML text dynamically each time
ball1.#xPos = 12;
ball1.#yPos = 42;
objs.appendChild( ball1 );
var vFile = File.desktopDirectory.resolvePath('file.xml');
var vStream = new FileStream();
vStream.open(vFile, FileMode.WRITE);
vStream.writeUTFBytes(objs);
vStream.close();
}

You are passing a String to the appendChild function and that's why you got your result as a "text" in your xml file. So to avoid that, you have just to pass an XML object instead of the String :
// ...
var ball1:XML = <ball />.appendChild(new XML(input_text.text));
// ...
EDIT :
To add the XML declaration to your XML file, you can use a XMLDocument like this :
// ...
objs.appendChild(ball1);
var xml_document:XMLDocument = new XMLDocument(objs.toXMLString());
xml_document.xmlDecl = '<?xml version="1.0" encoding="utf-8"?>\n';
var file = File.desktopDirectory.resolvePath('file.xml');
var file_stream = new FileStream();
file_stream.open(file, FileMode.WRITE);
file_stream.writeUTFBytes(xml_document.toString());
file_stream.close();
Hope that can help.

Related

An error occurred while parsing EntityName. Line 119, position 40

Although I find similar questions as mine, the answers to those questions don't answer my question. I'm trying to convert XML and XSLT into HTML so it can get converted to a PDF.
I have an HTML page (249 lines) that gets converted to XSLT:
`string filePath = hostURL + "path/to/somefile.htm";`
`xslt = client.DownloadData(filePath);`
The corresponding XML gets generated with XmlDocument xmlDoc = new XmlDocument();
then XmlElement nodes are added and MemoryStream xmlStream is returned where xslt and xmlStream are passed to
`string html = Helper.GenerateHTML(xmlStream, xslt);`
In Helper.GenerateHTML(this MemoryStream xmlStream, byte[] xsltByte) this occurs:
`XmlReaderSettings settings = new XmlReaderSettings();
settings.XmlResolver = null;
settings.DtdProcessing = DtdProcessing.Parse;`
`using (var xsltMemoryStream = new MemoryStream(xsltByte))
using (var xmlReader = XmlReader.Create(xsltMemoryStream, settings))
using (var xmlMemoryStream = new MemoryStream())`
`using (var xmlTextWriter = new XmlTextWriter(xmlMemoryStream, null))
{
var xct = new XslCompiledTransform();
xct.Load(xmlReader);
...
}`
but I get the error at xct.Load(xmlReader); and the Create PDF button click that invoked this code does not result in a PDF being created nor displayed.
Neither the XSL nor XML have symbol-related ("&" vs. "&", etc.) issues. For what it's worth, there is another process that extracts XSLT from the database (instead of an HTML file), generates its corresponding XML with XMLGenerator xgen = new XMLGenerator() then calls Helper.GenerateHTML(xmlStream, xslt) but does not choke at the xct.Load(xmlReader); line of code and a resulting PDF is displayed.
Why does the parsing error occur?

HTML from Database to PDF

I need to generate pdf from html dynamically using asp.net. HTML is stored in database. HTML has tables and css, upto 10 pages. I have tried iTextSharp by directly passing html, it produces pdf which is not opening. Destination pdf.codeplex.com has no documentation, it produces PDF with styles from parent page.
Any other solution will be helpful.
I've tried many HTML to PDF solutions including iTextSharp, wkhtmltopdf and ABCpdf (paid)
I'm currently settled on PhantomJS a headless, open-source, WebKit-based browser. It is scriptable with a javascript API which is reasonably well documented.
The only disadvantage I found was that attempting to use stdin to pass HTML into the process was unsuccessful because the REPL still has some bugs. I also found that using stdout seemed to be a lot slower than simply allowing the process to write to disk.
The code below avoids stdin and stdout by creating the javascript input as a temp file, executing PhantomJS, copying the output file to a MemoryStream and cleaning up the temporary files at the end.
using System.IO;
using System.Drawing;
using System.Diagnostics;
public Stream HTMLtoPDF (string html, Size pageSize) {
string path = "C:\\dev\\";
string inputFileName = "tmp.js";
string outputFileName = "tmp.pdf";
StringBuilder input = new StringBuilder();
input.Append("var page = require('webpage').create();");
input.Append(String.Format("page.viewportSize = {{ width: {0}, height: {1} }};", pageSize.Width, pageSize.Height));
input.Append("page.paperSize = { format: 'Letter', orientation: 'portrait', margin: '1cm' };");
input.Append("page.onLoadFinished = function() {");
input.Append(String.Format("page.render('{0}');", outputFileName));
input.Append("phantom.exit();");
input.Append("};");
// html is being passed into a string literal so make sure any double quotes are properly escaped
input.Append("page.content = \"" + html.Replace("\"", "\\\"") + "\";");
File.WriteAllText(path + inputFileName, input.ToString());
Process p;
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = path + "phantomjs.exe";
psi.Arguments = inputFileName;
psi.WorkingDirectory = Path.GetDirectoryName(psi.FileName);
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
p = Process.Start(psi);
p.WaitForExit(10000);
Stream strOut = new MemoryStream();
Stream fileStream = File.OpenRead(path + outputFileName);
fileStream.CopyTo(strOut);
fileStream.Close();
strOut.Position = 0;
File.Delete(path + inputFileName);
File.Delete(path + outputFileName);
return strOut;
}

Saving string to text file in AS3

I have a function for writing String to a text file. It works, but for some reason (encoding?) it adds some weird data to the beginning of the file.
Here is the relevant code:
var file:File = new File(OUTPUT_FILE_NAME);
var stream:FileStream = new FileStream();
stream.open(file, FileMode.WRITE);
stream.writeUTF("Hello World!");
stream.close();
When I open the file in Notepad++, it shows this:
What am I doing wrong?
use this stream.writeUTFBytes("Hello World"); instead of stream.writeUTF("Hello World!");
if we use writeUTF then it write prefix the string with a 16-bit length word. if you use writeUTFBytes then it omit this prefix Length String.
writeUTF prepends the length of the string before writing it to file. Use writeUTFBytes if you want to write only the string.

Outputting an uint / Number value as a String in ActionScript3

Let me preface this by stating that I am not terribly familiar with ActionScript, so forgive any seemingly obvious things that I may be missing.
I current have a very simple function with an AS3 application that will output a file when a button is clicked using a FileReference object as seen below :
//Example download event
public function download(event:MouseEvent):void
{
//Build a simple file to store the current file
var outputFile:FileReference = new FileReference();
//Perform a function to build a .wav file from the existing file
//this returns a ByteArray (buffer)
downloadBuffer = PrepareAudioFile();
//Attempt to build the filename (using the length of bytes as the file name)
var fileName:String = downloadBuffer.length.toString() + ".wav";
//Save the file
audioFile.save(downloadBuffer, fileName);
}
There appears to be an error occurring somewhere within here that is resulting in the File not being outputted at all when I attempt to concatenate the file name as seen above. However, if I replace the fileName variable with a hard-coded option similar to the following, it works just fine :
audioFile.save(downloadBuffer, "Audio.wav");
Ideally, I would love to derive the duration of the file based on the length of the byteArray using the following :
//Get the duration (in seconds) as it is an audio file encoded in 44.1k
var durationInSeconds:Number = downloadBuffer.length / 44100;
//Grab the minutes and seconds
var m:Number = Math.floor(durationInSeconds / 60);
var s:Number = Math.floor(durationInSeconds % 60);
//Create the file name using those values
audioFile.save(downloadBuffer, m.toString() + "_" + s.toString() + ".wav");
Any ideas would be greatly appreciated.
Where is the problem other than missing the parentheses in m.toString()?
Aren't you missing a .lenght before the division of downloadBuffer as well?
I was finally able to come up with a viable solution that required explicit typing of all of the variables (including using a separate variable for the .toString() operations) as seen below :
public function download(event:MouseEvent):void
{
//Build a simple file to store the current file
var outputFile:FileReference = new FileReference();
//Perform a function to build a .wav file from the existing file
//this returns a ByteArray (buffer)
downloadBuffer = PrepareAudioFile();
//When accessing the actual length, this needed to be performed separately (and strongly typed)
var bufferLength:uint = downloadBuffer.length;
//The string process also needed to be stored in a separate variable
var stringLength:String = bufferLength.toString();
//Use the variables to properly concatenate a file name
var fileName:String = dstringLength + ".wav";
//Save the file
audioFile.save(downloadBuffer, fileName);
}
It's bizarre that these had to explicitly be stored within separate values and couldn't simply be used in-line as demonstrated in the other examples.

Any function or method by which I can save the new modified data to the xml file from which it is retrieved or loaded?

How can I save the modified data to the same xml file after loading from that external xml file in ActionScript3.
Is there exist any function or method or any way to save the modified data again in the same file from which it was loaded.
import flash.net.URLRequest;
var myXML:XML = new XML();
var XML_URL:String = "sample.xml";
var myXMLURL:URLRequest = new URLRequest(XML_URL);
var myLoader:URLLoader = new URLLoader(myXMLURL);
myLoader.addEventListener("complete", xmlLoaded);
function xmlLoaded(event:Event):void
{
myXML = XML(myLoader.data);
trace("Data loaded.");
trace(myXML); //showing output of just loaded xml file.
//process of adding new child node or property.
var newnode:XML = new XML();
newnode =
<student >
<sname srno="2">mm</sname>
<father tax="no">
<fname>Ratan</fname>
<focc>business man</focc>
<mobno>9928946899</mobno>
</father>
</student>;
myXML = myXML.appendChild(newnode);
trace(myXML); //showing o/p after being the child-node appended.
}
where the sample.xml file located in the same working path, contains only the following data.-
<data>
<student srno="1" class="5" rollno="1">
<sname>Rohan Jain</sname>
<father tax="yes">
<fname>Ronak Jain</fname>
<focc>teacher</focc>
<mobno>9928946899</mobno>
</father>
</student>
</data>
If you're building a browser based application; nothing you can do on the client will save the file to a specific name and location. You'll have to send your updated doc to the server for saving. It is easy to write a service to do this in most server side languages I have dealt with.
If you want to save the file to the client machine; you can do so using FileReference.save(). However, this requires user input and there is no way to guarantee what the user will name the file or where they'll put it.