C# GDI 绘图打印
用了很久的水晶报表,最近经常遇到客户电脑上无法安装水晶报表,只能重装系统解决。决定用最原始的 GDI 绘图来打印报表。
using MySql.Data.MySqlClient; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Printing; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace ConsoleApp1 { class Program { static void Main(string[] args) { MyDocument d = new MyDocument(); //d.DefaultPageSettings.PrinterSettings.PrinterName = "GP-L80160 Series";//设置打印机 //Console.WriteLine(d.DefaultPageSettings.PrintableArea.Width);//可以获得打印机的默认纸张宽度 //d.DefaultPageSettings.Landscape = true; 横向纵向控制 d.DefaultPageSettings.PaperSize = GetSize("MyPaper", 100, 500); if (true) { d.Preview();//调用扩展方法 } else { d.Print(); } Console.ReadLine(); } //宽高为毫米 static PaperSize GetSize(string name, float width, float height) { float mul = 3.937f;//GDI 打印尺寸为百分之一英寸,需要对毫米进行转换 return new PaperSize(name, (int)Math.Floor(width * mul), (int)Math.Floor(height * mul)); } } public class MyDocument : PrintDocument { //与 Print_PrintPage 相关的变量需要在 MyDocument_BeginPrint 中初始化。 //仅在构造函数中初始化是不够的。在反复调用 PrintDocument 的 Print 方法时 pageIndex 的值会出错。 int pageIndex; public MyDocument() { this.BeginPrint += MyDocument_BeginPrint; this.PrintPage += Print_PrintPage; } private void MyDocument_BeginPrint(object sender, PrintEventArgs e) { pageIndex = 0; } private void Print_PrintPage(object sender, PrintPageEventArgs e) { string text = "abcdefghijklmn"; Font f = new Font("宋体", 10); StringFormat sf = new StringFormat() { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center, FormatFlags = StringFormatFlags.NoWrap }; //测量字符串,可以指定宽度和是否换行, 默认是允许换行的 SizeF size = e.Graphics.MeasureString(text, f, 100, sf); float x, y; x = y = 10; //在实际绘制文本时使用的文本,字体等样式必须与测量时一致,并使用测量得到的尺寸 e.Graphics.DrawString(text, f, Brushes.Black, new RectangleF(x, y, size.Width, size.Height), sf); //绘制线条 e.Graphics.DrawLine(Pens.Black, 0, 0, 200, 200); if (pageIndex == 0) { pageIndex++; e.HasMorePages = true; } } } public static class PrintDocumentExtension { public static void Preview(this PrintDocument document) { PrintPreviewDialog ppd = new PrintPreviewDialog(); ppd.Document = document; (ppd as Form).WindowState = FormWindowState.Maximized; ppd.ShowDialog(); } } }