方式一:
public bool Print(string pathStr)
{
try
{
if (File.Exists(pathStr) == false)
return false; var pr = new Process
{
StartInfo =
{
FileName = pathStr,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
Verb = "Print"//printo、edit、open
//printto 调用默认打印机打印
//open 打开图片
}
};
pr.Start();
return true;
}
catch (Exception)
{
return false;
}
}
//等价于==》 private void PrintImage(string filePath)
{
  Process process = new Process();

   process.StartInfo.FileName ="filePath";

   string[] items=process.StartInfo.Verbs;
   process.StartInfo.Verb = "printto";
   process.StartInfo.CreateNoWindow = true;
   process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
   process.Start();

}
private void SaveWindowToImage(Window window, string fileName)
{
FrameworkElement element = window.Content as FrameworkElement;
RenderTargetBitmap bmp = new RenderTargetBitmap((int)element.ActualWidth,
(int)element.ActualHeight, 96d, 96d, PixelFormats.Default);
bmp.Render(window); BmpBitmapEncoder encoder = new BmpBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmp)); using(FileStream stream=File.Open(fileName,FileMode.OpenOrCreate))
{
encoder.Save(stream);
}
}

调用方式如下:

SaveWindowToImage(this,"c:\\test.bmp");
Print("c:\\test.bmp");

实现思路:用户界面转换为图片,打印图片文件。

方式二:

第一步,将WPF用户界面转换为图片

private string SaveWindowToImage(Window window, string fileName)
{
FrameworkElement element = window.Content as FrameworkElement;
RenderTargetBitmap bmp = new RenderTargetBitmap((int)element.ActualWidth,
(int)element.ActualHeight, 96d, 96d, PixelFormats.Default);
bmp.Render(window); BmpBitmapEncoder encoder = new BmpBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmp)); using (FileStream stream = File.Open(fileName, FileMode.OpenOrCreate))
{
encoder.Save(stream);
}
return fileName;
}

第二步,打印图片

SolidBrush brush = new SolidBrush(System.Drawing.Color.Black);
Font DrawFont = new Font("Arial", 22);
private PrintDocument pd = new PrintDocument();
private void button3_Click(object sender, RoutedEventArgs e)
{
pd.PrintPage += PicturePrintDocument_PrintPage; //注册打印事件
//pd.PrinterSettings.PrinterName = "HP LaserJet Professional M1213nf MFP"; //打印机选择
pd.Print(); // =>就似这么简单
} /// <summary>
/// 打印事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PicturePrintDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
   System.Drawing.Image img = new Bitmap(filePath);
e.Graphics.DrawImage(img, 50, 50);
//e.Graphics.DrawString("aaa", DrawFont, brush, 600, 600); //绘制字符串
e.HasMorePages = false;
}
//filePath=SaveWindowToImage(this,"c:\\test.bmp");

  

 

05-11 16:59