Ejemplo n.º 1
0
        public override iTextSharp.text.IElement GeneratePdfElement()
        {
            SignaturePanelStyle style = (Manifest != null) ? Manifest.Styles.GetMergedFromConfiguration(Style) : Style;

            Phrase phrase = new Phrase();

            Chunk signature = new Chunk(Signature);
            signature.Style.Font.Apply(style.Font);
            phrase.Content.Add(signature);
            phrase.Content.Add(new NewLine());

            Separator separator = new Separator();
            separator.Style.BorderColor = style.BorderColor;
            separator.Style.Width = style.BorderWidth;
            phrase.Content.Add(separator);

            GenericIdentity identity = new GenericIdentity(User);

            AD.ActiveDirectory activeDirectory = new AD.ActiveDirectory();
            UserDescriptor adUser = activeDirectory.GetUser(identity.GetUserName());
            string fullName = adUser.DisplayName;

            phrase.Content.Add(new NewLine());
            phrase.Content.Add(new Chunk(String.Format("{0} ({1:MMMM dd, yyyy})", fullName, Date)));

            PdfPanel panel = new PdfPanel(phrase);
            panel.Style.BackgroundColor = style.BackgroundColor;
            panel.Style.BorderColor = style.BorderColor;
            panel.Style.Padding = style.Padding;
            panel.Style.BorderWidth = style.BorderWidth;
            panel.Style.Width = style.Width;

            return panel.GeneratePdfElement();
        }
Ejemplo n.º 2
0
        public OperationResult<Message> InvokeMethod(Phrase phrase)
        {
            var res = new OperationResult<Message>();
            var msg = new Message();

            try
            {
                object mres = phrase.Method.Invoke("dummy", phrase.Params != null? phrase.Params.ToArray():null);

                var mStream = new MemoryStream();
                var formatter = new BinaryFormatter();
                formatter.Serialize(mStream, mres);
                mStream.Close();

                //var marshall = new XmlSerializer(mres.GetType());
                //var mStream = new MemoryStream();

                //marshall.Serialize(mStream, mres);

                using (var reader = new StreamReader(mStream))
                {
                    msg.Value = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                res.HasError = true;
                res.Message = ex.Message;
            }

            res.Result = msg;

            return res;
        }
Ejemplo n.º 3
0
        //    Map a given object path to a value in the Trie.
        public bool putObjectString(Word[] characters, Phrase phrase)
        {
            Node p = root;

            for (int n=0; n < characters.Length; n++)
            {

                Word character = characters[n];
                //	Try to get a pointer to the next node
                Node child = p.getChildNode(character);
                //	If there is no next node, then make it.
                if (child == null)
                {
                    if (n == characters.Length - 1)
                    {
                        p.setChildNode(character, new Node(character, phrase));
                        return false;	//	False: it wasn't here already.
                    }
                    else
                    {
                        p.setChildNode(character, new Node(character));
                    }
                }
                else
                {
                    //	Move the pointer down the Trie.
                    p = child;
                }
            }
            //	If we get to this point, then the final node wasn't new (or we would have returned).
            //	So, we just need to overwrite the value in that location.
            p.addPhrase(phrase);
            return true;	//	true because we overwrote what was there.
        }
 public void SetUpEach()
 {
     db = new InMemoryDatabase ();
     phrase1 = new Phrase ("Das Restaurant", "Ресторан", "audio/lesson1/00_Das_Restaurant.mp3");
     phrase2 = new Phrase ("Ich bin sehr mude", "Я очень устал,", "audio/lesson1/01_Ich_bin_sehr_mude.mp3");
     phrase3 = new Phrase ("1", "2", "3");
 }
Ejemplo n.º 5
0
    public static bool ExportPDF(string path)
    {
        try
        {
        //            string path = "D:\\RebateForm" + confirmDetailsRow.ConfirmationID + ".pdf"; //Server.MapPath(ConfigurationManager.AppSettings["ExportPDF"] + misc.RandomString(6, true) + ".pdf");
            Document document = new Document(PageSize.A4, 3, 3, 10, 10);
            PdfWriter.GetInstance(document, new FileStream(path, FileMode.Create));

            Phrase ph = new Phrase("All Information Deemed Accurate but not Warranted\n EQUAL HOUSING OPPERTUNITY", FontFactory.GetFont(FontFactory.HELVETICA, 10, new Color(51, 51, 51)));
            HeaderFooter footer = new HeaderFooter(ph, false);
            footer.Border = 0;
            footer.Alignment = Element.ALIGN_CENTER;
            document.Footer = footer;

            document.Open();
            iTextSharp.text.Table tblMain = new iTextSharp.text.Table(2);
            tblMain.Border = 0;
            tblMain.DefaultCellBorder = 0;
            tblMain.Cellpadding = 2;
            SetTitle(confirmDetailsRow, tblMain);
            SetContactInfo(confirmDetailsRow, tblMain);

            document.Add(tblMain);
            document.Close();
            return true;
        }
        catch (Exception)
        {
            //return false;
            throw;
        }
    }
Ejemplo n.º 6
0
    protected static Phrase GetTextPhrase(string text, bool isBold)
    {
        string fontName = isBold ? FontFactory.HELVETICA_BOLD : FontFactory.HELVETICA;

        Phrase ph = new Phrase(text, FontFactory.GetFont(fontName, 10, new Color(51, 51, 51)));
        return ph;
    }
        public static Phrase Parse(IFuzzyState state, Phrase phrase) {
            Match regexMatch = TimeVariableTemporalPrimitiveToken.RegexMatch.Match(phrase.Text);

            if (regexMatch.Success == true) {
                int? hours = regexMatch.Groups["hours"].Value.Length > 0 ? int.Parse(regexMatch.Groups["hours"].Value) : 0;
                int? minutes = regexMatch.Groups["minutes"].Value.Length > 0 ? int.Parse(regexMatch.Groups["minutes"].Value) : 0;
                int? seconds = regexMatch.Groups["seconds"].Value.Length > 0 ? int.Parse(regexMatch.Groups["seconds"].Value) : 0;

                if (String.Compare(regexMatch.Groups["meridiem"].Value, "pm", StringComparison.OrdinalIgnoreCase) == 0 && hours < 12) {
                    hours += 12;
                }
                else if (String.Compare(regexMatch.Groups["meridiem"].Value, "am", StringComparison.OrdinalIgnoreCase) == 0) {
                    if (hours == 12) {
                        hours = 0;
                    }
                }

                hours %= 24;

                phrase.Add(new TimeVariableTemporalPrimitiveToken() {
                    Pattern = new FuzzyDateTimePattern() {
                        Rule = TimeType.Definitive,
                        Hour = (regexMatch.Groups["hours"].Value.Length > 0 ? hours : null),
                        Minute = (regexMatch.Groups["minutes"].Value.Length > 0 ? minutes : null),
                        Second = (regexMatch.Groups["seconds"].Value.Length > 0 ? seconds : null)
                    },
                    Text = phrase.Text,
                    Similarity = 100.0F
                });
            }

            return phrase;
        }
        public static Phrase ReduceDividendForwardSlashDivisor(IFuzzyState state, Dictionary<String, Token> parameters) {
            FloatNumericPrimitiveToken dividend = (FloatNumericPrimitiveToken) parameters["dividend"];
            ForwardSlashPunctuationSyntaxToken forwardSlash = (ForwardSlashPunctuationSyntaxToken) parameters["forwardSlash"];
            FloatNumericPrimitiveToken divisor = (FloatNumericPrimitiveToken) parameters["divisor"];

            Phrase phrase = null;

            if (divisor.ToFloat() != 0.0F) {
                phrase = new Phrase() {
                    new FloatNumericPrimitiveToken() {
                        Value = dividend.ToFloat() / divisor.ToFloat(),
                        Text = String.Format("{0} {1} {2}", dividend.Text, forwardSlash.Text, divisor.Text),
                        Similarity = (dividend.Similarity + forwardSlash.Similarity + divisor.Similarity) / 3.0F
                    }
                };
            }
            else {
                // TODO: Create new token for exceptions
                phrase = new Phrase() {
                    new FloatNumericPrimitiveToken() {
                        Value = 0.0F,
                        Text = String.Format("{0} {1} {2}", dividend.Text, forwardSlash.Text, divisor.Text),
                        Similarity = (dividend.Similarity + forwardSlash.Similarity + divisor.Similarity) / 3.0F
                    }
                };
            }

            return phrase;
        }
        public static List<Phrase> GetPhrases(this Tree root, Rhetorica.Sentence sentence = null, string ignore = "", string punctuation = null, AnalyzerOptions options = AnalyzerOptions.None)
        {
            var phrases = new List<Phrase>();

              for (java.util.Iterator i = root.iterator(); i.hasNext(); ) {
            Tree tree = (Tree)i.next();
            if (tree.isPhrasal()) {
              java.util.List children = tree.getChildrenAsList();
              if (children.size() == 1 && ((Tree)children.get(0)).isPhrasal())
            continue;

              var current = new Phrase(tree.GetTokens(root, sentence, ignore, punctuation, options));
              // If current node matches previous node but for punctuation omission, replace previous with current:
              bool omitFalseDuplicatePhrases = options.HasFlag(AnalyzerOptions.OmitFalseDuplicatePhrases);
              if (omitFalseDuplicatePhrases) {
            if (phrases.Count > 0) {
              Phrase previous = phrases.Last();
              if (previous.EqualExceptPunctuationOmission(current)) {
                phrases[phrases.Count - 1] = current;
                continue;
              }
            }
              }

              if (current.Count == 0)
            continue;

              phrases.Add(current);
            }
              }

              return phrases;
        }
Ejemplo n.º 10
0
            public static void GameLoop()
            {
                int exactMatch = 0;
                int partialMatch = 0;
                int hint = 1;
                bool gameOver = false;
                string guessString;
                Phrase actual = new Phrase();

                while (!gameOver)
                {
                    Console.Write("Enter your guess: ");
                    guessString = Console.ReadLine();

                    if (guessString == "hint")
                    {
                        string padding = new string('-', Phrase.PhraseSize - hint);
                        Console.WriteLine("{0}{1}", actual.Value.Substring(0, hint), padding);

                        // begin -- for debugging only
                        Console.WriteLine("{0} G x {1}", actual.Value, actual.Count.G);
                        Console.WriteLine("{0} A x {1}", actual.Value, actual.Count.A);
                        Console.WriteLine("{0} T x {1}", actual.Value, actual.Count.T);
                        Console.WriteLine("{0} C x {1}", actual.Value, actual.Count.C);
                        // end -- for debugging only

                        if (hint < Phrase.PhraseSize)
                        {
                            hint++;
                        }

                        else
                        {
                            Console.WriteLine("No more hints! Game Over.");
                            gameOver = true;
                        }
                    }

                    else
                    {
                        Phrase guess = new Phrase(guessString);
                        if (!actual.Compare(guess, out exactMatch, out partialMatch))
                        {
                            Console.WriteLine("You have {0} exact and {1} partial matches. Try again.", exactMatch, partialMatch);
                        }

                        else
                        {
                            Console.WriteLine("Congratulations! You Win!");
                            gameOver = true;
                        }

                    }

                }
            }
Ejemplo n.º 11
0
        public static Phrase Parse(IFuzzyState state, Phrase phrase) {
            if (phrase.Text.Length > 0 && phrase.Text.First() == '"' && phrase.Text.Last() == '"' && phrase.Refactoring == false) {
                phrase.Add(new StringPrimitiveToken() {
                    Text = phrase.Text.Trim('"'),
                    Similarity = 80,
                    Value = phrase.Text.Trim('"')
                });
            }

            return phrase;
        }
Ejemplo n.º 12
0
        public bool addPhraseAndDeleteExistingPhrases(Phrase phrase)
        {
            //	Get the node where the phrase belongs
            bool created;
            Trie<ProseObject, List<Phrase>>.Node phraseNode = patternTrie.getOrCreateNodeAtObjectPath(phrase.getPattern(), out created);

            //	Make this phrase the only one at the node.
            phraseNode.setValue(new List<Phrase>(1));
            phraseNode.Value.Add(phrase);
            return created;
        }
        public new static Phrase Parse(IFuzzyState state, Phrase phrase) {
            List<SelfReflectionThingObjectToken> createdTokens = null;
            TokenReflection.CreateDescendants(state, phrase, out createdTokens);

            if (createdTokens != null && createdTokens.Count > 0) {
                foreach (SelfReflectionThingObjectToken self in createdTokens) {
                    state.ParseSelfReflectionThing(state, self);
                }
            }

            return phrase;
        }
Ejemplo n.º 14
0
        public bool addPhrase(Phrase phrase)
        {
            //	Get the node where the phrase belongs
            bool created;
            Trie<ProseObject, List<Phrase>>.Node phraseNode = patternTrie.getOrCreateNodeAtObjectPath(phrase.getPattern(), out created);

            //	Add the phrase to the node
            if (phraseNode.Value == null)					//	If we have to make a place in the node to put our phrase...
                phraseNode.setValue(new List<Phrase>());
            phraseNode.Value.Add(phrase);
            return created;
        }
Ejemplo n.º 15
0
        public void PhrasesEqualityTest()
        {
            Phrase p1 = new Phrase ("1", "2", "3");
            Phrase p2 = new Phrase ("1", "2", "3");
            Phrase p3 = new Phrase ("1", "2", "-");
            Phrase p4 = new Phrase ("1", "-", "3");
            Phrase p5 = new Phrase ("-", "2", "3");

            Assert.IsTrue (p1.Equals (p2));
            Assert.IsFalse (p1.Equals (p3));
            Assert.IsFalse (p1.Equals (p4));
            Assert.IsFalse (p1.Equals (p5));
        }
        public Phrase Handle(Phrase input, GrammarParser.ParaphraseOptions? opts, List<string> emph, double prob)
        {
            if (opts == null)
                opts = GrammarParser.ParaphraseOptions.NoOptions;

            List<Phrase> emphasizes = new List<Phrase>();
            if (emph != null) {
                foreach (string word in emph)
                    emphasizes.AddRange(input.FindPhrases(word));
            }

            return input.Parapharse(verbs, nouns, wordnet, opts.Value, emphasizes, ref prob);
        }
Ejemplo n.º 17
0
        public void Say(Phrase say, bool sayTime = false)
        {
            Game.ExecuteCommand("chatwheel_say " + (int)say);

            if (sayTime)
            {
                DelayAction.Add(250, () => Game.ExecuteCommand("chatwheel_say " + (int)Phrase.CurrentTime));
                Variables.Sleeper.Sleep(random.Next(3111, 3333), "CanPing");
            }
            else
            {
                Variables.Sleeper.Sleep(random.Next(1111, 1333), "CanPing");
            }
        }
Ejemplo n.º 18
0
        static void Main(string[] args)
        {
            List<string> resources = new List<string>();

                Parser parser = new Parser(fileName);

                List<Audio> phraseAudios = new List<Audio>();

                phraseAudios.Add(new Audio(new Byte[10], parser.Bpm));

                Phrase phrase = new Phrase(phraseAudios, parser.Difficulty);

                List<Phrase> phrases = new List<Phrase>();
        }
    protected PdfPTable CreateSectionDetail()
    {
        Section section = GetCurrentSection();
        PdfPTable nestedTable = null;

        if (section.Type == WebConstants.SectionTypes.MULTIPLE_SELECT_LIST)
        {
            textCount++;
            nestedTable = new PdfPTable(section.RepeatColumns);
            nestedTable.DefaultCell.Border = Rectangle.NO_BORDER;
            nestedTable.WidthPercentage = 100;

            int index = 0;
            int limit = section.Details.Count/section.RepeatColumns;
            if(section.Details.Count%section.RepeatColumns != 0)
            {
                limit++;
            }
            for (int i = 0; i < section.RepeatColumns ; i++)
            {
                Phrase phrase = new Phrase();
                for(int j=0; j < limit && index < section.Details.Count;j++)
                {
                    if (j > 0)
                    {
                        phrase.Add(new Chunk("\n"));
                    }
                    if (section.Details[index].Selected)
                    {
                        phrase.Add(new Chunk(AddCheckedCheckBox(),0,0));
                    }
                    else
                    {
                        phrase.Add(new Chunk(AddCheckBox(), 0, 0));
                    }
                    //phrase.Add(new Chunk(" " + section.Details[index].Text));
                    phrase.Add(new Chunk(" " + section.Details[index].Text, FontFactory.GetFont("Arial", 9)));
                    index++;
                }
                nestedTable.AddCell(phrase);
            }
        }
        else
        {
            nestedTable = new PdfPTable(1);
        }
        return nestedTable;
    }
Ejemplo n.º 20
0
        private void AddInsertion(AstNode node, Phrase phrase)
        {
            // start tag
            Insertions.Add(new Insertion
            {
                Offset = Document.GetOffset(node.StartLocation),
                Phrase = String.Format("<span class='{0}'>", phrase.ToCss())
            });

            // end tag
            Insertions.Add(new Insertion
            {
                Offset = Document.GetOffset(node.EndLocation),
                Phrase = "</span>"
            });
        }
Ejemplo n.º 21
0
        public void DettachPhraseTest()
        {
            DataBase.Create();
            using (var db = new DataBase())
            {
                db.Lessons.InsertOnSubmit(new Lesson() { LessonId = 1, Name = "lesson" });
                db.SubmitChanges();
                var w = new Phrase() { PhraseId = 1 };
                var l = db.Lessons.First();
                l.AttacPhrase(w);
                db.Phrases.InsertOnSubmit(w);
                db.SubmitChanges();
                Assert.AreNotEqual(null, w.Lesson);
                l.DetachPhrase(w);
                Assert.AreEqual(null, w.Lesson);

            }
        }
        public static Phrase ReduceDateTimeDateTime(IFuzzyState state, Dictionary<String, Token> parameters) {
            DateTimeTemporalPrimitiveToken dateTimeA = (DateTimeTemporalPrimitiveToken) parameters["dateTimeA"];
            DateTimeTemporalPrimitiveToken dateTimeB = (DateTimeTemporalPrimitiveToken) parameters["dateTimeB"];

            Phrase phrase = null;

            FuzzyDateTimePattern combined = dateTimeA.Pattern + dateTimeB.Pattern;

            if (combined != null) {
                phrase = new Phrase() {
                    new DateTimeTemporalPrimitiveToken() {
                        Pattern = combined,
                        Text = String.Format("{0} {1}", dateTimeA.Text, dateTimeB.Text),
                        Similarity = (dateTimeA.Similarity + dateTimeB.Similarity) / 2.0F
                    }
                };
            }

            return phrase;
        }
        public static Phrase Parse(IFuzzyState state, Phrase phrase) {
            Match regexMatch = DateVariableTemporalPrimitiveToken.RegexMatch.Match(phrase.Text);

            if (regexMatch.Success == true) {
                DateTime dt;
                if (DateTime.TryParse(phrase.Text, out dt) == true) {
                    phrase.Add(new DateVariableTemporalPrimitiveToken() {
                        Pattern = new FuzzyDateTimePattern() {
                            Rule = TimeType.Definitive,
                            Year = dt.Year,
                            Month = dt.Month,
                            Day = dt.Day
                        },
                        Text = phrase.Text,
                        Similarity = 100.0F
                    });
                }
            }

            return phrase;
        }
Ejemplo n.º 24
0
        public static List<Phrase> GetClauses(this Tree root, Rhetorica.Sentence sentence = null, string ignore = "", string punctuation = null, AnalyzerOptions options = AnalyzerOptions.None)
        {
            var phrases = new List<Phrase>();

              for (java.util.Iterator i = root.iterator(); i.hasNext(); ) {
            Tree tree = (Tree)i.next();

            var treeLabel = tree.label().value();
            var clauseRe = @"^(S|SBAR|SBARQ|SINV|SQ|FRAG)$";
            bool isClausal = Regex.IsMatch(treeLabel, clauseRe, RegexOptions.IgnoreCase);

            if (isClausal) {
              var current = new Phrase(tree.GetTokens(root, sentence, ignore, punctuation, options));
              // If current node matches previous node but for punctuation omission, replace previous with current:
              bool omitFalseDuplicatePhrases = options.HasFlag(AnalyzerOptions.OmitFalseDuplicatePhrases);
              if (omitFalseDuplicatePhrases) {
            if (phrases.Count > 0) {
              Phrase previous = phrases.Last();
              if (previous.EqualExceptPunctuationOmission(current)) {
                phrases[phrases.Count - 1] = current;
                continue;
              }
            }
              }

              if (current.Count == 0)
            continue;

              phrases.Add(current);
            }
              }

              if (phrases.Count == 0) { // Since 'root' has been identified as a sentence, it should have at least one clause associated with it.
            var pseudoClauses = root.GetPhrases(sentence, ignore, punctuation, options);
            if (pseudoClauses.Count > 0)
              phrases.Add(pseudoClauses[0]);
              }

              return phrases;
        }
Ejemplo n.º 25
0
 public bool AddPhrase(int accountID, string text, SourceType sourceType)
 {
     return InvokeSafeSingleCall(() => {
         text = text.ToLower();
         var phrase = Phrase.DataSource
             .WhereEquals(Phrase.Fields.Text, text)
             .WhereEquals(Phrase.Fields.CollectionIdentity, (short)AlgoBase.CollectionIdentity)
             .First();
         if (phrase == null) {
             phrase = new Phrase {
                 Datecreated = DateTime.UtcNow,
                 Text = text,
                 Status = PhraseStatus.NotCollected,
                 CollectionIdentity = AlgoBase.CollectionIdentity,
             };
             phrase.Save();
         }
         var phraseAccount = Phraseaccount.DataSource
             .WhereEquals(Phraseaccount.Fields.AccountidentityID, accountID)
             .WhereEquals(Phraseaccount.Fields.PhraseID, phrase.ID)
             .WhereEquals(Phraseaccount.Fields.CollectionIdentity, (short)AlgoBase.CollectionIdentity)
             .First();
         if (phraseAccount == null) {
             phraseAccount = new Phraseaccount {
                 Datecreated = DateTime.UtcNow,
                 AccountidentityID = accountID,
                 PhraseID = phrase.ID,
                 SourceType = sourceType,
                 CollectionIdentity = AlgoBase.CollectionIdentity
             };
         } else {
             phraseAccount.SourceType |= sourceType;
         }
         return phraseAccount.Save();
     }, false);
 }
        private void ExportToPDF(GridView gvReport, string tenBang, bool LandScape)
        {
            int       noOfColumns = 0, noOfRows = 0;
            DataTable tbl = null;

            if (gvReport.AutoGenerateColumns)
            {
                tbl         = gvReport.DataSource as DataTable; // Gets the DataSource of the GridView Control.
                noOfColumns = tbl.Columns.Count;
                noOfRows    = tbl.Rows.Count;
            }
            else
            {
                noOfColumns = gvReport.Columns.Count;
                noOfRows    = gvReport.Rows.Count;
            }

            float ApplicationNameSize = 7;

            // Creates a PDF document

            Document document = null;

            if (LandScape == true)
            {
                // Sets the document to A4 size and rotates it so that the     orientation of the page is Landscape.
                document = new Document(PageSize.A4.Rotate(), 0, 0, 15, 5);
            }
            else
            {
                document = new Document(PageSize.A4, 0, 0, 15, 5);
            }

            // Creates a PdfPTable with column count of the table equal to no of columns of the gridview or gridview datasource.
            iTextSharp.text.pdf.PdfPTable mainTable = new iTextSharp.text.pdf.PdfPTable(noOfColumns);

            // Sets the first 4 rows of the table as the header rows which will be repeated in all the pages.
            mainTable.HeaderRows = 4;
            string   ARIALUNI_TFF = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "times.TTF");
            BaseFont bf           = BaseFont.CreateFont(ARIALUNI_TFF, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            iTextSharp.text.Font text = new iTextSharp.text.Font(bf, 14, iTextSharp.text.Font.NORMAL);

            // Creates a PdfPTable with 2 columns to hold the header in the exported PDF.
            iTextSharp.text.pdf.PdfPTable headerTable = new iTextSharp.text.pdf.PdfPTable(2);

            // Creates a phrase to hold the application name at the left hand side of the header.
            Phrase phApplicationName = new Phrase("Nhom 5 - Library management", text);

            // Creates a PdfPCell which accepts a phrase as a parameter.
            PdfPCell clApplicationName = new PdfPCell(phApplicationName);

            // Sets the border of the cell to zero.
            clApplicationName.Border = PdfPCell.NO_BORDER;
            // Sets the Horizontal Alignment of the PdfPCell to left.
            clApplicationName.HorizontalAlignment = Element.ALIGN_LEFT;

            // Creates a phrase to show the current date at the right hand side of the header.
            Phrase phDate = new Phrase(DateTime.Now.Date.ToString("dd/MM/yyyy"), FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));

            // Creates a PdfPCell which accepts the date phrase as a parameter.
            PdfPCell clDate = new PdfPCell(phDate);

            // Sets the Horizontal Alignment of the PdfPCell to right.
            clDate.HorizontalAlignment = Element.ALIGN_RIGHT;
            // Sets the border of the cell to zero.
            clDate.Border = PdfPCell.NO_BORDER;

            // Adds the cell which holds the application name to the headerTable.
            headerTable.AddCell(clApplicationName);
            // Adds the cell which holds the date to the headerTable.
            headerTable.AddCell(clDate);
            // Sets the border of the headerTable to zero.
            headerTable.DefaultCell.Border = PdfPCell.NO_BORDER;

            // Creates a PdfPCell that accepts the headerTable as a parameter and then adds that cell to the main PdfPTable.
            PdfPCell cellHeader = new PdfPCell(headerTable);

            cellHeader.Border = PdfPCell.NO_BORDER;
            // Sets the column span of the header cell to noOfColumns.
            cellHeader.Colspan = noOfColumns;
            // Adds the above header cell to the table.
            mainTable.AddCell(cellHeader);

            // Creates a phrase which holds the file name.
            Phrase   phHeader = new Phrase(tenBang, text);
            PdfPCell clHeader = new PdfPCell(phHeader);

            clHeader.Colspan             = noOfColumns;
            clHeader.Border              = PdfPCell.NO_BORDER;
            clHeader.HorizontalAlignment = Element.ALIGN_CENTER;
            mainTable.AddCell(clHeader);

            // Creates a phrase for a new line.
            Phrase   phSpace = new Phrase("\n");
            PdfPCell clSpace = new PdfPCell(phSpace);

            clSpace.Border  = PdfPCell.NO_BORDER;
            clSpace.Colspan = noOfColumns;
            mainTable.AddCell(clSpace);

            // Sets the gridview column names as table headers.
            for (int i = 0; i < noOfColumns; i++)
            {
                Phrase ph = null;

                if (gvReport.AutoGenerateColumns)
                {
                    ph = new Phrase(tbl.Columns[i].ColumnName, text);
                }
                else
                {
                    ph = new Phrase(gvReport.Columns[i].HeaderText, text);
                }

                mainTable.AddCell(ph);
            }

            // Reads the gridview rows and adds them to the mainTable
            for (int rowNo = 0; rowNo < noOfRows; rowNo++)
            {
                for (int columnNo = 0; columnNo < noOfColumns; columnNo++)
                {
                    if (gvReport.AutoGenerateColumns)
                    {
                        string s  = gvReport.Rows[rowNo].Cells[columnNo].Text.Trim();
                        Phrase ph = new Phrase(s, text);
                        mainTable.AddCell(ph);
                    }
                    else
                    {
                        if (gvReport.Columns[columnNo] is TemplateField)
                        {
                            DataBoundLiteralControl lc = gvReport.Rows[rowNo].Cells[columnNo].Controls[0] as DataBoundLiteralControl;
                            string s  = lc.Text.Trim();
                            Phrase ph = new Phrase(s, text);
                            mainTable.AddCell(ph);
                        }
                        else
                        {
                            string s  = gvReport.Rows[rowNo].Cells[columnNo].Text.Trim();
                            Phrase ph = new Phrase(s, text);
                            mainTable.AddCell(ph);
                        }
                    }
                }

                // Tells the mainTable to complete the row even if any cell is left incomplete.
                mainTable.CompleteRow();
            }

            // Gets the instance of the document created and writes it to the output stream of the Response object.
            PdfWriter.GetInstance(document, Response.OutputStream);

            // Creates a footer for the PDF document.

            //HeaderFooter pdfFooter = new HeaderFooter(new Phrase(), true);
            //pdfFooter.Alignment = Element.ALIGN_CENTER;
            //pdfFooter.Border = Rectangle.NO_BORDER;

            //// Sets the document footer to pdfFooter.
            //document.Footer = pdfFooter;
            // Opens the document.
            document.Open();
            // Adds the mainTable to the document.
            document.Add(mainTable);
            // Closes the document.
            document.Close();

            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment; filename= SampleExport.pdf");
            Response.End();
        }
Ejemplo n.º 27
0
        public void blank()
        {
            dict = new Dictionary <string, string>();
            dict.Add("oboi", "Обои");
            dict.Add("plitka", "Плитка");
            dict.Add("table", "Стол");
            dict.Add("stol", "Стул");
            dict.Add("plita", "Плита");
            dict.Add("icebox", "Холодильник");
            mbd.Connection();

            DataTable dt = mbd.selectionquery("select naimenovanie,nazvanie,price from StroyMaterial join StroyMaterialZakaz on StroyMaterial.id_stroy_mater = StroyMaterialZakaz.id_StroyMaterial" +
                                              " join Zakaz on StroyMaterialZakaz.id_zakaz = Zakaz.id_zakaz  where zakaz.id_zakaz = " + Convert.ToString(id) + ";");

            DataTable dt1 = mbd.selectionquery("select naimenovanie,nazvanie,price from Furnitura  join FurnituraZakaz  on FurnituraZakaz.id_Furnitura = Furnitura.id_furnit " +
                                               " join Zakaz on FurnituraZakaz.id_zakaz = Zakaz.id_zakaz  where zakaz.id_zakaz = " + Convert.ToString(id) + " AND type = 'mebel';");

            DataTable dt2 = mbd.selectionquery("select naimenovanie,nazvanie,price from Furnitura  join FurnituraZakaz  on FurnituraZakaz.id_Furnitura = Furnitura.id_furnit " +
                                               " join Zakaz on FurnituraZakaz.id_zakaz = Zakaz.id_zakaz  where zakaz.id_zakaz = " + Convert.ToString(id) + " AND type = 'technics';");

            var doc = new Document();

            PdfWriter.GetInstance(doc, new FileStream(@"Document.pdf", FileMode.Create));
            doc.Open();

            BaseFont baseFont = BaseFont.CreateFont(@"ARIAL.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            iTextSharp.text.Phrase p = new Phrase("Бланк заказа №" + Convert.ToString(id),
                                                  new iTextSharp.text.Font(baseFont, 14,
                                                                           iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black)));
            Paragraph a1 = new Paragraph(p);

            a1.Alignment = Element.ALIGN_CENTER;
            a1.Add(Environment.NewLine);
            a1.SpacingAfter = 5;
            doc.Add(a1);

            PdfPTable table = new PdfPTable(3);

            PdfPCell cell = new PdfPCell(new Phrase("Наименование", new iTextSharp.text.Font(baseFont,
                                                                                             12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black))));

            //cell.BackgroundColor = new BaseColor(Color.Yellow);
            //cell.Padding = 3; //отступ
            cell.Colspan             = 1;
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            cell.VerticalAlignment   = PdfPCell.ALIGN_MIDDLE;
            table.AddCell(cell);
            cell = new PdfPCell(new Phrase("Название", new iTextSharp.text.Font(baseFont,
                                                                                12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black))));
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            table.AddCell(cell);
            cell = new PdfPCell(new Phrase("Цена", new iTextSharp.text.Font(baseFont,
                                                                            12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black))));
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            table.AddCell(cell);

            cell = new PdfPCell(new Phrase("Строительные материалы", new iTextSharp.text.Font(baseFont,
                                                                                              12, iTextSharp.text.Font.BOLD, new BaseColor(Color.Black))));

            //cell.BackgroundColor = new BaseColor(Color.Yellow);
            cell.Padding             = 3; //отступ
            cell.Colspan             = 3;
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            table.AddCell(cell);

            //PdfPCell cell1 = new PdfPCell(new Phrase("14"));
            //cell1.Rowspan = 1;
            //table.AddCell(cell1);
            int sumSM = 0;

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string s = Convert.ToString(dt.Rows[i][j]);
                    if (j == 0)
                    {
                        cell = new PdfPCell(new Phrase(dict[Convert.ToString(dt.Rows[i][j])], new iTextSharp.text.Font(baseFont,
                                                                                                                       12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black))));
                    }
                    else
                    {
                        cell = new PdfPCell(new Phrase(Convert.ToString(dt.Rows[i][j]), new iTextSharp.text.Font(baseFont,
                                                                                                                 12, iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black))));
                    }


                    table.AddCell(cell);
                }
                sumSM += Convert.ToInt32(dt.Rows[i][2]);
            }

            cell = new PdfPCell(new Phrase("Мебель", new iTextSharp.text.Font(baseFont,
                                                                              12, iTextSharp.text.Font.BOLD, new BaseColor(Color.Black))));

            cell.Padding             = 3; //отступ
            cell.Colspan             = 3;
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            table.AddCell(cell);
            int sumM = 0;

            for (int i = 0; i < dt1.Rows.Count; i++)
            {
                for (int j = 0; j < dt1.Columns.Count; j++)
                {
                    if (j == 0)
                    {
                        cell = new PdfPCell(new Phrase(dict[Convert.ToString(dt1.Rows[i][j])], new iTextSharp.text.Font(baseFont, 12,
                                                                                                                        iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black))));
                    }
                    else
                    {
                        cell = new PdfPCell(new Phrase(Convert.ToString(dt1.Rows[i][j]), new iTextSharp.text.Font(baseFont, 12,
                                                                                                                  iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black))));
                    }
                    table.AddCell(cell);
                }
                sumM += Convert.ToInt32(dt1.Rows[i][2]);
            }

            cell = new PdfPCell(new Phrase("Техника", new iTextSharp.text.Font(baseFont,
                                                                               12, iTextSharp.text.Font.BOLD, new BaseColor(Color.Black))));
            int sumT = 0;

            cell.Padding             = 3; //отступ
            cell.Colspan             = 3;
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            table.AddCell(cell);

            for (int i = 0; i < dt2.Rows.Count; i++)
            {
                for (int j = 0; j < dt2.Columns.Count; j++)
                {
                    if (j == 0)
                    {
                        cell = new PdfPCell(new Phrase(dict[Convert.ToString(dt2.Rows[i][j])], new iTextSharp.text.Font(baseFont, 12,
                                                                                                                        iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black))));
                    }
                    else
                    {
                        cell = new PdfPCell(new Phrase(Convert.ToString(dt2.Rows[i][j]), new iTextSharp.text.Font(baseFont, 12,
                                                                                                                  iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black))));
                    }
                    table.AddCell(cell);
                }
                sumT += Convert.ToInt32(dt2.Rows[i][2]);
            }

            //table.AddCell("Обои");
            //table.AddCell("Col 3 Row 1");
            //table.AddCell("Col 2 Row 2");


            //jpg = iTextSharp.text.Image.GetInstance(@"G:/left.jpg");
            //cell = new PdfPCell(jpg);
            //cell.Padding = 5;
            //cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
            //table.AddCell(cell);

            //jpg = iTextSharp.text.Image.GetInstance(@"G:/right.jpg");
            //cell = new PdfPCell(jpg);
            //cell.Padding = 5;
            //cell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
            //table.AddCell(cell);


            doc.Add(table);


            Phrase p1 = new Phrase("             Сумма строительных материалов(это не точно): " + Convert.ToString(sumSM),
                                   new iTextSharp.text.Font(baseFont, 14,
                                                            iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black)));
            Paragraph a2 = new Paragraph(p1);

            a2.Alignment = Element.ALIGN_LEFT;
            a2.Add(Environment.NewLine);
            //a2.SpacingAfter = 5;
            doc.Add(a2);

            p1 = new Phrase("             Сумма техники: " + Convert.ToString(sumT),
                            new iTextSharp.text.Font(baseFont, 14,
                                                     iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black)));
            a2 = new Paragraph(p1);
            doc.Add(a2);

            p1 = new Phrase("             Сумма мебели: " + Convert.ToString(sumM),
                            new iTextSharp.text.Font(baseFont, 14,
                                                     iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black)));
            a2 = new Paragraph(p1);

            doc.Add(a2);

            p1 = new Phrase("             Общая сумма: " + Convert.ToString(sumM + sumT + sumSM),
                            new iTextSharp.text.Font(baseFont, 14,
                                                     iTextSharp.text.Font.BOLD, new BaseColor(Color.Black)));
            a2 = new Paragraph(p1);

            a2.SpacingAfter = 30;
            doc.Add(a2);
            a2.SpacingAfter = 30;
            DateTime second = DateTime.Now;

            Phrase p2 = new Phrase("Дата формирования заказа: " + second,
                                   new iTextSharp.text.Font(baseFont, 12,
                                                            iTextSharp.text.Font.ITALIC, new BaseColor(Color.Black)));

            a2           = new Paragraph(p2);
            a2.Alignment = Element.ALIGN_RIGHT;
            doc.Add(a2);

            doc.Close();
        }
