SetUnderline() public method

public SetUnderline ( BaseColor color, float thickness, float thicknessMul, float yPosition, float yPositionMul, int cap ) : Chunk
color BaseColor
thickness float
thicknessMul float
yPosition float
yPositionMul float
cap int
return Chunk
Beispiel #1
5
        public void CreateTaggedPdf15() {
            InitializeDocument("15");

            Paragraph p = new Paragraph();
            Chunk chunk = new Chunk("Hello tagged world!");
            chunk.SetBackground(new BaseColor(255, 0, 255));
            chunk.Font = FontFactory.GetFont("TimesNewRoman", 20, BaseColor.ORANGE);
            chunk.SetUnderline(BaseColor.PINK, 1.2f, 1, 1, 1, 0);
            p.Add(chunk);

            document.Add(p);
            document.Close();
            int[] nums = new int[] {3};
            CheckNums(nums);
            CompareResults("15");
        }
Beispiel #2
0
// ---------------------------------------------------------------------------
    /**
     * Creates a Phrase with the name and given name of a director using different fonts.
     * @param    rs    the ResultSet containing director records.
     */
    protected override Phrase CreateDirectorPhrase(DbDataReader r) {
      Phrase director = new Phrase();
      Chunk name = new Chunk(r["name"].ToString(), BOLD);
      name.SetUnderline(0.2f, -2f);
      director.Add(name);
      director.Add(new Chunk(",", BOLD));
      director.Add(new Chunk(" ", NORMAL));
      director.Add(
        new Chunk(r["given_name"].ToString(), NORMAL)
      );
      director.Leading = 24;
      return director;
    }
