Диалоговое окно "печать" и диалоговое окно "печать" prewiew для WPF
есть ли диалог печати для WPF, который объединен с диалогом предварительного просмотра печати в WPF, как Google Chrome или Word?
в данный момент я использую диалоговое окно предварительного просмотра печати из Windows forms. Я также пытаюсь использовать его версию WPF. Но WPF не имеет PrintPreviewDialog или PrintPrewiewControl. Вот мой код:
//To the top of my class file:
using Forms = System.Windows.Forms;
//in a methode on the same class:
PageSettings setting = new PageSettings();
setting.Landscape = true;
_document = new PrintDocument();
_document.PrintPage += _document_PrintPage;
_document.DefaultPageSettings = setting ;
Forms.PrintPreviewDialog printDlg = new Forms.PrintPreviewDialog();
printDlg.Document = _document;
printDlg.Height = 500;
printDlg.Width = 200;
try
{
    if (printDlg.ShowDialog() == Forms.DialogResult.OK)
    {
        _document.Print();
    }
}
catch (InvalidPrinterException)
{
    MessageBox.Show("No printers found.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
Я также искал пакет NuGet, но ничего не нашел действительно хорошего.
2 ответов
что вы хотите сделать, это создать xpsDocument из содержимого, которое вы хотите распечатать (a 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
обработчик событий щелчка кнопки печати должен выглядеть следующим образом:
 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 вы должны добавить ссылку на
ваши требования можно достигнуть в нескольких путей, например, вы можете
используйте PrintDialog класса. Следующие страницы MSDN содержат описания, а также некоторые примеры кода:
- WinForms:
 
            