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).
Related
I have created a pivot table using Closed XML. I want to change the font name and size of the pivot table (cells). When I try doing so, it changes the font name and size of the outer sheet (not of the cell content in pivot table). I also tried setting the font name of each cell but couldn't work. Below is the part of my code -
public void CreatePivotTable(List<EmployeeModel> employeeModels)
{
var workbook = new XLWorkbook();
var sheet = workbook.Worksheets.Add("SourceData");
var table = sheet.Cell(1, 1).InsertTable(employeeModels, "SourceData", true);
var sheetName = "PivotTable";
var ptSheet = workbook.Worksheets.Add(sheetName);
ptSheet.Style.Font.FontName = "Arial";
ptSheet.Style.Font.FontSize = 8;
var pt = ptSheet.PivotTables.Add(sheetName, ptSheet.Cell(5, 2), table.AsRange());
// pt.SetPreserveCellFormatting(false);
pt.RowLabels.Add("EmpId").Compact = true;
pt.RowLabels.Add("EmpName");
pt.ColumnLabels.Add("Description");
pt.ColumnLabels.Add("Department");
pt.Values.Add("HR", "Sum of HR");
pt.Values.Add("MT", "Sum of MT");
pt.SetShowGrandTotalsRows(false);
ptSheet.Cell(1, 3).Value = DateTime.Now.ToString();
ptSheet.Cell(2, 3).Style.Font.Bold = true;
ptSheet.Columns().Width = 11;
ptSheet.Columns("C").Width = 25;
ptSheet.Columns("A").Width = 1;
ptSheet.Columns("B").Width = 0;
ptSheet.Columns("1,2").Hide();
ptSheet.SheetView.FreezeColumns(4);
ptSheet.SheetView.FreezeRows(7);
ptSheet.Rows(1, 4).Hide();
ptSheet.Rows(4, 4).Unhide();
pt.Theme = XLPivotTableTheme.None;
pt.SetClassicPivotTableLayout(true);
//Print Options.
PrintOptionsForPivotTable(ptSheet);
workbook.SaveAs(#"C:\Users\prags\source\repos\WindowsFormsApp1\ClosedXmlPivotTable\pivot.xlsx");
}
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'm working on Mvc web app, I want to create new excel sheet with two drop down lists filled with data from database. I want the second drop down list to be dependent on selection changed of first one. I already create file and fill drop down list but I can't find a way to make them dependent.
Any clue how to do this?
Here's my code
public void ExportToXlsx(Stream stream)
{
if (stream == null)
throw new ArgumentNullException("stream");
// ok, we can run the real code of the sample now
using (var xlPackage = new ExcelPackage(stream))
{
// get handle to the existing worksheet#region
#region MyRegion Create Main File
var worksheet = xlPackage.Workbook.Worksheets.Add("Beneficiary");
var properties = new string[]
{
" الاسم "," رقم الهوية " ," رقم الجوال "," نوع المستفيد "," IBAN " ," نوع الوظيفة "," الرتبة/ المرتبة "
};
for (var i = 0; i < properties.Length; i++)
{
worksheet.Cells[1, i + 1].Value = properties[i];
worksheet.Cells[1, i + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[1, i + 1].Style.Fill.BackgroundColor.SetColor(Color.AliceBlue);
worksheet.Cells[1, i + 1].Style.Font.Bold = true;
}
worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
worksheet.View.RightToLeft = true;
#endregion
#region Ismilitry List
ExcelWorksheet isMilitryddList = xlPackage.Workbook.Worksheets.Add("IsMilitry");
var ismilitryValues = new string[]
{
"مدنى","عسكرى" ,"أخرى"
};
var valismilitry = worksheet.DataValidations.AddListValidation(worksheet.Cells[2, 4, 10000, 4].Address);
for (int index = 1; index <= ismilitryValues.Length; index++)
{
isMilitryddList.Cells[1,index].Value = ismilitryValues[index - 1];
}
var addressismilitry = isMilitryddList.Cells[1, 1, 1, ismilitryValues.Count()].Address;
var arrismilitry = addressismilitry.Split(':');
var ismilitrychar1 = arrismilitry[0][0];
var ismilitrynum1 = arrismilitry[0].Trim(ismilitrychar1);
var ismilitrychar2 = arrismilitry[1][0];
var ismilitrynum2 = arrismilitry[1].Trim(ismilitrychar2);
valismilitry.Formula.ExcelFormula = string.Format("=IsMilitry!${0}${1}:${2}${3}", ismilitrychar1, ismilitrynum1, ismilitrychar2, ismilitrynum2);
valismilitry.ShowErrorMessage = true;
valismilitry.Error = "Select from List of Values ...";
#endregion
#region Ranktype List
ExcelWorksheet ddList = xlPackage.Workbook.Worksheets.Add("DropDownList");
var brokerBranchs = new RankTypeBl().SelectAllRankTypes();
var val = worksheet.DataValidations.AddListValidation(worksheet.Cells[2, 6, 10000, 6].Address);
for (int index = 1; index <= brokerBranchs.Count; index++)
{
ddList.Cells[index, 1].Value = brokerBranchs[index - 1].Name;
}
var address = ddList.Cells[1, 1, brokerBranchs.Count(), 1].Address.ToString();
var arr = address.Split(':');
var char1 = arr[0][0];
var num1 = arr[0].Trim(char1);
var char2 = arr[1][0];
var num2 = arr[1].Trim(char2);
val.Formula.ExcelFormula = string.Format("=DropDownList!${0}${1}:${2}${3}", char1, num1, char2, num2);
val.ShowErrorMessage = true;
val.Error = "Select from List of Values ...";
#endregion
#region rank list
ExcelWorksheet ddList1 = xlPackage.Workbook.Worksheets.Add("ranks");
var ranks = new BeneficiaryRankBl().SelectAllBeneficiaryRank();
var val1 = worksheet.DataValidations.AddListValidation(worksheet.Cells[2, 7, 10000, 7].Address);
for (int index = 1; index <= ranks.Count; index++)
{
ddList1.Cells[index, 1].Value = ranks[index - 1].ArName;
}
var address1 = ddList1.Cells[1, 1, ranks.Count(), 1].Address;
var arr1 = address1.Split(':');
var char11 = arr1[0][0];
var num11 = arr1[0].Trim(char11);
var char22 = arr1[1][0];
var num21 = arr1[1].Trim(char22);
val1.Formula.ExcelFormula = string.Format("=ranks!${0}${1}:${2}${3}", char11, num11, char22, num21);
val1.ShowErrorMessage = true;
val1.Error = "Select from List of Values ...";
#endregion
xlPackage.Save();
}
}
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;
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 :)