please describe How to add picture at run time in the crystal report using C#
private void LoadImage(DataRow objDataRow,
string strImageField, string FilePath)
{
FileStream fs = new FileStream(FilePath,
System.IO.FileMode.Open, System.IO.FileAccess.Read);
}
use crystalrepoert.setdatasource(datatable) to load pictures in crystal report file, the image column of datatable apeears in report.
also you can you use runtime dataset like this:
http://www.c-sharpcorner.com/UploadFile/saj/CrystalReports03192006090510AM/CrystalReports.aspx
Related
We are reading the adobe form template using ABCpdf , populating form fields with values retrieved from database and amending them into a single PDF document and sending the document back as File stream in the HTTP response to the users in a ASP.net MVC App.
This approach is working fine and PDF documents are getting generated successfully. But when the user choose to open the generated PDF file and try to close it, they are being prompted ‘Do you want to save changes to xxx.pdf before closing’ dialog from Adobe Acrobat. Is there any way of suppressing this message using ABC pdf?.
Following is the code we are using to generate the PDF.
public byte[] GeneratePDF(Employee employee, String TemplatePath)
{
string[] FieldNames;
Doc theDoc;
MemoryStream MSgeneratedPDFFile = new MemoryStream();
//Get the PDF Template and read all the form fields inside the template
theDoc = new Doc();
theDoc.Read(HttpContext.Current.Server.MapPath(TemplatePath));
FieldNames = theDoc.Form.GetFieldNames();
//Navigate through each Form field and populate employee details
foreach (string FieldName in FieldNames)
{
Field theField = theDoc.Form[FieldName];
switch (FieldName)
{
case "Your_First_Name":
theField.Value = employee.FirstName;
break;
default:
theField.Value = theField.Name;
break;
}
//Remove Form Fields and replace them with text
theField.Focus();
theDoc.Color.String = "240 240 255";
theDoc.FillRect();
theDoc.Rect.Height = 12;
theDoc.Color.String = "220 0 0";
theDoc.AddText(theField.Value);
theDoc.Delete(theField.ID);
}
return theDoc.GetData();
}
Today I ran into this problem too, but with a PDF with no form fields. I ran #CharlieNoTomatoes code and confirmed the FieldNames collection was definitely empty.
I stepped through the various stages of my code and found that if I saved the PDF to the file system and opened from there it was fine. Which narrowed it down to the code that took the abcpdf data stream and sent it directly to the user (I normally don't bother actually saving to disk). Found this in the WebSuperGoo docs and it suggested my server might be sending some extra rubbish in the Response causing the file to be corrupted.
Adding Response.End(); did the trick for me. The resulting PDF files no longer displayed the message.
byte[] theData = _thisPdf.Doc.GetData();
var curr = HttpContext.Current;
curr.Response.Clear();
curr.Response.ContentType = "application/pdf";
curr.Response.AddHeader("Content-Disposition", "attachment; filename=blah.pdf");
curr.Response.Charset = "UTF-8";
curr.Response.AddHeader("content-length", theData.Length.ToString());
curr.Response.BinaryWrite(theData);
curr.Response.End();
I ran into this problem, as well. I found a hint about "appearance streams" here:
The PDF contains form fields and the NeedAppearances entry in the interactive form dictionary is set to true. This means that the conforming PDF reader will generate an appearance stream where necessary for form fields in the PDF and as a result the Save button is enabled. If the NeedAppearances entry is set to false then the conforming PDF reader should not generate any new appearance streams. More information about appearance streams in PDF files and how to control them with Debenu Quick PDF Library.
So, I looked for "appearance" things in the websupergoo doc and was able to set some form properties and call a field method to get rid of the "Save changes" message. In the code sample above, it would look like this:
Edit: After exchanging emails with fast-and-helpful WebSuperGoo support about the same message after creating a PDF with AddImageHtml that WASN'T fixed by just setting the form NeedAppearances flag, I added the lines about Catalog and Atom to remove the core document NeedAppearances flag that gets set during AddImageHtml.
public byte[] GeneratePDF(Employee employee, String TemplatePath)
{
string[] FieldNames;
Doc theDoc;
MemoryStream MSgeneratedPDFFile = new MemoryStream();
//Get the PDF Template and read all the form fields inside the template
theDoc = new Doc();
theDoc.Read(HttpContext.Current.Server.MapPath(TemplatePath));
FieldNames = theDoc.Form.GetFieldNames();
//Tell PDF viewer to not create its own appearances
theDoc.Form.NeedAppearances = false;
//Generate appearances when needed
theDoc.Form.GenerateAppearances = true;
//Navigate through each Form field and populate employee details
foreach (string FieldName in FieldNames)
{
Field theField = theDoc.Form[FieldName];
switch (FieldName)
{
case "Your_First_Name":
theField.Value = employee.FirstName;
break;
default:
theField.Value = theField.Name;
break;
}
//Update the appearance for the field
theField.UpdateAppearance();
//Remove Form Fields and replace them with text
theField.Focus();
theDoc.Color.String = "240 240 255";
theDoc.FillRect();
theDoc.Rect.Height = 12;
theDoc.Color.String = "220 0 0";
theDoc.AddText(theField.Value);
theDoc.Delete(theField.ID);
}
Catalog cat = theDoc.ObjectSoup.Catalog;
Atom.RemoveItem(cat.Resolve(Atom.GetItem(cat.Atom, "AcroForm")), "NeedAppearances");
return theDoc.GetData();
}
I'm starting using DevExpress XtraReports for the company project. My problem is the following:
I have a stored procedure that extracts the data, given three paramaters: startDay, endDay and developer ID, and this SP is inside a .dbml file.
Following this example http://www.devexpress.com/Support/Center/p/B223095.aspx, we have the this method:
static void report_DataSourceDemanded(object sender, System.EventArgs e)
{
Reports.WeeklyTimesheet report = (Reports.WeeklyTimesheet)sender;
DataClasses1DataContext context = new DataClasses1DataContext();
System.Data.Linq.ISingleResult<WeeklyTimesheetUserReportResult> res = >context.WeeklyTimesheetUserReport(Convert.ToDateTime("2012/01/16"), >Convert.ToDateTime("2012/01/20"), 52);
var result = from orderDetail in res select orderDetail;
report.DataSource = res.ToList();
}
Which is the only way i've found (that works) to pass parameters to the SP for the report.
What can i do so the report comes with the data i am sucessfully bringing but is not binding into the report? The attached images will illustrate this point better.
I have to point that when i made that report in the images, were originally formatted from a dataset using the wizard (hence why is ordered), but i have no idea how i can format it instead using the .dbml file.
Thanks in advance.
http://imgur.com/YQ7RE
XtraReport have xrTables, xrLabel controls, they will let you to create custom report and after that you can bind those cell etc and modify the XRControl bindings of the report in the following manner:
[C#]
...
// Original
//this.xrTableCell14.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
// new DevExpress.XtraReports.UI.XRBinding("Text", null, "Symbols.Description")});
// Modified
this.xrTableCell14.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "Description")});
...
Refer these links and samples..
Binding a Report to an Entity Framework object at runtime
[ How to
use LINQ to SQL data source to create a Master-Detail report
example
Is there a way to decrease the margin of the PDF reports using the BIRT API?
I tried setting the PDF rendering options to:
PDFRenderOption renderOption = new PDFRenderOption();
renderOption.setOutputFormat(PDFRenderOption.OUTPUT_FORMAT_PDF);
renderOption.setOption(IPDFRenderOption.PDF_HYPHENATION, true);
renderOption.setOption(IPDFRenderOption.PDF_TEXT_WRAPPING, true);
renderOption.setOption(IPDFRenderOption.PAGE_OVERFLOW,
IPDFRenderOption.ENLARGE_PAGE_SIZE);
Basically the problem I have is that if I have a longer text in a column (from one of the tables) it will get it on the next line, but if I set the IPDFRenderOption.PDF_HYPHENATION to false I will get the text split right in the middle of the text (see below).
PDF with IPDFRenderOption.PDF_HYPHENATION set to true
PDF with IPDFRenderOption.PDF_HYPHENATION set to false
So, I was trying to set the margin of the PDF to be smaller to overcome this issue, but I don't find any documentation on how to do this with the BIRT API...
There is this suggestion of modifying the master page, but I have way too many reports to modify them by hand.
How should I approach the problem? Is this even possible using the BIRT API?
All I needed to do was to loop through all the handles, test which of them is a MasterPageHandle and call setProperty with these keys:
MasterPageHandle.BOTTOM_MARGIN_PROP
MasterPageHandle.LEFT_MARGIN_PROP
MasterPageHandle.RIGHT_MARGIN_PROP
MasterPageHandle.TOP_MARGIN_PROP
and the DimensionValue I needed.
Code sample
#SuppressWarnings("unchecked")
private void shrinkPageSizeForExport(IReportRunnable reportRunnable) {
DesignElementHandle designHandle = reportRunnable.getDesignHandle();
IElementDefn elementDefn = designHandle.getDefn();
for (int i = 0; i < elementDefn.getSlotCount(); i++) {
SlotHandle slotHandle = designHandle.getSlot(i);
for (DesignElementHandle elementHandle: (List<DesignElementHandle>)slotHandle.getContents()) {
if (!(elementHandle instanceof MasterPageHandle)) continue;
MasterPageHandle mph = (MasterPageHandle)elementHandle;
DimensionValue dv = new DimensionValue(0.1, "cm");
setAllMarginsTo(mph, dv);
}
}
}
private void setAllMarginsTo(MasterPageHandle mph, DimensionValue dv) {
try {
mph.setProperty(MasterPageHandle.BOTTOM_MARGIN_PROP, dv);
mph.setProperty(MasterPageHandle.LEFT_MARGIN_PROP, dv);
mph.setProperty(MasterPageHandle.RIGHT_MARGIN_PROP, dv);
mph.setProperty(MasterPageHandle.TOP_MARGIN_PROP, dv);
} catch (SemanticException se) {
throw new RuntimeException("Cannot set margins for report export!", se);
}
}
Alternate suggestion:
Build a MasterPage in your BIRT library, and use it on all reports. Then all reports it is used on can be updated at one time. If you did not start with library MasterPages, you can replace the report MasterPage with the library master page, quicker then trying to recode them all.
Things like DataSources, and MasterPages are almost always better as library items.
I had created many reports with VS 2008. Now starting with VS 2010 for new requirement. Please note I am using .rdlc report
I could add subreport control to the report but could not select the available reports. There is no browse button or a dropdown to choose the available .rdlc report.
When I manually type the report name, the reportviewer doesnt show up any subreport. I dont see any error message on the 'Output' window either.
How do I use subreport with VS 2010? Am I missing anything? Any help is appreciated.
I have SQL 2005/2008 (report services installed), VS 2008, VS 2010 installed on the same PC.
First select sub report from Toolbox and put where you want to show.See the image bellow
Now right click on sub report properties and type your sub report name .
Now You have to create a sub report even handler in your .cs file from where you load your report like that:
public Ctor()
{
string path = HttpContext.Current.Server.MapPath("Your Report path");
ReportViewer1.Reset(); //important
ReportViewer1.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Local;
ReportViewer1.LocalReport.SubreportProcessing += Process_Subreport;
LocalReport objReport = ReportViewer1.LocalReport;
objReport.ReportPath = path;
// Add Parameter If you need
List<ReportParameter> parameters = new List<ReportParameter>();
parameters.Add(new ReportParameter("Name", Value));
ReportViewer1.LocalReport.SetParameters(parameters);
ReportViewer1.ShowParameterPrompts = false;
ReportViewer1.ShowPromptAreaButton = false;
ReportViewer1.LocalReport.Refresh();
//Add Datasourdce
ReportDataSource reportDataSource = new ReportDataSource();
reportDataSource.Name = "Datasource Name Used due to report design";
reportDataSource.Value = DataSourceValue;
objReport.DataSources.Add(reportDataSource);
objReport.Refresh();
}
Now Create Even Handler Method to load sub report details.
private void Process_Subreport(object sender, SubreportProcessingEventArgs e)
{
//You can get parameter from main report
int paramname = int.Parse(e.Parameters[0].Values[0].ToString());
//You can also add parameter in sub report if you need like main report
//Now add sub report data source
e.DataSources.Add(new ReportDataSource("DataSource Name",DataSourceValue)));
}
I think it will be works for you.Thank you.
I am using Sap Crystal Report in asp.net 2010
It will shows the error no valid report source id available, when i refreshing the report or moving to next page at run time using report viewer tools
and this is my coding,
Dim crdoc5 As New ReportDocument()
Dim crtablogoninfo5 As New TableLogOnInfo
Dim crtabs5 As Tables
If Not IsPostBack Then
crdoc5.Load(Server.MapPath("CrStaffrecruit.rpt"))
Session.Add("CrStaffrecruit", crdoc5)
CrystalReportViewer5.ReportSource = crdoc5
Else
CrystalReportViewer5.ReportSource = Session("CrStaffrecruit")
End If
crdoc5.Load(Server.MapPath("CrStaffrecruit.rpt"))
Dim crconninfo5 As New ConnectionInfo()
rconninfo5.ServerName = "servername"
crconninfo5.DatabaseName = "databasename"
crconninfo5.UserID = "sa"
crconninfo5.Password = ""
crtabs5 = crdoc5.Database.Tables()
For Each crtab5 As CrystalDecisions.CrystalReports.Engine.Table In crtabs5
crtablogoninfo5 = crtab5.LogOnInfo
crtablogoninfo5.ConnectionInfo = crconninfo5
crtab5.ApplyLogOnInfo(crtablogoninfo5)
Next
CrystalReportViewer5.ReportSource = crdoc5
CrystalReportViewer5.RefreshReport()
If any one know pls help me...
Thanks in advance
For this please go through the following link
http://forums.sdn.sap.com/thread.jspa?messageID=10951477�
Although the following code is in C#, it shouldn't be too difficult to translate it to VB and it should solve your issue:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
//whatever you do when the page is loaded for the first time
//this could even be bindReport();
}
else
{
bindReport();
}
}
public void bindReport()
{
ReportDocument rptDoc = new ReportDocument();
dsSample ds = new dsSample(); // .xsd file name
DataTable dt = new DataTable();
// Just set the name of data table
dt.TableName = "Crystal Report Example";
dt = getMostDialledNumbers(); //This function populates the DataTable
ds.Tables[0].Merge(dt, true, MissingSchemaAction.Ignore);
// Your .rpt file path will be below
rptDoc.Load(Server.MapPath("yourReportFilePath.rpt"));
//set dataset to the report viewer.
rptDoc.SetDataSource(ds);
CrystalReportViewer1.ReportSource = rptDoc;
CrystalReportViewer1.RefreshReport();
//in case you have an UpdatePanel in your page, it needs to be updated
UpdatePanel1.Update();
}
I was experiencing the same problem. In what event are you executing the code you posted? I ask because after much debugging, I discovered that you need to place the code in Page_Load (as opposed to PreRender like I was doing previously...)
Hope this helps.
I have got this problem several times, and the solution is to save the Report Document variable in a session then in the Page_load put the below code:
if (IsPostBack)
{
if (Session["reportDocument"] != null)
{
ReportDocument cr = new ReportDocument();
cr = (ReportDocument)Session["reportDocument"];
CrystalReportViewer1.ReportSource = cr;
CrystalReportViewer1.DataBind();
}
}
NB:
Don't forget to fill the (Session["reportDocument"]) with the Display button.
Go through following link. I resolved same issue with that solution.
http://www.aspsnippets.com/Articles/ASPNet-Crystal-Reports-13-Visual-Studio-2010-CrystalReportViewer-Search-Button-Issue---No-valid-report-source-is-available.aspx