从添加到我的问题的评论中得到提示,我这样做了:
private string _previewWindowXaml =
@"<Window
xmlns ='http://schemas.microsoft.com/netfx/2007/xaml/presentation'
xmlns:x ='http://schemas.microsoft.com/winfx/2006/xaml'
Title ='Print Preview - @@TITLE'
Height ='200'
Width ='300'
WindowStartupLocation ='CenterOwner'>
<DocumentViewer Name='dv1'/>
</Window>";
internal void DoPreview(string title)
{
string fileName = System.IO.Path.GetRandomFileName();
FlowDocumentScrollViewer visual = (FlowDocumentScrollViewer)(_parent.FindName("fdsv1"));
try
{
// write the XPS document
using (XpsDocument doc = new XpsDocument(fileName, FileAccess.ReadWrite))
{
XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc);
writer.Write(visual);
}
// Read the XPS document into a dynamically generated
// preview Window
using (XpsDocument doc = new XpsDocument(fileName, FileAccess.Read))
{
FixedDocumentSequence fds = doc.GetFixedDocumentSequence();
string s = _previewWindowXaml;
s = s.Replace("@@TITLE", title.Replace("'", "'"));
using (var reader = new System.Xml.XmlTextReader(new StringReader(s)))
{
Window preview = System.Windows.Markup.XamlReader.Load(reader) as Window;
DocumentViewer dv1 = LogicalTreeHelper.FindLogicalNode(preview, "dv1") as DocumentViewer;
dv1.Document = fds as IDocumentPaginatorSource;
preview.ShowDialog();
}
}
}
finally
{
if (File.Exists(fileName))
{
try
{
File.Delete(fileName);
}
catch
{
}
}
}
}
它的作用:它实际上将视觉对象的内容打印到 XPS 文档中。然后它加载“打印的”XPS 文档并将其显示在一个非常简单的 XAML 文件中,该文件存储为字符串,而不是单独的模块,并在运行时动态加载。生成的窗口具有 DocumentViewer 按钮:打印、调整到最大页面宽度等。
我还添加了一些代码来隐藏搜索框。请参阅WPF 的此答案:如何删除 DocumentViewer 中的搜索框?我是怎么做到的。
效果是这样的:
XpsDocument 可以在 ReachFramework dll 中找到,XpsDocumentWriter 可以在 System.Printing dll 中找到,两者都必须作为对项目的引用添加