Beispiel #3
0
        public void CreateTaggedPdf16() {
            InitializeDocument("16");

            Paragraph p = new Paragraph();
            Chunk chunk = new Chunk("Hello tagged world!");
            chunk.SetBackground(new BaseColor(255, 0, 255));
            chunk.Font = FontFactory.GetFont("TimesNewRoman", 20, BaseColor.ORANGE);
            chunk.SetUnderline(BaseColor.PINK, 1.2f, 1, 1, 1, 0);
            p.Add(chunk);
            PdfDiv div = new PdfDiv();
            div.AddElement(p);
            document.Add(div);

            document.Add(new Paragraph("This paragraph appears between 2 div blocks"));

            div = new PdfDiv();
            div.AddElement(new Paragraph(text));
            document.Add(div);


            document.Close();
            int[] nums = new int[] {48, 7};
            CheckNums(nums);
            CompareResults("16");
        }
        /// <summary>
        /// Generates a pdf of election results for this election.
        /// </summary>
        /// <param name="session">A valid session.</param>
        /// <param name="path">The path where the pdf will be saved.</param>
        /// <returns>The document which was created.</returns>
        public virtual Document GenerateResultsPDF(ISession session, string path)
        {
            Committee committee = Committee.FindCommittee(session,
                PertinentCommittee);
            List<Certification> certifications = Certification.FindCertifications(session, ID);
            Dictionary<string, int> users = GetResults(session);

            var doc = new Document();
            PdfWriter.GetInstance(doc,
                new FileStream(path, FileMode.Create));

            PdfPTable table = new PdfPTable(2);
            table.SpacingBefore = 30f;
            table.SpacingAfter = 30f;

            table.AddCell("Candidate");
            table.AddCell("Number of Votes");

            foreach (KeyValuePair<string, int> i in users)
            {
                User user = User.FindUser(session, i.Key);
                table.AddCell(user.FirstName + " " + user.LastName);
                table.AddCell(i.Value.ToString());
            }

            doc.Open();
            Font header = FontFactory.GetFont("Arial", 24, BaseColor.BLACK);
            doc.Add(new Phrase("APSCUF-KU Election Results\n", header));

            // The semester the election was started during
            string semester = "nothing";

            // The fall semester is between august 27 and december 17
            if (Started >= new DateTime(Started.Year, 8, 27) &&
                Started <= new DateTime(Started.Year, 12, 17))
                semester = " held during the Fall " + Started.Year.ToString() + " semester.";
            // The spring semester is between january 22 and may 12
            else if (Started >= new DateTime(Started.Year, 1, 22) &&
                Started <= new DateTime(Started.Year, 5, 12))
                semester = " held during the Spring " + Started.Year.ToString() + " semester.";
            else // otherwise just say what date it started.
                semester = " started on " + Started.ToString("d") + ".";

            doc.Add(new Paragraph("The following results were collected during an election held to fill " + committee.NumberOfVacancies(session).ToString() + " vacancies in the " + committee.Name + semester));
            doc.Add(table);

            foreach(Certification i in certifications)
            {
                User certifyingUser = User.FindUser(session, i.User);
                Chunk sigLine = new Chunk("                                                  \n");
                sigLine.SetUnderline(0.5f, -1.5f);
                Phrase signatureArea = new Phrase();
                signatureArea.Add("I hereby certify the results of this election:\n");
                signatureArea.Add(sigLine);
                signatureArea.Add(certifyingUser.FirstName + " " + certifyingUser.LastName + "\n");
                signatureArea.Add(sigLine);
                signatureArea.Add("Date\n\n");

                doc.Add(signatureArea);
            }
            doc.Close();
            return doc;
        }
        /// <summary>
        /// Print an order to PDF
        /// </summary>
        /// <param name="stream">Stream</param>
        /// <param name="orders">Orders</param>
        /// <param name="lang">Language</param>
        public virtual void PrintOrdersToPdf(Stream stream, IList<Order> orders, Language lang)
        {
            if (stream == null)
                throw new ArgumentNullException("stream");

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

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


            var pageSize = PageSize.A4;

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


            var doc = new Document(pageSize, 40, 40, 40, 80);
            var writer = PdfWriter.GetInstance(doc, stream);
            writer.PageEvent = new OrderPdfPageEvents(_pictureService, _pdfSettings, _companyInformationSettings, _bankConnectionSettings, _contactDataSettings,
				_localizationService, lang, _storeContext);
            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)
            {
                #region Header

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

                ////header
                var headerTable = new PdfPTable(logoExists ? 2 : 1);
                headerTable.WidthPercentage = 100f;
                if (logoExists)
                    headerTable.SetWidths(new[] { 50, 50 });

                //store info
				var store = _storeService.GetStoreById(order.StoreId) ?? _storeContext.CurrentStore;

                var cell = new PdfPCell();
                cell.Border = Rectangle.NO_BORDER;
                cell.HorizontalAlignment = Element.ALIGN_LEFT;
                var pOrderId = new Paragraph(String.Format(_localizationService.GetResource("PDFInvoice.Order#", lang.Id), order.GetOrderNumber()), titleFont);
                pOrderId.Alignment = Element.ALIGN_LEFT;
                cell.AddElement(pOrderId);
                //var anchor = new Anchor(_storeInformationSettings.StoreUrl.Trim(new char[] { '/' }), font);
                //anchor.Reference = _storeInformationSettings.StoreUrl;
                //var pAnchor = new Paragraph(anchor);
                //pAnchor.Alignment = Element.ALIGN_LEFT;
                //cell.AddElement(pAnchor);
                var pDate = new Paragraph(String.Format(_localizationService.GetResource("PDFInvoice.OrderDate", lang.Id), _dateTimeHelper.ConvertToUserTime(order.CreatedOnUtc, DateTimeKind.Utc).ToString("D", new CultureInfo(lang.LanguageCulture))), font);
                pDate.Alignment = Element.ALIGN_LEFT;
                cell.AddElement(pDate);
                headerTable.AddCell(cell);

                //logo
                if (logoExists)
                {
                    var logoFilePath = _pictureService.GetThumbLocalPath(logoPicture, 0, false);
                    if (logoFilePath.HasValue())
                    {
                        var img = Image.GetInstance(logoFilePath);
                        img.ScaleToFit(250, 40);
                        var cellLogo = new PdfPCell(img);
                        cellLogo.Border = Rectangle.NO_BORDER;
                        cellLogo.HorizontalAlignment = Element.ALIGN_RIGHT;
                        headerTable.AddCell(cellLogo);
                    }
                }
                doc.Add(headerTable);

                PdfContentByte cb = writer.DirectContent;
                cb.MoveTo(pageSize.Left + 40f, pageSize.Top - 80f);
                cb.LineTo(pageSize.Right - 40f, pageSize.Top - 80f);
                cb.Stroke();

                #endregion

                #region Addresses

                var fontSmall = new Font(iTextSharp.text.Font.FontFamily.HELVETICA, 7, iTextSharp.text.Font.NORMAL);

                var addressTable = new PdfPTable(2);
                addressTable.WidthPercentage = 100f;
                addressTable.SetWidths(new[] { 50, 50 });

                //billing address
                string company = String.Format("{0}, {1}, {2} {3}", _companyInformationSettings.CompanyName, 
                    _companyInformationSettings.Street, 
                    _companyInformationSettings.ZipCode,
                    _companyInformationSettings.City);

                cell = new PdfPCell();
                cell.Border = Rectangle.NO_BORDER;
                cell.AddElement(new Paragraph(" "));
                cell.AddElement(new Paragraph(" "));

                Chunk chkHeader = new Chunk(company, fontSmall);
                chkHeader.SetUnderline(.5f, -2f);
                cell.AddElement(new Paragraph(chkHeader));

                if (_addressSettings.CompanyEnabled && !String.IsNullOrEmpty(order.BillingAddress.Company))
                {
                    cell.AddElement(new Paragraph(order.BillingAddress.Company, font));
                }
                cell.AddElement(new Paragraph(String.Format(order.BillingAddress.FirstName + " " + order.BillingAddress.LastName), font));
                if (_addressSettings.StreetAddressEnabled)
                {
                    cell.AddElement(new Paragraph(order.BillingAddress.Address1, font));
                }
                if (_addressSettings.StreetAddress2Enabled && !String.IsNullOrEmpty(order.BillingAddress.Address2))
                {
                    cell.AddElement(new Paragraph(order.BillingAddress.Address2, font));
                }
                if (_addressSettings.CityEnabled || _addressSettings.StateProvinceEnabled || _addressSettings.ZipPostalCodeEnabled || _addressSettings.CountryEnabled && order.BillingAddress.Country != null)
                {
                    cell.AddElement(new Paragraph(String.Format("{0} {1} - {2} {3}", 
                        order.BillingAddress.Country != null ? order.BillingAddress.Country.GetLocalized(x => x.TwoLetterIsoCode, lang.Id) : "",
                        order.BillingAddress.StateProvince != null ? "(" + order.BillingAddress.StateProvince.GetLocalized(x => x.Name, lang.Id) + ")": "", 
                        order.BillingAddress.ZipPostalCode,
                        order.BillingAddress.City ), font));
                }
                
                addressTable.AddCell(cell);

                //legal + shop infos 
                cell = new PdfPCell();
                cell.Border = Rectangle.NO_BORDER;
                var paragraph = new Paragraph(_companyInformationSettings.CompanyName, font);
                paragraph.Alignment = Element.ALIGN_RIGHT;
                cell.AddElement(paragraph);

                paragraph = new Paragraph(_companyInformationSettings.Street, font);
                paragraph.Alignment = Element.ALIGN_RIGHT;
                cell.AddElement(paragraph);

                paragraph = new Paragraph(_companyInformationSettings.ZipCode + " " + _companyInformationSettings.City, font);
                paragraph.Alignment = Element.ALIGN_RIGHT;
                cell.AddElement(paragraph);
                cell.AddElement(new Paragraph(" ", fontSmall));
                
                //email
                paragraph = new Paragraph(_contactDataSettings.CompanyEmailAddress, font);
                paragraph.Alignment = Element.ALIGN_RIGHT;
                cell.AddElement(paragraph);

                //url
				paragraph = new Paragraph(store.Url, font);
                paragraph.Alignment = Element.ALIGN_RIGHT;
                cell.AddElement(paragraph);

                //phone
                paragraph = new Paragraph(String.Format(_localizationService.GetResource("PDFInvoice.Phone", lang.Id), _contactDataSettings.CompanyTelephoneNumber), font);
                paragraph.Alignment = Element.ALIGN_RIGHT;
                cell.AddElement(paragraph);

                //fax
                paragraph = new Paragraph(String.Format(_localizationService.GetResource("PDFInvoice.Fax", lang.Id), _contactDataSettings.CompanyFaxNumber), font);
                paragraph.Alignment = Element.ALIGN_RIGHT;
                cell.AddElement(paragraph);

                //tax number/ust-id
                paragraph = new Paragraph(String.Format(_localizationService.GetResource("PDFInvoice.TaxNumber", lang.Id), _companyInformationSettings.TaxNumber), font);
                paragraph.Alignment = Element.ALIGN_RIGHT;
                cell.AddElement(paragraph);

                //vat id
                paragraph = new Paragraph(String.Format(_localizationService.GetResource("PDFInvoice.VatId", lang.Id), _companyInformationSettings.VatId), font);
                paragraph.Alignment = Element.ALIGN_RIGHT;
                cell.AddElement(paragraph);

                //commercial register heading
                paragraph = new Paragraph(_localizationService.GetResource("PDFInvoice.CommercialRegisterHeading", lang.Id), font);
                paragraph.Alignment = Element.ALIGN_RIGHT;
                cell.AddElement(paragraph);

                //handelregister
                paragraph = new Paragraph(_companyInformationSettings.CommercialRegister, font);
                paragraph.Alignment = Element.ALIGN_RIGHT;
                cell.AddElement(paragraph);

                addressTable.AddCell(cell);

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

                #endregion

                #region Products
                //products
                doc.Add(new Paragraph(_localizationService.GetResource("PDFInvoice.Product(s)", lang.Id), titleFont));
                doc.Add(new Paragraph(" "));

				float cellPadding = 4f;
                var orderItems = _orderService.GetAllOrderItems(order.Id, null, null, null, null, null, null);

                var productsTable = new PdfPTable(_catalogSettings.ShowProductSku ? 5 : 4);
                productsTable.WidthPercentage = 100f;
                productsTable.SetWidths(_catalogSettings.ShowProductSku ? new[] { 40, 15, 15, 15, 15 } : new[] { 40, 20, 20, 20 });

                //product name
                cell = new PdfPCell(new Phrase(_localizationService.GetResource("PDFInvoice.ProductName", lang.Id), font));
				cell.Padding = cellPadding;
                cell.BackgroundColor = BaseColor.LIGHT_GRAY;
                cell.HorizontalAlignment = Element.ALIGN_LEFT;
                productsTable.AddCell(cell);

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

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

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

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

                for (int i = 0; i < orderItems.Count; i++)
                {
                    var orderItem = orderItems[i];
                    var p = orderItem.Product;

                    //product name
					string name = p.GetLocalized(x => x.Name, lang.Id);
					cell = new PdfPCell();
					cell.Padding = cellPadding;
					cell.HorizontalAlignment = Element.ALIGN_LEFT;
                    cell.AddElement(new Paragraph(name, font));

					if (p.ProductType == ProductType.BundledProduct)
					{
						var itemParagraph = new Paragraph("", font);
						itemParagraph.IndentationLeft = 25;

						var bundleData = orderItem.GetBundleData();
						foreach (var bundleItem in bundleData)
						{
							if (bundleData.IndexOf(bundleItem) != 0)
								itemParagraph.Add(new Paragraph(" "));

							if (bundleItem.PerItemShoppingCart && bundleItem.Quantity > 1)
								itemParagraph.Add(new Paragraph("{0} × {1}".FormatWith(bundleItem.ProductName, bundleItem.Quantity), font));
							else
								itemParagraph.Add(new Paragraph(bundleItem.ProductName, font));

							if (bundleItem.PerItemShoppingCart)
							{
								decimal priceWithDiscount = _currencyService.ConvertCurrency(bundleItem.PriceWithDiscount, order.CurrencyRate);
								itemParagraph.Add(new Paragraph(_priceFormatter.FormatPrice(priceWithDiscount, true, order.CustomerCurrencyCode, lang, false), font));
							}
							
							if (bundleItem.AttributesInfo.HasValue())
								itemParagraph.Add(new Paragraph(HtmlUtils.ConvertHtmlToPlainText(bundleItem.AttributesInfo, true, true), attributesFont));
						}
						cell.AddElement(itemParagraph);
					}
					else
					{
						var attributesParagraph = new Paragraph(HtmlUtils.ConvertHtmlToPlainText(orderItem.AttributeDescription, true, true), attributesFont);
						cell.AddElement(attributesParagraph);
					}

                    productsTable.AddCell(cell);

                    //SKU
                    if (_catalogSettings.ShowProductSku)
                    {
						p.MergeWithCombination(orderItem.AttributesXml, _productAttributeParser);
                        cell = new PdfPCell(new Phrase(p.Sku ?? String.Empty, font));
						cell.Padding = cellPadding;
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        productsTable.AddCell(cell);
                    }

                    //price
                    string unitPrice = string.Empty;
                    switch (order.CustomerTaxDisplayType)
                    {
                        case TaxDisplayType.ExcludingTax:
                            {
                                var unitPriceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceExclTax, order.CurrencyRate);
                                unitPrice = _priceFormatter.FormatPrice(unitPriceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false);
                            }
                            break;
                        case TaxDisplayType.IncludingTax:
                            {
                                var unitPriceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.UnitPriceInclTax, order.CurrencyRate);
                                unitPrice = _priceFormatter.FormatPrice(unitPriceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true);
                            }
                            break;
                    }
                    cell = new PdfPCell(new Phrase(unitPrice, font));
					cell.Padding = cellPadding;
                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    productsTable.AddCell(cell);

                    //qty
                    cell = new PdfPCell(new Phrase(orderItem.Quantity.ToString(), font));
					cell.Padding = cellPadding;
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    productsTable.AddCell(cell);

                    //total
                    string subTotal = string.Empty;
                    switch (order.CustomerTaxDisplayType)
                    {
                        case TaxDisplayType.ExcludingTax:
                            {
                                var priceExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.PriceExclTax, order.CurrencyRate);
                                subTotal = _priceFormatter.FormatPrice(priceExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false);
                            }
                            break;
                        case TaxDisplayType.IncludingTax:
                            {
                                var priceInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(orderItem.PriceInclTax, order.CurrencyRate);
                                subTotal = _priceFormatter.FormatPrice(priceInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true);
                            }
                            break;
                    }
                    cell = new PdfPCell(new Phrase(subTotal, font));
					cell.Padding = cellPadding;
                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    productsTable.AddCell(cell);
                }
                doc.Add(productsTable);

                #endregion

                #region Checkout attributes

                if (!String.IsNullOrEmpty(order.CheckoutAttributeDescription))
                {
                    doc.Add(new Paragraph(" "));
                    string attributes = HtmlUtils.ConvertHtmlToPlainText(order.CheckoutAttributeDescription, true, true);
                    var pCheckoutAttributes = new Paragraph(attributes, font);
                    pCheckoutAttributes.Alignment = Element.ALIGN_RIGHT;
                    doc.Add(pCheckoutAttributes);
                    doc.Add(new Paragraph(" "));
                }

                #endregion

                #region Totals

                //subtotal
                doc.Add(new Paragraph(" "));
                switch (order.CustomerTaxDisplayType)
                {
                    case TaxDisplayType.ExcludingTax:
                        {
                            var orderSubtotalExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalExclTax, order.CurrencyRate);
                            string orderSubtotalExclTaxStr = _priceFormatter.FormatPrice(orderSubtotalExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false);

                            var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Sub-Total", lang.Id), orderSubtotalExclTaxStr), font);
                            p.Alignment = Element.ALIGN_RIGHT;
                            doc.Add(p);
                        }
                        break;
                    case TaxDisplayType.IncludingTax:
                        {
                            var orderSubtotalInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubtotalInclTax, order.CurrencyRate);
                            string orderSubtotalInclTaxStr = _priceFormatter.FormatPrice(orderSubtotalInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true);

                            var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Sub-Total", lang.Id), orderSubtotalInclTaxStr), font);
                            p.Alignment = Element.ALIGN_RIGHT;
                            doc.Add(p);
                        }
                        break;
                }
                //discount (applied to order subtotal)
                if (order.OrderSubTotalDiscountExclTax > decimal.Zero)
                {
                    switch (order.CustomerTaxDisplayType)
                    {
                        case TaxDisplayType.ExcludingTax:
                            {
                                var orderSubTotalDiscountExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountExclTax, order.CurrencyRate);
                                string orderSubTotalDiscountInCustomerCurrencyStr = _priceFormatter.FormatPrice(-orderSubTotalDiscountExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false);

                                var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Discount", lang.Id), orderSubTotalDiscountInCustomerCurrencyStr), font);
                                p.Alignment = Element.ALIGN_RIGHT;
                                doc.Add(p);
                            }
                            break;
                        case TaxDisplayType.IncludingTax:
                            {
                                var orderSubTotalDiscountInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderSubTotalDiscountInclTax, order.CurrencyRate);
                                string orderSubTotalDiscountInCustomerCurrencyStr = _priceFormatter.FormatPrice(-orderSubTotalDiscountInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true);

                                var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Discount", lang.Id), orderSubTotalDiscountInCustomerCurrencyStr), font);
                                p.Alignment = Element.ALIGN_RIGHT;
                                doc.Add(p);
                            }
                            break;
                    }
                }

                //shipping
                if (order.ShippingStatus != ShippingStatus.ShippingNotRequired)
                {
                    switch (order.CustomerTaxDisplayType)
                    {
                        case TaxDisplayType.ExcludingTax:
                            {
                                var orderShippingExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingExclTax, order.CurrencyRate);
                                string orderShippingExclTaxStr = _priceFormatter.FormatShippingPrice(orderShippingExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false);

                                var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Shipping", lang.Id), orderShippingExclTaxStr), font);
                                p.Alignment = Element.ALIGN_RIGHT;
                                doc.Add(p);
                            }
                            break;
                        case TaxDisplayType.IncludingTax:
                            {
                                var orderShippingInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.OrderShippingInclTax, order.CurrencyRate);
                                string orderShippingInclTaxStr = _priceFormatter.FormatShippingPrice(orderShippingInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true);

                                var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Shipping", lang.Id), orderShippingInclTaxStr), font);
                                p.Alignment = Element.ALIGN_RIGHT;
                                doc.Add(p);
                            }
                            break;
                    }
                }

                //payment fee
                if (order.PaymentMethodAdditionalFeeExclTax > decimal.Zero)
                {
                    switch (order.CustomerTaxDisplayType)
                    {
                        case TaxDisplayType.ExcludingTax:
                            {
                                var paymentMethodAdditionalFeeExclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeExclTax, order.CurrencyRate);
                                string paymentMethodAdditionalFeeExclTaxStr = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeExclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, false);

                                var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.PaymentMethodAdditionalFee", lang.Id), paymentMethodAdditionalFeeExclTaxStr), font);
                                p.Alignment = Element.ALIGN_RIGHT;
                                doc.Add(p);
                            }
                            break;
                        case TaxDisplayType.IncludingTax:
                            {
                                var paymentMethodAdditionalFeeInclTaxInCustomerCurrency = _currencyService.ConvertCurrency(order.PaymentMethodAdditionalFeeInclTax, order.CurrencyRate);
                                string paymentMethodAdditionalFeeInclTaxStr = _priceFormatter.FormatPaymentMethodAdditionalFee(paymentMethodAdditionalFeeInclTaxInCustomerCurrency, true, order.CustomerCurrencyCode, lang, true);

                                var p = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.PaymentMethodAdditionalFee", lang.Id), paymentMethodAdditionalFeeInclTaxStr), font);
                                p.Alignment = Element.ALIGN_RIGHT;
                                doc.Add(p);
                            }
                            break;
                    }
                }

                //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 Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Tax", lang.Id), taxStr), font);
                    p.Alignment = Element.ALIGN_RIGHT;
                    doc.Add(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 Paragraph(String.Format("{0} {1}", taxRate, taxValue), font);
                        p.Alignment = Element.ALIGN_RIGHT;
                        doc.Add(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 Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.Discount", lang.Id), orderDiscountInCustomerCurrencyStr), font);
                    p.Alignment = Element.ALIGN_RIGHT;
                    doc.Add(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 Paragraph(String.Format("{0} {1}", gcTitle, gcAmountStr), font);
                    p.Alignment = Element.ALIGN_RIGHT;
                    doc.Add(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 Paragraph(String.Format("{0} {1}", rpTitle, rpAmount), font);
                    p.Alignment = Element.ALIGN_RIGHT;
                    doc.Add(p);
                }

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


                var pTotal = new Paragraph(String.Format("{0} {1}", _localizationService.GetResource("PDFInvoice.OrderTotal", lang.Id), orderTotalStr), titleFont);
                pTotal.Alignment = Element.ALIGN_RIGHT;
                doc.Add(pTotal);

                #endregion

                #region Order notes

                if (_pdfSettings.RenderOrderNotes)
                {
                    var orderNotes = order.OrderNotes
                        .Where(on => on.DisplayToCustomer)
                        .OrderByDescending(on => on.CreatedOnUtc)
                        .ToList();
                    if (orderNotes.Count > 0)
                    {
                        doc.Add(new Paragraph(_localizationService.GetResource("PDFInvoice.OrderNotes", lang.Id), titleFont));

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

                        var notesTable = new PdfPTable(2);
                        notesTable.WidthPercentage = 100f;
                        notesTable.SetWidths(new[] { 30, 70 });

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

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

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

                            cell = new PdfPCell();
                            cell.AddElement(new Paragraph(HtmlUtils.ConvertHtmlToPlainText(orderNote.FormatOrderNoteText(), true, true), font));
                            cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            notesTable.AddCell(cell);
                        }
                        doc.Add(notesTable);
                    }
                }

                #endregion

                ordNum++;
                if (ordNum < ordCount)
                {
                    doc.NewPage();
                }
            }
            doc.Close();
        }
