Running on Empty

The few things I know, I like to share.

Using FlowDocuments XAML to print XPS Documents. (Part 4)


Welcome to Part 4 of the Using FlowDocument XAML to print XPS Documents series. This article will focus on saving XAML to an XPS Document file… finally.

In previous parts of this series I demonstrated creating DocumentPaginator, adjusting PageSize, and printing.  Saving the XPS document is actually quite easy at this point. I will be building upon the classes discussed in Part 1, 2 and 3 of this series.

Creating a method to save an XPS document from a DocumentPaginator.

This method accepts a DocumentPaginator source and saves it to test.xps file, clean and simple.  Obvious improvments would be to use a save file dialogue.

public static void CreateXPSDocument(DocumentPaginator paginator)
    using (Package container = Package.Open("test" + ".xps", FileMode.Create))
        using (XpsDocument xpsDoc = new XpsDocument(container, CompressionOption.Maximum))
            XpsSerializationManager xpsSM = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);

Using the CreateXPSDocument method.

private void SaveXPSButton_Click(object sender, RoutedEventArgs e)
    SampleClass sample = new SampleClass();
    sample.Sample = "FlowDocument DataBinding Sample";   

    IDocumentPaginatorSource flowDocument =
        XamlTemplatePrinter.RenderFlowDocumentTemplate(Path.Combine(Environment.CurrentDirectory, "XamlDocumentTemplate.xaml"), sample);      

    flowDocument.DocumentPaginator.PageSize = new Size(96 * 8, 96 * 11);       


Yes, it really was that easy. The XamlTemplatePrinter class we have created during this series is now actually becoming quite useful. This article will conclude this series for now, unless I think of something I might have forgotten.Please feel free to comment or leave suggestions for future articles.


January 4, 2008 Posted by | C#, WPF, XAML, XPS | 12 Comments