Stimulsoft fields with the same data - c#

I´m making a program to generate the report through code.
First I go through the datagrid to remove the empty columns and the result of this operation is sent to the class to generate the report.
DataTable dt = new DataTable();
dt = DgvNomina.DataSource as DataTable;
foreach (DataRow r in dt.Rows)
{
for(int i = dt.Columns.Count - 1; i >= 0; i--)
{
if (r[dt.Columns[i]].ToString() == string.Empty)
{
dt.Columns.RemoveAt(i);
}
}
}
Imprimir_Nomina(dt);//clase para generar reporte
Then I use this code to make the report.
The code comes on the page, I just adapt it to my needs.
private void Imprimir_Nomina(DataTable table)
{
try
{
SplashScreenManager.ShowDefaultWaitForm("Cargando Reporte...", "Por Favor Espere.");
Reportes rep = new Reportes() { Nombre = "Reporte Nómina" }.GetbyName();//cargarmos el reporte
StiReport report = new StiReport();
report.LoadFromString(rep.Fichero);
report.ReportName = rep.Nombre;
DataView dv = new DataView(table);
report.ScriptLanguage = StiReportLanguageType.CSharp;
//añadimos los datos y variables
report.RegData("GalaxySoft", dv);
report.Dictionary.Variables.Add(new StiVariable("Titulo", ElcbDepartamentos.Text));
report.Dictionary.Variables.Add(new StiVariable("FechaInicio", "De " + FI.ToLongDateString()));
report.Dictionary.Variables.Add(new StiVariable("FechaFin", " A " + FF.ToLongDateString()));
report.Dictionary.Synchronize();
//establecemos la configuración de la hoja del reporte
StiPage page = report.Pages.Items[0];
page.PaperSize = PaperKind.Legal;
page.Orientation = StiPageOrientation.Landscape;
//creamos la banda de encabezado
StiHeaderBand header = new StiHeaderBand();
header.Height = 0.8f;
header.Name = "Encabezado";
page.Components.Add(header);
//creamos el databand
StiDataBand data = new StiDataBand();
data.DataSourceName = "Nomina" + dv.Table.TableName;
data.Height = 0.5f;
data.Name = "Contenido";
page.Components.Add(data);
//creamos los textos de la tabla
Double pos = 0;
Double colW = 0;
int nameIndex = 1;
StiText headerText;
StiText dataText;
StiCondition condition;
foreach (DataColumn col in dv.Table.Columns)
{
switch (col.Caption)
{
case "ID":
//texto de encabezado
headerText = new StiText(new RectangleD(pos, 0, colW = 2, 0.5f));
headerText.Font = new Font("Arial", 8, FontStyle.Bold);
headerText.HorAlignment = StiTextHorAlignment.Center;
headerText.VertAlignment = StiVertAlignment.Center;
headerText.WordWrap = true;
headerText.Text.Value = col.Caption;
headerText.Name = "HeaderText" + nameIndex.ToString();
headerText.Brush = new StiSolidBrush(Color.LightGray);
headerText.Height = 0.8;
headerText.Border.Side = StiBorderSides.Bottom;
header.Components.Add(headerText);
//texto fila
dataText = new StiText(new RectangleD(pos, 0, colW = 2, 0.5f));
dataText.Font = new Font("Arial", 8);
dataText.HorAlignment = StiTextHorAlignment.Center;
dataText.VertAlignment = StiVertAlignment.Center;
dataText.Text.Value = "{view" + dv.Table.TableName + "." + Stimulsoft.Report.CodeDom.StiCodeDomSerializator.ReplaceSymbols(col.ColumnName) + "}";
dataText.Name = "DataText" + nameIndex.ToString();
dataText.Border.Side = StiBorderSides.Top;
dataText.Border.Side = StiBorderSides.Bottom;
//añadir resaltado
condition = new StiCondition();
condition.BackColor = Color.LightBlue;
condition.TextColor = Color.Black;
condition.Expression = "(Line & 1 == 1";
condition.Item = StiFilterItem.Expression;
dataText.Conditions.Add(condition);
data.Components.Add(dataText);
break;
case "Empleado":
//texto de encabezado
headerText = new StiText(new RectangleD(pos, 0, colW = 5, 0.5f));
headerText.Font = new Font("Arial", 8, FontStyle.Bold);
headerText.HorAlignment = StiTextHorAlignment.Center;
headerText.VertAlignment = StiVertAlignment.Center;
headerText.WordWrap = true;
headerText.Text.Value = col.Caption;
headerText.Name = "HeaderText" + nameIndex.ToString();
headerText.Brush = new StiSolidBrush(Color.LightGray);
headerText.Height = 0.8;
headerText.Border.Side = StiBorderSides.Bottom;
header.Components.Add(headerText);
//Texto de fila
dataText = new StiText(new RectangleD(pos, 0, colW = 5, 0.5f));
dataText.Font = new Font("Arial", 8);
dataText.HorAlignment = StiTextHorAlignment.Center;
dataText.VertAlignment = StiVertAlignment.Center;
dataText.Text.Value = "{view" + dv.Table.TableName + "." + Stimulsoft.Report.CodeDom.StiCodeDomSerializator.ReplaceSymbols(col.ColumnName) + "}";
dataText.Name = "DataText" + nameIndex.ToString();
dataText.Border.Side = StiBorderSides.Top;
dataText.Border.Side = StiBorderSides.Bottom;
//añadir resaltado
condition = new StiCondition();
condition.BackColor = Color.LightBlue;
condition.TextColor = Color.Black;
condition.Expression = "(Line & 1 == 1";
condition.Item = StiFilterItem.Expression;
dataText.Conditions.Add(condition);
data.Components.Add(dataText);
break;
case "Sueldo Base":
//texto de encabezado
headerText = new StiText(new RectangleD(pos, 0, colW = 2.5, 0.5f));
headerText.Font = new Font("Arial", 8, FontStyle.Bold);
headerText.HorAlignment = StiTextHorAlignment.Center;
headerText.VertAlignment = StiVertAlignment.Center;
headerText.WordWrap = true;
headerText.Text.Value = col.Caption;
headerText.Name = "HeaderText" + nameIndex.ToString();
headerText.Brush = new StiSolidBrush(Color.LightGray);
headerText.Height = 0.8;
headerText.Border.Side = StiBorderSides.Bottom;
header.Components.Add(headerText);
//texto de fila
dataText = new StiText(new RectangleD(pos, 0, colW = 2.5, 0.5f));
dataText.Font = new Font("Arial", 8);
dataText.HorAlignment = StiTextHorAlignment.Center;
dataText.VertAlignment = StiVertAlignment.Center;
dataText.Text.Value = "{view" + dv.Table.TableName + "." + Stimulsoft.Report.CodeDom.StiCodeDomSerializator.ReplaceSymbols(col.ColumnName) + "}";
dataText.Name = "DataText" + nameIndex.ToString();
dataText.Border.Side = StiBorderSides.Top;
dataText.Border.Side = StiBorderSides.Bottom;
//añadir resaltado
condition = new StiCondition();
condition.BackColor = Color.LightBlue;
condition.TextColor = Color.Black;
condition.Expression = "(Line & 1 == 1";
condition.Item = StiFilterItem.Expression;
dataText.Conditions.Add(condition);
data.Components.Add(dataText);
break;
default:
//texto de encabezado
headerText = new StiText(new RectangleD(pos, 0, colW = 2, 0.5f));
headerText.Font = new Font("Arial", 8, FontStyle.Bold);
headerText.HorAlignment = StiTextHorAlignment.Center;
headerText.VertAlignment = StiVertAlignment.Center;
headerText.WordWrap = true;
headerText.Text.Value = col.Caption;
headerText.Name = "HeaderText" + nameIndex.ToString();
headerText.Brush = new StiSolidBrush(Color.LightGray);
headerText.Height = 0.8;
headerText.Border.Side = StiBorderSides.Bottom;
header.Components.Add(headerText);
//texto fila
dataText = new StiText(new RectangleD(pos, 0, colW = 2, 0.5f));
dataText.Font = new Font("Arial", 8);
dataText.HorAlignment = StiTextHorAlignment.Center;
dataText.VertAlignment = StiVertAlignment.Center;
dataText.Text.Value = "{view" + dv.Table.TableName + "." + Stimulsoft.Report.CodeDom.StiCodeDomSerializator.ReplaceSymbols(col.ColumnName) + "}";
dataText.Name = "DataText" + nameIndex.ToString();
dataText.Border.Side = StiBorderSides.Top;
dataText.Border.Side = StiBorderSides.Bottom;
//añadir resaltado
condition = new StiCondition();
condition.BackColor = Color.LightBlue;
condition.TextColor = Color.Black;
condition.Expression = "(Line & 1 == 1";
condition.Item = StiFilterItem.Expression;
dataText.Conditions.Add(condition);
data.Components.Add(dataText);
break;
}
pos += colW;
nameIndex++;
}
//Creamos el FooterBand
StiFooterBand footer = new StiFooterBand();
footer.Height = 0.5f;
footer.Name = "FooterBand";
page.Components.Add(footer);
//Creamos el texto del FooterBand
StiText textF = new StiText(new RectangleD(0, 0, page.Width, 0.5f));
textF.Text.Value = "Total={Count()}";
textF.HorAlignment = StiTextHorAlignment.Right;
textF.Brush = new StiSolidBrush(Color.LightGray);
footer.Components.Add(textF);
report.Render(false);
report.Show();
SplashScreenManager.CloseDefaultWaitForm();
}
catch (SqlException ex)
{
MessageBox.Show("El reporte seleccionado no existe.\n" + ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
But when it gets to the 'report.Render (false);' part, it gives me the following error:
System.Exception: 'c:\Users\SISTEMAS\AppData\Local\Temp\ia0gbyuy.0.cs(49,53) : error CS0102: The type 'Reports.Report' already contains a definition for 'Text2'c:\Users\SISTEMAS\AppData\Local\Temp\ia0gbyuy.0.cs(271,21) : error CS0111: Type 'Reports.Report' already defines a member called 'Text2__GetValue' with the same parameter types'
I've already searched but haven't found anything about the problem.

use these codes below Instead of your code
StiReport report = new StiReport();
report.Load(Server.MapPath("../*yourfolder*/*mrt_report_name*.mrt"));
report.ReportName = "name your report";
report.Compile();

Related

Customiz (or Create) a table(StiTable) at runtime in C# (.NET4)

I'm working on stimulsoft 2017.2.2 and C# (.NET4).
I have designed a report with footer and header , It is A4 and there is a table in it , based on stimulsofts method(DataGrid) to create a table at runtime I managed to change it to a report which accepts DataTable and everything works just fine on an empty project (.mrt file).
There is a table so i want to customize it there , Call it and customize it at runtime.
The problem is when I want to add this to my own file (.mrt) the table is empty , it only has 1 column and the rows are fine , the whole table is empty but the design is visible.
So I will really appreciate If you could help me to sort this problem out.
My method looks like this :
private void PrintDataTable(string StiTableName, string DataSourceName, DataTable dataTable, StiReport report)
{
DataView dataView = new DataView(dataTable);
report.Compile();
//script lang
report.ScriptLanguage = StiReportLanguageType.CSharp;
// Add data to datastore
report.RegData(DataSourceName, dataView);
// Fill dictionary
report.Dictionary.Synchronize();
//StiPage page = report.Pages.Items[0];
// Create Table
StiTable table = (StiTable)report[StiTableName];
//StiTable table = (StiTable)report.GetComponentByName(StiTableName);
table.DataSourceName = DataSourceName;
table.AutoWidthType = StiTableAutoWidthType.LastColumns;
table.ColumnCount = dataTable.Columns.Count;
table.RowCount = 3;
table.HeaderRowsCount = 1;
table.FooterRowsCount = 1;
//table.Width = page.Width;
//table.Height = page.GridSize * 12;
//table.DataSourceName = DataSourceName;
table.CreateCell();
table.TableStyleFX = new StiTable21StyleFX();
table.TableStyle = Stimulsoft.Report.Components.Table.StiTableStyle.Style59;
int indexHeaderCell = 0;
int indexDataCell = dataTable.Columns.Count;
//int indexDataCell = dataTable.Columns.Count;
foreach (DataColumn column in dataView.Table.Columns)
{
// Set text on header
StiTableCell headerCell = table.Components[indexHeaderCell] as StiTableCell;
headerCell.Text.Value = column.Caption;
headerCell.HorAlignment = StiTextHorAlignment.Center;
headerCell.VertAlignment = StiVertAlignment.Center;
StiTableCell dataCell = table.Components[indexDataCell] as StiTableCell;
dataCell.HorAlignment = StiTextHorAlignment.Center;
headerCell.VertAlignment = StiVertAlignment.Center;
dataCell.Text.Value = "{" + DataSourceName + "." + Stimulsoft.Report.CodeDom.StiCodeDomSerializator.ReplaceSymbols(column.ColumnName) + "}";
dataCell.Border = new StiBorder(StiBorderSides.All, Color.FromArgb(32, 178, 170), 1, StiPenStyle.Dash);
indexHeaderCell++;
indexDataCell++;
}
// Set text on footer
StiTableCell footerCell = table.Components[table.Components.Count - 1] as StiTableCell;
footerCell.Text.Value = "Count - {Count()}";
footerCell.Font = new Font("Arial", 15, FontStyle.Bold);
footerCell.VertAlignment = StiVertAlignment.Center;
footerCell.HorAlignment = StiTextHorAlignment.Center;
}
Thank you.
I'ts been 2 weeks and I even tried other ways like
report.GetComponentByName("Table1");
and still nothing ,
I really need this in short time ,
Will appreiciate your help.
Thank you.
This is a HOTFIX:
private void PrintTableFine(StiReport report ,DataTable dataTable)
{
DataView dataView = new DataView(dataTable);
report.Load(Application.StartupPath + "\\A4 Portrait.mrt");
report.ScriptLanguage = StiReportLanguageType.CSharp;
// Add data to datastore
report.RegData("view", dataView);
// Fill dictionary
report.Dictionary.Synchronize();
StiPage page = report.Pages.Items[0];
// Create Table
StiTable table = new StiTable();
table.Name = "Table1";
table.AutoWidthType = StiTableAutoWidthType.LastColumns;
table.ColumnCount = dataTable.Columns.Count;
table.RowCount = 3;
table.HeaderRowsCount = 1;
table.FooterRowsCount = 1;
table.Width = page.Width;
table.Height = page.GridSize * 12;
table.DataSourceName = "view" + dataView.Table.TableName;
page.Components.Add(table);
table.CreateCell();
table.TableStyleFX = new StiTable21StyleFX();
table.TableStyle = Stimulsoft.Report.Components.Table.StiTableStyle.Style31;
int indexHeaderCell = 0;
int indexDataCell = dataTable.Columns.Count;
foreach (DataColumn column in dataView.Table.Columns)
{
// Set text on header
StiTableCell headerCell = table.Components[indexHeaderCell] as StiTableCell;
headerCell.Text.Value = column.Caption;
headerCell.Font = new Font("IRANSans(FaNum)", 10, FontStyle.Bold);
headerCell.HorAlignment = StiTextHorAlignment.Center;
headerCell.VertAlignment = StiVertAlignment.Center;
headerCell.Border = new StiBorder(StiBorderSides.All, Color.FromArgb(0, 0, 0), 1, StiPenStyle.Dash);
StiTableCell dataCell = table.Components[indexDataCell] as StiTableCell;
dataCell.Text.Value = "{view" + dataView.Table.TableName + "." +
Stimulsoft.Report.CodeDom.StiCodeDomSerializator.ReplaceSymbols(column.ColumnName) + "}";
dataCell.Font = new Font("IRANSans(FaNum)", 10, FontStyle.Regular);
dataCell.HorAlignment = StiTextHorAlignment.Center;
dataCell.VertAlignment = StiVertAlignment.Center;
dataCell.Border = new StiBorder(StiBorderSides.All, Color.FromArgb(0, 0, 0), 1, StiPenStyle.Dash);
indexHeaderCell++;
indexDataCell++;
}
// Set text on footer
StiTableCell footerCell = table.Components[table.Components.Count - 1] as StiTableCell;
//footerCell.Text.Value = "Count - {Count()}";
footerCell.Font = new Font("IRANSans(FaNum)", 10, FontStyle.Regular);
footerCell.VertAlignment = StiVertAlignment.Center;
footerCell.HorAlignment = StiTextHorAlignment.Center;
}
Actually it creates a table.
Please remember , to use it like this :
DataTable dt = new DataTable();
StiReport report = new StiReport();
//Reminder: compiling is after the table
//table:
PrintTableFine(report,dt);
report.Compile();
//adding a variable:
report["Variable"] = "var1ا";
report.Render(false);
report.Show();
Just give it a DataTable and it will create a table with header and footer.
Reminder: the report which your adding this table to SHOULD NOT HAVE A (Sti)TABLE IN IT(in the design).

Facial Recognition Using c# & EMGU CV Accuracy Problem

I have project code to create a face recognition system using EMGUCV. I have trained the database with 2 people. When the webcam detects those people and able to show the name correctly but the problem is the third person whose do not exist in trained database detect by webcam, it will take the nearest face and display the name on it instead of show "Unknown". How can I improve the accuracy? I have tried to change the threshold value but didn't help. What's going wrong?
MCvFont font = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_TRIPLEX, 0.6d, 0.6d);
HaarCascade faceDetected;
Image<Bgr, Byte> Frame;
Capture camera;
Image<Gray, byte> result;
Image<Gray, byte> TrainedFace = null;
Image<Gray, byte> grayFace = null;
List<Image<Gray, byte>> trainingImages = new List<Image<Gray, byte>>();
List<string> labels = new List<string>();
List<string> Users = new List<string>();
EigenObjectRecognizer recognizer;
int Count, NumLabels, t;
string name, names = null;
public Form1()
{
InitializeComponent();
PhotoPers.Image = Properties.Resources.EmptyPiC;
//HaarCascade is for face detection
faceDetected = new HaarCascade("haarcascade_frontalface_default.xml");
try
{
string Labelsinfo = File.ReadAllText(Application.StartupPath + "/Faces/Faces.txt");
string[] Labels = Labelsinfo.Split(',');
NumLabels = Convert.ToInt16(Labels[0]);
Count = NumLabels;
string LoadFaces;
// if (result)
// {
// CvInvoke.cvPutText(Frame, name[result.Labels], new Point(face.X - 2, face.Y - 2),
// FontFace.HersheyComplex, 1.0, new Bgr(Color.Orange).MCvScalar);
// CvInvoke.cvRectangle(Frame, face, new Bgr(Color.Green).MCvScalar, 2);
//}
for (int tf = 1; tf < NumLabels + 1; tf++)
{
LoadFaces = "face" + tf + ".bmp";
trainingImages.Add(new Image<Gray, byte>(Application.StartupPath + "/Faces/" + LoadFaces));
labels.Add(Labels[tf]);
}
}
catch (Exception e)
{
}
}
string imgLocation = " ";
private void button1_Click(object sender, EventArgs e)
{
camera = new Capture();
camera.QueryFrame();
Application.Idle += new EventHandler(FrameProcedure);
}
private void BtnSave_Click(object sender, EventArgs e)
{
byte[] images = null;
FileStream Streem = new FileStream(imgLocation, FileMode.Open, FileAccess.Read);
BinaryReader brs = new BinaryReader(Streem);
images = brs.ReadBytes((int)Streem.Length);
if (txtName.Text == "" || txtLName.Text == " " || txtIDNo.Text == " " || cboDepartment.Text == " ")
{
MessageBox.Show("All fields must be fillup!");
}
else
{
Count = Count + 1;
grayFace = camera.QueryGrayFrame().Resize(320, 240, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
MCvAvgComp[][] DetectedFaces = grayFace.DetectHaarCascade(faceDetected, 1.2, 10, Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(20, 20));
foreach (MCvAvgComp f in DetectedFaces[0])
{
TrainedFace = Frame.Copy(f.rect).Convert<Gray, byte>();
break;
}
TrainedFace = result.Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
trainingImages.Add(TrainedFace);
labels.Add(txtName.Text);
File.WriteAllText(Application.StartupPath + "/Faces/Faces.txt", trainingImages.ToArray().Length.ToString() + ",");
for (int i = 1; i < trainingImages.ToArray().Length + 1; i++)
{
trainingImages.ToArray()[i - 1].Save(Application.StartupPath + "/Faces/face" + i + ".bmp");
File.AppendAllText(Application.StartupPath + "/Faces/Faces.txt", labels.ToArray()[i - 1] + ",");
}
}
mCon.ConOpen();
string SaveStr = "INSERT INTO tblRegister (FirstName, LastName, IDno, Department, Image)" +
"VALUES(#FirstName, #LastName, #IDno, #Department, #Image)";
SqlCommand myCommand = new SqlCommand(SaveStr, mCon.myCon);
myCommand.Parameters.AddWithValue("#FirstName", txtName.Text);
myCommand.Parameters.AddWithValue("#LastName", txtLName.Text);
myCommand.Parameters.AddWithValue("#IDno", txtIDNo.Text);
myCommand.Parameters.AddWithValue("#Department", cboDepartment.Text);
myCommand.Parameters.AddWithValue("#Image", images);
myCommand.ExecuteNonQuery();
mCon.ConClose();
MessageBox.Show("Data has been Save!");
txtName.Text = " ";
txtLName.Text = " ";
txtIDNo.Text = " ";
cboDepartment.Text = " ";
}
private void PhotoPers_Click(object sender, EventArgs e)
{
}
private void FrameProcedure(object sender, EventArgs e)
{
Users.Add("");
Frame = camera.QueryFrame().Resize(500, 300, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
grayFace = Frame.Convert<Gray, Byte>();
MCvAvgComp[][] facesDetectedNow = grayFace.DetectHaarCascade(faceDetected, 1.2, 10, Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(20, 20));
foreach (MCvAvgComp f in facesDetectedNow[0])
{
result = Frame.Copy(f.rect).Convert<Gray, Byte>().Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
Frame.Draw(f.rect, new Bgr(Color.Cyan), 3);
if (trainingImages.ToArray().Length != 0)
{
MCvTermCriteria termCriterias = new MCvTermCriteria(Count, 0.001);
EigenObjectRecognizer recognizer = new EigenObjectRecognizer(trainingImages.ToArray(), labels.ToArray(), 4500, ref termCriterias);
name = recognizer.Recognize(result);
Frame.Draw(string.IsNullOrEmpty(name) ? "UNKNOWN" : name, ref font, new Point(f.rect.X - 2, f.rect.Y - 2), new Bgr(Color.Red));
}
Users.Add("");
}
CameraBox.Image = Frame;
names = "";
Users.Clear();
}
private void TrainImagesFromDir()
{
//string path = Directory.GetCurrentDirectory() + "/Faces/Faces.txt";
//Users.Add("");
//Frame = camera.QueryFrame().Resize(320, 240, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
//grayFace = Frame.Convert<Gray, Byte>();
//MCvAvgComp[][] facesDetectedNow = grayFace.DetectHaarCascade(faceDetected, 1.2, 10, Emgu.CV.CvEnum.HAAR_DETECTION_TYPE.DO_CANNY_PRUNING, new Size(20, 20));
//foreach (MCvAvgComp f in facesDetectedNow[1])
//{
// result = Frame.Copy(f.rect).Convert<Gray, Byte>().Resize(100, 100, Emgu.CV.CvEnum.INTER.CV_INTER_CUBIC);
// Frame.Draw(f.rect, new Bgr(Color.Green), 3);
// if (trainingImages.ToArray().Length != 0)
// {
// MCvTermCriteria termCriterias = new MCvTermCriteria(Count, 0.001);
// EigenObjectRecognizer recognizer = new EigenObjectRecognizer(trainingImages.ToArray(), labels.ToArray(), 1500, ref termCriterias);
// name = recognizer.Recognize(result);
// Frame.Draw(name, ref font, new Point(f.rect.X - 2, f.rect.Y - 2), new Bgr(Color.Red));
}
private void btnUpload_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "png files(*.png)|*.png|jpg files(*.jpg)|*.jpg|All files (*.*)|*.*";
if (dialog.ShowDialog() == DialogResult.OK)
{
imgLocation = dialog.FileName.ToString();
PhotoPers.ImageLocation = imgLocation;
}
}
}

Merge all the PDFs that been generated

I am developing a web application and one of its features is to generate a multiple certificate in a PDF file. There's no problem in generating a pdf but what I want to happen when generating a multiple certificate is to be in one pdf file only. I am just a beginner so I don't have much idea on doing that. Below is my code for generating a certificate. Thanks in advance!
protected void btnPdf_Click(object sender, EventArgs e)
{
string now = DateTime.Now.ToString("MM-dd-yyyy");
foreach (GridViewRow row in TraineeGrid.Rows)
{
CheckBox chk = (CheckBox)row.FindControl("chkSelect");
if (chk.Checked)
{
Label varName = (Label)row.FindControl("lbName");
string name = varName.Text;
Label varCourse = (Label)row.FindControl("lbCourse");
string course = varCourse.Text;
Label varCertNum = (Label)row.FindControl("lbCertNum");
string certNumber = varCertNum.Text;
Label varEndDate = (Label)row.FindControl("lbEndDate");
string endDate = varEndDate.Text;
DateTime date = DateTime.Parse(endDate);
string finalEDate = date.ToString("MMMM dd, yyyy");
Label varStartDate = (Label)row.FindControl("lbStartDate");
string startDate = varStartDate.Text;
DateTime date1 = DateTime.Parse(startDate);
string dateFileName = date1.ToString("MM-dd-yyyy");
string finalSDate = date1.ToString("MMMM dd, yyyy");
var checkedBoxes = TraineeGrid.Controls.OfType<CheckBox>().Count(c => chk.Checked);
try
{
Directory.CreateDirectory("D:\\Intern\\BASSWeb\\Certificates\\"+now+"\\");
string inputCertificate = "D:\\Intern\\BASSWeb\\Certificates\\CertificateLayout.pdf";
string outputCertificate = "D:\\Intern\\BASSWeb\\Certificates\\"+now+"\\"+name+"_" + course + "_"+dateFileName+".pdf";
// open the reader
PdfReader reader = new PdfReader(inputCertificate);
Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document();
// open the writer
FileStream fs = new FileStream(outputCertificate, FileMode.Create, FileAccess.Write);
PdfStamper stamp = new PdfStamper(reader, fs);
PdfContentByte cb = stamp.GetOverContent(1);
var pageSize = reader.GetPageSize(1);
ColumnText ct = new ColumnText(cb);
PdfCopy copy = new PdfCopy(document, fs);
document.Open();
Font font = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 45, iTextSharp.text.Color.BLACK);
ct.SetSimpleColumn(10f, 100f, 600f, 325f);
Paragraph certText = new Paragraph(new Phrase(20, name, font));
ct.AddElement(certText);
ct.Go();
Font font2 = FontFactory.GetFont(FontFactory.HELVETICA_OBLIQUE, 19, iTextSharp.text.Color.GRAY);
ct.SetSimpleColumn(10f, 100f, 600f, 390f);
certText = new Paragraph(new Phrase("This is to certify that ", font2));
ct.AddElement(certText);
ct.Go();
ct.SetSimpleColumn(10f, 100f, 500f, 297f);
certText = new Paragraph(new Phrase("has successfully completed the " + course + " at BASS Philippines RHQ", font2));
ct.AddElement(certText);
ct.Go();
ct.SetSimpleColumn(10f, 100f, 500f, 240f);
certText = new Paragraph(new Phrase("From: " + finalSDate + "", font2));
ct.AddElement(certText);
ct.Go();
ct.SetSimpleColumn(10f, 100f, 500f, 216f);
certText = new Paragraph(new Phrase("To: " + finalEDate + "", font2));
ct.AddElement(certText);
ct.Go();
Font font3 = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10, iTextSharp.text.Color.BLACK);
ct.SetSimpleColumn(10f, 100f, 500f, 192f);
certText = new Paragraph(new Phrase("Certificate Number: " + certNumber + "", font2));
ct.AddElement(certText);
ct.Go();
stamp.Close();
reader.Close();
fs.Close();
Process.Start(outputCertificate);
chk.Checked = false;
}
catch (Exception ex)
{
string errorMessage = "alert(\"ERROR: "+ ex.Message.ToString() +" \");";
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", errorMessage, true);
}
}
}
}

