WPFアプリケーションでの印刷 part2

前回の続きです。
とりあえず前回のサンプルを参考に、自分でも書いてみました。
(以下のコードを実行するにはReachFrameworkを参照設定に追加する必要があります)

PrintWindow.xaml


<Window x:Class="WPF2.PrintWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="PrintWindow" Height="300" Width="300">
<Grid>
<DocumentViewer Name="documentViewer1" />
</Grid>
</Window>


PrintWindow.xaml.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.IO;
using System.Windows.Xps.Packaging;

namespace WPF2
{
///


/// PrintWindow.xaml の相互作用ロジック
///

public partial class PrintWindow : Window
{
public PrintWindow()
{
InitializeComponent();

Print();
}

private void Print()
{
//印刷対象コンテンツを作成する******
FlowDocumentPageViewer viewer = new FlowDocumentPageViewer();
FlowDocument flowDocument = new FlowDocument();
flowDocument.ColumnWidth = 600;//600というのは適当
viewer.Document = flowDocument;

Paragraph paragraph = new Paragraph(new Run("Hello!"));
flowDocument.Blocks.Add(paragraph);


//XpsDocumentに変換する******
DocumentPaginator paginator = viewer.Document.DocumentPaginator;

using (System.IO.Packaging.Package container = System.IO.Packaging.Package.Open("test" + ".xps", FileMode.Create))
{
using (XpsDocument xpsDoc = new XpsDocument(container, System.IO.Packaging.CompressionOption.Maximum))
{
System.Windows.Xps.Serialization.XpsSerializationManager xpsSM = new System.Windows.Xps.Serialization.XpsSerializationManager(new System.Windows.Xps.Serialization.XpsPackagingPolicy(xpsDoc), false);
xpsSM.SaveAsXaml(paginator);
}
}

XpsDocument xpsDoc2 = new XpsDocument("test.xps", System.IO.FileAccess.Read);
//Window上に貼り付けてあるDocumentViewerに表示。画面上で印刷操作も可能
this.documentViewer1.Document = xpsDoc2.GetFixedDocumentSequence();
xpsDoc2.Close();
}
}
}


実行結果はこんな感じ

ここまで表示できれば、DocumentViewerコントロールの印刷ボタンから、印刷できるはずです。

途中に出てくる「Paragraph paragraph = new Paragraph(new Run("Hello!"));」が印刷したいコンテンツにあたります。ここで、フローコンテンツとして扱えるTableなどを動的に作成してflowDocument.Blocksに追加した後、XpsDocumentに変換すればいいわけです