在DocumentViewer中显示html MemoryStream

本文关键字:html MemoryStream 显示 DocumentViewer | 更新日期: 2023-09-27 18:03:37

我在c# WPF。

我想创建一个打印函数。首先,我从XmlDocument生成MemoryStream:

XmlDocument xmlDoc;
XslCompiledTransform _xsl; // Initialized before
/* creating Doc */
MemoryStream ms = new MemoryStream();
_xsl.Transform(xmlDoc, null, ms);
ms.Flush();
ms.Position = 0;

我可以使用webBrowser.NavigateToStream(e.NewValue as Stream);在WebBrowser元素中显示MemoryStream。但是现在我想在打印之前显示MemoryStream。我有一个预览窗口:

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

Binding元素是:

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

但是如何从MemoryStream ms创建FixedDocumentSequence DocumentView呢?

在DocumentViewer中显示html MemoryStream

您可以通过以下代码实现:

PackageUriString:可以是你想要的任何东西。

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();
}

请记住将Package对象保存在PackageStore中,直到对文档的所有操作完成。

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