Generating report (invoice) in ASP.NET C#

So I have a gridview with orders filling it. On the side of each row I have set a link button which says "generate invoice". I've defined command name as "GenerateInvoiceCommand" and command argument OrderID so that I can get all the data I need about that order. Now my question is... Is there any way that I can generate a PDF report and once its generated that it automatically starts downloading? Is there any way I can do this without inserting the pdf report first into the database then downloading it?
What other ways are there to generate reports like this?
Any help is appreciated!
Thanks!
I can see there are two ways :
Use Crystal Report to generate PDF, this answer
Write your own code to generate PDFs, my answer
Because you have tagged Crystal Report, you may want to use first but for gaining more control on your report's appearance second option looks better.
you should first use a third party software like crystal-reports or stimulsoft to generate the report's template(myReport.mrt) and then do something like this :
StiReport report = new StiReport();
string path = "~/report/myReport.mrt";
report.Load(Server.MapPath(path));
// register your data to report's template
report.Render();
if (!Directory.Exists(Server.MapPath("~/report/PDF")))
Directory.CreateDirectory(Server.MapPath("~/report/PDF"));
string ReportFileName = Server.MapPath("~/report/PDF/test.pdf");
report.ExportDocument(StiExportFormat.Pdf, ReportFileName);
FileStream file = File.Open(ReportFileName, FileMode.Open);
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=test.pdf");
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/pdf";
file.Close();
Response.WriteFile(ReportFileName);
hope it helps
You can generate a report programmatically using following code in asp.net C#
you should bound your datatable with your data
DataTable dt = GetDataTableFromDGV(AFIs, ArrayTitle, ArrayEnTitle, ArrayOrder, ArrayChecked);
DataView dataView = dt.DefaultView;
report.ScriptLanguage = StiReportLanguageType.CSharp;
report.RegData("view", dataView);
//fill dictionary
report.Dictionary.Synchronize();
StiPage page = report.Pages.Items[0];
if (Landscape)
page.Orientation = StiPageOrientation.Landscape;
else
page.Orientation = StiPageOrientation.Portrait;
//
Double pos = 0;
//Double columnWidth = StiAlignValue.AlignToMinGrid(page.Width / dataView.Table.Columns.Count, 0.1, true);
Double columnWidth = StiAlignValue.AlignToMinGrid(page.Width / dt.Columns.Count, 0.1, true);
int nameIndex = 1;
columnWidth = StiAlignValue.AlignToMinGrid(page.Width / dt.Columns.Count, 0.1, true);
//create ReportTitleBand
StiReportTitleBand rt = new StiReportTitleBand();
rt.Height = 1.5f;
rt.Name = "ReportTitleBand";
StiText st = new StiText(new RectangleD(0, 0, page.Width, 1f));
st.Text.Value = ReportTitle;
st.HorAlignment = StiTextHorAlignment.Center;
st.Name = "TitleText1";
st.Font = new Font(FontName, 16f);
rt.Components.Add(st);
page.Components.Add(rt);
//create HeaderBand
StiHeaderBand headerBand = new StiHeaderBand();
if (chkRotate)
headerBand.Height = 0.9f;
else
headerBand.Height = 0.5f;
headerBand.Name = "HeaderBand";
page.Components.Add(headerBand);
//create Dataaband
StiDataBand dataBand = new StiDataBand();
dataBand.DataSourceName = "view" + dataView.Table.TableName;
dataBand.Height = 0.5f;
dataBand.Name = "DataBand";
dataBand.CanBreak = true;//Added 11 20 2014
page.Components.Add(dataBand);
//create FooterBand
StiFooterBand footerBand = new StiFooterBand();
footerBand.Height = 0.5f;
footerBand.Name = "FooterBand";
footerBand.Border = new StiBorder(StiBorderSides.All, Color.Black, 1, StiPenStyle.Solid);
footerBand.PrintOnAllPages = true;
page.Components.Add(footerBand);
pos = (page.Width - (columnWidth * Convert.ToDouble(dataView.Table.Columns.Count))) / Convert.ToDouble(2);
for (int i = dataView.Table.Columns.Count - 1; i != -1; i--)
{
DataColumn column = dataView.Table.Columns[i];
//initilized column value
Double headerHeight = 0.5f;
if (chkRotate)
headerHeight = 0.9f;
StiText headerText = new StiText(new RectangleD(pos, 0, columnWidth, headerHeight));
headerText.Text.Value = Stimulsoft.Report.CodeDom.StiCodeDomSerializator.ReplaceSymbols(column.Caption).Replace("_", " ");//ReplaceUnderLineWithSpace(column.Caption);
if (chkRotate)
headerText.Angle = 90;
headerText.HorAlignment = StiTextHorAlignment.Center;
headerText.VertAlignment = StiVertAlignment.Center;
headerText.Name = "HeaderText" + nameIndex.ToString();
headerText.Brush = new StiSolidBrush(Color.LightGreen);
headerText.Border.Side = StiBorderSides.All;
headerBand.Components.Add(headerText);
headerText.Font = new Font(FontName, 11.0f);
headerText.WordWrap = true;
headerText.GrowToHeight = true;
//initilized Data Band value
StiText dataText = new StiText(new RectangleD(pos, 0, columnWidth, 0.5f));
dataText.Text.Value = "{view" + dataView.Table.TableName + "." + Stimulsoft.Report.CodeDom.StiCodeDomSerializator.ReplaceSymbols(column.ColumnName) + "}";
dataText.Name = "DataText" + nameIndex.ToString();
dataText.HorAlignment = StiTextHorAlignment.Center;
dataText.VertAlignment = StiVertAlignment.Center;
dataText.Border.Side = StiBorderSides.All;
dataText.WordWrap = true;
dataText.GrowToHeight = true;
dataText.Font = new Font(FontName, 11.0f);
//Add highlight
if (true)
{
StiCondition condition = new StiCondition();
condition.BackColor = Color.CornflowerBlue;
condition.TextColor = Color.Black;
condition.Expression = "(Line & 1) == 1";
condition.Font = new Font(FontName, 11.0f);
condition.Item = StiFilterItem.Expression;
dataText.Conditions.Add(condition);
}
dataBand.Components.Add(dataText);
pos += columnWidth;
nameIndex++;
}
////footer text
StiText footerText = new StiText(new RectangleD(0, 0, page.Width, 0.5f));
footerText.Text.Value = "صفحه {PageNumber}";
footerText.HorAlignment = StiTextHorAlignment.Center;
footerText.Name = "FooterText";
footerText.Brush = new StiSolidBrush(Color.WhiteSmoke);
footerText.Font = new Font(FontName, 11.0f);
footerBand.Components.Add(footerText);
report.Render(true);
StiWebViewer1.ResetReport();
StiWebViewer1.Report = report;

