Running on Empty

The few things I know, I like to share.

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


Welcome to Part 5 of the Using FlowDocument XAML to print XPS Documents series.  This article has been a long time coming.  In this article I will focus on creating dynamic XAML content.

Creating a method to Load Xaml Strings

This method simply takes a raw XAML string and loads it into a FlowDocument.

        public static IDocumentPaginatorSource RenderFlowDocumentString(string rawXamlString, object dataContextObject)
            FlowDocument document = XamlReader.Load(new XmlTextReader(new StringReader(rawXamlString))) as FlowDocument;
            if (dataContextObject != null)
                document.DataContext = dataContextObject;
            return document;

Now all we need to do is create some XAML strings.

Using the new Xaml string loader plus some.

        public void PrintGenericList(List<Awards> awardList)
            PrintDialog flowPrintDialog = XamlTemplatePrinter.GetPrintDialog();
            if (flowPrintDialog == null)

                StringBuilder xamlString = new StringBuilder();
                xamlString.Append("<FlowDocument xmlns=\"<a href="\">\</a>" \nxmlns:x=\"<a href="\">\</a>">");
                foreach (Awards award in awardList)
                    xamlString.Append("<Paragraph FontFamily=\"Arial\" Margin=\"20\">");
                    xamlString.AppendFormat("<TextBlock Text=\"{0}  {1}\" Margin=\"170,0,0,0\" />", award.SerialNumber, award.ControlNumber);
                    xamlString.Append("<TextBlock Text=\"\" Margin=\"170,0,0,0\" />");


                IDocumentPaginatorSource flowDocument =
                       XamlTemplatePrinter.RenderFlowDocumentString(xamlString.ToString(), null);

                flowDocument.DocumentPaginator.PageSize = new Size(96 * 5, 96 * 2);

                PrintQueue flowPrintQueue = flowPrintDialog.PrintQueue;
                XamlTemplatePrinter.PrintFlowDocument(flowPrintQueue, flowDocument.DocumentPaginator);            


In this article I demonstrated building dynamic XAML to print or same as an XPS document.  I am personally using this in an application to format labels to be sent to a printer.


April 30, 2008 Posted by | C#, WPF, XAML, XPS | 4 Comments