A Phrase is a series of Chunks.
A Phrase has a main Font, but some chunks within the phrase can have a Font that differs from the main Font. All the Chunks in a Phrase have the same leading.
Inheritance: System.Collections.ArrayList, ITextElementArray
 /**
  * Initialize one of the headers, based on the chapter title;
  * reset the page number.
  * @see com.itextpdf.text.pdf.PdfPageEventHelper#onChapter(
  *      com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document, float,
  *      com.itextpdf.text.Paragraph)
  */
 public override void OnChapter(
   PdfWriter writer, Document document,
   float paragraphPosition, Paragraph title)
 {
     header[1] = new Phrase(title.Content);
     pagenumber = 1;
 }
        public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)
        {
            iTextSharp.text.Phrase p1Footer  = new iTextSharp.text.Phrase("Thank you for your business.\nPlease remit payment to address above", iTextSharp.text.FontFactory.GetFont("verdana", 8));
            iTextSharp.text.Phrase p1Footer1 = new iTextSharp.text.Phrase("Page " + document.PageNumber.ToString(), iTextSharp.text.FontFactory.GetFont("verdana", 8));
            //iTextSharp.text.Image imgPDF = iTextSharp.text.Image.GetInstance(HttpRuntime.AppDomainAppPath + "\\Images\\logo.gif");
            PdfPTable pdfTabFooter = new PdfPTable(1);
            PdfPCell  pdfCell1     = new PdfPCell(p1Footer);
            PdfPCell  pdfCell2     = new PdfPCell(p1Footer1);

            pdfCell1.Phrase.Font.Color   = iTextSharp.text.BaseColor.GRAY;
            pdfCell1.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER;
            pdfCell2.HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT;
            pdfCell1.Border = 0;
            pdfCell2.Border = 0;


            pdfTabFooter.TotalWidth = document.PageSize.Width - 40;
            //pdfCell1.Width = pdfTabFooter.TotalWidth - 40;
            //pdfCell2.Width = 40;

            float[] cfWidths = new float[] { 2f };
            // pdfTabFooter.SetWidths(cfWidths);
            pdfTabFooter.AddCell(pdfCell1);
            pdfTabFooter.AddCell(pdfCell2);

            //pdfTabFooter.TotalWidth = document.PageSize.Width - 20;
            pdfTabFooter.WriteSelectedRows(0, -1, 10, pdfTabFooter.TotalHeight, writer.DirectContent);
            //pdfTabFooter.WriteSelectedRows(0, -1, 10, document.PageSize.Height - 15, writer.DirectContent);
            document.SetMargins(document.LeftMargin, document.RightMargin, document.TopMargin + 30, document.BottomMargin + 30);
            pdfContent = writer.DirectContent;
            pdfContent.MoveTo(30, document.PageSize.Height - 50);
            //pdfContent.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 40);
            pdfContent.Stroke();
        }
Example #3
0
        /// <summary>
        /// <para>座標を指定してテキストを追加します。</para>
        /// <para>PDF では用紙左上が座標基準 (0, 0) である点に注意してください。</para>
        /// </summary>
        /// <param name="text">追加するテキスト</param>
        /// <param name="fontSize">フォントサイズ</param>
        /// <param name="x">X 座標</param>
        /// <param name="y">Y座標</param>
        public void AddText(string text, int fontSize, int x, int y)
        {
            // 左下の座標
            float llx = x;
            float lly = 0f;

            // 右上の座標
            float urx = this.Page.Width;
            float ury = y;

            var pcb = this.Writer.DirectContent;
            var ct = new ColumnText(pcb);
            var font = new Font(this.BaseFont, fontSize, Font.NORMAL);

            var phrase = new Phrase(text, font);

            ct.SetSimpleColumn(
                phrase,
                llx,
                lly,
                urx,
                ury,
                0,
                Element.ALIGN_LEFT | Element.ALIGN_TOP
                );

            // 以下を実行して反映する (消さないこと)
            ct.Go();
        }
        //重写 关闭一个页面时
        public override void OnEndPage(PdfWriter writer, Document document)
        {
            try
            {
                Font font = new Font(basefont, defaultFontSize);
                Phrase head = new Phrase(header, font);
                PdfContentByte cb = writer.DirectContent;
               
                //页眉显示的位置
                ColumnText.ShowTextAligned(cb, Element.ALIGN_RIGHT, head,
                        document.Right - 10 + document.LeftMargin, document.Top + 10, 0);
                if (PAGE_NUMBER)
                {
                    Phrase footer = new Phrase("第 " + writer.PageNumber + " / " + "   "+" 頁", font);
                    cb = writer.DirectContent;
                    //tpl = cb.CreateTemplate(100, 100);
                    //模版 显示总共页数
                    cb.AddTemplate(tpl, document.Left / 2 + document.Right / 2 , document.Bottom - 10);//调节模版显示的位置
                    //页脚显示的位置
                    ColumnText.ShowTextAligned(cb, Element.ALIGN_RIGHT, footer,
                            document.Left / 2+document.Right/ 2+23, document.Bottom - 10, 0);
                    

                }
            }
            catch (Exception ex)
            {
                throw new Exception("HeaderAndFooterEvent-->OnEndPage-->" + ex.Message);
            }
        }
        private static PDF.PdfPCell GetFormattedCell(TableCell cell)
        {
            PDF.PdfPCell formattedCell = new PDF.PdfPCell();

            Element[] cellElements = cell.SubElements;

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

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

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

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

            }

            return formattedCell;
        }
Example #6
0
        public static iTextSharp.text.pdf.PdfPCell AddText2Cell(string text, iTextSharp.text.Font font, string align)
        {
            const string METHOD_NAME = "AddText2Cell";

            try {
                iTextSharp.text.Phrase       phrase = new iTextSharp.text.Phrase(text, font);
                iTextSharp.text.pdf.PdfPCell cell   = new iTextSharp.text.pdf.PdfPCell(phrase);
                cell.BorderWidth = 0;

                switch (align.ToLower())
                {
                case "left":
                    cell.HorizontalAlignment = Element.ALIGN_LEFT;
                    break;

                case "center":
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    break;

                case "right":
                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    break;
                }

                return(cell);
            }
            catch (Exception ex) {
                ApplicationException aex = new ApplicationException(MOD_NAME + METHOD_NAME, ex);
                throw (aex);
            }
        }
 // ---------------------------------------------------------------------------          
 public void Write(Stream stream)
 {
     // step 1
     using (Document document = new Document())
     {
         // step 2
         PdfWriter writer = PdfWriter.GetInstance(document, stream);
         // step 3
         document.Open();
         // step 4
         Phrase phrase;
         Chunk chunk;
         foreach (Movie movie in PojoFactory.GetMovies())
         {
             phrase = new Phrase(movie.MovieTitle);
             chunk = new Chunk("\u00a0");
             chunk.SetAnnotation(PdfAnnotation.CreateText(
               writer, null, movie.MovieTitle,
               string.Format(INFO, movie.Year, movie.Duration),
               false, "Comment"
             ));
             phrase.Add(chunk);
             document.Add(phrase);
             document.Add(PojoToElementFactory.GetDirectorList(movie));
             document.Add(PojoToElementFactory.GetCountryList(movie));
         }
     }
 }
Example #8
0
        public void Add(Athlete athete)
        {
            var data =
            new IT.Phrase(athete.Id.ToString() ,
                          IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_ROW, IT.Font.NORMAL));

              var cell = new IT.pdf.PdfPCell(data);
              cell.HorizontalAlignment = IT.Element.ALIGN_LEFT;
              cell.PaddingBottom = PAD_BOTTOM;
              table.AddCell(cell);

             data = new IT.Phrase(athete.Surname + " "  + athete.Name,
                              IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_ROW, IT.Font.NORMAL));
             cell = new IT.pdf.PdfPCell(data);
             cell.HorizontalAlignment = IT.Element.ALIGN_LEFT;
             cell.PaddingBottom = PAD_BOTTOM;
             table.AddCell(cell);

             data = new IT.Phrase(" ",
                              IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_TITLE, IT.Font.NORMAL));
             cell = new IT.pdf.PdfPCell(data);
             cell.HorizontalAlignment = IT.Element.ALIGN_LEFT;
             cell.PaddingBottom = PAD_BOTTOM;
             table.AddCell(cell);
        }
Example #9
0
    private void Creo_Cabecera(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)
    {
        PdfPTable t = new PdfPTable(2);

        Single[] arrAnchosC = { 20F, 80F };
        t.SetWidthPercentage(arrAnchosC, iTextSharpText.PageSize.A4);
        t.WidthPercentage = 100;

        iTextSharp.text.Image png = iTextSharp.text.Image.GetInstance(AppDomain.CurrentDomain.BaseDirectory + "App_Themes\\imagenes\\logo_impresion.png");
        PdfPCell c = new PdfPCell(png);

        c.HorizontalAlignment = iTextSharpText.Element.ALIGN_LEFT;
        c.BorderWidth         = 0;

        iTextSharpText.Phrase texto = new iTextSharpText.Phrase();
        texto.Font = iTextSharpText.FontFactory.GetFont("Arial", 14, iTextSharpText.Element.ALIGN_CENTER);
        texto.Add(new iTextSharpText.Phrase("Reporte de Solicitudes de Prestamos a Liquidar\n\n"));

        texto.Font = iTextSharpText.FontFactory.GetFont("Arial", 8, iTextSharpText.Element.ALIGN_CENTER);
        texto.Add(new iTextSharpText.Phrase("Fecha Reporte: " + lst[0].Fecha_Informe.ToString("dd/MM/yyyy") + "   N° Reporte: " + lst[0].nroInforme));

        PdfPCell c1 = new PdfPCell(texto);

        c1.HorizontalAlignment = iTextSharpText.Element.ALIGN_CENTER;
        c1.BorderWidth         = 0;

        t.AddCell(c);
        t.AddCell(c1);

        iTextSharpText.Paragraph Cabecera = new iTextSharpText.Paragraph();
        Cabecera.Add(t);

        document.Add(Cabecera);
        document.Add(iTextSharpText.Chunk.NEWLINE);
    }