Beispiel #6
0
        /**
         *
         * @param c the Chunk to apply CSS to.
         * @param t the tag containing the chunk data
         * @return the styled chunk
         */

        virtual public Chunk Apply(Chunk c, Tag t)
        {
            Font f = ApplyFontStyles(t);
            float size = f.Size;
            String value = null;
            IDictionary<String, String> rules = t.CSS;
            foreach (KeyValuePair<String, String> entry in rules)
            {
                String key = entry.Key;
                value = entry.Value;
                if (Util.EqualsIgnoreCase(CSS.Property.FONT_STYLE, key)) {
                    if (Util.EqualsIgnoreCase(CSS.Value.OBLIQUE, value)) {
                        c.SetSkew(0, 12);
                    }
                } else if (Util.EqualsIgnoreCase(CSS.Property.LETTER_SPACING, key)) {
                    String letterSpacing = entry.Value;
                    float letterSpacingValue = 0f;
                    if (utils.IsRelativeValue(value)) {
                        letterSpacingValue = utils.ParseRelativeValue(letterSpacing, f.Size);
                    } else if (utils.IsMetricValue(value)) {
                        letterSpacingValue = utils.ParsePxInCmMmPcToPt(letterSpacing);
                    }
                    c.SetCharacterSpacing(letterSpacingValue);
                } else if (Util.EqualsIgnoreCase(CSS.Property.XFA_FONT_HORIZONTAL_SCALE, key)) {
                    // only % allowed; need a catch block NumberFormatExc?
                    c.SetHorizontalScaling(
                        float.Parse(value.Replace("%", ""))/100);
                }
            }
            // following styles are separate from the for each loop, because they are based on font settings like size.
            if (rules.TryGetValue(CSS.Property.VERTICAL_ALIGN, out value))
            {
                if (Util.EqualsIgnoreCase(CSS.Value.SUPER, value)
                    || Util.EqualsIgnoreCase(CSS.Value.TOP, value)
                    || Util.EqualsIgnoreCase(CSS.Value.TEXT_TOP, value)) {
                    c.SetTextRise((float) (size/2 + 0.5));
                } else if (Util.EqualsIgnoreCase(CSS.Value.SUB, value)
                    || Util.EqualsIgnoreCase(CSS.Value.BOTTOM, value)
                    || Util.EqualsIgnoreCase(CSS.Value.TEXT_BOTTOM, value)) {
                    c.SetTextRise(-size/2);
                } else {
                    c.SetTextRise(utils.ParsePxInCmMmPcToPt(value));
                }
            }
            String xfaVertScale;
            if (rules.TryGetValue(CSS.Property.XFA_FONT_VERTICAL_SCALE, out xfaVertScale))
            {
                if (xfaVertScale.Contains("%"))
                {
                    size *= float.Parse(xfaVertScale.Replace("%", ""))/100;
                    c.SetHorizontalScaling(100/float.Parse(xfaVertScale.Replace("%", "")));
                }
            }
            if (rules.TryGetValue(CSS.Property.TEXT_DECORATION, out value)) {
                String[] splitValues = new Regex(@"\s+").Split(value);
                foreach (String curValue in splitValues) {
                    if (Util.EqualsIgnoreCase(CSS.Value.UNDERLINE, curValue)) {
                        c.SetUnderline(0.75f, -size/8f);
                    }
                    if (Util.EqualsIgnoreCase(CSS.Value.LINE_THROUGH, curValue)) {
                        c.SetUnderline(0.75f, size/4f);
                    }
                }
            }
            if (rules.TryGetValue(CSS.Property.BACKGROUND_COLOR, out value))
            {
                c.SetBackground(HtmlUtilities.DecodeColor(value));
            }
            f.Size = size;
            c.Font = f;


            float? leading = null;
            value = null;
            if (rules.TryGetValue(CSS.Property.LINE_HEIGHT, out value)) {
                if (utils.IsNumericValue(value)) {
                    leading = float.Parse(value) * c.Font.Size;
                } else if (utils.IsRelativeValue(value)) {
                    leading = utils.ParseRelativeValue(value, c.Font.Size);
                } else if (utils.IsMetricValue(value)) {
                    leading = utils.ParsePxInCmMmPcToPt(value);
                }
            }

            if (leading != null) {
                c.setLineHeight((float)leading);
            }
            return c;
        }
