封装一个打印的公共类,跟童鞋们分享一下

ImagePrinter 类是封装好的打印类,打印前需要调用 public bool PrinterReady(Bitmap printContent) 方法传入一个图片文件,

之后就可以调用 PrintView() 进行打印浏览,调用 PrintOut()  就可以打印了。

ExpressPrinter 类是调用 ImagePrinter 打印封装类的一个实例,旨在与看看怎么使用GDI+绘制需要打印的内容和字体。

================================================

using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Printing;
using Lib.Biz.ClientService;
using Lib.Utility.Extension;
using PrintOrder.Utility;


namespace PrintOrder.ExpressPrinter.PrintDoc
{
  /// <summary>
  /// 打印图片内容
  /// </summary>
  public class ExpressPrinter
  {
    /// <summary>
    /// 创建快递单打印对象实例
    /// </summary>
    /// <param name="printerName">打印机名称,如果为空将使用默认打印机</param>
    /// <param name="template">打印模板</param>
    /// <param name="items">打印项</param>
    /// <param name="isCoordinateRule">是否打印定位标尺</param>
    public ExpressPrinter(string printerName, Print_Template template, List<Print_Item> items, bool isCoordinateRule)
    {
      m_template = template;
      m_items = items;
      m_print = new ImagePrinter(printerName);
      m_isCoordinateRule = isCoordinateRule;
      InitPrinter();
    }
    #region 变量


    private Print_Template m_template;
    private List<Print_Item> m_items;
    private Bitmap m_bitmap = new Bitmap(10, 10);
    private Brush m_brush = new SolidBrush(Color.Black);
    private ImagePrinter m_print = null;
    private bool m_isCoordinateRule = false;
    #endregion
    /// <summary>
    /// 设置纸张大小
    /// </summary>
    private void SetPrintPageSize()
    {
      //使用百分之一英寸为单位重新创建绘图图面
      using (Graphics g = Graphics.FromImage(m_bitmap))
      {
        //注:使用百分之一为单位
        SizeF sizeF = new SizeF(
         CommonMethod.PixelsToInches(m_template.Width,g.DpiX)*100,
         CommonMethod.PixelsToInches(m_template.Height,g.DpiY)*100);
        Size size = Size.Ceiling(sizeF);
        m_print.DefaultPaperSize = new PaperSize("NewPage", size.Width,size.Height);
      }
      m_print.DefaultMargins = new Margins(0, 0, 0, 0);
      m_print.PrintDocName = string.Format("{0}({1})",m_template.TemplateName,m_template.Modifier);
    }
    /// <summary>
    /// 打印前初始化
    /// </summary>
    private void InitPrinter()
    {
      SetPrintPageSize(); //设置纸张大小
      m_bitmap = new Bitmap(m_template.Width, m_template.Height);
      Func<Print_Item, Font> getFont = (o =>
      {
        FontStyle fontStyle = FontStyle.Regular;
        if (o.FontBold == 1)
          fontStyle = fontStyle | FontStyle.Bold;
        if (o.FontItalic == 1)
          fontStyle = fontStyle | FontStyle.Italic;
        if (o.FontStrikeout == 1)
          fontStyle = fontStyle | FontStyle.Strikeout;
        if (o.FontUnderline == 1)
          fontStyle = fontStyle | FontStyle.Underline;
        Font font = new Font(o.FontName, o.FontSize, fontStyle);
        return font;
      });
      using (Graphics g = Graphics.FromImage(m_bitmap))
      {
        g.PageUnit = GraphicsUnit.Pixel;
        //填充数据到图片模板(位置要在制作图片模板的时候度量好)
        g.FillRectangle(Brushes.White, 0f, 0f
          ,m_template.Width
          ,m_template.Height);
        //测试纸张大小
        //this.DrawTestRectangle(g);
        if (m_isCoordinateRule)
        {
          TestPageSize(g);
        }
        foreach (Print_Item item in m_items)
        {
          g.DrawString(
            item.Text
            , getFont(item)
            , Brushes.Black
            , new RectangleF(
               item.Offset_X + m_template.Offset_X   //设置全局打印偏移 X 坐标
              ,item.Offset_Y + m_template.Offset_Y //设置全局打印偏移 Y 坐标
              ,item.Width
              ,item.Height));
        }
        g.Dispose();
      }
      //m_bitmap.Save(@"D:\WorkTest\temp\express.jpg");
      m_print.PrinterReady(m_bitmap);
    }


