从字节数组创建XPS文档

时间:2017-08-02 07:59:07

标签: c# arrays wpf

我有一个存储在sql server中的xps文件内容的字节数组,我试图将其检索回来并将其显示在DocumentViewer控件中。

cmd.CommandText = "select text from [table] where docName = '" + selectedText + "'";
using (SqlDataReader read = cmd.ExecuteReader())
{
    while (read.Read())
    {
        byte[] retrieve = ((byte[])read["text"]); //text is column name for the byte array
        var package = System.IO.Packaging.Package.Open(new MemoryStream(retrieve));
        var xpsDocument = new XpsDocument(package, System.IO.Packaging.CompressionOption.Maximum);
        pptViewer.Visibility = System.Windows.Visibility.Visible;
        pptViewer.Document = xpsDocument.GetFixedDocumentSequence();
    }
}

问题是此行new XpsDocument(package, System.IO.Packaging.CompressionOption.Maximum)需要一个额外的参数 - 文件的Uri。我没有它,因为它没有在本地存储 - 我将它转换为字节数组然后存储它,所以原来的xps文件已经消失。

可以在没有任何uri的情况下将字节数组转换为xps文档吗?如果没有,我怎样才能在我的wpf应用程序中显示文档(来自字节数组,coruse)?

1 个答案:

答案 0 :(得分:2)

您可以使用一种方法从字节数组中提取FixedDocumentSequence,如:

private FixedDocumentSequence GetFixedDocumentSequence(byte[] xpsBytes)
{
    Uri packageUri;
    XpsDocument xpsDocument = null;

    using (MemoryStream xpsStream = new MemoryStream(xpsBytes))
    {
        using (Package package = Package.Open(xpsStream))
        {
            packageUri = new Uri("memorystream://myXps.xps");

            try
            {
                PackageStore.AddPackage(packageUri, package);
                xpsDocument = new XpsDocument(package, CompressionOption.Maximum, packageUri.AbsoluteUri);

                return xpsDocument.GetFixedDocumentSequence();
            }
            finally
            {
                if (xpsDocument != null)
                {
                    xpsDocument.Close();
                }
                PackageStore.RemovePackage(packageUri);
            }
        }
    }
}

然后调用它在您的代码中设置DocumentViewer

pptViewer.Document = GetFixedDocumentSequence(retrieve);