AddElement() public method

public AddElement ( IElement element ) : void
element IElement
return void
Ejemplo n.º 1
1
// ---------------------------------------------------------------------------    
    /**
     * Creates a table with screenings.
     * @param day a film festival day
     * @return a table with screenings
     */
    public PdfPTable GetTable(string day) {
    // Create a table with 7 columns
      PdfPTable table = new PdfPTable(new float[] { 2, 1, 2, 5, 1, 3, 2 });
      table.WidthPercentage = 100f;
      table.DefaultCell.UseAscender = true;
      table.DefaultCell.UseDescender = true;
      // Add the first header row
      Font f = new Font();
      f.Color = BaseColor.WHITE;
      PdfPCell cell = new PdfPCell(new Phrase(day, f));
      cell.BackgroundColor = BaseColor.BLACK;
      cell.HorizontalAlignment = Element.ALIGN_CENTER;
      cell.Colspan = 7;
      table.AddCell(cell);
      // Add the second header row twice
      table.DefaultCell.BackgroundColor = BaseColor.LIGHT_GRAY;
      for (int i = 0; i < 2; i++) {
        table.AddCell("Location");
        table.AddCell("Time");
        table.AddCell("Run Length");
        table.AddCell("Title");
        table.AddCell("Year");
        table.AddCell("Directors");
        table.AddCell("Countries");
      }
      table.DefaultCell.BackgroundColor = null;
      // There are three special rows
      table.HeaderRows = 3;
      // One of them is a footer
      table.FooterRows = 1;
      // Now let's loop over the screenings
      List<Screening> screenings = PojoFactory.GetScreenings(day);
      Movie movie;
      foreach (Screening screening in screenings) {
        movie = screening.movie;
        table.AddCell(screening.Location);
        table.AddCell(screening.Time.Substring(0, 5));
        table.AddCell(movie.Duration.ToString() + " '");
        table.AddCell(movie.MovieTitle);
        table.AddCell(movie.Year.ToString());
        cell = new PdfPCell();
        cell.UseAscender = true;
        cell.UseDescender = true;
        cell.AddElement(PojoToElementFactory.GetDirectorList(movie));
        table.AddCell(cell);
        cell = new PdfPCell();
        cell.UseAscender = true;
        cell.UseDescender = true;
        cell.AddElement(PojoToElementFactory.GetCountryList(movie));
        table.AddCell(cell);
      }
      return table;
    }    
Ejemplo n.º 2
1
        private static void agregarIntimacionAdministrativaEncabezado(Document doc)
        {
            PdfPTable t = new PdfPTable(1);
            float[] widths = new float[] { 80f };
            t.WidthPercentage = 85;
            t.SetWidths(widths);
            int leading = 8;
            Paragraph p;
            PdfPCell c = new PdfPCell();

            c = new PdfPCell();
            c.Border = 0;
            c.PaddingTop = -2;
            c.Border = 0;
            c.BorderWidthBottom = 0;
            p = new Paragraph(leading, "CALVAGNA Consorcios - Maipú 1148 piso 10 Oficina 04 S2000CGN Rosario", calibri8I);
            c.AddElement(p);
            t.AddCell(c);

            c = new PdfPCell();
            c.Border = 0;
            c.PaddingTop = -2;
            c.Border = 0;
            c.BorderWidthBottom = 0;
            p = new Paragraph(leading, "Certificada plegada sin sobre con aviso de retorno. Copia en poder del remitente", calibri8I);
            c.AddElement(p);
            t.AddCell(c);

            c = new PdfPCell();
            c.Border = 0;
            c.PaddingTop = -2;
            c.Border = 0;
            c.BorderWidthBottom = 0;
            p = new Paragraph(leading, "INTIMACION  ADMINISTRATIVA - ULTIMO AVISO PREVIO A LEGALES", calibri8I);
            c.AddElement(p);
            t.AddCell(c);

            doc.Add(t);
        }
Ejemplo n.º 3
0
        private static PDF.PdfPCell GetFormattedCell(TableCell cell)
        {
            PDF.PdfPCell formattedCell = new PDF.PdfPCell();

            Element[] cellElements = cell.SubElements;

            foreach (Element temp in cellElements)
            {
                switch (temp.GetElementType())
                {
                    //TODO: Add other enum values
                    case ElementType.Text:
                        IT.Phrase phrase = new IT.Phrase(TextFormatter.GetFormattedText((Text)temp));
                        formattedCell.AddElement(phrase);
                        break;

                    case ElementType.Paragraph:
                        formattedCell.AddElement(ParagraphFormatter.GetFormattedParagraph((Paragraph)temp));
                        break;

                    case ElementType.Table:
                        formattedCell.AddElement(TableFormatter.GetFormattedTable((Table)temp));
                        break;

                    case ElementType.Image:
                        formattedCell.AddElement(ImageFormatter.GetFormattedImage((Image)temp));
                        break;
                }

            }

            return formattedCell;
        }
Ejemplo n.º 4
0
        private static PdfPTable CreateNestedTables(int n) {
            PdfPCell cell = new PdfPCell();
            cell.AddElement(new Chunk("Hello"));

            if (n > 0)
                cell.AddElement(CreateNestedTables(n - 1));

            PdfPTable table = new PdfPTable(1);
            table.AddCell(cell);
            return table;
        }
        public PdfPCell RenderingCell(CellAttributes attributes)
        {
            var pdfCell = new PdfPCell();
            var table = new PdfGrid(1) { RunDirection = PdfWriter.RUN_DIRECTION_LTR };

            var filePath = System.IO.Path.Combine(AppPath.ApplicationPath, "Images\\" + _rnd.Next(1, 5).ToString("00") + ".png");
            var photo = PdfImageHelper.GetITextSharpImageFromImageFile(filePath);
            table.AddCell(new PdfPCell(photo, fit: false)
            {
                Border = 0,
                VerticalAlignment = Element.ALIGN_BOTTOM,
                HorizontalAlignment = Element.ALIGN_CENTER
            });

            var name = attributes.RowData.TableRowData.GetSafeStringValueOf("User");
            table.AddCell(new PdfPCell(attributes.BasicProperties.PdfFont.FontSelector.Process(name))
            {
                Border = 0,
                HorizontalAlignment = Element.ALIGN_CENTER
            });

            pdfCell.AddElement(table);

            return pdfCell;
        }
Ejemplo n.º 6
0
 public static void AddPlainRow(this PdfPTable t, string s, Font bfont)
 {
     var c = new PdfPCell(t.DefaultCell);
     c.Border = PdfPCell.NO_BORDER;
     c.Colspan = t.NumberOfColumns;
     c.AddElement(new Phrase(s, bfont));
     t.AddCell(c);
 }
Ejemplo n.º 7
0
 public static void Add(this PdfPTable t, string s, int colspan, Font font)
 {
     var c = new PdfPCell(new Paragraph(s, font));
     c.Border = t.DefaultCell.Border;
     c.BackgroundColor = t.DefaultCell.BackgroundColor;
     c.SetLeading(t.DefaultCell.Leading, 1f);
     c.Colspan = colspan;
     c.AddElement(new Paragraph(s, font));
     t.AddCell(c);
 }
Ejemplo n.º 8
0
        // ---------------------------------------------------------------------------
        /**
         * Creates the PDF.
         * @return the bytes of a PDF file.
         */
        public byte[] CreateMoviePage(Movie movie)
        {
            using (MemoryStream ms = new MemoryStream()) {
            // step 1
            using (Document document = new Document()) {
              // step 2
              PdfWriter.GetInstance(document, ms);
              // step 3
              document.Open();
              // step 4
              Paragraph p = new Paragraph(
            movie.MovieTitle,
            FontFactory.GetFont(
              BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED, 16
            )
              );
              document.Add(p);
              document.Add(Chunk.NEWLINE);
              PdfPTable table = new PdfPTable(WIDTHS);
              table.AddCell(Image.GetInstance(
            String.Format(RESOURCE, movie.Imdb)
              ));
              PdfPCell cell = new PdfPCell();
              cell.AddElement(new Paragraph("Year: " + movie.Year.ToString()));
              cell.AddElement(new Paragraph("Duration: " + movie.Duration.ToString()));
              table.AddCell(cell);
              document.Add(table);

              PdfTargetDictionary target = new PdfTargetDictionary(false);
              target.AdditionalPath = new PdfTargetDictionary(false);
              Chunk chunk = new Chunk("Go to original document");
              PdfAction action = PdfAction.GotoEmbedded(
            null, target, new PdfString("movies"), false
              );
              chunk.SetAction(action);
              document.Add(chunk);
            }
            return ms.ToArray();
              }
        }
Ejemplo n.º 9
0
 // ===========================================================================
 public void Write(Stream stream)
 {
     // step 1
     using (Document document = new Document())
     {
         // step 2
         PdfWriter.GetInstance(document, stream);
         // step 3
         document.Open();
         // step 4
         string RESOURCE = Utility.ResourcePosters;
         // we'll use 4 images in this example
         Image[] img = {
             Image.GetInstance(Path.Combine(RESOURCE, "0120903.jpg")),
             Image.GetInstance(Path.Combine(RESOURCE, "0290334.jpg")),
             Image.GetInstance(Path.Combine(RESOURCE, "0376994.jpg")),
             Image.GetInstance(Path.Combine(RESOURCE, "0348150.jpg"))
         };
         // Creates a table with 6 columns
         PdfPTable table = new PdfPTable(6);
         table.WidthPercentage = 100;
         // first movie
         table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
         table.DefaultCell.VerticalAlignment = Element.ALIGN_TOP;
         table.AddCell("X-Men");
         // we wrap he image in a PdfPCell
         PdfPCell cell = new PdfPCell(img[0]);
         table.AddCell(cell);
         // second movie
         table.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
         table.AddCell("X2");
         // we wrap the image in a PdfPCell and let iText scale it
         cell = new PdfPCell(img[1], true);
         table.AddCell(cell);
         // third movie
         table.DefaultCell.VerticalAlignment = Element.ALIGN_BOTTOM;
         table.AddCell("X-Men: The Last Stand");
         // we add the image with addCell()
         table.AddCell(img[2]);
         // fourth movie
         table.AddCell("Superman Returns");
         cell = new PdfPCell();
         // we add it with addElement(); it can only take 50% of the width.
         img[3].WidthPercentage = 50;
         cell.AddElement(img[3]);
         table.AddCell(cell);
         // we complete the table (otherwise the last row won't be rendered)
         table.CompleteRow();
         document.Add(table);
     }
 }
Ejemplo n.º 10
0
 public static void AddRow(this PdfPTable t, string s, Font bfont)
 {
     t.AddCell("");
     t.CompleteRow();
     var c = new PdfPCell(t.DefaultCell);
     c.Border = PdfPCell.TOP_BORDER;
     c.BorderColorTop = BaseColor.BLACK;
     c.BorderWidthTop = 2.0f;
     c.Colspan = t.NumberOfColumns;
     c.AddElement(new Paragraph(s, bfont));
     c.GrayFill = .8f;
     t.AddCell(c);
     c.MinimumHeight = t.DefaultCell.MinimumHeight;
 }
Ejemplo n.º 11
0
        public override iTextSharp.text.IElement GeneratePdfElement()
        {
            PdfPanelStyle style = (Manifest != null) ? Manifest.Styles.GetMergedFromConfiguration(Style) : Style;

            iTextPdf.PdfPTable panel = new iTextPdf.PdfPTable(1)
            {
                HorizontalAlignment = (int)(style.HorizontalAlignment ?? PdfPanelStyle.Default.HorizontalAlignment.Value),
                SpacingBefore = style.TopIndent ?? PdfPanelStyle.Default.TopIndent.Value,
                SpacingAfter = style.BottomIndent ?? PdfPanelStyle.Default.BottomIndent.Value,
            };

            iTextPdf.PdfPCell cell = new iTextPdf.PdfPCell()
            {
                BackgroundColor = new BaseColor(style.BackgroundColor ?? PdfPanelStyle.Default.BackgroundColor.Value),
                BorderColor = new BaseColor(style.BorderColor ?? PdfPanelStyle.Default.BorderColor.Value),
                Border = iText.Rectangle.BOX,
                Padding = style.Padding ?? PdfPanelStyle.Default.Padding.Value,
                BorderWidth = style.BorderWidth ?? PdfPanelStyle.Default.BorderWidth.Value,
            };

            if (Content.Any())
            {
                Content.ForEach(e => cell.AddElement(e.GeneratePdfElement()));
            }

            panel.AddCell(cell);

            cell.SetLeading(style.Leading ?? PdfPanelStyle.Default.Leading.Value, 0);

            if (style.Width.HasValue && !style.Width.Value.IsBlank)
            {
                PdfUnit unit = style.Width.Value;
                if (unit.Type.IsPercentage())
                {
                    panel.WidthPercentage = unit.Value;
                }
                else
                {
                    panel.SetTotalWidth(new float[] { unit.Value });
                    panel.LockedWidth= true;
                }
            }

            return panel;
        }
Ejemplo n.º 12
0
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public PdfPCell RenderingCell(CellAttributes attributes)
        {
            var pdfCell = new PdfPCell();
            var table = new PdfGrid(1) { RunDirection = PdfWriter.RUN_DIRECTION_LTR };

            var photo = PdfImageHelper.GetITextSharpImageFromImageFile(System.IO.Path.Combine(AppPath.ApplicationPath, "Images\\" + _rnd.Next(1, 5).ToString("00") + ".png"));
            table.AddCell(new PdfPCell(photo) { Border = 0, MinimumHeight = photo.Height, VerticalAlignment = Element.ALIGN_BOTTOM });

            var name = attributes.RowData.TableRowData.GetSafeStringValueOf<User>(x => x.Name);
            table.AddCell(new PdfPCell(attributes.BasicProperties.PdfFont.FontSelector.Process(name)) { Border = 0 });

            var lastName = attributes.RowData.TableRowData.GetSafeStringValueOf<User>(x => x.LastName);
            table.AddCell(new PdfPCell(attributes.BasicProperties.PdfFont.FontSelector.Process(lastName)) { Border = 0 });

            pdfCell.AddElement(table);

            return pdfCell;
        }
Ejemplo n.º 13
0
 // ---------------------------------------------------------------------------   
 /**
  * Create a table with information about a movie.
  * @param screening a Screening
  * @return a table
  */
 private PdfPTable GetTable(Screening screening)
 {
     // Create a table with 4 columns
     PdfPTable table = new PdfPTable(4);
     table.SetWidths(new int[] { 1, 5, 10, 10 });
     // Get the movie
     Movie movie = screening.movie;
     // A cell with the title as a nested table spanning the complete row
     PdfPCell cell = new PdfPCell();
     // nesting is done with addElement() in this example
     cell.AddElement(FullTitle(screening));
     cell.Colspan = 4;
     cell.Border = PdfPCell.NO_BORDER;
     BaseColor color = WebColors.GetRGBColor(
       "#" + movie.entry.category.color
     );
     cell.BackgroundColor = color;
     table.AddCell(cell);
     // empty cell
     cell = new PdfPCell();
     cell.Border = PdfPCell.NO_BORDER;
     cell.UseAscender = true;
     cell.UseDescender = true;
     table.AddCell(cell);
     // cell with the movie poster
     cell = new PdfPCell(GetImage(movie.Imdb));
     cell.Border = PdfPCell.NO_BORDER;
     table.AddCell(cell);
     // cell with the list of directors
     cell = new PdfPCell();
     cell.AddElement(PojoToElementFactory.GetDirectorList(movie));
     cell.Border = PdfPCell.NO_BORDER;
     cell.UseAscender = true;
     cell.UseDescender = true;
     table.AddCell(cell);
     // cell with the list of countries
     cell = new PdfPCell();
     cell.AddElement(PojoToElementFactory.GetCountryList(movie));
     cell.Border = PdfPCell.NO_BORDER;
     cell.UseAscender = true;
     cell.UseDescender = true;
     table.AddCell(cell);
     return table;
 }
Ejemplo n.º 14
0
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public PdfPCell RenderingCell(CellAttributes attributes)
        {
            var pdfCell = new PdfPCell();
            var table = new PdfGrid(1) { RunDirection = PdfWriter.RUN_DIRECTION_LTR };

            // Please note that All columns and properties of an object will create a single cell here.

            var idx = attributes.RowData.ColumnNumber;
            var data = attributes.RowData.TableRowData;

            var character = data.GetSafeStringValueOf<CharacterInfo>(x => x.Character, propertyIndex: idx);
            table.AddCell(new PdfPCell(_customFont.FontSelector.Process(character)) { Border = 0, HorizontalAlignment = Element.ALIGN_CENTER });

            var characterCode = data.GetSafeStringValueOf<CharacterInfo>(x => x.CharacterCode, propertyIndex: idx);
            table.AddCell(new PdfPCell(attributes.BasicProperties.PdfFont.FontSelector.Process(characterCode)) { Border = 0, HorizontalAlignment = Element.ALIGN_CENTER });

            pdfCell.AddElement(table);

            return pdfCell;
        }
