C# 打印必备

1.打印纸张设置、像素转毫米、像素转英寸、毫米转英寸

2.像素转换是使用的 DPI 获取方式,这里提供三种方法

3.下面有两个文件,一个 form 窗体文件,一个是转换的公共方法类

C# 打印必备_第1张图片

C# 打印必备_第2张图片

**************************************************************************

using System;
using System.Drawing;
using System.Drawing.Printing;
using System.Runtime.InteropServices;
using System.Windows.Forms;


namespace PrintOrder.ExpressPrinter
{
  public partial class FrmTest : Form
  {
    public FrmTest()
    {
      InitializeComponent();
      //使用窗体获取DPI
      m_dpiX = this.CreateGraphics().DpiX;
      m_dpiY = this.CreateGraphics().DpiY;
      //使用系统API获取DPI
      SetProcessDPIAware(); //重要
      IntPtr screenDC = GetDC(IntPtr.Zero);
      int dpi_x = GetDeviceCaps(screenDC, LOGPIXELSX);
      int dpi_y = GetDeviceCaps(screenDC, LOGPIXELSY);
      ReleaseDC(IntPtr.Zero, screenDC);
      //使用GDI+ 绘图图面 获取DPI
      float imgX, imgY = 0;
      Bitmap map = new Bitmap(100, 100);
      using (Graphics g = Graphics.FromImage(map))
      {
        imgX = g.DpiX;
        imgY = g.DpiY;
      }
      //显示三种DPI
      this.textBox1.Text = string.Format("窗口DPI:x={0},y={1}; 系统DPI:x={2},y={3}; 图片DPI:x={4},y={5}"
                                         , m_dpiX
                                         , m_dpiY
                                         , dpi_x
                                         , dpi_y
                                         , imgX
                                         , imgY);
    }


    float m_dpiX = 0;
    float m_dpiY = 0;
    #region 获取系统DPI
    
    [DllImport("user32.dll")]
    static extern IntPtr GetDC(IntPtr ptr);


    [DllImport("user32.dll", EntryPoint = "ReleaseDC")]
    public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDc);


    [DllImport("gdi32.dll")]
    public static extern IntPtr CreateDC(
    string lpszDriver, // driver name
    string lpszDevice, // device name
    string lpszOutput, // not used; should be NULL
    Int64 lpInitData // optional printer data
    );


    [DllImport("gdi32.dll")]
    public static extern int GetDeviceCaps(
    IntPtr hdc, // handle to DC
    int nIndex // index of capability
    );


    [DllImport("user32.dll")]
    internal static extern bool SetProcessDPIAware();


    //const int DRIVERVERSION = 0;
    //const int TECHNOLOGY = 2;
    //const int HORZSIZE = 4;
    //const int VERTSIZE = 6;
    //const int HORZRES = 8;
    //const int VERTRES = 10;
    //const int BITSPIXEL = 12;
    //const int PLANES = 14;
    //const int NUMBRUSHES = 16;
    //const int NUMPENS = 18;
    //const int NUMMARKERS = 20;
    //const int NUMFONTS = 22;
    //const int NUMCOLORS = 24;
    //const int PDEVICESIZE = 26;
    //const int CURVECAPS = 28;
    //const int LINECAPS = 30;
    //const int POLYGONALCAPS = 32;
    //const int TEXTCAPS = 34;
    //const int CLIPCAPS = 36;
    //const int RASTERCAPS = 38;
    //const int ASPECTX = 40;
    //const int ASPECTY = 42;
    //const int ASPECTXY = 44;
    //const int SHADEBLENDCAPS = 45;
    const int LOGPIXELSX = 88;
    const int LOGPIXELSY = 90;
    //const int SIZEPALETTE = 104;
    //const int NUMRESERVED = 106;
    //const int COLORRES = 108;
    //const int PHYSICALWIDTH = 110;
    //const int PHYSICALHEIGHT = 111;
    //const int PHYSICALOFFSETX = 112;
    //const int PHYSICALOFFSETY = 113;
    //const int SCALINGFACTORX = 114;
    //const int SCALINGFACTORY = 115;
    //const int VREFRESH = 116;
    //const int DESKTOPVERTRES = 117;
    //const int DESKTOPHORZRES = 118;
    //const int BLTALIGNMENT = 119;


    #endregion


    #region 打印功能
    private void FrmTest_Load(object sender, EventArgs e)
    {
      m_printDoc = new PrintDocument();
      m_printDoc.PrintPage += new PrintPageEventHandler(m_printDoc_PrintPage);
      //打印页边距(百分之一英寸)-- 暂时没有设置成功
      //m_printDoc.OriginAtMargins = true;
      //m_printDoc.DefaultPageSettings.Margins = new Margins(10, 10, 10, 10);
      //打印纸张大小(百分之一英寸)
      m_printDoc.DefaultPageSettings.PaperSize = new PaperSize("newPage"
        , (int)Utility.CommonMethod.MillimetersToInches(m_pageWidth) * 100  //四舍五入到double再转int
        , (int)Utility.CommonMethod.MillimetersToInches(m_pageHeight) * 100);
    }