Beispiel #7
0
    protected void Download_Click(object sender, EventArgs e)
    {
        //  Check condition
        if (!GridView1.Columns[GridView1.Columns.Count - 1].Visible)
        {
            // Create PDF Document
            String Path = Server.MapPath("~\\Bangdiem\\DKHP\\DKHP_" + userName + ".pdf");
            Document myDocument = new Document(PageSize.A4, 5, 5, 30, 10);

            if (!File.Exists(Path))
            {

                PdfWriter.GetInstance(myDocument, new FileStream(Path, FileMode.CreateNew));

                //  Open document
                myDocument.Open();

                BaseFont bf = BaseFont.CreateFont(Server.MapPath(@"~\Font\TIMES.TTF"), BaseFont.IDENTITY_H, true);
                iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 12);

                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(Server.MapPath("~/images/UIT.png"));
                image.Alignment = iTextSharp.text.Image.UNDERLYING;
                image.ScaleToFit(30f, 30f);

                Chunk c1 = new Chunk("TRƯỜNG ĐẠI HỌC CÔNG NGHỆ THÔNG TIN", font);
                c1.SetUnderline(0.5f, -4f);
                Paragraph Header = new Paragraph(15);
                Header.IndentationLeft = 15;
                Header.Alignment = 3;
                Header.Font = font;
                Header.Add(image);
                Header.SpacingBefore = 5f;
                Header.Add("             ĐẠI HỌC QUỐC GIA THÀNH PHỐ HỒ CHÍ MINH \n               ");
                Header.Add(c1);

                Header.Add("\n\n\n");

                myDocument.Add(Header);

                // Add gridview to
                iTextSharp.text.Table table = new iTextSharp.text.Table(5);

                // set table style properties
                table.BorderWidth = 1;
                table.BorderColor = Color.DARK_GRAY;
                table.Padding = 4;
                table.Alignment = 1;
                table.Width = 90;

                // set *column* widths
                float[] widths = { 0.05f, 0.23f, 0.17f, 0.45f, 0.1f };
                table.Widths = widths;

                string[] col = { "TT", "Mã Lớp", "Mã Môn", "Tên Môn Học", "Số TC" };
                font = new iTextSharp.text.Font(bf, 13, 1);

                // create the *table* header row
                for (int i = 0; i < col.Length; ++i)
                {
                    Cell cell = new Cell(new Phrase(col[i], font));
                    cell.Header = true;
                    cell.HorizontalAlignment = 1;
                    table.AddCell(cell);
                }
                table.EndHeaders();

                int sum = 0;
                font = new iTextSharp.text.Font(bf, 12);
                int order = 0;
                foreach (GridViewRow row in GridView1.Rows)
                {
                    Cell c = new Cell(new Phrase((++order).ToString(), font));
                    c.HorizontalAlignment = 1;
                    table.AddCell(c);

                    c = new Cell(new Phrase(row.Cells[1].Text, font));
                    c.HorizontalAlignment = 1;
                    table.AddCell(c);

                    c = new Cell(new Phrase(((HiddenField)row.FindControl("SubID")).Value, font));
                    c.HorizontalAlignment = 1;
                    table.AddCell(c);

                    c = new Cell(new Phrase("   " + ((LinkButton)row.FindControl("SubNm")).Text, font));
                    table.AddCell(c);

                    c = new Cell(new Phrase(row.Cells[3].Text, font));
                    c.HorizontalAlignment = 1;
                    try { sum += Int16.Parse(row.Cells[3].Text); }
                    catch (Exception ex) { }
                    table.AddCell(c);
                }

                font = new iTextSharp.text.Font(bf, 14);
                Paragraph p = new Paragraph("ĐĂNG KÍ HỌC PHẦN HK " + getTerm() + " " + getYear() + " \n", font);
                p.Alignment = 1;
                p.Add("MSSV : " + userName);
                myDocument.Add(p);

                font = new iTextSharp.text.Font(bf, 12);
                c1 = new Chunk("\n\nHọ Tên : ", font);
                font = new iTextSharp.text.Font(bf, 12, 2);
                Chunk c2 = new Chunk(((Label)StudentData.Items[0].FindControl("StuNmLB")).Text, font);
                font = new iTextSharp.text.Font(bf, 12);
                Chunk c3 = new Chunk("     Khoa : ", font);
                font = new iTextSharp.text.Font(bf, 12, 2);
                Chunk c4 = new Chunk(((Label)StudentData.Items[0].FindControl("DeptLB")).Text, font);

                Paragraph p2 = new Paragraph();
                p2.IndentationLeft = 30f;
                p2.Alignment = 3;
                p2.Add(c1);
                p2.Add(c2);
                p2.Add(c3);
                p2.Add(c4);
                myDocument.Add(p2);

                //  Add Gridview
                myDocument.Add(table);

                if (sum > 25)
                {
                    myDocument.Close();
                    if (File.Exists(Path))
                        try { File.Delete(Path); }
                        catch (Exception ex)
                        {
                        }
                    return;
                }
                font = new iTextSharp.text.Font(bf, 12);
                p = new Paragraph(String.Format("Tổng số TC :        {0}                 ", sum.ToString()), font);
                p.Alignment = 2;
                myDocument.Add(p);

                //  Add sign
                font = new iTextSharp.text.Font(bf, 13);
                p = new Paragraph("\n\n\n                                                                                              Chữ ký SV", font);
                p.Add("                                  Chữ ký PĐT\n\n");
                p.Add("                                                                                           .......................");
                p.Add("                              ........................\n");
                myDocument.Add(p);

                //  Check
                List<string> DateL = new List<string>();
                List<string> Derror = new List<string>();
                String error = "";
                bool first = true;
                foreach (GridViewRow grow in GridView1.Rows)
                {
                    string Date = ((Label)grow.FindControl("Day")).Text;
                    string Period = ((Label)grow.FindControl("Period")).Text;

                    string[] dates = Date.Replace("<br/>", ",").Split(',');
                    string[] periods = Period.Replace("<br/>", ",").Split(',');

                    for (int i = 0; i < dates.Length; i++)
                    {
                        string dateandperiod = dates[i] + periods[i];
                        if (DateL.Contains(dateandperiod))      // Error on samq datetime
                        {
                            if (!Derror.Contains(dateandperiod))
                            {
                                if (first)
                                {
                                    error += "Thứ " + dates[i] + " ca " + periods[i];
                                    first = false;
                                }
                                else error += ", Thứ " + dates[i] + " ca " + periods[i];

                                Derror.Add(dateandperiod);
                            }
                        }
                        else DateL.Add(dateandperiod);
                    }
                }

                if (error != "")
                {
                    font = new iTextSharp.text.Font(bf, 12);
                    p = new Paragraph("\n\n        Ghi chú : trùng giờ học ", font);
                    p.Add("\n        (" + error + ")");
                    myDocument.Add(p);
                }

                font = new iTextSharp.text.Font(bf, 11);
                p = new Paragraph("\n        In vào :" + DateTime.UtcNow.ToShortTimeString() +
                    " " + DateTime.UtcNow.ToShortDateString(), font);
                p.Add("\n        Chú ý : Sinh viên \n        không được tự ý thay đổi nội dung file này.");
                myDocument.Add(p);

                //  Close document
                myDocument.Close();

                //  Check connection and trangfer file
                using (SqlConnection scon = new SqlConnection(ConnectionString))
                {
                    scon.Open();
                    using (SqlCommand scom = new SqlCommand("Insert into DownloadLog values(@StuID,getdate())", scon))
                    {
                        scom.Parameters.Add("@StuID", userName);
                        try
                        {
                            scom.ExecuteNonQuery();
                        }
                        catch (Exception ex)
                        {
                            using (SqlCommand scom1 = new SqlCommand("Update Downloadlog set log = getdate() where StuID = @StuID", scon))
                            {
                                try
                                {
                                    scom1.Parameters.Add("@StuID", userName);
                                    scom1.ExecuteNonQuery();

                                }
                                catch (Exception ex1) { }
                            }
                        }
                    }
                }
            }
            Response.ClearContent();
            Response.ClearHeaders();
            Response.ContentType = "application/pdf";
            Response.AddHeader
            ("Content-Disposition", "attachment; filename = DKHP_" + userName + ".pdf");
            Response.TransmitFile(Path);
            Response.End();
            Response.Flush();
            Response.Clear();
        }
    }
        protected void pdfButton_Click(object sender, EventArgs e)
        {
            Document doc = new Document(PageSize.A4, 36, 72, 108, 180);
            string path = @"D:\";
            PdfWriter.GetInstance(doc, new FileStream(path + "/Treatment.pdf", FileMode.Create));
            doc.Open();
            Voter aVoter = new Voter();
            aVoter.Id=nationalIdTextBox.Text;
            aVoter.Name = nameTextBox.Text;
            aVoter.Address = addressTextBox.Text;
                Paragraph paragraph = new Paragraph();
                paragraph.Add("National Id : " + aVoter.Id);
                paragraph.Add(Environment.NewLine);
                paragraph.Add("Name : " + aVoter.Name);
                paragraph.Add(Environment.NewLine);
                paragraph.Add("Address :" + aVoter.Address);
                paragraph.Add(Environment.NewLine);
                paragraph.Add(Environment.NewLine);
                doc.Add(paragraph);

                Patient aPatient = new Patient();
                aPatient.VoterId = nationalIdTextBox.Text;
                GetPatientInformation(aPatient.VoterId);
                aPatient.Id = patientManager.GetPatientId(aPatient);

             int count = 0;
                List<Treatment> ObservationList = treatmentManager.GetObservationList(aPatient);
                foreach (var observation in ObservationList)
                {
                    count++;
                    PdfPTable table = new PdfPTable(1);
                    Paragraph aParagraph = new Paragraph();
                    Chunk chunk = new Chunk("Treatment-" + count, FontFactory.GetFont("dax-black"));
                    chunk.SetUnderline(0.5f, -1.5f);
                    doc.Add(chunk);

                    string centerName = centerManager.GetCenterName(observation.CenterId);
                    aParagraph.Add("Center Name : " + centerName);
                    aParagraph.Add(Environment.NewLine);
                    string Date = observation.Date;
                    aParagraph.Add("Date : " + Date);
                    aParagraph.Add(Environment.NewLine);
                    string DoctorName = doctorManager.GetDoctorName(observation.DoctorId);
                    aParagraph.Add("Doctor Name : " + DoctorName);
                    aParagraph.Add(Environment.NewLine);
                    string Observation = observation.Observation;
                    aParagraph.Add("Observation : " + Observation);
                    aParagraph.Add(Environment.NewLine);
                    table.AddCell(aParagraph);
                    doc.Add(table);
                    List<Treatment> treatmentList = treatmentManager.GetTreatmentList(observation.ObservationId);
                    List<Treatment> aTreatmentList = new List<Treatment>();
                    foreach (var treatment in treatmentList)
                    {
                        string diseaseName = diseaseManager.GetDiseaseName(treatment.DiseaseId);
                        string medicineName = medicineManager.GetMedicineName(treatment.MedicineId);
                        Treatment aTreatment = new Treatment();
                        aTreatment.NameOfDisease = diseaseName;
                        aTreatment.NameOfMedicine = medicineName;
                        aTreatment.Dose = treatment.Dose;
                        aTreatment.TakenTime = treatment.TakenTime;
                        aTreatment.Quantity = treatment.Quantity;
                        aTreatment.Note = treatment.Note;

                        aTreatmentList.Add(aTreatment);
                    }
                    ShowAllTreatment(centerName, Date, DoctorName, Observation, count, aTreatmentList);
                    PdfPTable aTable = new PdfPTable(6);
                    aTable.AddCell("Disease");
                    aTable.AddCell("Medicine");
                    aTable.AddCell("Dose");
                    aTable.AddCell("Before/After meal");
                    aTable.AddCell("Quantity");
                    aTable.AddCell("Note");
                    foreach (var eachTreatment in aTreatmentList) {
                        aTable.AddCell(eachTreatment.NameOfDisease);
                        aTable.AddCell(eachTreatment.NameOfMedicine);
                        aTable.AddCell(eachTreatment.Dose);
                        aTable.AddCell(eachTreatment.TakenTime);
                        aTable.AddCell(eachTreatment.Quantity.ToString());
                        aTable.AddCell(eachTreatment.Note);
                    }
                    doc.Add(aTable);
                }
            doc.Close();
            Response.Redirect("OpenPdfUI.aspx");
            megLabel.Text = "PDF Creation Successful!";
        }