Ejemplo n.º 15
0
        /// <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, IList<Order> orders, int languageId = 0)
        {
            if (stream == null)
                throw new ArgumentNullException("stream");

            if (orders == null)
                throw new ArgumentNullException("orders");

            var pageSize = PageSize.A4;

            if (_pdfSettings.LetterPageSizeEnabled)
            {
                pageSize = PageSize.LETTER;
            }

            var doc = new Document(pageSize);
            var pdfWriter = PdfWriter.GetInstance(doc, stream);
            doc.Open();

            //fonts
            var titleFont = GetFont();
            titleFont.SetStyle(Font.BOLD);
            titleFont.Color = BaseColor.BLACK;
            var font = GetFont();
            var attributesFont = GetFont();
            attributesFont.SetStyle(Font.ITALIC);

            int ordCount = orders.Count;
            int ordNum = 0;

            foreach (var order in orders)
            {
                //by default _pdfSettings contains settings for the current active store
                //and we need PdfSettings for the store which was used to place an order
                //so let's load it based on a store of the current order
                var pdfSettingsByStore = _settingContext.LoadSetting<PdfSettings>(order.StoreId);

                var lang = _languageService.GetLanguageById(languageId == 0 ? order.CustomerLanguageId : languageId);
                if (lang == null || !lang.Published)
                    lang = _workContext.WorkingLanguage;

                #region Header

                //logo
                var logoPicture = _pictureService.GetPictureById(pdfSettingsByStore.LogoPictureId);
                var logoExists = logoPicture != null;

                //header
                var headerTable = new PdfPTable(logoExists ? 2 : 1);
                headerTable.RunDirection = GetDirection(lang);
                headerTable.DefaultCell.Border = Rectangle.NO_BORDER;

                //store info
                var store = _storeService.GetStoreById(order.StoreId) ?? _storeContext.CurrentStore;
                var anchor = new Anchor(store.Url.Trim(new [] { '/' }), font);
                anchor.Reference = store.Url;

                var cellHeader = new PdfPCell(new Phrase(String.Format(_localizationService.GetResource("PDFInvoice.Order#", lang.Id), order.Id), titleFont));
                cellHeader.Phrase.Add(new Phrase(Environment.NewLine));
                cellHeader.Phrase.Add(new Phrase(anchor));
                cellHeader.Phrase.Add(new Phrase(Environment.NewLine));
                cellHeader.Phrase.Add(new Phrase(String.Format(_localizationService.GetResource("PDFInvoice.OrderDate", lang.Id), _dateTimeHelper.ConvertToUserTime(order.CreatedOnUtc, DateTimeKind.Utc).ToString("D", new CultureInfo(lang.LanguageCulture))), font));
                cellHeader.Phrase.Add(new Phrase(Environment.NewLine));
                cellHeader.Phrase.Add(new Phrase(Environment.NewLine));
                cellHeader.HorizontalAlignment = Element.ALIGN_LEFT;
                cellHeader.Border = Rectangle.NO_BORDER;

                headerTable.AddCell(cellHeader);

                if (logoExists)
                    if (lang.Rtl)
                        headerTable.SetWidths(new[] { 0.2f, 0.8f });
                    else
                        headerTable.SetWidths(new[] { 0.8f, 0.2f });
                headerTable.WidthPercentage = 100f;

                //logo
                if (logoExists)
                {
                    var logoFilePath = _pictureService.GetThumbLocalPath(logoPicture, 0, false);
                    var logo = Image.GetInstance(logoFilePath);
                    logo.Alignment = GetAlignment(lang, true);
                    logo.ScaleToFit(65f, 65f);

                    var cellLogo = new PdfPCell();
                    cellLogo.Border = Rectangle.NO_BORDER;
                    cellLogo.AddElement(logo);
                    headerTable.AddCell(cellLogo);
                }
                doc.Add(headerTable);

                #endregion

                #region Addresses

                var addressTable = new PdfPTable(2);
                addressTable.RunDirection = GetDirection(lang);
                addressTable.DefaultCell.Border = Rectangle.NO_BORDER;
                addressTable.WidthPercentage = 100f;
                addressTable.SetWidths(new[] { 50, 50 });

                //billing info
                var billingAddress = new PdfPTable(1);
                billingAddress.DefaultCell.Border = Rectangle.NO_BORDER;
                billingAddress.RunDirection = GetDirection(lang);

                billingAddress.AddCell(new Paragraph(_localizationService.GetResource("PDFInvoice.BillingInformation", lang.Id), titleFont));

                if (_addressSettings.CompanyEnabled && !String.IsNullOrEmpty(order.BillingAddress.Company))
                    billingAddress.AddCell(new Paragraph("   " + String.Format(_localizationService.GetResource("PDFInvoice.Company", lang.Id), order.BillingAddress.Company), font));

                billingAddress.AddCell(new Paragraph("   " + String.Format(_localizationService.GetResource("PDFInvoice.Name", lang.Id), order.BillingAddress.FirstName + " " + order.BillingAddress.LastName), font));
                if (_addressSettings.PhoneEnabled)
                    billingAddress.AddCell(new Paragraph("   " + String.Format(_localizationService.GetResource("PDFInvoice.Phone", lang.Id), order.BillingAddress.PhoneNumber), font));
                if (_addressSettings.FaxEnabled && !String.IsNullOrEmpty(order.BillingAddress.FaxNumber))
                    billingAddress.AddCell(new Paragraph("   " + String.Format(_localizationService.GetResource("PDFInvoice.Fax", lang.Id), order.BillingAddress.FaxNumber), font));
                if (_addressSettings.StreetAddressEnabled)
                    billingAddress.AddCell(new Paragraph("   " + String.Format(_localizationService.GetResource("PDFInvoice.Address", lang.Id), order.BillingAddress.Address1), font));
                if (_addressSettings.StreetAddress2Enabled && !String.IsNullOrEmpty(order.BillingAddress.Address2))
                    billingAddress.AddCell(new Paragraph("   " + String.Format(_localizationService.GetResource("PDFInvoice.Address2", lang.Id), order.BillingAddress.Address2), font));
                if (_addressSettings.CityEnabled || _addressSettings.StateProvinceEnabled || _addressSettings.ZipPostalCodeEnabled)
                    billingAddress.AddCell(new Paragraph("   " + String.Format("{0}, {1} {2}", order.BillingAddress.City, order.BillingAddress.StateProvince != null ? order.BillingAddress.StateProvince.GetLocalized(x => x.Name, lang.Id) : "", order.BillingAddress.ZipPostalCode), font));
                if (_addressSettings.CountryEnabled && order.BillingAddress.Country != null)
                    billingAddress.AddCell(new Paragraph("   " + String.Format("{0}", order.BillingAddress.Country != null ? order.BillingAddress.Country.GetLocalized(x => x.Name, lang.Id) : ""), font));

                //VAT number
                if (!String.IsNullOrEmpty(order.VatNumber))
                    billingAddress.AddCell(new Paragraph("   " + String.Format(_localizationService.GetResource("PDFInvoice.VATNumber", lang.Id), order.VatNumber), font));

                //custom attributes
                var customBillingAddressAttributes = _addressAttributeFormatter.FormatAttributes( order.BillingAddress.CustomAttributes);
                if (!String.IsNullOrEmpty(customBillingAddressAttributes))
                {
                    //TODO: we should add padding to each line (in case if we have sevaral custom address attributes)
                    billingAddress.AddCell(new Paragraph("   " + HtmlHelper.ConvertHtmlToPlainText(customBillingAddressAttributes, true, true), font));
                }

                //payment method
                var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(order.PaymentMethodSystemName);
                string paymentMethodStr = paymentMethod != null ? paymentMethod.GetLocalizedFriendlyName(_localizationService, lang.Id) : order.PaymentMethodSystemName;
                if (!String.IsNullOrEmpty(paymentMethodStr))
                {
                    billingAddress.AddCell(new Paragraph(" "));
                    billingAddress.AddCell(new Paragraph("   " + String.Format(_localizationService.GetResource("PDFInvoice.PaymentMethod", lang.Id), paymentMethodStr), font));
                    billingAddress.AddCell(new Paragraph());
                }

                //custom values
                var customValues = order.DeserializeCustomValues();
                if (customValues != null)
                {
                    foreach (var item in customValues)
                    {
                        billingAddress.AddCell(new Paragraph(" "));
                        billingAddress.AddCell(new Paragraph("   " + item.Key + ": " + item.Value, font));
                        billingAddress.AddCell(new Paragraph());
                    }
                }

                addressTable.AddCell(billingAddress);

                //shipping info
                var shippingAddress = new PdfPTable(1);
                shippingAddress.DefaultCell.Border = Rectangle.NO_BORDER;
                shippingAddress.RunDirection = GetDirection(lang);

                if (order.ShippingStatus != ShippingStatus.ShippingNotRequired)
                {
                    //cell = new PdfPCell();
                    //cell.Border = Rectangle.NO_BORDER;

                    if (!order.PickUpInStore)
                    {
                        if (order.ShippingAddress == null)
                            throw new NopException(string.Format("Shipping is required, but address is not available. Order ID = {0}", order.Id));

                        shippingAddress.AddCell(new Paragraph(_localizationService.GetResource("PDFInvoice.ShippingInformation", lang.Id), titleFont));
                        if (!String.IsNullOrEmpty(order.ShippingAddress.Company))
                            shippingAddress.AddCell(new Paragraph("   " + String.Format(_localizationService.GetResource("PDFInvoice.Company", lang.Id), order.ShippingAddress.Company), font));
                        shippingAddress.AddCell(new Paragraph("   " + String.Format(_localizationService.GetResource("PDFInvoice.Name", lang.Id), order.ShippingAddress.FirstName + " " + order.ShippingAddress.LastName), font));
                        if (_addressSettings.PhoneEnabled)
                            shippingAddress.AddCell(new Paragraph("   " + String.Format(_localizationService.GetResource("PDFInvoice.Phone", lang.Id), order.ShippingAddress.PhoneNumber), font));
                        if (_addressSettings.FaxEnabled && !String.IsNullOrEmpty(order.ShippingAddress.FaxNumber))
                            shippingAddress.AddCell(new Paragraph("   " + String.Format(_localizationService.GetResource("PDFInvoice.Fax", lang.Id), order.ShippingAddress.FaxNumber), font));
                        if (_addressSettings.StreetAddressEnabled)
                            shippingAddress.AddCell(new Paragraph("   " + String.Format(_localizationService.GetResource("PDFInvoice.Address", lang.Id), order.ShippingAddress.Address1), font));
                        if (_addressSettings.StreetAddress2Enabled && !String.IsNullOrEmpty(order.ShippingAddress.Address2))
                            shippingAddress.AddCell(new Paragraph("   " + String.Format(_localizationService.GetResource("PDFInvoice.Address2", lang.Id), order.ShippingAddress.Address2), font));
                        if (_addressSettings.CityEnabled || _addressSettings.StateProvinceEnabled || _addressSettings.ZipPostalCodeEnabled)
                            shippingAddress.AddCell(new Paragraph("   " + String.Format("{0}, {1} {2}", order.ShippingAddress.City, order.ShippingAddress.StateProvince != null ? order.ShippingAddress.StateProvince.GetLocalized(x => x.Name, lang.Id) : "", order.ShippingAddress.ZipPostalCode), font));
                        if (_addressSettings.CountryEnabled && order.ShippingAddress.Country != null)
                            shippingAddress.AddCell(new Paragraph("   " + String.Format("{0}", order.ShippingAddress.Country != null ? order.ShippingAddress.Country.GetLocalized(x => x.Name, lang.Id) : ""), font));
                        //custom attributes
                        var customShippingAddressAttributes = _addressAttributeFormatter.FormatAttributes(order.ShippingAddress.CustomAttributes);
                        if (!String.IsNullOrEmpty(customShippingAddressAttributes))
                        {
                            //TODO: we should add padding to each line (in case if we have sevaral custom address attributes)
                            shippingAddress.AddCell(new Paragraph("   " + HtmlHelper.ConvertHtmlToPlainText(customShippingAddressAttributes, true, true), font));
                        }
                        shippingAddress.AddCell(new Paragraph(" "));
                    }
                    shippingAddress.AddCell(new Paragraph("   " + String.Format(_localizationService.GetResource("PDFInvoice.ShippingMethod", lang.Id), order.ShippingMethod), font));
                    shippingAddress.AddCell(new Paragraph());

                    addressTable.AddCell(shippingAddress);
                }
                else
                {
                    shippingAddress.AddCell(new Paragraph());
                    addressTable.AddCell(shippingAddress);
                }

                doc.Add(addressTable);
                doc.Add(new Paragraph(" "));

                #endregion

                #region Products

                //products
                var productsHeader = new PdfPTable(1);
                productsHeader.RunDirection = GetDirection(lang);
                productsHeader.WidthPercentage = 100f;
                var cellProducts = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.Product(s)", lang.Id), titleFont));
                cellProducts.Border = Rectangle.NO_BORDER;
                productsHeader.AddCell(cellProducts);
                doc.Add(productsHeader);
                doc.Add(new Paragraph(" "));

                var orderItems = _orderService.GetAllOrderItems(order.Id, null, null, null, null, null, null);

                var productsTable = new PdfPTable(_catalogSettings.ShowProductSku ? 5 : 4);
                productsTable.RunDirection = GetDirection(lang);
                productsTable.WidthPercentage = 100f;
                if (lang.Rtl)
                {
                    productsTable.SetWidths(_catalogSettings.ShowProductSku
                        ? new[] {15, 10, 15, 15, 45}
                        : new[] {20, 10, 20, 50});
                }
                else
                {
                    productsTable.SetWidths(_catalogSettings.ShowProductSku
                        ? new[] {45, 15, 15, 10, 15}
                        : new[] {50, 20, 10, 20});
                }

                //product name
                var cellProductItem = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.ProductName", lang.Id), font));
                cellProductItem.BackgroundColor = BaseColor.LIGHT_GRAY;
                cellProductItem.HorizontalAlignment = Element.ALIGN_CENTER;
                productsTable.AddCell(cellProductItem);

                //SKU
                if (_catalogSettings.ShowProductSku)
                {
                    cellProductItem = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.SKU", lang.Id), font));
                    cellProductItem.BackgroundColor = BaseColor.LIGHT_GRAY;
                    cellProductItem.HorizontalAlignment = Element.ALIGN_CENTER;
                    productsTable.AddCell(cellProductItem);
                }

                //price
                cellProductItem = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.ProductPrice", lang.Id), font));
                cellProductItem.BackgroundColor = BaseColor.LIGHT_GRAY;
                cellProductItem.HorizontalAlignment = Element.ALIGN_CENTER;
                productsTable.AddCell(cellProductItem);

                //qty
                cellProductItem = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.ProductQuantity", lang.Id), font));
                cellProductItem.BackgroundColor = BaseColor.LIGHT_GRAY;
                cellProductItem.HorizontalAlignment = Element.ALIGN_CENTER;
                productsTable.AddCell(cellProductItem);

                //total
                cellProductItem = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.ProductTotal", lang.Id), font));
                cellProductItem.BackgroundColor = BaseColor.LIGHT_GRAY;
                cellProductItem.HorizontalAlignment = Element.ALIGN_CENTER;
                productsTable.AddCell(cellProductItem);

                foreach (var orderItem in orderItems)
                {
                    var pAttribTable = new PdfPTable(1);
                    pAttribTable.RunDirection = GetDirection(lang);
                    pAttribTable.DefaultCell.Border = Rectangle.NO_BORDER;

                    var p = orderItem.Product;

                    //product name
                    string name = p.GetLocalized(x => x.Name, lang.Id);
                    pAttribTable.AddCell(new Paragraph(name, font));
                    cellProductItem.AddElement(new Paragraph(name, font));
                    //attributes
                    if (!String.IsNullOrEmpty(orderItem.AttributeDescription))
                    {
                        var attributesParagraph = new Paragraph(HtmlHelper.ConvertHtmlToPlainText(orderItem.AttributeDescription, true, true), attributesFont);
                        pAttribTable.AddCell(attributesParagraph);
                    }
                    //rental info
                    if (orderItem.Product.IsRental)
                    {
                        var rentalStartDate = orderItem.RentalStartDateUtc.HasValue ? orderItem.Product.FormatRentalDate(orderItem.RentalStartDateUtc.Value) : "";
                        var rentalEndDate = orderItem.RentalEndDateUtc.HasValue ? orderItem.Product.FormatRentalDate(orderItem.RentalEndDateUtc.Value) : "";
                        var rentalInfo = string.Format(_localizationService.GetResource("Order.Rental.FormattedDate"),
                            rentalStartDate, rentalEndDate);

                        var rentalInfoParagraph = new Paragraph(rentalInfo, attributesFont);
                        pAttribTable.AddCell(rentalInfoParagraph);
                    }
                    productsTable.AddCell(pAttribTable);

                    //SKU
                    if (_catalogSettings.ShowProductSku)
                    {
                        var sku = p.FormatSku(orderItem.AttributesXml, _productAttributeParser);
                        cellProductItem = new PdfPCell(new Phrase(sku ?? String.Empty, font));
                        cellProductItem.HorizontalAlignment = Element.ALIGN_CENTER;
                        productsTable.AddCell(cellProductItem);
                    }

                    //price
                    string unitPrice;
                    if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax)
                    {
                        //including tax
                        var unitPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceInclTax, order.CurrencyRate);
                        unitPrice = _priceFormatter.FormatPrice(unitPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true);
                    }
                    else
                    {
                        //excluding tax
                        var unitPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceExclTax, order.CurrencyRate);
                        unitPrice = _priceFormatter.FormatPrice(unitPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false);
                    }
                    cellProductItem = new PdfPCell(new Phrase(unitPrice, font));
                    cellProductItem.HorizontalAlignment = Element.ALIGN_LEFT;
                    productsTable.AddCell(cellProductItem);

                    //qty
                    cellProductItem = new PdfPCell(new Phrase(orderItem.Quantity.ToString(), font));
                    cellProductItem.HorizontalAlignment = Element.ALIGN_LEFT;
                    productsTable.AddCell(cellProductItem);

                    //total
                    string subTotal;
                    if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax)
                    {
                        //including tax
                        var priceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.PriceInclTax, order.CurrencyRate);
                        subTotal = _priceFormatter.FormatPrice(priceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true);
                    }
                    else
                    {
                        //excluding tax
                        var priceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.PriceExclTax, order.CurrencyRate);
                        subTotal = _priceFormatter.FormatPrice(priceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false);
                    }
                    cellProductItem = new PdfPCell(new Phrase(subTotal, font));
                    cellProductItem.HorizontalAlignment = Element.ALIGN_LEFT;
                    productsTable.AddCell(cellProductItem);
                }
                doc.Add(productsTable);

                #endregion

                #region Checkout attributes

                if (!String.IsNullOrEmpty(order.CheckoutAttributeDescription))
                {
                    doc.Add(new Paragraph(" "));
                    var attribTable = new PdfPTable(1);
                    attribTable.RunDirection = GetDirection(lang);
                    attribTable.WidthPercentage = 100f;

                    string attributes = HtmlHelper.ConvertHtmlToPlainText(order.CheckoutAttributeDescription, true, true);
                    var cCheckoutAttributes = new PdfPCell(new Phrase(attributes, font));
                    cCheckoutAttributes.Border = Rectangle.NO_BORDER;
                    cCheckoutAttributes.HorizontalAlignment = Element.ALIGN_RIGHT;
                    attribTable.AddCell(cCheckoutAttributes);
                    doc.Add(attribTable);
                }

                #endregion

                #region Totals

                //subtotal
                var totalsTable = new PdfPTable(1);
                totalsTable.RunDirection = GetDirection(lang);
                totalsTable.DefaultCell.Border = Rectangle.NO_BORDER;
                totalsTable.WidthPercentage = 100f;

                //order subtotal
                if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax && !_taxSettings.ForceTaxExclusionFromOrderSubtotal)
                {
                    //including tax

                    var orderSubtotalInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalInclTax, order.CurrencyRate);
                    string orderSubtotalInclTaxStr = _priceFormatter.FormatPrice(orderSubtotalInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true);

                    var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Sub-Total", lang.Id), orderSubtotalInclTaxStr), font));
                    p.HorizontalAlignment = Element.ALIGN_RIGHT;
                    p.Border = Rectangle.NO_BORDER;
                    totalsTable.AddCell(p);
                }
                else
                {
                    //excluding tax

                    var orderSubtotalExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalExclTax, order.CurrencyRate);
                    string orderSubtotalExclTaxStr = _priceFormatter.FormatPrice(orderSubtotalExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false);

                    var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Sub-Total", lang.Id), orderSubtotalExclTaxStr), font));
                    p.HorizontalAlignment = Element.ALIGN_RIGHT;
                    p.Border = Rectangle.NO_BORDER;
                    totalsTable.AddCell(p);
                }

                //discount (applied to order subtotal)
                if (order.OrderSubTotalDiscountExclTax > decimal.Zero)
                {
                    //order subtotal
                    if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax && !_taxSettings.ForceTaxExclusionFromOrderSubtotal)
                    {
                        //including tax

                        var orderSubTotalDiscountInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountInclTax, order.CurrencyRate);
                        string orderSubTotalDiscountInCustomerCurrencyStr = _priceFormatter.FormatPrice(-orderSubTotalDiscountInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true);

                        var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Discount", lang.Id), orderSubTotalDiscountInCustomerCurrencyStr), font));
                        p.HorizontalAlignment = Element.ALIGN_RIGHT;
                        p.Border = Rectangle.NO_BORDER;
                        totalsTable.AddCell(p);
                    }
                    else
                    {
                        //excluding tax

                        var orderSubTotalDiscountExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountExclTax, order.CurrencyRate);
                        string orderSubTotalDiscountInCustomerCurrencyStr = _priceFormatter.FormatPrice(-orderSubTotalDiscountExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false);

                        var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Discount", lang.Id), orderSubTotalDiscountInCustomerCurrencyStr), font));
                        p.HorizontalAlignment = Element.ALIGN_RIGHT;
                        p.Border = Rectangle.NO_BORDER;
                        totalsTable.AddCell(p);
                    }
                }

                //shipping
                if (order.ShippingStatus != ShippingStatus.ShippingNotRequired)
                {
                    if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax)
                    {
                        //including tax
                        var orderShippingInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingInclTax, order.CurrencyRate);
                        string orderShippingInclTaxStr = _priceFormatter.FormatShippingPrice(orderShippingInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true);

                        var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Shipping", lang.Id), orderShippingInclTaxStr), font));
                        p.HorizontalAlignment = Element.ALIGN_RIGHT;
                        p.Border = Rectangle.NO_BORDER;
                        totalsTable.AddCell(p);
                    }
                    else
                    {
                        //excluding tax
                        var orderShippingExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingExclTax, order.CurrencyRate);
                        string orderShippingExclTaxStr = _priceFormatter.FormatShippingPrice(orderShippingExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false);

                        var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Shipping", lang.Id), orderShippingExclTaxStr), font));
                        p.HorizontalAlignment = Element.ALIGN_RIGHT;
                        p.Border = Rectangle.NO_BORDER;
                        totalsTable.AddCell(p);
                    }
                }

                //payment fee
                if (order.PaymentMethodAdditionalFeeExclTax > decimal.Zero)
                {
                    if (order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax)
                    {
                        //including tax
                        var paymentMethodAdditionalFeeInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeInclTax, order.CurrencyRate);
                        string paymentMethodAdditionalFeeInclTaxStr = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true);

                        var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.PaymentMethodAdditionalFee", lang.Id), paymentMethodAdditionalFeeInclTaxStr), font));
                        p.HorizontalAlignment = Element.ALIGN_RIGHT;
                        p.Border = Rectangle.NO_BORDER;
                        totalsTable.AddCell(p);
                    }
                    else
                    {
                        //excluding tax
                        var paymentMethodAdditionalFeeExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeExclTax, order.CurrencyRate);
                        string paymentMethodAdditionalFeeExclTaxStr = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false);

                        var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.PaymentMethodAdditionalFee", lang.Id), paymentMethodAdditionalFeeExclTaxStr), font));
                        p.HorizontalAlignment = Element.ALIGN_RIGHT;
                        p.Border = Rectangle.NO_BORDER;
                        totalsTable.AddCell(p);
                    }
                }

                //tax
                string taxStr = string.Empty;
                var taxRates = new SortedDictionary<decimal, decimal>();
                bool displayTax = true;
                bool displayTaxRates = true;
                if (_taxSettings.HideTaxInOrderSummary && order.CustomerTaxDisplayType == TaxDisplayType.IncludingTax)
                {
                    displayTax = false;
                }
                else
                {
                    if (order.OrderTax == 0 && _taxSettings.HideZeroTax)
                    {
                        displayTax = false;
                        displayTaxRates = false;
                    }
                    else
                    {
                        taxRates = order.TaxRatesDictionary;

                        displayTaxRates = _taxSettings.DisplayTaxRates && taxRates.Count > 0;
                        displayTax = !displayTaxRates;

                        var orderTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTax, order.CurrencyRate);
                        taxStr = _priceFormatter.FormatPrice(orderTaxInCustomerCurrency, true, order.CustomerCurrencyCode, false, lang);
                    }
                }
                if (displayTax)
                {
                    var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Tax", lang.Id), taxStr), font));
                    p.HorizontalAlignment = Element.ALIGN_RIGHT;
                    p.Border = Rectangle.NO_BORDER;
                    totalsTable.AddCell(p);
                }
                if (displayTaxRates)
                {
                    foreach (var item in taxRates)
                    {
                        string taxRate = String.Format(_localizationService.GetResource("PDFInvoice.TaxRate", lang.Id), _priceFormatter.FormatTaxRate(item.Key));
                        string taxValue = _priceFormatter.FormatPrice(_currencyService.ConvertCurrency(item.Value, order.CurrencyRate), true, order.CustomerCurrencyCode, false, lang);

                        var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", taxRate, taxValue), font));
                        p.HorizontalAlignment = Element.ALIGN_RIGHT;
                        p.Border = Rectangle.NO_BORDER;
                        totalsTable.AddCell(p);
                    }
                }

                //discount (applied to order total)
                if (order.OrderDiscount > decimal.Zero)
                {
                    var orderDiscountInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderDiscount, order.CurrencyRate);
                    string orderDiscountInCustomerCurrencyStr = _priceFormatter.FormatPrice(-orderDiscountInCustomerCurrency, true, order.CustomerCurrencyCode, false, lang);

                    var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Discount", lang.Id), orderDiscountInCustomerCurrencyStr), font));
                    p.HorizontalAlignment = Element.ALIGN_RIGHT;
                    p.Border = Rectangle.NO_BORDER;
                    totalsTable.AddCell(p);
                }

                //gift cards
                foreach (var gcuh in order.GiftCardUsageHistory)
                {
                    string gcTitle = string.Format(_localizationService.GetResource("PDFInvoice.GiftCardInfo", lang.Id), gcuh.GiftCard.GiftCardCouponCode);
                    string gcAmountStr = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(gcuh.UsedValue, order.CurrencyRate)), true, order.CustomerCurrencyCode, false, lang);

                    var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", gcTitle, gcAmountStr), font));
                    p.HorizontalAlignment = Element.ALIGN_RIGHT;
                    p.Border = Rectangle.NO_BORDER;
                    totalsTable.AddCell(p);
                }

                //reward points
                if (order.RedeemedRewardPointsEntry != null)
                {
                    string rpTitle = string.Format(_localizationService.GetResource("PDFInvoice.RewardPoints", lang.Id), -order.RedeemedRewardPointsEntry.Points);
                    string rpAmount = _priceFormatter.FormatPrice(-(_currencyService.ConvertCurrency(order.RedeemedRewardPointsEntry.UsedAmount, order.CurrencyRate)), true, order.CustomerCurrencyCode, false, lang);

                    var p = new PdfPCell(new Paragraph(String.Format("{0} {1}", rpTitle, rpAmount), font));
                    p.HorizontalAlignment = Element.ALIGN_RIGHT;
                    p.Border = Rectangle.NO_BORDER;
                    totalsTable.AddCell(p);
                }

                //order total
                var orderTotalInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderTotal, order.CurrencyRate);
                string orderTotalStr = _priceFormatter.FormatPrice(orderTotalInCustomerCurrency, true, order.CustomerCurrencyCode, false, lang);

                var pTotal = new PdfPCell(new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.OrderTotal", lang.Id), orderTotalStr), titleFont));
                pTotal.HorizontalAlignment = Element.ALIGN_RIGHT;
                pTotal.Border = Rectangle.NO_BORDER;
                totalsTable.AddCell(pTotal);

                doc.Add(totalsTable);

                #endregion

                #region Order notes

                if (pdfSettingsByStore.RenderOrderNotes)
                {
                    var orderNotes = order.OrderNotes
                        .Where(on => on.DisplayToCustomer)
                        .OrderByDescending(on => on.CreatedOnUtc)
                        .ToList();
                    if (orderNotes.Count > 0)
                    {
                        var notesHeader = new PdfPTable(1);
                        notesHeader.RunDirection = GetDirection(lang);
                        notesHeader.WidthPercentage = 100f;
                        var cellOrderNote = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.OrderNotes", lang.Id), titleFont));
                        cellOrderNote.Border = Rectangle.NO_BORDER;
                        notesHeader.AddCell(cellOrderNote);
                        doc.Add(notesHeader);
                        doc.Add(new Paragraph(" "));

                        var notesTable = new PdfPTable(2);
                        notesTable.RunDirection = GetDirection(lang);
                        if (lang.Rtl)
                        {
                            notesTable.SetWidths(new[] {70, 30});
                        }
                        else
                        {
                            notesTable.SetWidths(new[] {30, 70});
                        }
                        notesTable.WidthPercentage = 100f;

                        //created on
                        cellOrderNote = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.OrderNotes.CreatedOn", lang.Id), font));
                        cellOrderNote.BackgroundColor = BaseColor.LIGHT_GRAY;
                        cellOrderNote.HorizontalAlignment = Element.ALIGN_CENTER;
                        notesTable.AddCell(cellOrderNote);

                        //note
                        cellOrderNote = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.OrderNotes.Note", lang.Id), font));
                        cellOrderNote.BackgroundColor = BaseColor.LIGHT_GRAY;
                        cellOrderNote.HorizontalAlignment = Element.ALIGN_CENTER;
                        notesTable.AddCell(cellOrderNote);

                        foreach (var orderNote in orderNotes)
                        {
                            cellOrderNote = new PdfPCell(new Phrase(_dateTimeHelper.ConvertToUserTime(orderNote.CreatedOnUtc, DateTimeKind.Utc).ToString(), font));
                            cellOrderNote.HorizontalAlignment = Element.ALIGN_LEFT;
                            notesTable.AddCell(cellOrderNote);

                            cellOrderNote = new PdfPCell(new Phrase(HtmlHelper.ConvertHtmlToPlainText(orderNote.FormatOrderNoteText(), true, true), font));
                            cellOrderNote.HorizontalAlignment = Element.ALIGN_LEFT;
                            notesTable.AddCell(cellOrderNote);

                            //should we display a link to downloadable files here?
                            //I think, no. Onyway, PDFs are printable documents and links (files) are useful here
                        }
                        doc.Add(notesTable);
                    }
                }

                #endregion

                #region Footer

                if (!String.IsNullOrEmpty(pdfSettingsByStore.InvoiceFooterTextColumn1) || !String.IsNullOrEmpty(pdfSettingsByStore.InvoiceFooterTextColumn2))
                {
                    var column1Lines = String.IsNullOrEmpty(pdfSettingsByStore.InvoiceFooterTextColumn1) ?
                        new List<string>() :
                        pdfSettingsByStore.InvoiceFooterTextColumn1
                        .Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
                        .ToList();
                    var column2Lines = String.IsNullOrEmpty(pdfSettingsByStore.InvoiceFooterTextColumn2) ?
                        new List<string>() :
                        pdfSettingsByStore.InvoiceFooterTextColumn2
                        .Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
                        .ToList();
                    if (column1Lines.Count > 0 || column2Lines.Count > 0)
                    {
                        var totalLines = Math.Max(column1Lines.Count, column2Lines.Count);
                        const float margin = 43;

                        //if you have really a lot of lines in the footer, then replace 9 with 10 or 11
                        int footerHeight = totalLines * 9;
                        var directContent = pdfWriter.DirectContent;
                        directContent.MoveTo(pageSize.GetLeft(margin), pageSize.GetBottom(margin) + footerHeight);
                        directContent.LineTo(pageSize.GetRight(margin), pageSize.GetBottom(margin) + footerHeight);
                        directContent.Stroke();

                        var footerTable = new PdfPTable(2);
                        footerTable.WidthPercentage = 100f;
                        footerTable.SetTotalWidth(new float[] { 250, 250 });
                        footerTable.RunDirection = GetDirection(lang);

                        //column 1
                        if (column1Lines.Count > 0)
                        {
                            var column1 = new PdfPCell(new Phrase());
                            column1.Border = Rectangle.NO_BORDER;
                            column1.HorizontalAlignment = Element.ALIGN_LEFT;
                            foreach (var footerLine in column1Lines)
                            {
                                column1.Phrase.Add(new Phrase(footerLine, font));
                                column1.Phrase.Add(new Phrase(Environment.NewLine));
                            }
                            footerTable.AddCell(column1);
                        }
                        else
                        {
                            var column = new PdfPCell(new Phrase(" "));
                            column.Border = Rectangle.NO_BORDER;
                            footerTable.AddCell(column);
                        }

                        //column 2
                        if (column2Lines.Count > 0)
                        {
                            var column2 = new PdfPCell(new Phrase());
                            column2.Border = Rectangle.NO_BORDER;
                            column2.HorizontalAlignment = Element.ALIGN_LEFT;
                            foreach (var footerLine in column2Lines)
                            {
                                column2.Phrase.Add(new Phrase(footerLine, font));
                                column2.Phrase.Add(new Phrase(Environment.NewLine));
                            }
                            footerTable.AddCell(column2);
                        }
                        else
                        {
                            var column = new PdfPCell(new Phrase(" "));
                            column.Border = Rectangle.NO_BORDER;
                            footerTable.AddCell(column);
                        }

                        footerTable.WriteSelectedRows(0, totalLines, pageSize.GetLeft(margin), pageSize.GetBottom(margin) + footerHeight, directContent);
                    }
                }

                #endregion

                ordNum++;
                if (ordNum < ordCount)
                {
                    doc.NewPage();
                }
            }
            doc.Close();
        }
