Display XPS Document in WPF

5.1k views Asked by At

I need to display data from a database into a WPF app and save it as an XPS document. I want to display it as part of a main window (with Toolbar, Menu and StatusBar) and not as a new window.

What control(s) should I use? Currently, I am looking at FixedDocument and FlowDocument. Am I on the right track? Any good material on how to start?

2

There are 2 answers

2
kundan kumar On

Add a Document viewer in your XAML

And add this code in the cs file:

string fileName = null;
string appPath= System.IO.Path.GetDirectoryName(Assembly.GetAssembly(typeof(DocumentWindow)).CodeBase);
fileName = appPath + @"\Documents\Help.xps";
fileName = fileName.Remove(0, 6);
XpsDocument doc = new XpsDocument(fileName, FileAccess.Read);
docView.Document = doc.GetFixedDocumentSequence();
0
JWP On

Improving on Stehpen's answer above...

Assume you've added a documents folder to your project:

enter image description here

Create a method GetDocument where the GetFilePath method refers to the Folder/Filename in the folder above.

    private void GetDocument()
    {     
        string fileName = Environment.CurrentDirectory.GetFilePath("Documents\\Title.xps");
        Debugger.Break();
        XpsDocument doc = new XpsDocument(fileName, FileAccess.Read);
        XDocViewer.Document = doc.GetFixedDocumentSequence();
    }

Where GetFilePath is an extension method that looks like this:

public static class StringExtensions
    {
        public static string GetFilePath(
            this string EnvironmentCurrentDirectory, string FolderAndFileName)
        {
            //Split on path characters
            var CurrentDirectory = 
                EnvironmentCurrentDirectory
                .Split("\\".ToArray())
                .ToList();
            //Get rid of bin/debug (last two folders)
            var CurrentDirectoryNoBinDebugFolder = 
                CurrentDirectory
                .Take(CurrentDirectory.Count() - 2)
                .ToList();
            //Convert list above to array for Join
            var JoinableStringArray = 
                CurrentDirectoryNoBinDebugFolder.ToArray();
            //Join and add folder filename passed in
            var RejoinedString = 
                string.Join("\\", JoinableStringArray) + "\\";
            var final = RejoinedString + FolderAndFileName;
            return final;
        }
    }