开发者

Opening FlowDocument saved as XPS document with XPS viewer?

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.ContentSt开发者_Go百科art, 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.


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