using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace PrintTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
static Rectangle GetRealPageBounds(PrintPageEventArgs e, bool preview)
{
if (preview) return e.MarginBounds;
float cx = e.PageSettings.HardMarginX;
float cy = e.PageSettings.HardMarginY;
float dpix = e.Graphics.DpiX;
float dpiy = e.Graphics.DpiY;
Rectangle marginBounds = e.MarginBounds;
marginBounds.Offset((int)(-cx * 100 / dpix), (int)(-cy * 100 / dpiy));
return marginBounds;
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
RectangleF realMarginBounds = GetRealPageBounds(e, false);
e.Graphics.DrawString("hello,你好", new Font(new FontFamily("黑体"), 11), System.Drawing.Brushes.Black,realMarginBounds);
//e.Graphics.DrawString("hello,你好", new Font(new FontFamily("黑体"), 11), System.Drawing.Brushes.Black, 10,35);//用这种方式字体超出纸张长度后不会自动换行 10是左边距,第二个35是上边距
}
private void button1_Click(object sender, EventArgs e)
{
//1.printDocument1 是想要打印的文件
this.printDocument1.DefaultPageSettings.PaperSize = new PaperSize("Custum", 500, 300);
//2.弹出选择打印机首选项
printDialog1.Document = printDocument1;
if (DialogResult.OK == printDialog1 .ShowDialog()) //如果确认,将会覆盖所有的打印参数设置
{
//3.页面设置对话框,设置上下左右边距。(可以不使用,其实PrintDialog对话框已提供页面设置)
PageSetupDialog psd = new PageSetupDialog();
psd.Document = printDocument1;
if (DialogResult.OK == psd.ShowDialog())
{
//4.将写好的格式给打印预览控件以便预览
printPreviewDialog1.Document = printDocument1;
DialogResult result = printPreviewDialog1.ShowDialog();
//5.开始打印
if (result == DialogResult.OK)
this.printDocument1.Print();
}
}
}
}
}
【C#】打印机 printDocument、printDialog、PageSetupDialog、printPreviewDialog
最新推荐文章于 2024-08-14 23:47:48 发布