码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2018-04-20 16:01:42      阅读:413      评论:0      收藏:0      [点我收藏+]

标签:tco   settings   转换   ng2   end   bmp   double   大于   nta   

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);
                // 将当前打印内容的Y坐标设置为打印页高(如有多页,每次都会从当前(0, currentY)开始打印
                currentY += pHeight;
                //当整个待打印区域超出了打印页,将表示有多页
                if (aHeight - currentY > 0)
                {
                    e.HasMorePages = true;
                }
                else
                {
                    e.HasMorePages = false;
                }
            }
        }

 

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

标签:tco   settings   转换   ng2   end   bmp   double   大于   nta   

原文地址:https://www.cnblogs.com/nb08611033/p/8890866.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!