Ejemplo n.º 16
0
    private void GeneratePDF1()
    {
        log4net.ILog log = log4net.LogManager.GetLogger("ServiceRowDataBound");
        log4net.Config.XmlConfigurator.Configure();

        try
        {
            /*CustomSessionClass objCustomSessionClass = new CustomSessionClass();
            System.Web.UI.HtmlControls.HtmlTable objtbl = objCustomSessionClass._Session;
            */

            System.Web.UI.HtmlControls.HtmlTable objtbl = (System.Web.UI.HtmlControls.HtmlTable)Cache["table"];

            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "inline;filename=results.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            //tblBusinessBankingOnline.RenderControl(hw);
            StringReader sr = new StringReader(sw.ToString());
        Document pdfDoc = new Document(PageSize.A4, 7f, 7f, 7f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
            //Set Header
            //iTextSharp.text.Image imgStlogo = iTextSharp.text.Image.GetInstance(iTextSharp.text.Image.GetInstance(Server.MapPath(@"StG_Master_Logo_RGBold.jpg")));
            //imgStlogo.SetAbsolutePosition(0, pdfDoc.PageSize.Height - imgStlogo.Height);
            //imgStlogo.ScaleToFit(200f, 90f);
                    //imgStlogo.SetAbsolutePosition(0, 750f);
           // pdfDoc.Add(imgStlogo);
            //

        iTextSharp.text.Image imgStlogo = iTextSharp.text.Image.GetInstance(iTextSharp.text.Image.GetInstance(Server.MapPath(@"StG_Master_Logo_RGBold.jpg")));
                PdfPTable pdfTable = new PdfPTable(1);
               // pdfTable.DefaultCell.Border = Rectangle.NO_BORDER;
              //  pdfTable.SplitRows = false;
                imgStlogo.ScaleToFit(183f, 66f);
                PdfPCell imageCell = new PdfPCell(imgStlogo);
                imageCell.Border = 0;
                pdfTable.AddCell(imageCell);
                pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
                pdfDoc.Add(pdfTable);
                pdfDoc.Add(new Paragraph(""));

           /*  pdfDoc.Add(new Paragraph(" "));
        pdfDoc.Add(new Paragraph(" "));
        pdfDoc.Add(new Paragraph(" "));*/

            iTextSharp.text.Font font18 = iTextSharp.text.FontFactory.GetFont(iTextSharp.text.FontFactory.HELVETICA, 8);
            iTextSharp.text.Chunk bullet = new iTextSharp.text.Chunk("\u2022", font18);
            iTextSharp.text.List list = new iTextSharp.text.List(false, 4);  // true= ordered, false= unordered
            iTextSharp.text.List list1 = new iTextSharp.text.List(false, 4);  // true= ordered, false= unordered

            string amt = "8";
            string atm = "Freedom Business Account";
            var get = Request.QueryString["item"];
            var phrase = new Phrase();

            string strTextData = Environment.NewLine + "Thank you for completing the Business Account Selector tool. You’ll find your results below."
                               + Environment.NewLine + "We understand that no two businesses are the same and we want to help you make the right decisions for your business to be successful."
                               + Environment.NewLine + "Like every great relationship, it starts with a conversation. So if you have any questions or want to take the next steps:" + Environment.NewLine;

            iTextSharp.text.Font FontTypeBold = FontFactory.GetFont("Arial", 8f, iTextSharp.text.Font.BOLD);
            iTextSharp.text.Font FontTypeBoldlarge = FontFactory.GetFont("Arial", 10f, iTextSharp.text.Font.BOLD);
            iTextSharp.text.Font FontType = FontFactory.GetFont("Arial", 8f, iTextSharp.text.Font.NORMAL);
            iTextSharp.text.Font FontTypeSmall = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL);

            phrase = new Phrase();
            phrase.Add(new Chunk("Business Account and Product Selector Results", FontTypeBoldlarge));
            phrase.Add(new Chunk(Environment.NewLine + "Hello " + Request.QueryString["Name"], FontTypeBold));

            phrase.Add(new Chunk(strTextData, FontType));
            pdfDoc.Add(phrase);
            PdfPTable tblCall = new PdfPTable(1);
            tblCall.WidthPercentage = 30f;
            tblCall.HorizontalAlignment = Element.ALIGN_LEFT;
            tblCall.DefaultCell.Border = Rectangle.NO_BORDER;
            iTextSharp.text.Image imgCall = iTextSharp.text.Image.GetInstance(iTextSharp.text.Image.GetInstance(Server.MapPath(@"pdfCTA-1.png")));
            tblCall.AddCell(imgCall);
            pdfDoc.Add(tblCall);
            phrase = new Phrase();
            phrase.Add(new Chunk("To find out what information is needed to become a customer, visit ", FontType));
            pdfDoc.Add(phrase);
            Font link = FontFactory.GetFont("Arial", 8, Font.UNDERLINE, new Color(0, 0, 255));
            Anchor anchor = new Anchor("http://www.stgeorge.com.au/idchecklist", link);
            anchor.Reference = "http://www.stgeorge.com.au/idchecklist";
            pdfDoc.Add(anchor);
            pdfDoc.Add(new Phrase(Environment.NewLine + Environment.NewLine, FontType));

            #region CodeForLastFiveProduct
            PdfPTable pdfpTableAdditionalProduct = new PdfPTable(2);
            pdfpTableAdditionalProduct.WidthPercentage = 100f;
            int[] TableAdditionalProductwidth = { 30, 70 };
            pdfpTableAdditionalProduct.SetWidths(TableAdditionalProductwidth);

            phrase = new Phrase(" " + Environment.NewLine);
            phrase.Add(new Chunk("Business Products", FontTypeBold));
            phrase.Add(Environment.NewLine + " ");
            PdfPCell cellAdditionalProduct = new PdfPCell(phrase);
            cellAdditionalProduct.Colspan = 3;

            //Used to checked Last Five product is selected
            bool isLastFiveProductSelected = false;
            if (get.Contains("f"))
            {
                // pdfDoc.NewPage();
                pdfpTableAdditionalProduct.AddCell(cellAdditionalProduct);
                isLastFiveProductSelected = true;

                PdfPCell Cell1 = new PdfPCell(new Phrase(Environment.NewLine + Environment.NewLine + "EFTPOS and merchant facilities", FontTypeBold));
                pdfpTableAdditionalProduct.AddCell(Cell1);
                phrase = new Phrase();
                phrase.Add(new Chunk("Customers being able to pay with a debit card?", FontTypeBold));
                phrase.Add(new Chunk("      and/or", FontType));
                phrase.Add(new Chunk(Environment.NewLine + "Customers being able to pay with a credit card?", FontTypeBold));

                list = new iTextSharp.text.List(false, 8);
                list.ListSymbol = bullet;
                ////////list.Add(new iTextSharp.text.ListItem(new Chunk("With this account, all day-to-day electronic transactions are fee-free",FontType)));
                list.Add(new iTextSharp.text.ListItem(new Chunk("To accept debit and credit cards from customers, whether it’s in person, over the phone or online, St.George has a range of EFTPOS and merchant solutions", FontType)));
                list.Add(new iTextSharp.text.ListItem(new Chunk("Get same-day settlement (when the terminal is settled before 9pm Sydney time) on debit and credit card sales, 7 days a week, when linked to a St.George business transaction account", FontType)));

                PdfPCell objCell = new PdfPCell();
                objCell.AddElement(phrase);
                objCell.AddElement(list);
                objCell.AddElement(new Phrase(" "));

                objCell.Colspan = 2;
                pdfpTableAdditionalProduct.AddCell(objCell);

            }
            if (get.Contains("g"))
            {
                if (!isLastFiveProductSelected)
                {
                    //pdfDoc.NewPage();
                    pdfpTableAdditionalProduct.AddCell(cellAdditionalProduct);
                    isLastFiveProductSelected = true;
                }
                PdfPCell Cell1 = new PdfPCell(new Phrase(Environment.NewLine + Environment.NewLine + "Equipment finance", FontTypeBold));
                pdfpTableAdditionalProduct.AddCell(Cell1);
                phrase = new Phrase();
                phrase.Add(new Chunk("Purchasing a vehicle?", FontTypeBold));
                phrase.Add(new Chunk("      and/or", FontType));
                phrase.Add(new Chunk(Environment.NewLine + "Purchasing equipment or machinery?", FontTypeBold));

                list = new iTextSharp.text.List(false, 8);
                list.ListSymbol = bullet;
                ////////list.Add(new iTextSharp.text.ListItem(new Chunk("With this account, all day-to-day electronic transactions are fee-free",FontType)));
                list.Add(new iTextSharp.text.ListItem(new Chunk("Finance up to 100% of the purchase price for vehicles or equipment", FontType)));
                list.Add(new iTextSharp.text.ListItem(new Chunk("Frees up money to run a business, rather than tying up working capital", FontType)));

                PdfPCell objCell = new PdfPCell();
                objCell.AddElement(phrase);
                objCell.AddElement(list);
                //  phrase.Add(new Chunk(Environment.NewLine + "Equipment Finance is offered by St.George Finance Limited ACL 387944."+Environment.NewLine+" Automotive Finance is offered by St.George Finance Limited ACL 387944 and St.George Motor Finance Limited ACL 387946.",FontType));
                //  objCell.AddElement(new Phrase("Equipment Finance by St.George Finance Limited Australian credit licence 387944.The Automotive Finance by St.George Finance Limited and St.George Motor Finance Limited Australian credit licence 387946"));

                var phBecauseText1 = new Phrase();
                phBecauseText1.Add(new Chunk(Environment.NewLine + "Equipment Finance by St.George Finance Limited Australian credit licence 387944.", FontType));
                //phBecauseText1.Add(new Chunk(Environment.NewLine + "Automotive Finance by St.George Finance Limited Australian credit licence 387944 and St.George Motor Finance Limited Australian credit licence 387946.", FontType));
                objCell.AddElement(phBecauseText1);

                objCell.AddElement(new Phrase(" "));

                objCell.Colspan = 3;
                pdfpTableAdditionalProduct.AddCell(objCell);

            }
            if (get.Contains("h"))
            {
                if (!isLastFiveProductSelected)
                {
                   // pdfDoc.NewPage();
                    pdfpTableAdditionalProduct.AddCell(cellAdditionalProduct);
                    isLastFiveProductSelected = true;
                }
                PdfPCell Cell1 = new PdfPCell(new Phrase(Environment.NewLine + Environment.NewLine + "Lending for a Business", FontTypeBold));
                pdfpTableAdditionalProduct.AddCell(Cell1);
                phrase = new Phrase();
                phrase.Add(new Chunk("Purchasing a business?", FontTypeBold));
                phrase.Add(new Chunk("      and/or", FontType));
                phrase.Add(new Chunk(Environment.NewLine + "Expanding a business?", FontTypeBold));

                list = new iTextSharp.text.List(false, 8);
                list.ListSymbol = bullet;
                ////////list.Add(new iTextSharp.text.ListItem(new Chunk("With this account, all day-to-day electronic transactions are fee-free",FontType)));
                list.Add(new iTextSharp.text.ListItem(new Chunk("St.George has a number of lending options to give a business a cash injection", FontType)));
                list.Add(new iTextSharp.text.ListItem(new Chunk("This includes both residentially and commercially secured loans or a combination of these", FontType)));

                PdfPCell objCell = new PdfPCell();
                objCell.AddElement(phrase);
                objCell.AddElement(list);
                objCell.AddElement(new Phrase(" "));
                objCell.Colspan = 3;
                pdfpTableAdditionalProduct.AddCell(objCell);

            }
            if (get.Contains("i"))
            {
                if (!isLastFiveProductSelected)
                {
                   // pdfDoc.NewPage();
                    pdfpTableAdditionalProduct.AddCell(cellAdditionalProduct);
                    isLastFiveProductSelected = true;
                }
                PdfPCell Cell1 = new PdfPCell(new Phrase(Environment.NewLine + Environment.NewLine + "Bank guarantee", FontTypeBold));
                pdfpTableAdditionalProduct.AddCell(Cell1);
                phrase = new Phrase();
                phrase.Add(new Chunk("Provide a landlord a guarantee of payment when renting premises?", FontTypeBold));
                phrase.Add(new Chunk("      and/or", FontType));
                phrase.Add(new Chunk(Environment.NewLine + "Provide customers or suppliers a guarantee of payment to secure a contract?", FontTypeBold));

                list = new iTextSharp.text.List(false, 8);
                list.ListSymbol = bullet;
                ////////list.Add(new iTextSharp.text.ListItem(new Chunk("With this account, all day-to-day electronic transactions are fee-free",FontType)));
                list.Add(new iTextSharp.text.ListItem(new Chunk("Allows a business to offer customers and suppliers a surety of payment without having to provide them a cash deposit upfront", FontType)));
                list.Add(new iTextSharp.text.ListItem(new Chunk("Where security other than cash is provided, this can free up money for other investment opportunities, and helps manage the highs and lows of cash flow", FontType)));

                PdfPCell objCell = new PdfPCell();
                objCell.AddElement(phrase);
                objCell.AddElement(list);
                objCell.AddElement(new Phrase(" "));
                objCell.Colspan = 3;
                pdfpTableAdditionalProduct.AddCell(objCell);
            }

            if (get.Contains("j"))
            {
                if (!isLastFiveProductSelected)
                {
                    // pdfDoc.NewPage();
                    pdfpTableAdditionalProduct.AddCell(cellAdditionalProduct);
                    isLastFiveProductSelected = true;
                }
                PdfPCell Cell1 = new PdfPCell(new Phrase(Environment.NewLine + Environment.NewLine + "Online legal and tax advice", FontTypeBold));
                pdfpTableAdditionalProduct.AddCell(Cell1);
                phrase = new Phrase();
                phrase.Add(new Chunk("Legal and tax advice?", FontTypeBold));

                list = new iTextSharp.text.List(false, 8);
                list.ListSymbol = bullet;
                ////////list.Add(new iTextSharp.text.ListItem(new Chunk("With this account, all day-to-day electronic transactions are fee-free",FontType)));
                //list.Add(new iTextSharp.text.ListItem(new Chunk("St.George provides business customers with access to free online legal and taxation advice",FontType)));
                iTextSharp.text.ListItem LstItm = new iTextSharp.text.ListItem();
                LstItm.Add(new Chunk("St.George provides business customers with access to free online legal and taxation advice", FontType));
                LstItm.Add(new Chunk("3", FontFactory.GetFont(FontFactory.HELVETICA, 5)).SetTextRise(4));

                list.Add(LstItm);

                list.Add(new iTextSharp.text.ListItem(new Chunk("Access this service by sending a confidential email to the third party provider", FontType)));
                list.Add(new iTextSharp.text.ListItem(new Chunk("For more information, visit http://www.stgeorge.com.au/business/business-tools/legal-tax-advice", FontType)));

                PdfPCell objCell = new PdfPCell();
                objCell.AddElement(phrase);
                objCell.AddElement(list);
                objCell.AddElement(new Phrase(" "));
                objCell.Colspan = 3;
                pdfpTableAdditionalProduct.AddCell(objCell);
            }

            /*  if (freetax.Checked)
              {
                  if (!isLastFiveProductSelected)
                  {
                      pdfDoc.NewPage();
                      pdfpTableAdditionalProduct.AddCell(cellAdditionalProduct);
                      isLastFiveProductSelected = true;
                  }

                  PdfPCell Cell1 = new PdfPCell(new Phrase(Environment.NewLine +Environment.NewLine +"Online legal and tax advice", FontTypeBold));
                  pdfpTableAdditionalProduct.AddCell(Cell1);
                  phrase = new Phrase();
                  phrase.Add(new Chunk("Legal and tax advice?", FontTypeBold));

                  phrase.Add(new Chunk(Environment.NewLine + "St.George provides customers with access to free online legal and taxation advice."
                                      + Environment.NewLine + "Accessing this service is easy, existing customers can access this service by sending a confidential email to Legal Access Services."
                                      + Environment.NewLine + "Legal and accountancy services are not provided by St.George. St.George accepts no responsibility for any advice provided by these third parties. Advice is available by email only.",FontType));

                  phrase.Add(Environment.NewLine + "For more information,");
                  link = FontFactory.GetFont("Arial", 12, Font.UNDERLINE, new Color(0, 0, 255));
                  anchor = new Anchor("http://www.stgeorge.com.au/business/business-tools/legal-tax-advice", link);
                  anchor.Reference = "http://www.stgeorge.com.au/business/business-tools/legal-tax-advice";
                  phrase.Add(anchor);

                  phrase.Add(Environment.NewLine + " ");
                  PdfPCell cell2 = new PdfPCell(phrase);
                  pdfpTableAdditionalProduct.AddCell(cell2);

                  list = new iTextSharp.text.List(false, 12);
                  list.ListSymbol = bullet;
                  list.Add(new iTextSharp.text.ListItem("St.George provides customers with access to free online legal and taxation advice"));
                  list.Add(new iTextSharp.text.ListItem("Accessing this service is easy, existing customers can access this service by sending a confidential email to Legal Access Services"));

                  PdfPCell objCell = new PdfPCell();
                  objCell.AddElement(phrase);
                  objCell.AddElement(list);

                  phrase = new Phrase();
                  phrase.Add(Environment.NewLine + "For more information,");
                  link = FontFactory.GetFont("Arial", 12, Font.UNDERLINE, new Color(0, 0, 255));
                  anchor = new Anchor("http://www.stgeorge.com.au/business/business-tools/legal-tax-advice", link);
                  anchor.Reference = "http://www.stgeorge.com.au/business/business-tools/legal-tax-advice";
                  phrase.Add(anchor);
                  objCell.AddElement(phrase);

                  objCell.AddElement(new Phrase(" "));
                  objCell.Colspan = 2;
                  pdfpTableAdditionalProduct.AddCell(objCell);

              }*/
            pdfDoc.Add(pdfpTableAdditionalProduct);

            #endregion CodeForLastFiveProduct

            var phraseTermAndConditionkalu = new Phrase();
            phraseTermAndConditionkalu.Add(new Chunk(Environment.NewLine + "", FontTypeBold));
            pdfDoc.Add(phraseTermAndConditionkalu);

            #region CodeForTopFiveProduct
            PdfPTable pdftblAllData = new PdfPTable(2);
            pdftblAllData.WidthPercentage = 100f;
            int[] firstTablecellwidth = { 30, 70 };
            pdftblAllData.SetWidths(firstTablecellwidth);

            phrase = new Phrase(" " + Environment.NewLine);
            phrase.Add(new Chunk("BizPack Essentials", FontTypeBold));
            phrase.Add(Environment.NewLine + " ");
            PdfPCell cellBizPack = new PdfPCell(phrase);
            cellBizPack.Colspan = 2;
            //Used to checked topfive product is selected
            bool IsTopFiveProductSelected = false;

            if (get.Contains("z"))
            {
                amt = "18";
                atm = "Business Cheque Account Plus";
                pdftblAllData.AddCell(cellBizPack);
                IsTopFiveProductSelected = true;

                PdfPCell Cell1 = new PdfPCell(new Phrase(Environment.NewLine + Environment.NewLine + "Business Cheque Account Plus", FontTypeBold));
                pdftblAllData.AddCell(Cell1);

                phrase = new Phrase();
                phrase.Add(new Chunk(" An everyday account used to pay suppliers and have funds paid into?", FontTypeBold));

                list = new iTextSharp.text.List(false, 4);
                list.ListSymbol = bullet;

                /*
                phrase = new Phrase();
                phrase.Add(new Chunk("Day-to-day electronic transactions are fee-free"));
                phrase.Add(new Chunk("1", FontFactory.GetFont(FontFactory.HELVETICA, 6)).SetTextRise(4));
                phrase.Add(new Chunk(",TestTestTest"));
                */
                //list.Add(new iTextSharp.text.ListItem("With this account, all day-to-day electronic transactions are fee-free1"));

                iTextSharp.text.ListItem LstItm = new iTextSharp.text.ListItem();
                LstItm.Add(new Chunk("With this account, all day-to-day electronic transactions are fee-free", FontType));
                LstItm.Add(new Chunk("1", FontFactory.GetFont(FontFactory.HELVETICA, 5)).SetTextRise(4));
                list.Add(LstItm);
                list.Add(new iTextSharp.text.ListItem(new Chunk("Plus, get 55 free in-branch transactions (over the counter) or cheque withdrawals every month", FontType)));

                /*list.Add(new iTextSharp.text.ListItem(new Chunk("With this account, all day-to-day electronic transactions are fee-free",FontType)));
                 list.Add(new iTextSharp.text.ListItem(new Chunk("1",FontType).SetTextRise(4)));
                 list.Add(new iTextSharp.text.ListItem(new Chunk("Plus, get 50 free in-branch transactions (over the counter) or cheque withdrawals every month",FontType)));
                 */
                /*
               iTextSharp.text.ListItem LstItm =new iTextSharp.text.ListItem();
               LstItm.Add(new Chunk("With this account, the day-to-day electronic transactions are fee-free"));
               LstItm.Add(new Chunk("1", FontFactory.GetFont(FontFactory.HELVETICA, 6)).SetTextRise(4));
               list.Add(LstItm);
               list.Add(new iTextSharp.text.ListItem(new Chunk("no matter how many are made")));

                */

                //list.Add(new iTextSharp.text.ListItem("Plus, get 50 free in-branch transactions (over the counter) or cheque withdrawals every month"));

                PdfPCell objCell = new PdfPCell();
                objCell.AddElement(phrase);
                objCell.AddElement(list);
                objCell.AddElement(new Phrase(" "));

                objCell.Colspan = 3;
                pdftblAllData.AddCell(objCell);

            }
            if (get.Contains("a"))
            {
                if (!IsTopFiveProductSelected)
                {
                    pdftblAllData.AddCell(cellBizPack);
                    IsTopFiveProductSelected = true;
                }
                amt = "8";
                atm = "Freedom Business Account";
                PdfPCell Cell1 = new PdfPCell(new Phrase(Environment.NewLine + Environment.NewLine + "Freedom Business Account", FontTypeBold));
                pdftblAllData.AddCell(Cell1);

                phrase = new Phrase();
                phrase.Add(new Chunk(" An everyday account used to pay suppliers and have funds paid into?", FontTypeBold));

                list = new iTextSharp.text.List(false, 8);
                list.ListSymbol = bullet;
                //list.Add(new iTextSharp.text.ListItem("With this account, all day-to-day electronic transactions are fee-free1"));
                //list.Add(new iTextSharp.text.ListItem("Plus, get 20 free in-branch transactions (over the counter) or cheque withdrawals every month"));
                /*list.Add(new iTextSharp.text.ListItem(new Chunk("With this account, all day-to-day electronic transactions are fee-free",FontType)));
                list.Add(new iTextSharp.text.ListItem(new Chunk("1",FontType).SetTextRise(4)));
                list.Add(new iTextSharp.text.ListItem(new Chunk("Plus, get 20 free in-branch transactions (over the counter) or cheque withdrawals every month",FontType)));
                */
                iTextSharp.text.ListItem LstItm = new iTextSharp.text.ListItem();
                LstItm.Add(new Chunk("With this account, all day-to-day electronic transactions are fee-free", FontType));
                LstItm.Add(new Chunk("1", FontFactory.GetFont(FontFactory.HELVETICA, 5)).SetTextRise(4));
                list.Add(LstItm);
                list.Add(new iTextSharp.text.ListItem(new Chunk("Plus, get 20 free in-branch transactions (over the counter) or cheque withdrawals every month", FontType)));

                PdfPCell objCell = new PdfPCell();

                objCell.AddElement(phrase);
                objCell.AddElement(list);
                objCell.AddElement(new Phrase(" "));

                objCell.Colspan = 3;
                pdftblAllData.AddCell(objCell);
            }

            if (get.Contains("b"))
            {
                if (!IsTopFiveProductSelected)
                {
                    pdftblAllData.AddCell(cellBizPack);
                    IsTopFiveProductSelected = true;
                }
                PdfPCell Cell1 = new PdfPCell(new Phrase(Environment.NewLine + Environment.NewLine + "Business Visa Debit Card", FontTypeBold));
                pdftblAllData.AddCell(Cell1);

                phrase = new Phrase();
                //phrase.Add(new Chunk("Business Visa Debit Card", FontTypeBold));
                phrase.Add(new Chunk("Access cash from an ATM?", FontTypeBold));
                phrase.Add(new Chunk("      and/or", FontType));
                phrase.Add(new Chunk(Environment.NewLine + "Make purchases in person, over the phone or online?", FontTypeBold));

                list = new iTextSharp.text.List(false, 8);
                list.ListSymbol = bullet;

                //list.Add(new iTextSharp.text.ListItem(new Chunk("Plus, get 20 free in-branch transactions (over the counter) or cheque withdrawals every month",FontType)));
                list.Add(new iTextSharp.text.ListItem(new Chunk("Access funds from the " + atm + " at ATMs", FontType)));
                list.Add(new iTextSharp.text.ListItem(new Chunk("Make purchases in person, over the phone and online, wherever Visa is accepted (that's over 32 million locations worldwide)", FontType)));

                PdfPCell objCell = new PdfPCell();
                objCell.AddElement(phrase);
                objCell.AddElement(list);
                objCell.AddElement(new Phrase(" "));

                objCell.Colspan = 3;
                pdftblAllData.AddCell(objCell);

            }

            if (get.Contains("c"))
            {
                if (!IsTopFiveProductSelected)
                {
                    pdftblAllData.AddCell(cellBizPack);
                    IsTopFiveProductSelected = true;
                }
                PdfPCell Cell1 = new PdfPCell(new Phrase(Environment.NewLine + Environment.NewLine + "Business Access Saver", FontTypeBold));
                pdftblAllData.AddCell(Cell1);

                phrase = new Phrase();
                phrase.Add(new Chunk("Put money away for tax and other future payments?", FontTypeBold));
                phrase.Add(new Chunk("      and/or", FontType));
                phrase.Add(new Chunk(Environment.NewLine + "Earn interest on this money?", FontTypeBold));

                list = new iTextSharp.text.List(false, 8);
                list.ListSymbol = bullet;
                //list.Add(new iTextSharp.text.ListItem(new Chunk("With this account, all day-to-day electronic transactions are fee-free",FontType)));
                list.Add(new iTextSharp.text.ListItem(new Chunk("Enables money to be parked for future payments (like GST and regular bills), while also earning interest along the way", FontType)));

                iTextSharp.text.ListItem LstItm = new iTextSharp.text.ListItem();
                LstItm.Add(new Chunk("Day-to-day electronic transactions are fee-free", FontType));
                LstItm.Add(new Chunk("1", FontFactory.GetFont(FontFactory.HELVETICA, 5)).SetTextRise(4));
                LstItm.Add(new Chunk(", as are 4 in-branch deposits (over the counter) every month", FontType));
                list.Add(LstItm);

                // list.Add(new iTextSharp.text.ListItem(new Chunk("Day-to-day electronic transactions are fee-free1, as are 4 in-branch deposits (over the counter) every month",FontType)));

                PdfPCell objCell = new PdfPCell();
                objCell.AddElement(phrase);
                objCell.AddElement(list);
                objCell.AddElement(new Phrase(" "));

                objCell.Colspan = 3;
                pdftblAllData.AddCell(objCell);
            }

            if (get.Contains("d"))
            {
                if (!IsTopFiveProductSelected)
                {
                    pdftblAllData.AddCell(cellBizPack);
                    IsTopFiveProductSelected = true;
                }
                PdfPCell Cell1 = new PdfPCell(new Phrase(Environment.NewLine + Environment.NewLine + "Business Banking Online", FontTypeBold));
                pdftblAllData.AddCell(Cell1);

                phrase = new Phrase();
                //phrase.Add(new Chunk("Business Visa Debit Card", FontTypeBold));
                phrase.Add(new Chunk("Manage money 24/7?", FontTypeBold));
                phrase.Add(new Chunk("      and/or", FontType));
                phrase.Add(new Chunk(Environment.NewLine + "Manage money when on the move?", FontTypeBold));

                /*phrase.Add(new Chunk(Environment.NewLine +"Business Banking Online won the 2013 Best Internet Business Bank, in the AB+F Corporate and Business Banking Awards.",FontType));
                phrase.Add(new Chunk(Environment.NewLine +"  Take control of business banking:",FontType));
                phrase.Add(new Chunk(Environment.NewLine +"  Ability to set daily payment limits",FontType));
                phrase.Add(new Chunk(Environment.NewLine +"  Allow multiple users to have access to business accounts",FontType));
                phrase.Add(new Chunk(Environment.NewLine +"  Nominate which users can authorise transactions using authentication device",FontType));
                phrase.Add(new Chunk(Environment.NewLine +"  Get ultimate portability with Business Banking Mobile",FontType));
                phrase.Add(Environment.NewLine + " ");
                PdfPCell cell2 = new PdfPCell(phrase);
                pdftblAllData.AddCell(cell2);
                */

                list = new iTextSharp.text.List(false, 8);
                list.ListSymbol = bullet;

                list1 = new iTextSharp.text.List(false, 8);
                list1.ListSymbol = bullet;
                ////list.Add(new iTextSharp.text.ListItem(new Chunk("With this account, all day-to-day electronic transactions are fee-free",FontType)));

                list.Add(new iTextSharp.text.ListItem(new Chunk("Business Banking Online won the 2013 Best Internet Business Bank, in the AB+F Corporate and Business Banking Awards", FontType)));
                list.Add(new iTextSharp.text.ListItem(new Chunk("Take control of business banking:", FontType)));

                list1.Add(new iTextSharp.text.ListItem(new Chunk("Ability to set daily payment limits", FontType)));
                list1.Add(new iTextSharp.text.ListItem(new Chunk("Allow multiple users to have access to business accounts", FontType)));
                list1.Add(new iTextSharp.text.ListItem(new Chunk("Nominate which users can authorise transactions using authentication device", FontType)));
                list1.Add(new iTextSharp.text.ListItem(new Chunk("Get ultimate portability with Business Banking Mobile", FontType)));

                list.Add(list1);

                PdfPCell objCell = new PdfPCell();
                objCell.AddElement(phrase);
                objCell.AddElement(list);
                objCell.AddElement(new Phrase(" "));

                objCell.Colspan = 3;
                pdftblAllData.AddCell(objCell);

            }

            if (get.Contains("e"))
            {
                if (!IsTopFiveProductSelected)
                {
                    pdftblAllData.AddCell(cellBizPack);
                    IsTopFiveProductSelected = true;
                }
                PdfPCell Cell1 = new PdfPCell(new Phrase(Environment.NewLine + Environment.NewLine + "BusinessVantage Visa Credit Card", FontTypeBold));
                pdftblAllData.AddCell(Cell1);

                phrase = new Phrase();
                //phrase.Add(new Chunk("Business Visa Debit Card", FontTypeBold));
                phrase.Add(new Chunk("A credit card to help manage business expenses and cash flow?", FontTypeBold));
                phrase.Add(new Chunk("      and/or", FontType));
                phrase.Add(new Chunk(Environment.NewLine + "Separate business and personal expenses?", FontTypeBold));

                /*phrase.Add(new Chunk(Environment.NewLine +"Low variable purchase rate (currently 9.99% p.a.) and up to 55 days interest free on purchases when closing balance paid by the due date",FontType));
                phrase.Add(new Chunk(Environment.NewLine +"A dedicated business credit card keeps business and personal expenses separate",FontType));
                phrase.Add(new Chunk(Environment.NewLine +"Provides peace of mind knowing extra working capital is at hand to help manage the highs and lows of cash flow",FontType));
                phrase.Add(Environment.NewLine + " ");
                PdfPCell cell2 = new PdfPCell(phrase);
                pdftblAllData.AddCell(cell2);*/

                list = new iTextSharp.text.List(false, 8);
                list.ListSymbol = bullet;

                //////list.Add(new iTextSharp.text.ListItem(new Chunk("With this account, all day-to-day electronic transactions are fee-free",FontType)));
                list.Add(new iTextSharp.text.ListItem(new Chunk("Low variable purchase rate (currently 9.99% p.a.) and up to 55 days interest free on purchases when closing balance paid by the due date", FontType)));
                list.Add(new iTextSharp.text.ListItem(new Chunk("A dedicated business credit card keeps business and personal expenses separate", FontType)));
                list.Add(new iTextSharp.text.ListItem(new Chunk("Provides peace of mind knowing extra working capital is at hand to help manage the highs and lows of cash flow", FontType)));

                PdfPCell objCell = new PdfPCell();
                objCell.AddElement(phrase);
                objCell.AddElement(list);
                objCell.AddElement(new Phrase(" "));

                objCell.Colspan = 3;
                pdftblAllData.AddCell(objCell);

            }

            if ((get.Contains("z") || get.Contains("a")) && get.Contains("c") && get.Contains("d") )
            {

                var phBecauseText = new Phrase();
                phBecauseText.Add(new Chunk("All the BizPack Essentials for only $" + amt + " per month in account keeping fees*."
                                      + Environment.NewLine + Environment.NewLine + "BizPack-ed full of savings:", FontTypeBold));

                list = new iTextSharp.text.List(false, 8);
                list.ListSymbol = bullet;
                ////////list.Add(new iTextSharp.text.ListItem(new Chunk("With this account, all day-to-day electronic transactions are fee-free",FontType)));
                list.Add(new iTextSharp.text.ListItem(new Chunk("Business Banking Online monthly access fee (currently $30 a month) waived, saving $360 annually", FontType)));
                list.Add(new iTextSharp.text.ListItem(new Chunk("BusinessVantage Visa Credit Card annual fee (currently $55 per card) waived for up to 3 cards, saving up to $165 annually", FontType)));
                list.Add(new iTextSharp.text.ListItem(new Chunk("Establishment fee for each new EFTPOS and merchant terminal waived, current saving of $77 per terminal", FontType)));

                PdfPCell objCell = new PdfPCell();
                objCell.AddElement(phBecauseText);
                objCell.AddElement(list);

                var phBecauseText1 = new Phrase();
                phBecauseText1.Add(new Chunk(Environment.NewLine + "*Transaction fees and special service fees may also apply.", FontType));
                objCell.AddElement(phBecauseText1);
                // objCell.AddElement(new Phrase("*Transaction fees and special service fees may also apply."));
                objCell.AddElement(new Phrase(" "));

                objCell.Colspan = 3;
                pdftblAllData.AddCell(objCell);
                //pdfDoc.Add(pdftblAllData);

            }
            else
            {
                //Business%20Access%20Saver
                var biznt =  Request.QueryString["bizpacknameneshat"];

                Phrase phBecauseText = new Phrase();
                phBecauseText.Add(new Chunk("Because the following have not been selected, BizPack has not been unlocked:", FontType));

                Phrase phBecauseText2 = new Phrase();
                phBecauseText2.Add(new Chunk(Environment.NewLine + "BizPack", FontTypeBold));
                phBecauseText2.Add(new Chunk(Environment.NewLine + "Pay only $" + amt + " per month in account keeping fees* for the BizPack Essentials.", FontType));

                phBecauseText2.Add(new Chunk(Environment.NewLine + "BizPack-ed full of savings:", FontType));

                list1 = new iTextSharp.text.List(false, 8);
                list1.ListSymbol = bullet;

                if(biznt.Contains("Freedom Business Account")){
                     list1.Add(new iTextSharp.text.ListItem(new Chunk("Freedom Business Account", FontType)));
                }
                if(biznt.Contains("Business Access Saver")){
                     list1.Add(new iTextSharp.text.ListItem(new Chunk("Business Access Saver", FontType)));
                }
                if(biznt.Contains("Business Banking Online")){
                    list1.Add(new iTextSharp.text.ListItem(new Chunk("Business Banking Online", FontType)));
                }

                list = new iTextSharp.text.List(false, 8);
                list.ListSymbol = bullet;
                ////////list.Add(new iTextSharp.text.ListItem(new Chunk("With this account, all day-to-day electronic transactions are fee-free",FontType)));
                list.Add(new iTextSharp.text.ListItem(new Chunk("Business Banking Online monthly access fee (currently $30 a month) waived, saving $360 annually", FontType)));
                list.Add(new iTextSharp.text.ListItem(new Chunk("BusinessVantage Visa Credit Card annual fee (currently $55 per card) waived for up to 3 cards, saving up to $165 annually", FontType)));
                list.Add(new iTextSharp.text.ListItem(new Chunk("Establishment fee for each new EFTPOS and merchant terminal waived, current saving of $77 per terminal", FontType)));

                PdfPCell objCell = new PdfPCell();
                objCell.AddElement(phBecauseText);
                objCell.AddElement(list1);
                objCell.AddElement(phBecauseText2);
                objCell.AddElement(list);
                var phBecauseText1 = new Phrase();
                phBecauseText1.Add(new Chunk(Environment.NewLine + "*Transaction fees and special service fees may also apply.", FontType));
                objCell.AddElement(phBecauseText1);
                objCell.AddElement(new Phrase(" "));

                objCell.Colspan = 3;
                pdftblAllData.AddCell(objCell);
                //pdfDoc.Add(pdftblAllData);
            }

            pdfDoc.Add(pdftblAllData);
            #endregion CodeForTopFiveProduct

                        #region TermAndCondition
            // pdfDoc.NewPage();
            FontTypeBold = FontFactory.GetFont("Arial", 8f, iTextSharp.text.Font.BOLD);
            FontType = FontFactory.GetFont("Arial", 8f, iTextSharp.text.Font.NORMAL);
            var phraseTermAndCondition = new Phrase();
            phraseTermAndCondition.Add(new Chunk(Environment.NewLine + "Things you should know", FontTypeBold));
            phraseTermAndCondition.Add(new Chunk(Environment.NewLine + "Information is current as at 31 March 2014 This offer may be withdrawn at any time, visit stgeorge.com.au for up-to-date information.", FontType));
            phraseTermAndCondition.Add(new Chunk(Environment.NewLine + "No personal information is stored by using this tool. This tool does not take into account your objectives, financial situation or needs. Before making any decision, consider its appropriateness having regard to your objectives, financial situation and needs. Before you acquire a product, read the Product Disclosure Statement or other disclosure document available at stgeorge.com.au and consider whether the product is appropriate for you. Credit criteria applies to all credit, lending, merchant and bank guarantee products and services selected. Terms and Conditions, fees and charges apply.", FontType));

            phraseTermAndCondition.Add(new Chunk(Environment.NewLine + "1. Electronic transactions are phone and internet banking deposits, withdrawals and transfers, direct debits and credits, St.George/BankSA/Bank of Melbourne/ Westpac ATM withdrawals in Australia, St.George/BankSA/Bank of Melbourne ATM deposits and mini transaction history and EFTPOS withdrawals and Business Visa Debit Card transactions. Daily limits apply.", FontType));
            phraseTermAndCondition.Add(new Chunk(Environment.NewLine + "2. The account keeping fee for the Transaction Account selected in BizPack is payable monthly. The monthly online access fee, annual card fee (for up to 3 cards) and facility establishment fee applicable to the other eligible products in BizPack are waived for as long as  customer holds a Transaction Account, Savings Account, and online banking facility in the same name. Internet Banking may replace Business Banking Online as the online banking facility held in BizPack. Transaction fees may also apply if you exceed the monthly fee-free transaction allowance on eligible products in the BizPack Essentials. Other transactions and special service fees may also apply.", FontType));

            //phraseTermAndCondition.Add(new Chunk(Environment.NewLine + "3. Customers can access the online legal and accountancy services by sending an email to Legal Access Services. These services are not provided by St.George and St.George accepts no responsibility for any advice provided by the third party. Advice is available by email only. All products and services in this tool (other than equipment finance and automotive finance) are issued by St.George Bank – A Division of Westpac Banking Corporation ABN 33 007 457 141 AFSL and Australian credit licence 233714. ", FontType));

            phraseTermAndCondition.Add(new Chunk(Environment.NewLine + "Equipment Finance by St.George Finance Limited ABN 99 001 094 471 Australian credit licence 387944.", FontType));

           // phraseTermAndCondition.Add(new Chunk(Environment.NewLine + "Automotive Finance by St.George Finance Limited ABN 99 001 094 471.", FontType));
           // phraseTermAndCondition.Add(new Chunk(" Australian credit licence 387944 and St.George Motor Finance Limited ABN 53 007 656 555 Australian credit licence 387946.", FontType));
            // phraseTermAndCondition.Add(new Chunk(Environment.NewLine + "St.George Bank – A Division of Westpac Banking Corporation. ABN 33 007 457 141 AFSL and Australian credit licence 233714", FontType));
            pdfDoc.Add(phraseTermAndCondition);
            #endregion TermAndCondition
            //Image and Text for Call
            //PdfPTable pdfTable = new PdfPTable(2);
            //pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
            //pdfTable.DefaultCell.Border = Rectangle.NO_BORDER;
            //pdfTable.SplitRows = false;
            //iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance(iTextSharp.text.Image.GetInstance(Server.MapPath("~/george.JPG")));
            //image1.ScaleToFit(750f, 750f);
            //Chunk imageChunk1 = new Chunk(image1, 0, -30);
            //phrase = new Phrase(new Chunk(image1, 0, -30));
            //PdfPCell imageCell = new PdfPCell(phrase);

            //imageCell.Border = 0;
            //imageCell.HorizontalAlignment = Element.ALIGN_LEFT; ;
            //PdfPCell fcell1 = new PdfPCell(new Phrase((": Call 13000"), FontFactory.GetFont("Arial", 10, iTextSharp.text.Font.NORMAL)));
            //fcell1.Border = 0;
            //fcell1.HorizontalAlignment = Element.ALIGN_LEFT;
            //pdfTable.AddCell(imageCell);
            //pdfTable.AddCell(fcell1);
            //pdfTable.SetWidthPercentage(new float[2] { 20f, 10f }, PageSize.LETTER);
            //pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
            //pdfDoc.Add(pdfTable);

            //Header Part
            //iTextSharp.text.Image logoHeader = iTextSharp.text.Image.GetInstance(Server.MapPath("~/PDF.jpg"));
            //logoHeader.ScaleAbsolute(500, 300);
            //pdfDoc.Add(logoHeader);

            //PdfPCell cell = new PdfPCell(phrase);
            //tblFirstData.AddCell(cell);

            //pdfDoc.Add(tblFirstData);
            //AddDataInPDFTable objAddDataInPDFTable = new AddDataInPDFTable();
            //objAddDataInPDFTable.AddTableInDoc(pdfDoc);

            htmlparser.Parse(sr);
            pdfDoc.Close();
            Response.Write(pdfDoc);
            Response.End();
        }
        catch (Exception ex)
        {
            log.Fatal("Error in Submitbtn_Click() function." + ex.Message, ex);
        }
    }
    public void ExportToPDF()
    {
        List<DashBoardSettingInfo> lstPages = DashBoardController.GetTopVisitedPage_Report(StartDate, EndDate);
        List<DashBoardSettingInfo> lstBrowser = DashBoardController.GetTopBrowser_Report(StartDate, EndDate);
        List<DashBoardSettingInfo> lstCountry = DashBoardController.GetTopVisitedCountry_Report(StartDate, EndDate);
        List<DashBoardSettingInfo> lstRefSite = DashBoardController.GetRefSite_Report(StartDate, EndDate);
       
        HttpContext.Current.Response.ContentType = "application/pdf";
        HttpContext.Current.Response.AddHeader("content-disposition",
                                               "attachment;filename=" + "CountryVisitCount_" +
                                               DateTime.Now.ToString("M_dd_yyyy_H_M_s") + ".pdf");
        Document doc = new Document(iTextSharp.text.PageSize.A4, 0, 0, 20, 20);
        PdfWriter writer = PdfWriter.GetInstance(doc, HttpContext.Current.Response.OutputStream);
        doc.Open();

        var bodyFont = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 9, Font.NORMAL, new BaseColor(0, 0, 0));
        var cellHeadingColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#E3EDFA"));

        PdfPCell ClearCell = new PdfPCell();
        ClearCell.Border = Rectangle.NO_BORDER;
        ClearCell.Colspan = 2;

        //Page

        PdfPTable tblPages;
        PdfPTable tblPage = new PdfPTable(2);

        tblPages = tblPage;

        var ReportHeaderFont = FontFactory.GetFont(FontFactory.COURIER_BOLD, 14, Font.NORMAL, new BaseColor(125, 88, 15));

        PdfPCell AnalyticReport = new PdfPCell();
        AnalyticReport.Colspan = 2;
        Paragraph AnalyticHeader = new Paragraph("Site Analytic Report", ReportHeaderFont);
        AnalyticReport.AddElement(AnalyticHeader);
        AnalyticHeader.Alignment = Element.ALIGN_CENTER;
        AnalyticReport.Border = Rectangle.NO_BORDER;
        tblPages.AddCell(AnalyticReport);
        tblPage.AddCell(ClearCell);

        var CellHeader = FontFactory.GetFont(FontFactory.COURIER_BOLD, 12, Font.NORMAL, new BaseColor(0, 0, 0));

        var PageHeaderFont = FontFactory.GetFont(FontFactory.COURIER_BOLD, 12, Font.NORMAL, new BaseColor(80, 160, 191));
        PdfPCell blankCell = new PdfPCell();
        blankCell.Colspan = 2;
        Paragraph PageHeader = new Paragraph("Page wise visit", PageHeaderFont);
        blankCell.AddElement(PageHeader);
        blankCell.Border = Rectangle.NO_BORDER;
        tblPages.AddCell(blankCell);


        PdfPTable PageHeaderTbl = new PdfPTable(2);
        PageHeaderTbl.SetWidths(new int[2] { 10, 15 });
        PageHeaderTbl.TotalWidth = doc.PageSize.Width;


        Paragraph headingPage = new Paragraph("Page", CellHeader);
        PdfPCell PageDateCell = new PdfPCell(headingPage);
        PageDateCell.HorizontalAlignment = Element.ALIGN_CENTER;
        tblPages.AddCell(PageDateCell);

        Paragraph HeadingPageCount = new Paragraph("Count", CellHeader);
        PdfPCell PageCount = new PdfPCell(HeadingPageCount);
        PageCount.HorizontalAlignment = Element.ALIGN_CENTER;
        tblPages.AddCell(PageCount);



        foreach (DashBoardSettingInfo objPageinfo in lstPages)
        {
            var PageCell = new PdfPCell(new Paragraph(objPageinfo.VistPageWithoutExtension, bodyFont));
            PageCell.BackgroundColor = cellHeadingColor;
            PageCell.HorizontalAlignment = Element.ALIGN_CENTER;
            tblPages.AddCell(PageCell);

            var CountCell = new PdfPCell(new Paragraph(objPageinfo.VisitTime, bodyFont));
            CountCell.BackgroundColor = cellHeadingColor;
            CountCell.HorizontalAlignment = Element.ALIGN_CENTER;
            tblPages.AddCell(CountCell);
        }

        tblPage.AddCell(ClearCell);
        tblPage.AddCell(ClearCell);
        doc.Add(tblPages);



        //Browser wise visit
        PdfPTable tblBrowsers;
        PdfPTable tblBrowser = new PdfPTable(2);
        tblBrowsers = tblBrowser;

        var BrowserBodyFont = FontFactory.GetFont(FontFactory.COURIER_BOLD, 12, Font.NORMAL, new BaseColor(80, 160, 191));
        PdfPCell BrowserblankCell = new PdfPCell();
        BrowserblankCell.Colspan = 2;
        Paragraph HeadingBrowser = new Paragraph("Browser wise visit", BrowserBodyFont);
        BrowserblankCell.AddElement(HeadingBrowser);
        BrowserblankCell.Border = Rectangle.NO_BORDER;
        tblBrowsers.AddCell(BrowserblankCell);



        PdfPTable BrowserHeaderTbl = new PdfPTable(2);
        PageHeaderTbl.SetWidths(new int[2] { 10, 15 });
        PageHeaderTbl.TotalWidth = doc.PageSize.Width;

        Paragraph headingPara = new Paragraph("Browser", CellHeader);
        PdfPCell BrowserHeading = new PdfPCell(headingPara);
        BrowserHeading.HorizontalAlignment = Element.ALIGN_CENTER;
        BrowserHeading.PaddingLeft = 15f;
        tblBrowsers.AddCell(BrowserHeading);

        Paragraph BrowserCount = new Paragraph("Count", CellHeader);
        PdfPCell BCount = new PdfPCell(BrowserCount);
        BCount.HorizontalAlignment = Element.ALIGN_CENTER;
        BCount.PaddingLeft = 50f;
        tblBrowsers.AddCell(BCount);



        foreach (DashBoardSettingInfo objBrowserinfo in lstBrowser)
        {
            var BrowserCell = new PdfPCell(new Paragraph(objBrowserinfo.Browser, bodyFont));
            BrowserCell.BackgroundColor = cellHeadingColor;
            BrowserCell.HorizontalAlignment = Element.ALIGN_CENTER;
            tblBrowsers.AddCell(BrowserCell);

            var BrowserCountCell = new PdfPCell(new Paragraph(objBrowserinfo.VisitTime, bodyFont));
            BrowserCountCell.HorizontalAlignment = Element.ALIGN_CENTER;
            BrowserCountCell.BackgroundColor = cellHeadingColor;
            tblBrowsers.AddCell(BrowserCountCell);
        }
        tblBrowsers.AddCell(ClearCell);
        tblBrowsers.AddCell(ClearCell);
        doc.Add(tblBrowsers);


        //Country
        PdfPTable tblCountrys;
        PdfPTable tblCountry = new PdfPTable(2);
        tblCountrys = tblCountry;

        var CountryBodyFont = FontFactory.GetFont(FontFactory.COURIER_BOLD, 12, Font.NORMAL, new BaseColor(80, 160, 191));
        PdfPCell CountryblankCell = new PdfPCell();
        CountryblankCell.Colspan = 2;
        Paragraph HeadingCountry = new Paragraph("Country wise visit", CountryBodyFont);
        CountryblankCell.AddElement(HeadingCountry);
        CountryblankCell.Border = Rectangle.NO_BORDER;
        tblCountrys.AddCell(CountryblankCell);



        PdfPTable CountryHeaderTbl = new PdfPTable(2);
        PageHeaderTbl.SetWidths(new int[2] { 10, 15 });
        PageHeaderTbl.TotalWidth = doc.PageSize.Width;

        Paragraph CountryPara = new Paragraph("Country", CellHeader);
        PdfPCell CountryHeading = new PdfPCell(CountryPara);
        CountryHeading.HorizontalAlignment = Element.ALIGN_CENTER;
        tblCountrys.AddCell(CountryHeading);

        Paragraph CountryCount = new Paragraph("Count", CellHeader);
        PdfPCell CCount = new PdfPCell(CountryCount);
        CCount.HorizontalAlignment = Element.ALIGN_CENTER;
        tblCountrys.AddCell(CCount);



        foreach (DashBoardSettingInfo objCountryInfo in lstCountry)
        {
            string CountryName = string.Empty;
            objIP.GetCountry(objCountryInfo.SessionUserHostAddress, out CountryName);
            if (CountryName == string.Empty)
            {
                objCountryInfo.Country = objCountryInfo.SessionUserHostAddress;
            }
            else
            {
                objCountryInfo.Country = CountryName;
            }
            var CountryCell = new PdfPCell(new Paragraph(objCountryInfo.Country, bodyFont));
            CountryCell.BackgroundColor = cellHeadingColor;
            CountryCell.HorizontalAlignment = Element.ALIGN_CENTER;
            tblCountrys.AddCell(CountryCell);

            var CountryVisitCell = new PdfPCell(new Paragraph(objCountryInfo.VisitTime, bodyFont));
            CountryVisitCell.HorizontalAlignment = Element.ALIGN_CENTER;
            CountryVisitCell.BackgroundColor = cellHeadingColor;
            tblCountrys.AddCell(CountryVisitCell);
        }
        tblCountrys.AddCell(ClearCell);
        tblCountrys.AddCell(ClearCell);
        doc.Add(tblCountrys);

        //References Sites

        PdfPTable tblRefSites;
        PdfPTable tblRefSite = new PdfPTable(2);
        tblRefSites = tblRefSite;

        var RefBodyFont = FontFactory.GetFont(FontFactory.COURIER_BOLD, 12, Font.NORMAL, new BaseColor(80, 160, 191));
        PdfPCell RefblankCell = new PdfPCell();
        RefblankCell.Colspan = 2;
        Paragraph HeadingRef = new Paragraph("Reference pages", RefBodyFont);
        RefblankCell.AddElement(HeadingRef);
        RefblankCell.Border = Rectangle.NO_BORDER;
        tblRefSites.AddCell(RefblankCell);



        PdfPTable RefHeaderTbl = new PdfPTable(2);
        PageHeaderTbl.SetWidths(new int[2] { 10, 15 });
        PageHeaderTbl.TotalWidth = doc.PageSize.Width;

        Paragraph RefPara = new Paragraph("Reference pages", CellHeader);
        PdfPCell RefHeading = new PdfPCell(RefPara);
        RefHeading.HorizontalAlignment = Element.ALIGN_CENTER;
        tblRefSites.AddCell(RefHeading);

        Paragraph RefCount = new Paragraph("Count", CellHeader);
        PdfPCell RefParaCount = new PdfPCell(RefCount);
        RefParaCount.HorizontalAlignment = Element.ALIGN_CENTER;
        tblRefSites.AddCell(RefParaCount);



        foreach (DashBoardSettingInfo objRefInfo in lstRefSite)
        {
            var RefCell = new PdfPCell(new Paragraph(objRefInfo.RefPage, bodyFont));
            RefCell.HorizontalAlignment = Element.ALIGN_CENTER;
            RefCell.BackgroundColor = cellHeadingColor;
            RefCell.HorizontalAlignment = Element.ALIGN_CENTER;
            tblRefSites.AddCell(RefCell);

            var RefVisitCell = new PdfPCell(new Paragraph(objRefInfo.VisitTime, bodyFont));
            RefVisitCell.HorizontalAlignment = Element.ALIGN_CENTER;
            RefVisitCell.BackgroundColor = cellHeadingColor;
            tblRefSites.AddCell(RefVisitCell);
        }
        tblRefSites.AddCell(ClearCell);
        tblRefSites.AddCell(ClearCell);
        doc.Add(tblRefSites);

        doc.Close();
    }
