私の質問に追加されたコメントからヒントを得て、私はこれを行いました:
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 ファイルに表示します。結果の Window には、DocumentViewer ボタン (印刷、最大ページ幅に調整など) があります。
検索ボックスを非表示にするコードも追加しました。WPFに対するこの回答を参照してください: DocumentViewer で検索ボックスを削除するにはどうすればよいですか? 私がそれをどのように行ったかについて。
効果はこんな感じです。
XpsDocument は ReachFramework dll にあり、XpsDocumentWriter は System.Printing dll にあります。どちらもプロジェクトへの参照として追加する必要があります。