C#實現打印功能
實際開發過程中經常會遇到打印某種報表的情況,用C#實現打印報表的功能。第一,如果報表的大小合適,或者紙張的大小足夠放得下報表,則可以選擇直接截屏,打印截屏所得的圖片;第二,如果報表和紙張的大小不匹配,則可能需要在程序中根據一定格式拼出合適大小的報表。
截屏實現打印報表
private void button3_Click(object sender, EventArgs e) { // 截屏 Form form = this; if (form != null) { Graphics mygraphics = form.CreateGraphics(); memoryImage = new Bitmap(form.Width, form.Height, mygraphics); Graphics memoryGraphics = Graphics.FromImage(memoryImage); memoryGraphics.CopyFromScreen(form.Location.X, form.Location.Y, 0, 0, form.Size); } // 設置打印文檔名(如果使用Adobe PDF或者Microsoft Office Document Image Writer打印,則作為默認輸出文件名) this.printDocument1.DocumentName = this.label27.Text; this.printDocument1.Print(); } // printDocument1的PrintPage事件 private void printDocument1_PrintPage(object sender, PrintPageEventArgs e) { e.Graphics.Clear(Color.White); e.Graphics.DrawImage(memoryImage, 0, 0); } //定義一個圖片 private Bitmap memoryImage = null;其中button3即為打印按鈕,打印按鈕的監聽事件配置請自行完成(可直接在VS的button3的“屬性”頁中設置)。printDocument1為PrintDocument空間,請自行添加;其PrintPage事件的監聽配置請自行完成。
拼湊特定格式的報表打印
private void button3_Click(object sender, EventArgs e) { this.printDocument1.DocumentName = this.label27.Text; this.printDocument1.Print(); } private void printDocument1_PrintPage(object sender, PrintPageEventArgs e) { e.Graphics.Clear(Color.White); // 開始繪制文檔 // 默認為橫排文字 e.Graphics.DrawString("標題", new Font(new FontFamily("宋體"), 22, FontStyle.Bold), System.Drawing.Brushes.Black, 170, 10); e.Graphics.DrawString("性別:" + this.comboBox1.Text, new Font(new FontFamily("宋體"), 14, FontStyle.Bold), System.Drawing.Brushes.Black, 20, 50); e.Graphics.DrawString("聯系電話:" + this.textBox9.Text, new Font(new FontFamily("宋體"), 14, FontStyle.Bold), System.Drawing.Brushes.Black, 350, 50); e.Graphics.DrawString("地址:" + this.textBox11.Text, new Font(new FontFamily("宋體"), 14, FontStyle.Bold), System.Drawing.Brushes.Black, 20, 80); // 橫線 e.Graphics.DrawLine(Pens.Black, 20, 110, 800, 110); // 豎排文字 e.Graphics.DrawString("內容", new Font(new FontFamily("宋體"), 14, FontStyle.Bold), System.Drawing.Brushes.Black, 20, 120, new StringFormat(StringFormatFlags.DirectionVertical)); }
來自: http://blog.csdn.net/kingzone_2008/article/details/8852316
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!