Ejemplo n.º 18
0
 /**
 * Creates a PdfPCell with these attributes.
 * @param rowAttributes
 * @return a PdfPCell based on these attributes.
 */
 public PdfPCell CreatePdfPCell(SimpleCell rowAttributes) {
     PdfPCell cell = new PdfPCell();
     cell.Border = NO_BORDER;
     SimpleCell tmp = new SimpleCell(CELL);
     tmp.Spacing_left = spacing_left;
     tmp.Spacing_right = spacing_right;
     tmp.Spacing_top = spacing_top;
     tmp.Spacing_bottom = spacing_bottom;
     tmp.CloneNonPositionParameters(rowAttributes);
     tmp.SoftCloneNonPositionParameters(this);
     cell.CellEvent = tmp;
     cell.HorizontalAlignment = rowAttributes.horizontalAlignment;
     cell.VerticalAlignment = rowAttributes.verticalAlignment;
     cell.UseAscender = rowAttributes.useAscender;
     cell.UseBorderPadding = rowAttributes.useBorderPadding;
     cell.UseDescender = rowAttributes.useDescender;
     cell.Colspan = colspan;
     if (horizontalAlignment != Element.ALIGN_UNDEFINED)
         cell.HorizontalAlignment = horizontalAlignment;
     if (verticalAlignment != Element.ALIGN_UNDEFINED)
         cell.VerticalAlignment = verticalAlignment;
     if (useAscender)
         cell.UseAscender = useAscender;
     if (useBorderPadding)
         cell.UseBorderPadding = useBorderPadding;
     if (useDescender)
         cell.UseDescender = useDescender;
     float p;
     float sp_left = spacing_left;
     if (float.IsNaN(sp_left)) sp_left = 0f;
     float sp_right = spacing_right;
     if (float.IsNaN(sp_right)) sp_right = 0f;
     float sp_top = spacing_top;
     if (float.IsNaN(sp_top)) sp_top = 0f;
     float sp_bottom = spacing_bottom;
     if (float.IsNaN(sp_bottom)) sp_bottom = 0f;
     p = padding_left;
     if (float.IsNaN(p)) p = 0f; 
     cell.PaddingLeft = p + sp_left;
     p = padding_right;
     if (float.IsNaN(p)) p = 0f; 
     cell.PaddingRight = p + sp_right;
     p = padding_top;
     if (float.IsNaN(p)) p = 0f; 
     cell.PaddingTop = p + sp_top;
     p = padding_bottom;
     if (float.IsNaN(p)) p = 0f; 
     cell.PaddingBottom = p + sp_bottom;
     foreach (IElement element in content) {
         cell.AddElement(element);
     }
     return cell;
 }
