从FlowDocument创建一个XPS文档,并动态地附加它

本文关键字:动态 文档 XPS 创建 FlowDocument 一个 | 更新日期: 2023-09-27 18:03:20

我有一个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查看器打开,我在这里缺少什么?

编辑:最后的代码工作,见注释

Thanks in advance

从FlowDocument创建一个XPS文档,并动态地附加它

解决了,查看问题帖子下的评论和帖子本身已经完成的编辑