I am working on a C# project within which I am generating reports from database and displaying then in a DataGridView because it is simpler to add rows and columns dynamically. But I now need to export a DataGridView content into a ReportViewer on the fly for printing purpose. I don't want to show up the ReportViewer. I just want to create its instance and populate from my DatagridView and then display the Print Dialog instantly in order to get a hight quality and well organized layout in the output. Currently I'm printing reports by converting them to HTML and then assign it to a WebBrowser control and call ShowPrintDialog() method. But in this way I'm unable to control some printing issues such as printing column headers in all pages as WebBrowser outputs the table sequentially.
I need to reach this goal in the shortest time as this is a production project.
Any idea is hightly appreciated.
You should use Microsoft Report Viewer
http://www.microsoft.com/en-us/download/details.aspx?id=3841
Add into your project the dll : Microsoft.ReportViewer.Common and Microsoft.ReportViewer.WinForms so you must create a *.rdlc file with this you can change the design of your report. And finally for save it you could do something of this:
public static void PrintArticles(ICollectionView Articles)
{
try
{
var articlesRows = new DataTable("Articles");
articlesRows.Columns.Add("Id");
articlesRows.Columns.Add("Description");
var arts = Articles.Cast<Article>();
foreach (var art in arts)
{
articlesRows.Rows.Add(art.Id, art.Description);
}
ReportViewer reporter = new ReportViewer();
reporter.LocalReport.DisplayName = "Report1";
reporter.LocalReport.ReportPath = Path.Combine(Program.BasePath + "PrintArticles.rdlc");
reporter.LocalReport.DataSources.Clear();
reporter.LocalReport.DataSources.Add(new ReportDataSource("Project1", articlesRows));
byte[] report = reporter.LocalReport.Render("PDF");
reporter.LocalReport.ReleaseSandboxAppDomain();
string pdfpath = Path.Combine(Program.BasePath, "file.pdf");
if (File.Exists(pdfpath))
File.Delete(Path.Combine(Program.BasePath, "file.pdf"));
FileStream writer = new FileStream(pdfpath, FileMode.Create);
writer.Write(report, 0, report.Length);
writer.Close();
Process ar = Process.Start(pdfpath);
}
catch (Exception e)
{
}
}