.netwpfxpsdocumentdocumentviewer

.NET WPF Application : Loading a resourced .XPS document


I'm trying to load a .xps document into a DocumentViewer object in my WPF application. Everything works fine, except when I try loading a resourced .xps document. I am able to load the .xps document fine when using an absolute path, but when I try loading a resourced document it throws a "DirectoryNotFoundException"

Here's an example of my code that loads the document.

     using System.Windows.Xps.Packaging;

      private void Window_Loaded(object sender, RoutedEventArgs e)
        {
//Absolute Path works (below)
            //var xpsDocument = new XpsDocument(@"C:\Users\..\Visual Studio 2008\Projects\MyProject\MyProject\Docs\MyDocument.xps", FileAccess.Read); 
//Resource Path doesn't work (below)
var xpsDocument = new XpsDocument(@"\MyProject;component/Docs/Mydocument.xps", FileAccess.Read);
            DocumentViewer.Document = xpsDocument.GetFixedDocumentSequence();
        }

When the DirectoryNotFoundException is thrown, it says "Could not find a part of the path : 'C:\MyProject;component\Docs\MyDocument.xps'

It appears that it is trying to grab the .xps document from that path, as if it were an actual path on the computer, and not trying to grab from the .xps that is stored as a resource within the application.


Solution

  • XpsDocument ctor accepts either a file path or a Package instance. Here's how you can open a Package to use the latter approach:

    var uri = new Uri("pack://application:,,,/Docs/Mydocument.xps");
    var stream = Application.GetResourceStream(uri).Stream;
    Package package = Package.Open(stream);
    PackageStore.AddPackage(uri, package);
    var xpsDoc = new XpsDocument(package, CompressionOption.Maximum, uri.AbsoluteUri);
    var fixedDocumentSequence = xpsDoc.GetFixedDocumentSequence();
    _vw.Document = fixedDocumentSequence; // displaying document in viewer
    xpsDoc.Close();