Example #10
0
        public static void AddValues2Paragraph(iTextSharp.text.Paragraph para, ArrayList values, Font font)
        {
            const string METHOD_NAME = "AddValues2Paragraph";

            try {
                iTextSharp.text.Phrase phrase = null;
                foreach (string s in values)
                {
                    if (s.Length > 0)
                    {
                        if (phrase != null)
                        {
                            phrase = new Phrase(@" \ " + s, font);
                        }
                        else
                        {
                            phrase = new Phrase(s, font);
                        }
                        para.Add(phrase);
                    }
                }
            }
            catch (Exception ex) {
                ApplicationException aex = new ApplicationException(MOD_NAME + METHOD_NAME, ex);
                throw(aex);
            }
        }
        public void Go()
        {
            // GetClassOutputPath() implementation left out for brevity
            var outputFile = Helpers.IO.GetClassOutputPath(this);

            using (FileStream stream = new FileStream(
                outputFile, 
                FileMode.Create, 
                FileAccess.Write))
            {
                Random random = new Random();

                StreamUtil.AddToResourceSearch(("iTextAsian.dll"));
                string chunkText = " 你好世界 你好你好,";
                var font = new Font(BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED), 12);

                using (Document document = new Document())
                {
                    PdfWriter.GetInstance(document, stream);
                    document.Open();
                    Phrase phrase = new Phrase();
                    Chunk chunk = new Chunk("", font);
                    for (var i = 0; i < 1000; ++i)
                    {
                        var asterisk = new String('*', random.Next(1, 20));
                        chunk.Append(
                            string.Format("[{0}] {1} ", asterisk, chunkText) 
                        );
                    }
                    chunk.SetSplitCharacter(new CustomSplitCharacter());
                    phrase.Add(chunk);
                    document.Add(phrase);
                }
            }
        }
Example #12
0
// ---------------------------------------------------------------------------    
    /**
     * Creates a PDF document.
     * @param stream Stream for the new PDF document
     */
    public void CreatePdf(Stream stream) {
      string RESOURCE = Utility.ResourcePosters;
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        Phrase phrase;
        Chunk chunk;
        PdfAnnotation annotation;
        foreach (Movie movie in PojoFactory.GetMovies()) {
          phrase = new Phrase(movie.MovieTitle);
          chunk = new Chunk("\u00a0\u00a0");
          annotation = PdfAnnotation.CreateFileAttachment(
            writer, null,
            movie.MovieTitle, null,
            Path.Combine(RESOURCE, movie.Imdb + ".jpg"),
            string.Format("img_{0}.jpg", movie.Imdb)
          );
          annotation.Put(PdfName.NAME, new PdfString("Paperclip"));
          chunk.SetAnnotation(annotation);
          phrase.Add(chunk);
          document.Add(phrase);
          document.Add(PojoToElementFactory.GetDirectorList(movie));
          document.Add(PojoToElementFactory.GetCountryList(movie));
        }
      }
    }
 // ---------------------------------------------------------------------------    
 /**
  * Creates a Phrase containing information about a movie.
  * @param    movie    the movie for which you want to create a Paragraph
  */
 public Phrase CreateMovieInformation(Movie movie)
 {
     Phrase p = new Phrase();
     p.Font = FilmFonts.NORMAL;
     p.Add(new Phrase("Title: ", FilmFonts.BOLDITALIC));
     p.Add(PojoToElementFactory.GetMovieTitlePhrase(movie));
     p.Add(" ");
     if (!string.IsNullOrEmpty(movie.OriginalTitle))
     {
         p.Add(new Phrase("Original title: ", FilmFonts.BOLDITALIC));
         p.Add(PojoToElementFactory.GetOriginalTitlePhrase(movie));
         p.Add(" ");
     }
     p.Add(new Phrase("Country: ", FilmFonts.BOLDITALIC));
     foreach (Country country in movie.Countries)
     {
         p.Add(PojoToElementFactory.GetCountryPhrase(country));
         p.Add(" ");
     }
     p.Add(new Phrase("Director: ", FilmFonts.BOLDITALIC));
     foreach (Director director in movie.Directors)
     {
         p.Add(PojoToElementFactory.GetDirectorPhrase(director));
         p.Add(" ");
     }
     p.Add(new Chunk("Year: ", FilmFonts.BOLDITALIC));
     p.Add(new Chunk(movie.Year.ToString(), FilmFonts.NORMAL));
     p.Add(new Chunk(" Duration: ", FilmFonts.BOLDITALIC));
     p.Add(new Chunk(movie.Duration.ToString(), FilmFonts.NORMAL));
     p.Add(new Chunk(" minutes", FilmFonts.NORMAL));
     p.Add(new LineSeparator(0.3f, 100, null, Element.ALIGN_CENTER, -2));
     return p;
 }
Example #14
0
// ---------------------------------------------------------------------------    
    /**
     * Creates a Phrase containing the name of a Director.
     * @param director a Director object
     * @return a Phrase object
     */
    public static Phrase GetDirectorPhrase(Director director) {
      Phrase phrase = new Phrase();
      phrase.Add(new Chunk(director.Name, FilmFonts.BOLD));
      phrase.Add(new Chunk(", ", FilmFonts.BOLD));
      phrase.Add(new Chunk(director.GivenName, FilmFonts.NORMAL));
      return phrase;
    }
        public void TextLeadingTest() {
            String file = "phrases.pdf";

            Document document = new Document();
            PdfWriter writer = PdfWriter.GetInstance(document, File.Create(OUTPUT_FOLDER + file));
            document.Open();

            Phrase p1 = new Phrase("first, leading of 150");
            p1.Leading = 150;
            document.Add(p1);
            document.Add(Chunk.NEWLINE);

            Phrase p2 = new Phrase("second, leading of 500");
            p2.Leading = 500;
            document.Add(p2);
            document.Add(Chunk.NEWLINE);

            Phrase p3 = new Phrase();
            p3.Add(new Chunk("third, leading of 20"));
            p3.Leading = 20;
            document.Add(p3);

            document.Close();

            // compare
            CompareTool compareTool = new CompareTool();
            String errorMessage = compareTool.CompareByContent(OUTPUT_FOLDER + file, TEST_RESOURCES_PATH + file, OUTPUT_FOLDER, "diff");
            if (errorMessage != null) {
                Assert.Fail(errorMessage);
            }
        }
        private static PdfPTable GenerateReportTable(DayReport report)
        {
            PdfPTable table = new PdfPTable(5);
            
            string[] headerTitles = {"Product", "Quantity", "Unit Price", "Location", "Sum"};
            foreach (var title in headerTitles)
            {
                Phrase phrase = new Phrase(title);
                phrase.Font = FontFactory.GetFont("Arial", 14, Font.BOLD);
                PdfPCell cell = new PdfPCell(phrase);
                cell.BackgroundColor = new BaseColor(175, 166, 166);
                table.AddCell(cell);
                cell.Padding = 0;
            }

            foreach (var sale in report.Sales)
            {
                table.AddCell(sale.ProductName);
                table.AddCell(sale.MeasureFormatted);
                table.AddCell(sale.UnitPrice.ToString());
                table.AddCell(sale.Supermarket);
                table.AddCell(sale.Sum.ToString());
            }

            PdfPCell footerCell = new PdfPCell(new Phrase("Total sum for " + report.FormattedDate + ": "));
            footerCell.Colspan = 4;
            footerCell.HorizontalAlignment = 2;
            table.AddCell(footerCell);
            table.AddCell(new Phrase(report.TotalSum.ToString()));
            return table;
        }
Example #17
0
 /**
 * Copy constructor for <CODE>Phrase</CODE>.
 */
 public Phrase(Phrase phrase)
     : base()
 {
     this.AddAll(phrase);
     leading = phrase.Leading;
     font = phrase.Font;
     hyphenation = phrase.hyphenation;
 }
 private static IElement SpecialInstructions(string commentsOrSpecialInstructions)
 {
     var c = new Phrase("\nCOMMENTS OR SPECIAL INSTRUCTIONS:\n", ElementFactory.StandardFontBold);
     var c1 = ElementFactory.GetPhrase(commentsOrSpecialInstructions, ElementFactory.Fonts.Standard);
     var c2 = new Phrase("\n\n\n", ElementFactory.StandardFont);
     var p = new Paragraph { c, c1, c2 };
     return p;
 }
Example #19
0
        private void SetTable(string titleString, int year)
        {
            var ed =
               new IT.Phrase("Trofeo Luca De Gerone" + year.ToString() ,
                         IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_TITLE + 2, IT.Font.BOLD)
                         );

             var title =
               new IT.Phrase(titleString,
                         IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_TITLE, IT.Font.BOLD)
                         );
             //pett, nome ,  tempo
             float[] widths = {1f,6f,4f};
             table = new IT.pdf.PdfPTable(widths);
             table.HeaderRows = 2;
             table.DefaultCell.Border = IT.Rectangle.NO_BORDER;

             // edizione
             var cell = new IT.pdf.PdfPCell(ed);
             cell.HorizontalAlignment = IT.Element.ALIGN_CENTER;
             cell.Colspan = COLUMNS;
             cell.PaddingBottom = PAD_BOTTOM;
             table.AddCell(cell);

             // intesatazione
             cell = new IT.pdf.PdfPCell(title);
             cell.HorizontalAlignment = IT.Element.ALIGN_CENTER;
             cell.Colspan = COLUMNS;
             cell.PaddingBottom = PAD_BOTTOM;
             cell.GrayFill = 0.90F;
             table.AddCell(cell);

             // riga vuota
             //table.AddCell(GetEmptyRow());

             var data =
               new IT.Phrase("Pett.",
                         IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_ROW, IT.Font.BOLD));

             cell = new IT.pdf.PdfPCell(data);
             cell.HorizontalAlignment = IT.Element.ALIGN_LEFT;
             cell.PaddingBottom = PAD_BOTTOM;
             table.AddCell(cell);

             data = new IT.Phrase("Nome",
                         IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_ROW, IT.Font.BOLD));
             cell = new IT.pdf.PdfPCell(data);
             cell.HorizontalAlignment = IT.Element.ALIGN_LEFT;
             cell.PaddingBottom = PAD_BOTTOM;
             table.AddCell(cell);

             data = new IT.Phrase("Tempo",
                IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_ROW, IT.Font.BOLD));
             cell = new IT.pdf.PdfPCell(data);
             cell.HorizontalAlignment = IT.Element.ALIGN_RIGHT;
             cell.PaddingBottom = PAD_BOTTOM;
             table.AddCell(cell);
        }
 private void fillRow(PdfPTable table) {
     for (int j = 0; j < 3; j++) {
         Phrase phrase = new Phrase("value");
         PdfPCell cell = new PdfPCell(phrase);
         cell.HorizontalAlignment = Element.ALIGN_CENTER;
         cell.VerticalAlignment = Element.ALIGN_CENTER;
         table.AddCell(cell);
     }
 }
 private static IElement ClientAddress(string clientAddress)
 {
     var p = new Phrase("\n\nTO:\n", ElementFactory.StandardFontBold);
     var p2 = new Phrase(clientAddress, ElementFactory.StandardFont);
     var x = new Paragraph() { Leading = 0, MultipliedLeading = 0.8f };
     x.Add(p);
     x.Add(p2);
     return x;
 }
Example #22
0
 private iText.Phrase MakePhrase(string lead, string text)
 {
     iText.Chunk leadChunk = new iText.Chunk(lead);
     leadChunk.Font = iText.FontFactory.GetFont(baseFont, normalSize, iText.Font.BOLD);
     iText.Chunk  textChunck = new iText.Chunk(text);
     iText.Phrase phrase     = new iText.Phrase();
     phrase.Add(leadChunk);
     phrase.Add(textChunck);
     return(phrase);
 }
Example #23
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                // собираем информацию обо всех блюдах
                string mail = "Перечень блюд\n";
                bludoBindingSource.MoveFirst();
                kafeDataSet.BludoRow r = (kafeDataSet.BludoRow)((DataRowView)bludoBindingSource.Current).Row;
                int i = 0;

                // формируем PDF файл с описанием блюд
                var doc = new Document();
                string docPath = Application.StartupPath + @"\Предложение.pdf";
                PdfWriter.GetInstance(doc, new FileStream(docPath, FileMode.Create));
                doc.Open();
                // заголовок
                string fg = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIAL.TTF");

                BaseFont baseFont = BaseFont.CreateFont(fg, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                iTextSharp.text.Phrase j = new Phrase("Перечень блюд", new iTextSharp.text.Font(baseFont, 14,
                              iTextSharp.text.Font.BOLD, new BaseColor(Color.Black)));
                Paragraph a1 = new Paragraph(j);
                a1.Add(Environment.NewLine);
                a1.Add(Environment.NewLine);
                a1.Add(Environment.NewLine);
                a1.Alignment = Element.ALIGN_CENTER;
                a1.SpacingAfter = 5;
                doc.Add(a1);
                while (i < bludoBindingSource.List.Count)
                {
                    r = (kafeDataSet.BludoRow)((DataRowView)bludoBindingSource.Current).Row;
                    mail += "Блюдо '" + r.Nazvanie + "': " + r.Opisanie + "\n\n";
                    j = new Phrase("Блюдо '" + r.Nazvanie + "'\n" + r.Opisanie + "\n\n", new iTextSharp.text.Font(baseFont, 12,
                  iTextSharp.text.Font.BOLD, new BaseColor(Color.Black)));
                    a1 = new Paragraph(j);
                    a1.Add(Environment.NewLine);
                    a1.Add(Environment.NewLine);
                    a1.Alignment = Element.ALIGN_LEFT;
                    a1.SpacingAfter = 5;
                    doc.Add(a1);

                    bludoBindingSource.MoveNext();
                    i++;
                }
                doc.Close();

                button2.Enabled = true;
                button4.Enabled = true;
                System.Windows.Forms.MessageBox.Show("Предложение было сформировано", "Информация", MessageBoxButtons.OK);
            }
            catch (Exception e1)
            {
                System.Windows.Forms.MessageBox.Show(e1.Message);
            }
        }
Example #24
0
        private IT.pdf.PdfPTable GetTable(int year)
        {
            var ed =
               new IT.Phrase("Trofeo Luca De Gerone " + year.ToString() ,
                         IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_TITLE + 2, IT.Font.BOLD)
                         );

             //pett, nome ,  firma
             float[] widths = {1f,6f,6f, 4f};
             IT.pdf.PdfPTable table = new IT.pdf.PdfPTable(widths);
             table.HeaderRows = 2;
             table.DefaultCell.Border = IT.Rectangle.NO_BORDER;

             // edizione
             var cell = new IT.pdf.PdfPCell(ed);
             cell.HorizontalAlignment = IT.Element.ALIGN_CENTER;
             cell.Colspan = COLUMNS;
             cell.PaddingBottom = PAD_BOTTOM;
             table.AddCell(cell);

             // riga vuota
             //table.AddCell(GetEmptyRow());

             var data =
               new IT.Phrase("Pett.",
                         IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_ROW, IT.Font.BOLD));

             cell = new IT.pdf.PdfPCell(data);
             cell.HorizontalAlignment = IT.Element.ALIGN_LEFT;
             cell.PaddingBottom = PAD_BOTTOM;
             table.AddCell(cell);

             data = new IT.Phrase("Cognome",
                         IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_ROW, IT.Font.BOLD));
             cell = new IT.pdf.PdfPCell(data);
             cell.HorizontalAlignment = IT.Element.ALIGN_LEFT;
             cell.PaddingBottom = PAD_BOTTOM;
             table.AddCell(cell);

             data = new IT.Phrase("Nome",
                         IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_ROW, IT.Font.BOLD));
             cell = new IT.pdf.PdfPCell(data);
             cell.HorizontalAlignment = IT.Element.ALIGN_LEFT;
             cell.PaddingBottom = PAD_BOTTOM;
             table.AddCell(cell);

             data = new IT.Phrase("Firma di un genitore",
                IT.FontFactory.GetFont(IT.FontFactory.HELVETICA, SIZE_ROW, IT.Font.BOLD));
             cell = new IT.pdf.PdfPCell(data);
             cell.HorizontalAlignment = IT.Element.ALIGN_RIGHT;
             cell.PaddingBottom = PAD_BOTTOM;
             table.AddCell(cell);
             return table;
        }
 public static Paragraph ParaCommonInfoAllBold(string field, string value)
 {
     Paragraph pr = new Paragraph();
     Phrase phr = new Phrase();
     Chunk chk1 = new Chunk(field, FontConfig.BoldFont);
     Chunk chk2 = new Chunk(value, FontConfig.BoldFont);
     phr.Add(chk1);
     phr.Add(chk2);
     pr.Add(phr);
     return pr;
 }
 public static void CreatePdf(string fileName)
 {
     Document document = new Document();
     FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate);
     PdfWriter writer = PdfWriter.GetInstance(document, stream);
     document.Open();
     writer.CompressionLevel = 0;
     Phrase hello = new Phrase("Hello World");
     PdfContentByte canvas = writer.DirectContentUnder;
     ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT, hello, 36, 788, 0);
     document.Close();
 }
Example #27
0
 internal void AddItemLine(string item, string subItems)
 {
     iText.Chunk itemChunck = new iText.Chunk(item);
     itemChunck.Font = iText.FontFactory.GetFont(baseFont, leadSize, iText.Font.BOLD, iText.BaseColor.BLACK);
     iText.Chunk subItemsChunck = new iText.Chunk(subItems);
     subItemsChunck.Font = iText.FontFactory.GetFont(baseFont, normalSize, iText.Font.NORMAL, iText.BaseColor.BLACK);
     iText.Phrase phrase = new iText.Phrase();
     phrase.Add(itemChunck);
     phrase.Add(subItemsChunck);
     iText.Paragraph paragraph = new iText.Paragraph(phrase);
     document.Add(paragraph);
 }
Example #28
0
// ---------------------------------------------------------------------------
    /**
     * Creates a Phrase with the name and given name of a director using different fonts.
     * @param r the DbDataReader containing director records.
     */
    protected virtual Phrase CreateDirectorPhrase(DbDataReader r) {
      Phrase director = new Phrase();
      director.Add(
        new Chunk(r["name"].ToString(), BOLD_UNDERLINED)
      );
      director.Add(new Chunk(",", BOLD_UNDERLINED));
      director.Add(new Chunk(" ", NORMAL));
      director.Add(
        new Chunk(r["given_name"].ToString(), NORMAL)
      );
      return director;
    }
Example #29
0
        public void AddRow(PdfPTable t, string fname, string lname, string phone, int pid)
        {
            var bc = new Barcode39();
            bc.X = 1.2f;
            bc.Font = null;
            bc.Code = pid.ToString();
            var img = bc.CreateImageWithBarcode(dc, null, null);
            var p1 = new Phrase();
            p1.Add(new Chunk(img, 0, 0));
            p1.Add(new Phrase("\n\n" + fname + " " + lname + " (" + pid + ")", smallfont));
            var c = new PdfPCell(p1);
            c.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
            c.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
            c.Border = PdfPCell.NO_BORDER;
            c.FixedHeight = H * 72f;

            var t2 = new PdfPTable(2);
            t2.WidthPercentage = 100f;
            t2.DefaultCell.Border = PdfPCell.NO_BORDER;

            var cc = new PdfPCell(new Phrase(fname, font));
            cc.Border = PdfPCell.NO_BORDER;
            cc.Colspan = 2;
            t2.AddCell(cc);

            cc = new PdfPCell(new Phrase(lname, font));
            cc.Border = PdfPCell.NO_BORDER;
            cc.Colspan = 2;
            t2.AddCell(cc);

            var pcell = new PdfPCell(new Phrase(pid.ToString(), smallfont));
            pcell.Border = PdfPCell.NO_BORDER;
            pcell.HorizontalAlignment = Element.ALIGN_LEFT;
            t2.AddCell(pcell);

            pcell = new PdfPCell(new Phrase(phone.FmtFone(), smallfont));
            pcell.Border = PdfPCell.NO_BORDER;
            pcell.HorizontalAlignment = Element.ALIGN_RIGHT;
            t2.AddCell(pcell);

            var cell = new PdfPCell(t2);
            cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
            cell.PaddingLeft = 8f;
            cell.PaddingRight = 8f;
            cell.Border = PdfPCell.NO_BORDER;
            cell.FixedHeight = H * 72f;

            t.AddCell(c);
            t.AddCell("");
            t.AddCell(cell);
            t.AddCell("");
            t.AddCell(cell);
        }
Example #30
0
// ---------------------------------------------------------------------------
    /**
     * Creates a Phrase with the name and given name of a director using different fonts.
     * @param    rs    the ResultSet containing director records.
     */
    protected override Phrase CreateDirectorPhrase(DbDataReader r) {
      Phrase director = new Phrase();
      Chunk name = new Chunk(r["name"].ToString(), BOLD);
      name.SetUnderline(0.2f, -2f);
      director.Add(name);
      director.Add(new Chunk(",", BOLD));
      director.Add(new Chunk(" ", NORMAL));
      director.Add(
        new Chunk(r["given_name"].ToString(), NORMAL)
      );
      director.Leading = 24;
      return director;
    }
        public PdfPCell GetCustomizedCell(string content, int alignment, int colspan = TABLE_COLUMNS, int padding = 10, 
            int red = 255, int green = 255, int blue = 255)
        {
            var cellContent = new Phrase(content);
            var cell = new PdfPCell(cellContent);

            cell.Colspan = colspan;
            cell.HorizontalAlignment = alignment;
            cell.Padding = padding;
            cell.BackgroundColor = new BaseColor(red, green, blue);

            return cell;
        }
