当前位置: 代码迷 >> 综合 >> 打印系统开发(26)——WinForm开发(46)——使用PrintDocument进行打印
  详细解决方案

打印系统开发(26)——WinForm开发(46)——使用PrintDocument进行打印

热度:86   发布时间:2023-10-01 15:41:43.0

背景:

  1.在winform中,需要直接调用打印机,进行打印处理

      2.找了很多实现方法是web的处理,然后查了下度娘,发现可以使用自带类PrintDocument进行处理,所以就有了这篇文章

说明:

  使用PrintDocument需要有几个步骤,如下:

  1. 需要定义全局变量PrintDocument

  2. 需要定义一个文本控件做处理

  3. 在程序初始化的时候,需要将设置画布的方法,加入到PrintDocument对象的PrintPage方法中

  4. 将打印机名赋值给PrintDocument对象的PrinterSettings对象的PrinterName

  5. 在自定义的文本控件中加入需要打印的内容

  6. 调用PrintDocument的Print方法进行打印输出

代码实现:

        private PrintDocument pd = new PrintDocument();/// <summary>/// 打印内容使用TextBox控件printTextBox/// </summary>private TextBox printTextBox = new TextBox();public Form1(){InitializeComponent();// 加入打印页面的设置处理pd.PrintPage += printdocument_PrintPage;// 关联打印机  赋值打印机的名字pd.PrinterSettings.PrinterName = "Microsoft Print to PDF";}/// <summary>/// 将打印内容 画在打印文档对象中/// </summary>private void printdocument_PrintPage(object sender, PrintPageEventArgs e){try{Font fnt = printTextBox.Font;Graphics g = e.Graphics;long rowheight = printTextBox.Font.Height;  //行距for (int i = 0; i < printTextBox.Lines.Length; i++){g.DrawString(printTextBox.Lines[i], fnt, bsh, 3, 10 + rowheight);rowheight += printTextBox.Font.Height;}g.Dispose();}catch (Exception){throw new Exception("打印失败!消息类型:2");}}private void Form1_Load(object sender, EventArgs e){/** 填写内容*/printTextBox.AppendText("测试处理");// 执行打印pd.Print();}

 

  相关解决方案