    private void DrawTestRectangle(Graphics g)
    {
      g.PageUnit = GraphicsUnit.Pixel;
      SizeF size = new SizeF(
        Utility.CommonMethod.MillimetersToPixel(30, g.DpiX)
        , Utility.CommonMethod.MillimetersToPixel(30, g.DpiY));
      g.DrawRectangle(new Pen(Color.Black, 1), 50, 50, size.Width, size.Height);
    }
    /// <summary>
    /// 打印标尺
    /// </summary>
    private void TestPageSize(Graphics g)
    {
      g.PageUnit = GraphicsUnit.Pixel;
      //八个定位方格
      Size size = new Size(20,20);
      Point ltop = new Point(0,0);
      Point rtop = new Point(m_template.Width - size.Width, 0);
      Point ldwn = new Point(0,m_template.Height - size.Height);
      Point rdwn = new Point(m_template.Width - size.Width, m_template.Height - size.Height);
      Point tmdio = new Point(m_template.Width/2-size.Width/2,0);
      Point dmdio = new Point(m_template.Width / 2 - size.Width/ 2, m_template.Height - size.Height);
      Point lmdio = new Point(0, m_template.Height / 2 - size.Height / 2);
      Point rmdio = new Point(m_template.Width - size.Width, m_template.Height / 2 - size.Height / 2);
      //Point mdio = new Point(m_template.Width / 2 - size.Width / 2, m_template.Height / 2 - size.Height / 2);
      //左下和右上的限度矩形
      Size tRec = new Size(m_template.Width/4,10);
      Size lRec = new Size(10, m_template.Height / 4);
      Point ldRec = new Point(0, lmdio.Y + size.Height + lRec.Height);//左下
      Point rtRec = new Point(tmdio.X + size.Width + tRec.Width, 0);//右上
      //十字中心
      Size tdCrossSize = new Size(10,50);
      Size lrCrossSize = new Size(50,10);
      Point tdCrossPnt = new Point(m_template.Width / 2 - tdCrossSize.Width / 2, m_template.Height / 2 - tdCrossSize.Height/2);
      Point lrCrossPnt = new Point(m_template.Width / 2 - lrCrossSize.Width / 2, m_template.Height / 2 - lrCrossSize.Height / 2);
      
      g.FillRectangle(m_brush, new Rectangle(ltop, size));
      g.FillRectangle(m_brush, new Rectangle(rtop, size));
      g.FillRectangle(m_brush, new Rectangle(ldwn, size));
      g.FillRectangle(m_brush, new Rectangle(rdwn, size));
      g.FillRectangle(m_brush, new Rectangle(tmdio, size));
      g.FillRectangle(m_brush, new Rectangle(dmdio, size));
      g.FillRectangle(m_brush, new Rectangle(lmdio, size));
      g.FillRectangle(m_brush, new Rectangle(rmdio, size));
      
      g.FillRectangle(m_brush, new Rectangle(rtRec, tRec));
      g.FillRectangle(m_brush, new Rectangle(ldRec, lRec));


      g.FillRectangle(m_brush, new Rectangle(tdCrossPnt, tdCrossSize));
      g.FillRectangle(m_brush, new Rectangle(lrCrossPnt, lrCrossSize));


      string defaultSize = string.Format("纸张:{0}X{1}(px),{2}X{3}(mm)"
        , CommonMethod.InchesToPixels(m_print.DefaultPaperSize.Width / 100f,g.DpiX)
        , CommonMethod.InchesToPixels(m_print.DefaultPaperSize.Height / 100f, g.DpiY)
        , CommonMethod.PixelToMillimeters(m_print.DefaultPaperSize.Width,g.DpiX)
        , CommonMethod.PixelToMillimeters(m_print.DefaultPaperSize.Height, g.DpiY));
      g.DrawString(defaultSize,new Font("宋体",9), m_brush,50,50);


      string defaultMargin = string.Format("页边距:上={0},下={1},左={2},右={3}"
        , CommonMethod.InchesToPixels(m_print.DefaultMargins.Top, g.DpiY)
        , CommonMethod.InchesToPixels(m_print.DefaultMargins.Bottom, g.DpiY)
        , CommonMethod.InchesToPixels(m_print.DefaultMargins.Left/ 100f,g.DpiX)
        , CommonMethod.InchesToPixels(m_print.DefaultMargins.Right/ 100f,g.DpiX));
      g.DrawString(defaultMargin, new Font("宋体", 12), m_brush, 50, 70);


      string lrCrossStr = string.Format("左右各{0}毫米"
        , CommonMethod.PixelToMillimeters(m_template.Width / 2F, g.DpiX));
      g.DrawString(lrCrossStr, new Font("宋体", 12)
        , m_brush
        , m_print.DefaultPaperSize.Width / 3F
        , m_print.DefaultPaperSize.Height / 2 + 30);
      string tdCrossStr = string.Format("上下各{0}毫米"
        , CommonMethod.PixelToMillimeters(m_template.Height / 2F, g.DpiY));
      g.DrawString(tdCrossStr, new Font("宋体", 12)
        , m_brush
        , m_print.DefaultPaperSize.Width / 3F
        , m_print.DefaultPaperSize.Height / 2 + 45);
    }




