C# winform 打印窗体内控件(以图片缩放的形式),核心部分代码

本文介绍了一个使用 C# 实现打印功能的方法,通过获取 splitContainer1.Panel1 中的内容并将其转换为位图,然后根据纸张大小调整打印内容的比例,实现高质量的文档打印。

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Printing;

 

int currentY = 0;
private void PrintDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {//打印文档
            Graphics g = e.Graphics;//获得绘图对象                    
            //待打印区域宽高打印splitContainer1.Panel1中的内容
            int aWidth = splitContainer1.Panel1.DisplayRectangle.Width;
            int aHeight = splitContainer1.Panel1.DisplayRectangle.Height;
            System.Drawing.Printing.PrintDocument pd = sender as System.Drawing.Printing.PrintDocument;
            //页宽高,Bounds自动会考虑到打印页是横向还是纵向打印 
            int pWidth = pd.DefaultPageSettings.Bounds.Width;
            int pHeight = pd.DefaultPageSettings.Bounds.Height;//如果打印区域宽度大于纸张,进行缩放
            double scale = 0.9;//缩放倍数
            int zWidth = aWidth;
            int zHeight = aHeight;
            if (aWidth >= pWidth * scale)
            {//缩小图片
                zWidth = Convert.ToInt32(aWidth * scale);
                zHeight = Convert.ToInt32((zWidth * aHeight) / aWidth);
            }

            if (currentY < aHeight)
            {//新建位图存放打印部分
                Bitmap bmp = new Bitmap(aWidth, aHeight);
                //将表格转换为位图
                splitContainer1.Panel1.DrawToBitmap(bmp, new Rectangle(0, 0, aWidth, aHeight));
                //打印指定位图的指定区域
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor;
                g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half;
                g.DrawImage(bmp,
                    new Rectangle((pWidth - zWidth) / 2, currentY, zWidth, zHeight),//缩放图
                    new Rectangle(0, currentY, bmp.Width, bmp.Height),//源图
                    GraphicsUnit.Pixel);
            }
        }

 

转载于:https://www.cnblogs.com/nb08611033/p/8890866.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值