private void btnPrint_Click(object sender, EventArgs e)
{
Run();
}
private int m_currentPageIndex;
private IList<Stream> m_streams;
private DataTable LoadSalesData()
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["testrdlc.Properties.Settings.NorthwindConnectionString"].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)
{
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>();
try
{
report.Render("Image", deviceInfo, CreateStream, out warnings);
}
catch (Exception ex)
{
Exception innerEx = ex.InnerException;//取內異常。因爲內異常的信息纔有用,才能排除問題。
while (innerEx != null)
{
MessageBox.Show(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 void Print()
{
const string printerName = "Microsoft Office Document Image Writer";
if (m_streams == null || m_streams.Count == 0)
return;
PrintDocument printDoc = new PrintDocument();
printDoc.PrinterSettings.PrinterName = printerName;
if (!printDoc.PrinterSettings.IsValid)
{
string msg = String.Format("Can't find printer /"{0}/".", printerName);
Debug.WriteLine(msg);
return;
}
printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
printDoc.Print();
}
private void Run()
{
LocalReport report = new LocalReport();
report.ReportPath = Application.StartupPath +"//Report1.rdlc";//加上報表的路徑
report.DataSources.Add(new ReportDataSource("NorthwindDataSet_Employees", LoadSalesData()));
Export(report);
m_currentPageIndex = 0;
Print();
}
要說明的是:
一、report.ReportPath 屬性指定的位置一定要有報表文件。
二、如果report.Render出現異常,必須捕獲內異常信息,因爲最外層異常信息的用處不大,根本無法排除問題。
三、
不預覽直接打印 Microsoft RDLC報表
我用.net寫程序,做報表時一直用水晶報表來做,最近發現用Microsoft的RDLC做報表也不錯,而且方便,最主要佈署(WEB)的時修沒有水晶報表那麼麻煩。 但是唯一的缺點是學習資料太少了,都得自己瞎搞。唯一好的資源就只有蠟人張同志的《RDLC報表》系列,當然還有MSDN 。 下面是不預覽直接打印的實現,主要代碼來自MSDN。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.