Ejemplo n.º 19
0
        // write on top of document
        public override void OnEndPage(PdfWriter writer, Document document)
        {
            base.OnEndPage(writer, document);
            var page = document.PageSize;
            float cellHeight = document.TopMargin;

            string imageFilePath = HttpContext.Current.Server.MapPath(".") + "/Images/Contacts.jpg";
            string image3 = HttpContext.Current.Server.MapPath(".") + "/Images/citi_sm-header.jpg";

            Image jpg = Image.GetInstance(imageFilePath);
            jpg.ScaleToFit(360f, 480f);
            jpg.Alignment = Image.ALIGN_LEFT;
            Image jpg3 = Image.GetInstance(image3);
            jpg3.ScaleToFit(80f, 60f);
            jpg3.Alignment = Image.ALIGN_RIGHT;

            PdfPTable table1 = new PdfPTable(2);
            table1.SpacingAfter = 10F;
            table1.TotalWidth = 560f;
            //table1.WidthPercentage = 100;

            PdfPCell cell11 = new PdfPCell();
            cell11.Border = PdfPCell.NO_BORDER;
            cell11.AddElement(jpg);

            //PdfPCell cell10 = new PdfPCell(new Phrase("                         "));
            //cell10.Border = PdfPCell.NO_BORDER;

            PdfPCell cell12 = new PdfPCell();
            cell12.Border = PdfPCell.NO_BORDER;
            cell12.AddElement(jpg3);

            PdfPCell cell13 = new PdfPCell(new Phrase("\n"));
            cell13.Border = PdfPCell.NO_BORDER;

            PdfPCell cell14 = new PdfPCell(new Phrase("\n"));
            cell14.Border = PdfPCell.NO_BORDER;

            //PdfPCell cell15 = new PdfPCell(new Phrase("\n"));
            //cell15.Border = PdfPCell.NO_BORDER;

            table1.AddCell(cell11);
            //table1.AddCell(cell10);
            table1.AddCell(cell12);
            table1.AddCell(cell13);
            table1.AddCell(cell14);
            //table1.AddCell(cell15);

            table1.WriteSelectedRows(0, -1, 10, page.Height - cellHeight + table1.TotalHeight, writer.DirectContent);//WriteSelectedRows(0, -1, 5, document.Top, writer.DirectContent);

            var normalFont = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 7);
            PdfPTable tabFot = new PdfPTable(new float[] { 1F });
            tabFot.SpacingAfter = 10F;
            CreatePdf getParams = new CreatePdf();
            var myParams = getParams.Parameters("FOOTER");
            string[] footerLines = myParams.Paramvalue.Replace("||","|").Split('|');

            PdfPCell cell;
            tabFot.TotalWidth = 600F;
            cell = new PdfPCell(new Phrase("\n"));
            cell.HorizontalAlignment = Element.ALIGN_LEFT;
            cell.Border = PdfPCell.NO_BORDER;
            tabFot.AddCell(cell);
            foreach (var  n in footerLines)
            {
                cell = new PdfPCell(new Phrase(n =="" ? "\n" : n , normalFont));
                cell.HorizontalAlignment = Element.ALIGN_LEFT;
                cell.Border = PdfPCell.NO_BORDER;
                tabFot.AddCell(cell);
            }

            //cell = new PdfPCell(new Phrase("Incorporated in the USA under the National Banking Act Charter No. 1481", normalFont));
            //cell.HorizontalAlignment = Element.ALIGN_LEFT;
            //cell.Border = PdfPCell.NO_BORDER;
            //tabFot.AddCell(cell);
            //cell = new PdfPCell(new Phrase("Local Manager: Joyce-Ann Wainaina", normalFont));
            //cell.HorizontalAlignment = Element.ALIGN_LEFT;
            //cell.Border = PdfPCell.NO_BORDER;
            //tabFot.AddCell(cell);
            //cell = new PdfPCell(new Phrase("Directors: Barbara J. Desoer, Duncan P. Hennes, Eugene M. McQuade, Gary M. Reiner, Robert L. Ryan, Anthony M. Santomero, Joan E. Spero, Diana L. Taylor, James S. Turley (US Citizens) ", normalFont));
            //cell.HorizontalAlignment = Element.ALIGN_LEFT;
            //cell.Border = PdfPCell.NO_BORDER;
            //tabFot.AddCell(cell);
            //cell = new PdfPCell(new Phrase("\n"));
            //cell.HorizontalAlignment = Element.ALIGN_LEFT;
            //cell.Border = PdfPCell.NO_BORDER;
            //tabFot.AddCell(cell);
            //cell = new PdfPCell(new Phrase("Citibank, N.A. Kenya Branch is licensed and regulated by the Central Bank of Kenya", normalFont));
            //cell.HorizontalAlignment = Element.ALIGN_LEFT;
            //cell.Border = PdfPCell.NO_BORDER;
            //tabFot.AddCell(cell);

            cell = new PdfPCell(new Phrase("\n"));
            cell.HorizontalAlignment = Element.ALIGN_LEFT;
            cell.Border = PdfPCell.NO_BORDER;
            tabFot.AddCell(cell);
            tabFot.WriteSelectedRows(0, -1, 20, document.Bottom, writer.DirectContent);
        }
Ejemplo n.º 20
0
        public void Run(Stream stream, CMSDataContext Db, IEnumerable<ContributorInfo> q, int set = 0)
        {
            pageEvents.set = set;
            IEnumerable<ContributorInfo> contributors = q;
            var toDate = ToDate.Date.AddHours(24).AddSeconds(-1);

            PdfContentByte dc;
            var font = FontFactory.GetFont(FontFactory.HELVETICA, 11);
            var boldfont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 11);

            var doc = new Document(PageSize.LETTER);
            doc.SetMargins(36f, 30f, 24f, 36f);
            var w = PdfWriter.GetInstance(doc, stream);
            w.PageEvent = pageEvents;
            doc.Open();
            dc = w.DirectContent;

            int prevfid = 0;
            var runningtotals = Db.ContributionsRuns.OrderByDescending(mm => mm.Id).FirstOrDefault();
            runningtotals.Processed = 0;
            Db.SubmitChanges();
            var count = 0;
            foreach (var ci in contributors)
            {
                if (set > 0 && pageEvents.FamilySet[ci.PeopleId] != set)
                    continue;
                doc.NewPage();
                if (prevfid != ci.FamilyId)
                {
                    prevfid = ci.FamilyId;
                    pageEvents.EndPageSet();
                }
                if (set == 0)
                    pageEvents.FamilySet[ci.PeopleId] = 0;
                count++;

                var css = @"
            <style>
            h1 { font-size: 24px; font-weight:normal; margin-bottom:0; }
            h2 { font-size: 11px; font-weight:normal; margin-top: 0; }
            p { font-size: 11px; }
            </style>
            ";

                //----Church Name
                var t1 = new PdfPTable(1);
                t1.TotalWidth = 72f * 5f;
                t1.DefaultCell.Border = Rectangle.NO_BORDER;
                string html1 = Db.ContentHtml("StatementHeader", Resource1.ContributionStatementHeader);
                string html2 = Db.ContentHtml("StatementNotice", Resource1.ContributionStatementNotice);

                var mh = new MyHandler();
                using (var sr = new StringReader(css + html1))
                    XMLWorkerHelper.GetInstance().ParseXHtml(mh, sr);

                var cell = new PdfPCell(t1.DefaultCell);
                foreach (var e in mh.elements)
                    if (e.Chunks.Count > 0)
                        cell.AddElement(e);
                //cell.FixedHeight = 72f * 1.25f;
                t1.AddCell(cell);
                t1.AddCell("\n");

                var t1a = new PdfPTable(1);
                t1a.TotalWidth = 72f * 5f;
                t1a.DefaultCell.Border = Rectangle.NO_BORDER;

                var ae = new PdfPTable(1);
                ae.DefaultCell.Border = Rectangle.NO_BORDER;
                ae.WidthPercentage = 100;

                var a = new PdfPTable(1);
                a.DefaultCell.Indent = 25f;
                a.DefaultCell.Border = Rectangle.NO_BORDER;
                a.AddCell(new Phrase(ci.Name, font));
                a.AddCell(new Phrase(ci.Address1, font));
                if (ci.Address2.HasValue())
                    a.AddCell(new Phrase(ci.Address2, font));
                a.AddCell(new Phrase(ci.CityStateZip, font));
                cell = new PdfPCell(a) { Border = Rectangle.NO_BORDER };
                //cell.FixedHeight = 72f * 1.0625f;
                ae.AddCell(cell);

                cell = new PdfPCell(t1a.DefaultCell);
                cell.AddElement(ae);
                t1a.AddCell(ae);

                //-----Notice
                var t2 = new PdfPTable(1);
                t2.TotalWidth = 72f * 3f;
                t2.DefaultCell.Border = Rectangle.NO_BORDER;
                t2.AddCell(new Phrase("\nPrint Date: {0:d}   (id:{1} {2})".Fmt(DateTime.Now, ci.PeopleId, ci.CampusId), font));
                t2.AddCell("");
                var mh2 = new MyHandler();
                using (var sr = new StringReader(css + html2))
                    XMLWorkerHelper.GetInstance().ParseXHtml(mh2, sr);
                cell = new PdfPCell(t1.DefaultCell);
                foreach (var e in mh2.elements)
                    if (e.Chunks.Count > 0)
                        cell.AddElement(e);
                t2.AddCell(cell);

                // POSITIONING OF ADDRESSES
                //----Header
                var yp = doc.BottomMargin +
                    Db.Setting("StatementRetAddrPos", "10.125").ToFloat() * 72f;
                t1.WriteSelectedRows(0, -1,
                    doc.LeftMargin - 0.1875f * 72f, yp, dc);

                yp = doc.BottomMargin +
                    Db.Setting("StatementAddrPos", "8.3375").ToFloat() * 72f;
                t1a.WriteSelectedRows(0, -1, doc.LeftMargin, yp, dc);

                yp = doc.BottomMargin + 10.125f * 72f;
                t2.WriteSelectedRows(0, -1, doc.LeftMargin + 72f * 4.4f, yp, dc);

                //----Contributions
                doc.Add(new Paragraph(" "));
                doc.Add(new Paragraph(" ") { SpacingBefore = 72f * 2.125f });

                doc.Add(new Phrase("\n  Period: {0:d} - {1:d}".Fmt(FromDate, toDate), boldfont));

                var pos = w.GetVerticalPosition(true);

                var ct = new ColumnText(dc);
                float gutter = 20f;
                float colwidth = (doc.Right - doc.Left - gutter) / 2;

                var t = new PdfPTable(new float[] { 10f, 24f, 10f });
                t.WidthPercentage = 100;
                t.DefaultCell.Border = Rectangle.NO_BORDER;
                t.HeaderRows = 2;

                cell = new PdfPCell(t.DefaultCell);
                cell.Colspan = 3;
                cell.Phrase = new Phrase("Contributions\n", boldfont);
                t.AddCell(cell);

                t.DefaultCell.Border = Rectangle.BOTTOM_BORDER;
                t.AddCell(new Phrase("Date", boldfont));
                t.AddCell(new Phrase("Description", boldfont));
                cell = new PdfPCell(t.DefaultCell);
                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                cell.Phrase = new Phrase("Amount", boldfont);
                t.AddCell(cell);

                t.DefaultCell.Border = Rectangle.NO_BORDER;

                var total = 0m;
                foreach (var c in APIContribution.contributions(Db, ci, FromDate, toDate))
                {
                    t.AddCell(new Phrase(c.ContributionDate.ToShortDateString(), font));
                    t.AddCell(new Phrase(c.Fund, font));
                    cell = new PdfPCell(t.DefaultCell);
                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    cell.Phrase = new Phrase(c.ContributionAmount.ToString("N2"), font);
                    t.AddCell(cell);
                    total += (c.ContributionAmount);
                }
                t.DefaultCell.Border = Rectangle.TOP_BORDER;
                cell = new PdfPCell(t.DefaultCell);
                cell.Colspan = 2;
                cell.Phrase = new Phrase("Total Contributions for period", boldfont);
                t.AddCell(cell);
                cell = new PdfPCell(t.DefaultCell);
                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                cell.Phrase = new Phrase(total.ToString("N2"), font);
                t.AddCell(cell);

                ct.AddElement(t);

                //------Pledges
                var pledges = APIContribution.pledges(Db, ci, toDate).ToList();
                if (pledges.Count > 0)
                {
                    t = new PdfPTable(new float[] { 16f, 12f, 12f });
                    t.WidthPercentage = 100;
                    t.DefaultCell.Border = Rectangle.NO_BORDER;
                    t.HeaderRows = 2;

                    cell = new PdfPCell(t.DefaultCell);
                    cell.Colspan = 3;
                    cell.Phrase = new Phrase("\n\nPledges\n", boldfont);
                    t.AddCell(cell);

                    t.DefaultCell.Border = Rectangle.BOTTOM_BORDER;
                    t.AddCell(new Phrase("Fund", boldfont));
                    cell = new PdfPCell(t.DefaultCell);
                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    cell.Phrase = new Phrase("Pledge", boldfont);
                    t.AddCell(cell);
                    cell = new PdfPCell(t.DefaultCell);
                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    cell.Phrase = new Phrase("Given", boldfont);
                    t.AddCell(cell);

                    t.DefaultCell.Border = Rectangle.NO_BORDER;

                    foreach (var c in pledges)
                    {
                        t.AddCell(new Phrase(c.Fund, font));
                        cell = new PdfPCell(t.DefaultCell);
                        cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        cell.Phrase = new Phrase(c.PledgeAmount.ToString2("N2"), font);
                        t.AddCell(cell);
                        cell = new PdfPCell(t.DefaultCell);
                        cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        cell.Phrase = new Phrase(c.ContributionAmount.ToString2("N2"), font);
                        t.AddCell(cell);
                    }
                    ct.AddElement(t);
                }

                //------Gifts In Kind
                var giftsinkind = APIContribution.GiftsInKind(Db, ci, FromDate, toDate).ToList();
                if (giftsinkind.Count > 0)
                {
                    t = new PdfPTable(new float[] { 12f, 18f, 20f });
                    t.WidthPercentage = 100;
                    t.DefaultCell.Border = Rectangle.NO_BORDER;
                    t.HeaderRows = 2;

                    cell = new PdfPCell(t.DefaultCell);
                    cell.Colspan = 3;
                    cell.Phrase = new Phrase("\n\nGifts in Kind\n", boldfont);
                    t.AddCell(cell);

                    t.DefaultCell.Border = Rectangle.BOTTOM_BORDER;
                    t.AddCell(new Phrase("Date", boldfont));
                    cell = new PdfPCell(t.DefaultCell);
                    cell.Phrase = new Phrase("Fund", boldfont);
                    t.AddCell(cell);
                    cell = new PdfPCell(t.DefaultCell);
                    cell.Phrase = new Phrase("Description", boldfont);
                    t.AddCell(cell);

                    t.DefaultCell.Border = Rectangle.NO_BORDER;

                    foreach (var c in giftsinkind)
                    {
                        t.AddCell(new Phrase(c.ContributionDate.ToShortDateString(), font));
                        cell = new PdfPCell(t.DefaultCell);
                        cell.Phrase = new Phrase(c.Fund, font);
                        t.AddCell(cell);
                        cell = new PdfPCell(t.DefaultCell);
                        cell.Phrase = new Phrase(c.Description, font);
                        t.AddCell(cell);
                    }
                    ct.AddElement(t);
                }

                //-----Summary
                t = new PdfPTable(new float[] { 29f, 9f });
                t.WidthPercentage = 100;
                t.DefaultCell.Border = Rectangle.NO_BORDER;
                t.HeaderRows = 2;

                cell = new PdfPCell(t.DefaultCell);
                cell.Colspan = 2;
                cell.Phrase = new Phrase("\n\nPeriod Summary\n", boldfont);
                t.AddCell(cell);

                t.DefaultCell.Border = Rectangle.BOTTOM_BORDER;
                t.AddCell(new Phrase("Fund", boldfont));
                cell = new PdfPCell(t.DefaultCell);
                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                cell.Phrase = new Phrase("Amount", boldfont);
                t.AddCell(cell);

                t.DefaultCell.Border = Rectangle.NO_BORDER;
                foreach (var c in APIContribution.quarterlySummary(Db, ci, FromDate, toDate))
                {
                    t.AddCell(new Phrase(c.Fund, font));
                    cell = new PdfPCell(t.DefaultCell);
                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    cell.Phrase = new Phrase(c.ContributionAmount.ToString("N2"), font);
                    t.AddCell(cell);
                }
                t.DefaultCell.Border = Rectangle.TOP_BORDER;
                t.AddCell(new Phrase("Total contributions for period", boldfont));
                cell = new PdfPCell(t.DefaultCell);
                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                cell.Phrase = new Phrase(total.ToString("N2"), font);
                t.AddCell(cell);
                ct.AddElement(t);

                var col = 0;
                var status = 0;
                while (ColumnText.HasMoreText(status))
                {
                    if (col == 0)
                        ct.SetSimpleColumn(doc.Left, doc.Bottom, doc.Left + colwidth, pos);
                    else if (col == 1)
                        ct.SetSimpleColumn(doc.Right - colwidth, doc.Bottom, doc.Right, pos);
                    status = ct.Go();
                    ++col;
                    if (col > 1)
                    {
                        col = 0;
                        pos = doc.Top;
                        doc.NewPage();
                    }
                }

                runningtotals.Processed += 1;
                runningtotals.CurrSet = set;
                Db.SubmitChanges();
            }

            if (count == 0)
            {
                doc.NewPage();
                doc.Add(new Phrase("no data"));
            }
            doc.Close();

            if (set == LastSet())
                runningtotals.Completed = DateTime.Now;
            Db.SubmitChanges();
        }
Ejemplo n.º 21
0
        private void MakePdfReportButton_OnClick(object sender, EventArgs e)
        {
            var Time = new Stopwatch();
            Time.Start();

            var Begin = startDate.Month + "/" + startDate.Day + "/" + startDate.Year;
            var End = endDate.Month + "/" + endDate.Day + "/" + endDate.Year;

            var data = GetData("SELECT " +
                               "sl.ReportDate," +
                               "p.[Product Name] AS Product," +
                               " sl.Quantity AS Quantitity," +
                               " sl.ActualPrice AS [Unit Price]," +
                               " s.Name AS [Location]," +
                               " sl.Quantity * sl.ActualPrice AS [Sum] " +
                               "FROM SalesReports sl " +
                               "INNER JOIN Products p ON sl.ProductId = p.ID " +
                               "INNER JOIN Supermarkets s ON sl.SupermarketId = s.Id " +
                               "WHERE sl.ReportDate > '" + Begin + "' AND sl.ReportDate < '" + End + "'");

            if (data.Rows.Count > 1)
            {
                var report = new Document();
                DateTime? date = null;
                double dateSum = 0;

                PdfWriter.GetInstance(report, new FileStream("../../../PDF-Reports/Report.pdf", FileMode.Create));

                report.Open();

                var times = new Font(null, 16, Font.BOLD);

                var header = new PdfPTable(1);
                header.WidthPercentage = 100;
                var headerCell = new PdfPCell(new Phrase("Aggregated Sales Report", times));
                headerCell.HorizontalAlignment = Element.ALIGN_CENTER;
                header.AddCell(headerCell);
                report.Add(header);

                var t = new PdfPTable(5);

                Console.WriteLine(data.Rows.Count);
                foreach (DataRow dataRow in data.Rows)
                {
                    t = new PdfPTable(5);

                    float[] widths = {2f, 1f, 1f, 3f, 1f};

                    t.SetWidths(widths);
                    t.DefaultCell.FixedHeight = 100f;
                    t.WidthPercentage = 100;

                    foreach (var item in dataRow.ItemArray)
                    {
                        if (item is DateTime)
                        {
                            if (date != (DateTime) item)
                            {
                                if (date != null)
                                {
                                    var finalDate = new PdfPCell(new Phrase("Total sum for: " + item,
                                        new Font(null, 11, Font.BOLD)));
                                    var finalSum = new PdfPCell();
                                    finalDate.Colspan = 4;
                                    finalSum.Colspan = 1;
                                    finalDate.HorizontalAlignment = Element.ALIGN_RIGHT;
                                    finalSum.AddElement(new Chunk(dateSum.ToString()));
                                    t.AddCell(finalDate);
                                    t.AddCell(finalSum);
                                }

                                date = (DateTime) item;
                                var newDate = new Chunk(item.ToString());
                                var dateCell = new PdfPCell();
                                dateCell.Colspan = 5;
                                dateCell.BackgroundColor = BaseColor.LIGHT_GRAY;
                                dateCell.AddElement(newDate);
                                t.AddCell(dateCell);
                            }
                        }
                        else
                        {
                            var chunk = new Chunk(item.ToString());
                            var c = new PdfPCell();
                            c.AddElement(chunk);
                            t.AddCell(c);
                        }
                    }
                    report.Add(t);

                    dateSum += double.Parse(dataRow.ItemArray[dataRow.ItemArray.Count() - 1].ToString());
                }

                var lastDate = new PdfPCell();
                var lastSum = new PdfPCell();
                lastDate.Colspan = 4;
                lastSum.Colspan = 1;
                lastDate.AddElement(new Chunk("Total sum for: " + date));
                lastSum.AddElement(new Chunk(dateSum.ToString()));
                t.AddCell(lastDate);
                t.AddCell(lastSum);

                report.Add(t);

                report.Close();

                var result = MessageBox.Show("PDF Report created successfully! It took us: "
                                             + Time.Elapsed.TotalSeconds + " seconds to complete your request.",
                    "Success", MessageBoxButton.OK, MessageBoxImage.Information);
                if (result == MessageBoxResult.OK)
                {
                    Application.Current.Shutdown();
                }
            }

            else
            {
                var error = MessageBox.Show("There were no entries for the " +
                                            "given period of time!", "Error",
                    MessageBoxButton.OK,
                    MessageBoxImage.Information);
                if (error == MessageBoxResult.OK)
                {
                    Application.Current.Shutdown();
                }
            }
        }
    protected void btnSavePDFForm2_Click(object sender, EventArgs e)
    {
        try
        {
            string tableContent = HdnValue.Value;

            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=" + "MyReport_" + DateTime.Now.ToString("M_dd_yyyy_H_M_s") + ".pdf");

            Document doc = new Document(iTextSharp.text.PageSize.A4, 40, 10f, 42, 10);// new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
            // pdfPage page = new pdfPage();
            PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);
            //writer.PageEvent = page;
            doc.Open();

            //--- start of header----
            // Paragraph pa = new Paragraph("Invoice");
            PdfPTable headerTbl = new PdfPTable(2);
            headerTbl.SetWidths(new int[2] { 10, 15 });
            //headerTbl.DefaultCell.Border = Rectangle.NO_BORDER;
            headerTbl.TotalWidth = doc.PageSize.Width;
            iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(Request.MapPath("~/Templates/" + TemplateName + "/images/aspxcommerce.png"));
            logo.ScalePercent(50f);
            PdfPCell cellH = new PdfPCell(logo);
            cellH.AddElement(logo);
            cellH.HorizontalAlignment = Element.ALIGN_LEFT;
            cellH.PaddingLeft = 40;
            // cellH.Width = 10;
            cellH.Border = Rectangle.NO_BORDER;
            cellH.Border = Rectangle.BOTTOM_BORDER;
            headerTbl.AddCell(cellH);

            //--for second cell ----------
            Paragraph pa = new Paragraph("Invoice", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 16, Font.BOLD, new BaseColor(0, 0, 255)));
            PdfPCell cell2 = new PdfPCell(pa);
            pa.Alignment = Element.ALIGN_BOTTOM;
            cell2.AddElement(pa);
            //cell2.HorizontalAlignment = Element.ALIGN_BASELINE;

            cell2.Border = Rectangle.NO_BORDER;
            cell2.Border = Rectangle.BOTTOM_BORDER;
            headerTbl.AddCell(cell2);


            headerTbl.WriteSelectedRows(0, -1, 0, (doc.PageSize.Height - 10), writer.DirectContent);

            //---end of header

            // -- portion for footer--------
            PdfPTable footerTbl = new PdfPTable(1);
            footerTbl.TotalWidth = doc.PageSize.Width;
            footerTbl.HorizontalAlignment = Element.ALIGN_CENTER;
            Paragraph para = new Paragraph("ASPXCommerce CopyRight 2011", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 9, Font.NORMAL, new BaseColor(0, 0, 255)));
            PdfPCell cell = new PdfPCell(para);
            cell = new PdfPCell(para);
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            cell.Border = Rectangle.NO_BORDER;
            cell.PaddingRight = 15;
            footerTbl.AddCell(cell);
            footerTbl.WriteSelectedRows(0, -1, 0, (doc.BottomMargin + 20), writer.DirectContent);
            //---- end of footer ------------


            //iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(Request.MapPath("Templates/ASPXCommerce/images/aspxcommerce.png"));
            //logo.Alignment = iTextSharp.text.Image.ALIGN_TOP;
            //logo.ScalePercent(50f);
            //doc.Add(logo);

            // iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();
            iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(doc);
            hw.Parse(new StringReader(tableContent));

            doc.Close();
        }
        catch (Exception ex)
        {
            ProcessException(ex);
        }
    }
