static void Main(string[] args)
{
string saveFileAs = "D:\\Hello.pdf";
Program p = new Program();
Document doc = p.CreateDocument();
PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always);
renderer.Document = doc;
renderer.RenderDocument();
renderer.PdfDocument.Save("D:\\Hello.pdf");
Process.Start(saveFileAs);
}
public Document CreateDocument()
{
// Create a new MigraDoc document
this.document = new Document();
this.document.Info.Title = "A sample invoice";
this.document.Info.Subject = "Demonstrates how to create an invoice.";
this.document.Info.Author = "Chandana Amarnath";
DefineStyles();
CreatePage();
FillContent();
return this.document;
}
void CreatePage()
{
// Each MigraDoc document needs at least one section.
Section section = this.document.AddSection();
// Put a logo in the header
Image image = section.Headers.Primary.AddImage("D:\\Cubes.jpg");
image.Height = "2.5cm";
image.LockAspectRatio = true;
image.RelativeVertical = RelativeVertical.Line;
image.RelativeHorizontal = RelativeHorizontal.Margin;
image.Top = ShapePosition.Top;
image.Left = ShapePosition.Right;
image.WrapFormat.Style = WrapStyle.Through;
// Create footer
Paragraph paragraph = section.Footers.Primary.AddParagraph();
// The following one prints at the footer;
paragraph.AddText("Aldata Inc.");
paragraph.Format.Font.Size = 9;
paragraph.Format.Alignment = ParagraphAlignment.Center;
// Create the text frame for the address
this.addressFrame = section.AddTextFrame();
this.addressFrame.Height = "3.0cm";
this.addressFrame.Width = "7.0cm";
this.addressFrame.Left = ShapePosition.Left;
this.addressFrame.RelativeHorizontal = RelativeHorizontal.Margin;
this.addressFrame.Top = "5.0cm";
this.addressFrame.RelativeVertical = RelativeVertical.Page;
// Put sender in address frame
paragraph = this.addressFrame.AddParagraph("Aldata-Apollo Inc.");
paragraph.Format.Font.Name = "Times New Roman";
paragraph.Format.Font.Size = 7;
paragraph.Format.SpaceAfter = 3;
// Add the print date field
paragraph = section.AddParagraph();
paragraph.Format.SpaceBefore = "8cm";
paragraph.Style = "Reference";
paragraph.AddFormattedText("Section Comparator", TextFormat.Bold);
paragraph.AddTab();
paragraph.AddText("Date: ");
paragraph.AddDateField("dd.MM.yyyy");
// Create the item table
this.table = section.AddTable();
this.table.Style = "Table";
this.table.Borders.Color = Color.Parse("Black");
this.table.Borders.Width = 0.25;
this.table.Borders.Left.Width = 0.5;
this.table.Borders.Right.Width = 0.5;
this.table.Rows.LeftIndent = 0;
//************ Before you can add a row, you must define the columns **********
Column column = this.table.AddColumn("4cm");
column.Format.Alignment = ParagraphAlignment.Center;
column = this.table.AddColumn("3cm");
column.Format.Alignment = ParagraphAlignment.Right;
// Create the header of the table
Row row = table.AddRow();
row.HeadingFormat = true;
row.Format.Alignment = ParagraphAlignment.Center;
row.Format.Font.Bold = true;
row.Shading.Color = Color.Parse("White");
row.Cells[0].AddParagraph("Added");
row.Cells[0].Format.Font.Bold = true;
row.Cells[0].Format.Alignment = ParagraphAlignment.Center;
row.Cells[0].MergeRight = 3;
row = table.AddRow();
row.HeadingFormat = true;
row.Format.Alignment = ParagraphAlignment.Center;
row.Format.Font.Bold = true;
row.Cells[0].AddParagraph("Deleted Items");
row.Cells[0].Format.Font.Bold = true;
row.Cells[0].Format.Alignment = ParagraphAlignment.Left;
row.Cells[0].MergeRight = 3;
this.table.SetEdge(0, 0, 2, 3, Edge.Box, BorderStyle.Single, 0.75, Color.Empty);
}
void FillContent()
{
string xmlFileName = "C:\\Section.xml";
XPathDocument xPathDocument = new XPathDocument(xmlFileName);
XPathNavigator item = xPathDocument.CreateNavigator();
XPathNodeIterator iter = item.Select("/Hello/*");
while (iter.MoveNext())
{
string name = iter.Current.Name;
item = iter.Current;
Row row1 = this.table.AddRow();
Row row2 = this.table.AddRow();
row1.TopPadding = 1.5;
row1.Cells[0].Shading.Color = Color.Parse("Gray");
row1.Cells[0].VerticalAlignment = VerticalAlignment.Center;
row1.Cells[0].MergeDown = 1;
row1.Cells[1].Format.Alignment = ParagraphAlignment.Left;
row1.Cells[1].MergeRight = 3;
row1.Cells[0].AddParagraph(item.ToString());
Console.WriteLine(name + "\t:" +item);
}
Console.ReadKey();
}
I am writing code for generating my report in PDF using MigraDoc. I have downloaded the code from PDFSharp site. The following has 3 functions DefineStyles(), CreatePage(), FillContent(). I made changes in function CreatePage(), FillContent(); But when I am running the program I am getting error saying
Argument out of Exception:
Specified argument was out of the range of valid values.
In the CreatePage() I added 2 rows and 2 columns to a table. And in the FillContent() function I read my XML file. But I am unable to find where I am crossing my index range.
SOLVED
The problem is when I am setting the table.SetEdge(...). I am accessing the columns that I have not created.
Thank u all .. :)
At this step I was setting the rows that are not yet created.
this.table.SetEdge(0, 0, 2, 3, Edge.Box, BorderStyle.Single, 0.75, Color.Empty);
Instead of 3 which are the number of rows I should use 2.
Related
I have this public class below and I want to include a condition which placed it inside and it doesn't work. Any suggestions?
public SummaryDates GetSummaryDates()
{
SummaryDates result = new SummaryDates();
var getDay = 3;
DateTime now = DateTime.UtcNow.Date;
var getMonth = 0;
var getQuarter = 0;
var quarterNow = now.AddMonths(3 * getQuarter);
var quarterNumber = Math.Ceiling(quarterNow.Month / 3m);
var quarterLabel2 = 0;
var quarterLabel1 = 0;
var quarterLabelA = 0;
var quarterLabelB = 0;
result.summaryDates = new SummaryDates
{
startOfQuarter2 = now,
endOfQuarter2 = now,
endOfQuarter2Plus1Day = now,
endOfQuarter1Plus1Day = now,
startOfQuarter1 = now,
endOfQuarter1 = now,
startOfQuarterA = now,
startOfQuarterB = now,
endOfQuarterA = now,
endOfQuarterB = now,
endOfQuarterAPlus1Day = now,
endOfQuarterBPlus1Day = now,
if (quarterNumber == 4)
{
startOfQuarter2 = new DateTime(getSummaryDates.quarter2Year, 10, 01);
endOfQuarter2 = new DateTime(getSummaryDates.quarter2Year, 12, 31);
endOfQuarter2Plus1Day = getSummaryDates.endOfQuarter2.AddDays(1);
quarterLabel2 = Convert.ToInt16(Math.Ceiling(getSummaryDates.endOfQuarter2.Month / 3m));
}
return result;
}
}
I've placed the conditions inside. It doesn't work.
I want to insert and update data into database on button click but when I fill all fields and start debugging and when dubugger is on buyer code this error is occurred "object reference not set to an instance of an object". Kindly help me.......
protected void btnSaveChanges_Click(object sender, EventArgs e)
{
if (Convert.ToInt32(ViewState["BuyerId"]) > 0)
{
oBuyer = new Buyer();
//Fill object with Text box values
oBuyer.BuyerId = Convert.ToInt32(ViewState["BuyerId"]);
oBuyer.BuyerCode = txtBuyerCode.Text;
oBuyer.SunCode = txtSunCode.Text;
oBuyer.BuyerName = txtBuyerName.Text;
oBuyer.BuyerAddress1 = txtBuyerAddress1.Text;
oBuyer.BuyerAddress2 = txtBuyerAddress2.Text;
oBuyer.BuyerAddress3 = txtBuyerAddress3.Text;
oBuyer.BuyerAddress4 = txtBuyerAddress4.Text;
oBuyer.BuyerPostCode = txtBuyerPostcode.Text;
oBuyer.BuyerPhone = txtBuyerPhone.Text;
oBuyer.BuyerFax = txtBuyerFax.Text;
oBuyer.BuyerEmail = txtBuyerMail.Text;
oBuyer.PfaCode = txtBuyerPFACode.Text;
oBuyer.Guarantee = Convert.ToDecimal(txtBuyerGuarantee.Text);
oBuyer.DefaultDestination = ddlBuyerDefaultDestination.SelectedValue;
oBuyer.HbaLevy = chkHBALeavy.Checked;
oBuyer.SfiaWhite = chkSFIAPelagic.Checked;
oBuyer.SfiaPelagic = chkSFIAPelagic.Checked;
oBuyer.MarketBox = txtBuyerMarketBox.Text;
oBuyer.Comments = txtComments.Text;
oBuyer.BuyerRegistrationNo = txtBuyerRigistrationNo.Text;
}
else
{
//Fill object with Text box values
oBuyer.BuyerCode = txtBuyerCode.Text;
oBuyer.SunCode = txtSunCode.Text;
oBuyer.BuyerName = txtBuyerName.Text;
oBuyer.BuyerAddress1 = txtBuyerAddress1.Text;
oBuyer.BuyerAddress2 = txtBuyerAddress2.Text;
oBuyer.BuyerAddress3 = txtBuyerAddress3.Text;
oBuyer.BuyerAddress4 = txtBuyerAddress4.Text;
oBuyer.BuyerPostCode = txtBuyerPostcode.Text;
oBuyer.BuyerPhone = txtBuyerPhone.Text;
oBuyer.BuyerFax = txtBuyerFax.Text;
oBuyer.BuyerEmail = txtBuyerMail.Text;
oBuyer.PfaCode = txtBuyerPFACode.Text;
oBuyer.Guarantee = Convert.ToDecimal(txtBuyerGuarantee.Text);
oBuyer.DefaultDestination = ddlBuyerDefaultDestination.SelectedValue;
oBuyer.HbaLevy = chkHBALeavy.Checked;
oBuyer.SfiaWhite = chkSFIAPelagic.Checked;
oBuyer.SfiaPelagic = chkSFIAPelagic.Checked;
oBuyer.MarketBox = txtBuyerMarketBox.Text;
oBuyer.Comments = txtComments.Text;
oBuyer.BuyerRegistrationNo = txtBuyerRigistrationNo.Text;
}
//enter into nSYScatch6 service
bool saveBuyer = nSYSCatch6ServiceInitiator.SaveBuyer(oBuyer);
if (saveBuyer)
{
}
Response.Redirect(Request.RawUrl);
}
You are missing an oBuyer = new Buyer(); in the else branch.
I was really hoping someone could help me,
I need to get the variable product from the method GridView1_RowDataBound to the quote value class string product.
Its for a pdf creator and any help would be greatly appreciated as i've been stuck on this for quite a while, please excuse as I'm fairly inexperienced in .net.
Thanks very much!!
enter code here
public partial class quotedetail : System.Web.UI.Page
{
private string quoteId;
private string product;
private string connectId = "";
string description = "Save Your Quote as a PDF with your Company Logo and Print out for Customers";
public string ConnectId { get { return connectId; } }
protected void Page_Init(object sender, EventArgs e)
{
connectId = Global.GetConnectionString();
quoteId = Request.QueryString["quote"];
product =
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
(Master as WebOnlineMasterPage).PageTitle = "Quote - " + quoteId;
DisplayPage();
}
}
protected void DisplayPage()
{
try
{
DataSet ds = new WebOnlineQuote.Quote().GetQuote(ConnectId, quoteId);
FormView1.DataSource = ds.Tables[0];
GridView1.DataSource = ds.Tables[1];
Page.DataBind();
}
catch (System.Web.Services.Protocols.SoapException ex)
{
Global.CheckException(ex);
description = "Sorry, information about this quote is unavailable.";
Panel1.Visible = false;
}
(Master as WebOnlineMasterPage).PageDescription = description;
}
public void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.DataRow))
{
e.Row.Attributes.Add("onmouseover", "className='dataOver'");
if (e.Row.DataItemIndex % 2 == 1)
e.Row.Attributes.Add("onmouseout", "className='dataAltRow'");
else
e.Row.Attributes.Add("onmouseout", "className='data'");
string product = ((DataRow)((DataRowView)e.Row.DataItem).Row)["ProductCode"].ToString();
e.Row.Attributes.Add("onClick", String.Format("document.location='productdetail.aspx?id={0}'", product));
}
}
protected void FormView1_DataBound(object sender, EventArgs e)
{
// get the expiry date
bool isopen = (bool)((DataRow)((DataRowView)FormView1.DataItem).Row)["IsOpen"];
bool expired = (bool)((DataRow)((DataRowView)FormView1.DataItem).Row)["Expired"];
int viewIndex = 0;
if (isopen && !expired)
viewIndex = 1;
// set appropriate view
MultiView view = (MultiView)FormView1.FindControl("QuoteProcessView");
view.ActiveViewIndex = viewIndex;
}
protected void AcceptQuote_Btn_Click(object sender, EventArgs e)
{
Response.Redirect("checkout.aspx?quote=" + quoteId);
}
protected void Requote_Btn_Click(object sender, EventArgs e)
{
Response.Redirect("requestquote.aspx?quote=" + quoteId);
}
// ********************PDF Start********************
protected void SaveAsPdf_Click(object sender, EventArgs e)
{
DataSet quote = new WebOnlineQuote.Quote().GetQuote(ConnectId, quoteId);
Document document = CreateDocument();
PdfDocumentRenderer renderer = new PdfDocumentRenderer();
renderer.Document = document;
renderer.RenderDocument();
MemoryStream ms = new MemoryStream();
renderer.PdfDocument.Save(ms);
byte[] pdfBytes = ms.ToArray();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=quote.pdf");
Response.AddHeader("Content-Length", pdfBytes.Length.ToString());
Response.BinaryWrite(pdfBytes);
Response.StatusCode = 200;
Response.End();
}
public Document CreateDocument()
{
Document document = new Document();
document.Info.Title = "A sample invoice";
document.Info.Subject = "Demonstrates how to create an invoice.";
DefineStyles(document);
TextFrame addressFrame;
MigraDoc.DocumentObjectModel.Tables.Table table;
CreatePage(document, out addressFrame, out table );
FillContent(document, addressFrame, table);
return document;
}
void DefineStyles(Document document)
{
// Get the predefined style Normal.
MigraDoc.DocumentObjectModel.Style style = document.Styles["Normal"];
// Because all styles are derived from Normal, the next line changes the
// font of the whole document. Or, more exactly, it changes the font of
// all styles and paragraphs that do not redefine the font.
style.Font.Name = "Verdana";
style = document.Styles[StyleNames.Header];
style.ParagraphFormat.AddTabStop("16cm", TabAlignment.Right);
style = document.Styles[StyleNames.Footer];
style.ParagraphFormat.AddTabStop("8cm", TabAlignment.Center);
// Create a new style called Table based on style Normal
style = document.Styles.AddStyle("Table", "Normal");
style.Font.Name = "Verdana";
style.Font.Name = "Times New Roman";
style.Font.Size = 9;
// Create a new style called Reference based on style Normal
style = document.Styles.AddStyle("Reference", "Normal");
style.ParagraphFormat.SpaceBefore = "5mm";
style.ParagraphFormat.SpaceAfter = "5mm";
style.ParagraphFormat.TabStops.AddTabStop("16cm", TabAlignment.Right);
}
void CreatePage(Document document, out TextFrame addressFrame, out MigraDoc.DocumentObjectModel.Tables.Table table)
{
// Each MigraDoc document needs at least one section.
Section section = document.AddSection();
// Put a logo in the header
MigraDoc.DocumentObjectModel.Shapes.Image image = section.Headers.Primary.AddImage(Server.MapPath("~/images/cnwlogo.jpg"));
image.Height = "2.5cm";
image.LockAspectRatio = true;
image.RelativeVertical = RelativeVertical.Line;
image.RelativeHorizontal = RelativeHorizontal.Margin;
image.Top = ShapePosition.Top;
image.Left = ShapePosition.Right;
image.WrapFormat.Style = WrapStyle.Through;
// Create footer
Paragraph paragraph = section.Footers.Primary.AddParagraph();
paragraph.AddText("PowerBooks Inc · Sample Street 42 · 56789 Cologne · Germany");
paragraph.Format.Font.Size = 9;
paragraph.Format.Alignment = ParagraphAlignment.Center;
// Create the text frame for the address
addressFrame = section.AddTextFrame();
addressFrame.Height = "3.0cm";
addressFrame.Width = "7.0cm";
addressFrame.Left = ShapePosition.Left;
addressFrame.RelativeHorizontal = RelativeHorizontal.Margin;
addressFrame.Top = "5.0cm";
addressFrame.RelativeVertical = RelativeVertical.Page;
// Put sender in address frame
paragraph = addressFrame.AddParagraph("PowerBooks Inc · Sample Street 42 · 56789 Cologne");
paragraph.Format.Font.Name = "Times New Roman";
paragraph.Format.Font.Size = 7;
paragraph.Format.SpaceAfter = 3;
// Add the print date field
paragraph = section.AddParagraph();
paragraph.Format.SpaceBefore = "8cm";
paragraph.Style = "Reference";
paragraph.AddFormattedText("INVOICE", TextFormat.Bold);
paragraph.AddTab();
paragraph.AddText("Cologne, ");
paragraph.AddDateField("dd.MM.yyyy");
// Create the item table
table = section.AddTable();
table.Style = "Table";
table.Borders.Color = Colors.DarkBlue;
table.Borders.Width = 0.25;
table.Borders.Left.Width = 0.5;
table.Borders.Right.Width = 0.5;
table.Rows.LeftIndent = 0;
// Before you can add a row, you must define the columns
Column column = table.AddColumn("3cm");
column.Format.Alignment = ParagraphAlignment.Left;
column = table.AddColumn("5cm");
column.Format.Alignment = ParagraphAlignment.Left;
column = table.AddColumn("1cm");
column.Format.Alignment = ParagraphAlignment.Left;
column = table.AddColumn("1cm");
column.Format.Alignment = ParagraphAlignment.Left;
column = table.AddColumn("2cm");
column.Format.Alignment = ParagraphAlignment.Left;
column = table.AddColumn("2cm");
column.Format.Alignment = ParagraphAlignment.Left;
column = table.AddColumn("2cm");
column.Format.Alignment = ParagraphAlignment.Right;
// Create the header of the table
CreateHeaderRow(table);
table.SetEdge(0, 0, 7, 1, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 0.75, Color.Empty);
//create data table
}
private static void CreateHeaderRow(MigraDoc.DocumentObjectModel.Tables.Table table)
{
Row headerRow1 = table.AddRow();
headerRow1.HeadingFormat = true;
headerRow1.Format.Alignment = ParagraphAlignment.Center;
headerRow1.Format.Font.Bold = true;
headerRow1.Shading.Color = Colors.AliceBlue;
headerRow1.Cells[0].AddParagraph("PRODUCT");
headerRow1.Cells[0].Format.Font.Bold = false;
headerRow1.Cells[0].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[0].VerticalAlignment = VerticalAlignment.Bottom;
headerRow1.Cells[0].MergeDown = 1;
headerRow1.Cells[1].AddParagraph("DESCRIPTION");
headerRow1.Cells[1].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[1].MergeDown = 1;
headerRow1.Cells[2].AddParagraph("QTY");
headerRow1.Cells[2].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[2].VerticalAlignment = VerticalAlignment.Bottom;
headerRow1.Cells[2].MergeDown = 1;
headerRow1.Cells[3].AddParagraph("UNIT");
headerRow1.Cells[3].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[3].VerticalAlignment = VerticalAlignment.Bottom;
headerRow1.Cells[3].MergeDown = 1;
headerRow1.Cells[4].AddParagraph("PRICE");
headerRow1.Cells[4].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[4].VerticalAlignment = VerticalAlignment.Bottom;
headerRow1.Cells[4].MergeDown = 1;
headerRow1.Cells[5].AddParagraph("TAX");
headerRow1.Cells[5].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[5].VerticalAlignment = VerticalAlignment.Bottom;
headerRow1.Cells[5].MergeDown = 1;
headerRow1.Cells[6].AddParagraph("TOTAL");
headerRow1.Cells[6].Format.Alignment = ParagraphAlignment.Left;
headerRow1.Cells[6].VerticalAlignment = VerticalAlignment.Bottom;
headerRow1.Cells[6].MergeDown = 1;
}
class QuoteItemRow
{
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ((e.Row.RowType == DataControlRowType.DataRow))
{
e.Row.Attributes.Add("onmouseover", "className='dataOver'");
if (e.Row.DataItemIndex % 2 == 1)
e.Row.Attributes.Add("onmouseout", "className='dataAltRow'");
else
e.Row.Attributes.Add("onmouseout", "className='data'");
string product = ((DataRow)((DataRowView)e.Row.DataItem).Row)["ProductID"].ToString();
e.Row.Attributes.Add("onClick", String.Format("document.location='productdetail.aspx?id={0}'", product));
}
}
public QuoteItemRow(decimal quantity, decimal price, decimal discount, string itemNumber, string title)
{
Quantity = quantity;
Price = price;
Discount = discount;
ItemNumber = itemNumber;
Title = title;
}
public decimal Quantity;
public decimal Discount;
public decimal Price;
public string ItemNumber;
public string Title;
}
void FillContent(Document document, TextFrame addressFrame, MigraDoc.DocumentObjectModel.Tables.Table table)
{
Paragraph paragraph = addressFrame.AddParagraph();
paragraph.AddText("Joe Bloggs");
paragraph.AddLineBreak();
paragraph.AddText("12 Some St");
paragraph.AddLineBreak();
paragraph.AddText(product);
// Iterate the invoice items
decimal totalExtendedPrice = 0;
QuoteItemRow[] items = new QuoteItemRow[] {
new QuoteItemRow (2.0m, 3.4m, 0.2m, "3213421", product ),
new QuoteItemRow (2.4m, 3.4m, 0.0m, "3534DD21", quoteId ),
new QuoteItemRow (8, 0.4m, 0.1m, "908587", quoteId ),
};
foreach (QuoteItemRow item in items)
{
decimal quantity = item.Quantity;
decimal price = item.Price;
decimal discount = item.Discount;
// Each item fills two rows
Row row1 = table.AddRow();
Row row2 = table.AddRow();
row1.TopPadding = 1.5;
row1.Cells[0].Shading.Color = Colors.LightGray;
row1.Cells[0].VerticalAlignment = VerticalAlignment.Center;
row1.Cells[1].Format.Alignment = ParagraphAlignment.Left;
row1.Cells[2].Format.Alignment = ParagraphAlignment.Left;
row1.Cells[3].Format.Alignment = ParagraphAlignment.Left;
row1.Cells[4].Format.Alignment = ParagraphAlignment.Left;
row1.Cells[5].Format.Alignment = ParagraphAlignment.Left;
row1.Cells[6].Format.Alignment = ParagraphAlignment.Left;
paragraph = row1.Cells[1].AddParagraph();
paragraph.AddFormattedText(item.Title, TextFormat.Bold);
row2.Cells[1].AddParagraph(item.Quantity.ToString());
row2.Cells[2].AddParagraph("$" + price.ToString("0.00"));
row2.Cells[3].AddParagraph("$" + discount.ToString("0.0"));
row2.Cells[4].AddParagraph();
row2.Cells[5].AddParagraph("$" + price.ToString("0.00"));
decimal extendedPrice = quantity * price;
extendedPrice = extendedPrice * (100 - discount) / 100;
row1.Cells[5].AddParagraph("$" + extendedPrice.ToString("0.00"));
row1.Cells[5].VerticalAlignment = VerticalAlignment.Bottom;
totalExtendedPrice += extendedPrice;
table.SetEdge(0, table.Rows.Count - 2, 6, 2, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 0.75);
}
// Add an invisible row as a space line to the table
Row row = table.AddRow();
row.Borders.Visible = false;
// Add the total price row
row = table.AddRow();
row.Cells[0].Borders.Visible = false;
row.Cells[0].AddParagraph("Total Price");
row.Cells[0].Format.Font.Bold = true;
row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
row.Cells[0].MergeRight = 4;
row.Cells[5].AddParagraph(totalExtendedPrice.ToString("0.00") + " €");
// Add the VAT row
row = table.AddRow();
row.Cells[0].Borders.Visible = false;
row.Cells[0].AddParagraph("VAT (19%)");
row.Cells[0].Format.Font.Bold = true;
row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
row.Cells[0].MergeRight = 4;
row.Cells[5].AddParagraph((0.19m * totalExtendedPrice).ToString("0.00") + " €");
// Add the additional fee row
row = table.AddRow();
row.Cells[0].Borders.Visible = false;
row.Cells[0].AddParagraph("Shipping and Handling");
row.Cells[5].AddParagraph(0.ToString("0.00") + " €");
row.Cells[0].Format.Font.Bold = true;
row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
row.Cells[0].MergeRight = 4;
// Add the total due row
row = table.AddRow();
row.Cells[0].AddParagraph("Total Due");
row.Cells[0].Borders.Visible = false;
row.Cells[0].Format.Font.Bold = true;
row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
row.Cells[0].MergeRight = 4;
totalExtendedPrice += 0.19m * totalExtendedPrice;
row.Cells[5].AddParagraph(totalExtendedPrice.ToString("0.00") + " €");
// Set the borders of the specified cell range
table.SetEdge(5, table.Rows.Count - 4, 1, 4, Edge.Box, MigraDoc.DocumentObjectModel.BorderStyle.Single, 0.75);
// Add the notes paragraph
paragraph = document.LastSection.AddParagraph();
paragraph.Format.SpaceBefore = "1cm";
paragraph.Format.Borders.Width = 0.75;
paragraph.Format.Borders.Distance = 3;
paragraph.Format.Borders.Color = Colors.DarkBlue;
paragraph.Format.Shading.Color = Colors.LightGray;
}
}
Easiest solution would be to put the value in a Session
Session.Add("ProductCode", ((DataRow)((DataRowView)e.Row.DataItem).Row)["ProductCode"].ToString());
To get the value:
Session["ProductCode"].ToString()
Keep in mind though that you are doing this in the item databound, in the event that you are expecting multiple values for product code, I would suggest storing the values in a collection prior to putting it in the Session.
i.e.
if(Session["ProductCode"] != null)
{
List<string> pcodes = Session["ProductCode"] as List<string>();
pcodes.Add(((DataRow)((DataRowView)e.Row.DataItem).Row)["ProductCode"].ToString());
Session.Add("ProductCode", pcodes);
}
else
{
List<string> pcodes = new List<string>();
pcodes.Add(((DataRow)((DataRowView)e.Row.DataItem).Row)["ProductCode"].ToString());
Session.Add("ProductCode", pcodes);
}
To get the values:
Session["ProductCode"] as List<string>()
Hello everyone i am working on a project which requires me to export some data to excel on a button click using open xml.Here is the class i am using for exporting to excel:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Drawing.Spreadsheet;
using _14junexcel.Account;
namespace _14junexcel
{
public class CreateExcelOpen
{
public void BuildWorkbook1(string filename)
{
string sFile = #"D:\\ExcelOpenXmlWithImageAndStyles.xlsx";
if (File.Exists(sFile))
{
File.Delete(sFile);
}
BuildWorkbook(sFile);
}
private static void BuildWorkbook(string filename)
{
try
{
using (SpreadsheetDocument xl = SpreadsheetDocument.Create(filename, SpreadsheetDocumentType.Workbook))
{
WorkbookPart wbp = xl.AddWorkbookPart();
WorksheetPart wsp = wbp.AddNewPart<WorksheetPart>();
Workbook wb = new Workbook();
FileVersion fv = new FileVersion();
fv.ApplicationName = "Microsoft Office Excel";
Worksheet ws = new Worksheet();
SheetData sd = new SheetData();
WorkbookStylesPart wbsp = wbp.AddNewPart<WorkbookStylesPart>();
wbsp.Stylesheet = CreateStylesheet();
wbsp.Stylesheet.Save();
string sImagePath = #"C:\\Users\\Public\\Pictures\\Sample Pictures\\Jellyfish.jpg";
DrawingsPart dp = wsp.AddNewPart<DrawingsPart>();
ImagePart imgp = dp.AddImagePart(ImagePartType.Png, wsp.GetIdOfPart(dp));
using (FileStream fs = new FileStream(sImagePath, FileMode.Open))
{
imgp.FeedData(fs);
}
NonVisualDrawingProperties nvdp = new NonVisualDrawingProperties();
nvdp.Id = 1025;
nvdp.Name = "Picture 1";
nvdp.Description = "polymathlogo";
DocumentFormat.OpenXml.Drawing.PictureLocks picLocks = new DocumentFormat.OpenXml.Drawing.PictureLocks();
picLocks.NoChangeAspect = true;
picLocks.NoChangeArrowheads = true;
NonVisualPictureDrawingProperties nvpdp = new NonVisualPictureDrawingProperties();
nvpdp.PictureLocks = picLocks;
NonVisualPictureProperties nvpp = new NonVisualPictureProperties();
nvpp.NonVisualDrawingProperties = nvdp;
nvpp.NonVisualPictureDrawingProperties = nvpdp;
DocumentFormat.OpenXml.Drawing.Stretch stretch = new DocumentFormat.OpenXml.Drawing.Stretch();
stretch.FillRectangle = new DocumentFormat.OpenXml.Drawing.FillRectangle();
BlipFill blipFill = new BlipFill();
DocumentFormat.OpenXml.Drawing.Blip blip = new DocumentFormat.OpenXml.Drawing.Blip();
blip.Embed = dp.GetIdOfPart(imgp);
blip.CompressionState = DocumentFormat.OpenXml.Drawing.BlipCompressionValues.Print;
blipFill.Blip = blip;
blipFill.SourceRectangle = new DocumentFormat.OpenXml.Drawing.SourceRectangle();
blipFill.Append(stretch);
DocumentFormat.OpenXml.Drawing.Transform2D t2d = new DocumentFormat.OpenXml.Drawing.Transform2D();
DocumentFormat.OpenXml.Drawing.Offset offset = new DocumentFormat.OpenXml.Drawing.Offset();
offset.X = 0;
offset.Y = 0;
t2d.Offset = offset;
Bitmap bm = new Bitmap(sImagePath);
//http://en.wikipedia.org/wiki/English_Metric_Unit#DrawingML
//http://stackoverflow.com/questions/1341930/pixel-to-centimeter
//http://stackoverflow.com/questions/139655/how-to-convert-pixels-to-points-px-to-pt-in-net-c
DocumentFormat.OpenXml.Drawing.Extents extents = new DocumentFormat.OpenXml.Drawing.Extents();
extents.Cx = (long)bm.Width * (long)((float)0 / bm.HorizontalResolution);
extents.Cy = (long)bm.Height * (long)((float)0 / bm.VerticalResolution);
bm.Dispose();
t2d.Extents = extents;
ShapeProperties sp = new ShapeProperties();
sp.BlackWhiteMode = DocumentFormat.OpenXml.Drawing.BlackWhiteModeValues.Auto;
sp.Transform2D = t2d;
DocumentFormat.OpenXml.Drawing.PresetGeometry prstGeom = new DocumentFormat.OpenXml.Drawing.PresetGeometry();
prstGeom.Preset = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle;
prstGeom.AdjustValueList = new DocumentFormat.OpenXml.Drawing.AdjustValueList();
sp.Append(prstGeom);
sp.Append(new DocumentFormat.OpenXml.Drawing.NoFill());
DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture picture = new DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture();
picture.NonVisualPictureProperties = nvpp;
picture.BlipFill = blipFill;
picture.ShapeProperties = sp;
Position pos = new Position();
pos.X = 0;
pos.Y = 0;
Extent ext = new Extent();
ext.Cx = extents.Cx;
ext.Cy = extents.Cy;
AbsoluteAnchor anchor = new AbsoluteAnchor();
anchor.Position = pos;
anchor.Extent = ext;
anchor.Append(picture);
anchor.Append(new ClientData());
WorksheetDrawing wsd = new WorksheetDrawing();
wsd.Append(anchor);
Drawing drawing = new Drawing();
drawing.Id = dp.GetIdOfPart(imgp);
wsd.Save(dp);
UInt32 index;
Random rand = new Random();
sd.Append(CreateHeader(2));
sd.Append(CreateColumnHeader(4));
for (index = 5; index < 6; ++index)
{
sd.Append(CreateContent(index, ref rand));
}
ws.Append(sd);
ws.Append(drawing);
wsp.Worksheet = ws;
wsp.Worksheet.Save();
Sheets sheets = new Sheets();
Sheet sheet = new Sheet();
sheet.Name = "Sheet1";
sheet.SheetId = 1;
sheet.Id = wbp.GetIdOfPart(wsp);
sheets.Append(sheet);
wb.Append(fv);
wb.Append(sheets);
xl.WorkbookPart.Workbook = wb;
xl.WorkbookPart.Workbook.Save();
//xl.WorkbookPart.Workbook.Save();
xl.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
Console.ReadLine();
}
}
private static Stylesheet CreateStylesheet()
{
Stylesheet ss = new Stylesheet();
Fonts fts = new Fonts();
DocumentFormat.OpenXml.Spreadsheet.Font ft = new DocumentFormat.OpenXml.Spreadsheet.Font();
FontName ftn = new FontName();
ftn.Val = StringValue.FromString("Calibri");
FontSize ftsz = new FontSize();
ftsz.Val = DoubleValue.FromDouble(11);
ft.FontName = ftn;
ft.FontSize = ftsz;
fts.Append(ft);
ft = new DocumentFormat.OpenXml.Spreadsheet.Font();
ftn = new FontName();
ftn.Val = StringValue.FromString("Palatino Linotype");
ftsz = new FontSize();
ftsz.Val = DoubleValue.FromDouble(18);
ft.FontName = ftn;
ft.FontSize = ftsz;
fts.Append(ft);
fts.Count = UInt32Value.FromUInt32((uint)fts.ChildElements.Count);
Fills fills = new Fills();
Fill fill;
PatternFill patternFill;
fill = new Fill();
patternFill = new PatternFill();
patternFill.PatternType = PatternValues.None;
fill.PatternFill = patternFill;
fills.Append(fill);
fill = new Fill();
patternFill = new PatternFill();
patternFill.PatternType = PatternValues.Gray125;
fill.PatternFill = patternFill;
fills.Append(fill);
fill = new Fill();
patternFill = new PatternFill();
patternFill.PatternType = PatternValues.Solid;
patternFill.ForegroundColor = new ForegroundColor();
patternFill.ForegroundColor.Rgb = HexBinaryValue.FromString("00ff9728");
patternFill.BackgroundColor = new BackgroundColor();
patternFill.BackgroundColor.Rgb = patternFill.ForegroundColor.Rgb;
fill.PatternFill = patternFill;
fills.Append(fill);
fills.Count = UInt32Value.FromUInt32((uint)fills.ChildElements.Count);
Borders borders = new Borders();
Border border = new Border();
border.LeftBorder = new LeftBorder();
border.RightBorder = new RightBorder();
border.TopBorder = new TopBorder();
border.BottomBorder = new BottomBorder();
border.DiagonalBorder = new DiagonalBorder();
borders.Append(border);
border = new Border();
border.LeftBorder = new LeftBorder();
border.LeftBorder.Style = BorderStyleValues.Thin;
border.RightBorder = new RightBorder();
border.RightBorder.Style = BorderStyleValues.Thin;
border.TopBorder = new TopBorder();
border.TopBorder.Style = BorderStyleValues.Thin;
border.BottomBorder = new BottomBorder();
border.BottomBorder.Style = BorderStyleValues.Thin;
border.DiagonalBorder = new DiagonalBorder();
borders.Append(border);
borders.Count = UInt32Value.FromUInt32((uint)borders.ChildElements.Count);
CellStyleFormats csfs = new CellStyleFormats();
CellFormat cf = new CellFormat();
cf.NumberFormatId = 0;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 1;
csfs.Append(cf);
csfs.Count = UInt32Value.FromUInt32((uint)csfs.ChildElements.Count);
uint iExcelIndex = 164;
NumberingFormats nfs = new NumberingFormats();
CellFormats cfs = new CellFormats();
cf = new CellFormat();
cf.NumberFormatId = 0;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 0;
cf.FormatId = 0;
cfs.Append(cf);
NumberingFormat nfDateTime = new NumberingFormat();
nfDateTime.NumberFormatId = UInt32Value.FromUInt32(iExcelIndex++);
nfDateTime.FormatCode = StringValue.FromString("dd/mm/yyyy hh:mm:ss");
nfs.Append(nfDateTime);
NumberingFormat nf4decimal = new NumberingFormat();
nf4decimal.NumberFormatId = UInt32Value.FromUInt32(iExcelIndex++);
nf4decimal.FormatCode = StringValue.FromString("#,##0.0000");
nfs.Append(nf4decimal);
// #,##0.00 is also Excel style index 4
NumberingFormat nf2decimal = new NumberingFormat();
nf2decimal.NumberFormatId = UInt32Value.FromUInt32(iExcelIndex++);
nf2decimal.FormatCode = StringValue.FromString("#,##0.00");
nfs.Append(nf2decimal);
// # is also Excel style index 49
NumberingFormat nfForcedText = new NumberingFormat();
nfForcedText.NumberFormatId = UInt32Value.FromUInt32(iExcelIndex++);
nfForcedText.FormatCode = StringValue.FromString("#");
nfs.Append(nfForcedText);
//Alignment
Alignment align = new Alignment(){Horizontal = HorizontalAlignmentValues.General,Vertical=VerticalAlignmentValues.Center};
//wraptext
// Alignment align1 = new Alignment(){Horizontal=HorizontalAlignmentValues.CenterContinuous,Vertical=VerticalAlignmentValues.Center};
// index 1
cf = new CellFormat();
cf.NumberFormatId = nfDateTime.NumberFormatId;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId = 0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
// index 2
cf = new CellFormat();
cf.NumberFormatId = nf4decimal.NumberFormatId;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId = 0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
// index 3
cf = new CellFormat();
cf.NumberFormatId = nf2decimal.NumberFormatId;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId = 0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
// index 4
cf = new CellFormat();
cf.NumberFormatId = nfForcedText.NumberFormatId;
cf.FontId = 0;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId = 0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
// index 5
// Header text
cf = new CellFormat();
cf.NumberFormatId = nfForcedText.NumberFormatId;
cf.FontId = 1;
cf.FillId = 0;
cf.BorderId = 0;
cf.FormatId = 0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
// index 6
// column text
cf = new CellFormat();
cf.NumberFormatId = nfForcedText.NumberFormatId;
cf.FontId = 1;
cf.FillId = 1;
cf.BorderId = 1;
cf.FormatId = 1;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
// index 7
// coloured 2 decimal text
cf = new CellFormat();
cf.NumberFormatId = nf2decimal.NumberFormatId;
cf.FontId = 0;
//cf.FillId = 2;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId =0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
//cf.Append(align);
cf.Append(align);
// index 8
// coloured column text
cf = new CellFormat();
cf.NumberFormatId = nfForcedText.NumberFormatId;
cf.FontId = 0;
//cf.FillId = 2;
cf.FillId = 0;
cf.BorderId = 1;
cf.FormatId = 0;
cf.ApplyNumberFormat = BooleanValue.FromBoolean(true);
cfs.Append(cf);
nfs.Count = UInt32Value.FromUInt32((uint)nfs.ChildElements.Count);
cfs.Count = UInt32Value.FromUInt32((uint)cfs.ChildElements.Count);
ss.Append(nfs);
ss.Append(fts);
ss.Append(fills);
ss.Append(borders);
ss.Append(csfs);
ss.Append(cfs);
CellStyles css = new CellStyles();
CellStyle cs = new CellStyle();
cs.Name = StringValue.FromString("Normal");
cs.FormatId = 0;
cs.BuiltinId = 0;
css.Append(cs);
css.Count = UInt32Value.FromUInt32((uint)css.ChildElements.Count);
ss.Append(css);
DifferentialFormats dfs = new DifferentialFormats();
dfs.Count = 0;
ss.Append(dfs);
TableStyles tss = new TableStyles();
tss.Count = 0;
tss.DefaultTableStyle = StringValue.FromString("TableStyleMedium9");
tss.DefaultPivotStyle = StringValue.FromString("PivotStyleLight16");
ss.Append(tss);
return ss;
}
private static Row CreateHeader(UInt32 index)
{
Row r = new Row();
r.RowIndex = index;
Cell c = new Cell();
c.DataType = CellValues.String;
c.StyleIndex = 5;
c.CellReference = "A" + index.ToString();
c.CellValue = new CellValue("REPORT");
r.Append(c);
return r;
}
private static Row CreateColumnHeader(UInt32 index)
{
Row r = new Row();
r.RowIndex = index;
Cell c;
c = new Cell();
c.DataType = CellValues.String;
c.StyleIndex = 7;
c.CellReference = "A" + index.ToString();
c.CellValue = new CellValue("Retail Customer Group");
r.Append(c);
c = new Cell();
c.DataType = CellValues.String;
c.StyleIndex = 7;
c.CellReference = "B" + index.ToString();
c.CellValue = new CellValue("Product Promotion Group");
r.Append(c);
return r;
}
private static Row CreateContent(UInt32 index, ref Random rd)
{
Row r = new Row();
r.RowIndex = index;
Cell c;
c = new Cell();
c.StyleIndex = 7;
c.CellReference = "A" + index.ToString();
//c.CellValue = new CellValue(rd.Next(1000000000).ToString());
c.CellValue = new CellValue("12334");
r.Append(c);
DateTime dtEpoch = new DateTime(1900, 1, 1, 0, 0, 0, 0);
DateTime dt = dtEpoch.AddDays(rd.NextDouble() * 100000.0);
TimeSpan ts = dt - dtEpoch;
double fExcelDateTime;
// Excel has "bug" of treating 29 Feb 1900 as valid
// 29 Feb 1900 is 59 days after 1 Jan 1900, so just skip to 1 Mar 1900
if (ts.Days >= 59)
{
fExcelDateTime = ts.TotalDays + 2.0;
}
else
{
fExcelDateTime = ts.TotalDays + 1.0;
}
c = new Cell();
c.StyleIndex = 7;
c.CellReference = "B" + index.ToString();
c.CellValue = new CellValue("124515");
//c.CellValue = new CellValue(fExcelDateTime.ToString());
r.Append(c);
return r;
}
}
}
and this is the function for button click :
protected void Button1_Click(object sender, EventArgs e)
{
string qwe = TextBox1.Text;
string ert = TextBox2.Text;
string filename = #"D:\\ExcelOpenXmlWithImageAndStyles.xlsx";
CreateExcelOpen exp = new CreateExcelOpen();
exp.BuildWorkbook1(filename);
}
here are my requirements:
1.I need to pass the values of two textboxes to the two cells(which now contain values 12334 and 124515).
2. The heading column does not adjust itself to accomodate the values which i have provided(Retail customer group etc).Please suggest the
modifications required in this class to enable the autofit.
Thank you.
In Your CreateContent method you have hard coded values like:
c.CellValue = new CellValue("12334");
change it with values of text boxes that you want to show.
for setting width of headers, you will have to add columns along with Cells as you need columns to define the width, following article will be of some help for you:
http://catalog.codeproject.com/script/Articles/ArticleVersion.aspx?aid=371203&av=543408
I wrote my own export to Excel writer. It is fast and allows for substantial formatting of the cells. You can review it at
https://openxmlexporttoexcel.codeplex.com/
I hope it helps.
I've spent a lot of time googling OpenXml related questions.
I finally found a solution to my problems by combining OpenXml features with Excel VBA.
So,
I have Excel - macro enabled file (xlsm) as template for my project.
Whatever logic is hard to implement in OpenXml I moved to VBA.
For AutoFit for example it is as easy as:
Sub Workbook_Open()
ActiveSheet.Columns.AutoFit
End Sub
Hope it may help.
I've added an header and a footer on my document by PdfPageEventHelper.
The document has several "large" tables populated at runtime.
I've tried to add those tables simply by "documen.Add(table)", but my header and my footer results overwritten.
I've already tried both methods to add the tables (WriteSelectedRows and document.Add(myPdfPtable).
Here is the code of the PageEventHelper:
private class MyPageEventHandler : PdfPageEventHelper
{
public iTextSharp.text.Image ImageHeader { get; set; }
public iTextSharp.text.Image ImageFooter { get; set; }
public override void OnEndPage(PdfWriter writer, Document document)
{
var fontintestazione = FontFactory.GetFont("Verdana", 10, Font.BOLD, BaseColor.LIGHT_GRAY);
var fontRight = FontFactory.GetFont("Verdana", 8, Font.BOLD, BaseColor.WHITE);
var fontFooter = FontFactory.GetFont("Verdana", 6, Font.NORMAL, BaseColor.BLUE);
float cellHeight = document.TopMargin;
Rectangle page = document.PageSize;
PdfPTable head = new PdfPTable(3);
head.TotalWidth = page.Width;
PdfPCell c = new PdfPCell(ImageHeader, true);
c.HorizontalAlignment = Element.ALIGN_LEFT;
c.FixedHeight = cellHeight;
c.Border = PdfPCell.NO_BORDER;
head.AddCell(c);
c = new PdfPCell(new Phrase("somePhrase", fontintestazione));
c.Border = PdfPCell.NO_BORDER;
head.AddCell(c);
c = new PdfPCell(new Phrase("someTextBlah", fontRight));
c.Border = PdfPCell.NO_BORDER;
c.HorizontalAlignment = 1;
c.BackgroundColor = new BaseColor(70, 130, 180);
head.AddCell(c);
head.WriteSelectedRows(0, -1, 10, page.Height - cellHeight + head.TotalHeight -30, writer.DirectContent);
PdfPTable footer = new PdfPTable(2);
footer.TotalWidth = 316f;
float[] cfWidths = new float[] { 2f, 1f };
footer.SetWidths(cfWidths);
PdfPCell cf = new PdfPCell(ImageFooter, true);
cf.HorizontalAlignment = Element.ALIGN_RIGHT;
cf.FixedHeight = cellHeight;
cf.Border = PdfPCell.NO_BORDER;
footer.AddCell(cf);
cf = new PdfPCell(new Phrase("someEndingText", fontFooter));
cf.HorizontalAlignment = Element.ALIGN_LEFT;
cf.Border = PdfPCell.NO_BORDER;
footer.AddCell(cf);
footer.WriteSelectedRows(0, -1, 10, 50, writer.DirectContent);
}
On my page, i simply do:
var document = new Document(PageSize.A4);
var output = new MemoryStream();
var writer = PdfWriter.GetInstance(document, output);
iTextSharp.text.Image imageHeader = iTextSharp.text.Image.GetInstance(Server.MapPath("/images/header.ong"));
iTextSharp.text.Image imageFooter = iTextSharp.text.Image.GetInstance(Server.MapPath("/images/footer.png"));
MyPageEventHandler eve = new MyPageEventHandler
{
ImageHeader = imageHeader ,
ImageFooter = imageFooter
};
writer.PageEvent = eve;
document.Open();
//adding a table
PdfPTable cvTable = new PdfPtable(3);
cvTable.TotalWidth = document.PageSize.Width;
PdfPCell hCell = new PdfPCell(new Phrase("Jobs By User", aCustomFont));
cvTable.AddCell(hCell);
for(int i = 0; i < myTable.Records.Count; i++)
{
PdfPCell idCell = new PdfPCell(new Phrase(myTable.Records[i]._id, aFont));
cvTable.Add(idCell);
//same stuff for other fields of table
}
//first attempt.... failed:
document.Add(cvTable) //<- header and footer are overwritten by table
//second attempt..... failed too...
cvTable.WriteSelectedRows(0, -1, 10, myPoisition, writer.DirectContent);
//kind of fail...:
//the table is large and need more pages. It is trunked on the first page and overwrite
//the footer.
In your OnEndPage method you have this line:
head.WriteSelectedRows(0, -1, 10, page.Height - cellHeight + head.TotalHeight - 30, writer.DirectContent);
That code correctly calculates where to put content based on the page's height and top margin but also includes a magical 30 in there which is causing the header to be drawn on top of the table. Change it to this and your header will be fine.
head.WriteSelectedRows(0, -1, 10, page.Height - cellHeight + head.TotalHeight, writer.DirectContent);
I'm guessing that that 30 is trying to include some padding between your header and the table itself. What I would recommend is actually changing the document's margins themselves in the main code:
document.SetMargins(document.LeftMargin, document.RightMargin, document.TopMargin + 30, document.BottomMargin);
And then accounting for that in the OnEndPage method:
float cellHeight = document.TopMargin - 30;
Your footer code doesn't actually account for the bottom margin and just draws it at 50 so this will always overlap. The quick fix would be to change it to:
footer.WriteSelectedRows(0, -1, 10, footer.TotalHeight, writer.DirectContent);
This will at least get the footer bottom-aligned. If you want some more padding like above just adjust the document margins again:
document.SetMargins(document.LeftMargin, document.RightMargin, document.TopMargin + 30, document.BottomMargin + 30);