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;
Related
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).
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();
I have been developing an application using winforms c# .net 4.0.
this application use datagridview and i add combobox + textbox to the datagridview.
During binddata and resizing actions, a black rectangle will draw in the bottom portion of the datagridview.
see the image of the problems
it works perfectly on standard DPI, but problem on the high DPI.
here is the some of my code to binddata and resizing.
using (Class1.Connection = new OleDbConnection(Class1.ConnString))
{
string sql1 = "SELECT tbAuditDetails.AuditNo, tbAuditQuestions.AutoSubcontent, tbAuditQuestions.AutoID, tbAuditQuestions.Questions, tbScore.Description, tbAuditDetails.QuestionID, tbAuditQuestions.QuestAutoID, tbAuditDetails.ScoreID, tbScore.Score, tbAuditQuestions.SubContentID, tbAuditDetails.ProfileID, tbAuditDetails.ScoreRanges, tbAuditDetails.Comments FROM (tbAuditDetails INNER JOIN tbAuditQuestions ON tbAuditDetails.QuestionID = tbAuditQuestions.QuestionID) INNER JOIN tbScore ON tbAuditDetails.ScoreID = tbScore.ScoreID WHERE (([tbAuditDetails.AuditNo] = " + Class1.detailsauditno + ") AND ([tbAuditQuestions.AutoSubcontent] = '" + newautosubcontentid + "') AND ([tbAuditDetails.ProfileID] = " + proid + ")) ORDER BY [tbAuditQuestions.QuestAutoID], [tbAuditDetails.QuestionID]";
Class1.Connection.Open();
oleCommand = new OleDbCommand(sql1, Class1.Connection);
oleAdapter = new OleDbDataAdapter(oleCommand);
oleBuilder = new OleDbCommandBuilder(oleAdapter);
oleDs = new DataSet();
oleAdapter.Fill(oleDs, "tbAuditDetails");
oleTable = oleDs.Tables["tbAuditDetails"];
Class1.Connection.Close();
dataGridView1.DataSource = oleDs.Tables["tbAuditDetails"];
//SET DATAGRIDVIEW
dataGridView1.Columns[0].Visible = false;
dataGridView1.Columns[4].Visible = false;
dataGridView1.Columns[5].Visible = false;
dataGridView1.Columns[6].Visible = false;
dataGridView1.Columns[7].Visible = false;
dataGridView1.Columns[8].Visible = false;
dataGridView1.Columns[9].Visible = false;
dataGridView1.Columns[10].Visible = false;
dataGridView1.Columns[1].HeaderText = " ";
dataGridView1.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridView1.Columns[1].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
dataGridView1.Columns[1].ReadOnly = true;
dataGridView1.Columns[1].Width = 40;
dataGridView1.Columns[2].HeaderText = "ID";
dataGridView1.Columns[2].Width = 40;
dataGridView1.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridView1.Columns[2].ReadOnly = true;
dataGridView1.Columns[3].Width = 600;
dataGridView1.Columns[3].ReadOnly = true;
dataGridView1.Columns[3].DefaultCellStyle.WrapMode = DataGridViewTriState.True;
dataGridView1.Columns[11].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
dataGridView1.Columns[11].HeaderText = "Score";
dataGridView1.Columns[12].Width = 220;
for (int iii = 0; iii < dataGridView1.Rows.Count; iii++)
{
DataGridViewComboBoxCell ComboBoxCell2 = new DataGridViewComboBoxCell();
ComboBoxCell2.Items.Add("0");
ComboBoxCell2.Items.Add("10");
ComboBoxCell2.Items.Add("20");
ComboBoxCell2.Items.Add("30");
ComboBoxCell2.Items.Add("40");
ComboBoxCell2.Items.Add("50");
ComboBoxCell2.Items.Add("60");
ComboBoxCell2.Items.Add("70");
ComboBoxCell2.Items.Add("80");
ComboBoxCell2.Items.Add("90");
ComboBoxCell2.Items.Add("100");
//ComboBoxCell.Items.AddRange(new string[] { "YES", "SOME", "NO", "N/A" });
ComboBoxCell2.FlatStyle = FlatStyle.Standard;
this.dataGridView1[11, iii] = ComboBoxCell2;
ComboBoxCell2.Dispose();
}
}
Any suggestions?
I don't know this is the right solution or not...
BUT, it fix my problem.
Here :
Right click on the .exe program (after you build) and Disable HIGH DPI
i have a tree view in which there are certain set of document list and another grid having patient details. what i need to do is when we select docs from treeview (select multiple..checkbox enabled) and patients from grid and click on a button should create all the documents using ITEXTSHARP.that is multiple documents are created. I tried it like this,
on button click
foreach( TreeNode node in TreeView1.Nodes)
{
if (node.ChildNodes.Count>0)
{
for(int i=0 ;i<(node.ChildNodes.Count);i++)
{
if (node.ChildNodes[i].Checked==true)
{
string nodevalue = node.ChildNodes[i].Value.ToString();
if (nodevalue=="3")
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chk = row.FindControl("CheckBox1") as CheckBox;
if (chk.Checked)
{
Label lbl_name = row.FindControl("Label1") as Label;
Label lbl_dob = row.FindControl("Label3") as Label;
pdf_abcd(lbl_name.Text.Trim(), lbl_dob.Text.Trim());
}
}
}
}
}
}
}
}
}
}
and the pdf_abcd function is
public void pdf_abcd(string name, string dob)
{
Phrase hospt_name = new Phrase();
Phrase slogan = new Phrase();
Phrase address = new Phrase();
Phrase pat_name = new Phrase();
Phrase phr_Consent_For_Treatment = new Phrase();
Phrase phr_Professional_Care = new Phrase();
Phrase phr_Consent_For_Treatment_head = new Phrase();
Phrase phr_Professional_Care_head = new Phrase();
Phrase phr_Nursing_Care = new Phrase();
Phrase phr_Nursing_Care_head = new Phrase();
Phrase phr_signtur_line = new Phrase();
Phrase phr_signtur_bigfont = new Phrase();
Phrase phr_signtur_smallfont_line = new Phrase();
Phrase phr_signtur_date_line = new Phrase();
Phrase phr_relationship = new Phrase();
Phrase phr_witness = new Phrase();
Phrase phr_paitient_name = new Phrase();
Phrase phr_paitient_dob = new Phrase();
Paragraph para = new Paragraph();
Paragraph pat_det = new Paragraph();
Paragraph Consent_For_Treatment = new Paragraph();
Paragraph Professional_Care = new Paragraph();
Paragraph Nursing_Care = new Paragraph();
Paragraph Consent_For_Treatment_head = new Paragraph();
Paragraph Professional_Care_head = new Paragraph();
Paragraph Nursing_Care_head = new Paragraph();
Paragraph signatur = new Paragraph();
Paragraph relationship = new Paragraph();
Paragraph witness = new Paragraph();
Paragraph paitient_name_dob = new Paragraph();
Font fntNormalText = FontFactory.GetFont(FontFactory.TIMES, 12, iTextSharp.text.Font.NORMAL);
Font fntBoldText = FontFactory.GetFont(FontFactory.TIMES, 12, Font.BOLD);
Font fntsmallText = FontFactory.GetFont(FontFactory.TIMES, 8, Font.NORMAL);
Font fntverysmallText = FontFactory.GetFont(FontFactory.TIMES, 6, Font.NORMAL);
Font fntBoldheadingText = FontFactory.GetFont(FontFactory.TIMES, 10, Font.BOLD);
Font fntparaText = FontFactory.GetFont(FontFactory.TIMES, 10, Font.NORMAL);
hospt_name = new Phrase("abcd", fntBoldText);
slogan = new Phrase(System.Environment.NewLine + "Quality health care here at home", fntNormalText);
address = new Phrase(System.Environment.NewLine + "P.O. Box 677", fntsmallText);
para.Add(hospt_name);
para.Add(slogan);
para.Add(address);
phr_paitient_name = new Phrase(System.Environment.NewLine + System.Environment.NewLine + System.Environment.NewLine + System.Environment.NewLine + name + " " + dob, fntNormalText);
pat_name = new Phrase(System.Environment.NewLine + "__________________________________________________________ _______________________________" + System.Environment.NewLine + "Patient's Name D.O.B.", fntsmallText);
pat_det.Add(phr_paitient_name);
pat_det.Add(pat_name);
phr_Consent_For_Treatment_head = new Phrase(System.Environment.NewLine + "Consent For Treatment", fntBoldheadingText);
Consent_For_Treatment_head.Add(phr_Consent_For_Treatment_head);
phr_Consent_For_Treatment = new Phrase("The undersigned consents to procedures and treatments which may be performed during this hospitalization or on an outpatient or emergency basis, including but not limited to anesthesia, laboratory procedures, medical or surgical treatments, x-ray examination, or other services rendered under the general and specific instructions of the physician, physician's assistant, nurse practitioner or Designee. In order to manage accidental exposure of a health care worker to blood or other bodily fluids, the undersigned further consents to such testing; including but not limited to AIDS, TB, Syphilis, and Hepatitis testing, as may be necessary for protection of the heath care worker.", fntparaText);
Consent_For_Treatment.Add(phr_Consent_For_Treatment);
phr_Professional_Care_head = new Phrase(System.Environment.NewLine + "Professional Care", fntBoldheadingText);
Professional_Care_head.Add(phr_Professional_Care_head);
phr_Professional_Care = new Phrase("The attending physician, usually selected by the patient except under unusual or emergency circumstances, is the professional who arranges for the patient's care and treatment Doctors of medicine, including anesthesia provider, pathologists, radiologists, emergency room physicians, osteopathy, podiatry, etc., are independent contractors and are not employees of Val Verde Regional Medical Center. You will receive a separate bill from the physician/anesthesia provider.", fntparaText);
Professional_Care.Add(phr_Professional_Care);
phr_Nursing_Care_head = new Phrase(System.Environment.NewLine + "Nursing Care", fntBoldheadingText);
Nursing_Care_head.Add(phr_Nursing_Care_head);
phr_Nursing_Care = new Phrase("The hospital provides general nursing care. Private duty nursing must be arranged by the patient's representative. The hospital is not responsible for and is released from all liabilities for failure to provide such care.", fntparaText);
Nursing_Care.Add(phr_Nursing_Care);
phr_signtur_line = new Phrase(System.Environment.NewLine + System.Environment.NewLine + "__________________________________________________________________________________________ ________________", fntsmallText);
phr_signtur_bigfont = new Phrase(System.Environment.NewLine + "Signature of Patient/Responsible Party/Patient Representative", fntNormalText);
phr_signtur_smallfont_line = new Phrase("(If patient unable to sign)", fntverysmallText);
phr_signtur_date_line = new Phrase(" Date ", fntNormalText);
signatur.Add(phr_signtur_line);
signatur.Add(phr_signtur_bigfont);
signatur.Add(phr_signtur_smallfont_line);
signatur.Add(phr_signtur_date_line);
phr_relationship = new Phrase(System.Environment.NewLine + "______________________________________________________________" + System.Environment.NewLine + "Relationship to patient", fntNormalText);
relationship.Add(phr_relationship);
phr_witness = new Phrase(System.Environment.NewLine + "___________________________________ __________" + System.Environment.NewLine + "Signature of Witness Date", fntNormalText);
witness.Add(phr_witness);
Document Doc = new Document(PageSize.A4, 0, 0, 25, 50);
PdfWriter.GetInstance(Doc, new FileStream(Server.MapPath("~/abcd/abcd.pdf"), FileMode.Create));
Doc.Open();
PdfPTable table = new PdfPTable(1);
table.TotalWidth = 500f;
table.LockedWidth = true;
iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance("~/img/abcd.png");
logo.ScaleAbsolute(30, 30);
PdfPCell image_header = new PdfPCell(logo);
image_header.HorizontalAlignment = Element.ALIGN_CENTER;
image_header.BorderWidth = 0;
table.AddCell(image_header);
PdfPCell header = new PdfPCell(para);
header.HorizontalAlignment = Element.ALIGN_CENTER;
header.Colspan = 4;
header.BorderWidth = 0;
table.AddCell(header);
PdfPCell patient = new PdfPCell(pat_det);
patient.BorderWidth = 0;
table.AddCell(patient);
//PdfPCell patientname = new PdfPCell(new Phrase(System.Environment.NewLine + System.Environment.NewLine + "Patient's Name D.O.B."));
//patientname.BorderWidth = 0;
//table.AddCell(patientname);
PdfPCell head_treatment = new PdfPCell(new Phrase(Consent_For_Treatment_head));
head_treatment.BorderWidth = 0;
table.AddCell(head_treatment);
PdfPCell treatment_content = new PdfPCell(Consent_For_Treatment);
treatment_content.BorderWidth = 0;
table.AddCell(treatment_content);
PdfPCell head_profcare = new PdfPCell(Professional_Care_head);
head_profcare.BorderWidth = 0;
table.AddCell(head_profcare);
PdfPCell profcare_content = new PdfPCell(Professional_Care);
profcare_content.BorderWidth = 0;
table.AddCell(profcare_content);
PdfPCell head_nursing = new PdfPCell(Nursing_Care_head);
head_nursing.BorderWidth = 0;
table.AddCell(head_nursing);
PdfPCell nursing_content = new PdfPCell(Nursing_Care);
nursing_content.BorderWidth = 0;
table.AddCell(nursing_content);
PdfPCell sig = new PdfPCell(signatur);
sig.BorderWidth = 0;
table.AddCell(sig);
PdfPCell raltntopatient = new PdfPCell(relationship);
raltntopatient.BorderWidth = 0;
table.AddCell(raltntopatient);
PdfPCell witnesslines = new PdfPCell(witness);
witnesslines.BorderWidth = 0;
table.AddCell(witnesslines);
Doc.Add(table);
Doc.Close();
string path = Server.MapPath("~/abcd/Dabcd.pdf");
ShowPdf(path);
//Response.Redirect(Server.MapPath("~/abcd/abcd.pdf"));
}
and
private void ShowPdf(string strS)
{
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=" + strS);
Response.TransmitFile(strS);
Response.End();
Response.Flush();
Response.Clear();
}
but the system only down loads one doc..can anyone helpme
If you step back and ignore PDFs for a bit and concentrate on just HTTP requests and responses you should have your answer. When a browser makes an HTTP request (your button click) the server is allowed to send one and only one response. You're code is trying (unsuccessfully) to send multiple responses to the browser. The first time that Response.End is called the pipeline gets terminated actually and the rest of your code doesn't run.
The solution is to just make one giant PDF in one pass, make individual PDFs and merge them or create a zip file containing all of the PDFs.
I guess you should create a zip file that combines your PDF files
If you want to Open the file in new tab you have different Methods:
Method 1:
Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=foo.pdf");
Response.TransmitFile(filePath);
Response.End();
Method 2:
Process process = new Process();
process.StartInfo.UseShellExecute = true;
process.StartInfo.FileName = outputPdfFile;
process.Start();
Hope this helps you!
I have a class that build the content for my table of contents and that works, fine and dandy.
Here's the code:
public void Build(string center,IDictionary<string,iTextSharp.text.Image> images)
{
iTextSharp.text.Image image = null;
XPathDocument rapportTekst = new XPathDocument(Application.StartupPath + #"..\..\..\RapportTemplates\RapportTekst.xml");
XPathNavigator nav = rapportTekst.CreateNavigator();
XPathNodeIterator iter;
iter = nav.Select("//dokument/brevhoved");
iter.MoveNext();
var logo = iTextSharp.text.Image.GetInstance(iter.Current.GetAttribute("url", ""));
iter = nav.Select("//dokument/gem_som");
iter.MoveNext();
string outputPath = iter.Current.GetAttribute("url", "")+center+".pdf";
iter = nav.Select("//dokument/titel");
iter.MoveNext();
this.titel = center;
Document document = new Document(PageSize.A4, 30, 30, 100, 30);
var outputStream = new FileStream(outputPath, FileMode.Create);
var pdfWriter = PdfWriter.GetInstance(document, outputStream);
pdfWriter.SetLinearPageMode();
var pageEventHandler = new PageEventHandler();
pageEventHandler.ImageHeader = logo;
pdfWriter.PageEvent = pageEventHandler;
DateTime timeOfReport = DateTime.Now.AddMonths(-1);
pageWidth = document.PageSize.Width - (document.LeftMargin + document.RightMargin);
pageHight = document.PageSize.Height - (document.TopMargin + document.BottomMargin);
document.Open();
var title = new Paragraph(titel, titleFont);
title.Alignment = Element.ALIGN_CENTER;
document.Add(title);
List<TableOfContentsEntry> _contentsTable = new List<TableOfContentsEntry>();
nav.MoveToRoot();
iter = nav.Select("//dokument/indhold/*");
Chapter chapter = null;
int chapterCount = 1;
while (iter.MoveNext())
{
_contentsTable.Add(new TableOfContentsEntry("Test", pdfWriter.CurrentPageNumber.ToString()));
XPathNodeIterator innerIter = iter.Current.SelectChildren(XPathNodeType.All);
chapter = new Chapter("test", chapterCount);
while(innerIter.MoveNext())
{
if (innerIter.Current.Name.ToString().ToLower().Equals("billede"))
{
image = images[innerIter.Current.GetAttribute("navn", "")];
image.Alignment = Image.ALIGN_CENTER;
image.ScaleToFit(pageWidth, pageHight);
chapter.Add(image);
}
if (innerIter.Current.Name.ToString().ToLower().Equals("sektion"))
{
string line = "";
var afsnit = new Paragraph();
line += (innerIter.Current.GetAttribute("id", "") + " ");
innerIter.Current.MoveToFirstChild();
line += innerIter.Current.Value;
afsnit.Add(line);
innerIter.Current.MoveToNext();
afsnit.Add(innerIter.Current.Value);
chapter.Add(afsnit);
}
}
chapterCount++;
document.Add(chapter);
}
document = CreateTableOfContents(document, pdfWriter, _contentsTable);
document.Close();
}
I'm then calling the method CreateTableOfContents(), and as such it is doing what it is supposed to do. Here's the code for the method:
public Document CreateTableOfContents(Document _doc, PdfWriter _pdfWriter, List<TableOfContentsEntry> _contentsTable)
{
_doc.NewPage();
_doc.Add(new Paragraph("Table of Contents", FontFactory.GetFont("Arial", 18, Font.BOLD)));
_doc.Add(new Chunk(Environment.NewLine));
PdfPTable _pdfContentsTable = new PdfPTable(2);
foreach (TableOfContentsEntry content in _contentsTable)
{
PdfPCell nameCell = new PdfPCell(_pdfContentsTable);
nameCell.Border = Rectangle.NO_BORDER;
nameCell.Padding = 6f;
nameCell.Phrase = new Phrase(content.Title);
_pdfContentsTable.AddCell(nameCell);
PdfPCell pageCell = new PdfPCell(_pdfContentsTable);
pageCell.Border = Rectangle.NO_BORDER;
pageCell.Padding = 6f;
pageCell.Phrase = new Phrase(content.Page);
_pdfContentsTable.AddCell(pageCell);
}
_doc.Add(_pdfContentsTable);
_doc.Add(new Chunk(Environment.NewLine));
/** Reorder pages so that TOC will will be the second page in the doc
* right after the title page**/
int toc = _pdfWriter.PageNumber - 1;
int total = _pdfWriter.ReorderPages(null);
int[] order = new int[total];
for (int i = 0; i < total; i++)
{
if (i == 0)
{
order[i] = 1;
}
else if (i == 1)
{
order[i] = toc;
}
else
{
order[i] = i;
}
}
_pdfWriter.ReorderPages(order);
return _doc;
}
The problem is however. I want to insert a page break before the table of contents, for the sake of reordering the pages, so that the table of contents is the first page, naturally. But the output of the pdf-file is not right.
Here's a picture of what it looks like:
It seems like the _doc.NewPage() in the CreateTableOfContents() method does not execute correctly. Meaning that the image and the table of contents is still on the same page when the method starts the reordering of pages.
EDIT: To clarify the above, the _doc.NewPage() gets executed, but the blank page is added after the picture and the table of contents.
I've read a couple of places that this could be because one is trying to insert a new page after an already blank page. But this is not the case.
I'll just link to the pdf files aswell, to better illustrate the problem.
The pdf with table of contents: with table of contents
The pdf without table of contents: without table of contents
Thank you in advance for your help :)