    #region 公共方法
    /// <summary>
    /// 打印预览
    /// </summary>
    /// <returns></returns>
    public DialogResult PrintProview()
    {
      return m_print.PrintView();
    }
    /// <summary>
    /// 开始打印
    /// </summary>
    public void PrintOut()
    {
      m_print.PrintOut();
    }
    #endregion
  }
}

======================================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Printing;
using Lib.Utility.Extension;
using PrintOrder.Utility;


namespace PrintOrder.ExpressPrinter.PrintDoc
{
  /// <summary>
  /// 打印图片内容
  /// </summary>
  public class ImagePrinter:IDisposable
  {
    public ImagePrinter(string printerName)
    {
      if (!printerName.IsNullOrEmpty())
        this.DefaultPrinterName = printerName;
      //打印事件设置
      m_printDoc.PrintPage += new PrintPageEventHandler(this.m_printDoc_PrintPage);
    }


    #region 变量
    /// <summary>
    /// 打印内容
    /// </summary>
    protected Bitmap m_printContent = null;
    /// <summary>
    /// 打印机名称
    /// </summary>
    protected string m_printerName = string.Empty;
    /// <summary>
    /// 打印预览
    /// </summary>
    PrintPreviewDialog m_printPreview = new PrintPreviewDialog();
    /// <summary>
    /// 待打印文档
    /// </summary>
    PrintDocument m_printDoc = new PrintDocument();
    #endregion


