我如何将下面的代码引用到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, "");
答案 0 :(得分: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);
}
}