Search code examples
c#wpfdocumentviewer

Display html MemoryStream in DocumentViewer


I'm in C# WPF.

I want to create a print function. First I generate a MemoryStream from an XmlDocument:

XmlDocument xmlDoc;
XslCompiledTransform _xsl; // Initialized before
/* creating Doc */

MemoryStream ms = new MemoryStream();
_xsl.Transform(xmlDoc, null, ms);
ms.Flush();
ms.Position = 0;

I can display the MemoryStream in a WebBrowser element using webBrowser.NavigateToStream(e.NewValue as Stream);. But now I want to display the MemoryStream before printing. I have a preview windows:

<Window Title="PrintView">    
    <Grid>          
        <DocumentViewer x:Name="printViewer"
                        Margin="10"
                        Document="{Binding DocumentView}"/>
    </Grid>
</Window>

The Binding element is:

FixedDocumentSequence _fixDoc = null;
public FixedDocumentSequence DocumentView
{
    get
    {
        return _fixDoc;
    }
    set
    {
        _fixDoc = value;
        OnPropertyChanged(nameof(DocumentView));
    }
}

But how can I create FixedDocumentSequence DocumentView from MemoryStream ms ?


Solution

  • You can achieve it by the following code:

    PackageUriString: can just be anything you want.

    private FixedDocumentSequence LoadXpsFromStream(Byte[] xpsByte, string packageUriString)
    {
      MemoryStream xpsStream = new MemoryStream(xpsByte);
      using (Package package = Package.Open(xpsStream))
      //Remember to create URI for the package
      Uri packageUri = new Uri(packageUriString);
      //Need to add the Package to the PackageStore
      PackageStore.AddPackage(packageUri, package);
      //Create instance of XpsDocument 
      XpsDocument document = new XpsDocument(package, CompressionOptions.MaximuCompression, packageUriString);
      //Do the operation on document here
      //Here I am viewing the document in the DocViewer
      return document.GetFixedDocumentSequence();
    }
    

    Remember to keep the Package object in PackageStore until all operations complete on document.

      //Remove the package from store
      PackageStore.RemovePackage(packageUri);