Example #32
0
        private static PdfPCell CreateDetailTitleCell(String text)
        {
            PdfPCell cell = new PdfPCell(new Phrase(text));
            Phrase phrase = new Phrase();
            phrase.Font = FontFactory.GetFont(FontFactory.HELVETICA, 9f, Font.UNDERLINE);
            phrase.Add(new Phrase(text));
            cell.Phrase = phrase;
            cell.BorderWidth = 0;
            cell.HorizontalAlignment = Element.ALIGN_LEFT;
            cell.Colspan = 3;

            return cell;
        }
        public override void OnEndPage(PdfWriter writer, Document document)
        {
            base.OnEndPage(writer, document);

            var baseFontNormal = new Font(Font.HELVETICA, 12f, Font.NORMAL, Color.BLACK);

            var p1Header = new Phrase("Physician Directory - " + _printTime.ToShortDateString(),
                                      baseFontNormal);

            //Create PdfTable object
            var pdfTab = new PdfPTable(1);

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

            //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));
            }

            pdfCell2.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell2.VerticalAlignment = Element.ALIGN_BOTTOM;

            pdfCell2.Border = 0;

            pdfTab.AddCell(pdfCell2);

            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 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();
        }
        public override void OnEndPage(PdfWriter writer, Document document)
        {
            if (PageNumber == -1) return;

            header = new Phrase("分析报告--这是页眉", font);
            footer = new Phrase("第" + (writer.PageNumber - 1) + "页--这是页脚", font);
            var cb = writer.DirectContent;

            ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, header,
                                       document.Right - 140 + document.LeftMargin, document.Top + 10, 0);

            ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, footer,
                                       document.Right - 60 + document.LeftMargin, document.Bottom - 10, 0);
        }
Example #35
0
        public static iTextSharp.text.pdf.PdfPCell AddText2Cell(iTextSharp.text.Phrase phrase)
        {
            const string METHOD_NAME = "AddText2Cell";

            try {
                iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(phrase);
                cell.BorderWidth = 0;

                return(cell);
            }
            catch (Exception ex) {
                ApplicationException aex = new ApplicationException(MOD_NAME + METHOD_NAME, ex);
                throw (aex);
            }
        }
Example #36
0
 // ===========================================================================
 public void Write(Stream stream)
 {
     // step 1
     using (Document document = new Document())
     {
         // step 2
         PdfWriter.GetInstance(document, stream);
         // step 3
         document.Open();
         // step 4
         PdfPTable table = new PdfPTable(2);
         // a long phrase
         Phrase p = new Phrase(
           "Dr. iText or: How I Learned to Stop Worrying and Love PDF."
         );
         PdfPCell cell = new PdfPCell(p);
         // the prhase is wrapped
         table.AddCell("wrap");
         cell.NoWrap = false;
         table.AddCell(cell);
         // the phrase isn't wrapped
         table.AddCell("no wrap");
         cell.NoWrap = true;
         table.AddCell(cell);
         // a long phrase with newlines
         p = new Phrase(
             "Dr. iText or:\nHow I Learned to Stop Worrying\nand Love PDF.");
         cell = new PdfPCell(p);
         // the phrase fits the fixed height
         table.AddCell("fixed height (more than sufficient)");
         cell.FixedHeight = 72f;
         table.AddCell(cell);
         // the phrase doesn't fit the fixed height
         table.AddCell("fixed height (not sufficient)");
         cell.FixedHeight = 36f;
         table.AddCell(cell);
         // The minimum height is exceeded
         table.AddCell("minimum height");
         cell = new PdfPCell(new Phrase("Dr. iText"));
         cell.MinimumHeight = 36f;
         table.AddCell(cell);
         // The last row is extended
         table.ExtendLastRow = true;
         table.AddCell("extend last row");
         table.AddCell(cell);
         document.Add(table);
     }
 }
Example #37
0
        public static iTextSharp.text.pdf.PdfPCell AddText2Cell(string text, iTextSharp.text.Font font, int colSpan)
        {
            const string METHOD_NAME = "AddText2Cell";

            try {
                iTextSharp.text.Phrase       phrase = new iTextSharp.text.Phrase(text, font);
                iTextSharp.text.pdf.PdfPCell cell   = new iTextSharp.text.pdf.PdfPCell(phrase);
                cell.BorderWidth = 0;
                cell.Colspan     = colSpan;

                return(cell);
            }
            catch (Exception ex) {
                ApplicationException aex = new ApplicationException(MOD_NAME + METHOD_NAME, ex);
                throw (aex);
            }
        }
Example #38
0
        public static iTextSharp.text.pdf.PdfPCell AddText2Table(PdfPTable table,
                                                                 string text, iTextSharp.text.Font font)
        {
            const string METHOD_NAME = "AddText2Table";

            try {
                iTextSharp.text.Phrase       phrase = new iTextSharp.text.Phrase(text, font);
                iTextSharp.text.pdf.PdfPCell cell   = new iTextSharp.text.pdf.PdfPCell(phrase);
                cell.BorderWidth = 0;
                table.AddCell(cell);

                return(cell);
            }
            catch (Exception ex) {
                ApplicationException aex = new ApplicationException(MOD_NAME + METHOD_NAME, ex);
                throw (aex);
            }
        }
Example #39
0
        public static iTextSharp.text.pdf.PdfPCell AddText2Cell(string text, iTextSharp.text.Font font, int hAlign, int vAlign, float fPadding, float borderWidth, int borderType, Color borderColor)
        {
            const string METHOD_NAME = "AddText2Cell";

            try {
                iTextSharp.text.Phrase       phrase = new iTextSharp.text.Phrase(text, font);
                iTextSharp.text.pdf.PdfPCell cell   = new iTextSharp.text.pdf.PdfPCell(phrase);

                cell.HorizontalAlignment = hAlign;
                cell.VerticalAlignment   = vAlign;
                cell.Padding             = fPadding;
                cell.BorderWidth         = borderWidth;
                cell.Border      = borderType;
                cell.BorderColor = borderColor;

                return(cell);
            }
            catch (Exception ex) {
                ApplicationException aex = new ApplicationException(MOD_NAME + METHOD_NAME, ex);
                throw (aex);
            }
        }
