以从注释提示加入到我的问题,我这样做:
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按钮:打印,调整到最大页面宽度等。
我还添加了一些代码来隐藏搜索框。请参阅this answer to WPF: How can I remove the searchbox in a DocumentViewer?我是如何做到这一点的。
的效果是这样的:
alt text http://i48.tinypic.com/2hzkfat.jpg
的XpsDocument可以在ReachFramework DLL被发现和XpsDocumentWriter可以在系统中找到。打印dll必须添加为项目的参考
嗨切西,这个答案http://stackoverflow.com/questions/584551/how-do-i-do-print-preview-when-using-a -documentpaginator-to-print/587962#587962建议使用XpsDocument与标准窗口结合使用...不想将它写为答案,因为我担心您已经看到该链接。以防万一。干杯:) – Anvaka 2010-02-23 22:11:14