Is the FlowDocument opening saved as an XPS document using the XPS viewer?

I save the WPF FlowDocument to the file system using this code and the file name with the 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 application 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 cannot open files. Saved XPS files display the XPS icon, but when you double-click it, the XPS viewer cannot open it. The error message reads: "XPS Viewer cannot open this document."

Any idea what I need to do for my XPS document to make it available to view the XPS Viewer? Thank you for your help.

+6
wpf xps flowdocument
source share
1 answer

As Michael noted, FlowDocument does not match an XPS document. FlowDocuments are designed to be read on the screen and will automatically update when the window is resized, while the layout of the XPS document is fixed.

The class required to write XPS documents is called XpsDocument. To use it, refer to the assembly of ReachFramework.dll. Here is a brief example of a method that saves a FlowDocument in 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 scale the output).

+6
source share

All Articles