首页 > 编程语言 >C# 打印必备

C# 打印必备

时间:2022-10-28 16:37:56浏览次数:39  
标签:float const C# 必备 打印 private int static public


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

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

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

C# 打印必备_desktop

C# 打印必备_sed_02

**************************************************************************
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);
}
}
}

标签:float,const,C#,必备,打印,private,int,static,public
From: https://blog.51cto.com/xxjjing/5805022

相关文章

  • asp.net mvc 3 获取路由领域名
    ----------------------------------------------------------------------------------------------------一、注册路由publicclassSysAreaRegistration:AreaRegist......
  • 解决 win7 注册com组件失败问题
    解决win7注册com组件失败问题运行:regsvr32xxx.ocx提示:模块"xxx.ocx"已加载,但对调用dllregisterserver的调用失败,错误代码0x80004005。问题分析:由于win7权限导......
  • nchu-software-oop-2022-5
    7-1点线形系列5-凸五边形的计算-1分数50  作者蔡轲  单位南昌航空大学用户输入一组选项和数据,进行与五边形有关的计算。以下五边形顶点的坐标要求按顺序......
  • C# 反射动态判断转换属性类型值生成类实例
    ///<summary>///为指定对象分配参数///</summary>///<typeparamname="T">待赋值的类型</typeparam>///<paramname="dic">字段/值</param>/......
  • 使用CEfSharp之旅(1) 加载网络页面
    新建工程winform,添加Nuget程序包Cefsharp.winform 本工程使用57.0版本 Cefsharp。请注意使用的版本  staticChromiumWebBrowserweb;privatevoidBrowser......
  • Mybatis出现java.io.IOException: Could not find resource XXX.xml异常
    //使用MyBatis提供的Resources类加载mybatis的配置文件Readerreader=Resources.getResourceAsReader("MenuConfig.xml");这条语句中不会写文件路径解决办......
  • 使用CEfSharp之旅(4)cefsharp 调用F12
    privatevoidbutton1_Click_1(objectsender,EventArgse){web.ShowDevTools();}......
  • web微信js WechatWeb js方法
    获取自己的信息JSangular.element(".info").scope().account;angular.element(".profile_mini").scope().contact获取左边的正在聊天的好友angular.element("#J_NavChatScro......
  • leetcode(32)前缀和系列题目
    303.区域和检索-数组不可变记录前i个元素的和,因此sum[left,right+1]=pre[right+1]-pre[left]classNumArray:def__init__(self,nums:List[int]):......
  • TypeC的CC、UFP、DFP、DRP
    1.CC(ConfigurationChannel):配置通道,这是USBType-C里新增的关键通道。它的作用有检测正反插,检测USB连接识别可以提供多大的电压和电流,USB设备间数据与VBUS的连接建立......