    #region 属性
    /// <summary>
    /// 待打印文档名,打印队列中的显示值
    /// </summary>
    /// <remarks>创建人员(日期):★草青工作室★(111216 12:13)</remarks>
    public string PrintDocName
    {
      set { m_printDoc.DocumentName = value; }
      get { return m_printDoc.DocumentName ; }
    }
    /// <summary>
    /// 获取或设置默认纸张名称
    /// </summary>
    /// <remarks>创建人员(日期):★草青工作室★(111216 12:13)</remarks>
    public string DefaultPrinterName
    {
      set { m_printDoc.DefaultPageSettings.PrinterSettings.PrinterName = value; }
      get { return m_printDoc.DefaultPageSettings.PrinterSettings.PrinterName; }
    }
    /// <summary>
    /// 获取或设置默认纸张大小
    /// </summary>
    /// <remarks>创建人员(日期):★草青工作室★(111216 12:13)</remarks>
    public PaperSize DefaultPaperSize
    {
      set { m_printDoc.DefaultPageSettings.PaperSize = value; }
      get { return m_printDoc.DefaultPageSettings.PaperSize; }
    }
    /// <summary>
    /// 获取或设置默认页边距
    /// </summary>
    /// <remarks>创建人员(日期):★草青工作室★(111216 12:13)</remarks>
    public Margins DefaultMargins
    {
      set { m_printDoc.DefaultPageSettings.Margins = value; }
      get { return m_printDoc.DefaultPageSettings.Margins; }
    }
    
    #endregion


    #region 方法
    /// <summary>
    /// 准备打印
    /// </summary>
    /// <param name="printContent">打印内容</param>
    /// <returns></returns>
    /// <remarks>创建人员(日期):★草青工作室★(111217 16:45)</remarks>
    public bool PrinterReady(Bitmap printContent)
    {
      m_printContent = printContent;
      //打印事件设置
      m_printDoc.PrintPage += new PrintPageEventHandler(this.m_printDoc_PrintPage);
      return true;
    }
    /// <summary>
    /// 打印浏览
    /// </summary>
    /// <remarks>创建人员(日期):★草青工作室★(111215 21:50)</remarks>
    public DialogResult PrintView()
    {
      //打印预览
      PrintPreviewDialog ppd = new PrintPreviewDialog();
      ppd.Document = m_printDoc;
      return ppd.ShowDialog();
    }
    /// <summary>
    /// 开始打印
    /// </summary>
    /// <remarks>创建人员(日期):★草青工作室★(111215 21:50)</remarks>
    public void PrintOut()
    {
      try
      {
        m_printDoc.Print();
      }
      catch (Exception ex)
      {
        //RegisterLog.ExceptionsStack.RegisterError(ex);
        MessageBox.Show(ex.Message, "打印出错,详见异常日志!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        m_printDoc.PrintController.OnEndPrint(m_printDoc, new PrintEventArgs());
      }
    }
    /// <summary>
    /// 打印事件处理
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void m_printDoc_PrintPage(object sender, PrintPageEventArgs e)
    {
      e.Graphics.PageUnit = GraphicsUnit.Pixel;
      //目标大小(注:打印区域使用的是‘百分之一英寸’为单位)
      int x = e.MarginBounds.X;
      int y = e.MarginBounds.Y;
      float width = CommonMethod.InchesToPixels((float)Math.Round(e.MarginBounds.Width/100.0,2),e.Graphics.DpiX);
      float height = CommonMethod.InchesToPixels((float)Math.Round(e.MarginBounds.Height / 100.0, 2), e.Graphics.DpiY);
      RectangleF destRectF = new RectangleF(x, y, width, height);//目标大小
      //原图大小
      Rectangle srcRectF = new Rectangle(0, 0, m_printContent.Width, m_printContent.Height); 
      //绘制打印内容
      e.Graphics.DrawImage(m_printContent
        , destRectF, srcRectF
        , GraphicsUnit.Pixel);
    }


    #endregion




    public void Dispose()
    {
      if(m_printDoc != null)
        m_printDoc.PrintPage -= new PrintPageEventHandler(this.m_printDoc_PrintPage);
    }
  }
}

使用的公共方法:http://my.csdn.net/xxj_jing/code/detail/41360

原文地址:http://blog.csdn.net/xxj_jing/article/details/8685728


你可能感兴趣的:(封装一个打印的公共类,跟童鞋们分享一下)