Ejemplo n.º 28
0
        private void GerarPDF3(object o, EventArgs e)
        {
            //Cria O documento
            Document  doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 10, 35);
            PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("Pedido.pdf", FileMode.Create));

            doc.Open();
            //Adiciona o logo
            iTextSharp.text.Image PNG = iTextSharp.text.Image.GetInstance("Logo.png");
            PNG.ScalePercent(85f);
            doc.Add(PNG);
            //Titulo
            Paragraph header = new Paragraph("Informações do Pedido ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 14f, iTextSharp.text.Font.BOLD, BaseColor.BLACK));

            header.Alignment = Element.ALIGN_LEFT;
            doc.Add(header);


            //Info sobre venda
            var blackListTextFont = FontFactory.GetFont("Calibri_BOLD", 14, BaseColor.BLACK);
            var redListTextFont   = FontFactory.GetFont("Calibri", 12, BaseColor.BLACK);

            //Cli:

            iTextSharp.text.Image cliente = iTextSharp.text.Image.GetInstance("User_32px.png");
            cliente.ScaleToFit(20f, 20f);
            Chunk imageCliente = new Chunk(cliente, 0, -4);

            var titleChunk       = new Chunk("  Cliente: ", blackListTextFont);
            var descriptionChunk = new Chunk(txtCliente.Text + "\n", redListTextFont);
            var phrase           = new Phrase(imageCliente);

            phrase.Add(titleChunk);
            phrase.Add(descriptionChunk);
            doc.Add(phrase);



            //Funcionario
            iTextSharp.text.Image image3 = iTextSharp.text.Image.GetInstance("User_32px.png");
            image3.ScaleToFit(20f, 20f);
            Chunk imageChunk3 = new Chunk(image3, 0, -4);

            var FuncionarioChunk     = new Chunk("  Funcionário Responsavel: ", blackListTextFont);
            var nomeFuncionarioChunk = new Chunk(txtVendedor.Text + "\n", redListTextFont);
            var phraseFuncionario    = new Phrase(imageChunk3);

            phraseFuncionario.Add(FuncionarioChunk);
            phraseFuncionario.Add(nomeFuncionarioChunk);
            doc.Add(phraseFuncionario);


            //ValorDaVenda

            iTextSharp.text.Image image2 = iTextSharp.text.Image.GetInstance("Duration Finance_50px.png");
            image2.ScaleToFit(20f, 20f);
            Chunk imageChunk2       = new Chunk(image2, 0, -4);
            var   titleChunk2       = new Chunk("  Valor do Pedido: ", blackListTextFont);
            var   descriptionChunk2 = new Chunk(lblValorTotalDaVenda.Text + "\n", redListTextFont);
            var   phrase2           = new Phrase(imageChunk2);

            phrase2.Add(titleChunk2);
            phrase2.Add(descriptionChunk2);
            doc.Add(phrase2);

            //DataVenda

            iTextSharp.text.Image imagemData = iTextSharp.text.Image.GetInstance("Schedule_50px.png");
            imagemData.ScaleToFit(20f, 20f);
            Chunk imagemChunkData   = new Chunk(imagemData, 0, -4);
            var   titleChunk3       = new Chunk("  Data do Pedido: ", blackListTextFont);
            var   descriptionChunk3 = new Chunk(Convert.ToString(DateTime.Now) + "\n", redListTextFont);
            var   phrase3           = new Phrase(imagemChunkData);

            phrase3.Add(titleChunk3);
            phrase3.Add(descriptionChunk3);
            doc.Add(phrase3);


            //DataVenda



            //Frma
            iTextSharp.text.Image imagemPgto = iTextSharp.text.Image.GetInstance("Bank Cards_48px.png");
            imagemPgto.ScaleToFit(20f, 20f);
            Chunk imagemChunkPgto   = new Chunk(imagemPgto, 0, -6);
            var   titleChunk4       = new Chunk("  Forma de pagamento: ", blackListTextFont);
            var   descriptionChunk4 = new Chunk(comboBox1.Text + "\n", redListTextFont);
            var   phrase4           = new Phrase(imagemChunkPgto);

            phrase4.Add(titleChunk4);
            phrase4.Add(descriptionChunk4);
            doc.Add(phrase4);


            //INfo Entrega
            Paragraph header1 = new Paragraph("Informações da Entrega ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 14f, iTextSharp.text.Font.BOLD, BaseColor.BLACK));

            header.Alignment = Element.ALIGN_LEFT;
            doc.Add(header1);



            //Endereço da entrega
            iTextSharp.text.Image imagemEnd2 = iTextSharp.text.Image.GetInstance("User_32px.png");
            imagemEnd2.ScaleToFit(20f, 20f);
            Chunk imagemChunkEnd2 = new Chunk(imagemEnd2, 0, -6);
            var   titleChunckEnd2 = new Chunk("  Nome do destinatario : ", blackListTextFont);
            // BuscarDestinatario();
            var DescriptionEnd2 = new Chunk(NomeDestinatarioPrint + "\n", redListTextFont);
            var phraseEnd2      = new Phrase(imagemChunkEnd2);

            phraseEnd2.Add(titleChunckEnd2);
            phraseEnd2.Add(DescriptionEnd2);
            doc.Add(phraseEnd2);



            iTextSharp.text.Image imagemEnd = iTextSharp.text.Image.GetInstance("icons8_Marker_64px_1.png");
            imagemEnd.ScaleToFit(20f, 20f);
            Chunk imagemChunkEnd = new Chunk(imagemEnd, 0, -6);
            var   titleChunckEnd = new Chunk("  Endereço de entrega: ", blackListTextFont);
            // BuscarDestinatario();
            var DescriptionEnd = new Chunk(EnderecoDestinatarioPrint + "\n" + "\n", redListTextFont);
            var phraseEnd      = new Phrase(imagemChunkEnd);

            phraseEnd.Add(titleChunckEnd);
            phraseEnd.Add(DescriptionEnd);
            doc.Add(phraseEnd);



            iTextSharp.text.Image imagemData1 = iTextSharp.text.Image.GetInstance("Schedule_50px.png" + "\n");
            imagemData1.ScaleToFit(20f, 20f);
            Chunk    imagemChunkData1 = new Chunk(imagemData, 0, -4);
            var      titleChunk31     = new Chunk("  Data de Entrega: ", blackListTextFont);
            DateTime date             = DateTime.Today.AddDays(10);


            var descriptionChunk31 = new Chunk(date.ToString("dd/MM/yyyy"), redListTextFont);
            var phrase31           = new Phrase(imagemChunkData1);

            phrase31.Add(titleChunk31);
            phrase31.Add(descriptionChunk31);
            doc.Add(phrase31);



            //Titulo2
            Paragraph paragraph = new Paragraph("Produtos do Pedido \n              ", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 20f, iTextSharp.text.Font.BOLD, BaseColor.BLACK));

            paragraph.Alignment = Element.ALIGN_CENTER;
            doc.Add(paragraph);


            //Produtos da venda

            PdfPTable table = new PdfPTable(dataGridView1.Columns.Count);

            //table.AddCell(cell);

            for (int i = 0; i < dataGridView1.Columns.Count; i++)
            {
                table.AddCell(new Phrase(dataGridView1.Columns[i].HeaderText, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 9f, iTextSharp.text.Font.BOLD, BaseColor.BLACK)));
            }
            table.HeaderRows = 1;
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                for (int k = 0; k < dataGridView1.Columns.Count; k++)
                {
                    if (dataGridView1[k, i].Value != null)
                    {
                        table.AddCell(new Phrase(dataGridView1[k, i].Value.ToString(), new iTextSharp.text.Font(iTextSharp.text.Font.NORMAL, 8f, iTextSharp.text.Font.NORMAL, BaseColor.BLACK)));
                    }
                }
            }

            doc.Add(table);
            //Finaliza o pdf
            doc.Close();

            //Abre o Pdf Gerado
            System.Diagnostics.Process.Start("Pedido.pdf");
        }
