您要做的是从您要打印的内容中创建一个xpsDocument(flowDocument)并使用该XpsDocument 预览内容,例如假设您有以下内容Xaml,带有您要打印其内容的flowDocument:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<FlowDocumentScrollViewer>
<FlowDocument x:Name="FD">
<Paragraph>
<Image Source="http://www.wpf-tutorial.com/images/logo.png" Width="90" Height="90" Margin="0,0,30,0" />
<Run FontSize="120">WPF</Run>
</Paragraph>
<Paragraph>
WPF, which stands for
<Bold>Windows Presentation Foundation</Bold> ,
is Microsoft's latest approach to a GUI framework, used with the .NET framework.
Some advantages include:
</Paragraph>
<List>
<ListItem>
<Paragraph>
It's newer and thereby more in tune with current standards
</Paragraph>
</ListItem>
<ListItem>
<Paragraph>
Microsoft is using it for a lot of new applications, e.g. Visual Studio
</Paragraph>
</ListItem>
<ListItem>
<Paragraph>
It's more flexible, so you can do more things without having to write or buy new controls
</Paragraph>
</ListItem>
</List>
</FlowDocument>
</FlowDocumentScrollViewer>
<Button Content="Print" Grid.Row="1" Click="Button_Click"></Button>
</Grid>
flowDocument 样本来自Wpf tutorials site
打印按钮 Click 事件处理程序应如下所示:
private void Button_Click(object sender, RoutedEventArgs e)
{
if (File.Exists("printPreview.xps"))
{
File.Delete("printPreview.xps");
}
var xpsDocument = new XpsDocument("printPreview.xps", FileAccess.ReadWrite);
XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
writer.Write(((IDocumentPaginatorSource)FD).DocumentPaginator);
Document = xpsDocument.GetFixedDocumentSequence();
xpsDocument.Close();
var windows = new PrintWindow(Document);
windows.ShowDialog();
}
public FixedDocumentSequence Document { get; set; }
所以你主要在这里:
- 创建 Xps 文档并将其存储在 printPreview.xps 文件中,
- 将
FlowDocument 内容写入该文件,
- 将
XpsDocument 传递给PrintWindow,您将在其中
处理预览和打印操作,
PrintWindow 的外观如下:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="1.5*"/>
</Grid.ColumnDefinitions>
<StackPanel>
<Button Content="Print" Click="Button_Click"></Button>
<!--Other print operations-->
</StackPanel>
<DocumentViewer Grid.Column="1" x:Name="PreviewD">
</DocumentViewer>
</Grid>
以及背后的代码:
public partial class PrintWindow : Window
{
private FixedDocumentSequence _document;
public PrintWindow(FixedDocumentSequence document)
{
_document = document;
InitializeComponent();
PreviewD.Document =document;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
//print directly from the Xps file
}
}
最终的结果是这样的
Ps:要使用 XpsDocument,您应该添加对 System.Windows.Xps.Packaging namespace 的引用