ASP.NET fileupload doesn't work in server

I have a website project in local and connection with database which database in server. I can add photo and country which I work in local but I can't add which I load project to server
public void resim_ekle()
{
if (FileUpload1.HasFile)
{
try
{
string fileExtension = Path.GetExtension(FileUpload1.FileName).ToLower();
string fileName = Guid.NewGuid().ToString(); // şifreli isim
string fileName2 = Guid.NewGuid().ToString();
if (File.Exists(fileName + fileExtension))
fileName = Guid.NewGuid().ToString();
if (File.Exists(fileName2 + fileExtension))
fileName2 = Guid.NewGuid().ToString();
if (FileUpload1.FileContent == null)
return;
if (FileUpload1.FileContent.Length == 0)
return;
System.Drawing.Bitmap originalBMP = new System.Drawing.Bitmap(FileUpload1.FileContent);
int origWidth = 800;
int origHeight = 600;
int origWidth2 = 120;
int origHeight2 = 90;
double sgnRatio = Convert.ToDouble(origWidth) / Convert.ToDouble(origHeight);
double sgnRatio2 = Convert.ToDouble(origWidth2) / Convert.ToDouble(origHeight2);
System.Drawing.Bitmap newBMP = new System.Drawing.Bitmap(originalBMP, origWidth, origHeight);
System.Drawing.Bitmap newBMP2 = new System.Drawing.Bitmap(originalBMP, origWidth2, origHeight2);
System.Drawing.Graphics oGraphics = System.Drawing.Graphics.FromImage(newBMP);
System.Drawing.Graphics oGraphics2 = System.Drawing.Graphics.FromImage(newBMP2);
oGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;
oGraphics2.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighSpeed;
oGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low;
oGraphics2.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low;
oGraphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
oGraphics2.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
oGraphics.DrawImage(originalBMP, 0, 0, origWidth, origHeight);
oGraphics2.DrawImage(originalBMP, 0, 0, origWidth2, origHeight2);
newBMP.Save(Server.MapPath("~/resimler/olkeler/" + fileName.ToString() + fileExtension));
newBMP2.Save(Server.MapPath("~/resimler/olkeler/kucuk/" + fileName2.ToString() + fileExtension));
olkeler ulke = new olkeler();
ulke.resim_buyuk = ("~/resimler/olkeler/" + fileName.ToString() + fileExtension).ToString();
ulke.resim_kucuk = ("~/resimler/olkeler/kucuk/" + fileName2.ToString() + fileExtension).ToString();
ulke.olke_adi = txtulke_adi.Text;
vt.insert_ulke(ulke);
label_Uyari.Text = "Resim Başarıyla Yüklendi...";
}
catch { label_Uyari.Text = "Resim Yükleme İşlemi Esnasında Bir Hata Oluştu. Lütfen Tekrar Deneyiniz..."; }
}
else { label_Uyari.Text = "Resim Seçilmemiş..."; }
}
This code run in my loclhost but doesn't work in server. FileUpload1 has no file in server
I think it's wrong with your
newBMP.Save(Server.MapPath("~/resimler/olkeler/" + fileName.ToString() + fileExtension));
I think you shall loose the ~
I write:
profilPic.SaveAs(Server.MapPath(#"images/people/") +
profilPic.FileName);
from here:
<asp:FileUpload ID="profilPic" runat="server" />

Categories

Resources