public FileStreamResult pdf(int Id) { MemoryStream workStream = new MemoryStream(); Document document = new Document(); PdfWriter.GetInstance(document, workStream).CloseStream = false; document.Open(); Font font_heading_1 = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 19, Font.BOLD); Font font_body = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 9); // Create the heading paragraph with the headig font Paragraph paragraph; paragraph = new Paragraph("Hello world!", font_heading_1); // Add a horizontal line below the headig text and add it to the paragraph iTextSharp.text.pdf.draw.VerticalPositionMark seperator = new iTextSharp.text.pdf.draw.LineSeparator(); seperator.Offset = -6f; paragraph.Add(seperator); //document.Add(new Header("Technology","Technology Report")); //document.Add(new Paragraph("Hello World")); //document.Add(new Paragraph(DateTime.Now.ToString())); document.Close(); byte[] byteInfo = workStream.ToArray(); workStream.Write(byteInfo, 0, byteInfo.Length); workStream.Position = 0; return(new FileStreamResult(workStream, "application/pdf")); }
public static Paragraph GetLineSeparator() { Paragraph LineSeparator = new Paragraph(" "); iTextSharp.text.pdf.draw.VerticalPositionMark seperator = new iTextSharp.text.pdf.draw.LineSeparator(); seperator.Offset = -4f; LineSeparator.Add(seperator); return(LineSeparator); }
// Este método cria um cabeçalho para o documento public override void OnStartPage(PdfWriter writer, Document document) { // Cria um novo paragrafo com o texto do cabeçalho Paragraph ph = null; document.Add(logotipo); //Rectangle rect = new Rectangle(10f, 30f); //rect.BorderColor = BaseColor.LIGHT_GRAY; //rect.BackgroundColor = BaseColor.GREEN; //rect.BorderWidth = 2f; //rect.Chunks.Add(new Chunk("Exmo.(s) Sr.(s) ")); //rect.Chunks.Add(new Chunk("SBDE, Lda. ")); //document.Add(rect); // adiciono a linha e posteriormente mais linhas que podem ser necessárias em um cabeçalho de relatório ph = new Paragraph("Exmo.(s) Sr.(s) ", fonte); ph.Alignment = 2; document.Add(ph); ph = new Paragraph("SBDE, Lda. ", fonte); ph.Alignment = 2; document.Add(ph); ph = new Paragraph("Luanda", fonte); ph.Alignment = 2; document.Add(ph); // cria um novo paragrafo para imprimir um traço e uma linha em branco ph = new Paragraph(); iTextSharp.text.pdf.draw.LineSeparator lineseparator = new iTextSharp.text.pdf.draw.LineSeparator(); lineseparator.LineColor = BaseColor.LIGHT_GRAY; // cria um objeto sepatador (um traço) iTextSharp.text.pdf.draw.VerticalPositionMark seperator = lineseparator; // adiciona o separador ao paragravo ph.Add(seperator); // adiciona a linha em branco(enter) ao paragrafo ph.Add(new Chunk("\n")); // imprime o pagagrafo no documento document.Add(ph); }
public void SaveDataGridViewToPDF(DataGridView Dv, string FilePath) { string folderPath = Environment.CurrentDirectory + "\\Relatório\\"; //"C:\\PDFs\\"; if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } iTextSharp.text.FontFactory.RegisterDirectories(); iTextSharp.text.Font myfont = iTextSharp.text.FontFactory.GetFont("Tahoma", BaseFont.IDENTITY_H, 15, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK); iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10f, 10f, 10f, 0f); pdfDoc.Open(); PdfWriter wri = PdfWriter.GetInstance(pdfDoc, new FileStream(FilePath + "Extrato da conta.pdf", FileMode.Create)); pdfDoc.Open(); PdfPTable _mytable = new PdfPTable(Dv.ColumnCount - 4); float[] widths = new float[] { 2.1f, 5f, 1.5f, 1.6f, 1.5f }; _mytable.SetWidths(widths); _mytable.WidthPercentage = 90; //_mytable.DefaultCell.Border = Rectangle.NO_BORDER; _mytable.DefaultCell.BorderColor = new iTextSharp.text.BaseColor(System.Drawing.Color.White); iTextSharp.text.Paragraph ph = new iTextSharp.text.Paragraph("Extrato da conta ", myfont); ph.Alignment = iTextSharp.text.Element.ALIGN_CENTER; pdfDoc.Add(ph); myfont = iTextSharp.text.FontFactory.GetFont("Tahoma", BaseFont.IDENTITY_H, 9, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); ph = new iTextSharp.text.Paragraph("Conta: " + cmbContas.Text, myfont); ph.Alignment = iTextSharp.text.Element.ALIGN_CENTER; pdfDoc.Add(ph); // adiciona a linha em branco(enter) ao paragrafo ph.Add(new iTextSharp.text.Chunk("\n")); ph = new iTextSharp.text.Paragraph("Período: " + dtDataIni.Text + " até " + dtDataFinal.Text, myfont); pdfDoc.Add(ph); ph = new iTextSharp.text.Paragraph("Dada de emissão: " + DateTime.Now, myfont); pdfDoc.Add(ph); ph = new iTextSharp.text.Paragraph(); // cria um objeto sepatador (um traço) iTextSharp.text.pdf.draw.VerticalPositionMark seperator = new iTextSharp.text.pdf.draw.LineSeparator(); // adiciona o separador ao paragravo ph.Add(seperator); // adiciona a linha em branco(enter) ao paragrafo ph.Add(new iTextSharp.text.Chunk("\n")); // imprime o pagagrafo no documento // pdfDoc.Add(ph); ph.Add(new iTextSharp.text.Chunk("\n")); pdfDoc.Add(ph); myfont = iTextSharp.text.FontFactory.GetFont("Tahoma", BaseFont.IDENTITY_H, 8, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK); for (int j = 0; j < Dv.Columns.Count; ++j) { if (Dv.Columns[j].HeaderText != "codigo" && Dv.Columns[j].HeaderText != "tipo" && Dv.Columns[j].HeaderText != "codigo_conta" && Dv.Columns[j].HeaderText != "valor") { iTextSharp.text.Phrase p = new iTextSharp.text.Phrase(Dv.Columns[j].HeaderText, myfont); PdfPCell cell = new PdfPCell(p); cell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER; cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL; cell.BorderWidth = 0; _mytable.AddCell(cell); } } myfont = iTextSharp.text.FontFactory.GetFont("Tahoma", BaseFont.IDENTITY_H, 9, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); //------------------------- for (int i = 0; i < Dv.Rows.Count; ++i) { for (int j = 0; j < Dv.Columns.Count; ++j) { if (Dv.Columns[j].HeaderText != "codigo" && Dv.Columns[j].HeaderText != "tipo" && Dv.Columns[j].HeaderText != "codigo_conta" && Dv.Columns[j].HeaderText != "valor") { iTextSharp.text.Phrase p = new iTextSharp.text.Phrase();// Dv.Rows[i].Cells[j].Value == null ? null : Dv.Rows[i].Cells[j].Value.ToString(), myfont); PdfPCell cell = new PdfPCell(); if (Dv.Columns[j].HeaderText == "Saldo" || Dv.Columns[j].HeaderText == "Saída/ Débito" || Dv.Columns[j].HeaderText == "Entrada/Crédito") { myfont = iTextSharp.text.FontFactory.GetFont("Tahoma", BaseFont.IDENTITY_H, 9, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); if (Dv.Columns[j].HeaderText == "Saída/ Débito") { myfont = iTextSharp.text.FontFactory.GetFont("Tahoma", BaseFont.IDENTITY_H, 9, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.RED); } else if (Dv.Columns[j].HeaderText == "Entrada/Crédito") { myfont = iTextSharp.text.FontFactory.GetFont("Tahoma", BaseFont.IDENTITY_H, 9, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLUE); } else if (Dv.Columns[j].HeaderText == "Saldo") { var saldo = Dv.Rows[i].Cells[j].Value == null ? 0 : Convert.ToDouble(Dv.Rows[i].Cells[j].Value); if (saldo < 0 && i == Dv.Rows.Count - 1) { myfont = iTextSharp.text.FontFactory.GetFont("Tahoma", BaseFont.IDENTITY_H, 9, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.RED); } } p = new iTextSharp.text.Phrase(Dv.Rows[i].Cells[j].Value == null ? null : Convert.ToDecimal(Dv.Rows[i].Cells[j].Value.ToString()).ToString("N2"), myfont); cell = new PdfPCell(p); cell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT; if (i == 0 || i == Dv.Rows.Count - 1) { cell.BackgroundColor = new iTextSharp.text.BaseColor(System.Drawing.Color.Silver); } } else if (Dv.Columns[j].HeaderText == "Data de lançamento" && Dv.Rows[i].Cells[j + 1].Value.ToString() == "SALDO ANTERIOR" || Dv.Rows[i].Cells[j + 1].Value.ToString() == "SALDO ATUAL CONTA") { p = new iTextSharp.text.Phrase(Dv.Rows[i].Cells[j].Value == null ? null : Convert.ToDateTime(Dv.Rows[i].Cells[j].Value.ToString()).ToString("dd/MM/yyyy"), myfont); cell = new PdfPCell(p); cell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT; if (i == 0 || i == Dv.Rows.Count - 1) { cell.BackgroundColor = new iTextSharp.text.BaseColor(System.Drawing.Color.Silver); } } else { p = new iTextSharp.text.Phrase(Dv.Rows[i].Cells[j].Value == null ? null : Dv.Rows[i].Cells[j].Value.ToString(), myfont); cell = new PdfPCell(p); cell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT; if (i == 0 || i == Dv.Rows.Count - 1) { cell.BackgroundColor = new iTextSharp.text.BaseColor(System.Drawing.Color.Silver); } } cell.BorderWidth = 0; // _mytable.DefaultCell.BorderWidth = 0; cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL; _mytable.AddCell(cell); } } } //------------------------ pdfDoc.Add(_mytable); pdfDoc.Close(); System.Diagnostics.Process.Start(FilePath); }
/// <summary> /// Add text at the X Y position; multiple lines handled /// </summary> private void addText(float x, float y, float width, float height, string[] textLines, StyleInfo styleInfo, float[] textWidths, bool wrap, string url, bool noClip, string tooltip) { RenderFont renderFont = RenderUtility.GetRenderFont(styleInfo); BaseFont baseFont = null; //convert the render font type to iTextSharp type int fontType = 0; switch (renderFont.Style) { case RenderFont.FontStyle.Bold: fontType = iTextSharp.text.Font.BOLD; break; case RenderFont.FontStyle.Italic: fontType = iTextSharp.text.Font.ITALIC; break; case RenderFont.FontStyle.BoldItalic: fontType = iTextSharp.text.Font.BOLDITALIC; break; default: fontType = iTextSharp.text.Font.NORMAL; break; } //get the index of the font name in the list font name int indexBaseFont = BaseFontNames.FindIndex(delegate(string _fontname) { return _fontname == renderFont.FaceName + "_" + fontType; }); //if not found then add the new BaseFont if (indexBaseFont == -1) { //create a new font or a with a new type baseFont = FontFactory.GetFont(renderFont.FaceName, BaseFont.IDENTITY_H, 0, fontType).BaseFont; //add the font face name and font to the lists BaseFontNames.Add(renderFont.FaceName + "_" + fontType); BaseFonts.Add(baseFont); } else baseFont = BaseFonts[indexBaseFont]; //text alignment int align = 0; //first position x and y and the leading (usefull for all kind of justified text) float firstStartX = -1; float firstStartY = -1; float leading = -1; //chunks of text List<Chunk> chunks = new List<Chunk>(); //loop thru the lines of text for (int i = 0; i < textLines.Length; i++) { string text = textLines[i]; float textwidth = textWidths[i]; float startX = x + styleInfo.PaddingLeft; // TODO: handle tb_rl float startY = y + styleInfo.PaddingTop + (i * styleInfo.FontSize); // TODO: handle tb_rl if (styleInfo.WritingMode == WritingModeEnum.lr_tb) { //calculate the x position switch (styleInfo.TextAlign) { case TextAlignEnum.Center: if (width > 0) { startX = x + styleInfo.PaddingLeft + (width - styleInfo.PaddingLeft - styleInfo.PaddingRight) / 2 - textwidth / 2; align = Element.ALIGN_CENTER; } break; case TextAlignEnum.Right: if (width > 0) { startX = x + width - textwidth - styleInfo.PaddingRight - 2; align = Element.ALIGN_RIGHT; } break; case TextAlignEnum.Justified: case TextAlignEnum.JustifiedLine: case TextAlignEnum.JustifiedDottedLine: if (width > 0) { startX += 2; align = Element.ALIGN_JUSTIFIED; } break; case TextAlignEnum.Left: default: if (width > 0) startX += 2; align = Element.ALIGN_LEFT; break; } //calculate the y position switch (styleInfo.VerticalAlign) { case VerticalAlignEnum.Middle: if (height <= 0) break; //calculate the middle of the region startY = y + styleInfo.PaddingTop + (height - styleInfo.PaddingTop - styleInfo.PaddingBottom) / 2 - styleInfo.FontSize / 2; //now go up or down depending on which line if (textLines.Length == 1) break; //even number if (textLines.Length % 2 == 0) startY = startY - ((textLines.Length / 2 - i) * styleInfo.FontSize) + styleInfo.FontSize / 2; else startY = startY - ((textLines.Length / 2 - i) * styleInfo.FontSize); break; case VerticalAlignEnum.Bottom: if (height <= 0) break; startY = y + height - styleInfo.PaddingBottom - (styleInfo.FontSize * (textLines.Length - i)); break; case VerticalAlignEnum.Top: default: break; } } else { //move x in a little - it draws to close to the edge of the rectangle (25% of the font size seems to work!) and Center or right align vertical text startX += styleInfo.FontSize / 4; switch (styleInfo.TextAlign) { case TextAlignEnum.Center: if (height > 0) startY = y + styleInfo.PaddingLeft + (height - styleInfo.PaddingLeft - styleInfo.PaddingRight) / 2 - textwidth / 2; break; case TextAlignEnum.Right: if (width > 0) startY = y + height - textwidth - styleInfo.PaddingRight; break; case TextAlignEnum.Left: default: break; } } //mark the first x position for justify text if (firstStartX == -1) firstStartX = startX; //mark the first y position for justify text if (firstStartY == -1) firstStartY = startY; //mark the first leading height for justify text else if (leading == -1) leading = startY - firstStartY; //draw background rectangle if needed (only put out on the first line, since we do whole rectangle) if (!styleInfo.BackgroundColor.IsEmpty && height > 0 && width > 0 && i == 0) addFillRectangle(x, y, width, height, styleInfo.BackgroundColor); //set the clipping path, (Itext have no clip) if (height > 0 && width > 0) { pdfContent.SetRGBColorFill(styleInfo.Color.R, styleInfo.Color.G, styleInfo.Color.B); if (align == Element.ALIGN_JUSTIFIED) chunks.Add(new Chunk(text)); else { if (styleInfo.WritingMode == WritingModeEnum.lr_tb) { //if textline after measure with word break can fit just simple show Text if (width >= textwidth) { pdfContent.SaveState(); pdfContent.BeginText(); pdfContent.SetFontAndSize(baseFont, styleInfo.FontSize); //same fonts dont have nativelly bold so we could simulate that if (renderFont.SimulateBold) { pdfContent.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE); pdfContent.SetLineWidth(0.2f); } pdfContent.SetTextMatrix(startX, pageHeight - startY - styleInfo.FontSize); pdfContent.ShowText(text); pdfContent.EndText(); pdfContent.RestoreState(); } else { //else use Column text to wrap or clip (wrap: for example a text like an URL so word break is not working here //itextsharp ColumnText do the work for us) ColumnText columnText = new ColumnText(pdfContent); columnText.SetSimpleColumn(new Phrase(text, new iTextSharp.text.Font(baseFont, styleInfo.FontSize)), x + styleInfo.PaddingLeft, pageHeight - startY, x + width - styleInfo.PaddingRight, pageHeight - y - styleInfo.PaddingBottom - height, 10f, align); columnText.Go(); } } else { //not checked double rads = -283.0 / 180.0; double radsCos = Math.Cos(rads); double radsSin = Math.Sin(rads); pdfContent.BeginText(); pdfContent.SetFontAndSize(baseFont, styleInfo.FontSize); pdfContent.SetTextMatrix((float)radsCos, (float)radsSin, (float)-radsSin, (float)radsCos, startX, pageHeight - startY); pdfContent.ShowText(text); pdfContent.EndText(); } } //add URL if (url != null) document.Add(new Annotation(x, pageHeight - y, height, width, url)); //add tooltip if (tooltip != null) document.Add(new Annotation(x, pageHeight - y, height, width, tooltip)); } //handle underlining etc ... float maxX; switch (styleInfo.TextDecoration) { case TextDecorationEnum.Underline: maxX = width > 0 ? Math.Min(x + width, startX + textwidth) : startX + textwidth; addLine(startX, startY + styleInfo.FontSize + 1, maxX, startY + styleInfo.FontSize + 1, 1, styleInfo.Color, BorderStyleEnum.Solid); break; case TextDecorationEnum.LineThrough: maxX = width > 0 ? Math.Min(x + width, startX + textwidth) : startX + textwidth; addLine(startX, startY + (styleInfo.FontSize / 2) + 1, maxX, startY + (styleInfo.FontSize / 2) + 1, 1, styleInfo.Color, BorderStyleEnum.Solid); break; case TextDecorationEnum.Overline: maxX = width > 0 ? Math.Min(x + width, startX + textwidth) : startX + textwidth; addLine(startX, startY + 1, maxX, startY + 1, 1, styleInfo.Color, BorderStyleEnum.Solid); break; case TextDecorationEnum.None: default: break; } } //add text to justify if (chunks.Count > 0) { Paragraph paragraph = new Paragraph(); paragraph.Alignment = align; paragraph.Leading = leading; paragraph.Font = new iTextSharp.text.Font(baseFont, styleInfo.FontSize); //join all text (is necessary to justify alignment) foreach (Chunk chunk in chunks) paragraph.Add(chunk); //add separator for kind of justified alignments if (styleInfo.TextAlign == TextAlignEnum.JustifiedLine) { iTextSharp.text.pdf.draw.LineSeparator lineSeparator = new iTextSharp.text.pdf.draw.LineSeparator(); lineSeparator.Offset = 3f; lineSeparator.LineColor = new BaseColor(styleInfo.Color); paragraph.Add(new Chunk(lineSeparator)); } else if (styleInfo.TextAlign == TextAlignEnum.JustifiedDottedLine) { iTextSharp.text.pdf.draw.DottedLineSeparator dottedLineSeparator = new iTextSharp.text.pdf.draw.DottedLineSeparator(); dottedLineSeparator.Offset = 3f; dottedLineSeparator.LineColor = new BaseColor(styleInfo.Color); paragraph.Add(new Chunk(dottedLineSeparator)); } ColumnText columnText = new ColumnText(pdfContent); //start from the top of the column columnText.UseAscender = true; //width, y position from the bottom page (compensate 2 units), x position, 0 columnText.SetSimpleColumn(firstStartX, pageHeight - firstStartY - 2, firstStartX + width - styleInfo.PaddingRight, 0); columnText.AddElement(paragraph); columnText.Go(); } //add any required border addBorder(styleInfo, x, y, width, height); }
public byte[] GeneratePDF(int?ReservationID) { MemoryStream memoryStream = new MemoryStream(); iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A5, 0, 0, 0, 0); PdfWriter writer = PdfWriter.GetInstance(document, memoryStream); document.Open(); int ID = int.Parse(Session["bookID"].ToString()); Student roomBooking = new Student(); roomBooking = db.students.Find(ID); //var tenant1 = db.Tenants.Find(roomBooking.TenantId); //var reservation = _iReservationService.Get(Convert.ToInt64(ReservationID)); //var user = _iUserService.Get(reservation.UserID); iTextSharp.text.Font font_heading_3 = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.RED); iTextSharp.text.Font font_body = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 9, iTextSharp.text.Color.BLUE); // Create the heading paragraph with the headig font PdfPTable table1 = new PdfPTable(1); PdfPTable table2 = new PdfPTable(5); PdfPTable table3 = new PdfPTable(1); iTextSharp.text.pdf.draw.VerticalPositionMark seperator = new iTextSharp.text.pdf.draw.LineSeparator(); seperator.Offset = -6f; // Remove table cell table1.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER; table3.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER; table1.WidthPercentage = 80; table1.SetWidths(new float[] { 100 }); table2.WidthPercentage = 80; table3.SetWidths(new float[] { 100 }); table3.WidthPercentage = 80; PdfPCell cell = new PdfPCell(new Phrase("")); cell.Colspan = 3; table1.AddCell("\n"); table1.AddCell(cell); table1.AddCell("\n\n"); table1.AddCell( "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" + "New Erra \n" + "Email :[email protected]" + "\n" + "\n" + "\n"); table1.AddCell(" Student Details "); table1.AddCell("\nClass Name : \t" + roomBooking.StudentGrade); table1.AddCell("Full Name : \t" + roomBooking.StudentName); table1.AddCell("Last Name : \t" + roomBooking.StudentSurname); table1.AddCell("Gender : \t" + roomBooking.StudentGender); table1.AddCell("Address : \t" + roomBooking.StudentAddress); table1.AddCell("Student Town : \t" + roomBooking.StudentTown); table1.AddCell("Student Contact : \t" + roomBooking.StudentContact); table1.AddCell("Student Email : \t" + roomBooking.StudentEmail); table1.AddCell("\n School details \n"); table1.AddCell("\nStudentGrade : \t" + roomBooking.StudentGrade); table1.AddCell("\n"); //table3.AddCell("------------Looking forward to hear from you soon-"); //////Intergrate information into 1 document //var qrCode = iTextSharp.text.Image.GetInstance(reservation.QrCodeImage); //qrCode.ScaleToFit(200, 200); table1.AddCell(cell); document.Add(table1); //document.Add(qrCode); document.Add(table3); document.Close(); byte[] bytes = memoryStream.ToArray(); memoryStream.Close(); return(bytes); }
public byte[] GeneratePDF(int BookingID) { MemoryStream memoryStream = new MemoryStream(); Document document = new Document(PageSize.A5, 0, 0, 0, 0); PdfWriter writer = PdfWriter.GetInstance(document, memoryStream); document.Open(); RoomBooking roomBooking = new RoomBooking(); roomBooking = db.RoomBookings.Find(BookingID); var userName = User.Identity.GetUserName(); var guest = db.guests.Where(x => x.Email == userName).FirstOrDefault(); iTextSharp.text.Font font_heading_3 = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.RED); iTextSharp.text.Font font_body = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 9, iTextSharp.text.BaseColor.BLUE); // Create the heading paragraph with the headig font PdfPTable table1 = new PdfPTable(1); PdfPTable table2 = new PdfPTable(5); PdfPTable table3 = new PdfPTable(1); iTextSharp.text.pdf.draw.VerticalPositionMark seperator = new iTextSharp.text.pdf.draw.LineSeparator(); seperator.Offset = -6f; // Remove table cell table1.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER; table3.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER; table1.WidthPercentage = 80; table1.SetWidths(new float[] { 100 }); table2.WidthPercentage = 80; table3.SetWidths(new float[] { 100 }); table3.WidthPercentage = 80; PdfPCell cell = new PdfPCell(new Phrase("")); cell.Colspan = 3; table1.AddCell("\n"); table1.AddCell(cell); table1.AddCell("\n\n"); table1.AddCell( "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" + "Homelink \n" + "Email :[email protected]" + "\n" + "\n" + "\n"); table1.AddCell("------------Your Details--------------!"); table1.AddCell("Full Name : \t" + guest.FullName); table1.AddCell("Last Name : \t" + guest.LastName); table1.AddCell("Email : \t" + guest.Email); table1.AddCell("Phone Number : \t" + guest.Phone); table1.AddCell("Gender : \t" + guest.Gender); table1.AddCell("Address : \t" + guest.Address); table1.AddCell("\n------------Booking details--------------!\n"); table1.AddCell("Booking # : \t" + roomBooking.RoomBookingId); table1.AddCell("Room Type : \t" + roomBooking.RoomType); table1.AddCell("Room Price Per Night: \t" + roomBooking.RoomPrice.ToString("C")); table1.AddCell("Arrival date : \t" + roomBooking.CheckInDate); table1.AddCell("Departure date : \t" + roomBooking.CheckOutDate); table1.AddCell("Number Of days : \t" + roomBooking.NumberOfDays); table1.AddCell("Number Of People : \t" + roomBooking.NumberOfPeople); table1.AddCell("Total Room Cost: \t" + roomBooking.Total.ToString("C")); table1.AddCell("\n"); table3.AddCell("------------Looking forward to hear from you soon--------------!"); //////Intergrate information into 1 document //var qrCode = iTextSharp.text.Image.GetInstance(reservation.QrCodeImage); //qrCode.ScaleToFit(200, 200); table1.AddCell(cell); document.Add(table1); //document.Add(qrCode); document.Add(table3); document.Close(); byte[] bytes = memoryStream.ToArray(); memoryStream.Close(); return(bytes); }
/// <summary> /// Print orders to PDF /// </summary> /// <param name="stream">Stream</param> /// <param name="orders">Orders</param> /// <param name="languageId">Language identifier; 0 to use a language used when placing an order</param> public virtual void PrintOrdersToPdf(Stream stream, PhoiVe _phoive, int languageId = 0) { if (stream == null) { throw new ArgumentNullException("stream"); } if (_phoive == null) { throw new ArgumentNullException("Không có vé"); } //get thong tin nguon ve var order = _orderService.GetOrderById(_phoive.OrderId); if (order == null) { throw new ArgumentNullException("Không có đơn hàng"); } var nguonvexe = _hanhtrinhService.GetNguonVeXeById(_phoive.NguonVeXeId); if (nguonvexe.ParentId > 0) { nguonvexe = _hanhtrinhService.GetNguonVeXeById(_phoive.NguonVeXeConId); } //get thong tin nha xe var nhaxe = _nhaxeService.GetNhaXeById(nguonvexe.NhaXeId); var diachi = _diachiService.GetById(nhaxe.DiaChiID); //get thong tin xe xuan ben var xexuatbenInfo = _nhaxeService.GetHistoryXeXuatBenByNguonVeId(nguonvexe.Id, _phoive.NgayDi); var TenXe = ""; var BienSo = ""; if (xexuatbenInfo != null) { var xeInfo = _xeinfoService.GetXeInfoById(xexuatbenInfo.XeVanChuyenId.GetValueOrDefault(0)); TenXe = xeInfo.TenXe; BienSo = xeInfo.BienSo; } //logo var logoPicture = _pictureService.GetPictureById(nhaxe.LogoID); var logoExists = logoPicture != null; var doc = new Document(); var pdfWriter = PdfWriter.GetInstance(doc, stream); doc.Open(); //fonts var titleFont = GetFont(); titleFont.Size = BaseFont.SUPERSCRIPT_SIZE; //font ten nha xe var TenNhaXe = GetFont(); TenNhaXe.SetStyle("initial"); //font thong tin var InfoFont = GetFont(); InfoFont.Size = 14; var font = GetFont(); font.Size = 13; var pdfSettingsByStore = _settingContext.LoadSetting <PdfSettings>(order.StoreId); var lang = _workContext.WorkingLanguage; //header float[] widths = { 3, 7 }; var HeaderVeIn = new PdfPTable(widths); HeaderVeIn.DefaultCell.Border = Rectangle.NO_BORDER; if (logoExists) { var logoFilePath = _pictureService.GetThumbLocalPath(logoPicture, 0, false); var logo = Image.GetInstance(logoFilePath); logo.ScaleToFit(200, 100); PdfPCell CellLeft = new PdfPCell(logo); CellLeft.Border = Rectangle.NO_BORDER; CellLeft.FixedHeight = 80f; HeaderVeIn.AddCell(CellLeft); } PdfPCell CellRight = new PdfPCell(); CellRight.Border = Rectangle.NO_BORDER; var ParaTenNhaXe = new Paragraph(string.Format(_localizationService.GetResource("PDFInvoice.TenNhaXe", lang.Id), nhaxe.TenNhaXe), font); ParaTenNhaXe.Alignment = Element.ALIGN_RIGHT; CellRight.AddElement(ParaTenNhaXe); var ParaDiaChi = new Paragraph(string.Format(_localizationService.GetResource("PDFInvoice.DiaChiNhXe", lang.Id), diachi.DiaChi1 + " " + diachi.DiaChi2), font); ParaDiaChi.Alignment = Element.ALIGN_RIGHT; CellRight.AddElement(ParaDiaChi); var ParaSdt = new Paragraph(string.Format(_localizationService.GetResource("PDFInvoice.SDTNhaXe", lang.Id), nhaxe.DienThoai), font); ParaSdt.Alignment = Element.ALIGN_RIGHT; CellRight.AddElement(ParaSdt); HeaderVeIn.AddCell(CellRight); doc.Add(HeaderVeIn); doc.Add(new Paragraph("")); doc.Add(new Paragraph("")); //add line var line = new iTextSharp.text.pdf.draw.LineSeparator(0, 100, BaseColor.GRAY, Element.ALIGN_CENTER, 1); doc.Add(new Chunk(line)); //content Paragraph vexekhach = new Paragraph(_localizationService.GetResource("PDFInvoice.VeXeKhach", lang.Id), titleFont); vexekhach.Alignment = Element.ALIGN_CENTER; doc.Add(vexekhach); doc.Add(new Paragraph("")); doc.Add(new Paragraph("")); var Table1 = new PdfPTable(2); float[] widthTable1 = new float[] { 1f, 2f }; Table1.SetWidths(widthTable1); Table1.RunDirection = GetDirection(lang); Table1.DefaultCell.Border = Rectangle.NO_BORDER; Table1.AddCell(new Paragraph(_localizationService.GetResource("PDFInvoice.Tuyen", lang.Id), font)); Table1.AddCell(new Paragraph(nguonvexe.TenDiemDon + " -- " + nguonvexe.TenDiemDen, InfoFont)); Table1.AddCell(new Paragraph(_localizationService.GetResource("PDFInvoice.GiaVe", lang.Id), font)); Table1.AddCell(new Paragraph(nguonvexe.LichTrinhInfo.GiaVeToanTuyen.ToString() + " VNĐ", InfoFont)); doc.Add(Table1); //add ghe,xe var Table2 = new PdfPTable(4); float[] widthTable2 = new float[] { 1f, 2f, 1f, 2f }; Table2.SetWidths(widthTable2); Table2.RunDirection = GetDirection(lang); Table2.DefaultCell.Border = Rectangle.NO_BORDER; Table2.AddCell(new Paragraph(_localizationService.GetResource("PDFInvoice.SoXe", lang.Id), font)); Table2.AddCell(new Paragraph(TenXe + "/" + BienSo, InfoFont)); Table2.AddCell(new Paragraph(_localizationService.GetResource("PDFInvoice.SoGhe", lang.Id), font)); Table2.AddCell(new Paragraph(_phoive.sodoghexequytac.Val + " ( Tầng" + _phoive.sodoghexequytac.Tang + ")", InfoFont)); doc.Add(Table2); //add thoi gian khoi hanh var Table3 = new PdfPTable(4); float[] widthTable3 = new float[] { 2f, 1f, 1f, 2f }; Table3.SetWidths(widthTable3); Table3.RunDirection = GetDirection(lang); Table3.DefaultCell.Border = Rectangle.NO_BORDER; Table3.AddCell(new Paragraph(_localizationService.GetResource("PDFInvoice.ThoiGianDi", lang.Id), font)); Table3.AddCell(new Paragraph(nguonvexe.ThoiGianDi.ToString("HH:mm"), InfoFont)); Table3.AddCell(new Paragraph(_localizationService.GetResource("PDFInvoice.NgayDi", lang.Id), font)); Table3.AddCell(new Paragraph(_phoive.NgayDi.ToString("dd/MM/yyyy"), InfoFont)); doc.Add(Table3); //add footer var FooterNgayBan = new Paragraph("Ngày " + DateTime.Now.Day + " tháng " + DateTime.Now.Month + " năm " + DateTime.Now.Year, font); FooterNgayBan.Alignment = Element.ALIGN_RIGHT; var FooterNguoiBanTitle = new Paragraph("Người bán vé", font); FooterNguoiBanTitle.Alignment = Element.ALIGN_RIGHT; var firtname = _workContext.CurrentCustomer.GetAttribute <string>(SystemCustomerAttributeNames.FirstName); var lastname = _workContext.CurrentCustomer.GetAttribute <string>(SystemCustomerAttributeNames.LastName); var FooterTenNguoiBan = new Paragraph(firtname + " " + lastname, font); FooterTenNguoiBan.Alignment = Element.ALIGN_RIGHT; var Table4 = new PdfPTable(1); Table4.DefaultCell.Border = Rectangle.NO_BORDER; PdfPCell CellFooter = new PdfPCell(); CellFooter.Border = Rectangle.NO_BORDER; CellFooter.AddElement(FooterNgayBan); CellFooter.AddElement(FooterNguoiBanTitle); CellFooter.AddElement(FooterTenNguoiBan); Table4.AddCell(CellFooter); doc.Add(Table4); doc.Add(new Paragraph(" ")); doc.NewPage(); doc.Close(); }
void ExportReport(iTextSharp.text.Document doc, DataTable dt) { iTextSharp.text.pdf.draw.LineSeparator line = new iTextSharp.text.pdf.draw.LineSeparator(2f, 100f, iTextSharp.text.BaseColor.BLACK, iTextSharp.text.Element.ALIGN_CENTER, -1); iTextSharp.text.Chunk linebreak = new iTextSharp.text.Chunk(line); iTextSharp.text.Font black = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 9f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); var logo = new iTextSharp.text.Paragraph() { Alignment = 0 }; logo.Add(new iTextSharp.text.Chunk("Tachyon", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 36, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK))); logo.Add(new iTextSharp.text.Chunk("FIX", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 36, iTextSharp.text.Font.BOLD, new iTextSharp.text.BaseColor(26, 188, 156)))); doc.Add(logo); doc.Add(new iTextSharp.text.Chunk(line)); doc.Add(new iTextSharp.text.Paragraph(new iTextSharp.text.Chunk(ConcatStrings("Log List", DateTime.Now.ToString()), new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 9f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK))) { Alignment = 0 }); doc.Add(new iTextSharp.text.Paragraph(new iTextSharp.text.Chunk(" ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 9f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK))) { Alignment = 0 }); doc.Add(linebreak); doc.Add(new iTextSharp.text.Paragraph(" ")); var bf = BaseFont.CreateFont(Environment.CurrentDirectory + @"\arial.ttf", BaseFont.IDENTITY_H, true); iTextSharp.text.Font NormalFont = new iTextSharp.text.Font(bf, 12, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); iTextSharp.text.Font TFont = new iTextSharp.text.Font(bf, 12, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.GREEN); iTextSharp.text.Font XFont = new iTextSharp.text.Font(bf, 12, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.RED); PdfPTable table = new PdfPTable(dt.Columns.Count) { WidthPercentage = 100 }; for (int i = 0; i < dt.Columns.Count; i++) { table.AddCell(new PdfPCell() { Phrase = new iTextSharp.text.Phrase(dt.Columns[i].ColumnName), BackgroundColor = iTextSharp.text.BaseColor.GRAY }); } //table.SetWidths(new float[] { 3, 25, 25, 8 }); for (int i = 0; i < dt.Rows.Count; i++) { ReportProgress((i / (double)dt.Rows.Count) * 100, "Exporting Rows..."); DataRow GridRow = dt.Rows[i]; for (int j = 0; j < dt.Columns.Count; j++) { table.AddCell(new iTextSharp.text.Phrase(GridRow.ItemArray[j].ToString(), NormalFont)); } } doc.Add(table); }
//public ActionResult Index(string levelString, string session, string arm, string DateFrom, string DateTo, string ApprovedString, string searchString, string SexString, string LevelString, string StudentIDString, int? page // , string paidschoolfess, string term, bool? printQuery) //{ public ActionResult Index(string levelString, string session, string arm, string DateFrom, string DateTo, string ApprovedString, string searchString, string SexString, string LevelString, string StudentIDString, int?page , string paidschoolfess, string term) { bool?thePrintQuery = null; // thePrintQuery = printQuery; if (User.IsInRole("Parent")) { List <TermRegistration> studentList = new List <TermRegistration>(); int theParentUserName = Convert.ToInt32(User.Identity.Name); Parent theParent = work.ParentRepository.Get(a => a.UserID == theParentUserName).First(); List <PrimarySchoolStudent> theStudents = work.PrimarySchoolStudentRepository.Get(a => a.ParentID == theParent.ParentID).ToList(); int counter = 0; foreach (PrimarySchoolStudent s in theStudents) { if (counter == 0) { theParent.StudentIDOne = Convert.ToString(s.UserID); } if (counter == 1) { theParent.StudentIDTwo = Convert.ToString(s.UserID); } if (counter == 2) { theParent.StudentIDThree = Convert.ToString(s.UserID); } if (counter == 3) { theParent.StudentIDFour = Convert.ToString(s.UserID); } if (counter == 4) { theParent.StudentIDFive = Convert.ToString(s.UserID); } counter = counter + 1; } if (!(string.IsNullOrEmpty(theParent.StudentIDOne))) { int theStudentID = Convert.ToInt32(theParent.StudentIDOne); //List<TermRegistration> theList = work.TermRegistrationRepository.Get(a => a.StudentID == theStudentID && a.Term == term && a.Session == session).ToList(); List <TermRegistration> theList = work.TermRegistrationRepository.Get(a => a.StudentID == theStudentID).ToList(); if (theList.Count > 0) { studentList.Add(theList[0]); } } if (!(string.IsNullOrEmpty(theParent.StudentIDTwo))) { int theStudentID = Convert.ToInt32(theParent.StudentIDTwo); List <TermRegistration> theList = work.TermRegistrationRepository.Get(a => a.StudentID == theStudentID).ToList(); if (theList.Count > 0) { studentList.Add(theList[0]); } } if (!(string.IsNullOrEmpty(theParent.StudentIDThree))) { int theStudentID = Convert.ToInt32(theParent.StudentIDThree); List <TermRegistration> theList = work.TermRegistrationRepository.Get(a => a.StudentID == theStudentID).ToList(); if (theList.Count > 0) { studentList.Add(theList[0]); } } if (!(string.IsNullOrEmpty(theParent.StudentIDFour))) { int theStudentID = Convert.ToInt32(theParent.StudentIDFour); List <TermRegistration> theList = work.TermRegistrationRepository.Get(a => a.StudentID == theStudentID).ToList(); if (theList.Count > 0) { studentList.Add(theList[0]); } } if (!(string.IsNullOrEmpty(theParent.StudentIDFive))) { int theStudentID = Convert.ToInt32(theParent.StudentIDFive); List <TermRegistration> theList = work.TermRegistrationRepository.Get(a => a.StudentID == theStudentID).ToList(); if (theList.Count > 0) { studentList.Add(theList[0]); } } List <SelectListItem> theItem = new List <SelectListItem>(); theItem.Add(new SelectListItem() { Text = "None", Value = "" }); foreach (var level in studentList) { theItem.Add(new SelectListItem() { Text = level.StudentID.ToString(), Value = level.StudentID.ToString() }); } ViewData["studentIds"] = theItem; // students = studentList; } if (term == "First") { ViewBag.Term = "1"; } if (term == "Second") { ViewBag.Term = "2"; } if (term == "Third") { ViewBag.Term = "3"; } decimal totalAmount = 0; if (Request.HttpMethod == "GET") { // searchString = currentFilter; } else { page = 1; } ViewBag.CurrentFilter = searchString; var students = from s in work.TermRegistrationRepository.Get(a => a.Term == term) select s; // var students = from s in work.TermRegistrationRepository.Get() // select s; if (!String.IsNullOrEmpty(term)) { // students = from s in work.TermRegistrationRepository.Get() // select s; students = students.Where(s => s.Term.Equals(term)); } if (!String.IsNullOrEmpty(session)) { students = students.Where(s => s.Session.Equals(session)); } if (!String.IsNullOrEmpty(LevelString)) { students = students.Where(s => s.Level == LevelString); } if (!String.IsNullOrEmpty(StudentIDString)) { int theID = Convert.ToInt32(StudentIDString); students = students.Where(s => s.StudentID == theID); } int pageSize = 50; int pageNumber = (page ?? 1); if (!String.IsNullOrEmpty(paidschoolfess)) { if (paidschoolfess == "Owing") { var payments = from s in work.SchoolFeePaymentRepository.Get() select s; if (!String.IsNullOrEmpty(term)) { payments = payments.Where(s => s.Term.Equals(term)); } if (!String.IsNullOrEmpty(session)) { payments = payments.Where(s => s.Session.Equals(session)); } if (!String.IsNullOrEmpty(LevelString)) { payments = payments.Where(s => s.Level == LevelString); } if (!String.IsNullOrEmpty(StudentIDString)) { int theID = Convert.ToInt32(StudentIDString); payments = payments.Where(s => s.StudentID == theID); } // payments = payments.Where(a => a.Owing > 0).OrderBy(a => a.StudentID);//.OrderBy(a => a.DatePaid); TermRegistration theStudentWhoRegistered = new TermRegistration(); List <TermRegistration> theOwingStudents = new List <TermRegistration>(); List <SchoolFeePayment> theRegisteredSchoolFeePyament = new List <SchoolFeePayment>(); SchoolFeePayment thePayment = new SchoolFeePayment(); TermRegistration tR = new TermRegistration(); SchoolFeePayment sF = new SchoolFeePayment(); List <TermRegistration> theRegisteredStudents = new List <TermRegistration>(); theRegisteredStudents = students.ToList(); foreach (TermRegistration t in theRegisteredStudents) { List <SchoolFeePayment> thisGuyPayment = work.SchoolFeePaymentRepository.Get(a => a.StudentID == t.StudentID && a.Term == term).OrderByDescending(a => a.DatePaid).ToList(); if (thisGuyPayment.Count() > 0) { SchoolFeePayment theCurrentPayment = thisGuyPayment[0]; if (theCurrentPayment.Owing > 0) { totalAmount += theCurrentPayment.Owing; theOwingStudents.Add(new TermRegistration { DateRegistered = t.DateRegistered, Owing = t.Owing, TermRegistrationID = t.TermRegistrationID, Register = t.Register, Sex = t.Sex, LastName = t.LastName, FirstName = t.FirstName, SchoolFeesKind = theCurrentPayment.TheSchoolFeesType, Cost = theCurrentPayment.Cost, Level = theCurrentPayment.Level, Session = theCurrentPayment.Session, Term = theCurrentPayment.Term, StudentID = theCurrentPayment.StudentID, }); } } } students = theOwingStudents; } else { if (Convert.ToBoolean(paidschoolfess) == true) { List <SchoolFeePayment> listOfPayments = work.SchoolFeePaymentRepository.Get().Where(a => a.Owing <= 0).OrderBy(a => a.DatePaid).ToList(); List <TermRegistration> theRegisteredStuentWhoHavePaid = new List <TermRegistration>(); foreach (TermRegistration r in students) { foreach (SchoolFeePayment l in listOfPayments) { if (r.StudentID == l.StudentID) { totalAmount += l.Cost; theRegisteredStuentWhoHavePaid.Add(r); break; } } // if(s.StudentID ==)theRegisteredStuentWhoHavePaid } students = theRegisteredStuentWhoHavePaid; } else { List <TermRegistration> theNeverPaidStuddentStudents = new List <TermRegistration>(); List <TermRegistration> theRegisteredStudents = new List <TermRegistration>(); theRegisteredStudents = students.ToList(); theRegisteredStudents = students.ToList(); foreach (TermRegistration t in theRegisteredStudents) { List <SchoolFeePayment> thisGuyPayment = new List <SchoolFeePayment>(); // List<SchoolFeePayment> thisGuyPayment = work.SchoolFeePaymentRepository.Get(a => a.StudentID == t.StudentID && a.Term == term).OrderByDescending(a => a.DatePaid).ToList(); if (string.IsNullOrEmpty(session)) { thisGuyPayment = work.SchoolFeePaymentRepository.Get(a => a.StudentID == t.StudentID && a.Term == term).OrderByDescending(a => a.DatePaid).ToList(); } if (!(string.IsNullOrEmpty(session))) { thisGuyPayment = work.SchoolFeePaymentRepository.Get(a => a.StudentID == t.StudentID && a.Session == session && a.Term == term).OrderByDescending(a => a.DatePaid).ToList(); } if (thisGuyPayment.Count() == 0) { totalAmount += t.Cost; theNeverPaidStuddentStudents.Add(new TermRegistration { LastName = t.LastName, FirstName = t.FirstName, SchoolFeesKind = t.SchoolFeesKind, Cost = t.Cost, Level = t.Level, Session = t.Session, Term = t.Term, StudentID = t.StudentID }); } } students = theNeverPaidStuddentStudents; } } } if (User.IsInRole("Parent")) { //ViewBag.Term = "1"; int theParentUserName = Convert.ToInt32(User.Identity.Name); Parent theParent = work.ParentRepository.Get(a => a.UserID == theParentUserName).First(); List <TermRegistration> studentList = new List <TermRegistration>(); int theStudentID = 0; if (!(string.IsNullOrEmpty(StudentIDString))) { theStudentID = Convert.ToInt32(StudentIDString); } List <TermRegistration> theList = new List <TermRegistration>(); theList = work.TermRegistrationRepository.Get(a => a.StudentID == theStudentID && a.Term == term && a.Session == session && a.Level == LevelString).ToList(); students = theList; } if (User.IsInRole("Student")) { // ViewBag.Term = "1"; int theStudentUserName = Convert.ToInt32(User.Identity.Name); List <PrimarySchoolStudent> theStudent = new List <PrimarySchoolStudent>(); List <TermRegistration> theList = new List <TermRegistration>(); theStudent = work.PrimarySchoolStudentRepository.Get(a => a.UserID == theStudentUserName).ToList(); // List<TermRegistration> studentList = new List<TermRegistration>(); if ((theStudent.Count > 0)) { int theStudentID = Convert.ToInt32(theStudent[0].UserID); theList = work.TermRegistrationRepository.Get(a => a.StudentID == theStudentID && a.Level == LevelString && a.Term == term && a.Session == session).ToList(); //if (theList.Count > 0) //{ // theList.Add(theList[0]); // } } students = theList; } if (thePrintQuery != null && students.Count() > 0) { thePrintQuery = null; StringWriter oStringWriter1 = new StringWriter(); Document itextDoc = new Document(PageSize.LETTER); itextDoc.Open(); Response.ContentType = "application/pdf"; PrintResult print = new PrintResult(); // Set up the document and the MS to write it to and create the PDF writer instance MemoryStream ms = new MemoryStream(); //Document document = new Document(PageSize.A3.Rotate()); Document document = new Document(PageSize.A4); PdfWriter writer = PdfWriter.GetInstance(document, ms); // Open the PDF document document.Open(); Document thedoc = new SchoolFeesPrinting().FeesPrinting(students.ToList(), ref oStringWriter1, ref document); iTextSharp.text.pdf.draw.VerticalPositionMark seperator = new iTextSharp.text.pdf.draw.LineSeparator(); seperator.Offset = -6f; document.Close(); // Hat tip to David for his code on stackoverflow for this bit // http://stackoverflow.com/questions/779430/asp-net-mvc-how-to-get-view-to-generate-pdf byte[] file = ms.ToArray(); MemoryStream output = new MemoryStream(); output.Write(file, 0, file.Length); output.Position = 0; HttpContext.Response.AddHeader("content-disposition", "attachment; filename=SchoolFees.pdf"); return(new FileStreamResult(output, "application/pdf")); //new FileStreamResult(output, "application/pdf"); // return View(new FileStreamResult(output, "application/pdf")); } ViewBag.TotalAmount = totalAmount; ViewBag.Count = students.Count(); return(View(students.ToPagedList(pageNumber, pageSize))); // } // else // { // return View("Index3", students.ToPagedList(pageNumber, pageSize)); // } }
/// <summary> /// Add text at the X Y position; multiple lines handled /// </summary> private void addText(float x, float y, float width, float height, string[] textLines, StyleInfo styleInfo, float[] textWidths, bool wrap, string url, bool noClip, string tooltip) { RenderFont renderFont = RenderUtility.GetRenderFont(styleInfo); BaseFont baseFont = null; //convert the render font type to iTextSharp type int fontType = 0; switch (renderFont.Style) { case RenderFont.FontStyle.Bold: fontType = iTextSharp.text.Font.BOLD; break; case RenderFont.FontStyle.Italic: fontType = iTextSharp.text.Font.ITALIC; break; case RenderFont.FontStyle.BoldItalic: fontType = iTextSharp.text.Font.BOLDITALIC; break; default: fontType = iTextSharp.text.Font.NORMAL; break; } //get the index of the font name in the list font name int indexBaseFont = BaseFontNames.FindIndex(delegate(string _fontname) { return(_fontname == renderFont.FaceName + "_" + fontType); }); //if not found then add the new BaseFont if (indexBaseFont == -1) { //create a new font or a with a new type baseFont = FontFactory.GetFont(renderFont.FaceName, BaseFont.IDENTITY_H, 0, fontType).BaseFont; //add the font face name and font to the lists BaseFontNames.Add(renderFont.FaceName + "_" + fontType); BaseFonts.Add(baseFont); } else { baseFont = BaseFonts[indexBaseFont]; } //text alignment int align = 0; //first position x and y and the leading (usefull for all kind of justified text) float firstStartX = -1; float firstStartY = -1; float leading = -1; //chunks of text List <Chunk> chunks = new List <Chunk>(); //loop thru the lines of text for (int i = 0; i < textLines.Length; i++) { string text = textLines[i]; float textwidth = textWidths[i]; float startX = x + styleInfo.PaddingLeft; // TODO: handle tb_rl float startY = y + styleInfo.PaddingTop + (i * styleInfo.FontSize); // TODO: handle tb_rl if (styleInfo.WritingMode == WritingModeEnum.lr_tb) { //calculate the x position switch (styleInfo.TextAlign) { case TextAlignEnum.Center: if (width > 0) { startX = x + styleInfo.PaddingLeft + (width - styleInfo.PaddingLeft - styleInfo.PaddingRight) / 2 - textwidth / 2; align = Element.ALIGN_CENTER; } break; case TextAlignEnum.Right: if (width > 0) { startX = x + width - textwidth - styleInfo.PaddingRight - 2; align = Element.ALIGN_RIGHT; } break; case TextAlignEnum.Justified: case TextAlignEnum.JustifiedLine: case TextAlignEnum.JustifiedDottedLine: if (width > 0) { startX += 2; align = Element.ALIGN_JUSTIFIED; } break; case TextAlignEnum.Left: default: if (width > 0) { startX += 2; } align = Element.ALIGN_LEFT; break; } //calculate the y position switch (styleInfo.VerticalAlign) { case VerticalAlignEnum.Middle: if (height <= 0) { break; } //calculate the middle of the region startY = y + styleInfo.PaddingTop + (height - styleInfo.PaddingTop - styleInfo.PaddingBottom) / 2 - styleInfo.FontSize / 2; //now go up or down depending on which line if (textLines.Length == 1) { break; } //even number if (textLines.Length % 2 == 0) { startY = startY - ((textLines.Length / 2 - i) * styleInfo.FontSize) + styleInfo.FontSize / 2; } else { startY = startY - ((textLines.Length / 2 - i) * styleInfo.FontSize); } break; case VerticalAlignEnum.Bottom: if (height <= 0) { break; } startY = y + height - styleInfo.PaddingBottom - (styleInfo.FontSize * (textLines.Length - i)); break; case VerticalAlignEnum.Top: default: break; } } else { //move x in a little - it draws to close to the edge of the rectangle (25% of the font size seems to work!) and Center or right align vertical text startX += styleInfo.FontSize / 4; switch (styleInfo.TextAlign) { case TextAlignEnum.Center: if (height > 0) { startY = y + styleInfo.PaddingLeft + (height - styleInfo.PaddingLeft - styleInfo.PaddingRight) / 2 - textwidth / 2; } break; case TextAlignEnum.Right: if (width > 0) { startY = y + height - textwidth - styleInfo.PaddingRight; } break; case TextAlignEnum.Left: default: break; } } //mark the first x position for justify text if (firstStartX == -1) { firstStartX = startX; } //mark the first y position for justify text if (firstStartY == -1) { firstStartY = startY; } //mark the first leading height for justify text else if (leading == -1) { leading = startY - firstStartY; } //draw background rectangle if needed (only put out on the first line, since we do whole rectangle) if (!styleInfo.BackgroundColor.IsEmpty && height > 0 && width > 0 && i == 0) { addFillRectangle(x, y, width, height, styleInfo.BackgroundColor); } //set the clipping path, (Itext have no clip) if (height > 0 && width > 0) { pdfContent.SetRGBColorFill(styleInfo.Color.R, styleInfo.Color.G, styleInfo.Color.B); if (align == Element.ALIGN_JUSTIFIED) { chunks.Add(new Chunk(text)); } else { if (styleInfo.WritingMode == WritingModeEnum.lr_tb) { //if textline after measure with word break can fit just simple show Text if (width >= textwidth) { pdfContent.SaveState(); pdfContent.BeginText(); pdfContent.SetFontAndSize(baseFont, styleInfo.FontSize); //same fonts dont have nativelly bold so we could simulate that if (renderFont.SimulateBold) { pdfContent.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE); pdfContent.SetLineWidth(0.2f); } pdfContent.SetTextMatrix(startX, pageHeight - startY - styleInfo.FontSize); pdfContent.ShowText(text); pdfContent.EndText(); pdfContent.RestoreState(); } else { //else use Column text to wrap or clip (wrap: for example a text like an URL so word break is not working here //itextsharp ColumnText do the work for us) ColumnText columnText = new ColumnText(pdfContent); columnText.SetSimpleColumn(new Phrase(text, new iTextSharp.text.Font(baseFont, styleInfo.FontSize)), x + styleInfo.PaddingLeft, pageHeight - startY, x + width - styleInfo.PaddingRight, pageHeight - y - styleInfo.PaddingBottom - height, 10f, align); columnText.Go(); } } else { //not checked double rads = -283.0 / 180.0; double radsCos = Math.Cos(rads); double radsSin = Math.Sin(rads); pdfContent.BeginText(); pdfContent.SetFontAndSize(baseFont, styleInfo.FontSize); pdfContent.SetTextMatrix((float)radsCos, (float)radsSin, (float)-radsSin, (float)radsCos, startX, pageHeight - startY); pdfContent.ShowText(text); pdfContent.EndText(); } } //add URL if (url != null) { document.Add(new Annotation(x, pageHeight - y, height, width, url)); } //add tooltip if (tooltip != null) { document.Add(new Annotation(x, pageHeight - y, height, width, tooltip)); } } //handle underlining etc ... float maxX; switch (styleInfo.TextDecoration) { case TextDecorationEnum.Underline: maxX = width > 0 ? Math.Min(x + width, startX + textwidth) : startX + textwidth; addLine(startX, startY + styleInfo.FontSize + 1, maxX, startY + styleInfo.FontSize + 1, 1, styleInfo.Color, BorderStyleEnum.Solid); break; case TextDecorationEnum.LineThrough: maxX = width > 0 ? Math.Min(x + width, startX + textwidth) : startX + textwidth; addLine(startX, startY + (styleInfo.FontSize / 2) + 1, maxX, startY + (styleInfo.FontSize / 2) + 1, 1, styleInfo.Color, BorderStyleEnum.Solid); break; case TextDecorationEnum.Overline: maxX = width > 0 ? Math.Min(x + width, startX + textwidth) : startX + textwidth; addLine(startX, startY + 1, maxX, startY + 1, 1, styleInfo.Color, BorderStyleEnum.Solid); break; case TextDecorationEnum.None: default: break; } } //add text to justify if (chunks.Count > 0) { Paragraph paragraph = new Paragraph(); paragraph.Alignment = align; paragraph.Leading = leading; paragraph.Font = new iTextSharp.text.Font(baseFont, styleInfo.FontSize); //join all text (is necessary to justify alignment) foreach (Chunk chunk in chunks) { paragraph.Add(chunk); } //add separator for kind of justified alignments if (styleInfo.TextAlign == TextAlignEnum.JustifiedLine) { iTextSharp.text.pdf.draw.LineSeparator lineSeparator = new iTextSharp.text.pdf.draw.LineSeparator(); lineSeparator.Offset = 3f; lineSeparator.LineColor = new BaseColor(styleInfo.Color); paragraph.Add(new Chunk(lineSeparator)); } else if (styleInfo.TextAlign == TextAlignEnum.JustifiedDottedLine) { iTextSharp.text.pdf.draw.DottedLineSeparator dottedLineSeparator = new iTextSharp.text.pdf.draw.DottedLineSeparator(); dottedLineSeparator.Offset = 3f; dottedLineSeparator.LineColor = new BaseColor(styleInfo.Color); paragraph.Add(new Chunk(dottedLineSeparator)); } ColumnText columnText = new ColumnText(pdfContent); //start from the top of the column columnText.UseAscender = true; //width, y position from the bottom page (compensate 2 units), x position, 0 columnText.SetSimpleColumn(firstStartX, pageHeight - firstStartY - 2, firstStartX + width - styleInfo.PaddingRight, 0); columnText.AddElement(paragraph); columnText.Go(); } //add any required border addBorder(styleInfo, x, y, width, height); }
public FileStreamResult printBidForm(string BidId) { var preBidDetails = HomeDal.getPreBidFormByBid(BidId); // Set up the document and the MS to write it to and create the PDF writer instance MemoryStream ms = new MemoryStream(); Document document = new Document(PageSize.A4); PdfWriter writer = PdfWriter.GetInstance(document, ms); // Open the PDF document document.Open(); // Set up fonts used in the document var LightBlue = new BaseColor(14, 45, 76); var grey = new BaseColor(119, 119, 119); iTextSharp.text.Font font_heading_1 = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 17, LightBlue); iTextSharp.text.Font font_body = FontFactory.GetFont(FontFactory.HELVETICA, 12, LightBlue); iTextSharp.text.Font font_body_bold = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12, LightBlue); iTextSharp.text.Font spanBold = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12, grey); iTextSharp.text.Font spanNormal = FontFactory.GetFont(FontFactory.HELVETICA, 11, grey); preBidDetails.JobNumber = (string.IsNullOrWhiteSpace(preBidDetails.JobNumber) ? BusinessConstants.NA : preBidDetails.JobNumber); // Create the heading paragraph with the headig font Paragraph header; header = new Paragraph("Pre-Bid [" + Convert.ToString(Session["CommID"]) + (preBidDetails.PRJID) + "] Bid Item #" + BidId, font_heading_1); iTextSharp.text.pdf.draw.VerticalPositionMark seperator = new iTextSharp.text.pdf.draw.LineSeparator(); seperator.Offset = -4f; header.Add(seperator); document.Add(header); var HeaderTable = new PdfPTable(4); HeaderTable.HorizontalAlignment = 0; HeaderTable.SpacingBefore = 5; HeaderTable.SpacingAfter = 5; HeaderTable.DefaultCell.Border = 0; HeaderTable.SetWidths(new int[] { 4, 7, 3, 4 }); HeaderTable.AddCell(new Phrase("Form Type:", spanBold)); HeaderTable.AddCell(new Phrase(preBidDetails.FormType, spanNormal)); HeaderTable.AddCell(new Phrase()); HeaderTable.AddCell(new Phrase()); HeaderTable.AddCell(new Phrase("JobNumber:", spanBold)); HeaderTable.AddCell(new Phrase(preBidDetails.JobNumber, spanNormal)); HeaderTable.AddCell(new Phrase("Job Name:", spanBold)); HeaderTable.AddCell(new Phrase(preBidDetails.JobName, spanNormal)); HeaderTable.AddCell(new Phrase("BI Number:", spanBold)); HeaderTable.AddCell(new Phrase(Convert.ToString(preBidDetails.BINumber), spanNormal)); HeaderTable.AddCell(new Phrase("BI Name:", spanBold)); HeaderTable.AddCell(new Phrase(preBidDetails.BIName, spanNormal)); HeaderTable.AddCell(new Phrase("Sales Person:", spanBold)); HeaderTable.AddCell(new Phrase(Convert.ToString(preBidDetails.SalesPerson), spanNormal)); HeaderTable.AddCell(new Phrase("Company:", spanBold)); HeaderTable.AddCell(new Phrase(preBidDetails.Company, spanNormal)); HeaderTable.AddCell(new Phrase("Fence Type:", spanBold)); HeaderTable.AddCell(new Phrase(Convert.ToString(preBidDetails.FenceType), spanNormal)); HeaderTable.AddCell(new Phrase("Rate Type:", spanBold)); HeaderTable.AddCell(new Phrase(preBidDetails.RateType, spanNormal)); HeaderTable.TotalWidth = 100; document.Add(HeaderTable); if (preBidDetails.PreTaxSoldFor < preBidDetails.SuggestdSoldFor) { Paragraph alertData; iTextSharp.text.Font redFont = FontFactory.GetFont(FontFactory.HELVETICA, 12, new BaseColor(255, 0, 0)); string data = "Pre-Tax Sold For " + String.Format("{0:C}", preBidDetails.PreTaxSoldFor) + " is quoted less than Suggested Price " + String.Format("{0:C}", preBidDetails.SuggestdSoldFor); alertData = new Paragraph(data, redFont); document.Add(alertData); } var SectionTable = new PdfPTable(4); SectionTable.HorizontalAlignment = 0; SectionTable.SpacingBefore = 5; SectionTable.SpacingAfter = 5; SectionTable.DefaultCell.Border = 0; SectionTable.SetWidths(new int[] { 7, 4, 4, 4 }); SectionTable.AddCell(getLabelValue("Material Cost:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.Material, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Material Handling Charge:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.MaterialHandling, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Concrete:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.Concrete, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Material Total:", font_body)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(preBidDetails.MaterialTotal, font_body_bold)); SectionTable.AddCell(getDecimalValue(preBidDetails.MaterialCOSPercent, spanNormal, true)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Onsite Labor:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.OnsiteLabor, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Load Labor:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.LoadLabor, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Drive Labor:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.DriveLabor, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Supervisor:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.Supervisor, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Labor Reserve:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.LaborReserve, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Labor Total:", font_body)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(preBidDetails.LaborTotal, font_body_bold)); SectionTable.AddCell(getDecimalValue(preBidDetails.LaborCOSPercent, spanNormal, true)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Other Charges:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.OtherCharges, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Other Charges Markup:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.OtherChargesMarkup, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Other Charges Total:", font_body)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(preBidDetails.OtherChargesTotal, font_body_bold)); SectionTable.AddCell(getDecimalValue(preBidDetails.OtherCOSPercent, spanNormal, true)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Equipment Cost:", font_body)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(preBidDetails.EquipmentCost, font_body_bold)); SectionTable.AddCell(getDecimalValue(preBidDetails.EquipmentCOSPercent, spanNormal, true)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Benefits:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.Benefits, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Retirement:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.Retirement, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Payroll Tax:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.PayrollTax, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Workers Comp:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.WorkersComp, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Indirect Total:", font_body)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(preBidDetails.IndirectTotal, font_body_bold)); SectionTable.AddCell(getDecimalValue(preBidDetails.IndirectCOSPercent, spanNormal, true)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Job Cost:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.JobCost, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Job Markup:", font_body)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(preBidDetails.JobMarkUpTotal, font_body_bold)); SectionTable.AddCell(getDecimalValue(preBidDetails.JobMarkupPercent, spanNormal, true)); SectionTable.AddCell(getLabelValue("Suggested Sold For:", font_body)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(preBidDetails.SuggestdSoldFor, font_body_bold)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Pre-Tax Sold For:", font_body)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(preBidDetails.PreTaxSoldFor, font_body_bold)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Sales Tax Type:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.SalesTaxType, spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Sales Tax Percent:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.SalesTaxPercent, spanNormal, true)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Sales Tax Total:", font_body)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getDecimalValue(preBidDetails.SalesTaxTotal, font_body_bold)); SectionTable.AddCell(getDecimalValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Crew Head Count:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.CrewHeadCount, spanNormal, hasBorder: false)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Days On Site:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.DaysOnsite, spanNormal, hasBorder: false, plainText: true)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Crew Labor Budget:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.CrewLaborBudget, spanNormal, hasBorder: false)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue("Rev Per Mh:", font_body)); SectionTable.AddCell(getDecimalValue(preBidDetails.RevPerMh, spanNormal, hasBorder: false)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); SectionTable.AddCell(getLabelValue(" ", spanNormal)); document.Add(SectionTable); //document.Add(FooterTable); document.Close(); byte[] file = ms.ToArray(); MemoryStream output = new MemoryStream(); output.Write(file, 0, file.Length); output.Position = 0; HttpContext.Response.AddHeader("content-disposition", "inline; filename=PreBid_BidItem_" + preBidDetails.BINumber + ".pdf"); return(File(output, "application/pdf")); }
public FileStreamResult PrintPassword() { // Set up the document and the MS to write it to and create the PDF writer instance MemoryStream ms = new MemoryStream(); Document document = new Document(PageSize.A4.Rotate()); PdfWriter writer = PdfWriter.GetInstance(document, ms); // Open the PDF document document.Open(); PdfPTable table1 = new PdfPTable(1); // oStringWriter.Write("This is the content"); // Response.ContentType = "text/plain"; // Response.ContentType = "application/pdf"; // MemoryStream ms = new MemoryStream(); // Document document = new Document(PageSize.A4.Rotate()); // Open the PDF document // document.Open(); // PdfWriter writer = PdfWriter.GetInstance(document, ms); // Set up fonts used in the document Font font_heading_1 = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 21, Font.BOLD); Font font_body = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12); Font font_body2 = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 13); List<string> theDepartments = new List<string>(); theDepartments.Add("100level Chemical Engineering"); theDepartments.Add("100level Computer Engineering"); theDepartments.Add("100level Civil Engineering"); theDepartments.Add("100level Electrical Electronics"); theDepartments.Add("100level Mechatronics Engineering"); theDepartments.Add("100level Mechanical Engineering"); theDepartments.Add("100level Petroleum Engineering"); theDepartments.Add("200level Chemical Engineering"); theDepartments.Add("200level Computer Engineering"); theDepartments.Add("200level Civil Engineering"); theDepartments.Add("200level Electrical Electronics"); theDepartments.Add("200level Mechatronics Engineering"); theDepartments.Add("200level Mechanical Engineering"); theDepartments.Add("200level Petroleum Engineering"); theDepartments.Add("400level Chemical Engineering"); theDepartments.Add("400level Computer Engineering"); theDepartments.Add("400level Civil Engineering"); theDepartments.Add("400level Electrical Electronic"); theDepartments.Add("400level Mechatronics Engineering"); theDepartments.Add("400level Mechanical Engineering"); theDepartments.Add("400level Petroleum Engineering"); theDepartments.Add("500level Chemical Engineering"); theDepartments.Add("500level Computer Engineering"); theDepartments.Add("500level Civil Engineering"); theDepartments.Add("500level Electrical Electronics"); theDepartments.Add("500level Mechatronics Engineering"); theDepartments.Add("500level Mechanical Engineering"); theDepartments.Add("500level Petroleum Engineering"); theDepartments.Add("300level Chemical Engineering"); theDepartments.Add("300level Computer Engineering"); theDepartments.Add("300level Civil Engineering"); theDepartments.Add("300level Electrical Electronics"); theDepartments.Add("300level Mechatronics Engineering"); theDepartments.Add("300level Mechanical Engineering"); theDepartments.Add("300level Petroleum Engineering"); // theDepartments.Add("ORAL MAXILLOFACIAL SURGERY"); // theDepartments.Add("GERIATRICS"); // theDepartments.Add("HOUSE OFFICER"); // theDepartments.Add("ANAESTHESIA"); // theDepartments.Add("CHEMICAL PATHOLOGY"); // theDepartments.Add("CLINICAL PHARMACOLOGY"); // theDepartments.Add("PREVENTIVE DENTISTRY"); // theDepartments.Add("GENERAL OUTPATIENT"); // theDepartments.Add("HAEMATOLOGY"); // theDepartments.Add("PRIVATE SUITE"); // theDepartments.Add("NEURO SURGERY"); // theDepartments.Add("MEDICAL MICROBIOLOGY"); // theDepartments.Add("MEDICINE"); // theDepartments.Add("OBSTETRICS & GYNAECOLOGY"); // theDepartments.Add("OPHTHALMOLOGY"); // theDepartments.Add("ENT"); // theDepartments.Add("PAEDIATRICS"); // theDepartments.Add("PATHOLOGY"); // theDepartments.Add("COMMUNITY MEDICINE"); // theDepartments.Add("PSYCHIATRY"); // theDepartments.Add("RADIOLOGY"); // theDepartments.Add("RADIOTHERAPY"); // theDepartments.Add("COLLEGE OF MEDICINE STAFF"); // theDepartments.Add("STAFF CLINIC"); // theDepartments.Add("SURGERY"); // theDepartments.Add("OFFICE OF CMD"); // theDepartments.Add("CONSULTANT"); // theDepartments.Add("ORTHOPAEDIC & TRAUMA"); // theDepartments.Add("ACCIDENT & EMEGENCY"); // theDepartments.Add("NUCLEAR MEDICINE"); //// theDepartments.Add("RESTORATIVE DENTISTRY"); // theDepartments.Add("ORAL MAXILLOFACIAL SURGERY"); // theDepartments.Add("GERIATRICS"); // theDepartments.Add("HOUSE OFFICER"); //string theDepartment = foreach (string d in theDepartments) { List<Voter> theVoters = work.VoterRepository.Get(a => a.IdentityNumber != "chair" && a.IdentityNumber != "kazeem" && a.IdentityNumber != "password" && a.Department == d && a.IdentityNumber != "").OrderBy(a => a.IdentityNumber).ToList(); Font font_body4 = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 21); PdfPTable table3 = new PdfPTable(1); Paragraph paragraph3 = new Paragraph(d, font_body4); table3.AddCell(paragraph3); table1.AddCell(table3); // table1.AddCell(paragraph3); foreach (Voter v in theVoters) { PdfPTable table2 = new PdfPTable(1); string staffID = v.FirstName + " Student Matic No- " + v.Matric; string staffPassword = "******" + v.IdentityNumber + " PASSWORD: "******""); } document.Add(table1); // Create the heading paragraph with the headig font // Paragraph paragraph; // paragraph = new Paragraph("Hello world!", font_heading_1); // itextDoc.Add(table1); // Document thedoc = itextDoc;// print.PrinttheResultPrimary(studentName, Term, studentLevel, ref oStringWriter1, ref document); // Add a horizontal line below the headig text and add it to the paragraph iTextSharp.text.pdf.draw.VerticalPositionMark seperator = new iTextSharp.text.pdf.draw.LineSeparator(); seperator.Offset = -6f; // paragraph.Add(seperator); // Add paragraph to document // document.Add(paragraph); // Close the PDF document document.Close(); // Hat tip to David for his code on stackoverflow for this bit // http://stackoverflow.com/questions/779430/asp-net-mvc-how-to-get-view-to-generate-pdf byte[] file = ms.ToArray(); MemoryStream output = new MemoryStream(); output.Write(file, 0, file.Length); output.Position = 0; HttpContext.Response.AddHeader("content-disposition", "attachment; filename=form.pdf"); // Close the PDF document // document.Close(); return File(output, "application/pdf"); }
public ActionResult PrintResult(int id) { Result theResult = work.ResultRepository.GetByID(id); string[] SplitedClass = theResult.Class.Split(':'); string theClass = SplitedClass[0]; string[] theClassNumber = theClass.Split(null); string theNumber = theClassNumber[1]; StringWriter oStringWriter1 = new StringWriter(); Document itextDoc = new Document(PageSize.A4); itextDoc.Open(); Response.ContentType = "application/pdf"; // PrintResult print = new PrintResult(); // Set up the document and the MS to write it to and create the PDF writer instance MemoryStream ms = new MemoryStream(); //Document document = new Document(PageSize.A3.Rotate()); Document document = new Document(PageSize.A4); PdfWriter writer = PdfWriter.GetInstance(document, ms); // Open the PDF document document.Open(); Document thedoc = new Document(); if (!(string.IsNullOrEmpty(theNumber))) { int theNewNumber = Convert.ToInt16(theNumber); if(theNewNumber > 9) { thedoc = new PrintResultSenoir().PrintSilverDaleResult(theResult, ref oStringWriter1, ref document); } else { thedoc = new PrintResult().PrintSilverDaleResult(theResult, ref oStringWriter1, ref document); } } iTextSharp.text.pdf.draw.VerticalPositionMark seperator = new iTextSharp.text.pdf.draw.LineSeparator(); seperator.Offset = -6f; document.Close(); // Hat tip to David for his code on stackoverflow for this bit // http://stackoverflow.com/questions/779430/asp-net-mvc-how-to-get-view-to-generate-pdf byte[] file = ms.ToArray(); MemoryStream output = new MemoryStream(); output.Write(file, 0, file.Length); output.Position = 0; // work.DeductionHistoryRepository HttpContext.Response.AddHeader("content-disposition", "attachment; filename=Result.pdf"); return new FileStreamResult(output, "application/pdf"); //new FileStreamResult(output, "application/pdf"); }
public byte[] GeneratePDF(int EventBookingID) { MemoryStream memoryStream = new MemoryStream(); Document document = new Document(PageSize.A5, 0, 0, 0, 0); PdfWriter writer = PdfWriter.GetInstance(document, memoryStream); document.Open(); BookEvent bookEvent = new BookEvent(); bookEvent = db.BookEvents.Find(EventBookingID); var userName = User.Identity.GetUserName(); var student = db.students.Where(x => x.StudentEmail == userName).FirstOrDefault(); iTextSharp.text.Font font_heading_3 = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.RED); iTextSharp.text.Font font_body = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 9, iTextSharp.text.BaseColor.BLUE); // Create the heading paragraph with the headig font PdfPTable table1 = new PdfPTable(1); PdfPTable table2 = new PdfPTable(5); PdfPTable table3 = new PdfPTable(1); iTextSharp.text.pdf.draw.VerticalPositionMark seperator = new iTextSharp.text.pdf.draw.LineSeparator(); seperator.Offset = -6f; // Remove table cell table1.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER; table3.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER; table1.WidthPercentage = 80; table1.SetWidths(new float[] { 100 }); table2.WidthPercentage = 80; table3.SetWidths(new float[] { 100 }); table3.WidthPercentage = 80; PdfPCell cell = new PdfPCell(new Phrase("")); cell.Colspan = 3; table1.AddCell("\n"); table1.AddCell(cell); table1.AddCell("\n\n"); table1.AddCell( "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t" + "Blue Sky Car Rental \n" + "Email :[email protected]" + "\n" + "\n" + "\n"); table1.AddCell("------------Personal Details--------------!"); table1.AddCell("First Name : \t" + student.StudentName); table1.AddCell("Last Name : \t" + student.StudentSurname); table1.AddCell("Email : \t" + student.StudentEmail); table1.AddCell("Phone Number : \t" + student.StudentContact); table1.AddCell("Gender : \t" + student.StudentGender); table1.AddCell("Address : \t" + student.StudentAddress); table1.AddCell("\n------------Rental details--------------!\n"); table1.AddCell("Booking Ref. # : \t" + bookEvent.RefNum); table1.AddCell("Date Booked : \t" + bookEvent.DateBookinFor.ToShortDateString()); //table1.AddCell("Number Of days : \t" + @event.Duration); //table1.AddCell("Total Rental Cost Due: \t" + @event.Amount.ToString("C")); //table1.AddCell("Amount Paid: \t" + @event.AmountPaid.ToString("C")); //table1.AddCell("Status : \t" + @event.Status); //table1.AddCell("Deposit Payed date : \t" + DateTime.Now); table1.AddCell("\n"); table3.AddCell("------------Looking forward to hear from you soon--------------!"); //////Intergrate information into 1 document //var qrCode = iTextSharp.text.Image.GetInstance(reservation.QrCodeImage); //qrCode.ScaleToFit(200, 200); table1.AddCell(cell); document.Add(table1); //document.Add(qrCode); document.Add(table3); document.Close(); byte[] bytes = memoryStream.ToArray(); memoryStream.Close(); return(bytes); }
public void AddBreakRule() { iPdf.draw.LineSeparator line = new iPdf.draw.LineSeparator(1F, 100F, iText.BaseColor.DARK_GRAY, iText.Element.ALIGN_CENTER, -8F); document.Add(line); AddLine(" ", false); }
// FIXME: add to other writers? public void AddLineSeparator() { var line1 = new it.pdf.draw.LineSeparator(0.0f, 100.0f, BaseColor.BLACK, Element.ALIGN_LEFT, 1); fDocument.Add(new Chunk(line1)); }
public ActionResult Edit(SalaryPaymentHistoryViewModel model) { try { // TODO: Add update logic here List <SalaryPaymentHistory> thePaymentNow = new List <SalaryPaymentHistory>(); if (model != null) { List <SalaryPaymentHistory> theSalaryHistory = new List <SalaryPaymentHistory>(); theSalaryHistory = work.SalaryPaymentHistoryRepository.Get(a => a.DatePaid.Month == DateTime.Now.Month && a.DatePaid.Year == DateTime.Now.Year).ToList(); foreach (var staffPayment in model.TheSalaryPaymentHistory) { //check if there are payments logged aready // staffPayment. if (staffPayment.PaySalary == true) // { SalaryPaymentHistory individualPayment = new SalaryPaymentHistory(); individualPayment = new SalaryHelper().Lateness(staffPayment); individualPayment = new SalaryHelper().Abscent(staffPayment); individualPayment = new SalaryHelper().Loan(staffPayment); individualPayment = new SalaryHelper().ContributionsOrDeductions(staffPayment); thePaymentNow.Add(individualPayment); } } StringWriter oStringWriter1 = new StringWriter(); Document itextDoc = new Document(PageSize.LETTER); itextDoc.Open(); Response.ContentType = "application/pdf"; PrintResult print = new PrintResult(); // Set up the document and the MS to write it to and create the PDF writer instance MemoryStream ms = new MemoryStream(); //Document document = new Document(PageSize.A3.Rotate()); Document document = new Document(PageSize.A4); PdfWriter writer = PdfWriter.GetInstance(document, ms); // Open the PDF document document.Open(); Document thedoc = new SalaryPrinting().PrintPaySlip(thePaymentNow, ref oStringWriter1, ref document); iTextSharp.text.pdf.draw.VerticalPositionMark seperator = new iTextSharp.text.pdf.draw.LineSeparator(); seperator.Offset = -6f; document.Close(); // Hat tip to David for his code on stackoverflow for this bit // http://stackoverflow.com/questions/779430/asp-net-mvc-how-to-get-view-to-generate-pdf byte[] file = ms.ToArray(); MemoryStream output = new MemoryStream(); output.Write(file, 0, file.Length); output.Position = 0; if (theSalaryHistory.Count == 0) { //log payment decimal totalDeduction = 0; // decimal totalSalarytobeDeducted = 0; foreach (var m in thePaymentNow) { // m.ActualSalary // work.SalaryPaymentHistoryRepository.Insert(m); if (m.TotalLatenessDeduction > 0) { DeductionHistory theLateness = new DeductionHistory(); theLateness.AmountDeducted = Convert.ToDecimal(m.TotalLatenessDeduction); theLateness.DatePaid = DateTime.Now; theLateness.Description = "Lasteness Deduction for the Month " + string.Format("{0:MMMM-yyyy}", DateTime.Now); theLateness.StaffID = m.StaffID.ToString(); totalDeduction = totalDeduction + theLateness.AmountDeducted; work.DeductionHistoryRepository.Insert(theLateness); // theLateness. } if (m.TotalAbscentDeduction > 0) { DeductionHistory theLateness = new DeductionHistory(); theLateness.AmountDeducted = Convert.ToDecimal(m.TotalAbscentDeduction); theLateness.DatePaid = DateTime.Now; theLateness.Description = "Abscent Deduction for the Month " + string.Format("{0:MMMM-yyyy}", DateTime.Now); theLateness.StaffID = m.StaffID.ToString(); totalDeduction = totalDeduction + theLateness.AmountDeducted; work.DeductionHistoryRepository.Insert(theLateness); // theLateness. } if (m.TotalLoan > 0) { DeductionHistory theLateness = new DeductionHistory(); theLateness.AmountDeducted = Convert.ToDecimal(m.TotalLoan); theLateness.DatePaid = DateTime.Now; theLateness.Description = "Loan Deduction for the Month " + string.Format("{0:MMMM-yyyy}", DateTime.Now); theLateness.StaffID = m.StaffID.ToString(); totalDeduction = totalDeduction + theLateness.AmountDeducted; work.DeductionHistoryRepository.Insert(theLateness); // theLateness. } // other subscibed deductions foreach (var subscibed in m.TheDeduction) { if (subscibed != null) { DeductionHistory theLateness = new DeductionHistory(); theLateness.AmountDeducted = Convert.ToDecimal(subscibed.Amount); theLateness.DatePaid = DateTime.Now; theLateness.Description = subscibed.DeductionDescription + " Deduction for the Month " + string.Format("{0:MMMM-yyyy}", DateTime.Now); theLateness.StaffID = m.StaffID.ToString(); totalDeduction = totalDeduction + theLateness.AmountDeducted; work.DeductionHistoryRepository.Insert(theLateness); // work.Save(); } } //save the actual salary payment PrimarySchoolStaff theStaf = work.PrimarySchoolStaffRepository.Get(a => a.UserID == m.StaffID).First(); Salary theStaffSalary = work.SalaryRepository.GetByID(theStaf.SalaryID); m.ActualSalary = theStaffSalary.Amount; m.Description = "Salary Payment for the Month of " + string.Format("{0:MMMM-yyyy}", DateTime.Now); m.AmountPaid = theStaffSalary.Amount - totalDeduction; m.DatePaid = DateTime.Now; work.SalaryPaymentHistoryRepository.Insert(m); work.Save(); totalDeduction = 0; // SalaryPaymentHistory theHistory = new SalaryPaymentHistory{ AmountPaid = m.AmountPaid, ActualSalary = m.ActualSalary, DatePaid = DateTime.Now, Description = "Salary Payment for "+ DateTime.Now.Month, FirstName = m.FirstName} } } // work.DeductionHistoryRepository HttpContext.Response.AddHeader("content-disposition", "attachment; filename=form.pdf"); return(new FileStreamResult(output, "application/pdf")); //new FileStreamResult(output, "application/pdf"); //return RedirectToAction("Index", new FileStreamResult(output, "application/pdf")); // return new ActionAsPdf // } } return(RedirectToAction("Index")); } catch { return(View()); } }