Beispiel #9
0
        /**
         *
         * @param c the Chunk to apply CSS to.
         * @param t the tag containing the chunk data
         * @return the styled chunk
         */

        public Chunk Apply(Chunk c, Tag t)
        {
            Font f = ApplyFontStyles(t);
            float size = f.Size;
            String value = null;
            IDictionary<String, String> rules = t.CSS;
            foreach (KeyValuePair<String, String> entry in rules)
            {
                String key = entry.Key;
                value = entry.Value;
                if (Util.EqualsIgnoreCase(CSS.Property.FONT_STYLE, key)) {
                    if (Util.EqualsIgnoreCase(CSS.Value.OBLIQUE, value))
                    {
                        c.SetSkew(0, 12);
                    }
                } else if (Util.EqualsIgnoreCase(CSS.Property.LETTER_SPACING, key)) {
                    c.SetCharacterSpacing(utils.ParsePxInCmMmPcToPt(value));
                } else if (Util.EqualsIgnoreCase(CSS.Property.XFA_FONT_HORIZONTAL_SCALE, key)) {
                    // only % allowed; need a catch block NumberFormatExc?
                    c.SetHorizontalScaling(
                        float.Parse(value.Replace("%", ""))/100);
                }
            }
            // following styles are separate from the for each loop, because they are based on font settings like size.
            if (rules.TryGetValue(CSS.Property.VERTICAL_ALIGN, out value))
            {
                if (Util.EqualsIgnoreCase(CSS.Value.SUPER, value)
                    || Util.EqualsIgnoreCase(CSS.Value.TOP, value)
                    || Util.EqualsIgnoreCase(CSS.Value.TEXT_TOP, value)) {
                    c.SetTextRise((float) (size/2 + 0.5));
                } else if (Util.EqualsIgnoreCase(CSS.Value.SUB, value)
                    || Util.EqualsIgnoreCase(CSS.Value.BOTTOM, value)
                    || Util.EqualsIgnoreCase(CSS.Value.TEXT_BOTTOM, value)) {
                    c.SetTextRise(-size/2);
                } else {
                    c.SetTextRise(utils.ParsePxInCmMmPcToPt(value));
                }
            }
            String xfaVertScale;
            if (rules.TryGetValue(CSS.Property.XFA_FONT_VERTICAL_SCALE, out xfaVertScale))
            {
                if (xfaVertScale.Contains("%"))
                {
                    size *= float.Parse(xfaVertScale.Replace("%", ""))/100;
                    c.SetHorizontalScaling(100/float.Parse(xfaVertScale.Replace("%", "")));
                }
            }
            if (rules.TryGetValue(CSS.Property.TEXT_DECORATION, out value))
            {
                // Restriction? In html a underline and a line-through is possible on one piece of text. A Chunk can set an underline only once.
                if (Util.EqualsIgnoreCase(CSS.Value.UNDERLINE, value))
                {
                    c.SetUnderline(0.75f, -size/8f);
                }
                if (Util.EqualsIgnoreCase(CSS.Value.LINE_THROUGH, value))
                {
                    c.SetUnderline(0.75f, size/4f);
                }
            }
            if (rules.TryGetValue(CSS.Property.BACKGROUND_COLOR, out value))
            {
                c.SetBackground(HtmlUtilities.DecodeColor(value));
            }
            f.Size = size;
            c.Font = f;
            return c;
        }
        protected void Button2_Click(object sender, EventArgs e)
        {
            PdfPTable pdftable = new PdfPTable(GridView1.HeaderRow.Cells.Count);

            foreach (TableCell headercell in GridView1.HeaderRow.Cells)
            {
                PdfPCell pdfcell = new PdfPCell(new Phrase(headercell.Text));

                pdfcell.HorizontalAlignment = Element.ALIGN_CENTER;
                pdfcell.VerticalAlignment = Element.ALIGN_MIDDLE;

                pdftable.TotalWidth = 500f;

                //fix the absolute width of the table
                pdftable.LockedWidth = true;

                //relative col widths in proportions - 1/3 and 2/3
                float[] widths = new float[] { 4f, 7f, 6f, 7f, 6f, 8f, 7f, 8f, 6f };
                pdftable.SetWidths(widths);
                pdftable.HorizontalAlignment = 0;

                //leave a gap before and after the table
                pdftable.SpacingBefore = 10f;
                pdftable.SpacingAfter = 10f;

                //border color

                /*
                pdfcell.BorderColorLeft = BaseColor.BLACK;
                pdfcell.BorderColorRight = BaseColor.BLACK;
                pdfcell.BorderColorTop = BaseColor.BLACK;
                pdfcell.BorderColorBottom = BaseColor.BLACK;
                pdfcell.BorderWidthLeft = 1f;
                pdfcell.BorderWidthRight = 1f;
                pdfcell.BorderWidthTop = 1f;
                pdfcell.BorderWidthBottom = 1f;

                 * */
                pdftable.AddCell(pdfcell);

            }

            // loop through each row in database
            foreach (GridViewRow gridviewrow in GridView1.Rows)
            {
                // loop through in each cell in database
                foreach (TableCell tablecell in gridviewrow.Cells)
                {
                    PdfPCell pdfcell = new PdfPCell(new Phrase(tablecell.Text));

                    pdfcell.HorizontalAlignment = Element.ALIGN_CENTER;
                    pdfcell.VerticalAlignment = Element.ALIGN_MIDDLE;

                    pdftable.TotalWidth = 500f;

                    //fix the absolute width of the table
                    pdftable.LockedWidth = true;

                    //relative col widths in proportions - 1/3 and 2/3
                    float[] widths = new float[] { 4f, 7f, 6f, 7f, 6f, 8f, 7f, 8f, 6f };
                    pdftable.SetWidths(widths);
                    pdftable.HorizontalAlignment = 0;
                    //leave a gap before and after the table
                    pdftable.SpacingBefore = 20f;
                    pdftable.SpacingAfter = 30f;

                    //bordercolor

                    /*
                    pdfcell.BorderColorLeft = BaseColor.BLACK;
                    pdfcell.BorderColorRight = BaseColor.BLACK;
                    pdfcell.BorderColorTop = BaseColor.BLACK;
                    pdfcell.BorderColorBottom = BaseColor.BLACK;
                    pdfcell.BorderWidthLeft = 1f;
                    pdfcell.BorderWidthRight = 1f;
                    pdfcell.BorderWidthTop = 1f;
                    pdfcell.BorderWidthBottom = 1f;

            */
                    pdftable.AddCell(pdfcell);

                }

                }

                Document pdfdocument = new Document(PageSize.A4, 30f, 20f, 20f, 20f);
                iTextSharp.text.Image PNG = iTextSharp.text.Image.GetInstance("logo1 copy.PNG");

                iTextSharp.text.Image PNG1 = iTextSharp.text.Image.GetInstance("copyright.PNG");
            PdfWriter.GetInstance(pdfdocument, Response.OutputStream);

                pdfdocument.Open();

                PNG.ScaleToFit(500f, 150f);
                PNG1.ScaleToFit(500f, 90f);

                Paragraph p1 = new Paragraph();
                Paragraph p2 = new Paragraph();

                Chunk chunk = new Chunk("Fare Details  "  , FontFactory.GetFont("dax-black"));

                chunk.SetUnderline(0.5f, -1.5f);

                Font arial = FontFactory.GetFont("Arial", 16, iTextSharp.text.BaseColor.RED);
                Font arial2 = FontFactory.GetFont("Arial", 12, iTextSharp.text.BaseColor.BLACK);

                p2.Add(Chunk.NEWLINE);
                p2.Add(Chunk.NEWLINE);

                p2.Add(new Chunk("Purchased on : " + Label6.Text + "", arial2));

                p2.Add(Chunk.NEWLINE);
                p2.Add(Chunk.NEWLINE);

                p2.Add(new Chunk("Your Ticket Number is : ", arial2));
                p2.Add(new Chunk("#" +Label4.Text+"", arial));

                //p1.Alignment = Element.ALIGN_RIGHT;

                p1.Add(new Chunk("Fare Details", arial2));
                p1.Add(Chunk.NEWLINE);
                p1.Add(Chunk.NEWLINE);
                p1.Add(new Chunk( "No of Adults : " +Label1.Text+"   ", arial2));
                p1.Add(Chunk.NEWLINE);
                p1.Add(Chunk.NEWLINE);
                p1.Add(new Chunk("No of Childs : " + Label2.Text + "   ", arial2));
                p1.Add(Chunk.NEWLINE);
                p1.Add(Chunk.NEWLINE);
                p1.Add(new Chunk("Total Fare (MYR)  : " + Label3.Text + ".00   ",arial));
                p1.Add(Chunk.NEWLINE);
                p1.Add(Chunk.NEWLINE);

                pdfdocument.Add(PNG);
                pdfdocument.Add(p2);
                pdfdocument.Add(pdftable);
                pdfdocument.Add(p1);
                pdfdocument.Add(PNG1);

                pdfdocument.Close();

                Response.ContentType = "application/pdf";

                string fileName =   "(" + "#" + Label4.Text + ")" + "-"+ "Ticket_Number.pdf";

                Response.AppendHeader("content-disposition", "attachment;filename=" + fileName);

                Response.Write(pdfdocument);

                Response.Flush();

                Response.End();
        }
