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