為WPF打印對話框和打印預覽對話框

[英]Print dialog and print prewiew dialog for WPF


Is there a print dialog for WPF that is combinated whit a print preview dialog in WPF like Google Chrome or Word does?

WPF是否有一個打印對話框,可以像谷歌或Word那樣在WPF中組合打印預覽對話框?

Like Google chrome does.

At this moment I use a the print preview dialog from Windows forms. I have also try for to use the WPF version of it. But WPF has no PrintPreviewDialog or PrintPrewiewControl. This is my code:

此時,我使用Windows窗體的打印預覽對話框。我也嘗試使用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);
}

I've also searched for a NuGet package but nothing found really good.

我也搜索了一個NuGet包,但沒有發現真正好的。

2 个解决方案

#1


9  

What you want to do, is to create an xpsDocument out from the content you want to print (a flowDocument) and use that XpsDocument to preview the content, for example let say you have the following Xaml, with a flowDocument that you want to print its content :

您要做的是,從您想要打印的內容(一個flowDocument)中創建一個xpsDocument,並使用該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>

the flowDocument Sample is from Wpf tutorials site

flowDocument示例來自Wpf教程站點

the print button Click event handler should looks like this :

打印按鈕單擊事件處理程序應該如下所示:

 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; }

so here you are mainly :

這里主要是

  • Creating an Xps document and storing it in printPreview.xps file,
  • 創建Xps文檔並將其存儲在printPreview中。xps文件,
  • Writing the FlowDocument content into that file,
  • 將FlowDocument內容寫入該文件,
  • passing the XpsDocument to the PrintWindow in which you will handle the preview and the print actions,
  • 將XpsDocument傳遞給PrintWindow,在那里您將處理預覽和打印操作,

here how the PrintWindow looks like :

這里的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>

and the code behind :

以及背后的代碼:

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 
    }
}

the final result looks something like this

最后的結果是這樣的

enter image description here

Ps: to use XpsDocument you should add a reference to System.Windows.Xps.Packaging namespace

要使用XpsDocument,你應該添加一個對System.Windows.Xps的引用。包裝名稱空間

#2


3  

Your requirements can be achieved in a number of ways, for instance, you can use the PrintDialog class. The following MSDN pages contains descriptions as well as some sample code:

您的需求可以通過多種方式實現,例如,您可以使用PrintDialog類。以下MSDN頁面包含描述和一些示例代碼:

Alternatively it can be achieved via C# ,for example, consider the next code:

或者也可以通過c#實現,例如,考慮下面的代碼:

 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
            {
            }
        }
    }
} 

What it does: it actually prints the content of a visual into an XPS document. Then it loads the "printed" XPS document and displays it in a very simple XAML file that is stored as a string, rather than as a separate module, and loaded dynamically at runtime. The resulting Window has the DocumentViewer buttons: print, adjust-to-max-page-width, and so on.

它的作用是:它實際上將視覺內容打印到XPS文檔中。然后,它加載“打印”的XPS文檔,並將其顯示在一個非常簡單的XAML文件中,該文件以字符串形式存儲,而不是作為單獨的模塊,並在運行時動態加載。結果窗口有DocumentViewer按鈕:打印、調整到最大頁面寬度,等等。

I also added some code to hide the Search box. See this answer to WPF: How can I remove the searchbox in a DocumentViewer? for how I did that.

我還添加了一些代碼來隱藏搜索框。請參見WPF的答案:如何在DocumentViewer中刪除searchbox ?我是怎么做到的。

The effect is like this:

效果是這樣的:

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

alt文本http://i48.tinypic.com/2hzkfat.jpg

The XpsDocument can be found in the ReachFramework dll and the XpsDocumentWriter can be found in the System.Printing dll both of which must be added as references to the project

XpsDocument可以在可達框架dll中找到,XpsDocumentWriter可以在系統中找到。打印dll,兩者都必須作為對項目的引用添加


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/04/27/a3090562b6ab3594d235005323cf71da.html



 
  © 2014-2022 ITdaan.com 联系我们: