Crystal Report direct saving as PDF, instead of viewing - asp.net

I want to make a report from ASP.Net, in Crystal Report. I want, when user click on print, it should simply show a browser dialog of Save,Open,Save as, and PDF should be saved, or Crystal Report print preview should appear, I don't want to display report first in Viewer then click on button to get print or PDF, I want simply from clicking on asp button, I have all the idea of parameters and know how to make report, my question is just to not to show viewer and take report from asp button in a form of PDF or print preview dialog to print. I have used the Export method of .Net for Crystal Report, but it does not work.

You can generate a PDF by Using a Crystal Report and piece of code....
First: Generate a Crystal Report as per your requirements.
Second: Use the below code to generate the PDF:
Place the following name spaces at the top of the code page
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Variable Declaration
Dim CrReport As New CrystalReport1() // Report Name
Dim CrExportOptions As ExportOptions
Dim CrDiskFileDestinationOptions As New DiskFileDestinationOptions()
Dim CrFormatTypeOptions as New PdfRtfWordFormatOptions()
Set the destination path and file name
CrDiskFileDestinationOptions.DiskFileName = "c:\RichText.pdf"
Specify a page range (optional)
crFormatTypeOptions.FirstPageNumber = 1 // Start Page in the Report
crFormatTypeOptions.LastPageNumber = 3 // End Page in the Report
crFormatTypeOptions.UsePageRange = True
Set export options
CrExportOptions = crReport.ExportOptions
With CrExportOptions
// Set the destination to a disk file
.ExportDestinationType = ExportDestinationType.DiskFile
// Set the format to PDF
.ExportFormatType = ExportFormatType.PortableDocFormat
// Set the destination options to DiskFileDestinationOptions object
.DestinationOptions = CrDiskFileDestinationOptions
.FormatOptions = crFormatTypeOptions
End With
Trap any errors that occur on export
Try
// Export the report
CrReport.Export()
Catch err As Exception
MessageBox.Show(err.ToString())
End Try
Thats it.... Now you are ready to create a PDF of the Report.

Here is the solution you are looking for:
http://www.c-sharpcorner.com/UploadFile/mahesh/ExportCRtoPDF10062006161918PM/ExportCRtoPDF.aspx
Here is the quote from the site:
The following steps will guide you to achieve the same:
Add crystal report (.cr) file to your ASP.NET application.
Add a report instance on the page level.
Dim report As MyReport = New MyReport
Populate reports data on Page_Init
Dim ds As DataSet = GetData()
report.SetDataSource(ds)
Export Report
report.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, False, "ExportedReport")
If you wish to format report to other formats, just change the ExportFormatType enumeration value to > your desired format.
If you wish to download the report, then you simply change the third parameter of >ExportToHttpResponse method in Step 4 to True.

Related

how to call page which creates pdf

