2013-07-11 49 views
2

我发现打印代码。但我想在没有对话框的情况下自动发送到打印机。我知道printername。我从SQL表中获取打印机名称。我该怎么做 ?不带对话框自动打印

// select printer and get printer settings 
     PrintDialog pd = new PrintDialog(); 
     if (pd.ShowDialog() != true) return; 


     // create a document 
     FixedDocument document = new FixedDocument(); 
     document.DocumentPaginator.PageSize = new Size(pd.PrintableAreaWidth, pd.PrintableAreaHeight); 

     // create a page 
     FixedPage page1 = new FixedPage(); 
     page1.Width = document.DocumentPaginator.PageSize.Width; 
     page1.Height = document.DocumentPaginator.PageSize.Height; 

     // add some text to the page 
     TextBlock page1Text = new TextBlock(); 
     page1Text.Text = "This is a text" 
     page1Text.FontSize = 12; // 30pt text 
     page1Text.Margin = new Thickness(50); // 1 inch margin 
     page1.Children.Add(page1Text); 

     // add the page to the document 
     PageContent page1Content = new PageContent(); 
     ((IAddChild)page1Content).AddChild(page1); 
     document.Pages.Add(page1Content); 

     // and print 
     pd.PrintDocument(document.DocumentPaginator, "Print"); 
+1

如果删除if(pd.ShowDialog()!= true),会发生什么情况; '线? –

+0

查看'PrintDocument'类:http://msdn.microsoft.com/en-us/library/system.drawing.printing.printdocument(v=vs.110).aspx – Treb

+0

谢谢默认语言环境。但是希望在Windows上使用不默认的打印机。我想使用我知道打印机名称的打印机。 – user2550719

回答

1

相反PrintDialog类类的,尽量直接使用PrintDocument类,在这里您可以通过名称设置打印机:

using System.Drawing.Printing; 

PrintDocument pd = new PrintDocument(); 
pd.PrinterSettings.PrinterName = "my printer"; 

要遍历可用的打印机名称:

foreach (string s in PrinterSettings.InstalledPrinters) { 
    // 
} 
1

我删除了if (pd.ShowDialog() != true) return;并添加此代码pd.PrintQueue = new PrintQueue(new PrintServer(), "printer name");来打印我选择的打印机。

+0

我喜欢这个答案,因为我需要PrintVisual,只有在PrintDialog – Yoni