這段時間做報表,用RDLC客戶老是反應,打印要按幾次纔可以打印,自己測試了一下,發現果真是存在這個問題,貌似自帶的打印是在彈出打印窗口後,第一次點擊是先將當前窗體激活,第二次點擊纔會真正的觸發打印事件,查詢:http://msdn.microsoft.com/zh-cn/library/ms252091(v=vs.100).aspx
修改了裏面幾個地方,如下:
using System; using System.IO; using System.Data; using System.Text; using System.Drawing.Imaging; using System.Drawing.Printing; using System.Collections.Generic; using System.Windows.Forms; using Microsoft.Reporting.WinForms; using System.Drawing; namespace YMParking.ParkingMg { public class Print { int m_currentPageIndex; IList<Stream> m_streams; // 摘要: // 爲 ReportViewer 控件提供流以進行呈現。 // // 返回結果: // ReportViewer 控件可以寫入數據的 Stream 對象。 private Stream CreateStream(string name, string fileNameExtension, Encoding encoding, string mimeType, bool willSeek) { Stream stream = new MemoryStream(); m_streams.Add(stream); return stream; } /// <summary> /// 將報表文件按指定的格式導出 /// </summary> /// <param name="report">報表文件</param> private void Export(LocalReport report) { string deviceInfo = @"<DeviceInfo> <OutputFormat>EMF</OutputFormat> <PageWidth>8.5in</PageWidth> <PageHeight>11in</PageHeight> <MarginTop>0.25in</MarginTop> <MarginLeft>0.25in</MarginLeft> <MarginRight>0.25in</MarginRight> <MarginBottom>0.25in</MarginBottom> </DeviceInfo>"; Warning[] warnings; m_streams = new List<Stream>(); report.Render("Image", deviceInfo, CreateStream, out warnings); foreach (Stream stream in m_streams) stream.Position = 0; } // Handler for PrintPageEvents private void PrintPage(object sender, PrintPageEventArgs ev) { Metafile pageImage = new Metafile(m_streams[m_currentPageIndex]); Rectangle adjustedRect = new Rectangle( ev.PageBounds.Left - (int)ev.PageSettings.HardMarginX, ev.PageBounds.Top - (int)ev.PageSettings.HardMarginY, ev.PageBounds.Width, ev.PageBounds.Height); ev.Graphics.FillRectangle(Brushes.White, adjustedRect); ev.Graphics.DrawImage(pageImage, adjustedRect); m_currentPageIndex++; ev.HasMorePages = (m_currentPageIndex < m_streams.Count); } /// <summary> /// 打印 /// </summary> /// <param name="IsShowPrint">是否彈出打印窗口</param> private void PrintFiel(bool IsShowPrint) { if (m_streams == null || m_streams.Count == 0) throw new Exception("指定的打印的文件錯誤"); PrintDocument document; if (IsShowPrint) { PrintDialog pd = new PrintDialog(); if (pd.ShowDialog() == DialogResult.OK) { document = new PrintDocument(); pd.Document = document; } else { return; } } else { document = new PrintDocument(); } if (!document.PrinterSettings.IsValid) { throw new Exception("連接打印機出錯"); } else { document.PrintPage += new PrintPageEventHandler(PrintPage); m_currentPageIndex = 0; document.Print(); } } public void Run(LocalReport report, bool IsShowPrint) { Export(report); PrintFiel(IsShowPrint); } public void Dispose() { if (m_streams != null) { foreach (Stream stream in m_streams) stream.Close(); m_streams = null; } } } }
寫了這個共用的類,重寫reportViewer打印事件,
private void reportViewer1_Print(object sender, CancelEventArgs e)
{
e.Cancel = true;
Print pt = new Print();
pt.Run(reportViewer1.LocalReport, true);
}
到此,問題解決了。