Dears
Im using Microsoft reportviewer in my asp.net core project to generate a pdf report .
I want to set an external path from my files into the header section as a logo ,
I'm tying to do that not by report designer , i need to do that at runtime by c# code.
im using this code to generate report
public static byte[] GenerateReport(string reportName, string reportHeader, List<ReportDataSource> DataSets, LanguageEnum language, bool setLanguage = true, string returnExtension = "Pdf", string reportParams = "")
{
ReportViewer EMSReportViewer = new ReportViewer();
EMSReportViewer.LocalReport.EnableExternalImages = true;
SetReport(EMSReportViewer, reportName, language, setLanguage, reportParams);
EMSReportViewer.LocalReport.DisplayName = getLabel(reportHeader, language);
EMSReportViewer.LocalReport.DataSources.Clear();
foreach (ReportDataSource dataset in DataSets)
EMSReportViewer.LocalReport.DataSources.Add(dataset);
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string filenameExtension;
byte[] bytes = EMSReportViewer.LocalReport.Render(returnExtension, null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings);
return bytes;
}
can you help me please?
If you want to pass a external images then you need to pass it as a ReportParameter.
Example:
public static byte[] GenerateReport(string reportName, string reportHeader,
List<ReportDataSource> DataSets, LanguageEnum language, bool setLanguage =
true, string returnExtension = "Pdf", string reportParams = "")
{
ReportViewer EMSReportViewer = new ReportViewer();
EMSReportViewer.LocalReport.EnableExternalImages = true;
//ReportParameter
var parameter = new ReportParameter("ImagePath","-Your Image Path--");
EMSReportViewer.LocalReport.SetParameters(parameter);
SetReport(EMSReportViewer, reportName, language, setLanguage, reportParams);
EMSReportViewer.LocalReport.DisplayName = getLabel(reportHeader, language);
EMSReportViewer.LocalReport.DataSources.Clear();
foreach (ReportDataSource dataset in DataSets)
EMSReportViewer.LocalReport.DataSources.Add(dataset);
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string filenameExtension;
byte[] bytes = EMSReportViewer.LocalReport.Render(returnExtension, null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings);
return bytes;
}
I have a method that renders a report as a PDF so that it can be attached in an email. The code is as follows:
private string generate_pdf_report(int ponum)
{
this.DataTable1TableAdapter.Fill(this.reportdataset.DataTable1, ponum);
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string filenameExtension;
string filename = "Purchase Requisition " + ponum.ToString() + ".pdf";
byte[] bytes = reportViewer1.LocalReport.Render(
"PDF", null, out mimeType, out encoding, out filenameExtension,
out streamids, out warnings);
try
{
using (FileStream fs = new FileStream(filename, FileMode.Create))
{
fs.Write(bytes, 0, bytes.Length);
}
}
catch(Exception ex)
{
throw ex;
}
return filename;
}
This works fine the first time, but if the user generates another report and sends an email, the report attached to the email is the first one generated, not the current one.
For example, the user opens the software, creates purchase order #3, and the PDF is generated and emailed correctly. The user then creates a new purchase order without exiting the software, #4. After #4 is submitted, the PDF attached to the email is from #3, like the ReportViewer did not clear out the previous data.
Even if the ReportViewer interface is used to generate a new report, it does not affect what is attached to the email. I have tried clearing the ReportViewer between renders to no avail.
What am I missing here?
I was able to correct the problem by resetting the ReportDataSource each iteration of the function:
this.DataTable1TableAdapter.Fill(this.reportdataset.DataTable1, ponum);
DataTable dt = new DataTable();
dt = DataTable1TableAdapter.GetData(ponum);
Microsoft.Reporting.WinForms.ReportDataSource rprtDTSource = new Microsoft.Reporting.WinForms.ReportDataSource(dt.TableName, dt);
reportViewer1.LocalReport.DataSources.Add(rprtDTSource);
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string filenameExtension;
string filename = "Purchase Requisition " + ponum.ToString() + ".pdf";
byte[] bytes = reportViewer1.LocalReport.Render(
"PDF", null, out mimeType, out encoding, out filenameExtension,
out streamids, out warnings);
try
{
using (FileStream fs = new FileStream(filename, FileMode.Create))
{
fs.Write(bytes, 0, bytes.Length);
fs.Flush();
}
}
catch (Exception ex)
{
throw ex;
}
return filename;
I am getting this error "Cannot create a data reader for dataset 'DataSet1'."
I expend lots of my time for solving this issue but unable to
resolved.Same code is working good for report generation but at the time of pdf generation it stuck.
Here is my code please reply.
protected void btnPdf_Click(object sender, EventArgs e)
{
string PDF = "PDF";
string ReportType = "ReportType";
Warning[] warnings = null;
string[] streamIds = null;
string mimeType = string.Empty;
string encoding = string.Empty;
string extension = string.Empty;
string filetype = string.Empty;
long _landIds = 0;
if (_farmId > 0)
{
Land land = LandManager.GetLandByFarmID(_farmId);
_landIds = land.LandID;
}
ReportViewer_MyReportID.SizeToReportContent = true;
ReportViewer_MyReportID.LocalReport.ReportPath = "reports/report/report.rdlc";
ReportViewer_MyReportID.ProcessingMode = ProcessingMode.Remote;
ObjectDataSource_Id.SelectParameters.Clear();
ObjectDataSource_Id.SelectParameters.Add(QueryStringEnum.CompanyID, CurrentCompanyID.ToString());
ObjectDataSource_Id.SelectParameters.Add(QueryStringEnum.LandID, _landIds.ToString());
var days = "-" + rdDuration.SelectedValue;
ObjectDataSource_Id.SelectParameters.Add(QueryStringEnum.Days, days.ToString());
ReportViewer_MyReportID.LocalReport.Refresh();
byte[] bytes = ReportViewer_MyReportID.LocalReport.Render("PDF", null,
out mimeType, out encoding, out extension, out streamIds, out warnings);
FileStream fs = new FileStream(Server.MapPath("~/GeneratedFiles/" + ReportType + "." + "PDF"), FileMode.OpenOrCreate);
fs.Write(bytes, 0, bytes.Length);
fs.Close();
}
It will work for you.Make sure dataset name is not different.
Code for your reference.
protected void btnPdf_Click(object sender, EventArgs e)
{
ReportViewer viwer = new ReportViewer();
ObjectDataSource ob = new ObjectDataSource("dataset.YourTableAdapter", "GetData");
dataset.YourTableAdapter ds = new dataset.YourTableAdapter();
string PDF = "PDF";
string ReportType = "ReportType";
Warning[] warnings = null;
string[] streamIds = null;
string mimeType = string.Empty;
string encoding = string.Empty;
string extension = string.Empty;
string filetype = string.Empty;
long _landIds = 0;
if (_farmId > 0)
{
Land land = LandManager.GetLandByFarmID(_farmId);
_landIds = land.LandID;
}
viwer.SizeToReportContent = true;
viwer.LocalReport.ReportPath = "reports/report/report.rdlc";
viwer.ProcessingMode = ProcessingMode.Local;
ob.SelectParameters.Clear();
ob.SelectParameters.Add(QueryStringEnum.CompanyID, CurrentCompanyID.ToString());
ob.SelectParameters.Add(QueryStringEnum.LandID, _landIds.ToString());
var days = "-" + rdDuration.SelectedValue;
ob.SelectParameters.Add(QueryStringEnum.Days, days.ToString());
ReportDataSource rds = new ReportDataSource("datasetname", (object) ds.GetData((long?)CurrentCompanyID.ToInt64(), (int?)days.ToInt(), (long?)_landIds.ToInt64()));
viwer.LocalReport.DataSources.Add(rds);
viwer.LocalReport.Refresh();
byte[] bytes = viwer.LocalReport.Render("PDF", null,
out mimeType, out encoding, out extension, out streamIds, out warnings);
FileStream fs = new FileStream(Server.MapPath("~/GeneratedFiles/" + ReportType + "." + "PDF"), FileMode.OpenOrCreate);
fs.Write(bytes, 0, bytes.Length);
fs.Close();
}
I am running a month-end process and want to have it automatically create some of the reports that need to be created at that time. I am using rdlc reports. Is there a way to automatically create a PDF from a RDLC report in the background?
This is easy to do, you can render the report as a PDF, and save the resulting byte array as a PDF file on disk. To do this in the background, that's more a question of how your app is written. You can just spin up a new thread, or use a BackgroundWorker (if this is a WinForms app), etc. There, of course, may be multithreading issues to be aware of.
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string filenameExtension;
byte[] bytes = reportViewer.LocalReport.Render(
"PDF", null, out mimeType, out encoding, out filenameExtension,
out streamids, out warnings);
using (FileStream fs = new FileStream("output.pdf", FileMode.Create))
{
fs.Write(bytes, 0, bytes.Length);
}
You can use following code which generate pdf file in background as like on button click and then would popup in brwoser with SaveAs and cancel option.
Warning[] warnings;
string[] streamIds;
string mimeType = string.Empty;
string encoding = string.Empty;`enter code here`
string extension = string.Empty;
DataSet dsGrpSum, dsActPlan, dsProfitDetails,
dsProfitSum, dsSumHeader, dsDetailsHeader, dsBudCom = null;
enter code here
//This is optional if you have parameter then you can add parameters as much as you want
ReportParameter[] param = new ReportParameter[5];
param[0] = new ReportParameter("Report_Parameter_0", "1st Para", true);
param[1] = new ReportParameter("Report_Parameter_1", "2nd Para", true);
param[2] = new ReportParameter("Report_Parameter_2", "3rd Para", true);
param[3] = new ReportParameter("Report_Parameter_3", "4th Para", true);
param[4] = new ReportParameter("Report_Parameter_4", "5th Para");
DataSet dsData= "Fill this dataset with your data";
ReportDataSource rdsAct = new ReportDataSource("RptActDataSet_usp_GroupAccntDetails", dsActPlan.Tables[0]);
ReportViewer viewer = new ReportViewer();
viewer.LocalReport.Refresh();
viewer.LocalReport.ReportPath = "Reports/AcctPlan.rdlc"; //This is your rdlc name.
viewer.LocalReport.SetParameters(param);
viewer.LocalReport.DataSources.Add(rdsAct); // Add datasource here
byte[] bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
// byte[] bytes = viewer.LocalReport.Render("Excel", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
// Now that you have all the bytes representing the PDF report, buffer it and send it to the client.
// System.Web.HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Buffer = true;
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "attachment; filename= filename" + "." + extension);
Response.OutputStream.Write(bytes, 0, bytes.Length); // create the file
Response.Flush(); // send it to the client to download
Response.End();
You don't need to have a reportViewer control anywhere - you can create the LocalReport on the fly:
var lr = new LocalReport
{
ReportPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? #"C:\", "Reports", "PathOfMyReport.rdlc"),
EnableExternalImages = true
};
lr.DataSources.Add(new ReportDataSource("NameOfMyDataSet", model));
string mimeType, encoding, extension;
Warning[] warnings;
string[] streams;
var renderedBytes = lr.Render
(
"PDF",
#"<DeviceInfo><OutputFormat>PDF</OutputFormat><HumanReadablePDF>False</HumanReadablePDF></DeviceInfo>",
out mimeType,
out encoding,
out extension,
out streams,
out warnings
);
var saveAs = string.Format("{0}.pdf", Path.Combine(tempPath, "myfilename"));
var idx = 0;
while (File.Exists(saveAs))
{
idx++;
saveAs = string.Format("{0}.{1}.pdf", Path.Combine(tempPath, "myfilename"), idx);
}
using (var stream = new FileStream(saveAs, FileMode.Create, FileAccess.Write))
{
stream.Write(renderedBytes, 0, renderedBytes.Length);
stream.Close();
}
lr.Dispose();
You can also add parameters: (lr.SetParameter()), handle subreports: (lr.SubreportProcessing+=YourHandler), or pretty much anything you can think of.
The below code work fine with me of sure thanks for the above comments. You can add report viewer and change the visible=false and use the below code on submit button:
protected void Button1_Click(object sender, EventArgs e)
{
Warning[] warnings;
string[] streamIds;
string mimeType = string.Empty;
string encoding = string.Empty;
string extension = string.Empty;
string HIJRA_TODAY = "01/10/1435";
ReportParameter[] param = new ReportParameter[3];
param[0] = new ReportParameter("CUSTOMER_NUM", CUSTOMER_NUMTBX.Text);
param[1] = new ReportParameter("REF_CD", REF_CDTB.Text);
param[2] = new ReportParameter("HIJRA_TODAY", HIJRA_TODAY);
byte[] bytes = ReportViewer1.LocalReport.Render(
"PDF",
null,
out mimeType,
out encoding,
out extension,
out streamIds,
out warnings);
Response.Buffer = true;
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader(
"content-disposition",
"attachment; filename= filename" + "." + extension);
Response.OutputStream.Write(bytes, 0, bytes.Length); // create the file
Response.Flush(); // send it to the client to download
Response.End();
}
private void PDFExport(LocalReport report)
{
string[] streamids;
string minetype;
string encod;
string fextension;
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;
byte[] rpbybe = report.Render("PDF", deviceInfo, out minetype, out encod, out fextension, out streamids,
out warnings);
using(FileStream fs=new FileStream("E:\\newwwfg.pdf",FileMode.Create))
{
fs.Write(rpbybe , 0, rpbybe .Length);
}
}
You can instanciate LocalReport
FicheInscriptionBean fiche = new FicheInscriptionBean();
fiche.ToFicheInscriptionBean(inscription);List<FicheInscriptionBean> list = new List<FicheInscriptionBean>();
list.Add(fiche);
ReportDataSource rds = new ReportDataSource();
rds = new ReportDataSource("InscriptionDataSet", list);
// attachement du QrCode.
string stringToCode = numinscription + "," + inscription.Nom + "," + inscription.Prenom + "," + inscription.Cin;
Bitmap BitmapCaptcha = PostulerFiche.GenerateQrCode(fiche.NumInscription + ":" + fiche.Cin, Brushes.Black, Brushes.White, 200);
MemoryStream ms = new MemoryStream();
BitmapCaptcha.Save(ms, ImageFormat.Gif);
var base64Data = Convert.ToBase64String(ms.ToArray());
string QR_IMG = base64Data;
ReportParameter parameter = new ReportParameter("QR_IMG", QR_IMG, true);
LocalReport report = new LocalReport();
report.ReportPath = Page.Server.MapPath("~/rdlc/FicheInscription.rdlc");
report.DataSources.Clear();
report.SetParameters(new ReportParameter[] { parameter });
report.DataSources.Add(rds);
report.Refresh();
string FileName = "FichePreinscription_" + numinscription + ".pdf";
string extension;
string encoding;
string mimeType;
string[] streams;
Warning[] warnings;
Byte[] mybytes = report.Render("PDF", null,
out extension, out encoding,
out mimeType, out streams, out warnings);
using (FileStream fs = File.Create(Server.MapPath("~/rdlc/Reports/" + FileName)))
{
fs.Write(mybytes, 0, mybytes.Length);
}
Response.ClearHeaders();
Response.ClearContent();
Response.Buffer = true;
Response.Clear();
Response.Charset = "";
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + FileName + "\"");
Response.WriteFile(Server.MapPath("~/rdlc/Reports/" + FileName));
Response.Flush();
File.Delete(Server.MapPath("~/rdlc/Reports/" + FileName));
Response.Close();
Response.End();
I'm trying to output a report as pdf and everything seems fine except I'm seeing only one page in the final output. The datasrouce is showing a count 2 but the final report shows only 1 page.
This is what I have in code:
if (reportType == ReportType.AllJobs)
{
dataSource = BRInfoGateway.GetAllJobs(); //This shows a count of 2 during debug
reportName = "./Reports/AllJobs.rdlc";
}
else
{
dataSource = BRInfoGateway.GetJob(jobContext);
reportName = "./Reports/SpecificJob.rdlc";
}
var report = new LocalReport();
report.ReportPath = reportName;
report.DataSources.Add(new ReportDataSource("BRInfo", dataSource));
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string extension;
return report.Render("PDF", null, out mimeType, out encoding, out extension,
out streamids, out warnings);
Then in my test I'm just saving the byte[]. Pretty normal stuf...
var reportData = Reports.ReportsGateway.GetReport(Reports.ReportType.AllJobs, null);
string filename = "AllJobs.pdf";
if(File.Exists(filename)) File.Delete(filename);
using (FileStream fs = File.Create(filename))
{
fs.Write(reportData, 0, reportData.Length);
}
Any thoughts. I'm not sure if I have to do something specific in the report template!
I got it to work by using a new report instead of the wizard...no idea why !