如何从字节数组创建XpsDocument



我想从字节数组创建一个新的System.Windows.Xps.Packaging.XpsDocument对象,因为我不想立即将其存储在本地计算机上。

通过使用临时文件,它可以很好地工作:

public static XpsDocument OpenXpsDocument(string url)
{
    WebClient webClient = new System.Net.WebClient();
    byte[] data = webClient.DownloadData(url);
    using (BinaryWriter writer = new System.IO.BinaryWriter(File.OpenWrite(xpsTempFilePath)))
    {
        writer.Write(data);
        writer.Flush();
    }
    XpsDocument xpsDocument = new System.Windows.Xps.Packaging.XpsDocument(xpsTempFilePath, FileAccess.Read);
    return xpsDocument;
}

然而,我想完成的更像是:

public static XpsDocument OpenXpsDocument(string url)
{
    WebClient webClient = new WebClient();
    byte[] data = webClient.DownloadData(url);
    Package package;
    using (Stream stream = new MemoryStream(data))
    {
        package = System.IO.Packaging.Package.Open(stream);
    }
    XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.SuperFast, url);
    return xpsDocument;
}

上述方法的用法如下:

XpsDocument xps = TaxReturnCreator.OpenXpsDocument(tempFileUrl);
documentViewer1.Document = xps.GetFixedDocumentSequence();

并且,使用最后描述的尝试在WPF窗口中显示XPS内容的方法(不保存(会导致System.ObjectDisposedException("无法访问关闭的流"(崩溃(第一种方法工作正常(。

创建XpsDocument后,我应该保持流打开吗?还是我缺少了其他东西?也许有人知道一种完全不同/更好的方法,可以通过网络将XPS数据检索为字节,并根据数据创建XpsDocument对象?

您不能关闭支持XpsDocument的流。您必须允许程序包管理备份MemoryStream,一旦收集到此程序包,就会收集该流。这样做可能有点异端:

public static XpsDocument OpenXpsDocument(string url)
{
    var webClient = new WebClient();
    var data = webClient.DownloadData(url);
    var package = System.IO.Packaging.Package.Open(new MemoryStream(data));
    var xpsDocument = new XpsDocument(package, 
                                      CompressionOption.SuperFast, 
                                      url);
    return xpsDocument;
}

但这是必须要做的。

您应该尝试包含

XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.SuperFast, url);

进入using块,即

Package package;
using (Stream stream = new MemoryStream(data))
{
    package = System.IO.Packaging.Package.Open(stream);
    XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.SuperFast, url);
}
return xpsDocument;

相关内容

  • 没有找到相关文章

最新更新