Creating a PDF from a RDLC Report in the Background - c#

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();

Related

Render a report to pdf

i have a c# code that renders a report into pdf form.
Random rand = new Random();
num = rand.Next(1111, 999999);
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string extension;
String deviceInf = "<DeviceInfo><PageHeight>8.27in</PageHeight><PageWidth>11.69in</PageWidth><MarginTop>0in</MarginTop><MarginBottom>0in</MarginBottom><MarginLeft>0in</MarginLeft><MarginRight>0in</MarginRight></DeviceInfo>";
byte[] bytes = reportViewer1.LocalReport.Render
(
"PDF", deviceInf, out mimeType, out encoding,
out extension,
out streamids, out warnings);
var folderPath = "D:\\ICard\\STAFFPDF\\";
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
FileStream fs = new FileStream(#"D:\ICard\STAFFPDF\" + num + ".pdf", FileMode.Create);
fs.Write(bytes, 0, bytes.Length);
this.reportViewer1.Refresh();
fs.Close();
What i am trying to do is save the pdf in a mirror form because the pdf needs to be printed as mirror image, is there any way i can achieve this ?
Try this piece of code. Source is here.
private string ExportReport()
{
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string filenameExtension;
ReportParameterInfoCollection pInfo = reportViewer1.ServerReport.GetParameters();
string filenameParams = "";
byte[] bytes;
if (reportViewer1.ProcessingMode == ProcessingMode.Local)
{
bytes = reportViewer1.LocalReport.Render("PDF", null, out mimeType,
out encoding, out filenameExtension, out streamids, out warnings);
}
else
{
bytes = reportViewer1.ServerReport.Render("PDF", null, out mimeType,
out encoding, out filenameExtension, out streamids, out warnings);
}
string filename = Path.Combine(Path.GetTempPath(), filenameParams + ".pdf");
using (FileStream fs = new FileStream(filename, FileMode.Create))
{ fs.Write(bytes, 0, bytes.Length); }
return filename;
}

How to get HTTP Response while export to excel on button click event

I am Developing RDLC report with export to excel functionality on button click in Asp.net. below code where i am using while button click i am not getting http response please help me how it will get http response
,Thanks
public void btnExportAll_Click(Object sender, EventArgs e)
{
string Name = ddl.SelectedValue;
string Type = Productddl.SelectedValue;
string Id = ddl.SelectedValue;
DateTime BD = Convert.ToDateTime(txtDate.Text);
DataSet ds = new DataSet();
ds = GetCashDataSource(BD, Name, Convert.ToInt32(Id), Flag);
ReportViewer viewer = new ReportViewer();
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string extension;
string filename;
viewer.LocalReport.ReportPath =
Server.MapPath("~/RDLCReports/ReportExport.rdlc");
viewer.LocalReport.DataSources.Clear();
viewer.LocalReport.DataSources.Add(new
ReportDataSource("Balance", ds.Tables[0]));
viewer.LocalReport.DataSources.Add(new
ReportDataSource("Name", ds.Tables[1]));
viewer.LocalReport.DataSources.Add(new
ReportDataSource("Amount", ds.Tables[2]));
viewer.LocalReport.DataSources.Add(new ReportDataSource("Amount",
ds.Tables[3]));
viewer.LocalReport.DataSources.Add(new ReportDataSource("GrandTotal", ds.Tables[4]));
viewer.LocalReport.DataSources.Add(new ReportDataSource("Diff", ds.Tables[5]));
viewer.LocalReport.DataSources.Add(new ReportDataSource("Name", ds.Tables[6]));
viewer.LocalReport.EnableHyperlinks = true;
string Code = "10,12";
ReportParameter rp1 = new ReportParameter("BusinessDate", txtDate.Text, false);
ReportParameter rp2 = new ReportParameter("DropDown", ddl.SelectedValue, false);
ReportParameter rp3 = new ReportParameter("Id", Code, false);
viewer.LocalReport.SetParameters(new ReportParameter[] { rp1, rp2, rp3 })
byte[] bytes = viewer.LocalReport.Render(
"Excel", null, out mimeType, out encoding,
out extension,
out streamids, out warnings);
filename = string.Format("{0}.{1}", "ExportToExcel", "xls");
Response.Buffer = true;
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
try
{
Response.BinaryWrite(bytes);
}
catch (Exception ex)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "ErrorAlert", "alert('Error while generating PDF.');", true);
Console.WriteLine(ex.StackTrace);
}
Response.WriteFile(Server.MapPath("~/RDLCReports/ReportExport.rdlc"));
Response.End();
viewer.LocalReport.Refresh();
}

View RDLC Report as pdf in Asp.net MVC

I am facing problem in last two days. I am trying to view rdlc report as pdf without reportviewer. I export rdlc to pdf using the following code...
public string Export(LocalReport rpt, string filePath)
{
string ack = "";
try
{
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string extension;
byte[] bytes = rpt.Render("PDF", null, out mimeType, out encoding, out extension, out streamids, out warnings);
using (FileStream stream = File.OpenWrite(filePath))
{
stream.Write(bytes, 0, bytes.Length);
}
return ack;
}
catch(Exception ex)
{
ack = ex.InnerException.Message;
return ack;
}
}
The pdf file exported to User->AppData->Temp
string filePath = System.IO.Path.GetTempFileName();
string ack = Export(rpt, Server.MapPath("~/Reports/Mymun_Lab/ComparisonStudy.rdlc"));
System.Diagnostics.Process.Start(filePath);
I want to render this pdf file to the client PC.
This Code is work fine on my local machine. But when i publish this to IIS Server and run for try to get the exported pdf file to client PC not success. How can i solve this issue. Can anyone help me.
Thanks In Advance...
Finally, i found one solution about view RDLC report as pdf in asp.net MVC. The solution is following....
public FileResult ViewReport()
{
string RptPath = Server.MapPath("~/Reports/Mymun_Lab/ComparisonStudy.rdlc");
Microsoft.Reporting.WebForms.LocalReport rpt = new Microsoft.Reporting.WebForms.LocalReport();
/* Bind Here Report Data Set */
rpt.ReportPath = RptPath;
string filePath = System.IO.Path.GetTempFileName();
Export(rpt, filePath);
//CLOSE REPORT OBJECT
rpt.Dispose();
return File(filePath, "application/pdf");
}
I use the following method for generate pdf from RDLC....
public string Export(LocalReport rpt, string filePath)
{
string ack = "";
try
{
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string extension;
byte[] bytes = rpt.Render("PDF", null, out mimeType, out encoding, out extension, out streamids, out warnings);
using (FileStream stream = File.OpenWrite(filePath))
{
stream.Write(bytes, 0, bytes.Length);
}
return ack;
}
catch(Exception ex)
{
ack = ex.InnerException.Message;
return ack;
}
}
[HttpPost]
public async Task<FileResult> DownloadReport(string id, string firstName, string lastName)
{
var result = await accountRepository.GetUserLogInDetailsByID(id);
//string RptPath = Server.MapPath("~/RDLC/rptUserLogInDetails.rdlc");
string RptPath = Server.MapPath("~/RDLC/rptUserLogInDetails.rdlc");
ReportViewer rv = new ReportViewer();
ReportDataSource rds = new ReportDataSource();
rds.Name = "DataSet1";
rds.Value = result;
string companyName = WebConfigurationManager.AppSettings["CompanyName"];
ReportParameter[] parameters = new ReportParameter[2];
parameters[0] = new ReportParameter("username", firstName + " " + lastName);
parameters[1] = new ReportParameter("companyName", companyName);
//ReportViewer rv = new Microsoft.Reporting.WebForms.ReportViewer();
rv.ProcessingMode = ProcessingMode.Local;
rv.LocalReport.ReportPath = RptPath;
// Add the new report datasource to the report.
rv.LocalReport.DataSources.Add(rds);
rv.LocalReport.EnableHyperlinks = true;
rv.LocalReport.SetParameters(parameters);
rv.LocalReport.Refresh();
byte[] streamBytes = null;
string mimeType = "";
string encoding = "";
string filenameExtension = "";
string[] streamids = null;
Warning[] warnings = null;
streamBytes = rv.LocalReport.Render("PDF", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings);
string fileName = "LogInDetails-" + firstName + lastName + ".pdf";
// This will download the pdf file
//return File(streamBytes, mimeType, fileName);
//This will open directly the pdf file
return File(streamBytes, "application/pdf");
}

Exporting RDLC to .docx file

I need the C# code to export the rdlc file to .docx. I have tried out the following code.But it does not work. Please help me with proper code.Thanks in advance
RvQpTemplate.LocalReport.SetParameters(new ReportParameter[] {
regulation, ExamName, SubjectName, SubjectCode,common });
var report = new LocalReport();
report.SetBasePermissionsForSandboxAppDomain(new PermissionSet(PermissionState.Unrestricted));
RvQpTemplate.LocalReport.DataSources.Add(new Microsoft.Reporting.WebForms.ReportDataSource());
RvQpTemplate.DataBind();
Byte[] mybytes = RvQpTemplate.LocalReport.Render("WORD", null,
out extension, out encoding,
out mimeType, out streams, out warnings);
Response.ClearHeaders();
Response.ClearContent();
Response.Buffer = true;
Response.Clear();
Response.ContentType = contentType;
Response.AddHeader("Content-Disposition", "attachment; filename="test.docx");
Response.BinaryWrite(mybytes);
Response.Flush();
Response.Close();
Response.End();
Use WORDOPENXML instead of WORD when you render the report. Also, this was discussed here:
How do I export directly to a word document in report viewer
public FileResult File(string id, string expedicion, string nombre, string historia)
{
ReportViewer ReportViewer1 = new ReportViewer();
ReportViewer1.ProcessingMode = ProcessingMode.Local;
ReportViewer1.LocalReport.ReportPath =
Server.MapPath("~/Reportes/Plantilla2.rdlc");
ReportViewer1.ShowParameterPrompts = true;
ReportParameter ID = new ReportParameter("ID", id);
ReportParameter EXP = new ReportParameter("Exp", expedicion);
ReportParameter Nombre = new ReportParameter("Nombre", nombre);
ReportParameter Historia = new ReportParameter("Historia", historia);
ReportParameter Sede = new ReportParameter("Sede", usuario.idnom);
ReportViewer1.LocalReport.SetParameters(ID);
ReportViewer1.LocalReport.SetParameters(EXP);
ReportViewer1.LocalReport.SetParameters(Nombre);
ReportViewer1.LocalReport.SetParameters(Historia);
ReportViewer1.LocalReport.SetParameters(Sede);
ReportViewer1.LocalReport.Refresh();
byte[] streamBytes = null;
string mimeType = "";
string encoding = "";
string filenameExtension = "";
string[] streamids = null;
Warning[] warnings = null;
streamBytes = ReportViewer1.LocalReport.Render("WORD", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings);
return File(streamBytes, mimeType, "Report1.doc");
}

How to save file to server without using html fileupload control?

I am using Reportviewer in asp.net mvc and rendering it as a pdf format after converting it into byte.
The code is given below:
public ActionResult PrintPO(string type)
{
LocalReport lr = new LocalReport();
string path = Url.Content(Server.MapPath("~/Report/RepPurchaseOrder.rdlc"));
if (System.IO.File.Exists(path))
{
lr.ReportPath = path;
}
else
{
return Content("Report File Not Found!");
}
ReportDataSource rd = new ReportDataSource("Data", list));
lr.DataSources.Add(rd);
string reportType = type;
string mimeType;
string encoding;
string fileNameExtension;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>" + id + "</OutputFormat>" +
" <PageWidth>10in</PageWidth>" +
" <PageHeight>10in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>1in</MarginLeft>" +
" <MarginRight>1in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
renderedBytes = lr.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
FileContentResult fileResult = File(renderedBytes, mimeType);
return fileResult;
}
I want to save this file to my server location. For example: /Content/PDF/Result1.pdf
I want to make a copy of rendered bytes into file so that I can see preview of it later also.
How can I achieve it? I am not using html FileUpload control.
Please help me.
Thanks.
You can save it using FileStream in server-side.
using (FileStream fileStream = System.IO.File.Create(filePath, renderedBytes.Length)){
fileStream.Write(renderedBytes, 0, renderedBytes.Length);
}
I've added the code to save file in specified file path(/Content/PDF/Result1.pdf) at the end of the method before setting FileContentResult
public ActionResult PrintPO(string type)
{
LocalReport lr = new LocalReport();
string path = Url.Content(Server.MapPath("~/Report/RepPurchaseOrder.rdlc"));
if (System.IO.File.Exists(path))
{
lr.ReportPath = path;
}
else
{
return Content("Report File Not Found!");
}
ReportDataSource rd = new ReportDataSource("Data", list));
lr.DataSources.Add(rd);
string reportType = type;
string mimeType;
string encoding;
string fileNameExtension;
string id="Dynamic ID Will Be Here";
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>" + id + "</OutputFormat>" +
" <PageWidth>10in</PageWidth>" +
" <PageHeight>10in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>1in</MarginLeft>" +
" <MarginRight>1in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
renderedBytes = lr.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
//Saving renderedBytes to File ~/Content/PDF/Result1.pdf
var filesDir = Server.MapPath(#"~/Content/PDF");
if (!Directory.Exists(filesDir)) {
Directory.CreateDirectory(filesDir);
}
var filePath = Path.Combine(filesDir, "Result1.pdf");
using (FileStream fileStream = System.IO.File.Create(filePath, renderedBytes.Length)) {
fileStream.Write(renderedBytes, 0, renderedBytes.Length);
}
FileContentResult fileResult = File(renderedBytes, mimeType);
return fileResult;
}

Categories

Resources