views:

310

answers:

1

I am saving a WPF FlowDocument to the file system, using this code and a fileName with an xps extension:

// Save FlowDocument to file system as XPS document
using (var fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
    var textRange = new TextRange(m_Text.ContentStart, m_Text.ContentEnd);
    textRange.Save(fs, DataFormats.XamlPackage);
}

My app can reload the document using this code:

// Load file
using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
    m_Text = new FlowDocument();
    var textRange = new TextRange(m_Text.ContentStart, m_Text.ContentEnd);
    textRange.Load(fs, DataFormats.XamlPackage);
}

However, the XPS Viewer that ships with Windows 7 can't open the files. The saved XPS files display the XPS icon, but when I double click one, the XPS viewer fails to open it. The error message reads "The XPS Viewer cannot open this document."

Any idea what I need to do to my XPS document to make it openable by the XPS Viewer? Thanks for your help.

+2  A: 

As Michael commented, a FlowDocument is not the same as an XPS document. FlowDocuments are meant for on-screen reading and will reflow automatically when the window size is changed, while the layout of an XPS document is fixed.

The class you need for writing XPS documents is called XpsDocument. You need to reference the ReachFramework.dll assembly to use it. Here's a short example of a method that saves a FlowDocument to an XPS document:

using System.IO;
using System.IO.Packaging;
using System.Windows.Documents;
using System.Windows.Xps.Packaging;
using System.Windows.Xps.Serialization;

namespace XpsConversion
{
    public static class FlowToXps
    {
        public static void SaveAsXps(string path, FlowDocument document)
        {
            using (Package package = Package.Open(path, FileMode.Create))
            {
                using (var xpsDoc = new XpsDocument(
                    package, System.IO.Packaging.CompressionOption.Maximum))
                {
                    var xpsSm = new XpsSerializationManager(
                        new XpsPackagingPolicy(xpsDoc), false);
                    DocumentPaginator dp = 
                        ((IDocumentPaginatorSource)document).DocumentPaginator;
                    xpsSm.SaveAsXaml(dp);
                }
            }
        }
    }
}

Feng Yuan has a larger example on his blog (including how to add headers and footers and rescale output).

odd parity