使用XPS查看器打开保存为XPS文档的FlowDocument?

7

我正在使用以下代码并使用带有xps扩展名的文件名将WPF FlowDocument保存到文件系统:

// 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);
}

我的应用可以使用以下代码重新加载文档:

// 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);
}

然而,随Windows 7一起提供的XPS Viewer无法打开这些文件。保存的XPS文件显示XPS图标,但是当我双击其中一个时,XPS查看器无法打开它。错误消息显示“XPS Viewer无法打开此文档。”

你有什么想法可以让我的XPS文档能够被XPS Viewer打开吗?感谢您的帮助。


3
XPS文档并不等同于XAML包。 - Michael Damatov
1个回答

8

正如Michael所评论的那样,FlowDocument并不等同于XPS文档。FlowDocuments适用于屏幕阅读,并且在窗口大小更改时会自动重新排放,而XPS文档的布局是固定的。

你需要使用名为XpsDocument的类来编写XPS文档。你需要引用ReachFramework.dll程序集才能使用它。这里有一个简短的示例方法,可以将FlowDocument保存为XPS文档:

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在他的博客上提供了更大的示例(包括如何添加页眉和页脚以及重新调整输出)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接