How to convert FlowDocument to FixedDocument using

2020-02-26 12:30发布

问题:

I have:

DocumentPaginator dp = ((IDocumentPaginatorSource)document).DocumentPaginator;

and:

FlowDocument document = new FlowDocument();
// create a flow document...

How do a convert the FlowDocument to a FixedDocument using the DocumentPaginator? I can't seem to find out how to do this. All sites I looked at use XpsWriter as in:

XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDoc); 
DocumentPaginator dp = ((IDocumentPaginatorSource)document).DocumentPaginator;
writer.Write(dp);

I could write the XPS and then get back the FixedDocument but there must be a better way?

回答1:

No, there doesn't seem to be a better way. But you don't need to save it to disk:

var paginator = ((IDocumentPaginatorSource)flowDocument).DocumentPaginator;
var package = Package.Open(new MemoryStream(), FileMode.Create, FileAccess.ReadWrite);
var packUri = new Uri("pack://temp.xps");
PackageStore.RemovePackage(packUri);
PackageStore.AddPackage(packUri, package);
var xps = new XpsDocument(package, CompressionOption.NotCompressed, packUri.ToString());
XpsDocument.CreateXpsDocumentWriter(xps).Write(paginator);
FixedDocument doc = xps.GetFixedDocumentSequence().References[0].GetDocument(true);