C# WPF 打印机
打印机接口 打印文本 打印图片 打印机属性对话框 设置默认打印机 搜索打印机
打印机接口
PrintServer PrintQueue PrintDocument
打印文本
private void PrintText ( string text, int width, int height)
{
PrintDocument pd = new PrintDocument ( ) ;
pd. PrintPage += ( sender, e) =>
{
using ( Bitmap bitmap = new Bitmap ( width, height) )
{
using ( Graphics g = Graphics. FromImage ( bitmap) )
{
g. FillRectangle ( System. Drawing. Brushes. White, 0 , 0 , width, height) ;
StringFormat format = new StringFormat ( ) ;
format. Alignment = StringAlignment. Center;
format. LineAlignment = StringAlignment. Center;
g. DrawString ( text, new Font ( "Arial" , 12 ) , System. Drawing. Brushes. Black, new RectangleF ( 0 , 0 , width, height) , format) ;
e. Graphics. DrawImage ( bitmap, 0 , 0 ) ;
}
}
} ;
try
{
pd. Print ( ) ;
}
catch ( Exception ex)
{
Console. WriteLine ( ex. Message) ;
}
}
打印图片
private void PrintImage ( string imagePath, int width, int height)
{
if ( File. Exists ( imagePath) )
{
PrintDocument pd = new PrintDocument ( ) ;
pd. DefaultPageSettings. Landscape = true ;
Image image = Image. FromFile ( imagePath) ;
pd. PrintPage += ( sender, e) =>
{
using ( Bitmap bitmap = new Bitmap ( width, height) )
{
using ( Graphics g = Graphics. FromImage ( bitmap) )
{
g. FillRectangle ( System. Drawing. Brushes. Black, 0 , 0 , width, height) ;
g. DrawImage ( image, 0 , 0 ) ;
e. Graphics. DrawImage ( bitmap, 0 , 0 ) ;
}
}
#if false
Image i = Image. FromFile ( imagePath) ;
System. Drawing. Rectangle m = e. MarginBounds;
if ( ( double ) i. Width / ( double ) i. Height > ( double ) m. Width / ( double ) m. Height)
{
m. Height = ( int ) ( ( double ) i. Height / ( double ) i. Width * ( double ) m. Width) ;
}
else
{
m. Width = ( int ) ( ( double ) i. Width / ( double ) i. Height * ( double ) m. Height) ;
}
e. Graphics. DrawImage ( i, m) ;
#endif
} ;
try
{
pd. Print ( ) ;
}
catch ( Exception ex)
{
Console. WriteLine ( ex. Message) ;
}
}
}
打印机属性对话框
private void btnPrintSettings_Click ( object sender, RoutedEventArgs e)
{
PrintDialog printDialog = new PrintDialog ( ) ;
if ( printDialog. ShowDialog ( ) == true )
{
Console. WriteLine ( "打印" ) ;
}
}
设置默认打印机
public static void SetDefaultPrinter ( string printerName)
{
PrintServer printServer = new PrintServer ( ) ;
PrintQueue printQueue = new PrintQueue ( printServer, printerName) ;
printQueue. Commit ( ) ;
}
搜索打印机
private void btnPrintSearch_Click ( object sender, RoutedEventArgs e)
{
PrintServer printServer = new PrintServer ( ) ;
PrintQueueCollection printQueues = printServer. GetPrintQueues ( ) ;
cmboxPrintList. Items. Clear ( ) ;
foreach ( PrintQueue p in printQueues)
{
cmboxPrintList. Items. Add ( p. Name) ;
}
}
private void cmboxPrintList_SelectionChanged ( object sender, SelectionChangedEventArgs e)
{
string pName = cmboxPrintList. SelectedItem as string ;
Console. WriteLine ( "选择打印机" ) ;
if ( pName != null )
{
Console. WriteLine ( "默认打印机:" + pName) ;
SetDefaultPrinter ( pName) ;
}
}