2

我将如何将下面的代码引用到 c# 中进行打印。我使用资源字典是因为我不想在打印时显示窗口,而是直接从按钮打印。

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<DockPanel Name="dockpanel" Width="auto"    LastChildFill="True" x:Key="Maindock">
        <Grid DockPanel.Dock="top" Width="340" >
</DockPanel>

这是打印代码:

//System.Printing
//get selected printer capabilities
System.Printing.PrintCapabilities capabilities =                 
                printDlg.PrintQueue.GetPrintCapabilities(printDlg.PrintTicket);

//get the size of the printer page
Size sz = new Size(capabilities.PageImageableArea.ExtentWidth,
                   capabilities.PageImageableArea.ExtentHeight);

// update the layout of the visual to the printer page size.
Print.Measure(sz);
Print.Arrange(new Rect(new Point(capabilities.PageImageableArea.OriginWidth,
              capabilities.PageImageableArea.OriginHeight), sz));

//now print the visual to printer to fit on the one page.
//printDlg.PageRangeSelection(printQty);
//now print the visual to printer to fit on the one page.
String printerName = "Brother DCP-7045N Printer";

System.Printing.PrintQueue queue = new System.Printing.LocalPrintServer()
                                               .GetPrintQueueprinterName);
printDlg.PrintQueue = queue;

printDlg.PrintVisual(Print, "");
4

1 回答 1

1

如果您要打印的资源是您的应用程序资源的一部分,即直接添加到 App.xaml 文件中,如下所示,或者通过合并的字典,那么您应该能够只新建一个可视元素并设置内容. 在这里,我使用 this.FindResource() 来获取要设置为内容的资源实例。

注意:您不必为了打印它而显示新的页面。

应用资源

<Application x:Class="PrintTest.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="MainWindow.xaml">
    <Application.Resources>
        <Grid x:Key="PrintTestResource">
            <TextBlock FontSize="50" HorizontalAlignment="Center" VerticalAlignment="Center">Hello World</TextBlock>
        </Grid>
    </Application.Resources>
</Application>

打印代码

public void Print()
{
    var printDialog = new PrintDialog();
    if (printDialog.ShowDialog().Value)
    {
        var printCapabilities = printDialog.PrintQueue.GetPrintCapabilities(printDialog.PrintTicket);
        var printSize = new Size(printCapabilities.PageImageableArea.ExtentWidth, printCapabilities.PageImageableArea.ExtentHeight);

        var printPage = new Page();
        printPage.Content = this.FindResource("PrintTestResource");
        printPage.Measure(printSize);
        printPage.Arrange(new Rect(new Point(printCapabilities.PageImageableArea.OriginWidth, printCapabilities.PageImageableArea.OriginHeight), printSize));

        printDialog.PrintVisual(printPage, String.Empty);
    }
}
于 2013-07-02T06:45:56.423 回答