I have a page called OrderExport.aspx which creates a pdf file in a folder on the server.
In my page OrderSend.aspx I have a function which sends an e-mail with the pdf file attached, like this:
Dim atc As Net.Mail.Attachment = New Attachment(stm, fileNameOrder)
mail.Attachments.Add(atc)
How can I call OrderExport.aspx from this function before sending the e-mail without showing it for the user?
I need to make sure that the pdf file exists when sending the e-mail.
You probably want to create a class rather than an aspx page to handle the PDF creation. One way to do this is to use the PDFSharp library which can handle creating the PDF document and then saving it to a stream which can be attach to an email message. You could also save the stream to a file on the server at the same time.
' Create a new PDF document
Dim document As PdfDocument = New PdfDocument
document.Info.Title = "TITLE"
Dim securitySettings As Security.PdfSecuritySettings = document.SecuritySettings
' Restrict some rights.
securitySettings.PermitAccessibilityExtractContent = False
securitySettings.PermitAnnotations = False
securitySettings.PermitAssembleDocument = False
securitySettings.PermitExtractContent = False
securitySettings.PermitFullQualityPrint = True
securitySettings.PermitModifyDocument = False
securitySettings.PermitPrint = True
' Create an empty page
Dim page As PdfPage = document.AddPage
' Get an XGraphics object for drawing
Dim gfx As XGraphics = XGraphics.FromPdfPage(page)
Dim img As XImage = XImage.FromGdiPlusImage(imgPermit)
gfx.DrawImage(img, 20, 20)
Dim stream As New MemoryStream()
document.Save(stream, False)
Dim xStream As System.IO.Stream = stream
SendEmail(sEmail, xStream)
in your mail message it would be constructed similar to this
Dim xStream As New Attachment(pdf, "FILE" + Date.Now.ToString("MM.dd.yyyy") + ".pdf")
mm.Attachments.Add(xStream)
You need to separate the GUI from the actual logic.
You presumably have code in OrderExport.aspx that creates the PDF and saves it to disk. You should put that code into a separate class, so that you can call it from OrderExport.aspx, and from the page with the "Send e-mail" button. Similarly, extract the code for sending the email from OrderSend.aspx and call it from there, and from the "Send e-mail" button.
Separation of Concerns is the best solution, but if you need a quick solution -not a good one- make the class and the function public and call it like any other class

Crystal Reports- Export report causing "Missing Parameter Values"

I am trying to export a report but everytime it runs the code to export the crystal report in the crystalreportviewer I get an error message saying "Missing Parameter Values". I've looked through many sources but havent found a solution. I do know that all parameters are filled in because without the export code, the site runs perfectly fine.
Export code
Try
Dim CrExportOptions As CrystalDecisions.Shared.ExportOptions
Dim CrDiskFileDestinationOptions As New _
CrystalDecisions.Shared.DiskFileDestinationOptions()
Dim CrFormatTypeOptions As New CrystalDecisions.Shared.PdfRtfWordFormatOptions()
CrDiskFileDestinationOptions.DiskFileName = _
"c:\crystalExport.pdf"
CrExportOptions = oRpt.ExportOptions
With CrExportOptions
.ExportDestinationType = CrystalDecisions.Shared.ExportDestinationType.DiskFile
.ExportFormatType = CrystalDecisions.Shared.ExportFormatType.PortableDocFormat
.DestinationOptions = CrDiskFileDestinationOptions
.FormatOptions = CrFormatTypeOptions
End With
oRpt.Export()
Catch ex As Exception
Response.Write(ex.ToString)
End Try
Also:
'Try
' oRpt.ExportToHttpResponse([Shared].ExportFormatType.PortableDocFormat, Response, True, "ExportedReport")
'Catch ex As Exception
' Response.Write(ex.ToString)
'End Try
Any help would be great.
This is caused under 2 reasons.
Either, you're not passing(from the program) a required parameter which you have created in the report.
Or, you're passing a parameter to the report but you haven't created it in the report.
To solve my own problem I found that the code actually exports the instance of the crystal report, whereas I was putting the parameters into the crystalreportviewer after providing the source. Instead I provided the parameters directly into the instance which gets pushed into the crystalreportviewer as a datasource.
:)
In my case, there was a subreport that was not correctly linked with the main report.
Check if all the parameters of the subreport is linked with the main report.
Cheers;
Have to set required parameters
Set rpt.SetDataSource(dt) even DataTable records count is 0:
DataTable dt = new DataTable();
dt.Load(data);
if (dt?.Rows != null)
{
rpt.SetDataSource(dt);
return true;
}

Load RDL report into Web Report Viewer

