从FlowDocument创建XPS文档并动态附加它

时间:2011-07-23 08:54:15

标签: c# .net wpf flowdocument xpsdocument

我有一个FlowDocument,我想将其转换为XPS文档并将其附加到电子邮件中并将它们一起发送。我正在使用此代码

 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;   
    }

然后我使用以下代码附加它:

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

其中FD是我要转换的FlowDocument,我接收到附加的0.0KB大小的XPS文件并且无法使用XPS Viewer打开,我在这里缺少什么?

编辑:有效的最终代码,请参阅评论

提前致谢

1 个答案:

答案 0 :(得分:3)

解决,请参阅问题帖子下的评论和已在帖子上完成的编辑