20

I'd like to create an XPS document for storing and printing.

What is the easiest way to create an XPS document (for example with a simple grid with some data inside) in my program, and to pass it around?

Sam
  • 28,421
  • 49
  • 167
  • 247
  • This might also help: [http://blogs.msdn.com/fyuan/archive/2005/09/12/463887.aspx](http://blogs.msdn.com/fyuan/archive/2005/09/12/463887.aspx) – noesgard Dec 11 '08 at 09:29

3 Answers3

15

Nothing easy about it. But it can be done. I've got some (sadly, still buggy) sample code and information on my blog for creating the document in memory.

Here's some code I whipped up for testing that encapsulates everything (it writes a collection of FixedPages to an XPS document in memory). It includes code for serializing the document to a byte array, but you can skip that part and just return the document:

public static byte[] ToXpsDocument(IEnumerable<FixedPage> pages)
{
    // XPS DOCUMENTS MUST BE CREATED ON STA THREADS!!!
    // Note, this is test code, so I don't care about disposing my memory streams
    // You'll have to pay more attention to their lifespan.  You might have to 
    // serialize the xps document and remove the package from the package store 
    // before disposing the stream in order to prevent throwing exceptions
    byte[] retval = null;
    Thread t = new Thread(new ThreadStart(() =>
    {
        // A memory stream backs our document
        MemoryStream ms = new MemoryStream(2048);
        // a package contains all parts of the document
        Package p = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);
        // the package store manages packages
        Uri u = new Uri("pack://TemporaryPackageUri.xps");
        PackageStore.AddPackage(u, p);
        // the document uses our package for storage
        XpsDocument doc = new XpsDocument(p, CompressionOption.NotCompressed, u.AbsoluteUri);
        // An xps document is one or more FixedDocuments containing FixedPages
        FixedDocument fDoc = new FixedDocument();
        PageContent pc;
        foreach (var fp in pages)
        {
            // this part of the framework is weak and hopefully will be fixed in 4.0
            pc = new PageContent();
            ((IAddChild)pc).AddChild(fp);
            fDoc.Pages.Add(pc);
        }
        // we use the writer to write the fixed document to the xps document
        XpsDocumentWriter writer;
        writer = XpsDocument.CreateXpsDocumentWriter(doc);
        // The paginator controls page breaks during the writing process
        // its important since xps document content does not flow 
        writer.Write(fDoc.DocumentPaginator);
        // 
        p.Flush();

        // this part serializes the doc to a stream so we can get the bytes
        ms = new MemoryStream();
        var writer = new XpsSerializerFactory().CreateSerializerWriter(ms);
        writer.Write(doc.GetFixedDocumentSequence());

        retval = ms.ToArray();
    }));
    // Instantiating WPF controls on a MTA thread throws exceptions
    t.SetApartmentState(ApartmentState.STA);
    // adjust as needed
    t.Priority = ThreadPriority.AboveNormal;
    t.IsBackground = false;
    t.Start();
    //~five seconds to finish or we bail
    int milli = 0;
    while (buffer == null && milli++ < 5000)
        Thread.Sleep(1);
    //Ditch the thread
    if(t.IsAlive)
        t.Abort();
    // If we time out, we return null.
    return retval;
}

Note the crappy threading code. You can't do this on MTA threads; if you are on an STA thread you can get rid of that as well.

  • 2
    Interesting thread timeout code - any reason you did not just use t.Join(5000) instead? I'm still trying to comprehend the rest :) – Sam Dec 09 '08 at 12:30
  • Will this code compile/work in .NET 4? I see the variable "writer" defined twice in the same scope, and the items in the FixedPage collection will be accessed from a different thread than the one on which they are created. – Michael Apr 15 '12 at 21:21
  • 2
    I have tried this piece of code and getting error : Parameter is unexpected type 'System.String'. Expected type is 'System.Windows.Documents.FixedPage'. Parameter name: value in line ((IAddChild)pc).AddChild(fp); How can I resolve this? – Sudha Apr 02 '13 at 09:19
  • @sudha you're trying to pass a string in instead of a FixedPage. If you can't figure out what's wrong with that I have no help for you. –  Apr 02 '13 at 13:04
  • @ Will Can you please help me to cteate a FixedPage? I didn't get an idea of how its creating.. – Sudha Apr 03 '13 at 05:14
  • @Sudha go read the docs, try it yourself, and if you have a problem ask a question. –  Apr 03 '13 at 12:18
  • @Will I have tried this one but I dont know how to create IEnumerable pages. At first I gave the file path as pages. But later I got some information about FixedPage from http://msdn.microsoft.com/en-us/library/system.windows.documents.fixedpage.aspx. But I couldn't create a FixedPage from the information got from this link. – Sudha Apr 04 '13 at 04:25
  • 4
    @Sudha yes, this is when it is convenient to have a programmer. I suggest you hire one. –  Apr 04 '13 at 04:50
  • @Will Sorry.. I didnt get you.. programmer for what? – Sudha Apr 04 '13 at 08:21
  • Some parts of this code went a long way toward helping me with an issue. Thanks! – krflol Oct 31 '19 at 14:09
7

If you are working in .NET (v2 or later), you can very easily generate a valid XPS document from a WPF visual.

For an example, take a look at this blog post of mine:

http://nixps.blogspot.com/2008/12/wpf-to-pdf.html

In the example I create a WPF visual and convert it as an XPS file, before doing further processing.

If you are not working in .NET, or want more control on the XPS output, then I would advise you to use a library (like the NiXPS SDK) for this. It is a lot easier to code for, and a lot less error prone than writing out the XML constructs yourself (and doing proper resource management, etc...).

nixps
  • 291
  • 1
  • 3
  • 1
    The link to your blog does not work, maybe you can copy the code example in your answer instead? – Sam Dec 09 '08 at 15:11
  • Copy and paste the URL instead of following it, it's just the href that is wrong. It shows perfectly how to create an XPS-file from a WPF visual. – Kristof Van Landschoot Dec 11 '08 at 08:15
  • WPF (Windows Presentation Foundation) wasn't released until .NET Framework 3.0 (with Windows Vista) – Ian Boyd Feb 07 '12 at 20:40
  • Notice: *NiXPS SDK* costs money (750€ is the cheapest package at the moment) – itsho May 17 '15 at 08:25
  • NiXPS seems dead at the moment. The homepage http://nixps.com/ shows a blank page and the last time the news was updated was 2010 (http://www.nixps.com/news.php?id=1) – Patrick D'Souza Jun 08 '15 at 07:54
0

All it is, is really XML. If you're comfortable working with XML files, you should have no problem working with XPS documents. Here's a simple tutorial I've used in the past to get me started:

http://blogs.ocrasoft.nl/jeroenveurink/?p=21

BFree
  • 102,548
  • 21
  • 159
  • 201
  • Bizarre. But definitely one way you can do it. I wouldn't suggest doing it this way unless you understood the XPS document specifications. –  Dec 09 '08 at 12:15
  • Creating a bizarre XML document, compressed into a zip? Not exactly what I had in mind when I wrote 'easiest way' :) – Sam Dec 09 '08 at 12:24
  • Is this tutorial still available anywhere? The blog's gone - but I'm quite interested... – Mladen Mihajlovic Jan 30 '21 at 10:13