如何在WPF应用程序中生成FlowDocument的“打印预览”?

时间:2010-02-23 21:57:39

标签: .net wpf printing flowdocument flowdocumentscrollviewer

我的各种WPF应用程序显示FlowDocument的。我可以使用the answer to Printing a WPF FlowDocument中描述的方法打印它们。

现在我想添加一个“打印预览”功能。在正常情况下,我正在打印窗口中显示的FlowDocument,因此我不需要打印预览。但在某些情况下,要打印的FlowDocument是在内存中即时构建的。在这些情况下,我想在打印前显示它。

现在,我当然可以弹出一个新窗口并显示FlowDocument,但

  1. 我希望预览真的感觉就像它是打印操作的一部分,而不仅仅是应用程序中的另一个窗口。

  2. 我不想在FlowDocumentScrollViewer中使用普通的FlowDocument。它不是“任何大小”,而是需要约束纸张的大小,特定的HxW比率和分页。

  3. 连连呢?

    • 我应该只使用标准窗口,在这种情况下,如何确保FlowDocument处于适当的比例?

    • 是否有更“集成”的方式在Windows的PrintDialog UI范围内进行预览?

    由于

2 个答案:

答案 0 :(得分:22)

从我的问题中添加了评论的提示,我做到了这一点:

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("'", "&apos;"));

            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按钮:print,adjust-to-max-page-width等。

我还添加了一些代码来隐藏搜索框。请参阅this answer to WPF: How can I remove the searchbox in a DocumentViewer?了解我是如何做到的。

效果是这样的:

alt text http://i48.tinypic.com/2hzkfat.jpg

可以在ReachFramework dll中找到XpsDocument,并且可以在System.Printing dll中找到XpsDocumentWriter,这两者都必须作为对项目的引用添加

答案 1 :(得分:2)

“FlowDocumentPageViewer”控件是我们其中一个项目中使用的“预览”控件的基础。这是“DocumentPreviewer”控件的XAML(长度道歉 - XAML不简洁):

<Control
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    xmlns:l="clr-namespace:Tyler.ComPort.UI"
    mc:Ignorable="d"
    x:Class="Tyler.ComPort.UI.DocumentPreviewer"
    x:Name="UserControl"
    Background="Gray"
    d:DesignWidth="640" d:DesignHeight="480">
    <Control.Resources>
        <ObjectDataProvider x:Key="ViewStyles" MethodName="GetValues" ObjectType="{x:Type sys:Enum}" >
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="l:ViewType" />
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
        <l:EnumMatchVisibilityConverter x:Key="EnumVisibilityConverter" />
    </Control.Resources>
    <Control.Template>
        <ControlTemplate>
            <ControlTemplate.Triggers>
                <Trigger Property="l:DocumentPreviewer.ViewType">
                    <Trigger.Value>
                        <l:ViewType>Actual</l:ViewType>
                    </Trigger.Value>
                    <Trigger.Setters>
                        <Setter TargetName="ScrollViewer" Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto" />
                        <Setter TargetName="ScrollViewer" Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto" />
                        <Setter TargetName="Viewbox" Property="Viewbox.Stretch" Value="None" />
                    </Trigger.Setters>
                </Trigger>
                <Trigger Property="l:DocumentPreviewer.ViewType">
                    <Trigger.Value>
                        <l:ViewType>Fit</l:ViewType>
                    </Trigger.Value>
                    <Trigger.Setters>
                        <Setter TargetName="ScrollViewer" Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" />
                        <Setter TargetName="ScrollViewer" Property="ScrollViewer.VerticalScrollBarVisibility" Value="Disabled" />
                        <Setter TargetName="Viewbox" Property="Viewbox.Stretch" Value="Uniform" />
                    </Trigger.Setters>
                </Trigger>
                <Trigger Property="l:DocumentPreviewer.ViewType">
                    <Trigger.Value>
                        <l:ViewType>Wide</l:ViewType>
                    </Trigger.Value>
                    <Trigger.Setters>
                        <Setter TargetName="ScrollViewer" Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" />
                        <Setter TargetName="ScrollViewer" Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto" />
                        <Setter TargetName="Viewbox" Property="Viewbox.Stretch" Value="UniformToFill" />
                    </Trigger.Setters>
                </Trigger>
            </ControlTemplate.Triggers>
            <DockPanel>
                <ToolBar DockPanel.Dock="Top">
                    <Button Command="{x:Static ApplicationCommands.Print}" CommandTarget="{Binding ElementName=PageViewer}" Content="Print..." />
                    <Separator />
                    <Button Command="{x:Static NavigationCommands.PreviousPage}" CommandTarget="{Binding ElementName=PageViewer}" Content="&lt; Previous" />
                    <Button Command="{x:Static NavigationCommands.NextPage}" CommandTarget="{Binding ElementName=PageViewer}" Content="Next &gt;" />
                    <Separator />
                    <l:ToolBarButtonGroup
                        ItemsSource="{Binding Source={StaticResource ViewStyles}}"
                        SelectedItem="{Binding ViewType, ElementName=UserControl}"
                        IsSynchronizedWithCurrentItem="True"
                        >
                        <l:ToolBarButtonGroup.ItemTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Horizontal" ToolTip="{Binding}" SnapsToDevicePixels="True">
                                    <Image Source="../Images/actual.png" Visibility="{Binding Converter={StaticResource EnumVisibilityConverter}, ConverterParameter=Actual}" />
                                    <Image Source="../Images/fit.png" Visibility="{Binding Converter={StaticResource EnumVisibilityConverter}, ConverterParameter=Fit}" />
                                    <Image Source="../Images/wide.png" Visibility="{Binding Converter={StaticResource EnumVisibilityConverter}, ConverterParameter=Wide}" />
                                </StackPanel>
                            </DataTemplate>
                        </l:ToolBarButtonGroup.ItemTemplate>
                    </l:ToolBarButtonGroup>
                </ToolBar>
                <ScrollViewer x:Name="ScrollViewer" HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Disabled">
                    <Border
                            BorderBrush="Black"
                            BorderThickness="1"
                            HorizontalAlignment="Center"
                            VerticalAlignment="Top"
                            Background="White"
                            Margin="10">
                        <Viewbox x:Name="Viewbox" Stretch="Uniform">
                            <FlowDocumentPageViewer
                                x:Name="PageViewer"
                                Document="{Binding Document, ElementName=UserControl}"
                                Zoom="100"
                                MinZoom="20"
                                MaxZoom="200">
                                <FlowDocumentPageViewer.Template>
                                    <ControlTemplate TargetType="{x:Type FlowDocumentPageViewer}">
                                        <AdornerDecorator>
                                            <DocumentPageView FlowDocumentPageViewer.IsMasterPage="True" />
                                        </AdornerDecorator>
                                    </ControlTemplate>
                                </FlowDocumentPageViewer.Template>
                            </FlowDocumentPageViewer>
                        </Viewbox>
                    </Border>
                </ScrollViewer>
            </DockPanel>
        </ControlTemplate>
    </Control.Template>
</Control>

你可能会把这样一个控件放在你(和你的应用程序)当然,但我们的应用程序与典型的Office应用程序有类似的行为,你可以直接打印或预览(显示上面的界面)和从那里打印。