I am trying to load an (.rdl) report file into a web report viewer control (visual studio 2010 control):
//Get the data and
.
.
//Add it to report
ReportViewer.LocalReport.DataSources.Add(new ReportDataSource(element.Name, dt));
//Pass the report to the viewer
using (FileStream stream = new FileStream(ReportDocument.FileName, FileMode.Open))
{
this.ReportViewer.LocalReport.LoadReportDefinition(stream);
}
Am I missing a line of code somewhere? I used the equivalent for the winforms report viewer with the addition of RefreshReport() - however there is no equivalent method that I could find for web report viewers). The page remains blank - what am I missing?
There is a .Refresh() method, and that is what you are missing. Here's what I'm using (in VB):
ReportViewer1.Reset()
ReportViewer1.LocalReport.Dispose()
ReportViewer1.LocalReport.DataSources.Clear()
ReportViewer1.LocalReport.ReportPath = Server.MapPath("/reports/" & ReportFile)
ReportViewer1.LocalReport.DataSources.Add(New ReportDataSource(<datasource>))
ReportViewer1.LocalReport.Refresh()

How to set crystal report's textbox value at run time?

How to set crystal report's textbox value at run time. I have a textbox in section2 (page header) in crystal report, now I have to set Text property of this textbox at run time. Basically I have to pass user name in this textbox.
You can change textbox text in runtime. You can use this:
using CrystalDecisions.CrystalReports.Engine;
rptMyReport report = new rptMyReport();
TextObject to = (TextObject)report.ReportDefinition.Sections["Section2"].ReportObjects["textboxname"];
to.Text = newvalue;
The another way is to use parameters.
If you have the user name before the report opens you can add a parameter field (string) to the report and then put that field on the report where you want it to appear at runtime. You will just need to pass it into the report as a parameter just like you would any other parameter.
Dim UserName As String = "BukHix"
crDOC.SetParameterValue("UserName", UserName)
try this
((TextObject)rpt.Section2.ReportObjects["Textbox"]).Text = "yourvalue";

Crystal Report print functionlity doesn't work after deployment?

I'm using crystal reports to build reports, everything is ok while development.
But after deployment of website, print functionality doesn't work.
I use _rptDocument.PrintToPrinter(1, false, 0, 0); to print report.
I've tried two methods to deploy website
Normal Publish option.
Web Deployment Project.
But I got the same output, print functionality doesn't work.
Also, I tried to set default printer, this also doesn't work.
Any ideas?
Printing on a web server isn`t a good idea. What should happen? A user prints on your servers printer? Use CR to create PDFs. Stream them to your clients. They can use their local printers.
try this :- Create PDF and open Browser Tab ...enter code here
string fname = "Report" + ".pdf";`enter code here`
//Create instance for crystal report Export option class
ExportOptions exprtopt = default(ExportOptions);
//create instance for destination option - This one is used to set path of your pdf file save
DiskFileDestinationOptions destiopt = new DiskFileDestinationOptions();
//Bind data in the crystal report first before export cystal report to PDF
ReportDocument RptDoc = new ReportDocument();
//Map your crystal report path
// RD.Load(Server.MapPath("~/CrystalReport2.rpt"));
//Set your crystal report datasource as dt
//Get path and assign into destination DiskFileName
destiopt.DiskFileName = Server.MapPath(fname);
exprtopt = RD.ExportOptions;
exprtopt.ExportDestinationType = ExportDestinationType.DiskFile;
//use PortableDocFormat for PDF data
exprtopt.ExportFormatType = ExportFormatType.PortableDocFormat;
exprtopt.DestinationOptions = destiopt;
//finally export your report document
RD.Export();
//To open your PDF after save it from crystal report
string Path = Server.MapPath(fname);
//create instance to client to open your pdf
WebClient client = new WebClient();
//Assign path to download pdf
Byte[] buffer = client.DownloadData(Path);
//metion content type as PDF and write
// Response.ContentType = "application/pdf";
//Response.AddHeader("content-length", buffer.Length.ToString());
//Response.BinaryWrite(buffer);
//======================================
Response.Write("<script>");
Response.Write("window.open('" + fname + "', '_newtab');");
Response.Write("</script>");
//===================================
IMTIYAZ

Resources