I’m looking for the best way to convert from a WordprocessingDocument object my application already creates (I can’t change this) into a FlowDocument for use in a WPF application.
What’s the best method for doing this via Aspose?
I would like to avoid using any temporary files, and do all the conversion in memory.
Here’s what I have, currently, that does use temporary files. This is in a sample application, so you’ll see the creation of the WordprocessingDocument object, but this is something that I can’t get away from in the real application; though I do have some control over how the WordprocessingDocument gets created.
As you’ll see, I currently write the WordprocessingDocument to a file, open it with Aspose, save it to a MemoryStream (doing a conversion in the process) and then stripping out some text, so that I can use XamlReader.Parse to convert it into an actual FlowDocument object. That just seems like a lot of hoops to jump through, and I’m hoping that there’s a simpler method that Aspose provides.
private FlowDocument LoadDocXFileAsFlowDocument(string filePath)
{
// Start simulation of real application
string tempFilePath = null;
WordprocessingDocument wpDoc = null;
MemoryStream stream = null;
try
{
tempFilePath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName());
var byteArray = File.ReadAllBytes(filePath);
stream = new MemoryStream();
stream.Write(byteArray, 0, byteArray.Length);
wpDoc = WordprocessingDocument.Open(stream, false);
// End simulation of real application
// Begin conversion from WordprocessingDocument to FlowDocument
// This is the section I’m really looking to replace
File.WriteAllBytes(tempFilePath, stream.ToArray());
var asposeDoc = new Document(tempFilePath);
using (var ms = new MemoryStream())
{
asposeDoc.Save(ms, SaveFormat.XamlFlow);
var s = Encoding.UTF8.GetString(ms.ToArray());
var startIndex = s.IndexOf(’<’);
var stopIndex = s.LastIndexOf(’>’);
s = s.Substring(startIndex, stopIndex - startIndex + 1);
s = Regex.Replace(s.Trim(), @"^<?xml.+?>(?=<)", string.Empty);
var convertedFlowDocument = XamlReader.Parse(s) as FlowDocument;
return convertedFlowDocument;
// End conversion from WordprocessingDocument to FlowDocument
}
}
finally
{
// Continue simulation of real application
if (File.Exists(tempFilePath))
File.Delete(tempFilePath);
if (wpDoc != null)
wpDoc.Dispose();
if (stream != null)
stream.Dispose();
}