Search code examples
c#.netwpfflowdocumentxpsdocument

creating an XPS Document from a FlowDocument and attach it on the fly


I have a FlowDocument that I want to convert to an XPS Document and attach it to an e-mail and send it all together. I'm using this code

public static Stream FlowDocumentToXPS(FlowDocument flowDocument, int width, int height)
{
    MemoryStream stream = new MemoryStream();
    using (Package package = Package.Open(stream, FileMode.Create,FileAccess.ReadWrite))
    {         
        using (XpsDocument xpsDoc = new XpsDocument(package, CompressionOption.Maximum))
        {
            xpsDoc.AddFixedDocumentSequence();
            XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);
         
            DocumentPaginator paginator = ((IDocumentPaginatorSource)flowDocument).DocumentPaginator;
            paginator.PageSize = new System.Windows.Size(width, height);              
            rsm.SaveAsXaml(paginator);                  
            rsm.Commit();
        }

        return stream;
    }
}

Then I attach it using this code:

Attachment xps = new Attachment(FlowDocumentToXPS(FD, 768, 676), "FileName.xps", "application/vnd.ms-xpsdocument");

where FD is the FlowDocument I want to convert , I'm receiving 0.0KB size XPS file attached and it can't be open with the XPS Viewer , what I'm missing here ?


Solution

  • Solved , this is the final code which worked:

        public static MemoryStream FlowDocumentToXPS(FlowDocument flowDocument, int width, int height)
        {
            MemoryStream stream = new MemoryStream();
            using (Package package = Package.Open(stream, FileMode.Create, FileAccess.ReadWrite))
            {
                using (XpsDocument xpsDoc = new XpsDocument(package, CompressionOption.Maximum))
                {                  
                    XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);
                    DocumentPaginator paginator = ((IDocumentPaginatorSource)flowDocument).DocumentPaginator;
                    paginator.PageSize = new System.Windows.Size(width, height);
                    rsm.SaveAsXaml(paginator);
                    rsm.Commit();                
                }
            }
            stream.Position = 0;
            Console.WriteLine(stream.Length);
            Console.WriteLine(stream.Position);
            return stream;   
        }
    

    Then I attach it using this code:

    Attachment xps = new Attachment(FlowDocumentToXPS(FD, 768, 676), "FileName.xps", "application/vnd.ms-xpsdocument");
    

    where FD is the FlowDocument I want to convert.