using Microsoft.Reporting.WebForms;using System.Text;using System.Drawing.Printing;using System.Drawing.Imaging;using System.Configuration; //必须引用的几个命名空间 private void btnPrint_Click(object sender, EventArgs e) { Run(); } private int m_currentPageIndex; private IList m_streams; private DataTable LoadSalesData() { //以下是取得数据源,可以自由发挥 SqlConnection con =new SqlConnection( System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); SqlCommand cmd = new SqlCommand("SELECT * FROM Employees", con); SqlDataAdapter adp = new SqlDataAdapter(); adp.SelectCommand = cmd; con.Open(); DataTable dt = new DataTable(); adp.Fill(dt); con.Close(); return dt; } private Stream CreateStream(string name, string fileNameExtension, Encoding encoding, string mimeType, bool willSeek) { Stream stream = new FileStream(name + "." + fileNameExtension, FileMode.Create); m_streams.Add(stream); return stream; } private void Export(LocalReport report) { //设置导出的报表基本显示的位置格式PageWidth、PageHeight、MarginTop、MarginLeft、MarginRight string deviceInfo = "" + " EMF" + //" 8.5in" + //" 11in" + //" 0.25in" + //" 0.25in" + //" 0.25in" + //" 0.25in" + ""; Warning[] warnings; m_streams = new List(); try { report.Render("Image", deviceInfo, CreateStream, out warnings); } catch (Exception ex) { Exception innerEx = ex.InnerException;//取内异常。因为内异常的信息才有用,才能排除问题。 while (innerEx != null) { label1.Text= innerEx.Message; // 有异常最好断点此调试容易发现问题 innerEx = innerEx.InnerException; } } foreach (Stream stream in m_streams) stream.Position = 0; } private void PrintPage(object sender, PrintPageEventArgs ev) { Metafile pageImage = new Metafile(m_streams[m_currentPageIndex]); ev.Graphics.DrawImage(pageImage, 0, 0); m_currentPageIndex++; ev.HasMorePages = (m_currentPageIndex < m_streams.Count); } private static PrintDocument fPrintDocument = new PrintDocument(); private void Print() { string printerName = fPrintDocument.PrinterSettings.PrinterName; //取得本地的默认打印机 if (m_streams == null || m_streams.Count == 0) return; PrintDocument printDoc = new PrintDocument(); printDoc.PrinterSettings.PrinterName = printerName; if (!printDoc.PrinterSettings.IsValid) { //打印机不可用,直接返回 return; } printDoc.PrintPage += new PrintPageEventHandler(PrintPage); printDoc.Print(); } private void Run() { LocalReport report = new LocalReport(); string spath = ConfigurationManager.AppSettings["ServerFilePath"].ToString(); report.ReportPath =spath ;//报表存放的路径 report.DataSources.Add(new ReportDataSource("NorthwindDataSet_Employees", LoadSalesData())); // 其中NorthwindDataSet_Employees 代表的是做的RDLC报表的数据源 Export(report); m_currentPageIndex = 0; Print(); }