Example #40
0
        public static iTextSharp.text.pdf.PdfPCell AddText2Table(PdfPTable table,
                                                                 string text, iTextSharp.text.Font font, string align)
        {
            const string METHOD_NAME = "AddText2Table";

            try {
                iTextSharp.text.Phrase       phrase = new iTextSharp.text.Phrase(text, font);
                iTextSharp.text.pdf.PdfPCell cell   = new iTextSharp.text.pdf.PdfPCell(phrase);
                cell.BorderWidth = 0;
                // debug: comment out above and uncomment below to see cell borders.
                //cell.BorderWidth = 1.0F;
                //cell.BorderColor = Color.BLACK;

                switch (align.ToLower())
                {
                case "left":
                    cell.HorizontalAlignment = Element.ALIGN_LEFT;
                    break;

                case "center":
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    break;

                case "right":
                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    break;
                }
                table.AddCell(cell);

                return(cell);
            }
            catch (Exception ex) {
                ApplicationException aex = new ApplicationException(MOD_NAME + METHOD_NAME, ex);
                throw (aex);
            }
        }
        private static void ReportBuilder(int cropYear, ArrayList shidList, string busName, ArrayList growerPerformanceList, ArrayList regionCodeList, ArrayList areaCodeList,
                                          ArrayList regionNameList, ArrayList areaNameList, string logoUrl, string filePath, System.IO.FileStream fs)
        {
            const string METHOD_NAME = "ReportBuilder: ";
            const string CharBlank   = " ";
            const string CharAffirm  = "X";

            Document  document = null;
            PdfWriter writer   = null;
            PdfPTable table    = null;
            ShareholderSummaryEvent pgEvent = null;

            iTextSharp.text.Image imgLogo = null;

            int    iShid               = 0;
            string areaCode            = "";
            string regionCode          = "";
            string regionName          = "";
            string areaName            = "";
            int    growerPerformanceID = 0;

            string rptTitle = "Western Sugar Cooperative\nShareholder Summary for " + cropYear.ToString() + " Crop Year";

            string okFertility  = "";
            string okIrrigation = "";
            string okStand      = "";
            string okWeed       = "";
            string okDisease    = "";
            string okVariety    = "";

            string descFertility  = "";
            string descIrrigation = "";
            string descStand      = "";
            string descWeed       = "";
            string descDisease    = "";
            string descVariety    = "";

            // Build the contract information.
            try {
                for (int j = 0; j < shidList.Count; j++)
                {
                    string shid = shidList[j].ToString();
                    iShid = Convert.ToInt32(shid);

                    if (growerPerformanceList.Count == 0)
                    {
                        busName = "";
                        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BeetConn"].ToString())) {
                            using (SqlDataReader dr = WSCField.SharholderSummaryGetAreas(conn, cropYear, iShid)) {
                                while (dr.Read())
                                {
                                    growerPerformanceList.Add(dr["GrowerPerformanceID"].ToString());
                                    regionCodeList.Add(dr["RegionCode"].ToString());
                                    areaCodeList.Add(dr["AreaCode"].ToString());
                                    regionNameList.Add(dr["RegionName"].ToString());
                                    areaNameList.Add(dr["AreaName"].ToString());
                                    if (busName.Length == 0)
                                    {
                                        busName = dr["BusName"].ToString();
                                    }
                                }
                            }
                        }
                    }

                    // ---------------------------------------------------------------------------------------------------------
                    // Given all of the pieces, crop year, shid, growerPerformanceID, region, and area, generate the report
                    // ---------------------------------------------------------------------------------------------------------
                    if (areaCodeList.Count > 0)
                    {
                        for (int i = 0; i < areaCodeList.Count; i++)
                        {
                            growerPerformanceID = Convert.ToInt32(growerPerformanceList[i]);
                            regionCode          = regionCodeList[i].ToString();
                            areaCode            = areaCodeList[i].ToString();
                            regionName          = regionNameList[i].ToString();
                            areaName            = areaNameList[i].ToString();

                            // ------------------------------------------------
                            // Collect the data: Get the report card.
                            // ------------------------------------------------
                            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BeetConn"].ToString())) {
                                using (SqlDataReader dr = WSCField.GrowerAdviceGetBySHID(conn, growerPerformanceID)) {
                                    if (dr.Read())
                                    {
                                        //busName = dr["gadBusinessName"].ToString();
                                        okFertility  = dr["gadGoodFertilityManagement"].ToString();
                                        okIrrigation = dr["gadGoodIrrigationManagement"].ToString();
                                        okStand      = dr["gadGoodStandEstablishment"].ToString();
                                        okWeed       = dr["gadGoodWeedControl"].ToString();
                                        okDisease    = dr["gadGoodDiseaseControl"].ToString();
                                        okVariety    = dr["gadGoodVarietySelection"].ToString();

                                        descFertility  = dr["gadTextFertilityManagement"].ToString();
                                        descIrrigation = dr["gadTextIrrigationManagement"].ToString();
                                        descStand      = dr["gadTextStandEstablishment"].ToString();
                                        descWeed       = dr["gadTextWeedControl"].ToString();
                                        descDisease    = dr["gadTextDiseaseControl"].ToString();
                                        descVariety    = dr["gadTextVarietySelection"].ToString();
                                    }
                                    else
                                    {
                                        //busName = "";
                                        okFertility  = "";
                                        okIrrigation = "";
                                        okStand      = "";
                                        okWeed       = "";
                                        okDisease    = "";
                                        okVariety    = "";

                                        descFertility  = "";
                                        descIrrigation = "";
                                        descStand      = "";
                                        descWeed       = "";
                                        descDisease    = "";
                                        descVariety    = "";
                                    }
                                }
                            }

                            if (document == null)
                            {
                                // IF YOU CHANGE MARGINS, CHANGE YOUR TABLE LAYOUTS !!!
                                //  ***  US LETTER: 612 X 792  ***
                                //document = new Document(iTextSharp.text.PageSize.LETTER, 36, 36, 54, 72);
                                document = new Document(PortraitPageSize.PgPageSize, PortraitPageSize.PgLeftMargin,
                                                        PortraitPageSize.PgRightMargin, PortraitPageSize.PgTopMargin, PortraitPageSize.PgBottomMargin);

                                // we create a writer that listens to the document
                                // and directs a PDF-stream to a file
                                writer = PdfWriter.GetInstance(document, fs);

                                imgLogo = PdfReports.GetImage(logoUrl, 127, 50, iTextSharp.text.Element.ALIGN_CENTER);

                                // Attach my override event handler(s)
                                //busName = dr["Business Name"].ToString();
                                pgEvent = new ShareholderSummaryEvent();
                                pgEvent.FillEvent(cropYear, shid, busName, rptTitle, regionName, areaName, imgLogo);

                                writer.PageEvent = pgEvent;

                                // Open the document
                                document.Open();
                            }
                            else
                            {
                                // everytime thru kick out a new page because we're on a different shid/region/area combination.
                                pgEvent.FillEvent(cropYear, shid, busName, rptTitle, regionName, areaName, imgLogo);
                                document.NewPage();
                            }

                            // -----------------------------------------------------
                            // Create the report card
                            // -----------------------------------------------------
                            table = PdfReports.CreateTable(_adviceTableLayout, 1);

                            Color borderColor   = Color.BLACK;  //new Color(255, 0, 0);
                            float borderWidth   = 1.0F;
                            int   borderTypeAll = Rectangle.TOP_BORDER | Rectangle.RIGHT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.LEFT_BORDER;
                            float fPadding      = 3;

                            // HEADER
                            iTextSharp.text.pdf.PdfPCell cell = PdfReports.AddText2Cell("Okay", _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                                                        fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell("Opportunity\nfor\nImprovement", _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell("Big Six Growing Practices", _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            /// ----------------------------------------
                            // TBODY
                            /// ----------------------------------------
                            // Fertility
                            cell = PdfReports.AddText2Cell((okFertility == "Y" ? CharAffirm : CharBlank), _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell((okFertility == "N" ? CharAffirm : CharBlank), _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell("Fertility Management", _labelFont, PdfPCell.ALIGN_LEFT, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            // Irrigation
                            cell = PdfReports.AddText2Cell((okIrrigation == "Y" ? CharAffirm : CharBlank), _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell((okIrrigation == "N" ? CharAffirm : CharBlank), _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell("Irrigation Water Management", _labelFont, PdfPCell.ALIGN_LEFT, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            // Stand
                            cell = PdfReports.AddText2Cell((okStand == "Y" ? CharAffirm : CharBlank), _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell((okStand == "N" ? CharAffirm : CharBlank), _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell("Stand Establishment (Harvest Plant Population)", _labelFont, PdfPCell.ALIGN_LEFT, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            // Weed
                            cell = PdfReports.AddText2Cell((okWeed == "Y" ? CharAffirm : CharBlank), _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell((okWeed == "N" ? CharAffirm : CharBlank), _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell("Weed Control", _labelFont, PdfPCell.ALIGN_LEFT, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            // Disease
                            cell = PdfReports.AddText2Cell((okDisease == "Y" ? CharAffirm : CharBlank), _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell((okDisease == "N" ? CharAffirm : CharBlank), _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell("Disease & Insect Control", _labelFont, PdfPCell.ALIGN_LEFT, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            // Varitey
                            cell = PdfReports.AddText2Cell((okVariety == "Y" ? CharAffirm : CharBlank), _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell((okVariety == "N" ? CharAffirm : CharBlank), _labelFont, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            cell = PdfReports.AddText2Cell("Proper Variety Selection", _labelFont, PdfPCell.ALIGN_LEFT, PdfPCell.ALIGN_BOTTOM,
                                                           fPadding, borderWidth, borderTypeAll, borderColor);
                            table.AddCell(cell);

                            PdfReports.AddText2Table(table, " ", _normalFont, 3);

                            PdfReports.AddTableNoSplit(document, pgEvent, table);

                            // ==========================================================
                            // Recommendations for Improvement.
                            // ==========================================================
                            table = PdfReports.CreateTable(_adviceTableLayout, 1);

                            // Caption
                            iTextSharp.text.Phrase phrase = new iTextSharp.text.Phrase("Recommendations for Improvement", _labelFont);
                            cell         = new iTextSharp.text.pdf.PdfPCell(phrase);
                            cell.Colspan = 3;

                            cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                            cell.VerticalAlignment   = PdfPCell.ALIGN_BOTTOM;
                            cell.Padding             = fPadding;
                            cell.BorderWidth         = borderWidth;
                            cell.Border      = Rectangle.TOP_BORDER | Rectangle.RIGHT_BORDER | Rectangle.LEFT_BORDER;
                            cell.BorderColor = borderColor;
                            table.AddCell(cell);

                            // Content
                            phrase = new iTextSharp.text.Phrase((descFertility.Length > 0 ? descFertility + "\n\n" : "") +
                                                                (descIrrigation.Length > 0 ? descIrrigation + "\n\n" : "") +
                                                                (descStand.Length > 0 ? descStand + "\n\n" : "") +
                                                                (descWeed.Length > 0 ? descWeed + "\n\n" : "") +
                                                                (descDisease.Length > 0 ? descDisease + "\n\n" : "") +
                                                                (descVariety.Length > 0 ? descVariety + "\n\n" : ""), _normalFont);

                            cell         = new iTextSharp.text.pdf.PdfPCell(phrase);
                            cell.Colspan = 3;

                            cell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                            cell.VerticalAlignment   = PdfPCell.ALIGN_BOTTOM;
                            cell.Padding             = fPadding;
                            cell.BorderWidth         = borderWidth;
                            cell.Border      = Rectangle.RIGHT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.LEFT_BORDER;
                            cell.BorderColor = borderColor;
                            table.AddCell(cell);

                            PdfReports.AddText2Table(table, " ", _normalFont, table.NumberOfColumns);
                            PdfReports.AddText2Table(table, " ", _normalFont, table.NumberOfColumns);

                            PdfReports.AddTableNoSplit(document, pgEvent, table);

                            // ------------------------------------------------
                            // Create the contract dump.
                            // ------------------------------------------------
                            ArrayList cntPerfs;
                            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BeetConn"].ToString())) {
                                cntPerfs = WSCField.ShareholderSummaryContracts(conn, iShid, cropYear, regionCode, areaCode);
                            }

                            // =======================================
                            // HEADER
                            // =======================================
                            table = PdfReports.CreateTable(_contractTableLayout, 0);
                            pgEvent.BuildContractDumpHeader(document, _contractTableLayout);
                            pgEvent.ContractTableLayout = _contractTableLayout;

                            // DATA
                            for (int k = 0; k < cntPerfs.Count; k++)
                            {
                                ContractPerformanceState perf = (ContractPerformanceState)cntPerfs[k];

                                switch (perf.RowType)
                                {
                                case 1:

                                    table = PdfReports.CreateTable(_contractTableLayout, 0);

                                    PdfReports.AddText2Table(table, perf.ContractNumber, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.ContractStation, _normalFont);
                                    PdfReports.AddText2Table(table, perf.FieldDescription, _normalFont);
                                    PdfReports.AddText2Table(table, perf.LandownerName, _normalFont);
                                    PdfReports.AddText2Table(table, perf.HarvestFinalNetTons, _normalFont, "right");
                                    PdfReports.AddText2Table(table, perf.TonsPerAcre, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestSugarPct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestTarePct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestSLMPct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestExtractableSugar, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.BeetsPerAcre, _normalFont, "center");

                                    PdfReports.AddTableNoSplit(document, pgEvent, table);

                                    break;

                                case 2:

                                    table = PdfReports.CreateTable(_contractTableLayout, 0);

                                    PdfReports.AddText2Table(table, " ", _normalFont, _contractTableLayout.Length);
                                    PdfReports.AddText2Table(table, " ", _normalFont);
                                    PdfReports.AddText2Table(table, "Overall Average", _labelFont, 3);
                                    PdfReports.AddText2Table(table, perf.HarvestFinalNetTons, _normalFont, "right");
                                    PdfReports.AddText2Table(table, perf.TonsPerAcre, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestSugarPct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestTarePct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestSLMPct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestExtractableSugar, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.BeetsPerAcre, _normalFont, "center");

                                    break;

                                case 3:

                                    PdfReports.AddText2Table(table, " ", _normalFont);
                                    PdfReports.AddText2Table(table, "Top 20% Area Average", _labelFont, 4);
                                    PdfReports.AddText2Table(table, perf.TonsPerAcre, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestSugarPct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestTarePct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestSLMPct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestExtractableSugar, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.BeetsPerAcre, _normalFont, "center");

                                    break;

                                case 4:

                                    PdfReports.AddText2Table(table, " ", _normalFont);
                                    PdfReports.AddText2Table(table, "Your Rankings", _labelFont, 10);

                                    PdfReports.AddText2Table(table, " ", _normalFont);
                                    PdfReports.AddText2Table(table, areaName, _labelFont, 4);
                                    PdfReports.AddText2Table(table, perf.TonsPerAcre, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestSugarPct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestTarePct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestSLMPct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestExtractableSugar, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.BeetsPerAcre, _normalFont, "center");

                                    break;

                                case 5:

                                    PdfReports.AddText2Table(table, " ", _normalFont);
                                    PdfReports.AddText2Table(table, regionName, _labelFont, 4);
                                    PdfReports.AddText2Table(table, perf.TonsPerAcre, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestSugarPct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestTarePct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestSLMPct, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.HarvestExtractableSugar, _normalFont, "center");
                                    PdfReports.AddText2Table(table, perf.BeetsPerAcre, _normalFont, "center");

                                    PdfReports.AddTableNoSplit(document, pgEvent, table);

                                    break;
                                }
                            }

                            pgEvent.ContractTableLayout = null;
                        }
                    }

                    // --------------------------------------------
                    // --------  reset for next iteration  --------
                    // --------------------------------------------
                    growerPerformanceList.Clear();
                    regionCodeList.Clear();
                    areaCodeList.Clear();
                    regionNameList.Clear();
                    areaNameList.Clear();
                }

                // ======================================================
                // Close document
                // ======================================================
                if (document != null)
                {
                    pgEvent.IsDocumentClosing = true;
                    document.Close();
                    document = null;
                }
                if (writer == null)
                {
                    // Warn that we have no data.
                    WSCIEMP.Common.CWarning warn = new WSCIEMP.Common.CWarning("No records matched your report criteria.");
                    throw (warn);
                }
            }
            catch (Exception ex) {
                string errMsg = "document is null: " + (document == null).ToString() + "; " +
                                "writer is null: " + (writer == null).ToString();
                WSCIEMP.Common.CException wscex = new WSCIEMP.Common.CException(MOD_NAME + METHOD_NAME + errMsg, ex);
                throw (wscex);
            }
            finally {
                if (document != null)
                {
                    pgEvent.IsDocumentClosing = true;
                    document.Close();
                }
                if (writer != null)
                {
                    writer.Close();
                }
            }
        }
Example #42
0
        public string CrearPdf(PagareContrato pagareContrato)
        {
            Guid x = Guid.NewGuid();

            manager = new Manager.Manager();
            Utilitario  Util          = new Utilitario();
            Solicitudes solicitudes   = new Solicitudes();
            var         pagareCon     = new List <PagareContrato>();
            var         datosContrato = new List <PagareContrato>();

            string xClase      = string.Format("{0}|{1}", MethodBase.GetCurrentMethod().Module.Name, MethodBase.GetCurrentMethod().DeclaringType.Name);
            string xProceso    = MethodBase.GetCurrentMethod().Name;
            string strHostName = System.Net.Dns.GetHostName();
            //IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName()); <-- Obsolete
            IPHostEntry ipHostInfo = Dns.GetHostEntry(strHostName);
            IPAddress   ipAddress  = ipHostInfo.AddressList[0];

            Tab_ConfigSys dto_Config = new Tab_ConfigSys();

            dto_Config.llave_Config1 = "SERVICIO";
            dto_Config.llave_Config2 = "CONFIGURACION";
            dto_Config.llave_Config3 = "SERVIDOR";
            dto_Config.llave_Config4 = "DIRECTORIO";
            dto_Config.llave_Config5 = "CONTRATOPAGARE";

            solicitudes.IdTipoIdentificacion = pagareContrato.IdTipoIdentificacion;
            solicitudes.Identificacion       = pagareContrato.Identificacion;

            var dto_DatosCredito = manager.CargarDatosCredito(solicitudes);

            var    dto_interval = manager.ConsultaConfiUrlImagen(dto_Config);
            string URL          = dto_interval.Where(y => y.llave_Config5 == "CONTRATOPAGARE").Select(y => y.Dato_Char1).FirstOrDefault();

            var dto_excepcion = new UTL_TRA_EXCEPCION
            {
                STR_CLASE      = xClase,
                STR_EVENTO     = xProceso,
                STR_APLICATIVO = ConfigurationManager.AppSettings["APLICATIVO"].ToString(),
                STR_SERVIDOR   = ipAddress.ToString(),
                STR_PARAMETROS = JsonConvert.SerializeObject(pagareContrato),
                FEC_CREACION   = DateTime.Now
            };

            try
            {
                if (dto_DatosCredito.Any())
                {
                    pagareCon = manager.TraeDocumentoPagare();
                    pagareContrato.IdSolicitud       = dto_DatosCredito.FirstOrDefault().IdSolicitud;
                    pagareContrato.fechagenerapagare = DateTime.Today;
                    datosContrato           = manager.PagareContrato(pagareContrato);
                    pagareContrato.Pagare   = pagareCon.FirstOrDefault().Pagare;
                    pagareContrato.Contrato = pagareCon.FirstOrDefault().Contrato;

                    string Contrato = pagareContrato.Contrato;
                    string Pagare   = pagareContrato.Pagare;
                    string fileName = @"Pagare y contrato_" + datosContrato[0].Nombre + ".docx";

                    //Remplazo en la cadena los datos para generar el contrato
                    Contrato = Contrato.Replace("<Nombre>", datosContrato[0].Nombre);
                    Contrato = Contrato.Replace("<Identificacion>", datosContrato[0].Identificacion);
                    Contrato = Contrato.Replace("<MontoProductoLetras>", datosContrato[0].MontoProductoLetras);
                    Contrato = Contrato.Replace("<Moneda>", datosContrato[0].Moneda);
                    Contrato = Contrato.Replace("<MontoProducto>", Convert.ToString(datosContrato[0].MontoProducto));
                    Contrato = Contrato.Replace("<CantidadCuotas>", Convert.ToString(datosContrato[0].CantidadCuotas));
                    Contrato = Contrato.Replace("<Frecuencia>", datosContrato[0].Frecuencia);
                    Contrato = Contrato.Replace("<Cuota>", Convert.ToString(datosContrato[0].Cuota));
                    Contrato = Contrato.Replace("<FechaPrimerPagoLetras>", datosContrato[0].FechaPrimerPagoLetras);
                    Contrato = Contrato.Replace("<FechaUltimoPagoLetras>", datosContrato[0].FechaUltimoPagoLetras);
                    Contrato = Contrato.Replace("<Interes>", Convert.ToString(datosContrato[0].Interes));
                    Contrato = Contrato.Replace("<InteresLetras>", datosContrato[0].InteresLetras);
                    Contrato = Contrato.Replace("<CtaCliente>", datosContrato[0].CtaCliente);
                    Contrato = Contrato.Replace("<FechaHoy>", datosContrato[0].FechaHoy);
                    Contrato = Contrato.Replace("<CuotaenLetras>", datosContrato[0].CuotaenLetras);
                    Contrato = Contrato.Replace("<Frecuencia2>", datosContrato[0].Frecuencia2);
                    Contrato = Contrato.Replace("<Frecuencia3>", datosContrato[0].Frecuencia3);
                    Contrato = Contrato.Replace("<CantidadCuotasLetras>", datosContrato[0].CantidadCuotasLetras);

                    //Reemplazo los datos para generar el Pagaré
                    Pagare = Pagare.Replace("<Nombre>", datosContrato[0].Nombre);
                    Pagare = Pagare.Replace("<Identificacion>", datosContrato[0].Identificacion);
                    Pagare = Pagare.Replace("<MontoProductoLetras>", datosContrato[0].MontoProductoLetras);
                    Pagare = Pagare.Replace("<Moneda>", datosContrato[0].Moneda);
                    Pagare = Pagare.Replace("<MontoProductoPagare>", Convert.ToString(datosContrato[0].MontoProductoPagare));
                    Pagare = Pagare.Replace("<MontoProductoLetrasPagare>", Convert.ToString(datosContrato[0].MontoProductoLetrasPagare));
                    Pagare = Pagare.Replace("<CantidadCuotas>", Convert.ToString(datosContrato[0].CantidadCuotas));
                    Pagare = Pagare.Replace("<Frecuencia>", datosContrato[0].Frecuencia);
                    Pagare = Pagare.Replace("<Cuota>", Convert.ToString(datosContrato[0].Cuota));
                    Pagare = Pagare.Replace("<FechaPrimerPagoLetras>", datosContrato[0].FechaPrimerPagoLetras);
                    Pagare = Pagare.Replace("<FechaUltimoPagoLetras>", datosContrato[0].FechaUltimoPagoLetras);
                    Pagare = Pagare.Replace("<Interes>", Convert.ToString(datosContrato[0].Interes));
                    Pagare = Pagare.Replace("<InteresLetras>", datosContrato[0].InteresLetras);
                    Pagare = Pagare.Replace("<CtaCliente>", datosContrato[0].CtaCliente);
                    Pagare = Pagare.Replace("<FechaHoy>", datosContrato[0].FechaHoy);
                    Pagare = Pagare.Replace("<CuotaenLetras>", datosContrato[0].CuotaenLetras);
                    Pagare = Pagare.Replace("<CantidadCuotasLetras>", datosContrato[0].CantidadCuotasLetras);
                    Pagare = Pagare.Replace("<Frecuencia2>", datosContrato[0].Frecuencia2);
                    Pagare = Pagare.Replace("<pagoProximasCuotas>", datosContrato[0].PagoProximasCuotas);

                    //creamos la imagen editada de la firma para agregarla luego al documento
                    if (datosContrato[0].FotoFirma != "")
                    {
                        editarImagen(datosContrato[0].FotoFirma);
                    }

                    //Doy formato al archivo PDF
                    iTextSharp.text.Font fontHeader_1 = FontFactory.GetFont("Calibri", 9, iTextSharp.text.Font.NORMAL, new iTextSharp.text.BaseColor(0, 0, 0));
                    //Genero el documento PDF con la libreria iTextSharp
                    using (Document pdfDoc = new Document(PageSize.LETTER, 25f, 25f, 25f, 25f))
                    {
                        iTextSharp.text.Document oDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER);
                        //Escribo el documento en el archivo PDF generado
                        //PdfWriter.GetInstance(pdfDoc, HttpContext.Current.Response.OutputStream);

                        var OutputPathDocumento = AppDomain.CurrentDomain.BaseDirectory + "/Machote/archivos/Documento-" + datosContrato.FirstOrDefault().Nombre.ToString() + x + ".pdf";
                        using (PdfWriter wri = PdfWriter.GetInstance(pdfDoc, new FileStream(OutputPathDocumento, FileMode.Create)))
                        {
                            pdfDoc.Open();

                            var espacio = new Paragraph(" ");
                            //Ingreso el texto que corresponde al Contrato
                            var tituloContrato = new Paragraph("Solicitud N°: " + datosContrato.FirstOrDefault().Id.ToString(), FontFactory.GetFont("Calibri", 14, BaseColor.BLACK));
                            tituloContrato.Alignment = Element.ALIGN_CENTER;
                            tituloContrato.Font.Size = 14;
                            pdfDoc.Add(tituloContrato);
                            pdfDoc.Add(espacio);
                            var Contratopdf = new Paragraph(Contrato, fontHeader_1);
                            Contratopdf.Alignment = Element.ALIGN_JUSTIFIED;
                            Contratopdf.Font.Size = 8;
                            pdfDoc.Add(Contratopdf);


                            //si existe foto de la firma lo agregamos al contrato
                            if (datosContrato[0].FotoFirma != "")
                            {
                                //creamos la imagen de la firma para el PDF
                                iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance(@AppDomain.CurrentDomain.BaseDirectory + @"\Machote\FotoFirma-Copia-Editada.png");
                                imagen.BorderWidth = 0;
                                imagen.Alignment   = Element.ALIGN_LEFT;
                                float percentage = 0.0f;
                                percentage = 70 / imagen.Width;
                                imagen.ScalePercent(percentage * 100);

                                //creamos una tabla para agregar la imagen
                                PdfPTable tablaImagen = new PdfPTable(1);;
                                PdfPCell  c1          = new PdfPCell();
                                PdfPCell  c2          = new PdfPCell(imagen);
                                c1.Border              = 0;
                                c2.Border              = 0;
                                c2.VerticalAlignment   = Element.ALIGN_MIDDLE;
                                c2.HorizontalAlignment = Element.ALIGN_LEFT;
                                tablaImagen.AddCell(c1); //celda con espacio a la derecha
                                tablaImagen.AddCell(c2); //celda con la imagen de la firma

                                // Insertamos la tabla con la imagen de la firma en el contrato
                                pdfDoc.Add(tablaImagen);
                            }
                            else
                            {
                                pdfDoc.Add(espacio);
                                pdfDoc.Add(espacio);
                            }

                            //Agregamos la info final del contrato
                            string textoFinal   = "               ……………………………………………                                                                                          ……………………………………………\n                                   El DEUDOR                                                                                                                                   LA ACREEDORA\n\n\n                                    " + datosContrato.FirstOrDefault().Identificacion.ToString() + "\n               …………………………………………      \n                                     CÉDULA ";
                            var    parrafoFinal = new Paragraph(textoFinal, fontHeader_1);
                            pdfDoc.Add(parrafoFinal);

                            //Ingreso el titulo del Pagaré
                            pdfDoc.NewPage();
                            var SubtituloPdf = new Paragraph("Pagaré N°: " + datosContrato.FirstOrDefault().Id.ToString(), FontFactory.GetFont("Calibri", 14, BaseColor.BLACK));
                            SubtituloPdf.Alignment = Element.ALIGN_CENTER;
                            SubtituloPdf.Font.Size = 14;
                            pdfDoc.Add(SubtituloPdf);
                            pdfDoc.Add(espacio);
                            //Ingreso Texto de Pagare
                            var PagarePdf = new Paragraph(Pagare, FontFactory.GetFont("Calibri", 10, BaseColor.BLACK));
                            PagarePdf.Alignment = Element.ALIGN_JUSTIFIED;
                            PagarePdf.Font.Size = 10;
                            pdfDoc.Add(PagarePdf);

                            if (datosContrato[0].FotoFirma != "")
                            {
                                iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance(@AppDomain.CurrentDomain.BaseDirectory + @"\Machote\FotoFirma-Copia-Editada.png");
                                imagen.BorderWidth = 0;
                                imagen.Alignment   = Element.ALIGN_LEFT;
                                float percentage = 0.0f;
                                percentage = 70 / imagen.Width;
                                imagen.ScalePercent(percentage * 100);
                                // Insertamos la imagen de la firma en el Pagare
                                PdfPTable tablaImagenPagare       = new PdfPTable(5);;
                                iTextSharp.text.Phrase fraseFirma = new iTextSharp.text.Phrase("Firma Deudor:");
                                fraseFirma.Font.Size = 10;
                                PdfPCell espacioCelda = new PdfPCell();
                                PdfPCell celdaTexto   = new PdfPCell(fraseFirma);
                                PdfPCell celdaFirma   = new PdfPCell(imagen);
                                espacioCelda.Border            = 0;
                                celdaTexto.Border              = 0;
                                celdaTexto.VerticalAlignment   = Element.ALIGN_MIDDLE;
                                celdaTexto.HorizontalAlignment = Element.ALIGN_LEFT;
                                celdaFirma.Border              = 0;
                                celdaFirma.VerticalAlignment   = Element.ALIGN_MIDDLE;
                                celdaFirma.HorizontalAlignment = Element.ALIGN_LEFT;
                                tablaImagenPagare.AddCell(celdaTexto);   //celda con el texto de la firma
                                tablaImagenPagare.AddCell(celdaFirma);   //celda con la imagen de la firma
                                tablaImagenPagare.AddCell(espacioCelda); //celda con espacio en blanco
                                tablaImagenPagare.AddCell(espacioCelda); //celda con espacio en blanco
                                tablaImagenPagare.AddCell(espacioCelda); //celda con espacio en blanco
                                pdfDoc.Add(tablaImagenPagare);
                            }
                            else
                            {
                                var parrafoFirma = new Paragraph("\n\n                     Firma Deudor: \n\n\n", fontHeader_1);
                                parrafoFirma.Font.Size = 10;
                                pdfDoc.Add(parrafoFirma);
                            }
                            //Agregamos la info final del contrato
                            string textoFinalPagare   = "                     Nombre Completo:   " + datosContrato[0].Nombre + "\n\n\n                     Número de Cédula:   " + datosContrato[0].Identificacion;
                            var    parrafoFinalPagare = new Paragraph(textoFinalPagare, fontHeader_1);
                            parrafoFinalPagare.Font.Size = 10;
                            pdfDoc.Add(parrafoFinalPagare);
                            //Cierro el archivo PDF
                            pdfDoc.Close();
                            wri.Close();
                        }
                        oDoc.Close();
                    }

                    //Proceso para crear y agregar el formulario BCCR a el pdf final
                    var    path          = @AppDomain.CurrentDomain.BaseDirectory + @"\Machote\formulario-bac.html";
                    var    pathOriginal  = @AppDomain.CurrentDomain.BaseDirectory + @"\Machote\formulario-bac-sin-remplazo.html";
                    string html          = File.ReadAllText(pathOriginal);
                    string EncodedString = "";
                    string ret           = "";
                    string DecodedStringFormulario;
                    string htmlOriginal = html; //este sera el html orinal sin hacer los remplazas para luego de todo el proceso volver a guaradr el archivo html con los valores originales
                    using (StringWriter writer = new StringWriter())
                    {
                        HttpUtility.HtmlEncode(html, writer);

                        //Server.HtmlEncode(html, writer);
                        EncodedString           = html.ToString();
                        ret                     = completarFormularioDomiciliacion(EncodedString, datosContrato[0]); // replazamos el html con la info dinamica
                        DecodedStringFormulario = HttpUtility.HtmlDecode(ret);                                       //Server.HtmlDecode(ret);
                        writer.Close();
                    }
                    using (StreamWriter sw = new StreamWriter(path)) //sobrescribimos el html con la nueva info
                    {
                        sw.WriteLine(DecodedStringFormulario);
                        sw.Close();
                    }
                    //Generamos el pdf del formulario caon base en el archivo html

                    NReco.PdfGenerator.HtmlToPdfConverter pdfFormulario = new NReco.PdfGenerator.HtmlToPdfConverter();
                    pdfFormulario.PageHeight = 279;
                    pdfFormulario.PageWidth  = 216;
                    pdfFormulario.GeneratePdfFromFile(path, null, @AppDomain.CurrentDomain.BaseDirectory + @"\Machote\archivos\Formulario-" + datosContrato.FirstOrDefault().Nombre + x + ".pdf");

                    //llamamos al metodo interno mergePdfs para unir los pdfs del contrato, el pagare y el formulario
                    string rutaDocumentoFinal = URL + "/" + pagareContrato.Identificacion + "/" + "Contrato_Pagare_" + pagareContrato.Identificacion + ".pdf";


                    if (Util.ValidarFichero(rutaDocumentoFinal) == true)
                    {
                        rutaDocumentoFinal = Util.Renamefile(rutaDocumentoFinal, pagareContrato.Identificacion, ".pdf");
                        string[] archivos = { AppDomain.CurrentDomain.BaseDirectory + "/Machote/archivos/Documento-" + datosContrato.FirstOrDefault().Nombre + x + ".pdf", @AppDomain.CurrentDomain.BaseDirectory + @"\Machote\archivos\Formulario-" + datosContrato.FirstOrDefault().Nombre + x + ".pdf" };
                        mergePdfs(rutaDocumentoFinal, archivos);
                    }
                    //volvemos a guaradar el archivo html Original(sin los valores remplazados)
                    using (StreamWriter sw = new StreamWriter(path))
                    {
                        sw.WriteLine(htmlOriginal);
                        sw.Close();
                    }
                    File.Delete(AppDomain.CurrentDomain.BaseDirectory + "/Machote/archivos/Documento-" + datosContrato.FirstOrDefault().Nombre + x + ".pdf");
                    File.Delete(@AppDomain.CurrentDomain.BaseDirectory + @"\Machote\archivos\Formulario-" + datosContrato.FirstOrDefault().Nombre + x + ".pdf");
                    File.Delete(@AppDomain.CurrentDomain.BaseDirectory + @"\Machote\FotoFirma-Copia-Editada.png");

                    return(rutaDocumentoFinal);
                }
            }
            catch (Exception ex)
            {
                dto_excepcion.STR_MENSAJE = ex.Message;
                DynamicSqlDAO.guardaExcepcion(dto_excepcion, GlobalClass.connectionString.Where(a => a.Key == infDto.STR_COD_PAIS).FirstOrDefault().Value);
                pagareContrato.Mensaje = "ERR";
            }

            return(null);
        }
        private void CreateReport(string filePath)
        {
            AppFileTemplate f = (AppFileTemplate)DataContext;

            // margins
            float left   = 30;
            float right  = 10;
            float top    = 10;
            float bottom = 10;
            float headH  = 20;
            float indent = 5;

            //string fontName = "C:\\WINDOWS\\FONTS\\CALIBRI.TTF";
            string fontName = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "CALIBRI.TTF");

            iText.Font     NormalSatirFont  = iText.FontFactory.GetFont(fontName, "CP1254", 10, iText.Font.NORMAL);
            iText.Font     BoldSatirFont    = iText.FontFactory.GetFont(fontName, "CP1254", 10, iText.Font.BOLD);
            iText.Font     NormalRiseFont   = iText.FontFactory.GetFont(fontName, "CP1254", 8, iText.Font.NORMAL);
            iText.Font     NormalSymbolFont = iText.FontFactory.GetFont(iText.FontFactory.SYMBOL, 10, iText.Font.NORMAL);
            iText.Document doc = new iText.Document(iText.PageSize.A4, left, right, top, bottom);

            float xLL = doc.GetLeft(left);
            float yLL = doc.GetBottom(bottom);
            float xUR = doc.GetRight(right);
            float yUR = doc.GetTop(top);
            float w   = xUR - xLL;
            float h   = yUR - yLL;
            float xUL = xLL;
            float yUL = yUR;
            float xLR = xUR;
            float yLR = yLL;
            //float graphW = w - 10;
            //float graphH = graphW * 2 / 3;


            float graphH = 3 * h / 5;
            float graphW = w - 10;


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

            doc.Open();

            // direct content
            PdfContentByte cb = writer.DirectContent;

            // çizgiler
            DrawLine(cb, xUR - w, yUR, xUR, yUR);
            DrawLine(cb, xUR - w, yUR, xLL, yLL);
            DrawLine(cb, xLL, yLL, xLL + w, yLL);
            DrawLine(cb, xLL + w, yLL, xUR, yUR);
            DrawLine(cb, xUL, yUL - headH, xUR, yUR - headH);
            DrawLine(cb, xUL, yUL - headH - graphH, xUR, yUR - headH - graphH);

            // başlık
            ColumnText ct = new ColumnText(cb);

            ct.Indent = indent;
            iText.Phrase txt = new iText.Phrase();
            txt.Add(new iText.Chunk(f.ReportTitle, NormalSatirFont));
            ct.SetSimpleColumn(txt, xUL, yUL - headH, xUR, yUR, headH / 1.5f, iText.Element.ALIGN_LEFT | iText.Element.ALIGN_MIDDLE);
            ct.Go();

            var stream      = new MemoryStream();
            var pngExporter = new PngExporter {
                Width = (int)graphW, Height = (int)graphH, Background = OxyColors.White
            };

            pngExporter.Export(PlotView.Model, stream);

            iText.Image png = iText.Image.GetInstance(stream.GetBuffer());
            png.Alignment = iText.Element.ALIGN_CENTER | iText.Element.ALIGN_MIDDLE;
            png.SetAbsolutePosition(xUL, yUL - headH - graphH);
            doc.Add(png);

            float      kstW    = w / 2;
            float      kstH    = (h - headH - graphH) / 1.5f;
            ColumnText ctKesit = new ColumnText(cb);

            ctKesit.Indent = indent;
            txt            = new iText.Phrase();
            txt.Add(new iText.Chunk("Kesit\n", BoldSatirFont));
            txt.Add(new iText.Chunk(String.Format("Genişlik, b = {0:0} cm\n", f.b), NormalSatirFont));
            txt.Add(new iText.Chunk(String.Format("Yükseklik, h = {0:0} cm\n", f.h), NormalSatirFont));
            txt.Add(new iText.Chunk(String.Format("Alan, bxh = {0:0} cm²\n", f.b * f.h), NormalSatirFont));
            txt.Add(new iText.Chunk("\nMalzeme\n", BoldSatirFont));
            txt.Add(new iText.Chunk("f", NormalSatirFont));
            txt.Add(new iText.Chunk("c", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(String.Format(" = {0:0} MPa   ", f.Beton().fc.TonnesForcePerSquareMeter().Megapascals), NormalSatirFont));
            txt.Add(new iText.Chunk("f", NormalSatirFont));
            txt.Add(new iText.Chunk("y", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(String.Format(" = {0:0} MPa\n", f.DonatiCeligi().fy.TonnesForcePerSquareMeter().Megapascals), NormalSatirFont));

            txt.Add(new iText.Chunk("f", NormalSatirFont));
            txt.Add(new iText.Chunk("cd", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(String.Format(" = {0:0} MPa   ", f.Beton().fcd.TonnesForcePerSquareMeter().Megapascals), NormalSatirFont));

            txt.Add(new iText.Chunk("f", NormalSatirFont));
            txt.Add(new iText.Chunk("yd", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(String.Format(" = {0:0} MPa\n", f.DonatiCeligi().fyd.TonnesForcePerSquareMeter().Megapascals), NormalSatirFont));

            txt.Add(new iText.Chunk("E", NormalSatirFont));
            txt.Add(new iText.Chunk("c", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(String.Format(" = {0:0} MPa   ", f.Beton().E.TonnesForcePerSquareMeter().Megapascals), NormalSatirFont));
            txt.Add(new iText.Chunk("E", NormalSatirFont));
            txt.Add(new iText.Chunk("s", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(String.Format(" = {0:0} MPa\n", f.DonatiCeligi().E.TonnesForcePerSquareMeter().Megapascals), NormalSatirFont));
            txt.Add(new iText.Chunk("e", NormalSymbolFont));
            txt.Add(new iText.Chunk("cu", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(String.Format(" = {0:0.0000} m/m   ", f.Beton().Ecu), NormalSatirFont));
            txt.Add(new iText.Chunk("e", NormalSymbolFont));
            txt.Add(new iText.Chunk("yd", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(String.Format(" = {0:0.00000} m/m\n", f.DonatiCeligi().Eyd), NormalSatirFont));
            txt.Add(new iText.Chunk("k", NormalSatirFont));
            txt.Add(new iText.Chunk("1", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(String.Format(" = {0:0.000}\n", f.Beton().k1), NormalSatirFont));

            ctKesit.SetSimpleColumn(txt, xUL, yUL - headH - graphH - kstH, xUL + kstW, yUL - headH - graphH, 15, iText.Element.ALIGN_LEFT);
            ctKesit.Go();

            ColumnText ctDonati = new ColumnText(cb);

            txt = new iText.Phrase();
            txt.Add(new iText.Chunk("Donatı\n", BoldSatirFont));
            int j = 1;

            foreach (var rb in f.ReinforcingBars)
            {
                txt.Add(new iText.Chunk("A", NormalSatirFont));
                txt.Add(new iText.Chunk(string.Format("s{0}", j), NormalRiseFont).SetTextRise(-1.0f));
                txt.Add(new iText.Chunk(string.Format("={0:0.00} cm², ", rb.As), NormalSatirFont));
                txt.Add(new iText.Chunk("d", NormalSatirFont));
                txt.Add(new iText.Chunk(string.Format("{0}", j), NormalRiseFont).SetTextRise(-1.0f));
                txt.Add(new iText.Chunk(string.Format("={0:0.00} cm\n", rb.di), NormalSatirFont));
                j++;
            }
            txt.Add(new iText.Chunk("r", NormalSymbolFont));
            txt.Add(new iText.Chunk(string.Format("=%{0:0.00}\n", 100.0 * f.ReinforcingBars.Sum(i => i.As) / (f.b * f.h)), NormalSatirFont));
            txt.Add(new iText.Chunk("(d", NormalSatirFont));
            txt.Add(new iText.Chunk("i", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(":Kesit basınç yüzeyinin donatı eksenine uzaklığı)\n", NormalSatirFont));
            txt.Add(new iText.Chunk("\nDayanım Azaltma Katsayıları\n", BoldSatirFont));
            txt.Add(new iText.Chunk("f", NormalSymbolFont));
            txt.Add(new iText.Chunk("a", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(string.Format(" = {0:0.00}, ", f.PhiA), NormalSatirFont));
            txt.Add(new iText.Chunk("f", NormalSymbolFont));
            txt.Add(new iText.Chunk("b", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(string.Format(" = {0:0.00}, ", f.PhiB), NormalSatirFont));
            txt.Add(new iText.Chunk("f", NormalSymbolFont));
            txt.Add(new iText.Chunk("c", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(string.Format(" = {0:0.00}", f.PhiC), NormalSatirFont));
            //txt.Add(new iText.Chunk("\n\nTasarım:\n", BoldSatirFont));
            //txt.Add(new iText.Chunk(f.Code.ToString(), NormalSatirFont));
            ctDonati.SetSimpleColumn(txt, xUL + kstW, yUL - headH - graphH - kstH, xUL + 2 * kstW, yUL - headH - graphH, 15, iText.Element.ALIGN_LEFT);
            ctDonati.Go();

            ColumnText ctTesir = new ColumnText(cb);

            ctTesir.Indent = indent;
            txt            = new iText.Phrase();
            txt.Add(new iText.Chunk("Maksimum eksenel basınç, N", NormalSatirFont));
            txt.Add(new iText.Chunk("max", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(string.Format(" = {0:0.00} t\n", f.Pmax), NormalSatirFont));
            txt.Add(new iText.Chunk("Maksimum eksenel çekme, N", NormalSatirFont));
            txt.Add(new iText.Chunk("min", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(string.Format(" = {0:0.00} t\n\n", f.Pmin), NormalSatirFont));

            txt.Add(new iText.Chunk("Yönetmelik maksimum eksenel basınç sınırı, N", NormalSatirFont));
            txt.Add(new iText.Chunk("max", NormalRiseFont).SetTextRise(-1.0f));
            txt.Add(new iText.Chunk(string.Format(" = {0:0.00} t", f.ActualPmax), NormalSatirFont));
            ctTesir.SetSimpleColumn(txt, xUL, yUL - headH - graphH - 1.5f * kstH, xUL + kstW, yUL - headH - graphH - kstH, 15, iText.Element.ALIGN_LEFT);
            ctTesir.Go();

            doc.Close();
        }
        public void Go()
        {
            // GetClassOutputPath() implementation left out for brevity
            var outputFile = Helpers.IO.GetClassOutputPath(this);

            using (FileStream stream = new FileStream(
                outputFile, 
                FileMode.Create, 
                FileAccess.Write))
            {
                string chunkText = "FirstName LastName (2016-01-13 11:13)";
                Random random = new Random();
                var font = new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD); 
                using (Document document = new Document())
                {
                    PdfWriter.GetInstance(document, stream);
                    document.Open();
                    Phrase phrase = new Phrase();
                    for (var i = 0; i < 1000; ++i)
                    {
                        var asterisk = new String('*', random.Next(1, 20));
                        Chunk chunk = new Chunk(
                            string.Format("[{0}] {1}", asterisk, chunkText), 
                            font
                        );
                        chunk.SetSplitCharacter(new CustomSplitCharacter());
                        phrase.Add(chunk);
                    }
 
                    document.Add(phrase);
                }
            }
        }