【C#】打印机 printDocument、printDialog、PageSetupDialog、printPreviewDialog

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


            
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JimCarter

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值