using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace Project
{
public partial class frmMain : Form
{
static public int m_cord_y = 0;
static public int m_cord_y_inc = 5;
public frmMain()
{
InitializeComponent();
Print();
}
/// <summary>
/// 调用此函数即可实现打印功能
/// </summary>
private void Print()
{
PrintDocument prnDoc = new PrintDocument();
PrintPreviewDialog predDlg = new PrintPreviewDialog();
//prnDlg.Document = prnDoc;
predDlg.Document = prnDoc;
//设置页面大小
PaperSize ppSize = new PaperSize("A4",MM2Atom(210), MM2Atom(297));
prnDoc.DefaultPageSettings.PaperSize = ppSize;
prnDoc.PrintPage += new PrintPageEventHandler(OnPrintPage);
predDlg.ShowDialog();
}
/// <summary>
/// 在此处添加打印内容
/// </summary>
/// <param name="obj"></param>
/// <param name="ppea"></param>
private void OnPrintPage(Object obj, PrintPageEventArgs ppea)
{
Graphics grfx = ppea.Graphics;
AddCaption(grfx, ppea, "草廬對");
string[] str =
{
"自董卓已來,豪傑並起,跨州連郡者不可勝數。",
"曹操比於袁紹,則名微而眾寡",
"然操遂能克紹,以弱為彊者,非惟天命,抑亦人謀也。"
};
int index = 0;
while (index < str.Length)
AddContent(grfx, ppea, str[index++]);
AddSubContent(grfx,ppea,"打印日期:"+System.DateTime.Now.ToString());
ppea.HasMorePages = false;
}
/// <summary>
/// 添加打印正文
/// </summary>
/// <param name="grfx"></param>
/// <param name="ppea"></param>
/// <param name="str"></param>
private void AddContent(Graphics grfx, PrintPageEventArgs ppea,string str)
{
Font font = new Font("宋体", 12);
Brush brush = Brushes.Black;
PointF point = new PointF();
point.X = MM2Atom(11);
point.Y = MM2Atom(41+m_cord_y);
m_cord_y = m_cord_y + m_cord_y_inc;
grfx.DrawString(str, font, brush, point);
}
/// <summary>
/// 添加页脚
/// </summary>
/// <param name="grfx"></param>
/// <param name="ppea"></param>
/// <param name="str"></param>
private void AddSubContent(Graphics grfx, PrintPageEventArgs ppea, string str)
{
Font font = new Font("宋体", 8);
Brush brush = Brushes.Black;
PointF point = new PointF();
point.X = MM2Atom(160);
point.Y = MM2Atom(280);
m_cord_y = m_cord_y + m_cord_y_inc;
grfx.DrawString(str, font, brush, point);
}
/// <summary>
/// 添加标题
/// </summary>
/// <param name="grfx"></param>
/// <param name="ppea"></param>
/// <param name="str"></param>
private void AddCaption(Graphics grfx, PrintPageEventArgs ppea,string str)
{
Font font = new Font("黑体", 16);
Pen pen = new Pen(Color.Black, 1);
Brush brush = Brushes.Black;
//显示数据图标
//grfx.DrawImageUnscaled(global::Project.Properties.Resources.br, MM2Atom(12), MM2Atom(11));
SizeF sizef = grfx.MeasureString(str, font);
grfx.DrawString(str, font, brush, (grfx.VisibleClipBounds.Width - sizef.Width) / 2, MM2Atom(12));
}
private int MM2Atom(double mm)
{
double foot = 304.8; //1 foot equal 304.8 mm
double inch = foot / 12f;
double atomUnit = inch / 100;
return Convert.ToInt32(mm / atomUnit);
}
}
}
c#简单打印
最新推荐文章于 2024-09-12 18:54:58 发布