Ejemplo n.º 29
0
        public void statToPDF(List <Auto> autok, DateTime date)
        {
            using (SaveFileDialog fd = new SaveFileDialog())
            {
                fd.CheckPathExists = fd.AddExtension = true;
                fd.Filter          = "PDF fájl|*.pdf";
                if (fd.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        iTextSharp.text.Font fon    = FontFactory.GetFont("c:\\Windows\\Fonts\\arial.ttf", BaseFont.IDENTITY_H, true, Font.Size);
                        iTextSharp.text.Font bold   = FontFactory.GetFont("c:\\Windows\\Fonts\\arialbd.ttf", BaseFont.IDENTITY_H, true, Font.Size);
                        Document             doc    = new Document(PageSize.A4, 30, 30, 72, 72);
                        PdfWriter            writer = PdfWriter.GetInstance(doc, new FileStream(fd.FileName, FileMode.Create, FileAccess.Write));

                        doc.Open();

                        Phrase w_cim  = new Phrase("Összes cím", bold);
                        Phrase w_rend = new Phrase("Rendszám", bold);
                        Phrase w_km   = new Phrase("Összes km", bold);
                        Phrase w_kolt = new Phrase("Összes költség", bold);
                        Phrase w_cso  = new Phrase("Összes csőhossz", bold);

                        PdfPTable table = new PdfPTable(5);
                        PdfPCell  cell  = new PdfPCell(new Phrase("Járműstatisztika " + date.ToShortDateString(), bold));
                        cell.Colspan             = 5;
                        cell.HorizontalAlignment = 1;
                        cell.Border        = 0;
                        cell.PaddingBottom = 20f;
                        table.AddCell(cell);

                        cell = new PdfPCell(w_rend);
                        cell.BackgroundColor     = iTextSharp.text.Color.LIGHT_GRAY;
                        cell.HorizontalAlignment = 1;
                        table.AddCell(cell);

                        cell = new PdfPCell(w_cim);
                        cell.BackgroundColor     = iTextSharp.text.Color.LIGHT_GRAY;
                        cell.HorizontalAlignment = 1;
                        table.AddCell(cell);

                        cell = new PdfPCell(w_km);
                        cell.BackgroundColor     = iTextSharp.text.Color.LIGHT_GRAY;
                        cell.HorizontalAlignment = 1;
                        table.AddCell(cell);

                        cell = new PdfPCell(w_kolt);
                        cell.BackgroundColor     = iTextSharp.text.Color.LIGHT_GRAY;
                        cell.HorizontalAlignment = 1;
                        table.AddCell(cell);

                        cell = new PdfPCell(w_cso);
                        cell.BackgroundColor     = iTextSharp.text.Color.LIGHT_GRAY;
                        cell.HorizontalAlignment = 1;
                        table.AddCell(cell);

                        float[] vals = new float[4];

                        foreach (Auto auto in autok)
                        {
                            table.AddCell(new Phrase(auto.Info, fon));
                            cell     = new PdfPCell(new Phrase(auto.OsszCim.ToString(), fon));
                            vals[0] += auto.OsszCim;
                            cell.HorizontalAlignment = 1;
                            table.AddCell(cell);
                            cell = new PdfPCell(new Phrase(auto.OsszTavolsag.ToString(), fon));
                            cell.HorizontalAlignment = 1;
                            vals[1] += auto.OsszTavolsag;
                            table.AddCell(cell);
                            cell = new PdfPCell(new Phrase(auto.Csohossz.ToString(), fon));
                            cell.HorizontalAlignment = 1;
                            vals[2] += auto.Csohossz;
                            table.AddCell(cell);
                            cell = new PdfPCell(new Phrase(auto.OsszKoltseg.ToString(), fon));
                            cell.HorizontalAlignment = 1;
                            vals[3] += auto.OsszKoltseg;
                            table.AddCell(cell);
                        }

                        cell = new PdfPCell(new Phrase("Mindösszesen:", bold));
                        table.AddCell(cell);

                        for (int a = 0; a < 4; a++)
                        {
                            cell = new PdfPCell(new Phrase(vals[a].ToString(), bold));
                            cell.HorizontalAlignment = 1;
                            table.AddCell(cell);
                        }

                        cell                     = new PdfPCell(new Phrase("Telítettségi cél %: " + Properties.Settings.Default.telitettCel.ToString(), bold));
                        cell.Colspan             = 5;
                        cell.HorizontalAlignment = 1;
                        cell.Border              = 0;
                        cell.PaddingTop          = 20f;
                        table.AddCell(cell);

                        doc.Add(table);
                        doc.Close();

                        MessageBox.Show("A mentés sikerült!", "Mentés kész", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (Exception e)
                    {
                        AppLogger.WriteException(e);
                        MessageBox.Show("A mentés nem sikerült!", "Hiba", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
Ejemplo n.º 30
0
    /// <summary>
    /// Exporta un archivo en formato PDF para que el usuario lo pueda descargar
    /// </summary>
    /// <param name="archivo">El archivo que se desea exportar</param>
    public void ExportarPdf(ArchivoDTO archivo, bool rotar)
    {
        HttpContext.Current.Response.ContentType = "application/pdf";
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + archivo.Nombre + ".pdf");
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);

        StringWriter   stringWriter   = new StringWriter();
        HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);

        stringWriter.Write(archivo.Datos);
        //StringReader stringReader = new StringReader(stringWriter.ToString());

        Document pdfDoc = new Document(rotar ? PageSize.A4.Rotate() : PageSize.A4, 20, 10, 10, 10);

        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

        PdfWriter.GetInstance(pdfDoc, HttpContext.Current.Response.OutputStream);
        pdfDoc.Open();

        PdfPTable t = new PdfPTable(2);

        t.SetWidthPercentage(new Single[] { 20F, 50F }, PageSize.A4);
        t.WidthPercentage = 98;

        /// HEADER
        Phrase texto = new Phrase();

        iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(AppDomain.CurrentDomain.BaseDirectory + "App_Themes\\Imagenes\\logo_Anses_Impresion.PNG");
        logo.ScaleAbsolute(50f, 30f);
        logo.SetAbsolutePosition(10, 800);

        iTextSharp.text.Font font_Bold = FontFactory.GetFont("arial", 18, iTextSharp.text.Font.BOLD);
        Paragraph            parrafo   = new Paragraph();

        if (archivo.Titulo.Contains("\n"))
        {
            Phrase p = new Phrase();
            p.Add(new Chunk(@archivo.Titulo, font_Bold));
            parrafo.Add(p);
            parrafo.Alignment = Element.ALIGN_RIGHT;
        }
        else
        {
            parrafo           = new Paragraph(@archivo.Titulo, font_Bold);
            parrafo.Alignment = Element.ALIGN_CENTER;
        }

        parrafo.SpacingBefore = 0;
        parrafo.SpacingAfter  = 0;
        parrafo.Add(logo);
        pdfDoc.Add(parrafo);

        using (TextReader htmlViewReader = new StringReader(stringWriter.ToString()))
        {
            using (var htmlWorker = new HTMLWorkerExtended(pdfDoc))
            {
                htmlWorker.Open();
                htmlWorker.Parse(htmlViewReader);
            }
        }

        pdfDoc.Close();
        HttpContext.Current.Response.Write(pdfDoc);
        HttpContext.Current.Response.OutputStream.Flush();
    }
Ejemplo n.º 31
0
        private static void PrintReceipt(TransactionMgnt.TxCylinder tx, CustomerMgntRef.Customer c)
        {
            Distributor dis     = new Distributor();
            string      disName = dis.AgencyName;
            string      disCode = dis.code.ToString();
            string      addr    = dis.Address + ", " + dis.City + "\n" + "District: " + dis.District + ", State: " + dis.State;
            string      phon    = dis.ContectNo;
            string      gstin   = dis.GSTIN;

            int    cashmemo  = tx.CashMemoNo;
            int    custNo    = tx.CustomerId;
            string custName  = tx.CustomerName;
            string date      = tx.TxDate.ToShortDateString();
            string custoAddr = c.Address + ", " + c.City + "\nDistrict: " + c.District + ", State: " + c.State + "-" + c.PinNo;

            string prod   = tx.CylinderDetails;
            int    qty    = tx.Quentity;
            double price  = tx.Price;
            double amount = tx.Amount;
            double cgst   = tx.CGST;
            double sgst   = tx.SGST;
            double totle  = tx.Total;


            try
            {
                #region Page
                #region Section-1

                iTextSharp.text.Font fontH1 = new iTextSharp.text.Font(BaseFont.CreateFont(
                                                                           BaseFont.TIMES_ROMAN,
                                                                           BaseFont.CP1252,
                                                                           BaseFont.EMBEDDED), 8, iTextSharp.text.Font.NORMAL);

                var boldFont = FontFactory.GetFont(FontFactory.TIMES_BOLD, 8);

                PdfPTable pdfTable1 = new PdfPTable(1);//Here 1 is Used For Count of Column
                PdfPTable pdfTable2 = new PdfPTable(4);
                PdfPTable pdfTable3 = new PdfPTable(4);

                pdfTable1.WidthPercentage = 100;
                pdfTable1.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
                pdfTable1.DefaultCell.VerticalAlignment   = Element.ALIGN_CENTER;
                pdfTable1.DefaultCell.BorderWidth         = 0;

                pdfTable2.WidthPercentage = 100;
                pdfTable2.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
                pdfTable2.DefaultCell.VerticalAlignment   = Element.ALIGN_CENTER;
                pdfTable2.DefaultCell.BorderWidth         = 0;

                pdfTable3.WidthPercentage = 100;
                pdfTable3.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
                pdfTable3.DefaultCell.VerticalAlignment   = Element.ALIGN_CENTER;
                pdfTable3.DefaultCell.BorderWidth         = 0.5f;

                int[] firstTablecellwidth = { 7, 43, 7, 43 };
                pdfTable2.SetWidths(firstTablecellwidth);
                string imageURL = @"./../Debug/Bill/logo.png";
                iTextSharp.text.Image myImage = iTextSharp.text.Image.GetInstance(imageURL);
                myImage.ScaleToFit(38f, 38f);
                myImage.SpacingBefore = 5f;
                myImage.SpacingAfter  = 10f;


                PdfPCell cellWithRowspan = new PdfPCell(myImage);
                cellWithRowspan.BorderWidth         = 0.0f;
                cellWithRowspan.Rowspan             = 3;
                cellWithRowspan.HorizontalAlignment = Element.ALIGN_RIGHT;

                pdfTable2.AddCell(cellWithRowspan);


                Chunk c1 = new Chunk(disName + " (" + disCode + ") ", FontFactory.GetFont("Times New Roman"));
                c1.Font.Color = new iTextSharp.text.BaseColor(255, 0, 0);
                c1.Font.SetStyle(0);
                c1.Font.Size = 10;
                Phrase p1 = new Phrase();
                p1.Add(c1);
                pdfTable2.AddCell(p1);
                pdfTable2.AddCell(cellWithRowspan);
                Chunk c11 = new Chunk(disName + " (" + disCode + ") ", FontFactory.GetFont("Times New Roman"));
                c11.Font.Color = new iTextSharp.text.BaseColor(0, 0, 255);
                c11.Font.SetStyle(0);
                c11.Font.Size = 10;
                Phrase p11 = new Phrase();
                p11.Add(c11);
                pdfTable2.AddCell(p11);

                Chunk c2 = new Chunk(addr, FontFactory.GetFont("Times New Roman"));
                c2.Font.Color = new iTextSharp.text.BaseColor(0, 0, 0);
                c2.Font.SetStyle(0);//0 For Normal Font
                c2.Font.Size = 8;
                Phrase p2 = new Phrase();
                p2.Add(c2);
                pdfTable2.AddCell(p2);
                pdfTable2.AddCell(p2);

                Chunk c3 = new Chunk("Phone No : " + phon + " | GSTIN : " + gstin + "\n\n", FontFactory.GetFont("Times New Roman"));
                c3.Font.Color = new iTextSharp.text.BaseColor(0, 0, 0);
                c3.Font.SetStyle(0);
                c3.Font.Size = 8;
                Phrase p3 = new Phrase();
                p3.Add(c3);
                pdfTable2.AddCell(p3);
                pdfTable2.AddCell(p3);
                #endregion


                #region section Table

                pdfTable3.AddCell(new Phrase("Cashmemo No.: ", fontH1));
                pdfTable3.AddCell(new Phrase(cashmemo + "", fontH1));
                pdfTable3.AddCell(new Phrase("Cashmemo No.: ", fontH1));
                pdfTable3.AddCell(new Phrase(cashmemo + "", fontH1));

                pdfTable3.AddCell(new Phrase("Customer ID: ", fontH1));
                pdfTable3.AddCell(new Phrase(custNo + "", fontH1));
                pdfTable3.AddCell(new Phrase("Customer ID: ", fontH1));
                pdfTable3.AddCell(new Phrase(custNo + "", fontH1));

                pdfTable3.AddCell(new Phrase("Customer Name: ", fontH1));
                pdfTable3.AddCell(new Phrase(custName + "", fontH1));
                pdfTable3.AddCell(new Phrase("Customer Name: ", fontH1));
                pdfTable3.AddCell(new Phrase(custName + "", fontH1));

                pdfTable3.AddCell(new Phrase("Transaction Date: ", fontH1));
                pdfTable3.AddCell(new Phrase(date + "", fontH1));
                pdfTable3.AddCell(new Phrase("Transaction Date: ", fontH1));
                pdfTable3.AddCell(new Phrase(date + "", fontH1));

                pdfTable3.AddCell(new Phrase("Address: ", fontH1));
                pdfTable3.AddCell(new Phrase(custoAddr + "", fontH1));
                pdfTable3.AddCell(new Phrase("Address: ", fontH1));
                pdfTable3.AddCell(new Phrase(custoAddr + "", fontH1));

                pdfTable3.AddCell(new Phrase("Product: ", fontH1));
                pdfTable3.AddCell(new Phrase(prod + "", fontH1));
                pdfTable3.AddCell(new Phrase("Product: ", fontH1));
                pdfTable3.AddCell(new Phrase(prod + "", fontH1));

                pdfTable3.AddCell(new Phrase("Price(Rs.): ", fontH1));
                pdfTable3.AddCell(new Phrase(price + "", fontH1));
                pdfTable3.AddCell(new Phrase("Price(Rs.): ", fontH1));
                pdfTable3.AddCell(new Phrase(price + "", fontH1));

                pdfTable3.AddCell(new Phrase("Quentity: ", fontH1));
                pdfTable3.AddCell(new Phrase(qty + "", fontH1));
                pdfTable3.AddCell(new Phrase("Quentity: ", fontH1));
                pdfTable3.AddCell(new Phrase(qty + "", fontH1));

                pdfTable3.AddCell(new Phrase("Amount (Quentity * Price) (Rs.): ", fontH1));
                pdfTable3.AddCell(new Phrase(amount + "", fontH1));
                pdfTable3.AddCell(new Phrase("Amount (Quentity * Price) (Rs.): ", fontH1));
                pdfTable3.AddCell(new Phrase(amount + "", fontH1));

                pdfTable3.AddCell(new Phrase("CGST(Rs.): ", fontH1));
                pdfTable3.AddCell(new Phrase(cgst + "", fontH1));
                pdfTable3.AddCell(new Phrase("CGST(Rs.): ", fontH1));
                pdfTable3.AddCell(new Phrase(cgst + "", fontH1));

                pdfTable3.AddCell(new Phrase("SGST(Rs.): ", fontH1));
                pdfTable3.AddCell(new Phrase(sgst + "", fontH1));
                pdfTable3.AddCell(new Phrase("SGST(Rs.): ", fontH1));
                pdfTable3.AddCell(new Phrase(sgst + "", fontH1));

                pdfTable3.AddCell(new Phrase("Total(Rs.): ", boldFont));
                pdfTable3.AddCell(new Phrase(totle + "", boldFont));
                pdfTable3.AddCell(new Phrase("Total(Rs.): ", boldFont));
                pdfTable3.AddCell(new Phrase(totle + "", boldFont));

                var cell = new PdfPCell(new Phrase("\n\n'Your Safety is our Priority' In case of Emergency Call 1906 \nFor any complaints / Queries call: 1800 - 233 - 3555(Toll Free)", fontH1));
                cell.Colspan = 2;
                pdfTable3.AddCell(cell);

                var cell1 = new PdfPCell(new Phrase("Declaration: I hereby confirm receipt of the filled LPG cylinder in sound condition and that the Cylinder was checked for weight & leakage.", fontH1));
                pdfTable3.AddCell(cell1);
                var cell2 = new PdfPCell(new Phrase("\n\n\n" + "\t\t" + "Signature of Customer", fontH1));
                cell2.HorizontalAlignment = Element.ALIGN_CENTER;
                pdfTable3.AddCell(cell2);

                #endregion

                #endregion


                SaveFileDialog sfd = new SaveFileDialog();
                sfd.InitialDirectory = @"C:\";
                sfd.RestoreDirectory = true;
                sfd.FileName         = cashmemo.ToString();
                sfd.DefaultExt       = "pdf";
                sfd.Filter           = "Pdf Files|*.pdf";
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    string path = sfd.FileName;
                    using (FileStream stream = new FileStream(path, FileMode.Create))
                    {
                        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
                        PdfWriter.GetInstance(pdfDoc, stream);
                        pdfDoc.Open();
                        #region PAGE-1
                        pdfDoc.Add(pdfTable1);
                        pdfDoc.Add(pdfTable2);
                        pdfDoc.Add(pdfTable3);
                        pdfDoc.NewPage();
                        #endregion

                        pdfDoc.Close();
                        stream.Close();
                    }
                    MessageBox.Show("Invoice is generated successfully!!!");
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Ejemplo n.º 32
0
 /// <summary>
 /// Constructs a Paragraph with a certain Phrase.
 /// </summary>
 /// <param name="phrase">a Phrase</param>
 public Paragraph(Phrase phrase)
     : base(phrase)
 {
     if (phrase is Paragraph) {
         Paragraph p = (Paragraph)phrase;
         Alignment = p.Alignment;
         ExtraParagraphSpace = p.ExtraParagraphSpace;
         FirstLineIndent = p.FirstLineIndent;
         IndentationLeft = p.IndentationLeft;
         IndentationRight = p.IndentationRight;
         SpacingAfter = p.SpacingAfter;
         SpacingBefore = p.SpacingBefore;
     }
 }
    public byte[] PrintAppointmentInvoice(string invoiceId, string appointmentToken, string doctorName, 
        string appointmentDate, string appointmentTime)
    {
        Document document = new Document(PageSize.A4);
        Font NormalFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, Color.BLACK);
        using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
        {
            PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
            PdfPTable table = null;
            Phrase phrase = null;
            PdfPCell cell = null;
            Paragraph paragraph = null;
            Color color = null;

            document.Open();

            table = new PdfPTable(2);
            float[] widths = new float[] { 5f, 10f };
            table.SetWidths(widths);

            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(System.Web.HttpContext.Current.Server.MapPath("../images/logo.png"));
            image.ScaleAbsolute(80, 80);
            cell = new PdfPCell(image);
            cell.Border = Rectangle.NO_BORDER;
            table.AddCell(cell);

            phrase = new Phrase();
            phrase.Add(new Chunk("ABC Hospital\n\n", FontFactory.GetFont("Arial", 18, Font.BOLD, Color.RED)));
            phrase.Add(new Chunk("123, Bodakdev\n", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
            phrase.Add(new Chunk("Ahmedabad 380015\n", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
            phrase.Add(new Chunk("INDIA\n", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
            phrase.Add(new Chunk("Ph:- 9543289345\n", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
            phrase.Add(new Chunk("Website:- http://www.abchospital.com\n", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));

            cell = new PdfPCell(phrase);
            cell.Border = Rectangle.NO_BORDER;
            table.AddCell(cell);

            color = new Color(System.Drawing.ColorTranslator.FromHtml("#000000"));
            DrawLine(writer, 25f, document.Top - 110f, document.PageSize.Width - 25f, document.Top - 110f, color);
            DrawLine(writer, 25f, document.Top - 110f, document.PageSize.Width - 25f, document.Top - 110f, color);

            phrase = new Phrase();
            phrase.Add(new Chunk("APPOINTMENT INVOICE\n\n", FontFactory.GetFont("Arial", 16, Font.BOLD, Color.BLACK)));

            paragraph = new Paragraph();
            paragraph.Add(phrase);
            paragraph.Alignment = Element.ALIGN_CENTER;
            paragraph.SpacingBefore = 50;
            paragraph.SpacingAfter = 30;

            document.Add(table);
            document.Add(paragraph);

            table = new PdfPTable(2);
            phrase = new Phrase();
            phrase.Add(new Chunk("Invoice ID", FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk(invoiceId, FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk("Invoice Date", FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk(DateTime.Now.ToString(), FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk("Appointment Token", FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk(appointmentToken, FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk("Doctor", FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk(doctorName, FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk("Appointment Date", FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk(appointmentDate, FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk("Appointment Time", FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk(appointmentTime, FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            table.AddCell(cell);
            table.HorizontalAlignment = Element.ALIGN_CENTER;

            document.Add(table);

            DrawLine(writer, 25f, document.Top - 750f, document.PageSize.Width - 25f, document.Top - 750f, color);
            DrawLine(writer, 25f, document.Top - 750f, document.PageSize.Width - 25f, document.Top - 750f, color);

            document.Close();
            byte[] bytes = memoryStream.ToArray();
            using (FileStream fs = File.Create(System.Web.HttpContext.Current.Server.MapPath("../Invoice/Appointments/" + invoiceId + ".pdf")))
            {
                fs.Write(bytes, 0, (int)bytes.Length);
            }
            memoryStream.Close();
            return bytes;
        }
    }
Ejemplo n.º 34
0
 /** Adds a cell element.
  * @param phrase the <CODE>Phrase</CODE> to be added to the cell
  */
 public void addCell(Phrase phrase)
 {
     defaultCell.Phrase = phrase;
     addCell(defaultCell);
     defaultCell.Phrase = null;
 }
        public void PrintCollectionSchedule(List <GetPrintScheduleByDID_Result> results, ReportBuilderModel model)
        {
            MemoryStream workStream = new MemoryStream();
            Document     document   = new Document();

            PdfWriter.GetInstance(document, workStream).CloseStream = false;
            PdfPTable table = new PdfPTable(8);

            table.TotalWidth = 550f;
            //fix the absolute width of the table
            table.LockedWidth = true;
            //relative col widths in proportions - 1/3 and 2/3
            float[] widths = new float[] { 7f, 4f, 2f, 3f, 3f, 3f, 3f, 4f };
            table.SetWidths(widths);
            table.HorizontalAlignment = 0;
            //leave a gap before and after the table
            table.SpacingBefore = 10f;
            table.SpacingAfter  = 10f;
            Font     bold = new Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
            Phrase   p    = new Phrase(model.ReportHeading, bold);
            PdfPCell cell = new PdfPCell(p);

            cell.BackgroundColor     = new iTextSharp.text.BaseColor(51, 192, 192);
            cell.Colspan             = 8;
            cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
            cell.VerticalAlignment   = 1;
            table.AddCell(cell);

            Font     b             = new Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 10, Font.BOLD);
            Phrase   reportSummary = new Phrase(string.Format("Collection Schedule on : {0}", DateTime.Now.Date.ToShortDateString()), b);
            PdfPCell cellHeading   = new PdfPCell(reportSummary);

            cellHeading.BackgroundColor     = new iTextSharp.text.BaseColor(192, 192, 192);
            cellHeading.Colspan             = 8;
            cellHeading.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
            cellHeading.VerticalAlignment   = 1;
            table.AddCell(cellHeading);

            //Add Branch and Total Amount
            Phrase   branchSummary = new Phrase(string.Format("Branch: {0} Schedule Date : {1} Actual Paid : {2}", model.BranchName, model.ScheduleDate, model.ActualPaid), b);
            PdfPCell cellHeading1  = new PdfPCell(branchSummary);

            cellHeading1.BackgroundColor     = new iTextSharp.text.BaseColor(192, 192, 192);
            cellHeading1.Colspan             = 8;
            cellHeading1.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
            cellHeading1.VerticalAlignment   = 1;
            table.AddCell(cellHeading1);

            PdfPCell cellBranchName = new PdfPCell(new Phrase("CL Code/Name"));

            cellBranchName.BackgroundColor = new iTextSharp.text.BaseColor(192, 192, 192);
            table.AddCell(cellBranchName);

            PdfPCell cellClientName = new PdfPCell(new Phrase("EMI Date"));

            cellClientName.BackgroundColor = new iTextSharp.text.BaseColor(192, 192, 192);
            table.AddCell(cellClientName);

            PdfPCell cellAmountPaid = new PdfPCell(new Phrase("EMI"));

            cellAmountPaid.BackgroundColor = new iTextSharp.text.BaseColor(192, 192, 192);
            table.AddCell(cellAmountPaid);

            PdfPCell cellPaymentDate = new PdfPCell(new Phrase("InstallNo"));

            cellPaymentDate.BackgroundColor = new iTextSharp.text.BaseColor(192, 192, 192);
            table.AddCell(cellPaymentDate);

            PdfPCell cellPrincipleAmount = new PdfPCell(new Phrase("Amt Paid"));

            cellPrincipleAmount.BackgroundColor = new iTextSharp.text.BaseColor(192, 192, 192);
            table.AddCell(cellPrincipleAmount);

            PdfPCell cellInterestAmount = new PdfPCell(new Phrase("Balance"));

            cellInterestAmount.BackgroundColor = new iTextSharp.text.BaseColor(192, 192, 192);
            table.AddCell(cellInterestAmount);


            PdfPCell cellSignature = new PdfPCell(new Phrase("Sign"));

            cellSignature.BackgroundColor = new iTextSharp.text.BaseColor(192, 192, 192);
            table.AddCell(cellSignature);

            PdfPCell cellAdditonalRemark = new PdfPCell(new Phrase("Remark"));

            cellAdditonalRemark.BackgroundColor = new iTextSharp.text.BaseColor(192, 192, 192);
            table.AddCell(cellAdditonalRemark);


            long?totalInstallment            = results.Max(x => x.EMINumber);
            GetPrintScheduleByDID_Result row = results.FirstOrDefault(x => x.ActualPaidAmount != 0);
            decimal?balance           = row.ActualPaidAmount;
            decimal?amountPaidTillNow = 0;
            decimal remainBalanceAll  = 0;

            foreach (Data.GetPrintScheduleByDID_Result item in results.ToList())
            {
                table.AddCell(item.ClientCode + " / " + item.ClientName);

                table.AddCell(item.EMIDate.Value.ToShortDateString());

                table.AddCell(item.EMI.ToString());

                table.AddCell(item.EMINumber.ToString() + " / " + totalInstallment);

                table.AddCell(item.AmountPaid.ToString());

                amountPaidTillNow += item.AmountPaid;
                decimal remainBalance = balance.Value - amountPaidTillNow.Value;
                remainBalanceAll = remainBalance;
                table.AddCell(remainBalance.ToString());

                table.AddCell(".............");

                table.AddCell(".............");
            }


            //Final Row summary
            table.AddCell(" ");

            table.AddCell(" ");

            table.AddCell("Total");

            table.AddCell(" - ");

            table.AddCell(amountPaidTillNow.ToString());

            table.AddCell(remainBalanceAll.ToString());

            table.AddCell(" ");

            table.AddCell(" ");


            document.Open();
            document.Add(table);
            document.Add(new Paragraph(DateTime.Now.ToString()));
            document.Close();

            byte[] byteInfo = workStream.ToArray();
            workStream.Write(byteInfo, 0, byteInfo.Length);
            workStream.Position = 0;
            Response.Buffer     = true;
            Response.AddHeader("Content-Disposition", "attachment; filename= " + Server.HtmlEncode(string.Format("CollectionSchedule_{0}.pdf", DateTime.Now.Date.ToShortDateString())));
            Response.ContentType = "APPLICATION/pdf";
            Response.BinaryWrite(byteInfo);
        }
Ejemplo n.º 36
0
        public void GerarRelatorio(Lancamento lancamentoGerar)
        {
            iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.A4, 40, 40, 40, 80);
            doc.AddCreationDate();

            Directory.CreateDirectory(System.AppDomain.CurrentDomain.BaseDirectory + @"\Relatorios");

            string nomeRelatorio = "relatorio_" + lancamentoGerar.Id + "_" + lancamentoGerar.Id + DateTime.Now.Millisecond + ".pdf";
            string caminho       = System.AppDomain.CurrentDomain.BaseDirectory + @"\Relatorios\" + nomeRelatorio;

            // exception interna porém é possível continuar
            PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream(caminho, FileMode.OpenOrCreate));

            doc.Open();

            // Título inicial
            Paragraph paragrafo = new Paragraph("", new Font(Font.NORMAL, 12))
            {
                Alignment = Element.ALIGN_LEFT,
                Font      = new Font(Font.FontFamily.TIMES_ROMAN, 13, 1)
            };

            paragrafo.Add("Relatório de Decisão");
            doc.Add(paragrafo);

            paragrafo.Clear();

            // Data
            paragrafo.Font = new Font(Font.FontFamily.TIMES_ROMAN, 11, 1)
            {
                Color = new BaseColor(128, 128, 128)
            };

            paragrafo.Add("Data : " + DateTime.Now.ToString());
            doc.Add(paragrafo);

            paragrafo.Clear();

            doc.Add(new Paragraph(" "));
            LineSeparator line = new LineSeparator(1f, 100f, new BaseColor(0, 0, 0), Element.ALIGN_LEFT, 1);

            doc.Add(line);

            // Dados lançamento
            paragrafo.Font = new Font(Font.FontFamily.TIMES_ROMAN, 12, 1);

            // nome
            var firstFont  = new Font(Font.FontFamily.TIMES_ROMAN, 12, 1);
            var secondFont = FontFactory.GetFont("Times New Roman", 12, new BaseColor(128, 128, 128));

            Chunk  title;
            Chunk  description;
            Phrase phrase;

            title       = new Chunk("Nome da decisão : ", firstFont);
            description = new Chunk(lancamentoGerar.Nome, secondFont);

            phrase = new Phrase(title)
            {
                description
            };

            phrase.Add("\n");
            doc.Add(phrase);

            // descrição
            title       = new Chunk("Descrição da decisão : ", firstFont);
            description = new Chunk(lancamentoGerar.Descricao, secondFont);

            phrase = new Phrase(title)
            {
                description
            };

            phrase.Add("\n");
            doc.Add(phrase);

            // data
            title       = new Chunk("Data da decisão : ", firstFont);
            description = new Chunk(lancamentoGerar.Data, secondFont);

            phrase = new Phrase(title)
            {
                description
            };

            phrase.Add("\n");
            doc.Add(phrase);

            // modelo
            title       = new Chunk("Modelo utilizado : ", firstFont);
            description = new Chunk(lancamentoGerar.Modelo.Nome, secondFont);

            phrase = new Phrase(title)
            {
                description
            };

            phrase.Add("\n");
            doc.Add(phrase);

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

            // Tabela 1
            paragrafo.Font      = new Font(Font.FontFamily.TIMES_ROMAN, 12, 1);
            paragrafo.Alignment = Element.ALIGN_CENTER;

            paragrafo.Add("Tabela 1 - Informações sobre os elementos");
            doc.Add(paragrafo);
            doc.Add(new Paragraph(" "));

            PdfPTable table = new PdfPTable(1 + lancamentoGerar.Modelo.Criterios.Count);

            table.AddCell(new Phrase(new Chunk("Nome", new Font(Font.FontFamily.TIMES_ROMAN, 12, 1))));

            foreach (var criterio in lancamentoGerar.Modelo.Criterios)
            {
                table.AddCell(new Phrase(new Chunk(criterio.Nome, new Font(Font.FontFamily.TIMES_ROMAN, 12, 1))));
            }

            foreach (var element in lancamentoGerar.Elementos)
            {
                table.AddCell(element.Nome);

                foreach (var criterio in element.Criterios)
                {
                    table.AddCell(Convert.ToString(criterio.Importancia));
                }
            }

            doc.Add(table);

            doc.Add(new Paragraph(" "));
            doc.Add(line);
            paragrafo.Clear();

            // Tabela 2
            paragrafo.Font      = new Font(Font.FontFamily.TIMES_ROMAN, 12, 1);
            paragrafo.Alignment = Element.ALIGN_CENTER;

            paragrafo.Add("Tabela 2 - Dados da tomada de decisão");
            doc.Add(paragrafo);
            doc.Add(new Paragraph(" "));

            table = new PdfPTable(2);

            table.AddCell(new Phrase(new Chunk("Nome", new Font(Font.FontFamily.TIMES_ROMAN, 12, 1))));
            table.AddCell(new Phrase(new Chunk("Peso", new Font(Font.FontFamily.TIMES_ROMAN, 12, 1))));

            foreach (var element in lancamentoGerar.ItensDecisao.OrderByDescending(entry => entry.Peso))
            {
                table.AddCell(element.Nome);
                table.AddCell(Convert.ToString(element.Peso));
            }

            doc.Add(table);

            doc.Close();
            System.Diagnostics.Process.Start(caminho);
        }
Ejemplo n.º 37
0
        public string crearPDF(CartaD v, string spr, bool aprob)
        {
            string ruta = "";

            using (TruequeEntities db = new TruequeEntities())
            {
                HeaderFooterD hfClass       = new HeaderFooterD(v);
                DateTime      fechaCreacion = DateTime.Now;
                string        nombreArchivo = string.Format("{0}.pdf", fechaCreacion.ToString(@"yyyyMMdd") + "_" + fechaCreacion.ToString(@"HHmmss"));
                string        rutaCompleta  = HttpContext.Current.Server.MapPath("~/PdfTemp/" + nombreArchivo);
                FileStream    fsDocumento   = new FileStream(rutaCompleta, FileMode.Create);
                //PASO UNO DEMINIMOS EL TIPO DOCUMENTO CON LOS RESPECTIVOS MARGENES (A4,IZQ,DER,TOP,BOT)
                Document  pdfDoc    = new Document(PageSize.A4, 30f, 30f, 40f, 100f);
                PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, fsDocumento);
                pdfWriter.PageEvent = new HeaderFooterD();
                var text = db.TEXTOCVs.Where(x => x.SPRAS_ID == spr);

                try
                {
                    pdfDoc.Open();
                    Paragraph frase1, frase2;

                    if (v.company_x)
                    {
                        frase1 = new Paragraph(v.company, negritaPeque);
                        a      = 18;
                    }
                    else
                    {
                        frase1 = new Paragraph("", negritaPeque);
                        a      = 0;
                    }

                    if (!aprob)
                    {
                        float fontSize = 250;
                        if (spr == "ES")
                        {
                            fontSize = 165;
                        }
                        float          xPosition = 300;
                        float          yPosition = 400;
                        float          angle     = 45;
                        PdfContentByte under     = pdfWriter.DirectContentUnder;
                        BaseFont       baseFont  = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
                        under.BeginText();
                        under.SetColorFill(BaseColor.LIGHT_GRAY);
                        under.SetFontAndSize(baseFont, fontSize);
                        under.ShowTextAligned(PdfContentByte.ALIGN_CENTER, text.Where(x => x.CAMPO == "agua").First().TEXTO, xPosition, yPosition, angle);
                        under.EndText();
                    }


                    frase1.Alignment = Element.ALIGN_RIGHT;
                    pdfDoc.Add(frase1);
                    pdfDoc.Add(new Chunk(""));

                    if (v.taxid_x)
                    {
                        frase2 = new Paragraph(v.taxid, negritaPeque);
                        b      = 18;
                    }
                    else
                    {
                        frase2 = new Paragraph("", negritaPeque);
                        b      = 0;
                    }
                    frase2.Alignment = Element.ALIGN_RIGHT;
                    pdfDoc.Add(frase2);
                    r = a + b;

                    //AQUI VA LA LINEA 2
                    pdfDoc.Add(new Chunk(""));
                    PdfPTable tabColor    = new PdfPTable(5);
                    PdfPCell  celdaColor  = new PdfPCell(new Paragraph(""));
                    PdfPCell  celdaColor2 = new PdfPCell(new Paragraph(""));
                    PdfPCell  celdaColor3 = new PdfPCell(new Paragraph(""));
                    PdfPCell  celdaColor4 = new PdfPCell(new Paragraph(""));
                    PdfPCell  celdaColor5 = new PdfPCell(new Paragraph(""));
                    celdaColor.BackgroundColor  = new BaseColor(181, 25, 70);
                    celdaColor2.BackgroundColor = new BaseColor(150, 23, 46);
                    celdaColor3.BackgroundColor = new BaseColor(238, 175, 48);
                    celdaColor4.BackgroundColor = new BaseColor(224, 0, 52);
                    celdaColor5.BackgroundColor = new BaseColor(252, 217, 0);
                    celdaColor.FixedHeight      = 10f;
                    tabColor.AddCell(celdaColor);
                    tabColor.AddCell(celdaColor2);
                    tabColor.AddCell(celdaColor3);
                    tabColor.AddCell(celdaColor4);
                    tabColor.AddCell(celdaColor5);
                    tabColor.SetWidthPercentage(new float[] { 400, 50, 80, 25, 110 }, PageSize.A4);
                    for (int i = 0; i < tabColor.Rows.Count; i++)
                    {
                        if (i <= 4)
                        {
                            hfClass.quitaBordes(i, tabColor);
                        }
                    }
                    pdfDoc.Add(tabColor);

                    //AQUI EMPIEZA APARTADO DE DATOS
                    pdfDoc.Add(new Chunk(""));
                    tablaDatos1.HorizontalAlignment = Element.ALIGN_LEFT;
                    tablaDatos1.SetWidthPercentage(new float[] { 298, 298 }, PageSize.A4);

                    if (v.concepto_x)
                    {
                        PdfPCell celda1 = new PdfPCell(new Paragraph(v.concepto, negritaPeque)); celda1.Border = 0; tablaDatos1.AddCell(celda1);
                    }
                    else
                    {
                        PdfPCell celda1 = new PdfPCell(new Paragraph("", negritaPeque)); celda1.Border = 0; tablaDatos1.AddCell(celda1);
                    }

                    if (v.folio_x)
                    {
                        PdfPCell celda2 = new PdfPCell(new Paragraph(text.Where(x => x.CAMPO == "folio").Select(x => x.TEXTO).First() + " " + v.folio, negritaPeque)); celda2.HorizontalAlignment = Element.ALIGN_RIGHT; celda2.Border = 0; tablaDatos1.AddCell(celda2);
                    }
                    else
                    {
                        PdfPCell celda2 = new PdfPCell(new Paragraph("", normalPeque)); celda2.HorizontalAlignment = Element.ALIGN_RIGHT; celda2.Border = 0; tablaDatos1.AddCell(celda2);
                    }

                    PdfPCell celdaB1 = new PdfPCell(new Paragraph("\n", negritaPeque)); celdaB1.Border = 0; tablaDatos1.AddCell(celdaB1);
                    PdfPCell celdaB2 = new PdfPCell(new Paragraph("\n", negritaPeque)); celdaB2.Border = 0; tablaDatos1.AddCell(celdaB2);

                    if (v.payerNom_x)
                    {
                        PdfPCell celda3 = new PdfPCell(new Paragraph(v.payerNom, negritaPeque)); celda3.Border = 0; tablaDatos1.AddCell(celda3);
                    }
                    else
                    {
                        PdfPCell celda3 = new PdfPCell(new Paragraph("", normalPeque)); celda3.Border = 0; tablaDatos1.AddCell(celda3);
                    }

                    if (v.lugarFech_x)
                    {
                        PdfPCell celda4 = new PdfPCell(new Paragraph(v.lugarFech, negritaPeque)); celda4.HorizontalAlignment = Element.ALIGN_RIGHT; celda4.Border = 0; tablaDatos1.AddCell(celda4);
                    }
                    else
                    {
                        PdfPCell celda4 = new PdfPCell(new Paragraph("", normalPeque)); celda4.HorizontalAlignment = Element.ALIGN_RIGHT; celda4.Border = 0; tablaDatos1.AddCell(celda4);
                    }

                    if (v.cliente_x)
                    {
                        PdfPCell celda5 = new PdfPCell(new Paragraph(v.cliente, negritaPeque)); celda5.Border = 0; tablaDatos1.AddCell(celda5);
                    }
                    else
                    {
                        PdfPCell celda5 = new PdfPCell(new Paragraph("", negritaPeque)); celda5.Border = 0; tablaDatos1.AddCell(celda5);
                    }

                    if (v.lugar_x)
                    {
                        PdfPCell celda6 = new PdfPCell(new Paragraph(v.lugar, negritaPeque)); celda6.HorizontalAlignment = Element.ALIGN_RIGHT; celda6.Border = 0; tablaDatos1.AddCell(celda6);
                    }
                    else
                    {
                        PdfPCell celda6 = new PdfPCell(new Paragraph("", negritaPeque)); celda6.HorizontalAlignment = Element.ALIGN_RIGHT; celda6.Border = 0; tablaDatos1.AddCell(celda6);
                    }

                    if (v.puesto_x)
                    {
                        PdfPCell celda7 = new PdfPCell(new Paragraph(v.puesto, normalPeque)); celda7.Border = 0; tablaDatos1.AddCell(celda7);
                    }
                    else
                    {
                        PdfPCell celda7 = new PdfPCell(new Paragraph("", normalPeque)); celda7.Border = 0; tablaDatos1.AddCell(celda7);
                    }

                    if (v.payerId_x)
                    {
                        PdfPCell celda8 = new PdfPCell(new Paragraph(text.Where(x => x.CAMPO == "control").Select(x => x.TEXTO).First(), negritaPeque)); celda8.BackgroundColor = new BaseColor(204, 204, 204); tablaDatos1.AddCell(celda8);
                    }
                    else
                    {
                        PdfPCell celda8 = new PdfPCell(new Paragraph("", negritaPeque)); celda8.Border = 0; tablaDatos1.AddCell(celda8);
                    }

                    if (v.direccion_x)
                    {
                        PdfPCell celda9 = new PdfPCell(new Paragraph(v.direccion, normalPeque)); celda9.Border = 0; tablaDatos1.AddCell(celda9);
                    }
                    else
                    {
                        PdfPCell celda9 = new PdfPCell(new Paragraph("", normalPeque)); celda9.Border = 0; tablaDatos1.AddCell(celda9);
                    }

                    if (v.payerId_x)
                    {
                        PdfPCell celda10 = new PdfPCell(new Paragraph(text.Where(x => x.CAMPO == "payer").Select(x => x.TEXTO).First() + " " + v.payerId, normalPeque)); tablaDatos1.AddCell(celda10);
                    }
                    else
                    {
                        PdfPCell celda10 = new PdfPCell(new Paragraph("", normalPeque)); celda10.Border = 0; tablaDatos1.AddCell(celda10);
                    }

                    pdfDoc.Add(tablaDatos1);

                    //APARTIR DE AQUI VA EL ESTIMADO
                    pdfDoc.Add(new Chunk("\n"));
                    Phrase fraseEstimado = new Phrase();

                    if (v.estimado_x)
                    {
                        fraseEstimado.Add(new Paragraph(text.Where(x => x.CAMPO == "estimado").Select(x => x.TEXTO).First() + " " + v.estimado, negritaPeque));
                    }
                    else
                    {
                        fraseEstimado.Add("");
                    }
                    pdfDoc.Add(fraseEstimado);

                    //APARTIR DE AQUI VA LA MECANICA
                    pdfDoc.Add(new Chunk("\n"));
                    pdfDoc.Add(new Chunk("\n"));
                    Phrase miFrase = new Phrase();

                    if (v.mecanica_x)
                    {
                        miFrase.Add(new Paragraph(v.mecanica, normalPeque));
                    }
                    else
                    {
                        miFrase.Add("");
                    }
                    pdfDoc.Add(miFrase);

                    //AQUI COMIENZAN LAS TABLAS
                    //1.- TABLA DE MATERIALES
                    int tablas = v.listaFechas.Count;      //SE RECIBE LA N CANTIDAD DE TABLAS A GENERAR
                    int cols   = v.numColEncabezado.Count; // SE RECIBE LA CANTIDAD DE COLUMNAS A CONTENER LA TABLA
                    int tamaño = 0;
                    try                                    //B20180720P MGC 2018.07.25
                    {
                        tamaño = 600 / cols;
                    }
                    catch (Exception)
                    {
                        tamaño = 0;
                    }

                    for (int a = 0; a < tablas; a++)
                    {
                        PdfPTable tablasN = new PdfPTable(cols);

                        if (cols == 1)
                        {
                            tablasN.SetWidthPercentage(new float[] { tamaño }, PageSize.A4);
                        }
                        else if (cols == 2)
                        {
                            tablasN.SetWidthPercentage(new float[] { tamaño, tamaño }, PageSize.A4);
                        }
                        else if (cols == 3)
                        {
                            tablasN.SetWidthPercentage(new float[] { tamaño, tamaño, tamaño }, PageSize.A4);
                        }
                        else if (cols == 4)
                        {
                            tablasN.SetWidthPercentage(new float[] { tamaño, tamaño, tamaño, tamaño }, PageSize.A4);
                        }
                        else if (cols == 5)
                        {
                            tablasN.SetWidthPercentage(new float[] { tamaño, tamaño, tamaño, tamaño, tamaño }, PageSize.A4);
                        }
                        else if (cols == 6)
                        {
                            tablasN.SetWidthPercentage(new float[] { tamaño, tamaño, tamaño, tamaño, tamaño, tamaño }, PageSize.A4);
                        }
                        else if (cols == 7)
                        {
                            tablasN.SetWidthPercentage(new float[] { tamaño, tamaño, tamaño, tamaño, tamaño, tamaño, tamaño }, PageSize.A4);
                        }
                        else if (cols == 8)
                        {
                            tablasN.SetWidthPercentage(new float[] { tamaño, tamaño, tamaño, tamaño, tamaño, tamaño, tamaño, tamaño }, PageSize.A4);
                        }
                        else if (cols == 9)
                        {
                            tablasN.SetWidthPercentage(new float[] { tamaño, tamaño, tamaño, tamaño, tamaño, tamaño, tamaño, tamaño, tamaño }, PageSize.A4);
                        }
                        else if (cols == 10)
                        {
                            tablasN.SetWidthPercentage(new float[] { tamaño, tamaño, tamaño, tamaño, tamaño, tamaño, tamaño, tamaño, tamaño, tamaño }, PageSize.A4);
                        }

                        PdfPCell rangoFecha = new PdfPCell(new Paragraph(text.Where(x => x.CAMPO == "de").Select(x => x.TEXTO).First() + " " + v.listaFechas[a].Remove(10) + " " + text.Where(x => x.CAMPO == "a").Select(x => x.TEXTO).First() + " " + (v.listaFechas[a].Remove(0, v.listaFechas[a].Length / 2)).Remove(10)));
                        rangoFecha.Border  = 0;
                        rangoFecha.Colspan = cols;
                        tablasN.AddCell(rangoFecha);

                        foreach (var celCabecera in v.numColEncabezado)
                        {
                            PdfPCell celdaCabeza = new PdfPCell();
                            celdaCabeza.AddElement(new Paragraph(celCabecera, letraTabNegrita));
                            celdaCabeza.BackgroundColor = new BaseColor(204, 204, 204);
                            tablasN.AddCell(celdaCabeza);
                        }

                        int columnas = 0;
                        int filas    = 0;
                        columnas = cols;
                        filas    = v.numfilasTabla[a];

                        for (int i = 0; i < filas; i++)
                        {
                            for (int j = 0; j < columnas; j++)
                            {
                                tablasN.AddCell(new Paragraph(v.listaCuerpo[pos], letraTab));
                                pos++;
                            }
                        }

                        pdfDoc.Add(tablasN);
                        pdfDoc.Add(new Chunk("\n"));
                    }

                    //APARTIR DE AQUI VA EL MONTO
                    miFrase.Clear();
                    if (v.monto_x)
                    {
                        miFrase.Add(new Paragraph(text.Where(x => x.CAMPO == "monto").Select(x => x.TEXTO).First() + " " + v.monto + " " + v.moneda, normalPeque));
                    }
                    else
                    {
                        miFrase.Add("");
                    }
                    pdfDoc.Add(miFrase);

                    //APARTIR DE AQUI VA LA SEGUNDA TABLA
                    //2.- TABLA DE RECURRENCIAS
                    if (v.secondTab_x)
                    {
                        pdfDoc.Add(new Paragraph(text.Where(x => x.CAMPO == "tituloRec").Select(x => x.TEXTO).First(), negritaPeque));
                        pdfDoc.Add(new Chunk("\n"));
                        int       cols2    = v.numColEncabezado2.Count;
                        int       tamaño2  = 600 / cols2;
                        PdfPTable tablasN2 = new PdfPTable(cols2);

                        if (cols2 == 5)
                        {
                            tablasN2.SetWidthPercentage(new float[] { tamaño2, tamaño2, tamaño2, tamaño2, tamaño2 }, PageSize.A4);
                        }
                        else if (cols2 == 4)
                        {
                            tablasN2.SetWidthPercentage(new float[] { tamaño2, tamaño2, tamaño2, tamaño2 }, PageSize.A4);
                        }

                        foreach (var celCabecera2 in v.numColEncabezado2)
                        {
                            PdfPCell celdaCabeza2 = new PdfPCell();
                            celdaCabeza2.AddElement(new Paragraph(celCabecera2, letraTabNegrita));
                            celdaCabeza2.BackgroundColor = new BaseColor(204, 204, 204);
                            tablasN2.AddCell(celdaCabeza2);
                        }

                        for (int i = 0; i < v.numfilasTabla2; i++)
                        {
                            for (int j = 0; j < cols2; j++)
                            {
                                tablasN2.AddCell(new Paragraph(v.listaCuerpoRec[pos2], letraTab));
                                pos2++;
                            }
                        }

                        pdfDoc.Add(tablasN2);
                        pdfDoc.Add(new Chunk("\n"));
                    }

                    //APARTIR DE AQUI VA LA TERCER TABLA
                    //2.- TABLA DE OBJETIVO Q
                    if (v.tercerTab_x)
                    {
                        pdfDoc.Add(new Paragraph(text.Where(x => x.CAMPO == "tituloObjQ").Select(x => x.TEXTO).First(), negritaPeque));
                        pdfDoc.Add(new Chunk("\n"));
                        int       cols3    = v.numColEncabezado3.Count;
                        int       tamano3  = 600 / cols3;
                        PdfPTable tablasN3 = new PdfPTable(cols3);

                        if (cols3 == 5)
                        {
                            tablasN3.SetWidthPercentage(new float[] { tamano3, tamano3, tamano3, tamano3, tamano3 }, PageSize.A4);
                        }

                        foreach (var celCabecera3 in v.numColEncabezado3)
                        {
                            PdfPCell celdaCabeza3 = new PdfPCell();
                            celdaCabeza3.AddElement(new Paragraph(celCabecera3, letraTabNegrita));
                            celdaCabeza3.BackgroundColor = new BaseColor(204, 204, 204);
                            tablasN3.AddCell(celdaCabeza3);
                        }

                        for (int i = 0; i < v.numfilasTabla3; i++)
                        {
                            for (int j = 0; j < cols3; j++)
                            {
                                tablasN3.AddCell(new Paragraph(v.listaCuerpoObjQ[pos3], letraTab));
                                pos3++;
                            }
                        }

                        pdfDoc.Add(tablasN3);
                        pdfDoc.Add(new Chunk("\n"));
                    }

                    //APARTIR DE AQUI VAN LAS FIRMAS
                    //LINEAS PARA LA FIRMA EN UNA TABLA
                    PdfPCell celFirma1 = new PdfPCell();
                    PdfPCell celFirma2 = new PdfPCell();

                    PdfPTable tabFirma1   = new PdfPTable(1);
                    PdfPCell  celFirmita1 = new PdfPCell();
                    if (v.nombreE_x || v.puestoE_x || v.companyC_x)
                    {
                        celFirmita1.AddElement(new Paragraph("\n", normalPeque)); celFirmita1.Border = 2;
                    }
                    else
                    {
                        celFirmita1.AddElement(new Paragraph("", normalPeque)); celFirmita1.Border = 0;
                    }
                    tabFirma1.AddCell(celFirmita1);
                    tabFirma1.SetWidthPercentage(new float[] { 450 }, PageSize.A4);

                    PdfPTable tabFirma2   = new PdfPTable(1);
                    PdfPCell  celFirmita2 = new PdfPCell();
                    if (v.nombreC_x || v.puestoC_x || v.companyCC_x)
                    {
                        celFirmita2.AddElement(new Paragraph("\n", normalPeque)); celFirmita2.Border = 2;
                    }
                    else
                    {
                        celFirmita2.AddElement(new Paragraph("", normalPeque)); celFirmita2.Border = 0;
                    }
                    tabFirma2.AddCell(celFirmita2);
                    tabFirma2.SetWidthPercentage(new float[] { 450 }, PageSize.A4);

                    celFirma1.AddElement(tabFirma1);
                    celFirma1.Border = 0;

                    celFirma2.AddElement(tabFirma2);
                    celFirma2.Border = 0;

                    tablaDatos2.AddCell(celFirma1);
                    tablaDatos2.AddCell(celFirma2);
                    tablaDatos2.SetWidthPercentage(new float[] { 300, 300 }, PageSize.A4);

                    pdfDoc.Add(tablaDatos2);

                    //DATOS PARA LAS FIRMAS
                    tablaDatos3.HorizontalAlignment = Element.ALIGN_LEFT;
                    tablaDatos3.SetWidthPercentage(new float[] { 298, 298 }, PageSize.A4);

                    if (v.nombreE_x)
                    {
                        PdfPCell celda1Dat3 = new PdfPCell(new Paragraph(v.nombreE, negritaPeque)); celda1Dat3.HorizontalAlignment = Element.ALIGN_CENTER; tablaDatos3.AddCell(celda1Dat3);
                    }
                    else
                    {
                        PdfPCell celda1Dat3 = new PdfPCell(new Paragraph("", negritaPeque)); celda1Dat3.HorizontalAlignment = Element.ALIGN_CENTER; tablaDatos3.AddCell(celda1Dat3);
                    }

                    if (v.nombreC_x)
                    {
                        PdfPCell celda2Dat3 = new PdfPCell(new Paragraph(v.nombreC, negritaPeque)); celda2Dat3.HorizontalAlignment = Element.ALIGN_CENTER; tablaDatos3.AddCell(celda2Dat3);
                    }
                    else
                    {
                        PdfPCell celda2Dat3 = new PdfPCell(new Paragraph("", negritaPeque)); celda2Dat3.HorizontalAlignment = Element.ALIGN_CENTER; tablaDatos3.AddCell(celda2Dat3);
                    }

                    if (v.puestoE_x)
                    {
                        PdfPCell celda3Dat3 = new PdfPCell(new Paragraph(v.puestoE, normalPeque)); celda3Dat3.HorizontalAlignment = Element.ALIGN_CENTER; tablaDatos3.AddCell(celda3Dat3);
                    }
                    else
                    {
                        PdfPCell celda3Dat3 = new PdfPCell(new Paragraph("", normalPeque)); celda3Dat3.HorizontalAlignment = Element.ALIGN_CENTER; tablaDatos3.AddCell(celda3Dat3);
                    }

                    if (v.puestoC_x)
                    {
                        PdfPCell celda4Dat3 = new PdfPCell(new Paragraph(v.puestoC, normalPeque)); celda4Dat3.HorizontalAlignment = Element.ALIGN_CENTER; tablaDatos3.AddCell(celda4Dat3);
                    }
                    else
                    {
                        PdfPCell celda4Dat3 = new PdfPCell(new Paragraph("", normalPeque)); celda4Dat3.HorizontalAlignment = Element.ALIGN_CENTER; tablaDatos3.AddCell(celda4Dat3);
                    }

                    if (v.companyC_x)
                    {
                        PdfPCell celda5Dat3 = new PdfPCell(new Paragraph(v.companyC, negritaPeque)); celda5Dat3.HorizontalAlignment = Element.ALIGN_CENTER; tablaDatos3.AddCell(celda5Dat3);
                    }
                    else
                    {
                        PdfPCell celda5Dat3 = new PdfPCell(new Paragraph("", negritaPeque)); celda5Dat3.HorizontalAlignment = Element.ALIGN_CENTER; tablaDatos3.AddCell(celda5Dat3);
                    }

                    if (v.companyCC_x)
                    {
                        PdfPCell celda6Dat3 = new PdfPCell(new Paragraph(v.companyCC, negritaPeque)); celda6Dat3.HorizontalAlignment = Element.ALIGN_CENTER; tablaDatos3.AddCell(celda6Dat3);
                    }
                    else
                    {
                        PdfPCell celda6Dat3 = new PdfPCell(new Paragraph("", negritaPeque)); celda6Dat3.HorizontalAlignment = Element.ALIGN_CENTER; tablaDatos3.AddCell(celda6Dat3);
                    }

                    for (int i = 0; i < tablaDatos3.Rows.Count; i++)
                    {
                        if (i <= 4)
                        {
                            hfClass.quitaBordes(i, tablaDatos3);
                        }
                    }
                    pdfDoc.Add(tablaDatos3);


                    //TABLA PARA LOS COMENTARIOS
                    pdfDoc.Add(new Chunk("\n"));
                    tabComentarios.HorizontalAlignment = Element.ALIGN_LEFT;
                    tabComentarios.SetWidthPercentage(new float[] { 300, 300 }, PageSize.A4);

                    if (v.comentarios_x)
                    {
                        PdfPCell celda1 = new PdfPCell(new Paragraph(v.comentarios, normalPeque)); celda1.Border = 0; tabComentarios.AddCell(celda1);
                    }
                    else
                    {
                        PdfPCell celda1 = new PdfPCell(new Paragraph("", normalPeque)); celda1.Border = 0; tabComentarios.AddCell(celda1);
                    }

                    if (v.compromisoK_x)
                    {
                        PdfPCell celda2 = new PdfPCell(new Paragraph(v.compromisoK, normalPeque)); celda2.Border = 0; tabComentarios.AddCell(celda2);
                    }
                    else
                    {
                        PdfPCell celda2 = new PdfPCell(new Paragraph("", normalPeque)); celda2.Border = 0; tabComentarios.AddCell(celda2);
                    }

                    if (v.compromisoC_x)
                    {
                        PdfPCell celda3 = new PdfPCell(new Paragraph("\n" + v.compromisoC, normalPeque)); celda3.Border = 0; tabComentarios.AddCell(celda3);
                    }
                    else
                    {
                        PdfPCell celda3 = new PdfPCell(new Paragraph("", normalPeque)); celda3.Border = 0; tabComentarios.AddCell(celda3);
                    }

                    PdfPCell celVacia = new PdfPCell(new Paragraph("", normalPeque));
                    celVacia.Border = 0;
                    tabComentarios.AddCell(celVacia);

                    pdfDoc.Add(tabComentarios);
                    pdfDoc.Close();
                    ruta = "/PdfTemp/" + nombreArchivo;
                }
                catch (Exception ex)
                {
                    Log.ErrorLogApp(ex, "CartaD", "Generar PDF");
                }
                return(ruta);
            }
        }
Ejemplo n.º 38
0
        public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)
        {
            base.OnEndPage(writer, document);
            iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
            iTextSharp.text.Font baseFontBig    = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);
            Phrase p1Header = new Phrase("Specimen", baseFontNormal);

            //Create PdfTable object
            PdfPTable pdfTab = new PdfPTable(3);

            //We will have to create separate cells to include image logo and 2 separate strings
            //Row 1
            PdfPCell pdfCell1 = new PdfPCell();
            PdfPCell pdfCell2 = new PdfPCell();
            PdfPCell pdfCell3 = new PdfPCell();
            String   text     = "Page " + writer.PageNumber + " of ";

            //Add paging to header
            {
                cb.BeginText();
                cb.SetFontAndSize(bf, 12);
                cb.SetTextMatrix(document.PageSize.GetRight(200), document.PageSize.GetTop(45));
                cb.ShowText(text);
                cb.EndText();
                float len = bf.GetWidthPoint(text, 12);
                //Adds "12" in Page 1 of 12
                cb.AddTemplate(headerTemplate, document.PageSize.GetRight(200) + len, document.PageSize.GetTop(45));
            }
            //Add paging to footer
            {
                cb.BeginText();
                cb.SetFontAndSize(bf, 12);
                cb.SetTextMatrix(document.PageSize.GetRight(180), document.PageSize.GetBottom(30));
                cb.ShowText(text);
                cb.EndText();
                float len = bf.GetWidthPoint(text, 12);
                cb.AddTemplate(footerTemplate, document.PageSize.GetRight(180) + len, document.PageSize.GetBottom(30));
            }

            //Row 2
            PdfPCell pdfCell4 = new PdfPCell(new Phrase("Sub Header Description", baseFontNormal));

            //Row 3
            PdfPCell pdfCell5 = new PdfPCell(new Phrase("Date:" + PrintTime.ToShortDateString(), baseFontBig));
            PdfPCell pdfCell6 = new PdfPCell();
            PdfPCell pdfCell7 = new PdfPCell(new Phrase("TIME:" + string.Format("{0:t}", DateTime.Now), baseFontBig));

            //set the alignment of all three cells and set border to 0
            pdfCell1.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell2.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell3.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell4.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell5.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell6.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell7.HorizontalAlignment = Element.ALIGN_CENTER;

            pdfCell2.VerticalAlignment = Element.ALIGN_BOTTOM;
            pdfCell3.VerticalAlignment = Element.ALIGN_MIDDLE;
            pdfCell4.VerticalAlignment = Element.ALIGN_TOP;
            pdfCell5.VerticalAlignment = Element.ALIGN_MIDDLE;
            pdfCell6.VerticalAlignment = Element.ALIGN_MIDDLE;
            pdfCell7.VerticalAlignment = Element.ALIGN_MIDDLE;

            pdfCell4.Colspan = 3;

            pdfCell1.Border = 0;
            pdfCell2.Border = 0;
            pdfCell3.Border = 0;
            pdfCell4.Border = 0;
            pdfCell5.Border = 0;
            pdfCell6.Border = 0;
            pdfCell7.Border = 0;

            //add all three cells into PdfTable
            pdfTab.AddCell(pdfCell1);
            pdfTab.AddCell(pdfCell2);
            pdfTab.AddCell(pdfCell3);
            pdfTab.AddCell(pdfCell4);
            pdfTab.AddCell(pdfCell5);
            pdfTab.AddCell(pdfCell6);
            pdfTab.AddCell(pdfCell7);

            pdfTab.TotalWidth      = document.PageSize.Width - 80f;
            pdfTab.WidthPercentage = 70;
            //pdfTab.HorizontalAlignment = Element.ALIGN_CENTER;

            //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, 40, document.PageSize.Height - 30, writer.DirectContent);
            //set pdfContent value

            //Move the pointer and draw line to separate header section from rest of page
            cb.MoveTo(40, document.PageSize.Height - 100);
            cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 100);
            cb.Stroke();

            //Move the pointer and draw line to separate footer section from rest of page
            cb.MoveTo(40, document.PageSize.GetBottom(50));
            cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50));
            cb.Stroke();
        }
Ejemplo n.º 39
0
        //"© " + DateTime.Now.Year.ToString() + " AllyAlign Health"
        public static void prepareHeaderFooter(Document document, PdfWriter writer, PdfContentByte cb, BaseFont helv, PdfTemplate total, float firstPageHeight, string docTitle, string copyright)
        {
            string page_num = "Page " + document.PageNumber.ToString();

            //We are going to add two strings in header. Create separate Phrase object with font setting and string to be included
            Phrase pTitle     = new Phrase(docTitle, FontFactory.GetFont("verdana", 20));
            Phrase pCopyright = new Phrase(copyright, FontFactory.GetFont("verdana", 12));
            Phrase pPageNum   = new Phrase(page_num, FontFactory.GetFont("verdana", 12));
            Phrase pPrintTime = new Phrase("Printed on " + DateTime.Now.ToString("hh:mm tt dddd, MMM dd, yyyy"), FontFactory.GetFont("verdana", 12));

            //Create PdfTable object
            PdfPTable pdfTabHeader  = new PdfPTable(1);
            PdfPCell  pdfCell1Title = new PdfPCell(pTitle);

            pdfCell1Title.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfCell1Title.Border    = 0;
            pdfTabHeader.TotalWidth = document.PageSize.Width - 40;
            pdfTabHeader.AddCell(pdfCell1Title);

            PdfPTable pdfTabFooter;

            if (firstPageHeight == document.PageSize.Height)
            {
                pdfTabFooter = new PdfPTable(3);
            }
            else
            {
                pdfTabFooter = new PdfPTable(1);
            }

            PdfPCell pdfCellCopyright = new PdfPCell(pCopyright);
            PdfPCell pdfPrintTime     = new PdfPCell(pPrintTime);
            PdfPCell pdfCellpPageNum  = new PdfPCell(pPageNum);

            pdfCellCopyright.HorizontalAlignment = Element.ALIGN_RIGHT;
            pdfPrintTime.HorizontalAlignment     = Element.ALIGN_CENTER;
            pdfCellpPageNum.HorizontalAlignment  = Element.ALIGN_LEFT;
            pdfCellCopyright.Border = 0;
            pdfPrintTime.Border     = 0;
            pdfCellpPageNum.Border  = 0;
            //add all three cells into PdfTable
            pdfTabFooter.AddCell(pdfCellpPageNum);

            if (firstPageHeight == document.PageSize.Height)
            {
                pdfTabFooter.AddCell(pdfPrintTime);
                pdfTabFooter.AddCell(pdfCellCopyright);
            }
            pdfTabFooter.TotalWidth = document.PageSize.Width - 40;
            //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
            if (firstPageHeight == document.PageSize.Height)
            {
                pdfTabHeader.WriteSelectedRows(0, -1, 20, document.PageSize.Height - 15, writer.DirectContent);
            }

            pdfTabFooter.WriteSelectedRows(0, -1, 20, 30, writer.DirectContent);
            //set pdfContent value
            PdfContentByte pdfContent;

            pdfContent = writer.DirectContent;
            //Move the pointer and draw line to separate header section from rest of page
            //Header Line
            if (firstPageHeight == document.PageSize.Height)
            {
                pdfContent.MoveTo(0, document.PageSize.Height - 50);
                pdfContent.LineTo(document.PageSize.Width - 0, document.PageSize.Height - 50);
            }

            //Footer Line
            pdfContent.MoveTo(0, 30);
            pdfContent.LineTo(document.PageSize.Width - 0, 30);

            pdfContent.Stroke();

            //**** Page Numbering
            cb.SaveState();
            string text     = "Page " + writer.PageNumber + " of ";
            float  textBase = document.Bottom - 20;
            float  textSize = 12; //helv.GetWidthPoint(text, 12);

            cb.BeginText();
            cb.SetFontAndSize(helv, 12);

            float adjust = helv.GetWidthPoint("0", 12);

            cb.SetTextMatrix(document.Left - textSize - adjust + 20, textBase);
            cb.ShowText("");
            cb.EndText();
            cb.AddTemplate(total, adjust, textBase);
            cb.RestoreState();
        }
Ejemplo n.º 40
0
        private void generarPDF(Recibo recibo)
        {
            try
            {
                // Cuadro de dialogo del sistema para guardar el PDF donde elija el usuario
                SaveFileDialog save = new SaveFileDialog();
                save.Filter           = "Archivo PDF|*.pdf";
                save.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                save.FileName         = "Recibo N° " + recibo.Id;

                if (save.ShowDialog() == DialogResult.OK)
                {
                    Document   doc = new Document(PageSize.A4);
                    FileStream fl  = new FileStream(save.FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
                    PdfWriter.GetInstance(doc, fl);

                    // Metadata (titulo y autor del archivo pdf)
                    doc.AddAuthor("Club Deportivo Vecinos Unidos");
                    doc.AddTitle("Recibo");
                    doc.Open();

                    // Imagen logo
                    iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance(@"C:\Users\pepa_\Documents\Visual Studio 2019\Projects\CDVU\CDVU\Resources\vecinos-unidos1.png");
                    imagen.BorderWidth = 0;
                    imagen.ScalePercent(20f);
                    imagen.Alignment = Element.ALIGN_RIGHT;

                    // Titulo
                    Paragraph titulo = new Paragraph("Recibo", FontFactory.GetFont("Calibri", 30));
                    titulo.Alignment = Element.ALIGN_CENTER;

                    // Tabla cabecera
                    PdfPTable tablaCabecera = new PdfPTable(2);
                    tablaCabecera.WidthPercentage = 100;

                    PdfPCell celda1 = new PdfPCell(titulo);
                    celda1.Border = 0;
                    celda1.HorizontalAlignment = 0;
                    celda1.VerticalAlignment   = 1;
                    tablaCabecera.AddCell(celda1);

                    PdfPCell celda2 = new PdfPCell(imagen);
                    celda2.Border = 0;
                    celda2.HorizontalAlignment = 2;
                    celda2.VerticalAlignment   = 1;
                    tablaCabecera.AddCell(celda2);

                    tablaCabecera.SpacingAfter = 15;
                    doc.Add(tablaCabecera);

                    PdfPTable tablaRecibo = new PdfPTable(1);
                    tablaRecibo.WidthPercentage = 100;

                    Phrase datosRecibo = new Phrase("DATOS DEL RECIBO");
                    datosRecibo.Font.Size = 12;
                    datosRecibo.Font.SetStyle("italic");
                    tablaRecibo.AddCell(datosRecibo);

                    // N° de Recibo
                    Phrase frase1 = new Phrase("Recibo N°: " + recibo.Id);
                    frase1.Font.Size = 10;
                    frase1.Font.SetStyle("bold");

                    PdfPCell renglon1 = new PdfPCell(frase1);
                    renglon1.Border = 0;
                    renglon1.HorizontalAlignment = 0;
                    renglon1.VerticalAlignment   = 1;
                    renglon1.Padding             = 5;
                    tablaRecibo.AddCell(renglon1);

                    // Fecha del recibo
                    Phrase frase2 = new Phrase("Fecha: " + recibo.Fecha.ToString("dd/MM/yyyy"));
                    frase2.Font.Size = 10;
                    frase2.Font.SetStyle("bold");

                    PdfPCell renglon2 = new PdfPCell(frase2);
                    renglon2.Border = 0;
                    renglon2.HorizontalAlignment = 0;
                    renglon2.VerticalAlignment   = 1;
                    renglon2.Padding             = 5;
                    tablaRecibo.AddCell(renglon2);

                    doc.Add(tablaRecibo);


                    // Datos del socio y recibo
                    PdfPTable tablaSocio = new PdfPTable(1);
                    tablaSocio.WidthPercentage = 100;

                    Phrase datosSocio = new Phrase("DATOS DEL SOCIO");
                    datosSocio.Font.Size = 12;
                    datosSocio.Font.SetStyle("italic");
                    tablaSocio.AddCell(datosSocio);

                    // Nombre del socio
                    Phrase frase3 = new Phrase("Nombre: " + recibo.Socio.Apellido + " " + recibo.Socio.Nombre);
                    frase3.Font.Size = 10;
                    frase3.Font.SetStyle("bold");

                    PdfPCell renglon3 = new PdfPCell(frase3);
                    renglon3.Border = 0;
                    renglon3.HorizontalAlignment = 0;
                    renglon3.VerticalAlignment   = 1;
                    renglon3.Padding             = 5;
                    tablaSocio.AddCell(renglon3);

                    // DNI del socio
                    Phrase frase4 = new Phrase("DNI: " + recibo.Socio.Dni);
                    frase4.Font.Size = 10;
                    frase4.Font.SetStyle("bold");

                    PdfPCell renglon4 = new PdfPCell(frase4);
                    renglon4.Border = 0;
                    renglon4.HorizontalAlignment = 0;
                    renglon4.VerticalAlignment   = 1;
                    renglon4.Padding             = 5;
                    tablaSocio.AddCell(renglon4);

                    // Teléfono del socio
                    Phrase frase5 = new Phrase("Teléfono: " + recibo.Socio.Telefono);
                    frase5.Font.Size = 10;
                    frase5.Font.SetStyle("bold");

                    PdfPCell renglon5 = new PdfPCell(frase5);
                    renglon5.Border = 0;
                    renglon5.HorizontalAlignment = 0;
                    renglon5.VerticalAlignment   = 1;
                    renglon5.Padding             = 5;
                    tablaSocio.AddCell(renglon5);

                    // Email del socio
                    Phrase frase6 = new Phrase("Email: " + recibo.Socio.Email);
                    frase6.Font.Size = 10;
                    frase6.Font.SetStyle("bold");

                    PdfPCell renglon6 = new PdfPCell(frase6);
                    renglon6.Border = 0;
                    renglon6.HorizontalAlignment = 0;
                    renglon6.VerticalAlignment   = 1;
                    renglon6.Padding             = 5;
                    tablaSocio.AddCell(renglon6);

                    // Tutor de este socio
                    if (recibo.Socio.Tutor == null)
                    {
                        Phrase frase7 = new Phrase("Tutor: No tiene");
                        frase7.Font.Size = 10;
                        frase7.Font.SetStyle("bold");

                        PdfPCell renglon7 = new PdfPCell(frase7);
                        renglon7.Border = 0;
                        renglon7.HorizontalAlignment = 0;
                        renglon7.VerticalAlignment   = 1;
                        renglon7.Padding             = 5;
                        tablaSocio.AddCell(renglon7);
                    }
                    else
                    {
                        Phrase frase7 = new Phrase("Tutor: " + recibo.Socio.Tutor.ToString());
                        frase7.Font.Size = 10;
                        frase7.Font.SetStyle("bold");

                        PdfPCell renglon7 = new PdfPCell(frase7);
                        renglon7.Border = 0;
                        renglon7.HorizontalAlignment = 0;
                        renglon7.Padding             = 5;
                        tablaSocio.AddCell(renglon7);
                    }

                    tablaSocio.SpacingBefore = 5;
                    tablaSocio.SpacingAfter  = 15;



                    // Datos de la inscripcion
                    Inscripcion inscripcion      = new GestorInscripcion().obtenerInscripcionPorIdRecibo(recibo.Id);
                    PdfPTable   tablaInscripcion = new PdfPTable(1);
                    tablaInscripcion.WidthPercentage = 100;

                    Phrase datosInscripcion = new Phrase("DATOS DE LA INSCRIPCIÓN");
                    datosInscripcion.Font.Size = 12;
                    datosInscripcion.Font.SetStyle("italic");
                    tablaInscripcion.AddCell(datosInscripcion);

                    // Fecha inscripcion
                    Phrase fechaInscripcion = new Phrase("Fecha inscripción: " + inscripcion.Fecha.ToString("dd/MM/yyyy"));
                    fechaInscripcion.Font.Size = 10;
                    fechaInscripcion.Font.SetStyle("bold");

                    PdfPCell renglon8 = new PdfPCell(fechaInscripcion);
                    renglon8.Border = 0;
                    renglon8.HorizontalAlignment = 0;
                    renglon8.VerticalAlignment   = 1;
                    renglon8.Padding             = 5;
                    tablaInscripcion.AddCell(renglon8);

                    // Deporte
                    Phrase deporte = new Phrase("Deporte: " + inscripcion.Entrenamiento.Deporte.ToString());
                    deporte.Font.Size = 10;
                    deporte.Font.SetStyle("bold");

                    PdfPCell renglon9 = new PdfPCell(deporte);
                    renglon9.Border = 0;
                    renglon9.HorizontalAlignment = 0;
                    renglon9.VerticalAlignment   = 1;
                    renglon9.Padding             = 5;
                    tablaInscripcion.AddCell(renglon9);

                    // Predio
                    Phrase predio = new Phrase("Predio: " + inscripcion.Entrenamiento.Predio.ToString());
                    predio.Font.Size = 10;
                    predio.Font.SetStyle("bold");

                    PdfPCell renglon10 = new PdfPCell(predio);
                    renglon10.Border = 0;
                    renglon10.HorizontalAlignment = 0;
                    renglon10.VerticalAlignment   = 1;
                    renglon10.Padding             = 5;
                    tablaInscripcion.AddCell(renglon10);

                    tablaInscripcion.SpacingBefore = 5;
                    tablaInscripcion.SpacingAfter  = 15;

                    // Tabla contenido
                    PdfPTable tablaContenido = new PdfPTable(2);
                    tablaContenido.WidthPercentage = 100;

                    PdfPCell cell1 = new PdfPCell(tablaSocio);
                    cell1.Border = 0;
                    cell1.HorizontalAlignment = 0;
                    cell1.VerticalAlignment   = 1;
                    tablaContenido.AddCell(cell1);

                    PdfPCell cell2 = new PdfPCell(tablaInscripcion);
                    cell2.Border = 0;
                    cell2.HorizontalAlignment = 2;
                    cell2.VerticalAlignment   = 1;
                    tablaContenido.AddCell(cell2);

                    tablaContenido.SpacingAfter = 10;
                    doc.Add(tablaContenido);

                    // Tabla y cabecera que contendra los datos de los pagos
                    PdfPTable tablaPago = new PdfPTable(3);
                    tablaPago.WidthPercentage = 100;

                    Phrase fraseColumna1 = new Phrase("N° de cuota");
                    fraseColumna1.Font.Color = BaseColor.WHITE;
                    fraseColumna1.Font.Size  = 11;
                    fraseColumna1.Font.SetStyle("bold");

                    Phrase fraseColumna2 = new Phrase("Descripción");
                    fraseColumna2.Font.Color = BaseColor.WHITE;
                    fraseColumna2.Font.Size  = 11;
                    fraseColumna2.Font.SetStyle("bold");

                    Phrase fraseColumna3 = new Phrase("Total");
                    fraseColumna3.Font.Color = BaseColor.WHITE;
                    fraseColumna3.Font.Size  = 11;
                    fraseColumna3.Font.SetStyle("bold");

                    PdfPCell columnaCabecera1 = new PdfPCell(fraseColumna1);
                    PdfPCell columnaCabecera2 = new PdfPCell(fraseColumna2);
                    PdfPCell columnaCabecera3 = new PdfPCell(fraseColumna3);

                    columnaCabecera1.BackgroundColor     = BaseColor.BLACK;
                    columnaCabecera1.Border              = 0;
                    columnaCabecera1.HorizontalAlignment = 1;
                    columnaCabecera1.VerticalAlignment   = 1;
                    columnaCabecera1.Padding             = 4;

                    columnaCabecera2.BackgroundColor     = BaseColor.BLACK;
                    columnaCabecera2.Border              = 0;
                    columnaCabecera2.HorizontalAlignment = 1;
                    columnaCabecera2.VerticalAlignment   = 1;
                    columnaCabecera2.Padding             = 4;

                    columnaCabecera3.BackgroundColor     = BaseColor.BLACK;
                    columnaCabecera3.Border              = 0;
                    columnaCabecera3.HorizontalAlignment = 1;
                    columnaCabecera3.VerticalAlignment   = 1;
                    columnaCabecera3.Padding             = 4;

                    tablaPago.AddCell(columnaCabecera1);
                    tablaPago.AddCell(columnaCabecera2);
                    tablaPago.AddCell(columnaCabecera3);

                    foreach (Pago p in gt.listaPagoSegunRecibo(recibo.Id))
                    {
                        // Agrego los datos de cada pago a la tabla

                        Phrase fraseCuota = new Phrase(p.NumeroCuota.ToString());
                        fraseCuota.Font.Color = BaseColor.BLACK;
                        fraseCuota.Font.Size  = 10;
                        fraseCuota.Font.SetStyle("bold");

                        Phrase fraseDescripcion = new Phrase(p.Descripcion);
                        fraseDescripcion.Font.Color = BaseColor.BLACK;
                        fraseDescripcion.Font.Size  = 10;
                        fraseDescripcion.Font.SetStyle("bold");

                        Phrase fraseTotal = new Phrase("$ " + p.Monto.ToString());
                        fraseTotal.Font.Color = BaseColor.BLACK;
                        fraseTotal.Font.Size  = 10;
                        fraseTotal.Font.SetStyle("bold");

                        PdfPCell filaCuota       = new PdfPCell(fraseCuota);
                        PdfPCell filaDescripcion = new PdfPCell(fraseDescripcion);
                        PdfPCell filaTotal       = new PdfPCell(fraseTotal);

                        filaCuota.BackgroundColor     = BaseColor.LIGHT_GRAY;
                        filaCuota.Border              = 0;
                        filaCuota.HorizontalAlignment = 1;
                        filaCuota.Padding             = 4;

                        filaDescripcion.BackgroundColor     = BaseColor.LIGHT_GRAY;
                        filaDescripcion.Border              = 0;
                        filaDescripcion.HorizontalAlignment = 1;
                        filaDescripcion.Padding             = 4;

                        filaTotal.BackgroundColor     = BaseColor.LIGHT_GRAY;
                        filaTotal.Border              = 0;
                        filaTotal.HorizontalAlignment = 1;
                        filaTotal.Padding             = 4;

                        tablaPago.AddCell(filaCuota);
                        tablaPago.AddCell(filaDescripcion);
                        tablaPago.AddCell(filaTotal);
                    }
                    tablaPago.SpacingAfter = 5;
                    doc.Add(tablaPago);

                    // Tabla para el total
                    PdfPTable tablaTotal = new PdfPTable(1);
                    tablaTotal.WidthPercentage = 100;

                    Phrase fraseTotalFinal = new Phrase("Total: $" + recibo.MontoTotal.ToString());
                    fraseTotalFinal.Font.Color = BaseColor.BLACK;
                    fraseTotalFinal.Font.Size  = 10;
                    fraseTotalFinal.Font.SetStyle("bold");

                    PdfPCell total = new PdfPCell(fraseTotalFinal);
                    total.BackgroundColor     = BaseColor.LIGHT_GRAY;
                    total.Border              = 0;
                    total.HorizontalAlignment = 2;
                    total.Padding             = 4;

                    tablaTotal.AddCell(total);
                    tablaTotal.SpacingAfter = 15;
                    doc.Add(tablaTotal);

                    Phrase generado = new Phrase("Archivo generado el día " + DateTime.Today.ToString("dd/MM/yyyy"));
                    generado.Font.Color = BaseColor.BLACK;
                    generado.Font.Size  = 7;
                    generado.Font.SetStyle("italic");
                    doc.Add(generado);

                    // Cierro el documento
                    doc.Close();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("No se pudo generar el pdf. \n" + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Ejemplo n.º 41
0
        private void bgworker_DoWork(object sender, DoWorkEventArgs e)
        {
            String    query = "", empid = "", loan_type = "", date_from = "", date_to = "", pay_code = "", table = "hr_rpt_files", filename = "", code = "", col = "", val = "", date_in = "";
            DataTable pay_period = null;

            Double total      = 0.00;
            String loan_query = "";

            query = "SELECT empid, firstname, lastname,pay_rate FROM rssys.hr_employee";
            cbo_employee.Invoke(new Action(() => {
                if (cbo_employee.SelectedIndex != -1)
                {
                    empid  = cbo_employee.SelectedValue.ToString();
                    query += " WHERE empid='" + empid + "'";
                }
            }));
            query += " ORDER BY empid ASC";


            DataTable employees = db.QueryBySQLCode(query);

            loan_query = "SELECT * FROM rssys.hr_loan_type";
            cbo_loan_type.Invoke(new Action(() =>
            {
                if (cbo_loan_type.SelectedIndex != -1)
                {
                    loan_type   = cbo_loan_type.SelectedValue.ToString();
                    loan_query += " WHERE code = '" + loan_type + "'";
                }
            }));
            DataTable dt_loan_type = db.QueryBySQLCode(loan_query);

            cbo_payollperiod.Invoke(new Action(() => {
                pay_code = cbo_payollperiod.SelectedValue.ToString();
            }));

            pay_period = get_date(pay_code);

            if (pay_period.Rows.Count > 0)
            {
                date_from = gm.toDateString(pay_period.Rows[0]["date_from"].ToString(), "yyyy-MM-dd");
                date_to   = gm.toDateString(pay_period.Rows[0]["date_to"].ToString(), "yyyy-MM-dd");
            }

            filename  = RandomString(5) + "_" + DateTime.Now.ToString("yyyy-MM-dd");
            filename += ".pdf";


            //System.IO.FileStream fs = new FileStream("\\\\RIGHTAPPS\\RightApps\\Eastland\\payroll_reports\\loan_summary\\" + filename, FileMode.Create);
            System.IO.FileStream fs = new FileStream(fileloc_dtr + "\\ViewController\\RPT\\Payroll\\loan_summary\\" + filename, FileMode.Create);

            Document document = new Document(PageSize.LEGAL, 25, 25, 30, 30);

            PdfWriter.GetInstance(document, fs);
            document.Open();

            BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

            iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 9, iTextSharp.text.Font.NORMAL);

            Paragraph paragraph = new Paragraph();

            paragraph.Alignment = Element.ALIGN_CENTER;
            paragraph.Font      = FontFactory.GetFont("Arial", 12);
            paragraph.SetLeading(1, 1);
            paragraph.Add("EMPLOYEE LOAN SUMMARY REPORTS");


            Phrase line_break = new Phrase("\n");

            document.Add(paragraph);
            document.Add(line_break);

            Paragraph paragraph_2 = new Paragraph();

            paragraph_2.Alignment = Element.ALIGN_CENTER;
            paragraph_2.Font      = FontFactory.GetFont("Arial", 12);
            paragraph_2.SetLeading(1, 1);
            paragraph_2.Add("For the payroll period " + date_from + " to " + date_to);


            Phrase line_break_2 = new Phrase("\n");

            document.Add(paragraph_2);
            document.Add(line_break_2);



            PdfPTable t = new PdfPTable(1);

            float[] widths = new float[] { 100 };
            t.WidthPercentage = 100;
            t.SetWidths(widths);

            PdfPTable dis_earnings = new PdfPTable(1);

            float[] _w2 = new float[] { 100f };
            dis_earnings.SetWidths(_w2);

            foreach (DataRow _employees in employees.Rows)
            {
                String fname = _employees["firstname"].ToString();
                String lname = _employees["lastname"].ToString();
                String empno = _employees["empid"].ToString();
                try
                {
                    foreach (DataRow _loan_type in dt_loan_type.Rows)
                    {
                        DataTable has_loan = db.QueryBySQLCode("SELECT employee_no FROM rssys.hr_loanhdr WHERE employee_no = '" + empno + "' AND loan_type = '" + _loan_type["code"].ToString() + "'");
                        if (has_loan != null && has_loan.Rows.Count > 0)
                        {
                            dis_earnings.AddCell(new PdfPCell(new Paragraph(fname + " " + lname))
                            {
                                Colspan = 2, Border = 2
                            });

                            DataTable hoe = db.QueryBySQLCode("SELECT DISTINCT(de.code) as code, de.description  FROM rssys.hr_loan_type de  LEFT JOIN rssys.hr_loanhdr od  ON de.code = od.loan_type WHERE od.employee_no = '" + empno + "'");

                            foreach (DataRow _hoe in hoe.Rows)
                            {
                                dis_earnings.AddCell(new PdfPCell(new Paragraph(_hoe["description"].ToString()))
                                {
                                    PaddingLeft = 30f, Colspan = 2, Border = 0
                                });
                                DataTable hee = db.QueryBySQLCode("SELECT * FROM rssys.hr_loanhdr WHERE loan_type = '" + _hoe["code"].ToString() + "' AND employee_no = '" + empno + "'");
                                foreach (DataRow _hee in hee.Rows)
                                {
                                    dis_earnings.AddCell(new PdfPCell(new Paragraph(_hee["loan_amount"].ToString()))
                                    {
                                        PaddingLeft = 40f, Colspan = 2, Border = 0
                                    });
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                empno = null;
            }

            document.Add(dis_earnings);
            document.Add(t);
            document.Close();

            code = db.get_pk("rpt_id");
            col  = "rpt_id,filename,date_added,rpt_type";
            val  = "'" + code + "','" + filename + "','" + DateTime.Now.ToShortDateString() + "','LOAN'";

            if (db.InsertOnTable(table, col, val))
            {
                db.set_pkm99("rpt_id", db.get_nextincrementlimitchar(code, 8)); //changes from 'hr_empid'
                MessageBox.Show("New summary reports created");
            }
            else
            {
                MessageBox.Show("Failed on saving.");
            }
            pic_loading.Invoke(new Action(() => {
                pic_loading.Visible = false;
                btn_submit.Enabled  = true;
            }));

            display_list();
        }
Ejemplo n.º 42
0
        private static void PrintSummary(Document document, ref PdfPTable table, List <ListGrowerTareItem> hdrList, bool isPreview)
        {
            table = PdfReports.CreateTable(_processSummaryLayout, 1);
            Paragraph p;
            Phrase    ph;

            if (isPreview)
            {
                p = new Paragraph("Note: Preview mode was active, so all documents were printed and none were emailed or faxed.\n\n", _normalFont);
                PdfReports.AddText2Table(table, p);
            }

            //-------------------
            // Printed
            //-------------------
            string prefixSep = "";
            Font   font      = _normalFont;

            p = new Paragraph("\nPrinted:\n", _labelFont);

            var mailList = hdrList.FindAll(item => item.RptType == "M");

            foreach (ListGrowerTareItem item in mailList)
            {
                if (String.IsNullOrEmpty(item.Success))
                {
                    ph = new Phrase(prefixSep + item.Contract_No + " (" +
                                    item.Delivery_Station_No + ": " + DateTime.Parse(item.Delivery_Date).ToString("MM/dd") + ")", _normalFont);
                }
                else
                {
                    ph = new Phrase(prefixSep + item.Contract_No + " (" +
                                    item.Delivery_Station_No + ": " +
                                    DateTime.Parse(item.Delivery_Date).ToString("MM/dd") + " : " + item.Success + ")", _failFont);
                }

                p.Add(ph);

                if (prefixSep.Length == 0)
                {
                    prefixSep = ", ";
                }
            }
            PdfReports.AddText2Table(table, p);

            //-------------------
            // Email
            //-------------------
            prefixSep = "";
            p         = new Paragraph("\nEmail:\n", _labelFont);

            var emailList = hdrList.FindAll(item => item.RptType == "E");

            foreach (ListGrowerTareItem item in emailList)
            {
                if (String.IsNullOrEmpty(item.Success))
                {
                    ph = new Phrase(prefixSep + item.Contract_No + " (" + item.Delivery_Station_No + ": " +
                                    DateTime.Parse(item.Delivery_Date).ToString("MM/dd") + ")", _normalFont);
                }
                else
                {
                    ph = new Phrase(prefixSep + item.Contract_No + " (" +
                                    item.Delivery_Station_No + ": " +
                                    DateTime.Parse(item.Delivery_Date).ToString("MM/dd") + " : " + item.Success + ")", _failFont);
                }

                p.Add(ph);

                if (prefixSep.Length == 0)
                {
                    prefixSep = ", ";
                }
            }
            PdfReports.AddText2Table(table, p);

            //-------------------
            // Fax
            //-------------------
            prefixSep = "";
            p         = new Paragraph("\nFax:\n", _labelFont);

            var faxList = hdrList.FindAll(item => item.RptType == "F");

            foreach (ListGrowerTareItem item in faxList)
            {
                if (String.IsNullOrEmpty(item.Success))
                {
                    ph = new Phrase(prefixSep + item.Contract_No + " (" +
                                    item.Delivery_Station_No + ": " + DateTime.Parse(item.Delivery_Date).ToString("MM/dd") + ")", _normalFont);
                }
                else
                {
                    ph = new Phrase(prefixSep + item.Contract_No + " (" +
                                    item.Delivery_Station_No + ": " +
                                    DateTime.Parse(item.Delivery_Date).ToString("MM/dd") + " : " + item.Success + ")", _failFont);
                }

                p.Add(ph);

                if (prefixSep.Length == 0)
                {
                    prefixSep = ", ";
                }
            }
            PdfReports.AddText2Table(table, p);

            //-------------------
            // Web View by Member
            //-------------------
            prefixSep = "";
            p         = new Paragraph("\nMember Web View (WSCI):\n", _labelFont);

            var webList = hdrList.FindAll(item => item.RptType == "W");

            foreach (ListGrowerTareItem item in webList)
            {
                if (String.IsNullOrEmpty(item.Success))
                {
                    ph = new Phrase(prefixSep + item.Contract_No + " (" +
                                    item.Delivery_Station_No + ": " + DateTime.Parse(item.Delivery_Date).ToString("MM/dd") + ")", _normalFont);
                }
                else
                {
                    ph = new Phrase(prefixSep + item.Contract_No + " (" +
                                    item.Delivery_Station_No + ": " +
                                    DateTime.Parse(item.Delivery_Date).ToString("MM/dd") + " : " + item.Success + ")", _failFont);
                }

                p.Add(ph);

                if (prefixSep.Length == 0)
                {
                    prefixSep = ", ";
                }
            }

            PdfReports.AddText2Table(table, p);
        }
Ejemplo n.º 43
0
        public static void SaveToDB(Phrase p)
        {
            using (SQLiteConnection conn = new SQLiteConnection(stringConnection))
            {
                conn.Open();
                using (SQLiteTransaction transaction = conn.BeginTransaction())
                {
                    SQLiteCommand command = new SQLiteCommand(conn);
                    command.Transaction = transaction;

                    English e = new English()
                    {
                        Sentence_eng = p.EnglishPhrase,
                        Sound_eng    = p.Sound
                    };

                    Russian r = new Russian()
                    {
                        Sentence_ru = p.RussianPhrase
                    };

                    command.CommandText = $"SELECT same_ru FROM russian WHERE sentence_ru = \"{r.Sentence_ru}\"";
                    e.Same_eng          = Convert.ToInt32(command.ExecuteScalar());

                    command.CommandText = $"SELECT same_eng FROM english WHERE sentence_eng = \"{e.Sentence_eng}\"";
                    r.Same_ru           = Convert.ToInt32(command.ExecuteScalar());


                    if (e.Same_eng > 0 && r.Same_ru == 0)
                    {
                        command.CommandText = $"SELECT same_russian FROM translate WHERE same_english == {e.Same_eng}";
                        r.Same_ru           = Convert.ToInt32(command.ExecuteScalar());
                    }

                    if (e.Same_eng == 0 && r.Same_ru > 0)
                    {
                        command.CommandText = $"SELECT same_english FROM translate WHERE same_russian == {r.Same_ru}";
                        e.Same_eng          = Convert.ToInt32(command.ExecuteScalar());
                    }


                    if (e.Same_eng == 0)
                    {
                        command.CommandText = $"SELECT same_eng FROM english ORDER BY same_eng DESC LIMIT 1";
                        int lastSame = Convert.ToInt32(command.ExecuteScalar());
                        e.Same_eng = lastSame + 1;
                    }

                    if (r.Same_ru == 0)
                    {
                        command.CommandText = $"SELECT same_ru FROM russian ORDER BY same_ru DESC LIMIT 1";
                        int lastSame = Convert.ToInt32(command.ExecuteScalar());
                        r.Same_ru = lastSame + 1;
                    }

                    if (e.Sound_eng == null || e.Sound_eng == "")
                    {
                        command.CommandText = $"INSERT OR IGNORE INTO english (sentence_eng, sound_eng, same_eng) VALUES (\"{e.Sentence_eng}\", null, {e.Same_eng})";
                        command.ExecuteNonQuery();
                    }
                    else
                    {
                        command.CommandText = $"INSERT OR IGNORE INTO english (sentence_eng, sound_eng, same_eng) VALUES (\"{e.Sentence_eng}\", \"{e.Sound_eng}\", {e.Same_eng})";
                        command.ExecuteNonQuery();
                    }

                    command.CommandText = $"INSERT OR IGNORE INTO russian (sentence_ru, same_ru) VALUES (\"{r.Sentence_ru}\", {r.Same_ru})";
                    command.ExecuteNonQuery();

                    Translate t = new Translate()
                    {
                        Same_English = e.Same_eng,
                        Same_Russian = r.Same_ru,
                        DateAdd      = DateTime.Now.ToString("yyyy.MM.dd")
                    };

                    command.CommandText = $"INSERT OR IGNORE INTO translate (same_english, same_russian, dateadd) VALUES ({t.Same_English}, {t.Same_Russian}, \"{t.DateAdd}\")";
                    command.ExecuteNonQuery();

                    transaction.Commit();
                }
                conn.Close();
            }

            //English english = new English();
            //Russian russian = new Russian();

            ////List<int> listAnalogEnglish = new List<int>();
            ////List<int> listAnalogRussian = new List<int>();

            //using (SQLiteConnection conn = new SQLiteConnection(stringConnection))
            //{
            //    conn.Open();
            //    using (SQLiteTransaction transaction = conn.BeginTransaction())
            //    {
            //        using (SQLiteCommand command = new SQLiteCommand(conn))
            //        {
            //            command.Transaction = transaction;
            //            command.CommandText = $"SELECT id FROM english WHERE {nameof(English.Sentence).ToString().ToLower()} = \"{phrase.EnglishPhrase}\"";
            //            object temp = command.ExecuteScalar();
            //            if (!(temp == null))
            //                english.ID = int.Parse(temp.ToString());

            //            command.CommandText = $"SELECT id FROM russian WHERE {nameof(Russian.Sentence).ToString().ToLower()} = \"{phrase.RussianPhrase}\"";
            //            temp = command.ExecuteScalar();
            //            if (!(temp == null))
            //                russian.ID = int.Parse(temp.ToString());
            //        }
            //        transaction.Commit();
            //    }
            //    conn.Close();
            //}

            //if (english.ID == 0)
            //{
            //    english.Sentence = phrase.EnglishPhrase;
            //    english.Sound = phrase.Sound;
            //    InsertRow(english);
            //}

            //if (russian.ID == 0)
            //{
            //    russian.Sentence = phrase.RussianPhrase;
            //    InsertRow(russian);
            //}

            ////using (SQLiteConnection conn = new SQLiteConnection(stringConnection))
            ////{
            ////    conn.Open();
            ////    using (SQLiteTransaction transaction = conn.BeginTransaction())
            ////    {
            ////        using (SQLiteCommand command = new SQLiteCommand(conn))
            ////        {
            ////            command.Transaction = transaction;
            ////            command.CommandText = $"SELECT id_english FROM translate WHERE id_russian IN (SELECT id_russian FROM translate WHERE {nameof(Translate.ID_English).ToString().ToLower()} = \"{english.ID}\")";
            ////            using (SQLiteDataReader reader = command.ExecuteReader())
            ////            {
            ////                while (reader.Read())
            ////                {
            ////                    int id = Convert.ToInt32(reader[nameof(Translate.ID_English).ToString().ToLower()]);
            ////                    listAnalogEnglish.Add(id);
            ////                }
            ////            }

            ////            command.CommandText = $"SELECT id_russian FROM translate WHERE id_english IN (SELECT id_english FROM translate WHERE {nameof(Translate.ID_Russian).ToString().ToLower()} = \"{russian.ID}\")";
            ////            using (SQLiteDataReader reader = command.ExecuteReader())
            ////            {
            ////                while (reader.Read())
            ////                {
            ////                    int id = Convert.ToInt32(reader[nameof(Translate.ID_Russian).ToString().ToLower()]);
            ////                    listAnalogRussian.Add(id);
            ////                }
            ////            }
            ////        }
            ////        transaction.Commit();
            ////    }
            ////    conn.Close();
            ////}

            //Translate trans = new Translate();
            //trans.Same_English = english.Same;
            //trans.Same_Russian = russian.Same;
            //trans.DateAdd = DateTime.Now.ToString("yyyy.MM.dd");
            //try
            //{
            //    InsertRow(trans);
            //}
            //catch
            //{
            //    MessageBox.Show($"Row same_eng={trans.Same_English} - same_rus={trans.Same_Russian}");
            //}


            ////foreach (var item in listAnalogRussian)
            ////{
            ////    Translate translate = new Translate();
            ////    translate.ID_English = english.ID;
            ////    translate.ID_Russian = item;
            ////    translate.DateAdd = DateTime.Now.ToString("yyyy.MM.dd");
            ////    try
            ////    {
            ////        InsertRow(translate);
            ////    }
            ////    catch
            ////    {
            ////        MessageBox.Show($"Row id_eng={translate.ID_English} - id_rus={translate.ID_Russian}");
            ////    }
            ////}

            ////foreach (var item in listAnalogEnglish)
            ////{
            ////    Translate translate = new Translate();
            ////    translate.ID_English = item;
            ////    translate.ID_Russian = russian.ID;
            ////    translate.DateAdd = DateTime.Now.ToString("yyyy.MM.dd");
            ////    try
            ////    {
            ////        InsertRow(translate);
            ////    }
            ////    catch
            ////    {
            ////        MessageBox.Show($"Row id_eng={translate.ID_English} - id_rus={translate.ID_Russian}");
            ////    }
            ////}
        }
        public MemoryStream GeneratePdfTemplate(GarmentPackingListViewModel viewModel, string fob, string cprice)
        {
            //int maxSizesCount = viewModel.Items.Max(i => i.Details.Max(d => d.Sizes.GroupBy(g => g.Size.Id).Count()));
            var newItems   = new List <GarmentPackingListItemViewModel>();
            var newItems2  = new List <GarmentPackingListItemViewModel>();
            var newDetails = new List <GarmentPackingListDetailViewModel>();

            foreach (var item in viewModel.Items)
            {
                foreach (var detail in item.Details)
                {
                    newDetails.Add(detail);
                }
            }
            newDetails = newDetails.OrderBy(a => a.Index).ToList();

            foreach (var d in newDetails)
            {
                if (newItems.Count == 0)
                {
                    var i = viewModel.Items.Single(a => a.Id == d.PackingListItemId);
                    i.Details = new List <GarmentPackingListDetailViewModel>();
                    i.Details.Add(d);
                    newItems.Add(i);
                }
                else
                {
                    if (newItems.Last().Id == d.PackingListItemId)
                    {
                        newItems.Last().Details.Add(d);
                    }
                    else
                    {
                        var y = viewModel.Items.Select(a => new GarmentPackingListItemViewModel
                        {
                            Id                  = a.Id,
                            RONo                = a.RONo,
                            Article             = a.Article,
                            BuyerAgent          = a.BuyerAgent,
                            ComodityDescription = a.ComodityDescription,
                            OrderNo             = a.OrderNo,
                            AVG_GW              = a.AVG_GW,
                            AVG_NW              = a.AVG_NW,
                            Description         = a.Description,
                            Uom                 = a.Uom
                        })
                                .Single(a => a.Id == d.PackingListItemId);
                        y.Details = new List <GarmentPackingListDetailViewModel>();
                        y.Details.Add(d);
                        newItems.Add(y);
                    }
                }
            }

            foreach (var item in newItems)
            {
                if (newItems2.Count == 0)
                {
                    newItems2.Add(item);
                }
                else
                {
                    if (newItems2.Last().OrderNo == item.OrderNo && newItems2.Last().Description == item.Description)
                    {
                        foreach (var d in item.Details)
                        {
                            newItems2.Last().Details.Add(d);
                        }
                    }
                    else
                    {
                        var y = viewModel.Items.Select(a => new GarmentPackingListItemViewModel
                        {
                            Id                  = a.Id,
                            RONo                = a.RONo,
                            Article             = a.Article,
                            BuyerAgent          = a.BuyerAgent,
                            ComodityDescription = a.ComodityDescription,
                            OrderNo             = a.OrderNo,
                            AVG_GW              = a.AVG_GW,
                            AVG_NW              = a.AVG_NW,
                            Description         = a.Description,
                            Uom                 = a.Uom
                        })
                                .Single(a => a.Id == item.Id);
                        y.Details = new List <GarmentPackingListDetailViewModel>();
                        foreach (var d in item.Details)
                        {
                            y.Details.Add(d);
                        }
                        newItems2.Add(y);
                    }
                }
            }

            var sizesCount = false;

            foreach (var item in newItems2)
            {
                var sizesMax = new Dictionary <int, string>();
                foreach (var detail in item.Details.OrderBy(o => o.Carton1).ThenBy(o => o.Carton2))
                {
                    foreach (var size in detail.Sizes)
                    {
                        sizesMax[size.Size.Id] = size.Size.Size;
                    }
                }
                if (sizesMax.Count > 11)
                {
                    sizesCount = true;
                }
            }
            int SIZES_COUNT = sizesCount ? 20 : 11;

            Font header_font            = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 14);
            Font normal_font            = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);
            Font body_font              = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);
            Font normal_font_underlined = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8, Font.UNDERLINE);
            Font bold_font              = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);

            Document     document = new Document(sizesCount ? PageSize.A4.Rotate() : PageSize.A4, 20, 20, 170, 60);
            MemoryStream stream   = new MemoryStream();
            PdfWriter    writer   = PdfWriter.GetInstance(document, stream);

            writer.PageEvent = new GarmentPackingListPDFTemplatePageEvent(_identityProvider, viewModel);

            document.Open();

            #region Description

            PdfPTable tableDescription = new PdfPTable(3);
            tableDescription.SetWidths(new float[] { 2f, 0.2f, 7.8f });
            PdfPCell cellDescription = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };

            cellDescription.Phrase = new Phrase(cprice, normal_font);
            tableDescription.AddCell(cellDescription);
            cellDescription.Phrase = new Phrase(":", normal_font);
            tableDescription.AddCell(cellDescription);
            cellDescription.Phrase = new Phrase(fob, normal_font);
            tableDescription.AddCell(cellDescription);
            if (viewModel.PaymentTerm == "LC")
            {
                cellDescription.Phrase = new Phrase("LC No.", normal_font);
                tableDescription.AddCell(cellDescription);
                cellDescription.Phrase = new Phrase(":", normal_font);
                tableDescription.AddCell(cellDescription);
                cellDescription.Phrase = new Phrase(viewModel.LCNo, normal_font);
                tableDescription.AddCell(cellDescription);
                cellDescription.Phrase = new Phrase("Tgl. LC", normal_font);
                tableDescription.AddCell(cellDescription);
                cellDescription.Phrase = new Phrase(":", normal_font);
                tableDescription.AddCell(cellDescription);
                cellDescription.Phrase = new Phrase(viewModel.LCDate.GetValueOrDefault().ToOffset(new TimeSpan(_identityProvider.TimezoneOffset, 0, 0)).ToString("dd MMMM yyyy"), normal_font);
                tableDescription.AddCell(cellDescription);
                cellDescription.Phrase = new Phrase("ISSUED BY", normal_font);
                tableDescription.AddCell(cellDescription);
                cellDescription.Phrase = new Phrase(":", normal_font);
                tableDescription.AddCell(cellDescription);
                cellDescription.Phrase = new Phrase(viewModel.IssuedBy, normal_font);
                tableDescription.AddCell(cellDescription);
            }
            else
            {
                cellDescription.Phrase = new Phrase("Payment Term", normal_font);
                tableDescription.AddCell(cellDescription);
                cellDescription.Phrase = new Phrase(":", normal_font);
                tableDescription.AddCell(cellDescription);
                cellDescription.Phrase = new Phrase(viewModel.PaymentTerm, normal_font);
                tableDescription.AddCell(cellDescription);
            }

            new PdfPCell(tableDescription);
            tableDescription.ExtendLastRow = false;
            tableDescription.SpacingAfter  = 5f;
            document.Add(tableDescription);

            #endregion

            PdfPCell cellBorderBottomRight = new PdfPCell()
            {
                Border = Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER | Rectangle.LEFT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER
            };
            PdfPCell cellBorderBottom = new PdfPCell()
            {
                Border = Rectangle.BOTTOM_BORDER, HorizontalAlignment = Element.ALIGN_CENTER
            };

            double        totalCtns       = 0;
            double        grandTotal      = 0;
            var           uom             = "";
            var           arrayGrandTotal = new Dictionary <String, double>();
            List <string> cartonNumbers   = new List <string>();

            foreach (var item in newItems2)
            {
                #region Item

                PdfPTable tableItem = new PdfPTable(3);
                tableItem.SetWidths(new float[] { 2f, 0.2f, 7.8f });
                PdfPCell cellItemContent = new PdfPCell()
                {
                    Border = Rectangle.NO_BORDER
                };

                cellItemContent.Phrase = new Phrase("DESCRIPTION OF GOODS", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(":", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(item.Description, normal_font);
                tableItem.AddCell(cellItemContent);

                new PdfPCell(tableItem);
                tableItem.ExtendLastRow = false;
                document.Add(tableItem);

                #endregion

                var sizes = new Dictionary <int, string>();
                foreach (var detail in item.Details)
                {
                    foreach (var size in detail.Sizes)
                    {
                        sizes[size.Size.Id] = size.Size.Size;
                    }
                }
                PdfPTable tableDetail = new PdfPTable(SIZES_COUNT + (viewModel.InvoiceType == "DL" ? 11 : 8));
                var       width       = new List <float> {
                    2f, 3.5f, 4f, 4f
                };
                for (int i = 0; i < SIZES_COUNT; i++)
                {
                    width.Add(1f);
                }
                if (viewModel.InvoiceType == "DL")
                {
                    width.AddRange(new List <float> {
                        1.5f, 1f, 1.5f, 2f, 1.5f, 1.5f, 1.5f
                    });
                }
                else
                {
                    width.AddRange(new List <float> {
                        1.5f, 1f, 1.5f, 2f
                    });
                }
                tableDetail.SetWidths(width.ToArray());

                PdfPCell cellDetailLine = new PdfPCell()
                {
                    Border = Rectangle.BOTTOM_BORDER, Colspan = 19, Padding = 0.5f, Phrase = new Phrase("")
                };
                tableDetail.AddCell(cellDetailLine);
                tableDetail.AddCell(cellDetailLine);

                cellBorderBottomRight.Phrase  = new Phrase(GetScalledChunk("CARTON NO.", normal_font, 0.75f));
                cellBorderBottomRight.Rowspan = 2;
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("COLOUR", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("STYLE", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("ORDER NO.", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase  = new Phrase(GetScalledChunk("S I Z E", normal_font, 0.75f));
                cellBorderBottomRight.Colspan = SIZES_COUNT;
                cellBorderBottomRight.Rowspan = 1;
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase  = new Phrase(GetScalledChunk("CTNS", normal_font, 0.75f));
                cellBorderBottomRight.Colspan = 1;
                cellBorderBottomRight.Rowspan = 2;
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("@", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("QTY", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("UNIT", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                if (viewModel.InvoiceType == "DL")
                {
                    cellBorderBottomRight.Phrase  = new Phrase(GetScalledChunk("GW/\nCTN", normal_font, 0.75f));
                    cellBorderBottomRight.Rowspan = 2;
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("NW/\nCTN", normal_font, 0.75f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("NNW/\nCTN", normal_font, 0.75f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Rowspan = 1;
                }

                for (int i = 0; i < SIZES_COUNT; i++)
                {
                    var size = sizes.OrderBy(a => a.Value).ElementAtOrDefault(i);
                    cellBorderBottomRight.Phrase  = new Phrase(GetScalledChunk(size.Key == 0 ? "" : size.Value, normal_font, 0.5f));
                    cellBorderBottomRight.Rowspan = 1;
                    tableDetail.AddCell(cellBorderBottomRight);
                }

                double subCtns       = 0;
                double subTotal      = 0;
                var    sizeSumQty    = new Dictionary <int, double>();
                var    arraySubTotal = new Dictionary <String, double>();
                foreach (var detail in item.Details.OrderBy(o => o.Carton1).ThenBy(o => o.Carton2))
                {
                    var ctnsQty = detail.CartonQuantity;
                    uom = viewModel.Items.Where(a => a.Id == detail.PackingListItemId).Single().Uom.Unit;
                    var article = viewModel.Items.Where(a => a.Id == detail.PackingListItemId).Single().Article;
                    if (cartonNumbers.Contains($"{detail.Index} - {detail.Carton1}- {detail.Carton2}"))
                    {
                        ctnsQty = 0;
                    }
                    else
                    {
                        cartonNumbers.Add($"{detail.Index} - {detail.Carton1}- {detail.Carton2}");
                    }
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk($"{detail.Carton1}- {detail.Carton2}", normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(detail.Colour, normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(detail.Style, normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(item.OrderNo, normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    for (int i = 0; i < SIZES_COUNT; i++)
                    {
                        var    size     = sizes.OrderBy(a => a.Value).ElementAtOrDefault(i);
                        double quantity = 0;
                        if (size.Key != 0)
                        {
                            quantity = detail.Sizes.Where(w => w.Size.Id == size.Key).Sum(s => s.Quantity);
                        }

                        if (sizeSumQty.ContainsKey(size.Key))
                        {
                            sizeSumQty[size.Key] += quantity * detail.CartonQuantity;
                        }
                        else
                        {
                            sizeSumQty.Add(size.Key, quantity * detail.CartonQuantity);
                        }

                        cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(quantity == 0 ? "" : quantity.ToString(), normal_font, 0.6f));

                        tableDetail.AddCell(cellBorderBottomRight);
                    }
                    subCtns += ctnsQty;
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(ctnsQty.ToString(), normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(detail.QuantityPCS.ToString(), normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    var totalQuantity = (detail.CartonQuantity * detail.QuantityPCS);
                    subTotal += totalQuantity;
                    if (!arraySubTotal.ContainsKey(uom))
                    {
                        arraySubTotal.Add(uom, totalQuantity);
                    }
                    else
                    {
                        arraySubTotal[uom] += totalQuantity;
                    }
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(totalQuantity.ToString(), normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(uom, normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    if (viewModel.InvoiceType == "DL")
                    {
                        cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(string.Format("{0:n2}", detail.GrossWeight), normal_font, 0.6f));
                        tableDetail.AddCell(cellBorderBottomRight);
                        cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(string.Format("{0:n2}", detail.NetWeight), normal_font, 0.6f));
                        tableDetail.AddCell(cellBorderBottomRight);
                        cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(string.Format("{0:n2}", detail.NetNetWeight), normal_font, 0.6f));
                        tableDetail.AddCell(cellBorderBottomRight);
                    }
                }

                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("SUMMARY", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                for (int i = 0; i < SIZES_COUNT; i++)
                {
                    var    size     = sizes.OrderBy(a => a.Value).ElementAtOrDefault(i);
                    double quantity = 0;
                    if (size.Key != 0)
                    {
                        quantity = sizeSumQty.Where(w => w.Key == size.Key).Sum(a => a.Value);
                    }

                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(quantity == 0 ? "" : quantity.ToString(), normal_font, 0.6f));

                    tableDetail.AddCell(cellBorderBottomRight);
                }

                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                if (viewModel.InvoiceType == "DL")
                {
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                }

                totalCtns  += subCtns;
                grandTotal += subTotal;
                if (!arrayGrandTotal.ContainsKey(uom))
                {
                    arrayGrandTotal.Add(uom, subTotal);
                }
                else
                {
                    arrayGrandTotal[uom] += subTotal;
                }

                tableDetail.AddCell(new PdfPCell()
                {
                    Border  = Rectangle.BOTTOM_BORDER,
                    Colspan = SIZES_COUNT + (viewModel.InvoiceType == "DL" ? 6 : 3),
                    Padding = 5,
                    Phrase  = new Phrase("SUB TOTAL .............................................................................................................................................. ", normal_font)
                });
                var subTotalResult = string.Join(" / ", arraySubTotal.Select(x => x.Value + " " + x.Key).ToArray());
                cellBorderBottom.Phrase  = new Phrase(subTotalResult, normal_font);
                cellBorderBottom.Colspan = 2;
                tableDetail.AddCell(cellBorderBottom);
                cellBorderBottom.Phrase  = new Phrase("", normal_font);
                cellBorderBottom.Colspan = 3;
                tableDetail.AddCell(cellBorderBottom);
                cellBorderBottom.Colspan = 1;

                tableDetail.AddCell(new PdfPCell()
                {
                    Border  = Rectangle.BOTTOM_BORDER,
                    Colspan = SIZES_COUNT + (viewModel.InvoiceType == "DL" ? 11 : 8),
                    Phrase  = new Phrase($"      - Sub Ctns = {subCtns}           - Sub G.W. = {String.Format("{0:0.00}", item.Details.Select(d => new { d.Index, d.Carton1, d.Carton2, TotalGrossWeight = d.CartonQuantity * d.GrossWeight }).GroupBy(g => new { g.Index, g.Carton1, g.Carton2 }, (key, value) => value.First().TotalGrossWeight).Sum())} Kgs           - Sub N.W. = {String.Format("{0:0.00}", item.Details.Select(d => new { d.Index, d.Carton1, d.Carton2, TotalNetWeight = d.CartonQuantity * d.NetWeight }).GroupBy(g => new { g.Index, g.Carton1, g.Carton2 }, (key, value) => value.First().TotalNetWeight).Sum())} Kgs            - Sub N.N.W. = {String.Format("{0:0.00}", item.Details.Select(d => new { d.Index, d.Carton1, d.Carton2, TotalNetNetWeight = d.CartonQuantity * d.NetNetWeight }).GroupBy(g => new { g.Index, g.Carton1, g.Carton2 }, (key, value) => value.First().TotalNetNetWeight).Sum())} Kgs", normal_font)
                });

                cellBorderBottom.Phrase = new Phrase("", normal_font);
                tableDetail.AddCell(cellBorderBottom);

                new PdfPCell(tableDetail);
                tableDetail.ExtendLastRow = false;
                //tableDetail.KeepTogether = true;
                tableDetail.WidthPercentage = 95f;
                tableDetail.SpacingAfter    = 10f;
                document.Add(tableDetail);
            }

            #region GrandTotal

            PdfPTable tableGrandTotal = new PdfPTable(2);
            tableGrandTotal.SetWidths(new float[] { 18f + SIZES_COUNT * 1f, 3f });
            PdfPCell cellHeaderLine = new PdfPCell()
            {
                Border = Rectangle.BOTTOM_BORDER, Colspan = 2, Padding = 0.5f, Phrase = new Phrase("")
            };

            tableGrandTotal.AddCell(cellHeaderLine);
            tableGrandTotal.AddCell(new PdfPCell()
            {
                Border  = Rectangle.BOTTOM_BORDER,
                Padding = 6,
                Phrase  = new Phrase("GRAND TOTAL ...................................................................................................................................................................................", normal_font)
            });
            var grandTotalResult = string.Join(" / ", arrayGrandTotal.Select(x => x.Value + " " + x.Key).ToArray());
            tableGrandTotal.AddCell(new PdfPCell()
            {
                Border              = Rectangle.BOTTOM_BORDER,
                Padding             = 4,
                HorizontalAlignment = Element.ALIGN_CENTER,
                Phrase              = new Phrase(grandTotalResult, normal_font)
            });
            tableGrandTotal.AddCell(cellHeaderLine);
            var comodities = viewModel.Items.Select(s => s.Comodity.Name.ToUpper()).Distinct();
            tableGrandTotal.AddCell(new PdfPCell()
            {
                Border  = Rectangle.NO_BORDER,
                Colspan = 2,
                Padding = 5,
                Phrase  = new Phrase($"{totalCtns} {viewModel.SayUnit} [ {NumberToTextEN.toWords(totalCtns).Trim().ToUpper()} {viewModel.SayUnit} OF {string.Join(" AND ", viewModel.OtherCommodity)}]", normal_font)
            });

            new PdfPCell(tableGrandTotal);
            tableGrandTotal.ExtendLastRow   = false;
            tableGrandTotal.WidthPercentage = 95f;
            tableGrandTotal.SpacingAfter    = 5f;
            document.Add(tableGrandTotal);

            #endregion

            #region Mark

            PdfPTable tableMark = new PdfPTable(2);
            tableMark.SetWidths(new float[] { 1f, 1f });

            PdfPCell cellShippingMark = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            Chunk chunkShippingMark = new Chunk("SHIPPING MARKS", normal_font);
            chunkShippingMark.SetUnderline(0.5f, -1);
            Phrase phraseShippingMark = new Phrase();
            phraseShippingMark.Add(chunkShippingMark);
            phraseShippingMark.Add(new Chunk("     :", normal_font));
            cellShippingMark.AddElement(phraseShippingMark);
            cellShippingMark.AddElement(new Paragraph(viewModel.ShippingMark, normal_font));
            tableMark.AddCell(cellShippingMark);

            PdfPCell cellSideMark = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            Chunk chunkSideMark = new Chunk("SIDE MARKS", normal_font);
            chunkSideMark.SetUnderline(0.5f, -1);
            Phrase phraseSideMark = new Phrase();
            phraseSideMark.Add(chunkSideMark);
            phraseSideMark.Add(new Chunk("     :", normal_font));
            cellSideMark.AddElement(phraseSideMark);
            cellSideMark.AddElement(new Paragraph(viewModel.SideMark, normal_font)
            {
            });
            tableMark.AddCell(cellSideMark);

            var    noImage = "data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAA0NDQ0ODQ4QEA4UFhMWFB4bGRkbHi0gIiAiIC1EKjIqKjIqRDxJOzc7STxsVUtLVWx9aWNpfZeHh5e+tb75+f8BDQ0NDQ4NDhAQDhQWExYUHhsZGRseLSAiICIgLUQqMioqMipEPEk7NztJPGxVS0tVbH1pY2l9l4eHl761vvn5///CABEIAAoACgMBIgACEQEDEQH/xAAVAAEBAAAAAAAAAAAAAAAAAAAAB//aAAgBAQAAAACnD//EABQBAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIQAAAAf//EABQBAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMQAAAAf//EABQQAQAAAAAAAAAAAAAAAAAAACD/2gAIAQEAAT8AH//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIBAT8Af//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMBAT8Af//Z";
            byte[] shippingMarkImage;
            if (String.IsNullOrEmpty(viewModel.ShippingMarkImageFile))
            {
                viewModel.ShippingMarkImageFile = noImage;
            }

            if (IsBase64String(Base64.GetBase64File(viewModel.ShippingMarkImageFile)))
            {
                shippingMarkImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.ShippingMarkImageFile));
                Image shipMarkImage = Image.GetInstance(imgb: shippingMarkImage);

                if (shipMarkImage.Width > 60)
                {
                    float percentage = 0.0f;
                    percentage = 100 / shipMarkImage.Width;
                    shipMarkImage.ScalePercent(percentage * 100);
                }

                PdfPCell shipMarkImageCell = new PdfPCell(shipMarkImage);
                shipMarkImageCell.Border = Rectangle.NO_BORDER;
                tableMark.AddCell(shipMarkImageCell);
            }

            byte[] sideMarkImage;

            if (String.IsNullOrEmpty(viewModel.SideMarkImageFile))
            {
                viewModel.SideMarkImageFile = noImage;
            }

            if (IsBase64String(Base64.GetBase64File(viewModel.SideMarkImageFile)))
            {
                sideMarkImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.SideMarkImageFile));
                Image _sideMarkImage = Image.GetInstance(imgb: sideMarkImage);

                if (_sideMarkImage.Width > 60)
                {
                    float percentage = 0.0f;
                    percentage = 100 / _sideMarkImage.Width;
                    _sideMarkImage.ScalePercent(percentage * 100);
                }

                PdfPCell _sideMarkImageCell = new PdfPCell(_sideMarkImage);
                _sideMarkImageCell.Border = Rectangle.NO_BORDER;
                tableMark.AddCell(_sideMarkImageCell);
            }

            new PdfPCell(tableMark);
            tableMark.ExtendLastRow = false;
            tableMark.SpacingAfter  = 5f;
            document.Add(tableMark);

            #endregion

            #region Measurement

            PdfPTable tableMeasurement = new PdfPTable(3);
            tableMeasurement.SetWidths(new float[] { 2f, 0.2f, 12f });
            PdfPCell cellMeasurement = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };

            cellMeasurement.Phrase = new Phrase("GROSS WEIGHT", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(":", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(String.Format("{0:0.00}", viewModel.GrossWeight) + " KGS", normal_font);
            tableMeasurement.AddCell(cellMeasurement);

            cellMeasurement.Phrase = new Phrase("NET WEIGHT", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(":", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(String.Format("{0:0.00}", viewModel.NettWeight) + " KGS", normal_font);
            tableMeasurement.AddCell(cellMeasurement);

            cellMeasurement.Phrase = new Phrase("NET NET WEIGHT", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(":", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(String.Format("{0:0.00}", viewModel.NetNetWeight) + " KGS", normal_font);
            tableMeasurement.AddCell(cellMeasurement);

            cellMeasurement.Phrase = new Phrase("MEASUREMENT", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(":", normal_font);
            tableMeasurement.AddCell(cellMeasurement);

            PdfPTable tableMeasurementDetail = new PdfPTable(5);
            tableMeasurementDetail.SetWidths(new float[] { 2f, 2f, 2f, 2f, 2f });
            PdfPCell cellMeasurementDetail = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
            };
            decimal totalCbm         = 0;
            int     countMeasurement = 0;
            var     measurements     = new List <(double, double, double)>();
            foreach (var measurement in viewModel.Measurements)
            {
                cellMeasurementDetail.Phrase = new Phrase(String.Format("{0:0.00}", measurement.Length) + " CM X ", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                cellMeasurementDetail.Phrase = new Phrase(String.Format("{0:0.00}", measurement.Width) + " CM X ", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                cellMeasurementDetail.Phrase = new Phrase(String.Format("{0:0.00}", measurement.Height) + " CM X ", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                cellMeasurementDetail.Phrase = new Phrase(measurement.CartonsQuantity + " CTNS = ", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                var cbm = (decimal)measurement.Length * (decimal)measurement.Width * (decimal)measurement.Height * (decimal)measurement.CartonsQuantity / 1000000;
                totalCbm += cbm;
                cellMeasurementDetail.Phrase = new Phrase(string.Format("{0:N2} CBM", cbm), normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);


                if (measurements.Contains((measurement.Length, measurement.Width, measurement.Height)) == false)
                {
                    measurements.Add((measurement.Length, measurement.Width, measurement.Height));
                    countMeasurement++;
                }
            }

            cellMeasurementDetail.Border = Rectangle.TOP_BORDER;
            cellMeasurementDetail.Phrase = new Phrase("", normal_font);
            tableMeasurementDetail.AddCell(cellMeasurementDetail);
            tableMeasurementDetail.AddCell(cellMeasurementDetail);
            if (countMeasurement > 1)
            {
                cellMeasurementDetail.Phrase = new Phrase("TOTAL", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                cellMeasurementDetail.Phrase = new Phrase(viewModel.Measurements.Sum(m => m.CartonsQuantity) + " CTNS .", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                cellMeasurementDetail.Phrase = new Phrase(string.Format("{0:N2} CBM", totalCbm), normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
            }


            new PdfPCell(tableMeasurementDetail);
            tableMeasurementDetail.ExtendLastRow = false;
            var paddingRight = SIZES_COUNT > 11 ? 400 : 200;
            tableMeasurement.AddCell(new PdfPCell(tableMeasurementDetail)
            {
                Border = Rectangle.NO_BORDER, PaddingRight = paddingRight
            });
            tableMeasurement.AddCell(new PdfPCell
            {
                Border  = Rectangle.NO_BORDER,
                Colspan = 3,
                Phrase  = new Phrase("REMARK :", normal_font_underlined)
            });
            tableMeasurement.AddCell(new PdfPCell
            {
                Border  = Rectangle.NO_BORDER,
                Colspan = 3,
                Phrase  = new Phrase(viewModel.Remark, normal_font)
            });

            byte[] remarkImage;

            if (String.IsNullOrEmpty(viewModel.RemarkImageFile))
            {
                viewModel.RemarkImageFile = noImage;
            }

            if (IsBase64String(Base64.GetBase64File(viewModel.RemarkImageFile)))
            {
                remarkImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.RemarkImageFile));
                Image images = Image.GetInstance(imgb: remarkImage);

                if (images.Width > 60)
                {
                    float percentage = 0.0f;
                    percentage = 100 / images.Width;
                    images.ScalePercent(percentage * 100);
                }

                PdfPCell imageCell = new PdfPCell(images);
                imageCell.Border  = Rectangle.NO_BORDER;
                imageCell.Colspan = 3;
                tableMeasurement.AddCell(imageCell);
            }

            new PdfPCell(tableMeasurement);
            tableMeasurement.ExtendLastRow = false;
            tableMeasurement.SpacingAfter  = 5f;
            document.Add(tableMeasurement);

            #endregion

            #region sign
            PdfPTable tableSign = new PdfPTable(3);
            tableSign.WidthPercentage = 100;
            tableSign.SetWidths(new float[] { 1f, 1f, 1f });

            PdfPCell cellBodySignNoBorder = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER
            };


            cellBodySignNoBorder.Phrase = new Phrase("", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);
            cellBodySignNoBorder.Phrase = new Phrase("", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);
            cellBodySignNoBorder.Phrase = new Phrase("\n\n\n\n", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);


            cellBodySignNoBorder.Phrase = new Phrase("", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);
            cellBodySignNoBorder.Phrase = new Phrase("", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);
            cellBodySignNoBorder.Phrase = new Phrase("( MRS. ADRIYANA DAMAYANTI )", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);

            cellBodySignNoBorder.Phrase = new Phrase("", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);
            cellBodySignNoBorder.Phrase = new Phrase("", normal_font);
            tableSign.AddCell(cellBodySignNoBorder);
            cellBodySignNoBorder.Phrase = new Phrase("AUTHORIZED SIGNATURE", normal_font_underlined);
            tableSign.AddCell(cellBodySignNoBorder);

            document.Add(tableSign);
            #endregion

            document.Close();
            byte[] byteInfo = stream.ToArray();
            stream.Write(byteInfo, 0, byteInfo.Length);
            stream.Position = 0;

            return(stream);
        }
Ejemplo n.º 45
0
        public void addHeader(Document doc, string totalEncaissement, string totalPoid)
        {
            float[]   sizeLine1 = { 25, 18, 5, 13, 39 };
            PdfPTable table     = new PdfPTable(sizeLine1);

            table.TotalWidth         = 550;
            table.LockedWidth        = true;
            table.DefaultCell.Border = 0;


            table.AddCell("Total encaissements : ");


            PdfPCell cell = new PdfPCell(new Phrase(totalEncaissement));

            cell.Border              = 1;
            cell.BackgroundColor     = iTextSharp.text.BaseColor.LIGHT_GRAY;
            cell.HorizontalAlignment = Element.ALIGN_LEFT;
            cell.VerticalAlignment   = Element.ALIGN_MIDDLE;
            table.AddCell(cell);
            table.AddCell("");
            cell = new PdfPCell(new Phrase("Total Poids : "));
            cell.HorizontalAlignment = Element.ALIGN_RIGHT;
            cell.Border            = 0;
            cell.VerticalAlignment = Element.ALIGN_MIDDLE;
            table.AddCell(cell);

            cell                     = new PdfPCell(new Phrase(totalPoid));
            cell.Border              = 1;
            cell.BackgroundColor     = iTextSharp.text.BaseColor.LIGHT_GRAY;
            cell.HorizontalAlignment = Element.ALIGN_LEFT;
            cell.VerticalAlignment   = Element.ALIGN_MIDDLE;
            table.AddCell(cell);

            iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(Globale_Varriables.VAR.PathCont + "/template/choix_0.png");
            jpg.ScaleAbsolute(14f, 14f);

            float[] size2 = { 25f, 18f, 18f, 39f };

            PdfPTable table2 = new PdfPTable(size2);

            table2.TotalWidth  = 550;
            table2.LockedWidth = true;

            table2.AddCell("Carburant consommation");
            table2.AddCell("KM parcourus");
            //table2.AddCell("Encaissements");
            table2.AddCell("Décompte des heures");

            Phrase phrase = new Phrase();

            phrase.Add(new Chunk(jpg, -1, -1));
            phrase.Add(new Chunk(" N° : C+R"));
            table2.AddCell(phrase);


            phrase = new Phrase();
            phrase.Add(new Chunk(jpg, -1, -1));
            phrase.Add(new Chunk(" Plein Garage Perroy"));

            //Ligne1
            table2.AddCell(phrase);        //"   Plein Garage Perroy");
            table2.AddCell("Km arrivé :"); ///FIX 1
            //table2.AddCell("Liquide : CHF ........");
            table2.AddCell("H.Départ :");


            phrase = new Phrase();
            phrase.Add(new Chunk(jpg, -1, -1));
            phrase.Add(new Chunk(" Noms chauffeur + aide chauffeur "));
            table2.AddCell(phrase);


            //Ligne2

            phrase = new Phrase();
            phrase.Add(new Chunk(jpg, -1, -1));
            phrase.Add(new Chunk(" Plein exterieur"));

            table2.AddCell(phrase);
            table2.AddCell("KM départ :");   ///FIX 1
            //table2.AddCell("CC      : CHF ........");
            table2.AddCell("H.Arrivé :");

            phrase = new Phrase();
            phrase.Add(new Chunk(jpg, -1, -1));
            phrase.Add(new Chunk(" BL signés"));
            table2.AddCell(phrase);

            //Ligne3
            table2.AddCell(".................. Litres");
            table2.AddCell("Km parcourus :");
            //table2.AddCell("Chéque  : CHF ........");
            table2.AddCell("");

            phrase = new Phrase();
            phrase.Add(new Chunk(jpg, -1, -1));
            phrase.Add(new Chunk(" Retours identifiés sur plan ID + code stock indiqué"));
            table2.AddCell(phrase);

            //Ligne4
            table2.AddCell(".................. CHF");
            table2.AddCell("Visa chauffeur");
            //table2.AddCell("Visa débriefing");
            table2.AddCell("Décompte :");

            phrase = new Phrase();
            phrase.Add(new Chunk(jpg, -1, -1));
            phrase.Add(new Chunk(" SAMS identifiés + personne de contact indiquée"));
            table2.AddCell(phrase);

            //Ligne5

            /*
             * table2.AddCell("P.Pneu avant :");
             * table2.AddCell("P.Pneu arriére :");
             * table2.AddCell("");
             * table2.AddCell("");
             */

            doc.Add(table);

            //doc.Add(table2);
        }
Ejemplo n.º 46
0
        public static PdfPTable CreateAlarmTable(PdfReportConfig cfg)
        {
            //Left in as a teaser for next phase of the project

            // the table object
            const int cols  = 6;
            PdfPTable table = new PdfPTable(cols);

            table.DefaultCell.PaddingBottom = 5;
            table.WidthPercentage           = 100;
            table.HeaderRows         = 2;
            table.DefaultCell.Phrase = new Phrase {
                Font = cfg.TableAlmCellFont
            };

            // columns relative widths
            float[] colWidths = new float[] { 10, 30, 0, 20, 20, 20 };
            table.SetWidths(colWidths);


            // Alarms - Row1
            Phrase   phrase = new Phrase("ALARMS", cfg.TableHeaderFont);
            PdfPCell cell   = new PdfPCell(phrase);

            cell.GrayFill = (float).95;
            cell.Border   = 0;
            cell.Colspan  = 6;
            table.AddCell(cell);

            // Alarms - Row2 - col1
            phrase       = new Phrase("ALM #", cfg.TableAlmHeaderFont);
            cell         = new PdfPCell(phrase);
            cell.Border  = 0;
            cell.Colspan = 1;
            table.AddCell(cell);

            // Alarms - Row2 - col2
            phrase       = new Phrase("DESCRIPTION", cfg.TableAlmHeaderFont);
            cell         = new PdfPCell(phrase);
            cell.Border  = 0;
            cell.Colspan = 1;
            table.AddCell(cell);

            // Alarms - Row2 - col3
            phrase       = new Phrase("GROUP", cfg.TableAlmHeaderFont);
            cell         = new PdfPCell(phrase);
            cell.Border  = 0;
            cell.Colspan = 1;
            table.AddCell(cell);

            // Alarms - Row2 - col4
            phrase       = new Phrase("SET TIME", cfg.TableAlmHeaderFont);
            cell         = new PdfPCell(phrase);
            cell.Border  = 0;
            cell.Colspan = 1;
            table.AddCell(cell);

            // Alarms - Row2 - col5
            phrase       = new Phrase("CLEAR TIME", cfg.TableAlmHeaderFont);
            cell         = new PdfPCell(phrase);
            cell.Border  = 0;
            cell.Colspan = 1;
            table.AddCell(cell);


            // Alarms - Row2 - col6
            phrase       = new Phrase("ACK TIME", cfg.TableAlmHeaderFont);
            cell         = new PdfPCell(phrase);
            cell.Border  = 0;
            cell.Colspan = 1;
            table.AddCell(cell);

            //clsAlarmList almList = cfg.OrderBase.AggregateAlarms();


            //if (almList.Count > 0)
            //{

            //	foreach (clsAlarm alm in almList)
            //	{
            //		cell = new PdfPCell(new Phrase(alm.Alm_ID.ToString(CultureInfo.InvariantCulture), cfg.TableAlmCellFont));
            //		table.AddCell(cell);

            //		cell = new PdfPCell(new Phrase(alm.Alm_Desc, cfg.TableAlmCellFont));
            //		table.AddCell(cell);

            //		cell = new PdfPCell(new Phrase(alm.Alm_Group, cfg.TableAlmCellFont));
            //		table.AddCell(cell);

            //		cell = new PdfPCell(new Phrase(alm.Alm_SetTime.ToString(CultureInfo.InvariantCulture), cfg.TableAlmCellFont));
            //		table.AddCell(cell);

            //		cell = new PdfPCell(new Phrase(alm.Alm_ClearTime.ToString(CultureInfo.InvariantCulture), cfg.TableAlmCellFont));
            //		table.AddCell(cell);

            //		cell = new PdfPCell(new Phrase(alm.Alm_AckTime.ToString(CultureInfo.InvariantCulture), cfg.TableAlmCellFont));
            //		table.AddCell(cell);
            //	}
            //}
            //else
            //{
            cell         = new PdfPCell(new Phrase("No alarms recorded for this order", cfg.TableAlmTableEmptyFont));
            cell.Colspan = 6;
            table.AddCell(cell);
            //}

            return(table);
        }
Ejemplo n.º 47
0
        public void CompartilharPDF(List <CE_Pesquisa04> perguntas)
        {
            if (Android.Support.V4.App.ActivityCompat.CheckSelfPermission(Android.App.Application.Context, Android.Manifest.Permission.WriteExternalStorage) != (int)Android.Content.PM.Permission.Granted)
            {
                Android.Support.V4.App.ActivityCompat.RequestPermissions(mainActivity, new string[] { Android.Manifest.Permission.WriteExternalStorage }, 0);

                return;
            }
            else
            {
                try
                {
                    Configuracao conf = ObterConfiguracao();
                    //String path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
                    String path       = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
                    String arquivoPDF = Path.Combine(path, "graficos.pdf");

                    DAO_Filtro       daoFiltro   = DAO_Filtro.Instance;
                    List <CE_Filtro> listFiltros = daoFiltro.ObterFiltrosPorPesquisa(perguntas[0].idpesquisa01);

                    List <CE_Pesquisa03> opcoes = new List <CE_Pesquisa03>();

                    foreach (var item in perguntas)
                    {
                        if (item.TemFiltro())
                        {
                            opcoes.AddRange(item.Opcoes);
                        }
                    }

                    perguntas = perguntas.Where(o => o.IsPergunta && o.selecionado).ToList();

                    FileStream fs       = new FileStream(arquivoPDF, FileMode.Create);
                    Document   document = new Document(PageSize.A4, 25, 25, 30, 30);
                    PdfWriter  writer   = PdfWriter.GetInstance(document, fs);

                    document.Open();

                    foreach (var pergunta in perguntas)
                    {
                        Paragraph paragrafo = new Paragraph();
                        paragrafo.Alignment = iTextSharp.text.Element.ALIGN_LEFT;

                        Phrase prCabecalho = new Phrase("Gráfico gerado em: " + String.Format("{0:dd/MM/yyyy HH:mm:ss}", DateTime.Now) + " \n", new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 15f, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK));

                        paragrafo.Add(prCabecalho);

                        Table table = new Table(1);
                        table.Alignment = iTextSharp.text.Element.ALIGN_CENTER;
                        table.Width     = 100;

                        Phrase pr = new Phrase(pergunta.descricao + " (" + pergunta.Quantidade + ") \n\n", new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 18f, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.WHITE));

                        iTextSharp.text.Cell cell = new iTextSharp.text.Cell(pr);
                        cell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER;
                        cell.BackgroundColor     = iTextSharp.text.Color.BLUE;

                        table.AddCell(cell);

                        paragrafo.Add(table);

                        Paragraph pImg = new Paragraph();
                        pImg.Alignment = iTextSharp.text.Element.ALIGN_CENTER;

                        MemoryStream ms = new MemoryStream();

                        if (pergunta.GraficoPizza != null)
                        {
                            if (pergunta.TipoGrafico == 1 && pergunta.GraficoPizza.Width > 0)
                            {
                                ((MikePhil.Charting.Data.PieData)pergunta.GraficoPizza.Data).SetValueTextSize(conf.TamanhoFonteGrafico);
                                ((MikePhil.Charting.Components.Legend)pergunta.GraficoPizza.Legend).TextSize = conf.TamanhoFonteGrafico - 2;
                                pergunta.GraficoPizza.ChartBitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 0, ms);
                                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(ms.ToArray());
                                img.ScalePercent(40f);
                                img.Alignment = iTextSharp.text.Element.ALIGN_CENTER;

                                pImg.Add(img);

                                paragrafo.Add(pImg);

                                document.Add(paragrafo);

                                ((MikePhil.Charting.Data.PieData)pergunta.GraficoPizza.Data).SetValueTextSize(15f);
                                ((MikePhil.Charting.Components.Legend)pergunta.GraficoPizza.Legend).TextSize = 15f;
                            }
                            else if (pergunta.TipoGrafico == 2 && pergunta.GraficoBarra.Width > 0)
                            {
                                pergunta.GraficoBarra.BarData.SetValueTextSize(conf.TamanhoFonteGrafico);
                                pergunta.GraficoBarra.ChartBitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 0, ms);
                                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(ms.ToArray());
                                img.ScalePercent(40f);
                                img.Alignment = iTextSharp.text.Element.ALIGN_CENTER;
                                pImg.Add(img);

                                paragrafo.Add(pImg);

                                document.Add(paragrafo);

                                pergunta.GraficoBarra.BarData.SetValueTextSize(15f);
                            }
                        }
                        else
                        {
                            if (pergunta.TipoGrafico == 1 && pergunta.GraficoLinha.Width > 0)
                            {
                                pergunta.GraficoLinha.LineData.SetValueTextSize(conf.TamanhoFonteGrafico);
                                pergunta.GraficoLinha.ChartBitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 0, ms);
                                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(ms.ToArray());
                                img.ScalePercent(40f);
                                img.Alignment = iTextSharp.text.Element.ALIGN_CENTER;

                                pImg.Add(img);

                                paragrafo.Add(pImg);

                                document.Add(paragrafo);

                                pergunta.GraficoLinha.LineData.SetValueTextSize(15f);
                            }
                            else if (pergunta.TipoGrafico == 2 && pergunta.GraficoBarra.Width > 0)
                            {
                                pergunta.GraficoBarra.BarData.SetValueTextSize(conf.TamanhoFonteGrafico);
                                pergunta.GraficoBarra.ChartBitmap.Compress(Android.Graphics.Bitmap.CompressFormat.Png, 0, ms);
                                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(ms.ToArray());
                                img.ScalePercent(40f);
                                img.Alignment = iTextSharp.text.Element.ALIGN_CENTER;
                                pImg.Add(img);

                                paragrafo.Add(pImg);

                                document.Add(paragrafo);

                                pergunta.GraficoBarra.BarData.SetValueTextSize(15f);
                            }
                        }

                        ms.Close();

                        Paragraph paragrafoRodape = new Paragraph();
                        paragrafoRodape.Alignment = iTextSharp.text.Element.ALIGN_LEFT;

                        String filtro = "Filtros: ";

                        if (listFiltros.Count > 0)
                        {
                            for (int i = 0; i < listFiltros.Count; i++)
                            {
                                if (i != listFiltros.Count - 1)
                                {
                                    filtro += opcoes.FirstOrDefault(o => o.idpesquisa03 == listFiltros[i].idpesquisa03).descricao + ", ";
                                }
                                else
                                {
                                    filtro += opcoes.FirstOrDefault(o => o.idpesquisa03 == listFiltros[i].idpesquisa03).descricao;
                                }
                            }
                        }
                        else
                        {
                            filtro = "Filtros: Nenhum";
                        }

                        Phrase prRodape = new Phrase(filtro, new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 15f, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK));

                        paragrafoRodape.Add(prRodape);

                        document.Add(paragrafoRodape);

                        document.NewPage();
                    }

                    document.Close();
                    writer.Close();
                    fs.Close();

                    var fileUri       = Android.Net.Uri.FromFile(new Java.IO.File(arquivoPDF));
                    var sharingIntent = new Intent();
                    sharingIntent.SetAction(Intent.ActionSend);
                    sharingIntent.SetType("application/pdf");
                    //sharingIntent.PutExtra(Intent.ExtraText, content);
                    sharingIntent.PutExtra(Intent.ExtraStream, fileUri);
                    //sharingIntent.AddFlags(ActivityFlags.GrantReadUriPermission);
                    Intent intent = Intent.CreateChooser(sharingIntent, "graficos.pdf");
                    intent.AddFlags(ActivityFlags.NewTask);
                    Android.App.Application.Context.StartActivity(intent);
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }
Ejemplo n.º 48
0
    public byte[] PrintAppointmentInvoice(string invoiceId, string appointmentToken, string doctorName,
                                          string appointmentDate, string appointmentTime)
    {
        Document document   = new Document(PageSize.A4);
        Font     NormalFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, Color.BLACK);

        using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
        {
            PdfWriter writer    = PdfWriter.GetInstance(document, memoryStream);
            PdfPTable table     = null;
            Phrase    phrase    = null;
            PdfPCell  cell      = null;
            Paragraph paragraph = null;
            Color     color     = null;

            document.Open();

            table = new PdfPTable(2);
            float[] widths = new float[] { 5f, 10f };
            table.SetWidths(widths);

            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(System.Web.HttpContext.Current.Server.MapPath("../images/logo.png"));
            image.ScaleAbsolute(80, 80);
            cell        = new PdfPCell(image);
            cell.Border = Rectangle.NO_BORDER;
            table.AddCell(cell);

            phrase = new Phrase();
            phrase.Add(new Chunk("ABC Hospital\n\n", FontFactory.GetFont("Arial", 18, Font.BOLD, Color.RED)));
            phrase.Add(new Chunk("123, Bodakdev\n", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
            phrase.Add(new Chunk("Ahmedabad 380015\n", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
            phrase.Add(new Chunk("INDIA\n", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
            phrase.Add(new Chunk("Ph:- 9543289345\n", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));
            phrase.Add(new Chunk("Website:- http://www.abchospital.com\n", FontFactory.GetFont("Arial", 9, Font.NORMAL, Color.BLACK)));

            cell        = new PdfPCell(phrase);
            cell.Border = Rectangle.NO_BORDER;
            table.AddCell(cell);

            color = new Color(System.Drawing.ColorTranslator.FromHtml("#000000"));
            DrawLine(writer, 25f, document.Top - 110f, document.PageSize.Width - 25f, document.Top - 110f, color);
            DrawLine(writer, 25f, document.Top - 110f, document.PageSize.Width - 25f, document.Top - 110f, color);

            phrase = new Phrase();
            phrase.Add(new Chunk("APPOINTMENT INVOICE\n\n", FontFactory.GetFont("Arial", 16, Font.BOLD, Color.BLACK)));

            paragraph = new Paragraph();
            paragraph.Add(phrase);
            paragraph.Alignment     = Element.ALIGN_CENTER;
            paragraph.SpacingBefore = 50;
            paragraph.SpacingAfter  = 30;

            document.Add(table);
            document.Add(paragraph);

            table  = new PdfPTable(2);
            phrase = new Phrase();
            phrase.Add(new Chunk("Invoice ID", FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk(invoiceId, FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk("Invoice Date", FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk(DateTime.Now.ToString(), FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk("Appointment Token", FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk(appointmentToken, FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk("Doctor", FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk(doctorName, FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk("Appointment Date", FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk(appointmentDate, FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk("Appointment Time", FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            cell.PaddingBottom = 20;
            table.AddCell(cell);
            phrase = new Phrase();
            phrase.Add(new Chunk(appointmentTime, FontFactory.GetFont("Arial", 11, Font.NORMAL, Color.BLACK)));
            cell = new PdfPCell(phrase);
            table.AddCell(cell);
            table.HorizontalAlignment = Element.ALIGN_CENTER;

            document.Add(table);

            DrawLine(writer, 25f, document.Top - 750f, document.PageSize.Width - 25f, document.Top - 750f, color);
            DrawLine(writer, 25f, document.Top - 750f, document.PageSize.Width - 25f, document.Top - 750f, color);

            document.Close();
            byte[] bytes = memoryStream.ToArray();
            using (FileStream fs = File.Create(System.Web.HttpContext.Current.Server.MapPath("../Invoice/Appointments/" + invoiceId + ".pdf")))
            {
                fs.Write(bytes, 0, (int)bytes.Length);
            }
            memoryStream.Close();
            return(bytes);
        }
    }
Ejemplo n.º 49
0
    public void generarBoletin(int id_salon, int id_estudiante)
    {
        /*Consultamos la matricula*/
        Matricula          objMatricula     = new Matricula();
        OperacionMatricula objOperMatricula = new OperacionMatricula(ConfigurationManager.ConnectionStrings["estigioacademicoConnectionString"].ConnectionString);

        Asignacion          objAsignacion     = new Asignacion();
        OperacionAsignacion objOperAsignacion = new OperacionAsignacion(ConfigurationManager.ConnectionStrings["estigioacademicoConnectionString"].ConnectionString);

        Asistencia          objAsistencia     = new Asistencia();
        OperacionAsistencia objOperAsistencia = new OperacionAsistencia(ConfigurationManager.ConnectionStrings["estigioacademicoConnectionString"].ConnectionString);

        Indicador          objIndicador     = new Indicador();
        OperacionIndicador objOperIndicador = new OperacionIndicador(ConfigurationManager.ConnectionStrings["estigioacademicoConnectionString"].ConnectionString);

        Calificacion          objCalificacion     = new Calificacion();
        OperacionCalificacion objOperCalificacion = new OperacionCalificacion(ConfigurationManager.ConnectionStrings["estigioacademicoConnectionString"].ConnectionString);

        Calificacion_Configuracion          objConfiguracion_Calificacion     = new Calificacion_Configuracion();
        OperacionCalificacion_Configuracion objOperConfiguracion_Calificacion = new OperacionCalificacion_Configuracion(ConfigurationManager.ConnectionStrings["estigioacademicoConnectionString"].ConnectionString);

        Salon          objSalon     = new Salon();
        OperacionSalon objOperSalon = new OperacionSalon(ConfigurationManager.ConnectionStrings["estigioacademicoConnectionString"].ConnectionString);



        MemoryStream ms       = new MemoryStream();
        Document     document = new Document(PageSize.LEGAL, 10f, 10f, 10f, 10f);
        PdfWriter    writer   = PdfWriter.GetInstance(document, ms);

        document.Open();


        Font fontTinyItalic = FontFactory.GetFont("Arial", 7);
        Font fontEncabezado = FontFactory.GetFont("Arial", 12);


        float[] porcentajes = { 15f, 45f, 10f, 10f, 10f, 10f };


        objMatricula.id_estudiante = id_estudiante;
        DataTable dts_Matricula = objOperMatricula.ConsultarMatricula(objMatricula);

        PdfPTable tabla = new PdfPTable(porcentajes);

        tabla.WidthPercentage = 100f;
        PdfPCell celda;
        Phrase   texto;

        celda = new PdfPCell();
        iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(new Uri("http://academico.itipuentenacional.edu.co/img/logo.png"));
        image.ScaleAbsolute(40f, 40f);
        image.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
        celda.Image     = image;
        celda.Border    = Rectangle.NO_BORDER;
        tabla.AddCell(celda);

        celda         = new PdfPCell();
        celda.Colspan = 4;
        texto         = new Phrase();
        texto.Font    = fontEncabezado;
        texto.Add("INSTITUTO TÉCNICO INDUSTRIAL FRANCISCO DE PAULA SANTANDER \n\nwww.itipuentenacional.edu.co \n\nINFORME ACADÉMICO 2014");
        celda.Phrase = texto;
        celda.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
        celda.VerticalAlignment   = PdfPCell.ALIGN_MIDDLE;
        celda.Border = Rectangle.NO_BORDER;
        tabla.AddCell(celda);

        celda = new PdfPCell();
        iTextSharp.text.Image image_estudiante = iTextSharp.text.Image.GetInstance(new Uri("http://academico.itipuentenacional.edu.co/" + dts_Matricula.Rows[0].ItemArray[10].ToString().Replace("~/", "")));
        image.ScaleAbsolute(10f, 10f);
        image.ScalePercent(10f);
        celda.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
        celda.VerticalAlignment   = PdfPCell.ALIGN_MIDDLE;
        celda.Image = image_estudiante;
        celda.AddElement(texto);
        celda.Border = Rectangle.NO_BORDER;
        tabla.AddCell(celda);

        String[] celdasEncabezado = { "CURSO", "ESTUDIANTE", "DOCUMENTO", "PROMEDIO GENERAL", "ESCALA NACIONAL", "PERIODO" };

        for (int i = 0; i < celdasEncabezado.Length; i++)
        {
            agregarCelda(celdasEncabezado[i], tabla);
        }

        /*CURSO*/
        agregarCelda(id_salon.ToString(), tabla);

        /*ESTUDIANTE*/
        var nombre_completo = dts_Matricula.Rows[0].ItemArray[7].ToString() + " "
                              + dts_Matricula.Rows[0].ItemArray[6].ToString();

        agregarCelda(nombre_completo, tabla);

        /*DOCUMENTO*/
        agregarCelda(id_estudiante.ToString(), tabla);

        /*PROMEDIO GENERAL*/
        Calificacion objPromedioGeneral = new Calificacion();

        objPromedioGeneral.id_asignacion = int.Parse(dts_Matricula.Rows[0].ItemArray[2].ToString());
        objPromedioGeneral.id_calificacion_configuracion = int.Parse(ddlPeriodo.SelectedValue.ToString());
        DataView promedio_general = objOperCalificacion.ConsultarPromedio_General(objPromedioGeneral).DefaultView;

        promedio_general.RowFilter = "id_estudiante=" + id_estudiante;
        GridView tbl_promedio_general = new GridView();

        tbl_promedio_general.DataSource = promedio_general;
        tbl_promedio_general.DataBind();
        decimal promedio_g = 0;

        if (tbl_promedio_general.Rows.Count > 0)
        {
            promedio_g = decimal.Parse(tbl_promedio_general.Rows[0].Cells[2].Text);
            agregarCelda(String.Format("{0:f2}", promedio_g), tabla);
        }
        else
        {
            agregarCelda("0,00", tabla);
        }



        /*ESCALA NACIONAL*/
        agregarCelda(getDesempeño(promedio_g), tabla);

        /*PERIODO*/
        agregarCelda(ddlPeriodo.SelectedItem.Text, tabla);

        tabla.SpacingBefore = 10;
        document.Add(tabla);

        tabla.Rows.Clear();


        objAsignacion.id_salon = id_salon;
        DataTable dts = objOperAsignacion.ConsultarAsignacion(objAsignacion);

        objAsignacion.id_salon = int.Parse(dts_Matricula.Rows[0].ItemArray[8].ToString());
        DataTable tecnica = objOperAsignacion.ConsultarAsignacion(objAsignacion);

        dts.Merge(tecnica);

        DataView dtv_Asignacion = dts.DefaultView;

        dtv_Asignacion.Sort = "orden_impresion ASC";

        GridView tbl_Asignacion = new GridView();

        tbl_Asignacion.DataSource = dtv_Asignacion;
        tbl_Asignacion.DataBind();


        objAsistencia.id_estudiante = id_estudiante;
        objAsistencia.id_periodo    = int.Parse(ddlPeriodo.SelectedValue.ToString());
        DataView dtvAsistencia = objOperAsistencia.ConsultarAsistencia(objAsistencia).DefaultView;

        objConfiguracion_Calificacion.id_periodo = int.Parse(ddlPeriodo.SelectedValue.ToString());
        DataTable dta_Configuracion_Calificacion = objOperConfiguracion_Calificacion.ConsultarCalificacion_Configuracion(objConfiguracion_Calificacion);

        objIndicador.id_grado = int.Parse(dts.Rows[0].ItemArray[11].ToString());
        objIndicador.id_anio_escolar_periodo = int.Parse(ddlPeriodo.SelectedValue.ToString());
        DataView dtvIndicador  = objOperIndicador.ConsultarIndicador(objIndicador).DefaultView;
        GridView tbl_Indicador = new GridView();

        objCalificacion.id_estudiante = id_estudiante;
        DataView     dtvCalificacion          = objOperCalificacion.ConsultarCalificacion(objCalificacion).DefaultView;
        GridView     tbl_Calificacion         = new GridView();
        Calificacion objCalificacion_Promedio = new Calificacion();

        objCalificacion_Promedio.id_estudiante = id_estudiante;
        objCalificacion_Promedio.id_asignacion = int.Parse(ddlPeriodo.SelectedValue.ToString());
        DataView   dtvPromedio            = objOperCalificacion.ConsultarPromedio_Periodo(objCalificacion_Promedio).DefaultView;
        DataView   dtvPromedio_Acumulado  = objOperCalificacion.ConsultarPromedio_PeriodoAcumulado(objCalificacion_Promedio).DefaultView;
        double     promedio_acumulado     = 0;
        GridView   tbl_Promedio           = new GridView();
        GridView   tbl_Promedio_Acumulado = new GridView();
        Asistencia objAsistencia_2        = new Asistencia();

        objAsistencia_2.id_estudiante = id_estudiante;
        DataView dtvAsistencia_Total  = objOperAsistencia.ConsultarAsistencia(objAsistencia_2).DefaultView;
        GridView tbl_Asistencia_Total = new GridView();
        int      asistencia_total     = 0;

        /*Tenemos que recorrer las notas solo esta el sabeer*/
        foreach (GridViewRow dr in tbl_Asignacion.Rows)
        {
            dtvAsistencia.RowFilter         = "id_asignacion = " + int.Parse(dr.Cells[0].Text);
            dtvAsistencia_Total.RowFilter   = "id_asignacion = " + int.Parse(dr.Cells[0].Text);
            tbl_Asistencia_Total.DataSource = dtvAsistencia_Total;
            tbl_Asistencia_Total.DataBind();

            GridView tbl_Asistencia = new GridView();
            tbl_Asistencia.DataSource = dtvAsistencia;
            tbl_Asistencia.DataBind();
            agregarCelda(HttpUtility.HtmlDecode(dr.Cells[7].Text), tabla, 14083004);
            agregarCelda("DOCENTE: " + HttpUtility.HtmlDecode(dr.Cells[10].Text), tabla, 14083004);
            agregarCelda("VALORIZACIÓN", tabla, 14083004);
            agregarCelda("DEFINITIVA PERIODO", tabla, 14083004);
            agregarCelda("DEFINITIVA ACUMULADO", tabla, 14083004);
            agregarCelda("FALLAS PERIODO", tabla, 14083004);

            String saber               = "";
            String indicador           = "";
            String calificacion        = "";
            String promedio            = "";
            String Spromedio_acumulado = "";
            String asistencia          = "";
            for (int i = 0; i < dta_Configuracion_Calificacion.Rows.Count; i++)
            {
                dtvIndicador.RowFilter = "id_materia =" + dr.Cells[2].Text +
                                         " AND id_saber = " + int.Parse(dta_Configuracion_Calificacion.Rows[i].ItemArray[0].ToString());
                tbl_Indicador.DataSource = dtvIndicador;
                tbl_Indicador.DataBind();

                dtvCalificacion.RowFilter = "id_asignacion = " + int.Parse(dr.Cells[0].Text) +
                                            " AND id_calificacion_configuracion = " + dta_Configuracion_Calificacion.Rows[i].ItemArray[0].ToString();
                saber = dta_Configuracion_Calificacion.Rows[i].ItemArray[1].ToString();

                /*Agregamos indicadores*/
                if (tbl_Indicador.Rows.Count == 1)
                {
                    indicador = HttpUtility.HtmlDecode(tbl_Indicador.Rows[0].Cells[1].Text);
                }
                else
                {
                    indicador = "";
                }

                /*Agregamos calificaciones*/
                tbl_Calificacion.DataSource = dtvCalificacion;
                tbl_Calificacion.DataBind();
                if (tbl_Calificacion.Rows.Count == 1)
                {
                    calificacion = tbl_Calificacion.Rows[0].Cells[5].Text;
                }
                else
                {
                    calificacion = "0,00";
                }

                dtvPromedio.RowFilter   = "id_asignacion = " + int.Parse(dr.Cells[0].Text);
                tbl_Promedio.DataSource = dtvPromedio;
                tbl_Promedio.DataBind();
                if (tbl_Promedio.Rows.Count == 1)
                {
                    promedio = tbl_Promedio.Rows[0].Cells[2].Text;
                }
                else
                {
                    promedio = "0,00";
                }

                dtvPromedio_Acumulado.RowFilter   = "id_asignacion = " + int.Parse(dr.Cells[0].Text);
                tbl_Promedio_Acumulado.DataSource = dtvPromedio_Acumulado;
                tbl_Promedio_Acumulado.DataBind();

                for (int j = 0; j < tbl_Promedio_Acumulado.Rows.Count; j++)
                {
                    promedio_acumulado += double.Parse(tbl_Promedio_Acumulado.Rows[j].Cells[2].Text);
                }
                double valor = promedio_acumulado;
                if (valor > 0)
                {
                    Spromedio_acumulado = String.Format("{0:f2}", valor);
                }
                else
                {
                    Spromedio_acumulado = "0,00";
                    valor = 0;
                }
                promedio_acumulado = 0;
                if (tbl_Asistencia.Rows.Count > 0)
                {
                    asistencia = tbl_Asistencia.Rows[0].Cells[4].Text;
                }
                else
                {
                    asistencia = "0";
                }

                if (i != (dta_Configuracion_Calificacion.Rows.Count - 1))
                {
                    agregarCelda(saber, tabla);
                    agregarCeldaJustificado(indicador, tabla);
                    agregarCelda(calificacion, tabla);
                }
                else
                {
                    agregarCeldaRow(saber, tabla, 2);
                    agregarCeldaRowJustificado(indicador, tabla, 2);
                    agregarCeldaRow(calificacion, tabla, 2);
                    for (int k = 0; k < 2; k++)
                    {
                        if (k == 0)
                        {
                            agregarCelda("DESEMPEÑO PERIODO", tabla, 14083004);
                            agregarCelda("DESEMPEÑO ACUMULADO", tabla, 14083004);
                            agregarCelda("FALLAS ACUMULADAS", tabla, 14083004);
                        }
                        else
                        {
                            agregarCelda(getDesempeño(Convert.ToDecimal(promedio)), tabla);
                            agregarCelda(getDesempeño(Convert.ToDecimal(valor)), tabla);
                            if (tbl_Asistencia_Total.Rows.Count > 0)
                            {
                                for (int j = 0; j < tbl_Asistencia_Total.Rows.Count; j++)
                                {
                                    asistencia_total += int.Parse(tbl_Asistencia_Total.Rows[j].Cells[4].Text);
                                }
                            }
                            else
                            {
                                asistencia_total = 0;
                            }
                            agregarCelda("" + asistencia_total, tabla);
                        }
                    }
                }

                if (i == 0)
                {
                    agregarCeldaRow(promedio, tabla, 2);
                    agregarCeldaRow(Spromedio_acumulado, tabla, 2);
                    agregarCeldaRow(asistencia, tabla, 2);
                }
            }
        }

        document.Add(tabla);
        if (tbl_promedio_general.Rows.Count > 0)
        {
            document.Add(new Paragraph(new Phrase("EL ESTUDIANTE HA OCUPADO EL PUESTO " + tbl_promedio_general.Rows[0].Cells[0].Text, fontTinyItalic))
            {
                Alignment = Element.ALIGN_CENTER
            });
        }
        tabla = new PdfPTable(1);
        tabla.SpacingBefore = 40f;
        objSalon.id         = id_salon;
        Phrase director = new Phrase(objOperSalon.ConsultarSalon(objSalon).Rows[0].ItemArray[8].ToString(), fontTinyItalic);

        celda.Phrase = director;
        celda.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
        celda.VerticalAlignment   = PdfPCell.ALIGN_MIDDLE;
        celda.Border = PdfPCell.TOP_BORDER;
        tabla.AddCell(celda);
        document.Add(tabla);
        document.NewPage();

        document.Close();
        writer.Close();
        ms.Close();
        Response.ContentType = "pdf/application";
        Response.AddHeader("content-disposition", "attachment;filename=Boletin.pdf");
        Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
    }
 /**
  * Adds a <CODE>Phrase</CODE> to the current text array.
  * Will not have any effect if addElement() was called before.
  * @param phrase the text
  * @since	2.1.5
  */
 public void AddText(Phrase phrase)
 {
     columnText.AddText(phrase);
 }
Ejemplo n.º 51
0
        private void btnImprimer_Click(object sender, EventArgs e)
        {
            numeroFacture = dataGridViewListeFacture.Rows[indexRowListeFacture].Cells[0].Value.ToString();
            dateFacture   = dataGridViewListeFacture.Rows[indexRowListeFacture].Cells[1].Value.ToString().Substring(0, 10);
            dateEcheance  = dataGridViewListeFacture.Rows[indexRowListeFacture].Cells[2].Value.ToString().Substring(0, 10);

            codeLigue = dataGridViewListeFacture.Rows[indexRowListeFacture].Cells[3].Value.ToString();
            totalTtc  = dataGridViewListeFacture.Rows[indexRowListeFacture].Cells[4].Value.ToString();

            var           connectionString = "SERVER=localhost" + ";" + "DATABASE=m2l" + ";" + "UID=root" + ";" + "PASSWORD="******";" + "CHARSET=utf8" + ";";
            List <string> quantites        = new List <string>();

            using (var connection = new MySqlConnection(connectionString))
            {
                connection.Open();
                var query = "SELECT * FROM ligne_facture WHERE NumeroFacture='" + numeroFacture + "'";
                using (var command = new MySqlCommand(query, connection))
                {
                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            quantites.Add(reader.GetString("Quantite"));
                        }
                        quantiteAffranchissement = float.Parse(quantites[0]).ToString("0.00");

                        quantitePhotocouleur = float.Parse(quantites[1]).ToString("0.00");

                        quantitePhotoNb = float.Parse(quantites[2]).ToString("0.00");

                        quantiteTraceur = float.Parse(quantites[3]).ToString("0.00");
                    }
                    var query2 = "SELECT * FROM ligue WHERE CodeLigue='" + codeLigue + "'";
                    using (var command2 = new MySqlCommand(query2, connection))
                    {
                        using (var reader = command2.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                nomLigue        = reader.GetString("NomLigue");
                                nomTresorier    = reader.GetString("NomTresorier");
                                prenomTresorier = reader.GetString("PrenomTresorier");
                                // adresseTresorier=reader.GetString("AdresseTresorier");
                                // codePostalTresorier = reader.GetString("CodePostalTresorier");
                                // communeTresorier=reader.GetString("CommuneTresorier");

                                // gestionnaire = reader.GetString("NomTresorier") + " " + reader.GetString("PrenomTresorier");
                                //ligue = where;
                                //codeClient = reader.GetString("CodeLigue");
                                //adresseTresorier = reader.GetString("AdresseTresorier");
                                //codePostal = reader.GetString("CodePostalTresorier");
                                //commune = reader.GetString("CommuneTresorier");
                            }
                        }
                    }
                }
                prixAffranchissement    = 3.330;
                prixPhotocouleur        = 0.240;
                prixPhotoNb             = 0.055;
                prixTraceur             = 0.356;
                montantAffranchissement = (float.Parse(quantiteAffranchissement) * prixAffranchissement).ToString("0.00");
                montantPhotocouleur     = (float.Parse(quantitePhotocouleur) * prixPhotocouleur).ToString("0.00");
                montantPhotoNb          = (float.Parse(quantitePhotoNb) * prixPhotoNb).ToString("0.00");
                montantTraceur          = (float.Parse(quantiteTraceur) * prixTraceur).ToString("0.00");

                Document nouveauDocument = new Document();


                FileStream fs     = new FileStream(@"c:\Users\OSN\Desktop\Chapter1_Example1.pdf", FileMode.Create, FileAccess.Write, FileShare.None);
                PdfWriter  writer = PdfWriter.GetInstance(nouveauDocument, fs);
                nouveauDocument.Open();


                //////////////////////////////////////////////////////////////////////////
                ////////////Déclaration des images et des varables de police//////////////
                //////////////////////////////////////////////////////////////////////////
                iTextSharp.text.Image CVCrosl = iTextSharp.text.Image.GetInstance("C:/Users/OSN/Desktop/CarteVisiteCrosl.JPG");
                //Image CVCrosl = Image.GetInstance("C:/Users/OSN/Desktop/CarteVisiteCrosl.JPG");
                iTextSharp.text.Image Logo = iTextSharp.text.Image.GetInstance("C:/Users/OSN/Desktop/LogoCrol.JPG");
                //Image Logo = Image.GetInstance("C:/Users/OSN/Desktop/LogoCrol.JPG");
                var    boldFont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10);
                var    adresse  = FontFactory.GetFont(FontFactory.HELVETICA, 10);
                var    texte    = FontFactory.GetFont(FontFactory.HELVETICA, 10);
                Chunk  test     = new Chunk();
                Phrase test2    = new Phrase(test);
                Chunk  test3    = new Chunk("    Maison Régionale des Sports de Lorraine \n    13 rue Jean Moulin \n \n    54510 TOMBLAINE \n    FRANCE METROPOLITAINE", adresse);
                // Chunk test3 = new Chunk("    " + adresseTresorier + "\n    " + codePostalTresorier + "\n    " + communeTresorier + "\n    FRANCE", adresse);
                test2.Add(test3);



                Paragraph adressestr = new Paragraph(" \n \n \n \n \n \n \n \n    " + nomLigue + " \n \n    A l'attention de " + nomTresorier + " " + prenomTresorier + " \n", boldFont);
                adressestr.Add(test2);
                //////////////////////////////////////////////
                ///////////////Mise en Page PDF///////////////
                //////////////////////////////////////////////

                //////////////////HEAD (Adresse CROSL Et trésorier + LOGOS)////////////////////////

                int[]     intTblWidth = { 8, 8, 3 };
                PdfPTable tableauHead = new PdfPTable(3);
                PdfPCell  celluleHead = new PdfPCell();
                tableauHead.TotalWidth = 540;
                tableauHead.SetWidths(intTblWidth);
                tableauHead.DefaultCell.BorderColor = new BaseColor(255, 255, 255);
                tableauHead.LockedWidth             = true;
                celluleHead.Colspan = 3;
                tableauHead.AddCell(celluleHead);
                tableauHead.AddCell(CVCrosl);
                tableauHead.AddCell(adressestr);
                tableauHead.AddCell(Logo);
                nouveauDocument.Add(tableauHead);

                ///////////////////En-tête de la facture//////////////////////////
                nouveauDocument.Add(new Phrase("FACTURE                                                                                                          ", boldFont));
                Phrase EcheanceText = new Phrase("ECHEANCE", texte);
                nouveauDocument.Add(EcheanceText);

                //////////////////Facture (Infos clients et dates)/////////////////////
                //Déclaration des contenus
                //A ne pas modifier !
                Phrase Date       = new Phrase("Date", adresse);
                Phrase Numero     = new Phrase("Numéro", adresse);
                Phrase CodeClient = new Phrase("Code Client", adresse);
                Phrase Echeance   = new Phrase("Echéance", adresse);
                //A Modifier !
                Phrase ValDate        = new Phrase(dateFacture, adresse);
                Phrase ValNum         = new Phrase(numeroFacture, adresse);
                Phrase ValCodeCli     = new Phrase(codeLigue, adresse);
                Phrase ValDatecheance = new Phrase(dateEcheance, adresse);
                // Phrase ValDatecheance = new Phrase(date.ToString("dd/MM/yyyy"), adresse);

                //Première ligne du tableau (Désignation des valeurs)
                int[]     intTblWidth2 = { 4, 4, 4, 4, 4 };
                PdfPTable tableauFact1 = new PdfPTable(5);
                PdfPCell  celluleFact1 = new PdfPCell();
                tableauFact1.TotalWidth = 540;
                tableauFact1.SetWidths(intTblWidth2);
                tableauFact1.DefaultCell.BorderColor     = new BaseColor(255, 255, 255);
                tableauFact1.DefaultCell.BackgroundColor = new BaseColor(253, 253, 213);
                tableauFact1.LockedWidth = true;
                celluleFact1.Colspan     = 5;
                tableauFact1.AddCell(Date);
                tableauFact1.AddCell(Numero);
                tableauFact1.AddCell("");
                tableauFact1.AddCell(CodeClient);
                tableauFact1.AddCell(Echeance);
                nouveauDocument.Add(tableauFact1);
                //Deuxième Ligne du tableau (avec les valeurs)
                PdfPTable tableauFact2 = new PdfPTable(5);
                PdfPCell  celluleFact2 = new PdfPCell();
                tableauFact2.TotalWidth = 540;
                tableauFact2.SetWidths(intTblWidth2);
                tableauFact2.DefaultCell.BorderColor = new BaseColor(255, 255, 255);
                tableauFact2.LockedWidth             = true;
                celluleFact2.Colspan = 5;
                tableauFact2.AddCell(ValDate);
                tableauFact2.AddCell(ValNum);
                tableauFact2.AddCell("");
                tableauFact2.AddCell(ValCodeCli);
                tableauFact2.AddCell(ValDatecheance);
                nouveauDocument.Add(tableauFact2);

                //////////////////Saut de ligne/////////////////////
                Phrase SautLigne = new Phrase("\n");
                nouveauDocument.Add(SautLigne);

                /////////////////////Ligne Facture (Prix et Quantité)////////////////////////
                //Déclaration des contenus
                //A ne pas Modifier
                Phrase Reference   = new Phrase("Référence", adresse);
                Phrase Designation = new Phrase("Désignation", adresse);
                Phrase Quantite    = new Phrase("Qté", adresse);
                Phrase PrixU       = new Phrase("P.U. HT", adresse);
                Phrase MontantTTC  = new Phrase("Montant TTC", adresse);
                //A Modifier
                Phrase ValRef        = new Phrase("...........", adresse);
                Phrase ValDesign     = new Phrase("..............................", adresse);
                Phrase ValQuantite   = new Phrase("0,00", adresse);
                Phrase ValPrix       = new Phrase("0,000", adresse);
                Phrase ValMontant    = new Phrase("0,00", adresse);
                Phrase totalTTC      = new Phrase("\n\n\n\n\n\n\n\n\n\n\n\n\n                                                                                             TOTAL TTC                                   " + totalTtc + "€", boldFont);
                Phrase montantAPayer = new Phrase("\n\n\n\n                                                                                             MONTANT A PAYER                    " + totalTtc + "€", boldFont);

                //Première ligne du tableau
                int[]     intTblWidth3      = { 4, 8, 2, 2, 4 };
                PdfPTable tableauLigneFact1 = new PdfPTable(5);
                PdfPCell  celluleLigneFact1 = new PdfPCell();
                tableauLigneFact1.TotalWidth = 540;
                tableauLigneFact1.SetWidths(intTblWidth3);
                tableauLigneFact1.DefaultCell.BorderColor     = new BaseColor(255, 255, 255);
                tableauLigneFact1.DefaultCell.BackgroundColor = new BaseColor(253, 253, 213);
                tableauLigneFact1.LockedWidth = true;
                celluleLigneFact1.Colspan     = 5;
                tableauLigneFact1.AddCell(Reference);
                tableauLigneFact1.AddCell(Designation);
                tableauLigneFact1.AddCell(Quantite);
                tableauLigneFact1.AddCell(PrixU);
                tableauLigneFact1.AddCell(MontantTTC);
                nouveauDocument.Add(tableauLigneFact1);
                //Deuxième ligne du tableau
                PdfPTable tableauLigneFact2 = new PdfPTable(5);
                PdfPCell  celluleLigneFact2 = new PdfPCell();
                tableauLigneFact2.TotalWidth = 540;
                tableauLigneFact2.SetWidths(intTblWidth3);
                tableauLigneFact2.DefaultCell.BorderColor = new BaseColor(255, 255, 255);
                tableauLigneFact2.LockedWidth             = true;
                celluleLigneFact2.Colspan = 5;
                tableauLigneFact2.AddCell("AFFRAN");
                tableauLigneFact2.AddCell("Affranchissement");
                tableauLigneFact2.AddCell(quantiteAffranchissement);
                tableauLigneFact2.AddCell(prixAffranchissement.ToString() + "0");
                tableauLigneFact2.AddCell(montantAffranchissement + "€");
                tableauLigneFact2.AddCell("PHOTOCOULEUR");
                tableauLigneFact2.AddCell("Photocopies couleur");
                tableauLigneFact2.AddCell(quantitePhotocouleur);
                tableauLigneFact2.AddCell(prixPhotocouleur.ToString() + "0");
                tableauLigneFact2.AddCell(montantPhotocouleur + "€");
                tableauLigneFact2.AddCell("PHOTON&B");
                tableauLigneFact2.AddCell("Photocopies noir et blanc");
                tableauLigneFact2.AddCell(quantitePhotoNb);
                tableauLigneFact2.AddCell(prixPhotoNb.ToString());
                tableauLigneFact2.AddCell(montantPhotoNb + "€");
                tableauLigneFact2.AddCell("TRACEUR");
                tableauLigneFact2.AddCell("Utilisation du traceur");
                tableauLigneFact2.AddCell(quantiteTraceur);
                tableauLigneFact2.AddCell(prixTraceur.ToString());
                tableauLigneFact2.AddCell(montantTraceur + "€");
                nouveauDocument.Add(tableauLigneFact2);
                nouveauDocument.Add(totalTTC);
                nouveauDocument.Add(montantAPayer);
                Phrase footer = new Phrase("\n\n\nDéclaré à la préfecture de Meurthe et Moselle N°3898\nDomiciliation bancaire 10278 04065 00016911045 05\nMerci de bien vouloir préciser les références de la facture acquittée\nTVA non applicable", adresse);
                nouveauDocument.Add(footer);

                ////////////////////////////////////////////////////////////
                ////////////////////////Ferme le PDF////////////////////////
                ////////////////////////////////////////////////////////////
                nouveauDocument.Close();
                System.Diagnostics.Process.Start(@"c:\Users\OSN\Desktop\Chapter1_Example1.pdf");
            }
        }
Ejemplo n.º 52
0
        public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)
        {
            base.OnEndPage(writer, document);

            iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);

            iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);

            iTextSharp.text.Font time = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA, 11f, Font.NORMAL);

            Image logo = Image.GetInstance(HttpContext.Current.Server.MapPath("~/assets/images/SLEmpresarial.png"));

            logo.ScaleToFit(150f, 62f);

            Phrase p1Header = new Phrase("PROPUESTA TÉCNICO ECONÓMICA\n EXÁMENES MÉDICOS\n OCUPACIONALES", baseFontNormal);

            //Create PdfTable object
            PdfPTable pdfTab = new PdfPTable(3);

            float[] width = { 100f, 320f, 100f };
            pdfTab.SetWidths(width);
            pdfTab.TotalWidth  = 520f;
            pdfTab.LockedWidth = true;


            //We will have to create separate cells to include image logo and 2 separate strings
            //Row 1
            PdfPCell pdfCell1 = new PdfPCell(logo);
            PdfPCell pdfCell2 = new PdfPCell(p1Header);
            String   text     = "Página " + writer.PageNumber + " de ";


            //Add paging to header
            {
                cb.BeginText();
                cb.SetFontAndSize(bf, 12);
                cb.SetTextMatrix(document.PageSize.GetRight(120), document.PageSize.GetTop(45));
                cb.ShowText(text);
                cb.EndText();
                float len = bf.GetWidthPoint(text, 12);
                //Adds "12" in Page 1 of 12
                cb.AddTemplate(headerTemplate, document.PageSize.GetRight(120) + len, document.PageSize.GetTop(45));
            }
            //Add paging to footer
            {
                Image logoSoftware = Image.GetInstance(HttpContext.Current.Server.MapPath("~/assets/images/SLEmpresarial.png"));
                logoSoftware.ScaleToFit(140f, 50f);

                var leftCol  = new Paragraph("Mukesh Salaria\n" + "Software Engineer", time);
                var rightCol = new Paragraph("saluslaboris.com.pe\n", time);
                var phone    = new Paragraph("Teléfono: (511) 6407309", time);
                var address  = new Paragraph("     ESTE DOCUMENTO ES PROPIEDAD\n" + "      INTELECTUAL DE SALUS LABORIS", time);
                var fax      = new Paragraph("Av. Alfredo Benavides 4994\n Surco", time);

                leftCol.Alignment  = Element.ALIGN_LEFT;
                rightCol.Alignment = Element.ALIGN_RIGHT;
                fax.Alignment      = Element.ALIGN_RIGHT;
                phone.Alignment    = Element.ALIGN_LEFT;
                address.Alignment  = Element.ALIGN_CENTER;

                var footerTbl = new PdfPTable(3)
                {
                    TotalWidth = 520f, HorizontalAlignment = Element.ALIGN_CENTER, LockedWidth = true
                };
                float[] widths = { 150f, 220f, 150f };
                footerTbl.SetWidths(widths);
                var footerCell1 = new PdfPCell(logoSoftware);
                var footerCell2 = new PdfPCell();
                var footerCell3 = new PdfPCell(rightCol);
                var sep         = new PdfPCell();
                var footerCell4 = new PdfPCell(phone);
                var footerCell5 = new PdfPCell(address);
                var footerCell6 = new PdfPCell(fax);


                footerCell1.Border = 0;
                footerCell2.Border = 0;
                footerCell3.Border = 0;
                footerCell4.Border = 0;
                footerCell5.Border = 0;
                footerCell6.Border = 0;
                footerCell6.HorizontalAlignment = Element.ALIGN_RIGHT;
                sep.Border      = 0;
                sep.FixedHeight = 10f;
                footerCell3.HorizontalAlignment = Element.ALIGN_RIGHT;
                footerCell6.PaddingLeft         = 0;
                sep.Colspan = 3;

                footerTbl.AddCell(footerCell1);
                footerTbl.AddCell(footerCell2);
                footerTbl.AddCell(footerCell3);
                footerTbl.AddCell(sep);
                footerTbl.AddCell(footerCell4);
                footerTbl.AddCell(footerCell5);
                footerTbl.AddCell(footerCell6);
                footerTbl.WriteSelectedRows(0, -1, 40, 80, writer.DirectContent);
            }


            PdfPCell pdfCell3 = new PdfPCell();
            PdfPCell pdfCell4 = new PdfPCell();
            PdfPCell pdfCell5 = new PdfPCell(new Phrase(""));

            //set the alignment of all three cells and set border to 0
            pdfCell1.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfCell2.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell3.HorizontalAlignment = Element.ALIGN_RIGHT;
            pdfCell5.HorizontalAlignment = Element.ALIGN_RIGHT;

            pdfCell2.PaddingTop = 9f;
            pdfCell3.PaddingTop = 20f;
            pdfCell5.PaddingTop = 9f;

            pdfCell1.Border = 0;
            pdfCell2.Border = 0;
            pdfCell3.Border = 0;
            pdfCell4.Border = 0;
            pdfCell5.Border = 0;

            //add all three cells into PdfTable
            pdfTab.AddCell(pdfCell1);
            pdfTab.AddCell(pdfCell2);
            pdfTab.AddCell(pdfCell3);
            pdfTab.AddCell(pdfCell4);
            pdfTab.AddCell(pdfCell5);

            pdfTab.TotalWidth  = 520f;
            pdfTab.LockedWidth = true;

            //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, 40, document.PageSize.Height - 30, writer.DirectContent);

            //Move the pointer and draw line to separate header section from rest of page
            cb.MoveTo(40, document.PageSize.Height - 100);
            cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 100);
            cb.Stroke();

            //Move the pointer and draw line to separate footer section from rest of page
            cb.MoveTo(40, document.PageSize.GetBottom(50));
            cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50));
            cb.Stroke();
        }
Ejemplo n.º 53
0
        private void listaDeInscriçõesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                Eventos eventoSelecionado = (Eventos)listViewEventos.SelectedItems[0].Tag;

                saveFileDialog_Save.FileName    = "ListaInscricoes_" + eventoSelecionado.Descricao + ".pdf";
                saveFileDialog_Save.Filter      = "All files (*.*)|*.*";
                saveFileDialog_Save.FilterIndex = 0;

                if (saveFileDialog_Save.ShowDialog() == DialogResult.OK)
                {
                    Document doc = new Document(PageSize.A4);
                    doc.SetMargins(60, 60, 30, 30);

                    PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(saveFileDialog_Save.FileName, FileMode.Create));

                    doc.Open();

                    //Font fontH1 = new Font(Currier, 16, Font.Bold);

                    // <---------------- Título ---------------->

                    Paragraph titulo = new Paragraph("Lista de Inscrições\n");
                    titulo.Alignment = Element.TITLE;


                    // <---------------- Informações sobre o Evento ---------------->

                    Paragraph evento   = new Paragraph("\n\nEvento: " + eventoSelecionado.Descricao);
                    Paragraph local    = new Paragraph("Local: " + eventoSelecionado.Local);
                    Paragraph data     = new Paragraph(string.Format("Data: {0:dd} de {0:MMMM} de {0:yyyy}", eventoSelecionado.DataHora));
                    Paragraph hora     = new Paragraph(string.Format("Hora: {0:HH:mm:ss}", eventoSelecionado.DataHora));
                    Paragraph limite   = new Paragraph("Limite de Participação: " + eventoSelecionado.LimiteParticipacao + " crianças");
                    Paragraph idadeInf = new Paragraph("Idade Mínima: " + eventoSelecionado.IdadeInferior + " anos");
                    Paragraph idadeSup = new Paragraph("Idade Máxima: " + eventoSelecionado.IdadeSuperior + " anos\n\n\n\n");

                    evento.Alignment   = Element.ALIGN_JUSTIFIED;
                    local.Alignment    = Element.ALIGN_JUSTIFIED;
                    data.Alignment     = Element.ALIGN_JUSTIFIED;
                    hora.Alignment     = Element.ALIGN_JUSTIFIED;
                    limite.Alignment   = Element.ALIGN_JUSTIFIED;
                    idadeInf.Alignment = Element.ALIGN_JUSTIFIED;
                    idadeSup.Alignment = Element.ALIGN_JUSTIFIED;


                    // <---------------- Tabela ---------------->

                    PdfPTable table = new PdfPTable(5);


                    Paragraph coluna1 = new Paragraph("Nome");
                    Paragraph coluna2 = new Paragraph("Idade");
                    Paragraph coluna3 = new Paragraph("Responsável");
                    Paragraph coluna4 = new Paragraph("Telefone");
                    Paragraph coluna5 = new Paragraph("Telemóvel");

                    coluna1.Alignment = Element.ALIGN_CENTER;
                    coluna2.Alignment = Element.ALIGN_CENTER;
                    coluna3.Alignment = Element.ALIGN_CENTER;
                    coluna4.Alignment = Element.ALIGN_CENTER;
                    coluna5.Alignment = Element.ALIGN_CENTER;


                    var cell1 = new PdfPCell();
                    var cell2 = new PdfPCell();
                    var cell3 = new PdfPCell();
                    var cell4 = new PdfPCell();
                    var cell5 = new PdfPCell();

                    cell1.AddElement(coluna1);
                    cell2.AddElement(coluna2);
                    cell3.AddElement(coluna3);
                    cell4.AddElement(coluna4);
                    cell5.AddElement(coluna5);

                    table.AddCell(cell1);
                    table.AddCell(cell2);
                    table.AddCell(cell3);
                    table.AddCell(cell4);
                    table.AddCell(cell5);

                    foreach (Inscricoes i in eventoSelecionado.Inscricoes.ToList <Inscricoes>())
                    {
                        Phrase nome = new Phrase(i.Filhos.Nome);
                        var    cell = new PdfPCell(nome);
                        table.AddCell(cell);

                        Phrase idade = new Phrase(Convert.ToString(i.Filhos.Idade()));
                        cell = new PdfPCell(idade);
                        table.AddCell(cell);

                        Phrase responsavel = new Phrase(i.Filhos.Clientes.Nome);
                        cell = new PdfPCell(responsavel);
                        table.AddCell(cell);

                        Phrase telefone = new Phrase(i.Filhos.Telefone);
                        cell = new PdfPCell(telefone);
                        table.AddCell(cell);

                        Phrase telemovel = new Phrase(i.Filhos.Telemovel);
                        cell = new PdfPCell(telemovel);
                        table.AddCell(cell);
                    }


                    // <---------------- Adicionar os dados todos ao documento ---------------->

                    doc.Add(titulo);
                    doc.Add(evento);
                    doc.Add(local);
                    doc.Add(data);
                    doc.Add(hora);
                    doc.Add(limite);
                    doc.Add(idadeInf);
                    doc.Add(idadeSup);
                    doc.Add(table);

                    doc.Close();

                    MessageBox.Show("Lista de Inscrições guardada com sucesso!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch
            {
                MessageBox.Show("Selecione o evento primeiro!", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
Ejemplo n.º 54
0
        public void pdfCreator(TextBox firstName, TextBox lastName, TextBox idNumber, TextBox contactNumber, TextBox medicalNumber, TextBox medicalType, TextBox DOB, ComboBox gender, TextBox emailAddress, TextBox Address)
        {
            try
            {
                #region Common Part
                PdfPTable table = new PdfPTable(1);

                //Footer Section
                PdfPTable footer = new PdfPTable(1);
                footer.DefaultCell.BorderWidth         = 0;
                footer.WidthPercentage                 = 100;
                footer.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;

                Chunk cFooter = new Chunk("This is the Footer", FontFactory.GetFont("Times New Roman"));
                cFooter.Font.Size = 8;
                footer.AddCell(new Phrase(cFooter));
                // End Footer

                table.AddCell(new Phrase(" "));
                table.DefaultCell.Border = 0;
                #endregion

                #region Page
                #region Section-1 <Header FORM>
                PdfPTable pdftable1 = new PdfPTable(1);
                PdfPTable pdftable2 = new PdfPTable(1);
                PdfPTable pdftable3 = new PdfPTable(2);


                // This is the 3 tables created
                pdftable1.WidthPercentage = 80;
                pdftable1.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
                pdftable1.DefaultCell.VerticalAlignment   = Element.ALIGN_CENTER;
                pdftable1.DefaultCell.BorderWidth         = 0;

                pdftable2.WidthPercentage = 80;
                pdftable2.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
                pdftable2.DefaultCell.VerticalAlignment   = Element.ALIGN_CENTER;
                pdftable2.DefaultCell.BorderWidth         = 0;

                pdftable3.DefaultCell.Padding     = 5;
                pdftable3.WidthPercentage         = 80;
                pdftable3.DefaultCell.BorderWidth = 0.5f;

                Chunk c1 = new Chunk("Doctor DB", FontFactory.GetFont("Times New Roman"));
                c1.Font.Color = new iTextSharp.text.BaseColor(0, 0, 0);
                c1.Font.SetStyle(0);
                c1.Font.Size = 14;
                Phrase p1 = new Phrase();
                p1.Add(c1);
                pdftable1.AddCell(p1);

                Chunk c2 = new Chunk("This is the PDF Form", FontFactory.GetFont("Times New Roman"));
                c2.Font.Color = new iTextSharp.text.BaseColor(0, 0, 0);
                c2.Font.SetStyle(0);
                c2.Font.Size = 11;
                Phrase p2 = new Phrase();
                p2.Add(c2);
                pdftable2.AddCell(p2);

                Chunk c3 = new Chunk("Created by - Fawaaz Dassie 24/04/2019", FontFactory.GetFont("Times New Roman"));
                c3.Font.Color = new iTextSharp.text.BaseColor(0, 0, 0);
                c3.Font.SetStyle(0);
                c3.Font.Size = 10;
                Phrase p3 = new Phrase();
                p3.Add(c3);
                pdftable2.AddCell(p3);
                #endregion

                #region Section <Bill Upper>
                PdfPTable pdfTable4 = new PdfPTable(4);
                pdfTable4.DefaultCell.Padding     = 5;
                pdfTable4.WidthPercentage         = 80;
                pdfTable4.DefaultCell.BorderWidth = 0.0f;

                #endregion


                #region SelectionTable
                pdftable3.AddCell(new Phrase("Full name:"));
                pdftable3.AddCell(new Phrase(string.Format("{0} {1}", firstName.Text, lastName.Text)));

                pdftable3.AddCell(new Phrase("ID Number"));
                pdftable3.AddCell(new Phrase(idNumber.Text));

                pdftable3.AddCell(new Phrase("Contact Number"));
                pdftable3.AddCell(new Phrase(contactNumber.Text));

                pdftable3.AddCell(new Phrase("Medical Aid Number"));
                pdftable3.AddCell(new Phrase(medicalNumber.Text));

                pdftable3.AddCell(new Phrase("Medical Aid Type"));
                pdftable3.AddCell(new Phrase(medicalType.Text));

                pdftable3.AddCell(new Phrase("DOB"));
                pdftable3.AddCell(new Phrase(DOB.Text));

                pdftable3.AddCell(new Phrase("Gender"));
                pdftable3.AddCell(new Phrase(gender.Text));

                pdftable3.AddCell(new Phrase("Email"));
                pdftable3.AddCell(new Phrase(emailAddress.Text));

                pdftable3.AddCell(new Phrase("Address"));
                pdftable3.AddCell(new Phrase(Address.Text));
                #endregion


                #region PDF Generation
                string folderPath = @"C:\Users\fdassie\Desktop\";

                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }

                // File Name
                int    fileCount   = Directory.GetFiles(@"C:\Users\fdassie\Desktop\").Length;
                string strFileName = "TestPdf" + (fileCount + 1) + ".pdf";

                using (FileStream stream = new FileStream(folderPath + strFileName, FileMode.Create))
                {
                    Document doc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
                    PdfWriter.GetInstance(doc, stream);
                    doc.Open();

                    #region Page-1
                    doc.Add(pdftable1);
                    doc.Add(pdftable2);
                    doc.Add(table);
                    doc.Add(pdftable3);
                    doc.Add(footer);
                    doc.NewPage();
                    #endregion

                    doc.Close();
                    stream.Close();
                }
                #endregion

                #region Display PDF
                System.Diagnostics.Process.Start(folderPath + "\\" + strFileName);
                #endregion
            }
            catch (Exception ex)
            {
                throw;
            }
            #endregion
        }
Ejemplo n.º 55
0
 /**
  * Simplified method for rectangular columns.
  * @param phrase a <CODE>Phrase</CODE>
  * @param llx the lower left x corner
  * @param lly the lower left y corner
  * @param urx the upper right x corner
  * @param ury the upper right y corner
  * @param leading the leading
  * @param alignment the column alignment
  */
 public void SetSimpleColumn(Phrase phrase, float llx, float lly, float urx, float ury, float leading, int alignment) {
     AddText(phrase);
     SetSimpleColumn(llx, lly, urx, ury, leading, alignment);
 }
Ejemplo n.º 56
0
 public PositionEvent(Phrase content, string pos)
 {
     this.content = content;
     this.pos     = pos;
 }
 public static Phrase Parse(IFuzzyState state, Phrase phrase) {
     return TokenReflection.CreateDescendants<TuesdayDaysVariableTemporalPrimitiveToken>(state, phrase);
 }
Ejemplo n.º 58
0
        /// <summary>
        /// Writes a Metatag in the header.
        /// @throws  IOException
        /// </summary>
        protected void Write(IElement element, int indent)
        {
            Properties styleAttributes = null;

            switch (element.Type)
            {
            case Element.MARKED:
            {
                try
                {
                    Add(element);
                }
                catch (DocumentException)
                {
                }
                return;
            }

            case Element.CHUNK:
            {
                Chunk chunk = (Chunk)element;
                // if the chunk contains an image, return the image representation
                Image image = chunk.GetImage();
                if (image != null)
                {
                    Write(image, indent);
                    return;
                }

                if (chunk.IsEmpty())
                {
                    return;
                }
                Hashtable attributes = chunk.Attributes;
                if (attributes != null && attributes[Chunk.NEWPAGE] != null)
                {
                    return;
                }
                bool tag = IsOtherFont(chunk.Font) || Markup.Count > 0;
                if (tag)
                {
                    // start span tag
                    AddTabs(indent);
                    WriteStart(HtmlTags.SPAN);
                    if (IsOtherFont(chunk.Font))
                    {
                        Write(chunk.Font, null);
                    }
                    WriteMarkupAttributes(Markup);
                    Os.WriteByte(GT);
                }
                if (attributes != null && attributes[Chunk.SUBSUPSCRIPT] != null)
                {
                    // start sup or sub tag
                    if ((float)attributes[Chunk.SUBSUPSCRIPT] > 0)
                    {
                        WriteStart(HtmlTags.SUP);
                    }
                    else
                    {
                        WriteStart(HtmlTags.SUB);
                    }
                    Os.WriteByte(GT);
                }
                // contents
                Write(HtmlEncoder.Encode(chunk.Content));
                if (attributes != null && attributes[Chunk.SUBSUPSCRIPT] != null)
                {
                    // end sup or sub tag
                    Os.WriteByte(LT);
                    Os.WriteByte(FORWARD);
                    if ((float)attributes[Chunk.SUBSUPSCRIPT] > 0)
                    {
                        Write(HtmlTags.SUP);
                    }
                    else
                    {
                        Write(HtmlTags.SUB);
                    }
                    Os.WriteByte(GT);
                }
                if (tag)
                {
                    // end tag
                    WriteEnd(html.Markup.HTML_TAG_SPAN);
                }
                return;
            }

            case Element.PHRASE:
            {
                Phrase phrase = (Phrase)element;
                styleAttributes = new Properties();
                if (phrase.HasLeading())
                {
                    styleAttributes[html.Markup.CSS_KEY_LINEHEIGHT] = phrase.Leading + "pt";
                }

                // start tag
                AddTabs(indent);
                WriteStart(html.Markup.HTML_TAG_SPAN);
                WriteMarkupAttributes(Markup);
                Write(phrase.Font, styleAttributes);
                Os.WriteByte(GT);
                Currentfont.Push(phrase.Font);
                // contents
                foreach (IElement i in phrase)
                {
                    Write(i, indent + 1);
                }
                // end tag
                AddTabs(indent);
                WriteEnd(html.Markup.HTML_TAG_SPAN);
                Currentfont.Pop();
                return;
            }

            case Element.ANCHOR:
            {
                Anchor anchor = (Anchor)element;
                styleAttributes = new Properties();
                if (anchor.HasLeading())
                {
                    styleAttributes[html.Markup.CSS_KEY_LINEHEIGHT] = anchor.Leading + "pt";
                }

                // start tag
                AddTabs(indent);
                WriteStart(HtmlTags.ANCHOR);
                if (anchor.Name != null)
                {
                    Write(HtmlTags.NAME, anchor.Name);
                }
                if (anchor.Reference != null)
                {
                    Write(HtmlTags.REFERENCE, anchor.Reference);
                }
                WriteMarkupAttributes(Markup);
                Write(anchor.Font, styleAttributes);
                Os.WriteByte(GT);
                Currentfont.Push(anchor.Font);
                // contents
                foreach (IElement i in anchor)
                {
                    Write(i, indent + 1);
                }
                // end tag
                AddTabs(indent);
                WriteEnd(HtmlTags.ANCHOR);
                Currentfont.Pop();
                return;
            }

            case Element.PARAGRAPH:
            {
                Paragraph paragraph = (Paragraph)element;
                styleAttributes = new Properties();
                if (paragraph.HasLeading())
                {
                    styleAttributes[html.Markup.CSS_KEY_LINEHEIGHT] = paragraph.TotalLeading + "pt";
                }

                // start tag
                AddTabs(indent);
                WriteStart(HtmlTags.DIV);
                WriteMarkupAttributes(Markup);
                string alignment = HtmlEncoder.GetAlignment(paragraph.Alignment);
                if (!"".Equals(alignment))
                {
                    Write(HtmlTags.ALIGN, alignment);
                }
                Write(paragraph.Font, styleAttributes);
                Os.WriteByte(GT);
                Currentfont.Push(paragraph.Font);
                // contents
                foreach (IElement i in paragraph)
                {
                    Write(i, indent + 1);
                }
                // end tag
                AddTabs(indent);
                WriteEnd(HtmlTags.DIV);
                Currentfont.Pop();
                return;
            }

            case Element.SECTION:
            case Element.CHAPTER:
            {
                // part of the start tag + contents
                WriteSection((Section)element, indent);
                return;
            }

            case Element.LIST:
            {
                List list = (List)element;
                // start tag
                AddTabs(indent);
                if (list.Numbered)
                {
                    WriteStart(HtmlTags.ORDEREDLIST);
                }
                else
                {
                    WriteStart(HtmlTags.UNORDEREDLIST);
                }
                WriteMarkupAttributes(Markup);
                Os.WriteByte(GT);
                // contents
                foreach (IElement i in list.Items)
                {
                    Write(i, indent + 1);
                }
                // end tag
                AddTabs(indent);
                if (list.Numbered)
                {
                    WriteEnd(HtmlTags.ORDEREDLIST);
                }
                else
                {
                    WriteEnd(HtmlTags.UNORDEREDLIST);
                }
                return;
            }

            case Element.LISTITEM:
            {
                ListItem listItem = (ListItem)element;
                styleAttributes = new Properties();
                if (listItem.HasLeading())
                {
                    styleAttributes[html.Markup.CSS_KEY_LINEHEIGHT] = listItem.TotalLeading + "pt";
                }

                // start tag
                AddTabs(indent);
                WriteStart(HtmlTags.LISTITEM);
                WriteMarkupAttributes(Markup);
                Write(listItem.Font, styleAttributes);
                Os.WriteByte(GT);
                Currentfont.Push(listItem.Font);
                // contents
                foreach (IElement i in listItem)
                {
                    Write(i, indent + 1);
                }
                // end tag
                AddTabs(indent);
                WriteEnd(HtmlTags.LISTITEM);
                Currentfont.Pop();
                return;
            }

            case Element.CELL:
            {
                Cell cell = (Cell)element;

                // start tag
                AddTabs(indent);
                if (cell.Header)
                {
                    WriteStart(HtmlTags.HEADERCELL);
                }
                else
                {
                    WriteStart(HtmlTags.CELL);
                }
                WriteMarkupAttributes(Markup);
                if (cell.BorderWidth.ApproxNotEqual(Rectangle.UNDEFINED))
                {
                    Write(HtmlTags.BORDERWIDTH, cell.BorderWidth.ToString(CultureInfo.InvariantCulture));
                }
                if (cell.BorderColor != null)
                {
                    Write(HtmlTags.BORDERCOLOR, HtmlEncoder.Encode(cell.BorderColor));
                }
                if (cell.BackgroundColor != null)
                {
                    Write(HtmlTags.BACKGROUNDCOLOR, HtmlEncoder.Encode(cell.BackgroundColor));
                }
                string alignment = HtmlEncoder.GetAlignment(cell.HorizontalAlignment);
                if (!"".Equals(alignment))
                {
                    Write(HtmlTags.HORIZONTALALIGN, alignment);
                }
                alignment = HtmlEncoder.GetAlignment(cell.VerticalAlignment);
                if (!"".Equals(alignment))
                {
                    Write(HtmlTags.VERTICALALIGN, alignment);
                }
                if (cell.GetWidthAsString() != null)
                {
                    Write(HtmlTags.WIDTH, cell.GetWidthAsString());
                }
                if (cell.Colspan != 1)
                {
                    Write(HtmlTags.COLSPAN, cell.Colspan.ToString());
                }
                if (cell.Rowspan != 1)
                {
                    Write(HtmlTags.ROWSPAN, cell.Rowspan.ToString());
                }
                if (cell.MaxLines == 1)
                {
                    Write(HtmlTags.STYLE, "white-space: nowrap;");
                }
                Os.WriteByte(GT);
                // contents
                if (cell.IsEmpty())
                {
                    Write(NBSP);
                }
                else
                {
                    foreach (IElement i in cell.Elements)
                    {
                        Write(i, indent + 1);
                    }
                }
                // end tag
                AddTabs(indent);
                if (cell.Header)
                {
                    WriteEnd(HtmlTags.HEADERCELL);
                }
                else
                {
                    WriteEnd(HtmlTags.CELL);
                }
                return;
            }

            case Element.ROW:
            {
                Row row = (Row)element;

                // start tag
                AddTabs(indent);
                WriteStart(HtmlTags.ROW);
                WriteMarkupAttributes(Markup);
                Os.WriteByte(GT);
                // contents
                IElement cell;
                for (int i = 0; i < row.Columns; i++)
                {
                    if ((cell = (IElement)row.GetCell(i)) != null)
                    {
                        Write(cell, indent + 1);
                    }
                }
                // end tag
                AddTabs(indent);
                WriteEnd(HtmlTags.ROW);
                return;
            }

            case Element.TABLE:
            {
                Table table;
                try
                {
                    table = (Table)element;
                }
                catch (InvalidCastException)
                {
                    table = ((SimpleTable)element).CreateTable();
                }
                table.Complete();
                // start tag
                AddTabs(indent);
                WriteStart(HtmlTags.TABLE);
                WriteMarkupAttributes(Markup);
                Os.WriteByte(SPACE);
                Write(HtmlTags.WIDTH);
                Os.WriteByte(EQUALS);
                Os.WriteByte(QUOTE);
                Write(table.Width.ToString(CultureInfo.InvariantCulture));
                if (!table.Locked)
                {
                    Write("%");
                }
                Os.WriteByte(QUOTE);
                string alignment = HtmlEncoder.GetAlignment(table.Alignment);
                if (!"".Equals(alignment))
                {
                    Write(HtmlTags.ALIGN, alignment);
                }
                Write(HtmlTags.CELLPADDING, table.Cellpadding.ToString(CultureInfo.InvariantCulture));
                Write(HtmlTags.CELLSPACING, table.Cellspacing.ToString(CultureInfo.InvariantCulture));
                if (table.BorderWidth.ApproxNotEqual(Rectangle.UNDEFINED))
                {
                    Write(HtmlTags.BORDERWIDTH, table.BorderWidth.ToString(CultureInfo.InvariantCulture));
                }
                if (table.BorderColor != null)
                {
                    Write(HtmlTags.BORDERCOLOR, HtmlEncoder.Encode(table.BorderColor));
                }
                if (table.BackgroundColor != null)
                {
                    Write(HtmlTags.BACKGROUNDCOLOR, HtmlEncoder.Encode(table.BackgroundColor));
                }
                Os.WriteByte(GT);
                // contents
                foreach (Row row in table)
                {
                    Write(row, indent + 1);
                }
                // end tag
                AddTabs(indent);
                WriteEnd(HtmlTags.TABLE);
                return;
            }

            case Element.ANNOTATION:
            {
                Annotation annotation = (Annotation)element;
                WriteComment(annotation.Title + ": " + annotation.Content);
                return;
            }

            case Element.IMGRAW:
            case Element.JPEG:
            case Element.JPEG2000:
            case Element.IMGTEMPLATE:
            {
                Image image = (Image)element;
                if (image.Url == null)
                {
                    return;
                }

                // start tag
                AddTabs(indent);
                WriteStart(HtmlTags.IMAGE);
                string path = image.Url.ToString();
                if (Imagepath != null)
                {
                    if (path.IndexOf("/", StringComparison.Ordinal) > 0)
                    {
                        path = Imagepath + path.Substring(path.LastIndexOf("/", StringComparison.Ordinal) + 1);
                    }
                    else
                    {
                        path = Imagepath + path;
                    }
                }
                Write(HtmlTags.URL, path);
                if ((image.Alignment & Image.RIGHT_ALIGN) > 0)
                {
                    Write(HtmlTags.ALIGN, HtmlTags.ALIGN_RIGHT);
                }
                else if ((image.Alignment & Image.MIDDLE_ALIGN) > 0)
                {
                    Write(HtmlTags.ALIGN, HtmlTags.ALIGN_MIDDLE);
                }
                else
                {
                    Write(HtmlTags.ALIGN, HtmlTags.ALIGN_LEFT);
                }
                if (image.Alt != null)
                {
                    Write(HtmlTags.ALT, image.Alt);
                }
                Write(HtmlTags.PLAINWIDTH, image.ScaledWidth.ToString(CultureInfo.InvariantCulture));
                Write(HtmlTags.PLAINHEIGHT, image.ScaledHeight.ToString(CultureInfo.InvariantCulture));
                WriteMarkupAttributes(Markup);
                WriteEnd();
                return;
            }

            default:
                return;
            }
        }
Ejemplo n.º 59
0
        /**
        * Adds a cell element.
        * @param phrase the <CODE>Phrase</CODE> to be added to the cell
        */

        virtual public void AddCell(Phrase phrase)
        {
            defaultCell.Phrase = phrase;
            PdfPCell newCell = AddCell(defaultCell);
            newCell.id = new AccessibleElementId();
            defaultCell.Phrase = null;
        }
Ejemplo n.º 60
0
        public void PrintPO(poheader poh, List <podetail> PODetail, string taxStr)
        {
            Dictionary <string, string> companyInfo = getCompanyInformation();
            //string stateDetail =
            customer custDetail = CustomerDB.getCustomerDetailForPO(poh.CustomerID);

            string[] companyBillingAdd = CompanyAddressDB.getCompTopBillingAdd(Login.companyID);
            string   poNoSuffix        = "";

            if (poh.DocumentID == "POGENERAL")
            {
                poNoSuffix = "G-";
            }
            else if (poh.DocumentID == "PURCHASEORDER")
            {
                poNoSuffix = "P-";
            }
            string supplAdd = "Supplier:\n" + custDetail.name + Main.delimiter1 + "\n" + custDetail.BillingAddress + "\n";

            if (custDetail.StateName.ToString().Length != 0)
            {
                supplAdd = supplAdd + "Sate Name:" + custDetail.StateName;
            }
            if (custDetail.StateCode.ToString().Length != 0)
            {
                supplAdd = supplAdd + "\nState Code:" + custDetail.StateCode;
            }
            if (custDetail.OfficeName.ToString().Length != 0)
            {
                supplAdd = supplAdd + "\nGST:" + custDetail.OfficeName; // For GST Code
            }
            //; : main.delimiter2
            //$ : main.delimiter1
            string InvoiceTo    = "Invoice To: \n" + companyBillingAdd[0] + Main.delimiter1 + "\n" + companyBillingAdd[1] + "\nGST:" + companyInfo["GST"] + "\nCIN:" + companyInfo["CIN"] + "\nPAN:" + companyInfo["PAN"];
            string DespatchTo   = "Dispatch To:\n" + companyBillingAdd[0] + Main.delimiter1 + "\n" + poh.DeliveryAddress + "\nGST:" + companyInfo["GST"];
            string HeaderString = supplAdd +
                                  Main.delimiter2 + "PO No : " + poNoSuffix + poh.PONo + Main.delimiter2 + "Date: " + poh.PODate.ToString("dd-MM-yyyy") +
                                  Main.delimiter2 + "Supplier Ref./Order No.\n" + poh.ReferenceQuotation.Replace(";", ",\n") +
                                  Main.delimiter2 + "Despatch Through:\n" + CatalogueValueDB.getParamValue("TransportationMode", poh.TransportationMode) +
                                  Main.delimiter2 + InvoiceTo +
                                  Main.delimiter2 + "Freight:\n" + CatalogueValueDB.getParamValue("Freight", poh.FreightTerms) +
                                  Main.delimiter2 + "Delivery Period:\n" + poh.DeliveryPeriod + " Days" + Main.delimiter2 +
                                  DespatchTo +
                                  Main.delimiter2 + "Tax And Duties:\n" + CatalogueValueDB.getParamValue("TaxStatus", poh.TaxTerms) +
                                  Main.delimiter2 + "Mode/Terms of Payment:\n" + CatalogueValueDB.getParamValue("PaymentMode", poh.ModeOfPayment) + "\n" + PTDefinitionDB.getPaymentTermString(poh.PaymentTerms);
            string footer1         = "Amount In Words\n\n";
            string ColHeader       = "SI No.;Description of Goods;Quantity;Unit;Unit Rate;Amount;Warranty\nIn Days";
            string footer2         = "";
            string footer3         = "for CELLCOMM SOLUTION LIMITED;Authorised Signatory";
            string termsAndCond    = getTCString(poh.TermsAndCondition);
            double totQuant        = 0.00;
            double totAmnt         = 0.00;
            int    n               = 1;
            string ColDetailString = "";
            var    count           = PODetail.Count();

            foreach (podetail pod in PODetail)
            {
                if (n == count)
                {
                    //ColDetailString = ColDetailString + n + "+" + pod.Description + "+" + pod.Quantity + "+"
                    //                  + pod.Unit + "+" + pod.Price + "+" + (pod.Quantity * pod.Price) + "+" + pod.WarrantyDays;
                    ColDetailString = ColDetailString + n + Main.delimiter1 + pod.Description + Main.delimiter1 + pod.Quantity + Main.delimiter1
                                      + pod.Unit + Main.delimiter1 + pod.Price + Main.delimiter1 + (pod.Quantity * pod.Price) + Main.delimiter1 + pod.WarrantyDays;
                    if (pod.Tax != 0)
                    {
                        //ColDetailString = ColDetailString + ";" +"" + "+" + pod.TaxCode + "+" + "" + "+"
                        //              + "" + "+" + "" + "+" + pod.Tax + "+" + "";
                        ColDetailString = ColDetailString + Main.delimiter2 + "" + Main.delimiter1 + pod.TaxCode + Main.delimiter1 + "" + Main.delimiter1
                                          + "" + Main.delimiter1 + "" + Main.delimiter1 + pod.Tax + Main.delimiter1 + "";
                    }
                    // ColDetailString = ColDetailString
                }
                else
                {
                    //ColDetailString = ColDetailString + n + "+" + pod.Description + "+" + pod.Quantity + "+"
                    //                  + pod.Unit + "+" + pod.Price + "+" + (pod.Quantity * pod.Price) + "+" + pod.WarrantyDays + ";";
                    ColDetailString = ColDetailString + n + Main.delimiter1 + pod.Description + Main.delimiter1 + pod.Quantity + Main.delimiter1
                                      + pod.Unit + Main.delimiter1 + pod.Price + Main.delimiter1 + (pod.Quantity * pod.Price) + Main.delimiter1 + pod.WarrantyDays + Main.delimiter2;
                    if (pod.Tax != 0)
                    {
                        //ColDetailString = ColDetailString + "" + "+" + pod.TaxCode + "+" + "" + "+"
                        //             + "" + "+" + "" + "+" + pod.Tax + "+" + "" + Main.delimiter2;
                        ColDetailString = ColDetailString + "" + Main.delimiter1 + pod.TaxCode + Main.delimiter1 + "" + Main.delimiter1
                                          + "" + Main.delimiter1 + "" + Main.delimiter1 + pod.Tax + Main.delimiter1 + "" + Main.delimiter2;
                    }
                }
                totQuant = totQuant + pod.Quantity;
                totAmnt  = totAmnt + (pod.Quantity * pod.Price);
                n++;
            }
            try
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Title            = "Save As PDF";
                sfd.Filter           = "Pdf files (*.Pdf)|*.pdf";
                sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

                sfd.FileName = poh.DocumentID + "-" + poh.PONo;

                if (sfd.ShowDialog() == DialogResult.Cancel || sfd.FileName == "")
                {
                    return;
                }
                FileStream fs  = new FileStream(sfd.FileName + ".pdf", FileMode.Create, FileAccess.Write);
                Rectangle  rec = new Rectangle(PageSize.A4);
                iTextSharp.text.Document doc = new iTextSharp.text.Document(rec);
                PdfWriter writer             = PdfWriter.GetInstance(doc, fs);
                MyEvent   evnt = new MyEvent();
                writer.PageEvent = evnt;

                doc.Open();
                Font   font1 = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
                Font   font2 = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
                Font   font3 = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.ITALIC, BaseColor.BLACK);
                String URL   = "Cellcomm2.JPG";
                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(URL);
                img.Alignment = Element.ALIGN_LEFT;


                PdfPTable tableMain = new PdfPTable(2);

                tableMain.WidthPercentage = 100;
                PdfPCell  cellImg = new PdfPCell();
                Paragraph pp      = new Paragraph();
                pp.Add(new Chunk(img, 0, 0));
                cellImg.AddElement(pp);
                cellImg.Border = 0;
                tableMain.AddCell(cellImg);

                PdfPCell        cellAdd = new PdfPCell();
                Paragraph       ourAddr = new Paragraph("");
                CompanyDetailDB compDB  = new CompanyDetailDB();
                cmpnydetails    det     = compDB.getdetails().FirstOrDefault(comp => comp.companyID == 1);
                if (det != null)
                {
                    string addr = det.companyname + "\n" + det.companyAddress;
                    ourAddr           = new Paragraph(new Phrase(addr, font2));
                    ourAddr.Alignment = Element.ALIGN_RIGHT;
                }
                cellAdd.AddElement(ourAddr);
                cellAdd.Border = 0;
                tableMain.AddCell(cellAdd);


                Paragraph paragraph = new Paragraph(new Phrase("PURCHASE ORDER", font2));
                paragraph.Alignment = Element.ALIGN_CENTER;

                PrintPurchaseOrder prog      = new PrintPurchaseOrder();
                string[]           HeaderStr = HeaderString.Split(Main.delimiter2);

                PdfPTable table = new PdfPTable(7);

                table.SpacingBefore   = 20f;
                table.WidthPercentage = 100;
                float[] HWidths = new float[] { 0.5f, 8f, 2f, 1.5f, 1.5f, 3f, 1.5f };
                table.SetWidths(HWidths);
                PdfPCell cell;
                int[]    arr = { 6, 7, 9, 10 };
                float    wid = 0;
                for (int i = 0; i < HeaderStr.Length; i++)
                {
                    if (i == 0 || i == 5 || i == 8)
                    {
                        string[] format = HeaderStr[i].Split(Main.delimiter1);
                        Phrase   phr    = new Phrase();
                        phr.Add(new Chunk(format[0], font2));
                        phr.Add(new Chunk(format[1], font1));
                        //cell = new PdfPCell(new Phrase(HeaderStr[i].Trim(), font1));
                        cell                     = new PdfPCell(phr);
                        cell.Rowspan             = 2;
                        cell.Colspan             = 2;
                        cell.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
                        //wid = cell.MinimumHeight / 2;
                        table.AddCell(cell);
                    }
                    else if (arr.Contains(i))
                    {
                        cell               = new PdfPCell(new Phrase(HeaderStr[i].Trim(), font1));
                        cell.Colspan       = 5;
                        cell.MinimumHeight = wid;
                        table.AddCell(cell);
                    }
                    else
                    {
                        cell = new PdfPCell(new Phrase(HeaderStr[i].Trim(), font1));
                        if (i % 2 != 0)
                        {
                            cell.Colspan = 3;
                        }
                        else
                        {
                            cell.Colspan = 2;
                        }
                        table.AddCell(cell);
                    }
                }
                string[] ColHeaderStr = ColHeader.Split(';');

                PdfPTable table1 = new PdfPTable(7);
                table1.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                table1.WidthPercentage = 100;
                float[] width = new float[] { 0.5f, 8f, 2f, 1.5f, 2f, 2.5f, 1.5f };
                table1.SetWidths(width);

                for (int i = 0; i < ColHeaderStr.Length; i++)
                {
                    if (i == 4 || i == 5)
                    {
                        PdfPCell hcell = new PdfPCell(new Phrase(ColHeaderStr[i].Trim() + "\n(" + poh.CurrencyID + ")", font2));
                        hcell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                        table1.AddCell(hcell);
                    }
                    else
                    {
                        PdfPCell hcell = new PdfPCell(new Phrase(ColHeaderStr[i].Trim(), font2));
                        hcell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                        table1.AddCell(hcell);
                    }
                }
                //---
                PdfPCell foot = new PdfPCell(new Phrase(""));
                foot.Colspan        = 7;
                foot.BorderWidthTop = 0;
                foot.MinimumHeight  = 0.5f;
                table1.AddCell(foot);

                table1.HeaderRows = 2;
                table1.FooterRows = 1;

                table1.SkipFirstHeader = false;
                table1.SkipLastFooter  = true;
                //---
                int     track = 0;
                decimal dc1   = 0;
                decimal dc2   = 0;

                string[] DetailStr = ColDetailString.Split(Main.delimiter2);
                float    hg        = 0f;
                for (int i = 0; i < DetailStr.Length; i++)
                {
                    track = 0;
                    hg    = table1.GetRowHeight(i + 1);
                    string[] str = DetailStr[i].Split(Main.delimiter1);
                    for (int j = 0; j < str.Length; j++)
                    {
                        PdfPCell pcell;

                        if (j == 2 || j == 4 || j == 5)
                        {
                            decimal p = 1;
                            if (Decimal.TryParse(str[j], out p))
                            {
                                pcell = new PdfPCell(new Phrase(String.Format("{0:0.00}", Convert.ToDecimal(str[j])), font1));
                            }
                            else
                            {
                                pcell = new PdfPCell(new Phrase(""));
                            }
                            pcell.Border = 0;
                            if (j == 5)
                            {
                                if (str[0].Length == 0)
                                {
                                    pcell.BorderWidthBottom = 0.01f;
                                    track = 1;
                                    dc2   = Convert.ToDecimal(str[j]);
                                }
                                else
                                {
                                    dc1 = Convert.ToDecimal(str[j]);
                                }
                            }
                        }
                        else
                        {
                            if (j == 6)
                            {
                                if ((str[j].Trim().Length == 0 || Convert.ToInt32(str[j]) == 0) && (track != 1))
                                {
                                    pcell = new PdfPCell(new Phrase("NA", font1));
                                }
                                else
                                {
                                    pcell = new PdfPCell(new Phrase(str[j], font1));
                                }
                            }
                            else if (j == 3)
                            {
                                int m = 1;
                                if (Int32.TryParse(str[j], out m) == true)
                                {
                                    if (Convert.ToInt32(str[j]) == 0)
                                    {
                                        pcell = new PdfPCell(new Phrase("", font1));
                                    }
                                    else
                                    {
                                        pcell = new PdfPCell(new Phrase(str[j], font1));
                                    }
                                }
                                else
                                {
                                    pcell = new PdfPCell(new Phrase(str[j], font1));
                                }
                            }
                            else
                            {
                                pcell = new PdfPCell(new Phrase(str[j], font1));
                            }

                            pcell.Border = 0;
                        }

                        //if (i == DetailStr.Length - 1)
                        //{
                        //    pcell.MinimumHeight = 50;
                        //}
                        //else
                        pcell.MinimumHeight = 10;
                        //pcell.MinimumHeight = 20;
                        if (j == 1)
                        {
                            pcell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                        }
                        else
                        {
                            pcell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                        }
                        pcell.BorderWidthLeft  = 0.01f;
                        pcell.BorderWidthRight = 0.01f;

                        table1.AddCell(pcell);
                    }
                    //foreach()
                    if (track == 1)
                    {
                        for (int j = 0; j < 7; j++)
                        {
                            PdfPCell pcell1;

                            if (j == 5)
                            {
                                pcell1                   = new PdfPCell(new Phrase(String.Format("{0:0.00}", Convert.ToDecimal(dc1 + dc2)), font1));
                                pcell1.Border            = 0;
                                pcell1.BorderWidthBottom = 0.01f;
                            }
                            else
                            {
                                pcell1        = new PdfPCell(new Phrase(""));
                                pcell1.Border = 0;
                            }
                            pcell1.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                            pcell1.BorderWidthLeft     = 0.01f;
                            pcell1.BorderWidthRight    = 0.01f;
                            table1.AddCell(pcell1);
                        }
                    }
                }

                double roundedAmt = Math.Round(poh.POValue, 0);
                double diffAmount = roundedAmt - poh.POValue;

                if (diffAmount != 0)
                {
                    table1.AddCell("");
                    table1.AddCell("");
                    PdfPCell cellRound = new PdfPCell(new Phrase("Round off Adj.", font1));
                    cellRound.Colspan             = 3;
                    cellRound.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                    table1.AddCell(cellRound);
                    table1.AddCell(new Phrase(String.Format("{0:0.00}", diffAmount), font1));
                    table1.AddCell("");
                }

                table1.AddCell("");
                table1.AddCell("");
                PdfPCell cellTotal = new PdfPCell(new Phrase("Total", font1));
                cellTotal.Colspan             = 3;
                cellTotal.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                table1.AddCell(cellTotal);
                table1.AddCell(new Phrase(String.Format("{0:0.00}", roundedAmt), font1));
                table1.AddCell("");

                string   total  = footer1 + NumberToString.convert(roundedAmt.ToString()).Replace("INR", poh.CurrencyID) + "\n\n";
                PdfPCell fcell1 = new PdfPCell(new Phrase((total), font1));
                fcell1.Colspan             = 6;
                fcell1.MinimumHeight       = 50;
                fcell1.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                fcell1.BorderWidthBottom   = 0;
                fcell1.BorderWidthRight    = 0;
                fcell1.BorderWidthTop      = 0;
                table1.AddCell(fcell1);

                PdfPCell fcell4 = new PdfPCell(new Phrase("E. & O.E", font1));
                //fcell4.MinimumHeight = 50;
                fcell4.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                fcell4.BorderWidthBottom   = 0;
                //fcell4.BorderWidthRight = 0;
                fcell4.BorderWidthLeft = 0;
                fcell4.BorderWidthTop  = 0;
                table1.AddCell(fcell4);

                if (poh.SpecialNote.Trim().Length != 0)
                {
                    footer2 = "Note:\n" + poh.SpecialNote.Trim();
                }
                PdfPCell fcell2 = new PdfPCell(new Phrase(footer2, font1));
                fcell2.Colspan             = 4;
                fcell2.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                fcell2.BorderWidthTop      = 0;
                fcell2.BorderWidthRight    = 0;
                table1.AddCell(fcell2);
                string[] ft = footer3.Split(';');

                PdfPCell fcell3 = new PdfPCell();
                Chunk    ch1    = new Chunk(ft[0], font1);
                Chunk    ch2    = new Chunk(ft[1], font1);
                Phrase   phrase = new Phrase();
                phrase.Add(ch1);
                for (int i = 0; i < 3; i++)
                {
                    phrase.Add(Chunk.NEWLINE);
                }
                phrase.Add(ch2);

                Paragraph para = new Paragraph();
                para.Add(phrase);
                para.Alignment = Element.ALIGN_RIGHT;
                fcell3.AddElement(para);
                fcell3.Border            = 0;
                fcell3.Colspan           = 4;
                fcell3.BorderWidthTop    = 0f;
                fcell3.BorderWidthLeft   = 0f;
                fcell3.BorderWidthRight  = 0.5f;
                fcell3.BorderWidthBottom = 0.5f;
                fcell3.MinimumHeight     = 50;
                table1.AddCell(fcell3);
                table1.KeepRowsTogether(table1.Rows.Count - 4, table1.Rows.Count);
                PdfPTable taxTab = new PdfPTable(3);
                //taxTab.
                taxTab.WidthPercentage = 100;

                float[] twidth = new float[] { 3f, 3f, 10f };
                taxTab.SetWidths(twidth);
                double dd = 0;
                if (poh.TaxAmount != 0)
                {
                    PdfPCell pcell;
                    pcell = new PdfPCell(new Phrase("Tax Details", font2));
                    taxTab.AddCell(pcell);
                    PdfPCell pcellc = new PdfPCell(new Phrase("Amount(" + poh.CurrencyID + ")", font2));
                    taxTab.AddCell(pcellc);
                    PdfPCell pcelllst = new PdfPCell(new Phrase("", font1));
                    pcelllst.Border = 0;
                    taxTab.AddCell(pcelllst);
                    //for (int i = 0; i < 2; i++)
                    //{

                    //    if (i == 1)
                    //        pcell = new PdfPCell(new Phrase("Tax Details", font2));
                    //    else

                    //    //pcell.Border = 0;
                    //    //pcell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                    //    //pcell.MinimumHeight = 20;
                    //    //pcell.BorderWidthLeft = 0.01f;
                    //    //pcell.BorderWidthRight = 0.01f;
                    //    table1.AddCell(pcell);
                    //}
                    string[] tax = taxStr.Split(Main.delimiter2);
                    for (int i = 0; i < tax.Length - 1; i++)
                    {
                        string[] subtax = tax[i].Split(Main.delimiter1);
                        PdfPCell pcell1;
                        pcell1 = new PdfPCell(new Phrase(subtax[0], font1));
                        PdfPCell pcell2;
                        pcell2 = new PdfPCell(new Phrase(String.Format("{0:0.00}", Convert.ToDecimal(subtax[1])), font1));
                        PdfPCell pcell3 = new PdfPCell(new Phrase("", font1));
                        pcell3.Border = 0;
                        //taxTab.AddCell(pcell3);
                        //pcell1.Border = 0;
                        //pcell1.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                        //pcell1.BorderWidthLeft = 0.01f;
                        //pcell1.BorderWidthRight = 0.01f;
                        //if (i == (tax.Length - 2))
                        //{
                        //    pcell1.MinimumHeight = 100;
                        //}
                        //else
                        //pcell1.MinimumHeight = 20;
                        taxTab.AddCell(pcell1);
                        //pcell2.MinimumHeight = 20;
                        taxTab.AddCell(pcell2);
                        taxTab.AddCell(pcell3);
                    }
                    taxTab.AddCell(new Phrase("Total Tax Amount", font2));
                    taxTab.AddCell(new Phrase(String.Format("{0:0.00}", Convert.ToDecimal(poh.TaxAmount)), font2));
                    PdfPCell pcellt = new PdfPCell(new Phrase("", font1));
                    pcellt.Border = 0;
                    taxTab.AddCell(pcellt);
                    taxTab.KeepTogether  = true;
                    taxTab.SpacingAfter  = 2f;
                    taxTab.SpacingBefore = 3f;
                }
                PdfPTable TCTab = new PdfPTable(2);
                if (poh.TermsAndCondition.Trim().Length != 0)
                {
                    Chunk TCchunk = new Chunk("Terms And Conditoins:\n", font2);
                    TCchunk.SetUnderline(0.2f, -2f);
                    TCTab = new PdfPTable(2);
                    TCTab.WidthPercentage = 100;
                    PdfPCell TCCell = new PdfPCell();
                    TCCell.Colspan = 2;
                    TCCell.Border  = 0;
                    TCCell.AddElement(TCchunk);
                    TCTab.AddCell(TCCell);
                    try
                    {
                        string[] ParaTC = termsAndCond.Split(Main.delimiter2);
                        for (int i = 0; i < ParaTC.Length - 1; i++)
                        {
                            TCCell         = new PdfPCell();
                            TCCell.Colspan = 2;
                            TCCell.Border  = 0;
                            Paragraph header  = new Paragraph();
                            Paragraph details = new Paragraph();
                            details.IndentationLeft  = 12f;
                            details.IndentationRight = 12f;
                            string paraHeaderStr = (i + 1) + ". " + ParaTC[i].Substring(0, ParaTC[i].IndexOf(Main.delimiter1)) + ":";
                            string paraFooterStr = ParaTC[i].Substring(ParaTC[i].IndexOf(Main.delimiter1) + 1);
                            header.Add(new Phrase(paraHeaderStr, font2));
                            details.Add(new Phrase(paraFooterStr, font1));
                            TCCell.AddElement(header);
                            TCCell.AddElement(details);
                            TCTab.AddCell(TCCell);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this.ToString() + "-" + System.Reflection.MethodBase.GetCurrentMethod().Name + "() : Error-" + ex.ToString());
                    }
                    try
                    {
                        if (TCTab.Rows.Count >= 3)
                        {
                            TCTab.KeepRowsTogether(0, 3);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this.ToString() + "-" + System.Reflection.MethodBase.GetCurrentMethod().Name + "() : Error-" + ex.ToString());
                    }
                }
                doc.Add(tableMain);
                //doc.Add(jpg);
                //doc.Add(img);
                doc.Add(paragraph);
                doc.Add(table);
                doc.Add(table1);
                if (poh.TaxAmount != 0)
                {
                    doc.Add(taxTab);
                }
                if (poh.TermsAndCondition.Trim().Length != 0)
                {
                    doc.Add(TCTab);
                }
                doc.Close();
                MessageBox.Show("Document Saved");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to Save Document");
            }
        }