    private PrintDocument m_printDoc = null;
    private PrintPreviewDialog m_printPreview=new PrintPreviewDialog();
    private float m_pageWidth = 230.5F;//单位毫米
    private float m_pageHeight = 100.5F;//单位毫米
    private float m_recWidth = 50F;//单位毫米
    private float m_recHeight = 35F;//单位毫米


    /// <summary>
    /// 绘制需要打印的内容
    /// </summary>
    void m_printDoc_PrintPage(object sender, PrintPageEventArgs e)
    {
      //绘制背景
      e.Graphics.PageUnit = GraphicsUnit.Inch;
      e.Graphics.FillRectangle(Brushes.White, 0F, 0F
        , Utility.CommonMethod.MillimetersToInches(m_pageWidth)
        , Utility.CommonMethod.MillimetersToInches(m_pageHeight));


      DrawingByInches(e.Graphics);
      DrawingByMillimeters(e.Graphics);
      DrawingByPixel(e.Graphics);
    }
    /// <summary>
    /// 以英寸为单位绘制
    /// </summary>
    private void DrawingByInches(Graphics g)
    {
      g.PageUnit = GraphicsUnit.Inch;
      g.FillRectangle(Brushes.White, 0F, 0F
        , Utility.CommonMethod.MillimetersToInches(m_pageWidth)
        , Utility.CommonMethod.MillimetersToInches(m_pageHeight));
      g.DrawRectangle(new Pen(Brushes.Red, 0.01f), 0.5f, 0.5f
        , Utility.CommonMethod.MillimetersToInches(m_recWidth)
        , Utility.CommonMethod.MillimetersToInches(m_recHeight));
    }
    /// <summary>
    /// 以毫米为单位绘制
    /// </summary>
    private void DrawingByMillimeters(Graphics g)
    {
      g.PageUnit = GraphicsUnit.Millimeter;
      g.DrawRectangle(new Pen(Brushes.Blue, 0.2f),20f, 20f
        , m_recWidth
        , m_recHeight);
    }
    /// <summary>
    /// 以像素为单位绘制
    /// </summary>
    private void DrawingByPixel(Graphics g)
    {
      g.PageUnit = GraphicsUnit.Pixel;
      g.DrawRectangle(new Pen(Brushes.Black, 1f), 80f, 50f
        , Utility.CommonMethod.MillimetersToPixel(m_recWidth, g.DpiX)
        , Utility.CommonMethod.MillimetersToPixel(m_recHeight, g.DpiY));
    }


    private void btnView_Click(object sender, EventArgs e)
    {
      m_printPreview.Document = m_printDoc;
      m_printPreview.ShowDialog();
    }


    private void btnPrint_Click(object sender, EventArgs e)
    {
      m_printDoc.Print();
    }
    #endregion
  }
}

**************************************************************************

using System;
using System.Windows.Forms;


namespace PrintOrder.Utility
{
  /// <summary>
  /// 公共方法
  /// </summary>
  public class CommonMethod
  {
    /// <summary>
    /// 显示普通 MessageBox 提示框
    /// </summary>
    /// <param name="msg"></param>
    public static void ShowMessageBox(string msg)
    {
      MessageBox.Show(msg,"提示");
    }
    /// <summary>
    /// 毫米转为像素(注:dpi分水平和垂直,获取方法为得到 Graphics 的实例化对象 g,调用g.DpiX、g.DpiY)
    /// </summary>
    /// <param name="mm">毫米</param>
    /// <param name="fDPI">分辨率(水平/垂直)</param>
    /// <returns></returns>
    public static float MillimetersToPixel(float mm, float fDPI)
    {
      //毫米转像素:mm * dpi / 25.4 
      return (float)Math.Round((mm * fDPI / 25.4f),2);
    }
    /// <summary>
    /// 像素转为毫米(注:dpi分水平和垂直,获取方法为得到 Graphics 的实例化对象 g,调用g.DpiX、g.DpiY)
    /// </summary>
    /// <param name="px">像素</param>
    /// <param name="fDPI">分辨率(水平/垂直)</param>
    /// <returns></returns>
    public static float PixelToMillimeters(float px, float fDPI)
    {
      //像素转毫米:px * 25.4 / dpi
      return (float)Math.Round(((px * 25.4f) / fDPI), 2); ;
    }
    /// <summary>
    /// 英寸到像素
    /// </summary>
    /// <param name="inches"></param>
    /// <returns></returns>
    public static float InchesToPixels(float inches, float fDPI)
    {
      return (float)Math.Round(inches * fDPI,2);
    }
    /// <summary>
    /// 像素到英寸
    /// </summary>
    /// <param name="px"></param>
    /// <returns></returns>
    public static float PixelsToInches(float px, float fDPI)
    {
      return (float)Math.Round(px / fDPI,2);
    }
    /// <summary>
    /// 毫米到英寸
    /// </summary>
    /// <param name="mm"></param>
    /// <returns></returns>
    public static float MillimetersToInches(float mm)
    {
      return (float)Math.Round(mm / 25.4f, 2);
    }
    /// <summary>
    /// 英寸到毫米
    /// </summary>
    /// <param name="mm"></param>
    /// <returns></returns>
    public static float InchesToMillimeters(float Inches)
    {
      return (float)Math.Round(Inches * 25.4f, 2);
    } 
  }
}

你可能感兴趣的:(C# 打印必备)