Ejemplo n.º 23
0
        protected void mCreaPDF(GridView gvMaestro, GridView gvDetalle)
        {
            MemoryStream tmp = new MemoryStream();
            try
            {
                //Dimensiones del Docuemnto
                //Document documento = new Document(PageSize.LETTER, 50, 50, 80, 50);
                Document documento = new Document(PageSize.LETTER);

                // step 2: creamos el documento
                 //pdf.PdfWriter.GetInstance(Documento, New FileStream("Demo.pdf", FileMode.Create)) '
                //PdfWriter writerPdf = PdfWriter.GetInstance(documento, tmp);
                string ruta = AppDomain.CurrentDomain.BaseDirectory.ToString()+"/constancia/"+NombreArchivo+".pdf";
                PdfWriter writerPdf = PdfWriter.GetInstance(documento, new FileStream(ruta, System.IO.FileMode.Create,FileAccess.ReadWrite));
                //PdfWriter writerPdf = PdfWriter.GetInstance(documento, tmp);
                itsEvents ev = new itsEvents();
                ev.USUARIO = Session["User"].ToString();
                ev.CREACION = DateTime.Now;
                writerPdf.PageEvent = ev;
                //writerPdf.SetEncryption(PdfWriter.STANDARD_ENCRYPTION_128, null, null, PdfWriter.AllowPrinting);

                #region FUENTES Y TEXTOS DE ARCHIVO
                Font fontFirmas = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 8, Font.BOLD, BaseColor.BLACK);
                Font font20B = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 20, Font.BOLD, BaseColor.DARK_GRAY);
                Font font8B = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 8, Font.BOLD, BaseColor.DARK_GRAY);
                Font LetraTituloTabla = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 8, Font.BOLDITALIC);
                Font LetraContenidoTabla = FontFactory.GetFont(FontFactory.HELVETICA, 6, Font.NORMAL);
                Phrase Titulo = new Phrase("CONSTANCIA DE RESGUARDO", font20B);
                Phrase SubTitulo = new Phrase(Session["NombreArchivo"].ToString(), font8B);
                Phrase SubTitulo2 = new Phrase("DETALLE POR SUCURSAL", LetraTituloTabla);
                #endregion
                // step 3: abrimos el documento
                documento.Open();
                #region ENCABEZADO

                ////agregar imagen
                //iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(AppDomain.CurrentDomain.BaseDirectory.ToString() + "/img/cofiño_stahl.jpg");
                ////jpg.Alignment = iTextSharp.text.Image.MIDDLE_ALIGN;
                //jpg.ScalePercent(25f);

                ////We are going to add two strings in header. Create separate Phrase object with font setting and string to be included
                //Phrase p1Header = new Phrase("Facturación Electrónica", FontFactory.GetFont("verdana", 14));
                //Phrase p2Header = new Phrase(DateTime.Now.ToLongDateString(), FontFactory.GetFont("verdana", 8));

                ////create iTextSharp.text Image object using local image path
                //iTextSharp.text.Image imgPDF = iTextSharp.text.Image.GetInstance(HttpRuntime.AppDomainAppPath + "\\img\\cofiño_stahl.jpg");
                //imgPDF.ScalePercent(25f);
                ////Create PdfTable object
                //PdfPTable pdfTab = new PdfPTable(3);
                ////We will have to create separate cells to include image logo and 2 separate strings
                //PdfPCell pdfCell1 = new PdfPCell(imgPDF);
                //PdfPCell pdfCell2 = new PdfPCell(p1Header);
                //PdfPCell pdfCell3 = new PdfPCell(p2Header);
                ////set the alignment of all three cells and set border to 0
                //pdfCell1.HorizontalAlignment = Element.ALIGN_LEFT;
                //pdfCell2.HorizontalAlignment = Element.ALIGN_LEFT;
                //pdfCell3.HorizontalAlignment = Element.ALIGN_LEFT;
                //pdfCell1.Border = 0;
                //pdfCell2.Border = 0;
                //pdfCell3.Border = 0;
                //pdfCell2.VerticalAlignment = Element.ALIGN_MIDDLE;
                //pdfCell3.VerticalAlignment = Element.ALIGN_BOTTOM;
                ////establecer anchos
                //float[] withsHead = new float[] { 14f, 49f, 21f };
                ////add all three cells into PdfTable
                //pdfTab.AddCell(pdfCell1);
                //pdfTab.AddCell(pdfCell2);
                //pdfTab.AddCell(pdfCell3);
                //pdfTab.SetWidthPercentage(withsHead, documento.PageSize);
                //pdfTab.TotalWidth = documento.PageSize.Width - 30;
                ////call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable
                ////first param is start row. -1 indicates there is no end row and all the rows to be included to write
                ////Third and fourth param is x and y position to start writing
                //pdfTab.WriteSelectedRows(0, -1, 30, documento.PageSize.Height - 15, writerPdf.DirectContent);
                ////set pdfContent value
                //PdfContentByte pdfContent = writerPdf.DirectContent;
                ////Move the pointer and draw line to separate header section from rest of page
                //pdfContent.MoveTo(30, documento.PageSize.Height - 45);
                //pdfContent.LineTo(documento.PageSize.Width - 40, documento.PageSize.Height - 45);
                //pdfContent.Stroke();

                //documento.Add(new Phrase(Chunk.NEWLINE));
                //documento.Add(new Phrase(Chunk.NEWLINE));
                //documento.Add(new Phrase(Chunk.NEWLINE));
                #endregion

                #region TITULO Y SUBTITULO
                Paragraph pTitulo = new Paragraph(Titulo);
                pTitulo.Alignment = Element.ALIGN_CENTER;
                documento.Add(pTitulo);

                Paragraph pSubTitulo = new Paragraph(SubTitulo);
                pSubTitulo.Alignment = Element.ALIGN_CENTER;
                documento.Add(pSubTitulo);

                documento.Add(new Phrase(Chunk.NEWLINE));
                #endregion

                #region MAESTRO
                //Creacion de la tabla que se mostrara en el Pdf
                PdfPTable table = new PdfPTable(8);
                //Cremos las cabeceras de la tabla
                PdfPCell compania = new PdfPCell(new Phrase("Compañia", LetraTituloTabla));
                PdfPCell tipoDocumento = new PdfPCell(new Phrase("Tipo Documento", LetraTituloTabla));
                PdfPCell cantidadDocumentos = new PdfPCell(new Phrase("Cantidad de Documentos", LetraTituloTabla));
                PdfPCell totalEFACE = new PdfPCell(new Phrase("Total EFACE", LetraTituloTabla));
                PdfPCell ivaEFACE = new PdfPCell(new Phrase("IVA EFACE", LetraTituloTabla));
                PdfPCell cantidadDocumentosVentas = new PdfPCell(new Phrase("Cantidad Documentos Ventas", LetraTituloTabla));
                PdfPCell ivaVentas = new PdfPCell(new Phrase("IVA Ventas", LetraTituloTabla));
                PdfPCell totalVentas = new PdfPCell(new Phrase("Total Ventas", LetraTituloTabla));

                compania.HorizontalAlignment = Element.ALIGN_CENTER;
                tipoDocumento.HorizontalAlignment = Element.ALIGN_CENTER;
                cantidadDocumentos.HorizontalAlignment = Element.ALIGN_CENTER;
                totalEFACE.HorizontalAlignment = Element.ALIGN_CENTER;
                ivaEFACE.HorizontalAlignment = Element.ALIGN_CENTER;
                cantidadDocumentosVentas.HorizontalAlignment = Element.ALIGN_CENTER;
                ivaVentas.HorizontalAlignment = Element.ALIGN_CENTER;
                totalVentas.HorizontalAlignment = Element.ALIGN_CENTER;

                //Adicionamos las cabeceras a la tabla
                table.AddCell(compania);
                table.AddCell(tipoDocumento);
                table.AddCell(cantidadDocumentos);
                table.AddCell(totalEFACE);
                table.AddCell(ivaEFACE);
                table.AddCell(cantidadDocumentosVentas);
                table.AddCell(ivaVentas);
                table.AddCell(totalVentas);

                // recorremos todos las filas del Datatable

                foreach (GridViewRow fila in gvMaestro.Rows)
                {
                    for (int k = 0; k < 8; k++)
                    {
                        PdfPCell ctmp;
                        if (k>2 && k<8 && k!=5)
                            ctmp = new PdfPCell(new Phrase("Q. "+fila.Cells[k].Text, LetraContenidoTabla));
                        else
                            ctmp = new PdfPCell(new Phrase((fila.Cells[k].Text.Contains("&#209;")) ? fila.Cells[k].Text.Replace("&#209;", "Ñ") : fila.Cells[k].Text, LetraContenidoTabla));
                        if (k > 1)
                            ctmp.HorizontalAlignment = Element.ALIGN_RIGHT;
                        table.AddCell(ctmp);
                    }
                }
                table.WidthPercentage = 100;
                //table.TotalWidth = 1000;
                //table.WriteSelectedRows(0, -1, 50, 700, writerPdf.DirectContent);

                documento.Add(table);
                documento.Add(new Phrase(Chunk.NEWLINE));
                #endregion

                #region DETALLE
                PdfPTable table2 = new PdfPTable(5);
                PdfPCell compania2 = new PdfPCell(new Phrase("Compañia", LetraTituloTabla));
                PdfPCell tipoDocumento2 = new PdfPCell(new Phrase("Tipo Documento", LetraTituloTabla));
                PdfPCell sucursal = new PdfPCell(new Phrase("Sucursal", LetraTituloTabla));
                PdfPCell cantidad = new PdfPCell(new Phrase("Cantidad", LetraTituloTabla));
                PdfPCell totalEFACE2 = new PdfPCell(new Phrase("Total EFACE", LetraTituloTabla));

                float[] withs = new float[] { 8f, 8f, 8f, 3f, 6f };
                table2.SetWidths(withs);
                compania2.HorizontalAlignment = Element.ALIGN_CENTER;
                tipoDocumento2.HorizontalAlignment = Element.ALIGN_CENTER;
                sucursal.HorizontalAlignment = Element.ALIGN_CENTER;
                cantidad.HorizontalAlignment = Element.ALIGN_CENTER;
                totalEFACE2.HorizontalAlignment = Element.ALIGN_CENTER;
                //Adicionamos las cabeceras a la tabla
                table2.AddCell(compania2);
                table2.AddCell(tipoDocumento2);
                table2.AddCell(sucursal);
                table2.AddCell(cantidad);
                table2.AddCell(totalEFACE2);

                // for (int j = 0; j < 50;j++ )
                // recorremos todos las filas del Datatable
                int iCantidad = 0;
                double iTotal = 0;
                foreach (GridViewRow fila in gvDetalle.Rows)
                {
                    for (int k = 0; k < 5; k++)
                    {
                        PdfPCell ctmp2;
                        if (k == 3)
                            iCantidad += int.Parse(fila.Cells[k].Text);
                        if (k == 4)
                        {
                            iTotal += double.Parse(fila.Cells[k].Text);
                            ctmp2 = new PdfPCell(new Phrase("Q. " + fila.Cells[k].Text, LetraContenidoTabla));
                        }
                        else
                            ctmp2 = new PdfPCell(new Phrase((fila.Cells[k].Text.Contains("&#209;")) ? fila.Cells[k].Text.Replace("&#209;", "Ñ") : fila.Cells[k].Text, LetraContenidoTabla));
                        if (k > 2)
                            ctmp2.HorizontalAlignment = Element.ALIGN_RIGHT;
                        table2.AddCell(ctmp2);
                    }
                }
                PdfPCell tmpEspacioCelda = new PdfPCell();
                tmpEspacioCelda.Colspan = 3;
                table2.AddCell(tmpEspacioCelda);
                PdfPCell tmpCantidad = new PdfPCell();
                PdfPCell tmpTotal = new PdfPCell();
                tmpCantidad = new PdfPCell(new Phrase(iCantidad.ToString(), LetraContenidoTabla));
                //string aux = String.Format("{0:n}", iTotal);
                tmpTotal = new PdfPCell(new Phrase("Q. " + String.Format("{0:n}",iTotal), LetraContenidoTabla));
                tmpCantidad.HorizontalAlignment = Element.ALIGN_RIGHT;
                tmpTotal.HorizontalAlignment = Element.ALIGN_RIGHT;
                table2.AddCell(tmpCantidad);
                table2.AddCell(tmpTotal);

                table2.WidthPercentage = 100;
                //table2.WriteSelectedRows(0, -1, 50, 900, writerPdf.DirectContent);
                Paragraph pSubTitulo2 = new Paragraph(SubTitulo2);
                pSubTitulo.Alignment = Element.ALIGN_LEFT;
                documento.Add(pSubTitulo2);
                documento.Add(table2);
                mEspacio(6, documento);
                #endregion

                #region FIRMA
                //tabla de firmas
                PdfPTable tFirmas = new PdfPTable(3);
                PdfPCell cFirma1 = new PdfPCell();
                PdfPCell cFirma2 = new PdfPCell();
                PdfPCell cEspacio = new PdfPCell();
                Paragraph pFirma1 = new Paragraph("WALTER CANU", fontFirmas);
                string operador = AD.RealizaConsulta(String.Format(querys.NombreUsuario, Session["User"].ToString())).Rows[0][0].ToString();
                Paragraph pFirma2 = new Paragraph(operador.Trim(), fontFirmas);
                Phrase pEspacio = new Phrase("     ");
                pFirma1.Alignment = Element.ALIGN_TOP;
                pFirma2.Alignment = Element.ALIGN_TOP;
                pFirma1.Alignment = Element.ALIGN_CENTER;
                pFirma2.Alignment = Element.ALIGN_CENTER;
                cFirma1.AddElement(pFirma1);
                cFirma2.AddElement(pFirma2);
                cFirma1.HorizontalAlignment = Element.ALIGN_CENTER;
                cFirma1.VerticalAlignment = Element.ALIGN_TOP;
                cFirma2.HorizontalAlignment = Element.ALIGN_CENTER;
                cFirma2.VerticalAlignment = Element.ALIGN_TOP;
                cFirma1.Border = 1;
                cFirma2.Border = 1;
                cEspacio.Border = 0;
                tFirmas.AddCell(cFirma1);
                tFirmas.AddCell(cEspacio);
                tFirmas.AddCell(cFirma2);
                float[] widthFirmas = new float[] { 45, 10, 45 };
                tFirmas.SetWidths(widthFirmas);

                documento.Add(tFirmas);
                #endregion
                mEspacio(5, documento);

                // step 4: Cerramos el Documento
                documento.Close();
            }
            catch (DocumentException de)
            {
                Debug.WriteLine(de.Message);
            }
            catch (IOException ioe)
            {
                Debug.WriteLine(ioe.Message);
            }
            #region DESCARGAR CONSTANCIA PDF

            //mDownloadFile(tmp,"constancia.pdf");

            #endregion
        }
Ejemplo n.º 24
0
Archivo: SSP.cs Proyecto: nasrun163/PDF
        public void pdfSSP(DataRow dr)
        {
            try
            {
                BaseFont             bf           = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                iTextSharp.text.Font Font8        = new iTextSharp.text.Font(bf, 8, iTextSharp.text.Font.NORMAL);
                iTextSharp.text.Font Font8Italic  = new iTextSharp.text.Font(bf, 8, iTextSharp.text.Font.ITALIC);
                iTextSharp.text.Font Font9        = new iTextSharp.text.Font(bf, 9, iTextSharp.text.Font.NORMAL);
                iTextSharp.text.Font Font10       = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);
                iTextSharp.text.Font Font10Italic = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.ITALIC);
                iTextSharp.text.Font Font10BOLD   = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.BOLD);
                iTextSharp.text.Font Font11       = new iTextSharp.text.Font(bf, 11, iTextSharp.text.Font.NORMAL);
                iTextSharp.text.Font Font12       = new iTextSharp.text.Font(bf, 12, iTextSharp.text.Font.NORMAL);
                iTextSharp.text.Font Font12BOLD   = new iTextSharp.text.Font(bf, 12, iTextSharp.text.Font.BOLD);
                iTextSharp.text.Font Font18BOLD   = new iTextSharp.text.Font(bf, 18, iTextSharp.text.Font.BOLD);
                iTextSharp.text.Font Font27BOLD   = new iTextSharp.text.Font(bf, 27, iTextSharp.text.Font.BOLD);
                Document             document     = new Document(PageSize.A4, 10, 10, 80, 5); //left, rigt, top, botton
                PdfWriter.GetInstance(document, new FileStream("D:/Sinau/HasilPrint/OutputSSP " + dr["TransaksiBank"] + ".pdf", FileMode.Create));
                document.Open();

                string[] KeteranganArsip = { "UNTUK ARSIP WP", "UNTUK ARSIP KPP", "UNTUK DILAPORKAN WP KE KPP", "UNTUK BANK PERSEPSI / KANTOR POS & GIRO" };
                for (int i = 1; i < 5; i++)
                {
                    #region HeaderRegion
                    //........................Coloum Header...............
                    PdfPTable tablelayout = new PdfPTable(3);
                    tablelayout.TotalWidth  = 550f;
                    tablelayout.LockedWidth = true;
                    float[] widths = new float[] { 230f, 160f, 160f };
                    tablelayout.SetWidths(widths);
                    PdfPTable logo = new PdfPTable(4);
                    logo.DefaultCell.BorderColor = BaseColor.WHITE;
                    string url = "D:/Sinau/PDF/PDF/Image/p.jpg";
                    iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(new Uri(url));
                    jpg.ScaleToFit(200f, 200f);
                    iTextSharp.text.pdf.PdfPCell imgCell1 = new iTextSharp.text.pdf.PdfPCell();
                    imgCell1.AddElement(new Chunk(jpg, 0, 0));
                    imgCell1.PaddingTop   = 25f;
                    imgCell1.PaddingRight = 0f;
                    imgCell1.BorderColor  = BaseColor.WHITE;
                    logo.AddCell(imgCell1);
                    PdfPCell Depart = new PdfPCell(new Phrase("\nDEPARTEMEN KEUANGAN RI \nDIREKTORAT JENDRAL PAJAK \nKANTOR PELAYANAN PAJAK", Font10));
                    Depart.BorderColor = BaseColor.WHITE;
                    Depart.Colspan     = 3;
                    logo.AddCell(Depart);
                    tablelayout.AddCell(logo);

                    PdfPTable ssp = new PdfPTable(1);
                    ssp.DefaultCell.BorderColor = BaseColor.WHITE;
                    PdfPCell surat = new PdfPCell(new Phrase("\nSURAT SETORAN PAJAK", Font12BOLD));
                    surat.BorderColor         = BaseColor.WHITE;
                    surat.HorizontalAlignment = Element.ALIGN_CENTER;
                    ssp.AddCell(surat);
                    PdfPCell SSP = new PdfPCell(new Phrase("(SSP)\n\n", Font18BOLD));
                    SSP.BorderColor         = BaseColor.WHITE;
                    SSP.HorizontalAlignment = Element.ALIGN_CENTER;
                    ssp.AddCell(SSP);
                    tablelayout.AddCell(ssp);

                    PdfPTable hal = new PdfPTable(2);
                    hal.DefaultCell.BorderColor = BaseColor.WHITE;
                    PdfPCell lembar1 = new PdfPCell(new Phrase("\n\nLEMBAR", Font12));
                    lembar1.BorderColor = BaseColor.WHITE;
                    hal.AddCell(lembar1);

                    PdfPTable no = new PdfPTable(1);
                    no.TotalWidth = 20f;
                    PdfPCell nohal = new PdfPCell(new Phrase("" + i.ToString(), Font27BOLD));
                    nohal.BorderColor = BaseColor.WHITE;
                    no.AddCell(nohal);
                    hal.AddCell(no);

                    PdfPCell keterangan = new PdfPCell(new Phrase(KeteranganArsip[i - 1] + "\n", Font8));
                    keterangan.BorderColor = BaseColor.WHITE;
                    keterangan.Colspan     = 2;
                    hal.AddCell(keterangan);
                    tablelayout.AddCell(hal);
                    document.Add(tablelayout);

                    #endregion // end of Header

                    #region ColoumIdentitas
                    //================ColoumIdentitas=================
                    PdfPTable TIden = new PdfPTable(1);
                    TIden.TotalWidth  = 550f;
                    TIden.LockedWidth = true;
                    PdfPTable TNWPWP          = new PdfPTable(3);
                    float[]   widthsIdentitas = new float[] { 110f, 10f, 420f };
                    TNWPWP.SetWidths(widthsIdentitas);
                    TNWPWP.DefaultCell.BorderColor = BaseColor.WHITE;
                    TNWPWP.SpacingBefore           = 8f;
                    TNWPWP.SpacingAfter            = 10f;
                    TNWPWP.AddCell(new Phrase("   NPWP", Font10BOLD));

                    TNWPWP.AddCell(new Phrase(":", Font10BOLD));

                    PdfPTable kotakNPWP = new PdfPTable(27);
                    kotakNPWP.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
                    kotakNPWP.DefaultCell.VerticalAlignment   = Element.ALIGN_CENTER;

                    PdfPCell spasikotak = new PdfPCell(new Phrase(""));
                    spasikotak.BorderColor      = BaseColor.WHITE;
                    spasikotak.BorderWidthLeft  = 0f;
                    spasikotak.BorderWidthRight = 0f;

                    char[] charNPWP = { ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' };
                    if (Convert.ToString(dr["NPWP"]) != "")
                    {
                        charNPWP = (dr["NPWP"].ToString()).ToCharArray();
                    }
                    kotakNPWP.AddCell(new Phrase("" + charNPWP[0], Font10BOLD));
                    kotakNPWP.AddCell(new Phrase("" + charNPWP[1], Font10BOLD));
                    kotakNPWP.AddCell(spasikotak);
                    kotakNPWP.AddCell(new Phrase("" + charNPWP[2], Font10BOLD));
                    kotakNPWP.AddCell(new Phrase("" + charNPWP[3], Font10BOLD));
                    kotakNPWP.AddCell(new Phrase("" + charNPWP[4], Font10BOLD));
                    kotakNPWP.AddCell(spasikotak);
                    kotakNPWP.AddCell(new Phrase("" + charNPWP[5], Font10BOLD));
                    kotakNPWP.AddCell(new Phrase("" + charNPWP[6], Font10BOLD));
                    kotakNPWP.AddCell(new Phrase("" + charNPWP[7], Font10BOLD));
                    kotakNPWP.AddCell(spasikotak);
                    kotakNPWP.AddCell(new Phrase("" + charNPWP[8], Font10BOLD));
                    kotakNPWP.AddCell(spasikotak);
                    kotakNPWP.AddCell(new Phrase("" + charNPWP[9], Font10BOLD));
                    kotakNPWP.AddCell(new Phrase("" + charNPWP[10], Font10BOLD));
                    kotakNPWP.AddCell(new Phrase("" + charNPWP[11], Font10BOLD));
                    kotakNPWP.AddCell(spasikotak);
                    kotakNPWP.AddCell(new Phrase("" + charNPWP[12], Font10BOLD));
                    kotakNPWP.AddCell(new Phrase("" + charNPWP[13], Font10BOLD));
                    kotakNPWP.AddCell(new Phrase("" + charNPWP[14], Font10BOLD));
                    PdfPCell batas = new PdfPCell(new Phrase(""));
                    batas.Colspan         = 7;
                    batas.BorderColor     = BaseColor.WHITE;
                    batas.BorderWidthLeft = 0f;
                    kotakNPWP.AddCell(batas);

                    TNWPWP.AddCell(kotakNPWP);
                    //TNWPWP.AddCell(new Phrase(":", Font10));
                    PdfPCell alert = new PdfPCell(new Phrase("Diisi sesuai dengan Nomor Pokok Wajib Pajak yang dimiliki", Font8Italic));
                    alert.Colspan     = 3;
                    alert.BorderColor = BaseColor.WHITE;
                    TNWPWP.AddCell(alert);
                    TNWPWP.AddCell(new Phrase("   NAMA WP", Font10BOLD));
                    TNWPWP.AddCell(new Phrase(":", Font10BOLD));
                    TNWPWP.AddCell(new Phrase("" + dr["NamaWP"], Font10));
                    TNWPWP.AddCell(new Phrase("   ALAMAT WP", Font10BOLD));
                    TNWPWP.AddCell(new Phrase(":", Font10BOLD));
                    TNWPWP.AddCell(new Phrase("" + dr["AlamatWP"] + "\n" + dr["KotaWP"], Font10));

                    TIden.AddCell(TNWPWP);
                    document.Add(TIden);

                    #endregion // ColoumIdentitas

                    #region ColoumNOP
                    //================ColoumNOP=================
                    PdfPTable TNop = new PdfPTable(1);
                    TNop.TotalWidth  = 550f;
                    TNop.LockedWidth = true;
                    PdfPTable NOP = new PdfPTable(3);
                    NOP.SpacingAfter = 10f;
                    float[] widthsNOP = new float[] { 110f, 10f, 420f };
                    NOP.SetWidths(widthsNOP);
                    NOP.DefaultCell.BorderColor = BaseColor.WHITE;
                    NOP.AddCell(new Phrase("  NOP", Font10BOLD));
                    NOP.AddCell(new Phrase(":", Font10BOLD));
                    PdfPTable kotakNOP = new PdfPTable(27);
                    kotakNOP.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
                    kotakNOP.DefaultCell.VerticalAlignment   = Element.ALIGN_CENTER;

                    char[] charNOP = { ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' };
                    if (Convert.ToString(dr["NOP"]) != "")
                    {
                        charNOP = (dr["NOP"].ToString()).ToCharArray();
                    }
                    kotakNOP.AddCell(new Phrase("" + charNOP[0], Font10BOLD));
                    kotakNOP.AddCell(new Phrase("" + charNOP[1], Font10BOLD));
                    kotakNOP.AddCell(spasikotak);
                    kotakNOP.AddCell(new Phrase("" + charNOP[2], Font10BOLD));
                    kotakNOP.AddCell(new Phrase("" + charNOP[3], Font10BOLD));
                    kotakNOP.AddCell(spasikotak);
                    kotakNOP.AddCell(new Phrase("" + charNOP[4], Font10BOLD));
                    kotakNOP.AddCell(new Phrase("" + charNOP[5], Font10BOLD));
                    kotakNOP.AddCell(new Phrase("" + charNOP[6], Font10BOLD));
                    kotakNOP.AddCell(spasikotak);
                    kotakNOP.AddCell(new Phrase("" + charNOP[7], Font10BOLD));
                    kotakNOP.AddCell(new Phrase("" + charNOP[8], Font10BOLD));
                    kotakNOP.AddCell(new Phrase("" + charNOP[9], Font10BOLD));
                    kotakNOP.AddCell(spasikotak);
                    kotakNOP.AddCell(new Phrase("" + charNOP[10], Font10BOLD));
                    kotakNOP.AddCell(new Phrase("" + charNOP[11], Font10BOLD));
                    kotakNOP.AddCell(new Phrase("" + charNOP[12], Font10BOLD));
                    kotakNOP.AddCell(spasikotak);
                    kotakNOP.AddCell(new Phrase("" + charNOP[13], Font10BOLD));
                    kotakNOP.AddCell(new Phrase("" + charNOP[14], Font10BOLD));
                    kotakNOP.AddCell(new Phrase("" + charNOP[15], Font10BOLD));
                    kotakNOP.AddCell(new Phrase("" + charNOP[16], Font10BOLD));
                    kotakNOP.AddCell(spasikotak);
                    kotakNOP.AddCell(new Phrase("" + charNOP[17], Font10BOLD));
                    PdfPCell batasNOP = new PdfPCell(new Phrase(""));
                    batasNOP.Colspan         = 3;
                    batasNOP.BorderColor     = BaseColor.WHITE;
                    batasNOP.BorderWidthLeft = 0f;
                    kotakNOP.AddCell(batasNOP);
                    NOP.AddCell(kotakNOP);

                    PdfPCell AlertNop = new PdfPCell(new Phrase("Diisi sesuai dengan Nomor Objek Pajak", Font8Italic));
                    AlertNop.Colspan     = 3;
                    AlertNop.BorderColor = BaseColor.WHITE;
                    NOP.AddCell(AlertNop);
                    NOP.AddCell(new Phrase("  ALAMAT NOP", Font10BOLD));
                    NOP.AddCell(new Phrase(":", Font10BOLD));
                    NOP.AddCell(new Phrase("" + dr["AlamatNOP"], Font10));
                    TNop.AddCell(NOP);
                    document.Add(TNop);

                    #endregion //endColoumNOP

                    #region ColoumKode
                    //================ColoumKode=================
                    PdfPTable TKode = new PdfPTable(2);
                    TKode.TotalWidth = 550f;
                    float[] widthsTKode = new float[] { 250f, 300f };
                    TKode.SetWidths(widthsTKode);
                    TKode.LockedWidth               = true;
                    TKode.DefaultCell.PaddingTop    = 10f;
                    TKode.DefaultCell.PaddingBottom = 20f;
                    PdfPTable kode = new PdfPTable(2);
                    kode.DefaultCell.BorderColor = BaseColor.WHITE;
                    PdfPCell akun = new PdfPCell(new Phrase("Kode Akun Pajak", Font10BOLD));
                    akun.HorizontalAlignment = Element.ALIGN_CENTER;
                    akun.BorderColor         = BaseColor.WHITE;
                    kode.AddCell(akun);
                    PdfPCell jenis = new PdfPCell(new Phrase("Kode Jenis Setor", Font10BOLD));
                    jenis.HorizontalAlignment = Element.ALIGN_CENTER;
                    jenis.BorderColor         = BaseColor.WHITE;
                    kode.AddCell(jenis);
                    PdfPTable kotakKodeAkun = new PdfPTable(8);
                    kotakKodeAkun.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
                    kotakKodeAkun.DefaultCell.VerticalAlignment   = Element.ALIGN_CENTER;

                    char[] charKodeAkun = { ' ', ' ', ' ', ' ', ' ', ' ' };
                    if (Convert.ToString(dr["KodeAkunPajak"]) != "")
                    {
                        charKodeAkun = (dr["KodeAkunPajak"].ToString()).ToCharArray();
                    }
                    kotakKodeAkun.AddCell(spasikotak);
                    kotakKodeAkun.AddCell(new Phrase("" + charKodeAkun[0], Font10BOLD));
                    kotakKodeAkun.AddCell(new Phrase("" + charKodeAkun[1], Font10BOLD));
                    kotakKodeAkun.AddCell(new Phrase("" + charKodeAkun[2], Font10BOLD));
                    kotakKodeAkun.AddCell(new Phrase("" + charKodeAkun[3], Font10BOLD));
                    kotakKodeAkun.AddCell(new Phrase("" + charKodeAkun[4], Font10BOLD));
                    kotakKodeAkun.AddCell(new Phrase("" + charKodeAkun[5], Font10BOLD));
                    kotakKodeAkun.AddCell(batas);
                    kode.AddCell(kotakKodeAkun);

                    PdfPTable kotakKodeJenis = new PdfPTable(8);
                    kotakKodeJenis.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
                    kotakKodeJenis.DefaultCell.VerticalAlignment   = Element.ALIGN_CENTER;

                    kotakKodeJenis.AddCell(spasikotak);
                    kotakKodeJenis.AddCell(spasikotak);
                    kotakKodeJenis.AddCell(spasikotak);
                    char[] charKodeSetor = { ' ', ' ', ' ' };
                    if (Convert.ToString(dr["KodeJenisSetor"]) != "")
                    {
                        charKodeSetor = (dr["KodeJenisSetor"].ToString()).ToCharArray();
                    }
                    kotakKodeJenis.AddCell(new Phrase("" + charKodeSetor[0], Font10BOLD));
                    kotakKodeJenis.AddCell(new Phrase("" + charKodeSetor[1], Font10BOLD));
                    kotakKodeJenis.AddCell(new Phrase("" + charKodeSetor[2], Font10BOLD));
                    kotakKodeJenis.AddCell(batas);
                    kode.AddCell(kotakKodeJenis);

                    TKode.AddCell(kode);
                    TKode.AddCell(new Phrase("   Uraian Pembayaran SSP \n" + dr["UraianPembayaranSSP"], Font10BOLD));
                    document.Add(TKode);
                    #endregion //ColoumKode

                    #region ColoumMasaPajak
                    //================ColoumMasaPajak=================
                    PdfPTable TMasa = new PdfPTable(2);
                    TMasa.TotalWidth = 550f;
                    float[] widthsMasa = new float[] { 390f, 160f };
                    TMasa.SetWidths(widthsMasa);
                    TMasa.LockedWidth = true;
                    PdfPTable TBulan = new PdfPTable(12);
                    TBulan.TotalWidth  = 390f;
                    TBulan.LockedWidth = true;
                    PdfPCell masa = new PdfPCell(new Phrase("Masa Pajak", Font10BOLD));
                    masa.Colspan             = 12;
                    masa.BorderWidthTop      = 0f;
                    masa.BorderWidthLeft     = 0f;
                    masa.HorizontalAlignment = Element.ALIGN_CENTER;
                    masa.PaddingBottom       = 10f;
                    TBulan.AddCell(masa);
                    PdfPCell Jan = new PdfPCell(new Phrase("Jan", Font10));
                    TBulan.AddCell(Jan);
                    PdfPCell Feb = new PdfPCell(new Phrase("Feb", Font10));
                    TBulan.AddCell(Feb);
                    PdfPCell Mar = new PdfPCell(new Phrase("Mar", Font10));
                    TBulan.AddCell(Mar);
                    PdfPCell Apr = new PdfPCell(new Phrase("Apr", Font10));
                    TBulan.AddCell(Apr);
                    PdfPCell Mei = new PdfPCell(new Phrase("Mei", Font10));
                    TBulan.AddCell(Mei);
                    PdfPCell Jun = new PdfPCell(new Phrase("Jun", Font10));
                    TBulan.AddCell(Jun);
                    PdfPCell Jul = new PdfPCell(new Phrase("Jul", Font10));
                    TBulan.AddCell(Jul);
                    PdfPCell Ags = new PdfPCell(new Phrase("Ags", Font10));
                    TBulan.AddCell(Ags);
                    PdfPCell Sep = new PdfPCell(new Phrase("Sep", Font10));
                    TBulan.AddCell(Sep);
                    PdfPCell Okt = new PdfPCell(new Phrase("Okt", Font10));
                    TBulan.AddCell(Okt);
                    PdfPCell Nov = new PdfPCell(new Phrase("Nov", Font10));
                    TBulan.AddCell(Nov);
                    PdfPCell Des = new PdfPCell(new Phrase("Des", Font10));
                    TBulan.AddCell(Des);

                    int    Bulan = (Convert.ToInt32((Convert.ToDateTime(dr["MasaPajak"])).Month)) - 1;
                    string x     = "X";
                    for (int j = 0; j < 12; j++)
                    {
                        if (j == Bulan)
                        {
                            PdfPCell bln = new PdfPCell(new Phrase(x));
                            bln.BorderWidth         = 0f;
                            bln.HorizontalAlignment = Element.ALIGN_CENTER;
                            TBulan.AddCell(bln);
                        }
                        else
                        {
                            TBulan.AddCell("");
                        }
                    }

                    PdfPCell alertmasa = new PdfPCell(new Phrase("Beri tanda silang (X) pada kolom bulan, sesuai dengan pembayaran untuk masa yang berkenaan", Font8));
                    alertmasa.Colspan             = 12;
                    alertmasa.HorizontalAlignment = Element.ALIGN_CENTER;
                    alertmasa.BorderWidthBottom   = 0f;
                    alertmasa.BorderWidthLeft     = 0f;
                    TBulan.AddCell(alertmasa);
                    TMasa.AddCell(TBulan);

                    PdfPTable Ttahun = new PdfPTable(1);
                    Ttahun.DefaultCell.BorderColor = BaseColor.WHITE;
                    PdfPCell tahun = new PdfPCell(new Phrase("          Tahun Pajak", Font10BOLD));
                    tahun.BorderColor   = BaseColor.WHITE;
                    tahun.PaddingBottom = 10f;
                    Ttahun.AddCell(tahun);
                    PdfPTable kotakTahunPajak = new PdfPTable(8);
                    kotakTahunPajak.TotalWidth = 410f;
                    kotakTahunPajak.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
                    kotakTahunPajak.DefaultCell.VerticalAlignment   = Element.ALIGN_CENTER;
                    kotakTahunPajak.AddCell(spasikotak);
                    char[] charTahunPajak = { ' ', ' ', ' ', ' ' };
                    if (Convert.ToString(dr["MasaPajak"]) != "")
                    {
                        DateTime thun = Convert.ToDateTime(dr["MasaPajak"]);
                        charTahunPajak = (thun.Year.ToString()).ToCharArray();
                    }
                    kotakTahunPajak.AddCell(new Phrase("" + charTahunPajak[0], Font10));
                    kotakTahunPajak.AddCell(new Phrase("" + charTahunPajak[1], Font10));
                    kotakTahunPajak.AddCell(new Phrase("" + charTahunPajak[2], Font10));
                    kotakTahunPajak.AddCell(new Phrase("" + charTahunPajak[3], Font10));
                    kotakTahunPajak.AddCell(batas);

                    Ttahun.AddCell(kotakTahunPajak);
                    Ttahun.AddCell(new Phrase("     Diisi tahun terutangnya pajak", Font8Italic));
                    TMasa.AddCell(Ttahun);

                    document.Add(TMasa);
                    #endregion //ColoumMasaPajak

                    #region ColoumKetetapan
                    //================ColoumKetetapan=================
                    PdfPTable TableTetap = new PdfPTable(1);
                    TableTetap.TotalWidth  = 550f;
                    TableTetap.LockedWidth = true;
                    PdfPTable TTetap      = new PdfPTable(3);
                    float[]   widthsTetap = new float[] { 100f, 10f, 440f };
                    TTetap.SetWidths(widthsTetap);
                    TTetap.TotalWidth              = 550f;
                    TTetap.LockedWidth             = true;
                    TTetap.DefaultCell.PaddingTop  = 8f;
                    TTetap.DefaultCell.BorderWidth = 0f;
                    TTetap.AddCell(new Phrase("Nomor Ketetapan", Font10));
                    TTetap.AddCell(new Phrase(":", Font9));

                    PdfPTable kotakKetetapan = new PdfPTable(26);
                    kotakKetetapan.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
                    kotakKetetapan.DefaultCell.VerticalAlignment   = Element.ALIGN_CENTER;

                    char[] charNoRefrensi = { ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' };
                    if (Convert.ToString(dr["NomorRefrensi"]) != "")
                    {
                        charNoRefrensi = (dr["NomorRefrensi"].ToString()).ToCharArray();
                    }
                    kotakKetetapan.AddCell(new Phrase("" + charNoRefrensi[0], Font10BOLD));
                    kotakKetetapan.AddCell(new Phrase("" + charNoRefrensi[1], Font10BOLD));
                    kotakKetetapan.AddCell(new Phrase("" + charNoRefrensi[2], Font10BOLD));
                    kotakKetetapan.AddCell(new Phrase("" + charNoRefrensi[3], Font10BOLD));
                    kotakKetetapan.AddCell(new Phrase("" + charNoRefrensi[4], Font10BOLD));
                    kotakKetetapan.AddCell(spasikotak);
                    kotakKetetapan.AddCell(new Phrase("" + charNoRefrensi[5], Font10BOLD));
                    kotakKetetapan.AddCell(new Phrase("" + charNoRefrensi[6], Font10BOLD));
                    kotakKetetapan.AddCell(new Phrase("" + charNoRefrensi[7], Font10BOLD));
                    kotakKetetapan.AddCell(spasikotak);
                    kotakKetetapan.AddCell(new Phrase("" + charNoRefrensi[8], Font10BOLD));
                    kotakKetetapan.AddCell(new Phrase("" + charNoRefrensi[9], Font10BOLD));
                    kotakKetetapan.AddCell(spasikotak);
                    kotakKetetapan.AddCell(new Phrase("" + charNoRefrensi[10], Font10BOLD));
                    kotakKetetapan.AddCell(new Phrase("" + charNoRefrensi[11], Font10BOLD));
                    kotakKetetapan.AddCell(new Phrase("" + charNoRefrensi[12], Font10BOLD));
                    kotakKetetapan.AddCell(spasikotak);
                    kotakKetetapan.AddCell(new Phrase("" + charNoRefrensi[13], Font10BOLD));
                    kotakKetetapan.AddCell(new Phrase("" + charNoRefrensi[14], Font10BOLD));
                    kotakKetetapan.AddCell(batas);
                    TTetap.AddCell(kotakKetetapan);

                    PdfPCell AlertTetap = new PdfPCell(new Phrase("Diisi sesuai Nomor Ketetapan : STP, SKPKB, SKPKBT", Font8Italic));
                    AlertTetap.BorderWidth   = 0f;
                    AlertTetap.PaddingBottom = 10f;
                    AlertTetap.Colspan       = 3;
                    AlertTetap.PaddingLeft   = 10f;
                    TTetap.AddCell(AlertTetap);

                    TableTetap.AddCell(TTetap);
                    document.Add(TableTetap);
                    #endregion //ColoumKetetapan

                    #region ColoumPemabayaran
                    //================ColoumPemabayaran=================
                    PdfPTable TBayar = new PdfPTable(1);
                    TBayar.TotalWidth  = 550f;
                    TBayar.LockedWidth = true;
                    TBayar.DefaultCell.PaddingBottom = 30f;
                    TBayar.DefaultCell.PaddingLeft   = 15f;
                    PdfPTable TBayar1 = new PdfPTable(4);
                    TBayar1.TotalWidth  = 550f;
                    TBayar1.LockedWidth = true;
                    float[] widthsBayar = new float[] { 110f, 10f, 300f, 130f };
                    TBayar1.SetWidths(widthsBayar);
                    TBayar1.DefaultCell.BorderWidth = 0f;
                    TBayar1.AddCell(new Phrase("Jumlah Pembayaran", Font10BOLD));
                    TBayar1.AddCell(new Phrase(":", Font10BOLD));
                    TBayar1.AddCell(new Phrase("" + String.Format(CultureInfo.CreateSpecificCulture("id-id"), "Rp. {0:N0}", dr["JumlahSetoran"]), Font10BOLD));
                    TBayar1.AddCell(new Phrase("Diisi dengan rupiah penuh", Font8));
                    TBayar1.AddCell(new Phrase("Terbilang", Font10BOLD));
                    TBayar1.AddCell(new Phrase(":", Font10BOLD));
                    PdfPCell terbilang = new PdfPCell(new Phrase("" + Terbilang(Convert.ToInt32(dr["JumlahSetoran"])), Font10Italic));
                    terbilang.Colspan     = 2;
                    terbilang.BorderWidth = 0f;
                    TBayar1.AddCell(terbilang);
                    TBayar.AddCell(TBayar1);
                    document.Add(TBayar);
                    #endregion //ColoumPemabayaran

                    #region ColoumTerima
                    //===============ColoumTerima===========================
                    PdfPTable Tterima = new PdfPTable(2);
                    Tterima.TotalWidth  = 550f;
                    Tterima.LockedWidth = true;
                    PdfPTable Pkantor = new PdfPTable(1);
                    Pkantor.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
                    Pkantor.DefaultCell.BorderColor         = BaseColor.WHITE;
                    Pkantor.AddCell(new Phrase("Diterima oleh Kantor Penerimaan Pembayaran", Font10BOLD));
                    Pkantor.AddCell(new Phrase("Tanggal " + Convert.ToDateTime(dr["TanggalBayar"].ToString()).ToString("dd-MM-yyyy"), Font10));
                    Pkantor.AddCell(new Phrase("Cap dan tanda tangan", Font8Italic));
                    Pkantor.AddCell("\n\n\n\n");
                    Pkantor.AddCell(new Phrase("Nama Jelas : Standard Chartered Bank\n\n", Font11));
                    Tterima.AddCell(Pkantor);

                    PdfPTable Penyetor = new PdfPTable(1);
                    Penyetor.DefaultCell.BorderColor         = BaseColor.WHITE;
                    Penyetor.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
                    Penyetor.AddCell(new Phrase("Wajib pajak/Penyetor", Font10BOLD));
                    Penyetor.AddCell(new Phrase("" + (dr["KotaWP"]).ToString().Trim() + ", Tanggal " + Convert.ToDateTime(dr["TanggalBayar"].ToString()).ToString("dd-MM-yyyy"), Font10));
                    Penyetor.AddCell(new Phrase("Cap dan tanda tangan", Font8Italic));
                    Penyetor.AddCell("\n\n\n\n");
                    Penyetor.AddCell(new Phrase("Nama Jelas " + dr["NamaWP"] + "\n\n", Font11));
                    Tterima.AddCell(Penyetor);

                    document.Add(Tterima);
                    #endregion //ColoumTerima

                    #region ColoumTerimakasih
                    //=======================ColoumTerimakasih=========================
                    PdfPTable Tterimakasih = new PdfPTable(1);
                    Tterimakasih.TotalWidth  = 550f;
                    Tterimakasih.LockedWidth = true;
                    PdfPTable Terimakasih       = new PdfPTable(3);
                    float[]   widthsTerimakasih = new float[] { 70f, 10f, 470f };
                    Terimakasih.SetWidths(widthsTerimakasih);
                    Terimakasih.DefaultCell.BorderColor = BaseColor.WHITE;
                    PdfPCell terima = new PdfPCell(new Phrase("Terima Kasih Telah Membayar Pajak - Pajak Untuk Pembangunan Bangsa", Font9));
                    terima.Colspan             = 3;
                    terima.HorizontalAlignment = Element.ALIGN_CENTER;
                    terima.BorderColor         = BaseColor.WHITE;
                    Terimakasih.AddCell(terima);
                    PdfPCell ruang = new PdfPCell(new Phrase("Ruang Validasi Kantor Penerimaan Pembayaran", Font9));
                    ruang.Colspan             = 3;
                    ruang.HorizontalAlignment = Element.ALIGN_CENTER;
                    ruang.BorderColor         = BaseColor.WHITE;
                    Terimakasih.AddCell(ruang);
                    Terimakasih.AddCell(new Phrase("  Tanggal", Font9));
                    Terimakasih.AddCell(new Phrase(":", Font9));
                    Terimakasih.AddCell(new Phrase("" + Convert.ToDateTime(dr["TanggalBayar"].ToString()).ToString("dd-MM-yyyy HH:mm"), Font9));
                    Terimakasih.AddCell(new Phrase("  Cabang", Font9));
                    Terimakasih.AddCell(new Phrase(":", Font9));
                    Terimakasih.AddCell(new Phrase("", Font9));
                    Terimakasih.AddCell(new Phrase("  Terminal", Font9));
                    Terimakasih.AddCell(new Phrase(":", Font9));
                    Terimakasih.AddCell(new Phrase("", Font9));
                    Terimakasih.AddCell(new Phrase("  Tx No.", Font9));
                    Terimakasih.AddCell(new Phrase(":", Font9));
                    Terimakasih.AddCell(new Phrase("", Font9));
                    Terimakasih.AddCell(new Phrase("  NTPN", Font9));
                    Terimakasih.AddCell(new Phrase(":", Font9));
                    Terimakasih.AddCell(new Phrase("", Font9));
                    PdfPCell spasibwah = new PdfPCell(new Phrase("\n\n\n"));
                    spasibwah.Colspan     = 3;
                    spasibwah.BorderWidth = 0f;
                    Terimakasih.AddCell(spasibwah);
                    Tterimakasih.AddCell(Terimakasih);
                    document.Add(Tterimakasih);
                    #endregion //ColoumTerimakasih
                }
                document.Close();
            }
            catch (Exception ex)
            {
            }
        }
Ejemplo n.º 25
0
        public void Print()
        {
            //logger.Info("Inicio Imprimir Resultados");
            List <DataTable> resultsTable = createResultsTables(stages);

            //var fileName = simulationPath + "\\resultados.pdf";
            System.IO.FileStream fs       = new System.IO.FileStream(simulationPath + "\\" + fileName, FileMode.Create, FileAccess.Write, FileShare.None);
            Document             document = new Document();

            document.SetPageSize(iTextSharp.text.PageSize.A4);
            PdfWriter writer = PdfWriter.GetInstance(document, fs);

            // calling PDFFooter class to Include in document
            writer.PageEvent = new PDFFooter();

            document.Open();

            //Report Header
            BaseFont bfntHead = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Font     fntHead  = new Font(bfntHead, 16, 1, BaseColor.BLACK);

            iTextSharp.text.Paragraph prgHeading = new iTextSharp.text.Paragraph();
            prgHeading.Alignment = Element.ALIGN_LEFT;
            prgHeading.Add(new Chunk("Análisis de Sensibilidad", fntHead));
            document.Add(prgHeading);

            //Formato de textos
            BaseFont bfntStage       = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Font     fntStage        = new Font(bfntStage, 14, 1, BaseColor.BLACK);
            BaseFont btnColumnHeader = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Font     fntColumnHeader = new Font(btnColumnHeader, 14, 1, BaseColor.WHITE);

            //CARGO LAS TABLAS SEGUN LA CANTIDAD DE STAGES
            foreach (var tbl in resultsTable)
            {
                if (tbl.TableName != "")
                {
                    //LINEA
                    iTextSharp.text.Paragraph p = new iTextSharp.text.Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100, BaseColor.BLACK, Element.ALIGN_LEFT, 0)));
                    document.Add(p);
                    document.Add(new Chunk("\n", fntHead));
                    //NOMBRE DEL STAGE
                    iTextSharp.text.Paragraph stageHeading = new iTextSharp.text.Paragraph();
                    stageHeading.Alignment = Element.ALIGN_CENTER;
                    stageHeading.Add(new Chunk(tbl.TableName, fntStage));
                    document.Add(stageHeading);
                }
                document.Add(new Chunk("\n", fntStage));
                //ESCRIBO TABLA
                PdfPTable table = new iTextSharp.text.pdf.PdfPTable(tbl.Columns.Count);
                //HEADER DE TABLA
                for (int i = 0; i < tbl.Columns.Count; i++)
                {
                    PdfPCell cell = new iTextSharp.text.pdf.PdfPCell();
                    cell.BackgroundColor = new BaseColor(67, 142, 185);
                    cell.AddElement(new Chunk(tbl.Columns[i].ColumnName, fntColumnHeader));
                    table.AddCell(cell);
                }

                //DATOS TABLA
                for (int i = 0; i < tbl.Rows.Count; i++)
                {
                    for (int j = 0; j < tbl.Columns.Count; j++)
                    {
                        table.AddCell(tbl.Rows[i][j].ToString());
                    }
                }

                document.Add(table);
            }
            //LINEA
            iTextSharp.text.Paragraph line = new iTextSharp.text.Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100, BaseColor.BLACK, Element.ALIGN_LEFT, 0)));
            document.Add(line);
            document.Add(new Chunk("\n", fntHead));
            //Tiempo total
            BaseFont bfntTime = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Font     fntTime  = new Font(bfntTime, 14, 1, BaseColor.BLACK);

            iTextSharp.text.Paragraph prgTime = new iTextSharp.text.Paragraph();
            prgTime.Alignment = Element.ALIGN_LEFT;
            prgTime.Add(new Chunk("Tiempo total de ejecución: " + simulationTotalTime.ToString(@"hh\:mm\:ss"), fntTime));
            document.Add(prgTime);

            document.Close();
            writer.Close();
            fs.Close();
            //logger.Info("Fin Imprimir Resultados");
        }
