I am trying to convert a FlowDocument
to XPS. Here is how the FlowDocument
is defined:
<FlowDocument PageHeight="29.7cm" PageWidth="21cm" PagePadding="2cm,2cm,2cm,2cm">
</FlowDocument>
It is inside a RichTextBox
and is populated by a user. It is saved as a .rtf
file (.xaml
gave me the same results).
Here is the method I am using to save the doc:
public void UploadTemplate(TextRange content, string filename)
{
string destPath = Path.Combine(default_template_path, filename ".rtf");
if (content.CanSave(DataFormats.Rtf))
{
using (var stream = new FileStream(destPath, FileMode.Create))
{
content.Save(stream, DataFormats.Rtf);
stream.Close();
}
}
}
And here is how I load the doc:
public void LoadTemplate(string template_path, TextRange content)
{
if (content.CanLoad(DataFormats.Rtf))
{
using (var stream = new FileStream(template_path, FileMode.Open))
{
content.Load(stream, DataFormats.Rtf);
stream.Close();
}
}
}
Finally this is the code I use for converting the FlowDocument
to XPS
:
public static MemoryStream FlowDocumentToXPS(FlowDocument flowDocument)
{
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 Size(flowDocument.PageWidth, flowDocument.PageHeight);
rsm.SaveAsXaml(paginator);
rsm.Commit();
}
}
stream.Position = 0;
Console.WriteLine(stream.Length);
Console.WriteLine(stream.Position);
return stream;
}
After saving this stream to a .xps
file the document pages seem like they are divided in 2 columns. This is what I get from that export. Can someone help me figure this out ?
CodePudding user response:
For anyone that might stumble upon this. You must set the FlowDocument.ColumnWidth
property when converting to XPS
. In this case it would need to be something like this:
public static MemoryStream FlowDocumentToXPS(FlowDocument flowDocument)
{
flowDocument.ColumnWidth = (int)YourColumnWidth; // THIS IS THE KEY LINE
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 Size(flowDocument.PageWidth, flowDocument.PageHeight);
rsm.SaveAsXaml(paginator);
rsm.Commit();
}
}
stream.Position = 0;
Console.WriteLine(stream.Length);
Console.WriteLine(stream.Position);
return stream;
}