Beispiel #11
0
  /*
  * (non-Javadoc)
  *
  * @see
  * com.itextpdf.tool.xml.css.CssApplier#apply(com.itextpdf.text.Element,
  * com.itextpdf.tool.xml.Tag)
  */
 public Chunk Apply(Chunk c, Tag t) {
     String fontName = null;
     String encoding = BaseFont.CP1252;
     float size = new FontSizeTranslator().GetFontSize(t);
     int style = Font.UNDEFINED;
     BaseColor color = null;
     IDictionary<String, String> rules = t.CSS;
     foreach (KeyValuePair<String, String> entry in rules) {
         String key = entry.Key;
         String value = entry.Value;
         if (Util.EqualsIgnoreCase(CSS.Property.FONT_WEIGHT, key)) {
             if (CSS.Value.BOLD.Contains(value)) {
                 if (style == Font.ITALIC) {
                     style = Font.BOLDITALIC;
                 }
                 else {
                     style = Font.BOLD;
                 }
             }
             else {
                 if (style == Font.BOLDITALIC) {
                     style = Font.ITALIC;
                 } else {
                     style = Font.NORMAL;
                 }
             }
         } else if (Util.EqualsIgnoreCase(CSS.Property.FONT_STYLE, key)) {
             if (Util.EqualsIgnoreCase(value, CSS.Value.ITALIC)) {
                 if (style == Font.BOLD)
                     style = Font.BOLDITALIC;
                 else
                     style = Font.ITALIC;
             }
             if (Util.EqualsIgnoreCase(value, CSS.Value.OBLIQUE)) {
                 c.SetSkew(0, 12);
             }
         } else if (Util.EqualsIgnoreCase(CSS.Property.FONT_FAMILY, key)) {
             if (value.Contains(",")){
                 String[] fonts = value.Split(',');
                 foreach (String s in fonts) {
                     string s2 = s.Trim();
                     if (!Util.EqualsIgnoreCase(FontFactory.GetFont(s2).Familyname, "unknown")){
                         fontName = s2;
                         break;
                     }
                 }
             } else {
                 fontName = value;
             }
         } else if (Util.EqualsIgnoreCase(CSS.Property.COLOR, key)) {
             color = HtmlUtilities.DecodeColor(value);
         } else if (Util.EqualsIgnoreCase(CSS.Property.LETTER_SPACING, key)) {
             c.SetCharacterSpacing(utils.ParsePxInCmMmPcToPt(value));
         } else if (rules.ContainsKey(CSS.Property.XFA_FONT_HORIZONTAL_SCALE)) { // only % allowed; need a catch block NumberFormatExc?
             c.SetHorizontalScaling(float.Parse(rules[CSS.Property.XFA_FONT_HORIZONTAL_SCALE].Replace("%", ""), CultureInfo.InvariantCulture)/100f);
         }
     }
     // following styles are separate from the for each loop, because they are based on font settings like size.
     if (rules.ContainsKey(CSS.Property.VERTICAL_ALIGN)) {
         String value = rules[CSS.Property.VERTICAL_ALIGN];
         if (Util.EqualsIgnoreCase(value, CSS.Value.SUPER)||Util.EqualsIgnoreCase(value, CSS.Value.TOP)||Util.EqualsIgnoreCase(value, CSS.Value.TEXT_TOP)) {
             c.SetTextRise((float) (size / 2 + 0.5));
         } else if (Util.EqualsIgnoreCase(value, CSS.Value.SUB)||Util.EqualsIgnoreCase(value, CSS.Value.BOTTOM)||Util.EqualsIgnoreCase(value, CSS.Value.TEXT_BOTTOM)) {
             c.SetTextRise(-size / 2);
         } else {
             c.SetTextRise(utils.ParsePxInCmMmPcToPt(value));
         }
     }
     String xfaVertScale;
     rules.TryGetValue(CSS.Property.XFA_FONT_VERTICAL_SCALE, out xfaVertScale);
     if (null != xfaVertScale) { // only % allowed; need a catch block NumberFormatExc?
         if (xfaVertScale.Contains("%")) {
             size *= float.Parse(xfaVertScale.Replace("%", ""), CultureInfo.InvariantCulture)/100;
             c.SetHorizontalScaling(100/float.Parse(xfaVertScale.Replace("%", ""), CultureInfo.InvariantCulture));
         }
     }
     if (rules.ContainsKey(CSS.Property.TEXT_DECORATION)) { // Restriction? In html a underline and a line-through is possible on one piece of text. A Chunk can set an underline only once.
         String value = rules[CSS.Property.TEXT_DECORATION];
         if (Util.EqualsIgnoreCase(CSS.Value.UNDERLINE, value)) {
             c.SetUnderline(0.75f, -size/8f);
         }
         if (Util.EqualsIgnoreCase(CSS.Value.LINE_THROUGH, value)) {
             c.SetUnderline(0.75f, size/4f);
         }
     }
     if (rules.ContainsKey(CSS.Property.BACKGROUND_COLOR)) {
         c.SetBackground(HtmlUtilities.DecodeColor(rules[CSS.Property.BACKGROUND_COLOR]));
     }
     Font f  = FontFactory.GetFont(fontName, encoding, BaseFont.EMBEDDED, size, style, color);
     c.Font = f;
     return c;
 }