Ejemplo n.º 26
0
        public static void Export(string file, Dictionary<TestMethod, StepFrame> frames, int flowCount, long recordCount, float randomness, ComputerConfiguration computerInfo, ReportType type)
        {
            var doc = new Document(PageSize.A4);

            if (File.Exists(file))
                File.Delete(file);

            var fileStream = new FileStream(file, FileMode.OpenOrCreate);
            PdfWriter.GetInstance(doc, fileStream);
            doc.Open();

            // Add header page.
            PdfPTable firstPageTable = new PdfPTable(1);
            firstPageTable.WidthPercentage = 100;

            PdfPCell title = new PdfPCell();
            title.VerticalAlignment = Element.ALIGN_MIDDLE;
            title.HorizontalAlignment = Element.ALIGN_CENTER;
            title.MinimumHeight = doc.PageSize.Height - (doc.BottomMargin + doc.TopMargin);
            title.AddElement(Image.GetInstance((System.Drawing.Image)DatabaseBenchmark.Properties.Resources.logo_01, Color.WHITE));

            firstPageTable.AddCell(title);
            doc.Add(firstPageTable);

            int chapterCount = 1;
            Font chapterFont = new Font(Font.TIMES_ROMAN, 16f, Font.TIMES_ROMAN, new Color(System.Drawing.Color.CornflowerBlue));

            Chapter benchamrkConfiguration = new Chapter(new Paragraph("Benchmark parameters.", chapterFont), chapterCount++);
            benchamrkConfiguration.Add(new Chunk("\n"));

            ExportTestSettings(benchamrkConfiguration, chapterFont, flowCount, recordCount, randomness);
            ExportComputerSpecification(benchamrkConfiguration, chapterFont, computerInfo);

            doc.Add(benchamrkConfiguration);

            foreach (var fr in frames)
            {
                StepFrame frame = fr.Value;
                List<BarChart> barCharts;

                if (type == ReportType.Summary)
                    barCharts = frame.GetSummaryBarCharts();
                else
                    barCharts = frame.GetAllBarCharts();

                string chapterTitle = fr.Key == TestMethod.SecondaryRead ? "Secondary read" : fr.Key.ToString();
                Chapter chapter = new Chapter(new Paragraph(chapterTitle, chapterFont), chapterCount++);
                chapter.Add(new Chunk("\n"));

                for (int i = 0; i < barCharts.Count; i++)
                {
                    Image image = Image.GetInstance(barCharts[i].ConvertToByteArray());
                    image.Alignment = Element.ALIGN_CENTER;

                    if (type == ReportType.Summary)
                        image.ScaleToFit(doc.PageSize.Width - 20, 271);
                    else
                        image.ScalePercent(100);

                    chapter.Add(image);
                }

                if (type == ReportType.Detailed)
                {
                    PdfPTable table = new PdfPTable(1);
                    table.WidthPercentage = 100;

                    AddCellToTable(table, "Average Speed:", frame.lineChartAverageSpeed.ConvertToByteArray);
                    AddCellToTable(table, "Moment Speed:", frame.lineChartMomentSpeed.ConvertToByteArray);
                    AddCellToTable(table, "Average Memory:", frame.lineChartMomentMemory.ConvertToByteArray);
                    //AddCellToTable(table, "Average CPU:", frame.lineChartAverageCPU.ConvertToByteArray);
                    //AddCellToTable(table, "Average I/O:", frame.lineChartAverageIO.ConvertToByteArray);

                    chapter.Add(table);
                }

                doc.Add(chapter);
            }

            doc.Close();

            foreach (var item in frames)
                item.Value.ResetColumnStyle();
        }
Ejemplo n.º 27
0
        private static void AddCellToTable(PdfPTable table, string text, Func<byte[]> converter)
        {
            Image image = Image.GetInstance(converter());
            PdfPCell cell = new PdfPCell();

            cell.AddElement(new Paragraph(text));
            cell.AddElement(new Chunk("\n"));
            cell.AddElement(image);

            table.AddCell(cell);
        }
        private PdfPCell userHelpingDetails(UserShows userShow)
        {
            User currentUser = new User(userShow.Userid);
            Shows show = new Shows(userShow.ShowID);

            PdfPCell panelCell = new PdfPCell();
            panelCell.BorderWidth = 1;
            panelCell.Padding = 4;

            PdfPTable panelTable = new PdfPTable(new float[] { 150, 150, 400});
            panelCell.AddElement(panelTable);

            var cell = new PdfPCell(new Phrase(new Chunk("Helper Details", headerFont)));
            cell.BorderWidth = 0;
            cell.Colspan = 3;
            cell.PaddingBottom = 10;
            panelTable.AddCell(cell);

            cell = new PdfPCell(new Phrase(new Chunk("Help Date", judgeFont)));
            cell.BorderWidth = 0;
            panelTable.AddCell(cell);

            cell = new PdfPCell(new Phrase(new Chunk("Ring No", judgeFont)));
            cell.BorderWidth = 0;
            panelTable.AddCell(cell);

            cell = new PdfPCell(new Phrase(new Chunk("Job", judgeFont))) {BorderWidth = 0};
            panelTable.AddCell(cell);

            var helpers = Business.Helpers.HelperForShow(userShow.ShowID, userShow.Userid);
            if (helpers.Any() && helpers.FirstOrDefault().RingNo > -1)
            {
                foreach(var h in helpers)
                {
                    cell = new PdfPCell(new Phrase(new Chunk($"{h.HelpDate:ddd dd MMM}", judgeFont))) {BorderWidth = 0};
                    panelTable.AddCell(cell);

                    cell = new PdfPCell(new Phrase(new Chunk($"{h.RingNo}", judgeFont))) {BorderWidth = 0};
                    panelTable.AddCell(cell);

                    cell = new PdfPCell(new Phrase(new Chunk($"{h.JobDetails}", judgeFont))) {BorderWidth = 0};
                    panelTable.AddCell(cell);
                }
            }
            else
            {
                panelCell = new PdfPCell();
                panelCell.BorderWidth = 0;
            }

            return panelCell;
        }
        /**
        * Signals that an <CODE>Element</CODE> was added to the <CODE>Document</CODE>.
        *
        * @param element the element to add
        * @return <CODE>true</CODE> if the element was added, <CODE>false</CODE> if not.
        * @throws DocumentException when a document isn't open yet, or has been closed
        */
        public override bool Add(IElement element) {
            if (writer != null && writer.IsPaused()) {
                return false;
            }
            if (element.Type != Element.DIV) {
                FlushFloatingElements();
            }
            switch (element.Type) {
                
                // Information (headers)
                case Element.HEADER:
                    info.Addkey(((Meta)element).Name, ((Meta)element).Content);
                    break;
                case Element.TITLE:
                    info.AddTitle(((Meta)element).Content);
                    break;
                case Element.SUBJECT:
                    info.AddSubject(((Meta)element).Content);
                    break;
                case Element.KEYWORDS:
                    info.AddKeywords(((Meta)element).Content);
                    break;
                case Element.AUTHOR:
                    info.AddAuthor(((Meta)element).Content);
                    break;
                case Element.CREATOR:
                    info.AddCreator(((Meta)element).Content);
                    break;
                case Element.LANGUAGE:
                    SetLanguage(((Meta)element).Content);
                    break;
                case Element.PRODUCER:
                    // you can not change the name of the producer
                    info.AddProducer();
                    break;
                case Element.CREATIONDATE:
                    // you can not set the creation date, only reset it
                    info.AddCreationDate();
                    break;
                    
                    // content (text)
                case Element.CHUNK: {
                    // if there isn't a current line available, we make one
                    if (line == null) {
                        CarriageReturn();
                    }
                    
                    // we cast the element to a chunk
                    PdfChunk chunk = new PdfChunk((Chunk) element, anchorAction, tabSettings);
                    // we try to add the chunk to the line, until we succeed
                    {
                        PdfChunk overflow;
                        while ((overflow = line.Add(chunk)) != null) {
                            CarriageReturn();
                            bool newlineSplit = chunk.IsNewlineSplit();
                            chunk = overflow;
                            if (!newlineSplit)
                                chunk.TrimFirstSpace();
                        }
                    }
                    pageEmpty = false;
                    if (chunk.IsAttribute(Chunk.NEWPAGE)) {
                        NewPage();
                    }
                    break;
                }
                case Element.ANCHOR: {
                    Anchor anchor = (Anchor) element;
                    String url = anchor.Reference;
                    leading = anchor.Leading;
                    PushLeading();
                    if (url != null) {
                        anchorAction = new PdfAction(url);
                    }
                    
                    // we process the element
                    element.Process(this);
                    anchorAction = null;
                    PopLeading();
                    break;
                }
                case Element.ANNOTATION: {
                    if (line == null) {
                        CarriageReturn();
                    }
                    Annotation annot = (Annotation) element;
                    Rectangle rect = new Rectangle(0, 0);
                    if (line != null)
                        rect = new Rectangle(annot.GetLlx(IndentRight - line.WidthLeft), annot.GetUry(IndentTop - currentHeight - 20), annot.GetUrx(IndentRight - line.WidthLeft + 20), annot.GetLly(IndentTop - currentHeight));
                    PdfAnnotation an = PdfAnnotationsImp.ConvertAnnotation(writer, annot, rect);
                    annotationsImp.AddPlainAnnotation(an);
                    pageEmpty = false;
                    break;
                }
                case Element.PHRASE: {
                    TabSettings backupTabSettings = tabSettings;
                    if (((Phrase)element).TabSettings != null)
                        tabSettings = ((Phrase)element).TabSettings;

                    // we cast the element to a phrase and set the leading of the document
                    leading = ((Phrase) element).TotalLeading;
                    PushLeading();
                    // we process the element
                    element.Process(this);
                    tabSettings = backupTabSettings;
                    PopLeading();
                    break;
                }
                case Element.PARAGRAPH: {
                    TabSettings backupTabSettings = tabSettings;
                    if (((Phrase)element).TabSettings != null)
                        tabSettings = ((Phrase)element).TabSettings;

                    // we cast the element to a paragraph
                    Paragraph paragraph = (Paragraph) element;
                    if (IsTagged(writer))
                    {
                        FlushLines();
                        text.OpenMCBlock(paragraph);
                    }
                    AddSpacing(paragraph.SpacingBefore, leading, paragraph.Font);
                    
                    // we adjust the parameters of the document
                    alignment = paragraph.Alignment;
                    leading = paragraph.TotalLeading;
                    PushLeading();
                    
                    CarriageReturn();
                    // we don't want to make orphans/widows
                    if (currentHeight + line.Height + leading > IndentTop - IndentBottom) {
                        NewPage();
                    }

                    indentation.indentLeft += paragraph.IndentationLeft;
                    indentation.indentRight += paragraph.IndentationRight;
                    
                    CarriageReturn();

                    IPdfPageEvent pageEvent = writer.PageEvent;
                    if (pageEvent != null && !isSectionTitle)
                        pageEvent.OnParagraph(writer, this, IndentTop - currentHeight);
                    
                    // if a paragraph has to be kept together, we wrap it in a table object
                    if (paragraph.KeepTogether) {
                        CarriageReturn();
                        PdfPTable table = new PdfPTable(1);
                        table.KeepTogether = paragraph.KeepTogether;
                        table.WidthPercentage = 100f;
                        PdfPCell cell = new PdfPCell();
                        cell.AddElement(paragraph);
                        cell.Border = Rectangle.NO_BORDER;
                        cell.Padding = 0;
                        table.AddCell(cell);
                        indentation.indentLeft -= paragraph.IndentationLeft;
                        indentation.indentRight -= paragraph.IndentationRight;
                        this.Add(table);
                        indentation.indentLeft += paragraph.IndentationLeft;
                        indentation.indentRight += paragraph.IndentationRight;
                    }
                    else {
                        line.SetExtraIndent(paragraph.FirstLineIndent);
                        element.Process(this);
                        CarriageReturn();
                        AddSpacing(paragraph.SpacingAfter, paragraph.TotalLeading, paragraph.Font);
                    }
                    
                    if (pageEvent != null && !isSectionTitle)
                        pageEvent.OnParagraphEnd(writer, this, IndentTop - currentHeight);
                    
                    alignment = Element.ALIGN_LEFT;
                    indentation.indentLeft -= paragraph.IndentationLeft;
                    indentation.indentRight -= paragraph.IndentationRight;
                    CarriageReturn();
                    tabSettings = backupTabSettings;
                    PopLeading();
                    if (IsTagged(writer))
                    {
                        FlushLines();
                        text.CloseMCBlock(paragraph);
                    }
                    break;
                }
                case Element.SECTION:
                case Element.CHAPTER: {
                    // Chapters and Sections only differ in their constructor
                    // so we cast both to a Section
                    Section section = (Section) element;
                    IPdfPageEvent pageEvent = writer.PageEvent;
                    
                    bool hasTitle = section.NotAddedYet && section.Title != null;
                    
                    // if the section is a chapter, we begin a new page
                    if (section.TriggerNewPage) {
                        NewPage();
                    }

                    if (hasTitle) {
                        float fith = IndentTop - currentHeight;
                        int rotation = pageSize.Rotation;
                        if (rotation == 90 || rotation == 180)
                            fith = pageSize.Height - fith;
                        PdfDestination destination = new PdfDestination(PdfDestination.FITH, fith);
                        while (currentOutline.Level >= section.Depth) {
                            currentOutline = currentOutline.Parent;
                        }
                        PdfOutline outline = new PdfOutline(currentOutline, destination, section.GetBookmarkTitle(), section.BookmarkOpen);
                        currentOutline = outline;
                    }
                    
                    // some values are set
                    CarriageReturn();
                    indentation.sectionIndentLeft += section.IndentationLeft;
                    indentation.sectionIndentRight += section.IndentationRight;                    
                    if (section.NotAddedYet && pageEvent != null)
                        if (element.Type == Element.CHAPTER)
                            pageEvent.OnChapter(writer, this, IndentTop - currentHeight, section.Title);
                        else
                            pageEvent.OnSection(writer, this, IndentTop - currentHeight, section.Depth, section.Title);
                    
                    // the title of the section (if any has to be printed)
                    if (hasTitle) {
                        isSectionTitle = true;
                        Add(section.Title);
                        isSectionTitle = false;
                    }
                    indentation.sectionIndentLeft += section.Indentation;
                    // we process the section
                    element.Process(this);
                    // some parameters are set back to normal again
                    indentation.sectionIndentLeft -= (section.IndentationLeft + section.Indentation);
                    indentation.sectionIndentRight -= section.IndentationRight;
                    
                    if (section.ElementComplete && pageEvent != null)
                        if (element.Type == Element.CHAPTER)
                            pageEvent.OnChapterEnd(writer, this, IndentTop - currentHeight);
                        else
                            pageEvent.OnSectionEnd(writer, this, IndentTop - currentHeight);
                    
                    break;
                }
                case Element.LIST: {
                    // we cast the element to a List
                    List list = (List) element;
                    if (IsTagged(writer))
                    {
                        FlushLines();
                        text.OpenMCBlock(list);
                    }
                    if (list.Alignindent) {
                        list.NormalizeIndentation();
                    }
                    // we adjust the document
                    indentation.listIndentLeft += list.IndentationLeft;
                    indentation.indentRight += list.IndentationRight;
                    // we process the items in the list
                    element.Process(this);
                    // some parameters are set back to normal again
                    indentation.listIndentLeft -= list.IndentationLeft;
                    indentation.indentRight -= list.IndentationRight;
                    CarriageReturn();
                    if (IsTagged(writer))
                    {
                        FlushLines();
                        text.CloseMCBlock(list);
                    }
                    break;
                }
                case Element.LISTITEM: {
                    // we cast the element to a ListItem
                    ListItem listItem = (ListItem) element;
                    if (IsTagged(writer)) {
                        FlushLines();
                        text.OpenMCBlock(listItem);
                    }
                    AddSpacing(listItem.SpacingBefore, leading, listItem.Font);
                    
                    // we adjust the document
                    alignment = listItem.Alignment;
                    indentation.listIndentLeft += listItem.IndentationLeft;
                    indentation.indentRight += listItem.IndentationRight;
                    leading = listItem.TotalLeading;
                    PushLeading();
                    CarriageReturn();
                    // we prepare the current line to be able to show us the listsymbol
                    line.ListItem = listItem;
                    // we process the item
                    element.Process(this);

                    AddSpacing(listItem.SpacingAfter, listItem.TotalLeading, listItem.Font);
                    
                    // if the last line is justified, it should be aligned to the left
                    if (line.HasToBeJustified()) {
                        line.ResetAlignment();
                    }
                    // some parameters are set back to normal again
                    CarriageReturn();
                    indentation.listIndentLeft -= listItem.IndentationLeft;
                    indentation.indentRight -= listItem.IndentationRight;
                    PopLeading();
                    if (IsTagged(writer))
                    {
                        FlushLines();
                        text.CloseMCBlock(listItem.ListBody);
                        text.CloseMCBlock(listItem);
                    }
                    break;
                }
                case Element.RECTANGLE: {
                    Rectangle rectangle = (Rectangle) element;
                    graphics.Rectangle(rectangle);
                    pageEmpty = false;
                    break;
                }
                case Element.PTABLE: {
                    PdfPTable ptable = (PdfPTable)element;
                    if (ptable.Size <= ptable.HeaderRows)
                        break; //nothing to do

                    // before every table, we add a new line and flush all lines
                    EnsureNewLine();
                    FlushLines();
                    
                    AddPTable(ptable);
                    pageEmpty = false;
                    NewLine();
                    break;
                }
                case Element.JPEG:
                case Element.JPEG2000:
                case Element.JBIG2:
                case Element.IMGRAW:
                case Element.IMGTEMPLATE: {
                    //carriageReturn(); suggestion by Marc Campforts
                    if(IsTagged(writer)) {
                        FlushLines();
                        text.OpenMCBlock((Image)element);
                    }
                    Add((Image)element);
                    if(IsTagged(writer)) {
                        FlushLines();
                        text.CloseMCBlock((Image)element);
                    }
                    break;
                }
                case Element.YMARK: {
                    IDrawInterface zh = (IDrawInterface)element;
                    zh.Draw(graphics, IndentLeft, IndentBottom, IndentRight, IndentTop, IndentTop - currentHeight - (leadingStack.Count > 0 ? leading : 0));
                    pageEmpty = false;
                    break;
                }
                case Element.MARKED: {
                    MarkedObject mo;
                    if (element is MarkedSection) {
                        mo = ((MarkedSection)element).Title;
                        if (mo != null) {
                            mo.Process(this);
                        }
                    }
                    mo = (MarkedObject)element;
                    mo.Process(this);
                    break;
                }
                case Element.WRITABLE_DIRECT:
                    if (null != writer) {
                        ((IWriterOperation)element).Write(writer, this);
                    }
                    break;
                case Element.DIV:
                    EnsureNewLine();
                    FlushLines();
                    AddDiv((PdfDiv)element);
                    pageEmpty = false;
                    //newLine();
                    break;
                default:
                    return false;
            }
            lastElementType = element.Type;
            return true;
        }
        /// <summary>
        /// Eigentliche Print Methode um Pdf zu befüllen
        /// </summary>
        /// 
        /// Erstellt von Adrian Glasnek
        private void PrintCriterionStructure(ref PdfPTable CritTable)
        {
            //Übergebene Liste von Methode "GetSortedCriterionStructure()" in Liste sortedProjectCriterionStructure schreiben
            List<ProjectCriterion> sortedProjectCriterionStructure = this.ProjCritContr.GetSortedCriterionStructure(this.Project.Project_Id);

            // Generische Liste - Dictionary Wertepaar vom Typ int - Schlüssel und Wert
            Dictionary<int, int> enumerations = new Dictionary<int, int>() { { 1, 0 } };

            //Foreach-Schleife druckt sortierte Kriterien auf das Pdf Dokument
            foreach (ProjectCriterion projectCriterion in sortedProjectCriterionStructure)
            {
                //Verbindung zu Erfüllungsdaten aus der Datenbank
                Fulfillment fulfillmentForCurrtentCrit = _fulfillmentForEachProduct.SingleOrDefault(fufi => fufi.Criterion_Id == projectCriterion.Criterion_Id);

                //Fehlermeldung wenn nicht für alle Kriterien dieses Produktes eine Erfüllung hinterlegt ist
                if (fulfillmentForCurrtentCrit == null)
                {
                    throw new NWATException(String.Format("Nicht für alle Kriterien zu diesem Produkt ist ein Erfüllungseintrag hinterlegt: \n Erfüllung für Kriterien ID {0} konnte nicht gefunden werden ", projectCriterion.Criterion_Id));
                }

                //Definieren der intend Variable um die richtige "Einrückung" auf dem Pdf Dokument erzielen zu können
                int layer = projectCriterion.Layer_Depth;
                int factor = 25;
                int intend;
                intend = layer * factor;

                //Aufzählunszahlen für die Kriterienstruktur in einen string schreiben
                string enumeration = GetEnumerationForCriterion(ref enumerations, layer);

                //Schriftgröße der angezeigten Kriterienstruktur bestimmen
                Font CritStructFont = FontFactory.GetFont("Arial", 10);

                //Paragraph der die Zellen befüllt
                string CritsEnumeration = "[" + enumeration + "]" + " " + projectCriterion.Criterion.Description.ToString();

                //Neuer Paragraph der den string übergeben bekommt
                Paragraph para = new Paragraph(CritsEnumeration, CritStructFont);
                //Einrückungsfaktor, das zugehörige Kriterien untereinander stehen
                para.IndentationLeft = intend;
                //Neue Tabellenzelle in der die Kriterienbeschreibungen reingeschrieben werden
                PdfPCell Crits = new PdfPCell();
                //Der Zelle den Paragraphen übergeben
                Crits.AddElement(para);
                //Anzeigen von Linien im Pdf
                Crits.Border = 1;
                string comment = "";
                //Die Pdf Zellen an die Pdf Tabelle übergeben
                CritTable.AddCell(Crits);
                CritTable.AddCell("");

                //If Abfrage - Wenn Kriterium erfüllt dann setzte ein Kreuz, wenn nicht setzte ein -
                if (!fulfillmentForCurrtentCrit.Fulfilled)
                {
                    CritTable.AddCell(new Paragraph("-", CritStructFont));
                }
                else
                {
                    CritTable.AddCell(new Paragraph("x", CritStructFont));
                    comment = fulfillmentForCurrtentCrit.Comment;           //Falls Kommentar vorhanden, dann printe Kommentar mit
                }

                CritTable.AddCell(new Paragraph(comment, CritStructFont));
            }
        }
Ejemplo n.º 31
0
// ---------------------------------------------------------------------------
    public void EndElement(string name) {
      if ("pace".Equals(name)) {
        PdfPCell cell = new PdfPCell();
        cell.AddElement(fs.Process(buf.ToString()));
        cell.Padding = 3;
        cell.UseAscender = true;
        cell.UseDescender = true;
        if (rtl) {
          cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
        }
        table.AddCell(language);
        table.AddCell(cell);
        table.AddCell(countries);
      }    
    }    
    public void NestedListAtTheEndOfAnotherNestedList() {
        String pdfFile = "nestedListAtTheEndOfAnotherNestedList.pdf";
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter.GetInstance(document, File.Create(DEST_FOLDER + pdfFile));
        // step 3
        document.Open();
        // step 4
        PdfPTable table = new PdfPTable(1);
        PdfPCell cell = new PdfPCell();
        cell.BackgroundColor = BaseColor.ORANGE;

        RomanList romanlist = new RomanList(true, 20);
        romanlist.IndentationLeft = 10f;
        romanlist.Add("One");
        romanlist.Add("Two");
        romanlist.Add("Three");

        RomanList romanlist2 = new RomanList(true, 20);
        romanlist2.IndentationLeft = 10f;
        romanlist2.Add("One");
        romanlist2.Add("Two");
        romanlist2.Add("Three");

        romanlist.Add(romanlist2);
        //romanlist.add("Four");

        List list = new List(List.ORDERED, 20f);
        list.SetListSymbol("\u2022");
        list.IndentationLeft = 20f;
        list.Add("One");
        list.Add("Two");
        list.Add("Three");
        list.Add("Four");
        list.Add("Roman List");
        list.Add(romanlist);

        list.Add("Five");
        list.Add("Six");

        cell.AddElement(list);
        table.AddCell(cell);
        document.Add(table);
        // step 5
        document.Close();

        CompareTool compareTool = new CompareTool();
        String error = compareTool.CompareByContent(DEST_FOLDER + pdfFile, SOURCE_FOLDER + pdfFile, DEST_FOLDER, "diff_");
        if (error != null) {
            Assert.Fail(error);
        }
    }