Contains all the specifications of a font: fontfamily, size, style and color.
Inheritance: IComparable
Exemplo n.º 1
1
        public void Build()
        {
            if (artUrls != null)
            {
                Build2();
                return;
            }
            Document document = new Document();
            PdfWriter.GetInstance(document, new FileStream(baseDir + _fileName, FileMode.Create));
            document.Open();
            document.AddTitle(_title);

            Font ft = new Font(baseFT, 12);

            int cnt = items.Count;

            for (int i = cnt - 1; i >= 0; i--)
            {
                var entity = items[i];
                if (!entity.IsDown)
                {
                    continue;
                }
                _callback("获取文章 " + (cnt - i) + "/" + cnt + ":" + entity.Title);

                document.Add(GetChapter(entity));
            }
            document.Close();
        }
Exemplo n.º 2
1
        private static void GenerateRow(PdfPTable table, PlayerInfo player, Font font, BaseColor backgroundColor)
        {
            var jpg = Image.GetInstance(player.PictureUrl);
            table.AddCell(jpg);

            PdfPCell cell;

            cell = new PdfPCell(new Phrase(player.JerseyNumber, font)) {BackgroundColor = backgroundColor};
            table.AddCell(cell);

            cell = new PdfPCell(new Phrase(player.Name, font)) {BackgroundColor = backgroundColor};
            table.AddCell(cell);

            if (table.NumberOfColumns == NumberColsWithPosition)
            {
                cell = new PdfPCell(new Phrase(player.Position, font)) {BackgroundColor = backgroundColor};
                table.AddCell(cell);
            }

            cell = new PdfPCell(new Phrase(player.Height, font)) {BackgroundColor = backgroundColor};
            table.AddCell(cell);

            cell = new PdfPCell(new Phrase(player.Weight, font)) {BackgroundColor = backgroundColor};
            table.AddCell(cell);

            cell = new PdfPCell(new Phrase(player.DateOfBirth, font)) {BackgroundColor = backgroundColor};
            table.AddCell(cell);

            cell = new PdfPCell(new Phrase(player.Age, font)) {BackgroundColor = backgroundColor};
            table.AddCell(cell);

            cell = new PdfPCell(new Phrase(player.BirthPlace, font)) {BackgroundColor = backgroundColor};
            table.AddCell(cell);
        }
Exemplo n.º 3
1
        public void Write(string outputPath, FlowDocument doc)
        {
            Document pdfDoc = new Document(PageSize.A4, 50, 50, 50, 50);
            Font textFont = new Font(baseFont, DEFAULT_FONTSIZE, Font.NORMAL, BaseColor.BLACK);
            Font headingFont = new Font(baseFont, DEFAULT_HEADINGSIZE, Font.BOLD, BaseColor.BLACK);
            using (FileStream stream = new FileStream(outputPath, FileMode.Create))
            {
                PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream);
                pdfDoc.Open();
                foreach (Block i in doc.Blocks) {
                    if (i is System.Windows.Documents.Paragraph)
                    {
                        TextRange range = new TextRange(i.ContentStart, i.ContentEnd);
                        Console.WriteLine(i.Tag);
                        switch (i.Tag as string)
                        {
                            case "Paragraph": iTextSharp.text.Paragraph par = new iTextSharp.text.Paragraph(range.Text, textFont);
                                par.Alignment = Element.ALIGN_JUSTIFIED;
                                              pdfDoc.Add(par);
                                              break;
                            case "Heading": iTextSharp.text.Paragraph head = new iTextSharp.text.Paragraph(range.Text, headingFont);
                                              head.Alignment = Element.ALIGN_CENTER;
                                              head.SpacingAfter = 10;
                                              pdfDoc.Add(head);
                                              break;
                            default:          iTextSharp.text.Paragraph def = new iTextSharp.text.Paragraph(range.Text, textFont);
                                              def.Alignment = Element.ALIGN_JUSTIFIED;
                                              pdfDoc.Add(def);
                                              break;

                        }
                    }
                    else if (i is System.Windows.Documents.List)
                    {
                        iTextSharp.text.List list = new iTextSharp.text.List(iTextSharp.text.List.UNORDERED, 10f);
                        list.SetListSymbol("\u2022");
                        list.IndentationLeft = 15f;
                        foreach (var li in (i as System.Windows.Documents.List).ListItems)
                        {
                            iTextSharp.text.ListItem listitem = new iTextSharp.text.ListItem();
                            TextRange range = new TextRange(li.Blocks.ElementAt(0).ContentStart, li.Blocks.ElementAt(0).ContentEnd);
                            string text = range.Text.Substring(1);
                            iTextSharp.text.Paragraph par = new iTextSharp.text.Paragraph(text, textFont);
                            listitem.SpacingAfter = 10;
                            listitem.Add(par);
                            list.Add(listitem);
                        }
                        pdfDoc.Add(list);
                    }

               }
                if (pdfDoc.PageNumber == 0)
                {
                    iTextSharp.text.Paragraph par = new iTextSharp.text.Paragraph(" ");
                    par.Alignment = Element.ALIGN_JUSTIFIED;
                    pdfDoc.Add(par);
                }
               pdfDoc.Close();
            }
        }
 // 函数描述:设置字体的样式
 public static Font BaseFontAndSize(string fontName, int size, int style, BaseColor baseColor)
 {
     BaseFont.AddToResourceSearch("iTextAsian.dll");
     BaseFont.AddToResourceSearch("iTextAsianCmaps.dll");
     string fileName;
     switch (fontName)
     {
         case "黑体":
             fileName = "SIMHEI.TTF";
             break;
         case "华文中宋":
             fileName = "STZHONGS.TTF";
             break;
         case "宋体":
             fileName = "simsun_1.ttf";
             break;
         default:
             fileName = "simsun_1.ttf";
             break;
     }
     var baseFont = BaseFont.CreateFont(@"c:/windows/fonts/" + fileName, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
     var fontStyle = style < -1 ? Font.NORMAL : style;
     var font = new Font(baseFont, size, fontStyle, baseColor);
     return font;
 }
 /// <summary>
 /// Sets registered font's name.
 /// </summary>
 /// <param name="mainFont">main font</param>
 /// <param name="defaultFont">default font</param>
 public GenericFontProvider(Font mainFont, Font defaultFont)
 {
     _mainFont = mainFont;
     _defaultFont = defaultFont;
     setDefaults(_mainFont);
     registerFonts(_mainFont.Familyname, _defaultFont.Familyname);
 }
Exemplo n.º 6
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
        BaseFont bf;
        Font font;
        String[] names = BaseFont.EnumerateTTCNames(FONT);
        for (int i = 0; i < names.Length; i++) {
          bf = BaseFont.CreateFont(
            String.Format("{0}, {1}", FONT, i),
            BaseFont.IDENTITY_H, BaseFont.EMBEDDED
          );
          font = new Font(bf, 12);
          document.Add(new Paragraph("font " + i + ": " + names[i], font));
          document.Add(new Paragraph("Rash\u00f4mon", font));
          document.Add(new Paragraph("Directed by Akira Kurosawa", font));
          document.Add(new Paragraph("\u7f85\u751f\u9580", font));
          document.Add(Chunk.NEWLINE);
        }
      }
    }
Exemplo n.º 7
0
        public int Convert(string sourcePath, string targetPath)
        {
            if (!File.Exists(sourcePath))
            {
                return ErrorMessages.FileNotExist;
            }

            try
            {
                var content = File.ReadAllText(sourcePath, System.Text.Encoding.Default);
                var content2 = File.ReadAllText(sourcePath, System.Text.Encoding.UTF8);
                Document document = new Document();
                BaseFont bf = BaseFont.CreateFont("c:\\windows\\fonts\\SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

                Font font = new Font(bf);

                PdfWriter.GetInstance(document, new FileStream(targetPath, FileMode.Create));
                document.Open();

                document.Add(new Paragraph(content, font));
                document.Close();
                return ErrorMessages.ConvertSuccess;
            }
            catch(Exception ex)
            {
                _logger.Error(ex.StackTrace);
                _logger.Error(ex.Message);
            }

            return ErrorMessages.ConvertFailed;
        }
Exemplo n.º 8
0
        protected void initFile(bool bBlackAndWhite = false)
        {
            m_doc = new Document();
            string folder = Settings.Default["pdffolder"].ToString() + m_strFolder;
            System.IO.Directory.CreateDirectory(folder );
            string fileName = folder + "/"+m_strTitle;
            if (bBlackAndWhite)
                fileName += "BW.pdf";
            else
                fileName += ".pdf";

            m_writer = PdfWriter.GetInstance(m_doc, new System.IO.FileStream(fileName, System.IO.FileMode.Create));
            m_doc.Open();
            m_fSmall = new iTextSharp.text.Font();
            m_fSmall.Size = 10;

            m_fBig = new iTextSharp.text.Font();
            m_fBig.Size = 40;
            m_fBig.Color = bBlackAndWhite ? BaseColor.BLACK : getNextColor();
            //            m_fBig.SetStyle("bold");

            m_fNorm = new iTextSharp.text.Font();
            m_fNorm.Size = 20;
            m_fNorm.Color = new BaseColor(m_colorText);

            m_doc.Add(new Paragraph("Name:____________________________________________  Date:______________"/*, fSmall*/));
            m_doc.Add(new Paragraph(m_strTitle, m_fBig));
            m_doc.Add(new Paragraph("   "));
        }
Exemplo n.º 9
0
        private void button1_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.Filter = "*.pdf|*.PDF";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                var doc = new Document();
                BaseFont baseFont = BaseFont.CreateFont(@"TIMES.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

                iTextSharp.text.Font zag = new iTextSharp.text.Font(baseFont, 16, iTextSharp.text.Font.BOLD);
                iTextSharp.text.Font curs = new iTextSharp.text.Font(baseFont, 14, iTextSharp.text.Font.ITALIC);
                iTextSharp.text.Font other_text = new iTextSharp.text.Font(baseFont, 12, iTextSharp.text.Font.BOLD);
                iTextSharp.text.Font othtext = new iTextSharp.text.Font(baseFont, 12, iTextSharp.text.Font.NORMAL);
                PdfWriter.GetInstance(doc, new FileStream(@saveFileDialog1.FileName, FileMode.Create));
                doc.Open();

                Paragraph par = new Paragraph("Акт закупок", zag);
                par.Alignment = Element.ALIGN_CENTER;
                Paragraph variant = new Paragraph("Аптека № 10", curs);
                variant.Alignment = Element.ALIGN_RIGHT;
                Paragraph otstup = new Paragraph("\r\n");
                doc.Add(par);

                doc.Add(otstup);
                PdfPTable table = new PdfPTable(5);

                PdfPCell cell1 = new PdfPCell(new Phrase("№", other_text));
                PdfPCell cell2 = new PdfPCell(new Phrase("Препарат", other_text));
                PdfPCell cell3 = new PdfPCell(new Phrase("Поставщик", other_text));
                PdfPCell cell4 = new PdfPCell(new Phrase("Количество", other_text));
                PdfPCell cell5 = new PdfPCell(new Phrase("Сумма", other_text));

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

                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    for (int j = 0; j < dataGridView1.Rows[i].Cells.Count; j++)
                    {
                        if (dataGridView1.Rows[i].Cells[j].Value != null)
                        {
                            string tempS = dataGridView1.Rows[i].Cells[j].Value.ToString();

                            cell1 = new PdfPCell(new Phrase(tempS, othtext));
                            table.AddCell(cell1);
                        }
                    }
                }

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

                MessageBox.Show("ok");

            }
        }
Exemplo n.º 10
0
 static PdfArchiver()
 {
     BaseFont.AddToResourceSearch("iTextAsian.dll");
     _font = new Font(
        BaseFont.CreateFont("HeiseiKakuGo-W5", "UniJIS-UCS2-H", BaseFont.NOT_EMBEDDED)
        , 16);
 }
Exemplo n.º 11
0
 static MovieHistory()
 {
     FONT[0] = new Font(Font.FontFamily.HELVETICA, 24);
     FONT[1] = new Font(Font.FontFamily.HELVETICA, 18);
     FONT[2] = new Font(Font.FontFamily.HELVETICA, 14);
     FONT[3] = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
 }
Exemplo n.º 12
0
        private static IT.Font GetFormattedFont(Font font)
        {
            IT.Font iTextFont = new IT.Font();

            //Return default font if font style is not available.
            if (font == null)
            {
                return new IT.Font();
            }

            foreach (var format in font.Formats)
            {
                switch (format)
                {
                    case FontFormats.Bold:
                        iTextFont.SetStyle(IT.Font.BOLD);
                        break;
                    case FontFormats.Italic:
                        iTextFont.SetStyle(IT.Font.ITALIC);
                        break;
                    case FontFormats.Underlined:
                        iTextFont.SetStyle(IT.Font.UNDERLINE);
                        break;
                    default:
                        break;
                }
            }
            return iTextFont;
        }
Exemplo n.º 13
0
        public int Convert(string from, string to)
        {
            _logger.DebugFormat("Text转换为Pdf, {0},到:{1}", from, to);

            try
            {
                var content = File.ReadAllText(@from, Encoding.Default);

                Document document = new Document();
                BaseFont bf = BaseFont.CreateFont("c:\\windows\\fonts\\SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

                Font font = new Font(bf);

                PdfWriter.GetInstance(document, new FileStream(@to, FileMode.Create));
                document.Open();

                document.Add(new Paragraph(content, font));
                document.Close();

                return ErrorMessages.Success;
            }
            catch(Exception ex)
            {
                throw new ConverterException(ErrorMessages.TextToPdfFailed, ex);
            }
        }
Exemplo n.º 14
0
        public void ApplyForText(PdfContentByte cb, IDictionary<String, String> css, Chunk chunk)
        {
            SetStrokeAndFillColor(cb, css);
            SetStrokeAndFill(cb, css);

            try
            {
                Font font = new Font(Font.FontFamily.COURIER, 6, Font.NORMAL, BaseColor.BLACK);

                Font font2 = chunk.Font;

                BaseFont bf2 = font2.BaseFont;
                //BaseFont bf = ;

                if (bf2 == null)
                {
                    cb.SetFontAndSize(font.GetCalculatedBaseFont(false), font2.Size);
                }
                else
                {
                    cb.SetFontAndSize(bf2, font2.Size);
                }
            } catch { }

        }
Exemplo n.º 15
0
        public void TestNotoFont()
        {
            Document document = new Document();

            PdfAWriter writer = PdfAWriter.GetInstance(document, new MemoryStream(), PdfAConformanceLevel.PDF_A_1B);
            writer.CreateXmpMetadata();

            document.Open();
            FileStream iccProfileFileStream = File.Open(RESOURCES + "sRGB Color Space Profile.icm", FileMode.Open, FileAccess.Read, FileShare.Read);
            ICC_Profile icc = ICC_Profile.GetInstance(iccProfileFileStream);
            iccProfileFileStream.Close();
            writer.SetOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);

            String fontPath = RESOURCES + "NotoSansCJKjp-Bold.otf";
            BaseFont bf = BaseFont.CreateFont(fontPath, "Identity-H", true);
            Font font = new Font(bf, 14);
            String[] lines = new String[] {"Noto test", "in japanese:", "\u713C"};

            foreach (String line in lines)
            {
                document.Add(new Paragraph(line, font));
            }

            document.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))
            {
                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);
                }
            }
        }
Exemplo n.º 17
0
 private void button2_Click(object sender, EventArgs e)
 {
     BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
     iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 12, iTextSharp.text.Font.ITALIC, BaseColor.DARK_GRAY);
     Document doc = new Document(iTextSharp.text.PageSize.LETTER,10,10,42,42);
     PdfWriter pdw = PdfWriter.GetInstance(doc, new FileStream(naziv + ".pdf", FileMode.Create));
     doc.Open();
     Paragraph p = new Paragraph("Word Count for : "+naziv,times);
     doc.Add(p);
     p.Alignment = 1;
     PdfPTable pdt = new PdfPTable(2);
     pdt.HorizontalAlignment = 1;
     pdt.SpacingBefore = 20f;
     pdt.SpacingAfter = 20f;
     pdt.AddCell("Word");
     pdt.AddCell("No of repetitions");
     foreach (Rijec r in lista_rijeci)
     {
         pdt.AddCell(r.Tekst);
         pdt.AddCell(Convert.ToString(r.Ponavljanje));
     }
     using (MemoryStream stream = new MemoryStream())
     {
         chart1.SaveImage(stream, ChartImageFormat.Png);
         iTextSharp.text.Image chartImage = iTextSharp.text.Image.GetInstance(stream.GetBuffer());
         chartImage.ScalePercent(75f);
         chartImage.Alignment = 1;
         doc.Add(chartImage);
     }
     doc.Add(pdt);
     doc.Close();
     MessageBox.Show("PDF created!");
 }
Exemplo n.º 18
0
 public bool CreatePDF(int fontSize)
 {
     Console.WriteLine(Helpers.IO.GetClassOutputPath(this));
     var font = new Font(Font.NORMAL, fontSize, 1, new BaseColor(0, 0, 0));
     var onePageDoc = new OnePageDocument();
     // GetClassOutputPath() implementation left out for brevity
     var outputFile = Helpers.IO.GetClassOutputPath(this);
     using (FileStream stream = new FileStream(
         outputFile, 
         FileMode.Create, 
         FileAccess.Write))
     {
         using (Document document = new Document())
         {
             var writer = PdfWriter.GetInstance(document, stream);
             writer.PageEvent = onePageDoc;
             document.Open();
             for (int i = 0; i < 4; ++i)
             {
                 document.Add(new Paragraph(TEST_STRING, font));
             }
         }
     }
     return onePageDoc.TotalPages > 1 ? true : false;
 } 
Exemplo n.º 19
0
		/// <summary>
		/// Gets the font object.
		/// </summary>
		/// <param name="textProperties">The text properties.</param>
		/// <returns>The font object</returns>
		public static Font GetFont(TextProperties textProperties)
		{
			try
			{
				Font font = new Font();
				if (textProperties != null)
				{
					string fontName = "";
					if (textProperties.FontName != null)
						fontName = textProperties.FontName;
					else
					{
						fontName = DefaultDocumentStyles.Instance().DefaultTextFont.Familyname;
					}

					if (FontFactory.Contains(fontName))
					{
						string colorStr = "#000000";
						int iTextFontStyle = 0; //normal
						int bold = (textProperties.Bold != null && textProperties.Bold.ToLower() == "bold") ? 1 : 0;
						int italic = (textProperties.Italic != null && textProperties.Italic.ToLower() == "italic") ? 1 : 0;
						int textLineThrough = (textProperties.TextLineThrough != null) ? 1 : 0;
						int underline = (textProperties.Underline != null) ? 1 : 0;
						float size = 12.0f; // up to now, standard todo: do it better
						if (textProperties.FontSize != null)
						{
							if (textProperties.FontSize.ToLower().EndsWith("pt"))
							{
								try
								{
									size = (float) Convert.ToDouble(textProperties.FontSize.ToLower().Replace("pt",""));
								}
								catch(Exception)
								{
									throw;
								}
							}
						}
						if (textProperties.FontColor != null)
						{
							colorStr = textProperties.FontColor;
						}
						if (bold == 1 && italic == 1)
							iTextFontStyle = Font.BOLDITALIC;
						if (bold == 1 && italic == 0)
							iTextFontStyle = Font.BOLD;
						if (bold == 0 && italic == 1)
							iTextFontStyle = Font.ITALIC;
						// TODO: underline strike through
						iTextSharp.text.Color color = RGBColorConverter.GetColorFromHex(colorStr);
						font = FontFactory.GetFont(fontName, size, iTextFontStyle, color);
					}
				}
				return font;
			}
			catch(Exception)
			{
				throw;
			}
		}
Exemplo n.º 20
0
        //重写 关闭一个页面时
        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);
            }
        }
Exemplo n.º 21
0
 NamedFont(string name, Font font)
 {
     if (name =="" || font == null)
         throw new InvalidParameterException();
     Font = font;
     _name = name;
 }
Exemplo n.º 22
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
        BaseFont bf;
        Font font;
        Image img = Image.GetInstance(POSTER);
        img.ScalePercent(50);
        img.BorderWidth = 18f;
        img.Border = Image.BOX;
        img.BorderColor = GrayColor.GRAYWHITE;
        img.Alignment = Element.ALIGN_LEFT | Image.TEXTWRAP;
        document.Add(img);
        document.Add(new Paragraph(
          "Movie title: Tears of the Black Tiger (Thailand)"
        ));
        document.Add(new Paragraph("directed by Wisit Sasanatieng"));
        for (int i = 0; i < 2; i++) {
          bf = BaseFont.CreateFont(
            FONTS[i], BaseFont.IDENTITY_H, BaseFont.EMBEDDED
          );
          document.Add(new Paragraph("Font: " + bf.PostscriptFontName));
          font = new Font(bf, 20);
          document.Add(new Paragraph(MOVIE, font));
        }
      }
    }
Exemplo n.º 23
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();
        }
Exemplo n.º 24
0
        public static void Export(DetailsView dvGetStudent, string imageFilePath, string filename)
        {
            int rows = dvGetStudent.Rows.Count;
            int columns = dvGetStudent.Rows[0].Cells.Count;
            int pdfTableRows = rows - 1;
            iTextSharp.text.Table PdfTable = new iTextSharp.text.Table(2, pdfTableRows);
            //PdfTable.BorderWidth = 1;
            PdfTable.Cellpadding = 0;
            PdfTable.Cellspacing = 0;
            iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);
            jpg.Alignment = Element.ALIGN_CENTER;
            jpg.ScaleToFit(150f, 150f);
            string fontUrl = System.AppDomain.CurrentDomain.BaseDirectory + "Files\\arial.ttf";
            BaseFont STF_Helvetica_Russian = BaseFont.CreateFont(fontUrl, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            Font font = new Font(STF_Helvetica_Russian, Font.DEFAULTSIZE, Font.NORMAL);
            for (int rowCounter = 1; rowCounter < rows; rowCounter++)
            {
                for (int columnCounter = 0; columnCounter < columns; columnCounter++)
                {
                    string strValue = dvGetStudent.Rows[rowCounter].Cells[columnCounter].Text;

                    PdfTable.AddCell(new Paragraph(strValue, font));
                }
            }
            Document Doc = new Document();

            PdfWriter.GetInstance(Doc, HttpContext.Current.Response.OutputStream);
            Doc.Open();
            Doc.Add(jpg);
            Doc.Add(PdfTable);
            Doc.Close();
            HttpContext.Current.Response.ContentType = "application/pdf";
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + filename + ".pdf");
            HttpContext.Current.Response.End();
        }
Exemplo n.º 25
0
        protected override void PopulateDocument()
        {
            var bfCourier = BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, false);
            var courier = new Font(bfCourier, 12, Font.ITALIC, BaseColor.RED);

            Document.Add(new Paragraph(string.Format("It did. {0}", DateTime.Now), courier));
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            filePdf = Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.InternetCache), "PDF_Temp.pdf");

            var document = new Document(PageSize.LETTER);

            // Create a new PdfWriter object, specifying the output stream
            var output = new FileStream(filePdf, FileMode.Create);
            var writer = PdfWriter.GetInstance(document, output);

            // Open the Document for writing
            document.Open();

            BaseFont bf = BaseFont.CreateFont (BaseFont.HELVETICA, BaseFont.CP1252, false);
            iTextSharp.text.Font font = new iTextSharp.text.Font (bf, 16, iTextSharp.text.Font.BOLD);
            var p = new Paragraph ("Sample text", font);

            document.Add (p);
            document.Close ();
            writer.Close ();

            //Close the Document - this saves the document contents to the output stream
            document.Close();
            writer.Close ();
        }
Exemplo n.º 27
0
// ===========================================================================
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter.GetInstance(document, stream).InitialLeading = 16;
        // step 3
        document.Open();
        // add the ID in another font
        Font font = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaseColor.WHITE);
        // step 4
        using (var c =  AdoDB.Provider.CreateConnection()) {
          c.ConnectionString = AdoDB.CS;
          using (DbCommand cmd = c.CreateCommand()) {
            cmd.CommandText = 
              "SELECT country,id FROM film_country ORDER BY country";
            c.Open();
            using (var r = cmd.ExecuteReader()) {
              while (r.Read()) {
                var country = r.GetString(0);
                var ID = r.GetString(1);
                document.Add(new Chunk(country));
                document.Add(new Chunk(" "));
                Chunk id = new Chunk(ID, font);
                // with a background color
                id.SetBackground(BaseColor.BLACK, 1f, 0.5f, 1f, 1.5f);
                // and a text rise
                id.SetTextRise(6);
                document.Add(id);
                document.Add(Chunk.NEWLINE);
              }
            }
          }
        }
      }
    }
Exemplo n.º 28
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
         BaseFont bf;
         Font font;
         for (int i = 0; i < 3; i++)
         {
             bf = BaseFont.CreateFont(
               MOVIES[i][0], MOVIES[i][1], BaseFont.NOT_EMBEDDED
             );
             font = new Font(bf, 12);
             document.Add(new Paragraph(bf.PostscriptFontName, font));
             for (int j = 2; j < 5; j++)
             {
                 document.Add(new Paragraph(MOVIES[i][j], font));
             }
             document.Add(Chunk.NEWLINE);
         }
     }
 }
Exemplo n.º 29
0
 /// <summary>
 /// Constructs a Paragraph with a certain leading, string
 /// and Font.
 /// </summary>
 /// <param name="leading">the leading</param>
 /// <param name="str">a string</param>
 /// <param name="font">a Font</param>
 public Paragraph(float leading, string str, Font font) : base(leading, str, font)
 {
 }
Exemplo n.º 30
0
 /// <summary>
 /// Constructs a Paragraph with a certain string
 /// and a certain Font.
 /// </summary>
 /// <param name="str">a string</param>
 /// <param name="font">a Font</param>
 public Paragraph(string str, Font font) : base(str, font)
 {
 }
Exemplo n.º 31
0
        public void fnConstruirCuerpoArchivo()
        {
            iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
            doc.Open();
            Paragraph titulo = new Paragraph("CUESTIONARIO DE DETECCION DE SIGNOS Y SÍNTOMAS");

            titulo.Alignment = Element.ALIGN_CENTER;
            doc.Add(titulo);
            doc.Add(Chunk.NEWLINE);
            doc.Add(Chunk.NEWLINE);
            doc.Add(new Paragraph("Fecha de aplicación: " + this.fecha_aplicacion));
            doc.Add(Chunk.NEWLINE);
            doc.Add(new Paragraph("Nombre del entrevistado: " + this.nombre_completo));
            doc.Add(Chunk.NEWLINE);
            doc.Add(new Paragraph("Nombre de la persona que realizo el filtro: " + fnNombreEntrevistador(this.numero_entrevistador)));
            doc.Add(Chunk.NEWLINE);
            doc.Add(new Paragraph("En los ultimos 7 días, ha tenido alguno de los siguientes síntomas:"));
            doc.Add(Chunk.NEWLINE);

            PdfPTable table_sintomas = new PdfPTable(3);

            table_sintomas.AddCell("SÍNTOMA");
            table_sintomas.AddCell("SI");
            table_sintomas.AddCell("NO");
            //Fiebre
            table_sintomas.AddCell("FIEBRE");
            table_sintomas.AddCell((this.fiebre == 1) ? "X" : " ");
            table_sintomas.AddCell((this.fiebre == 0) ? "X" : " ");
            //Tos, Estornudos
            table_sintomas.AddCell("TOS, ESTORNUDOS");
            table_sintomas.AddCell((this.tos == 1) ? "X" : " ");
            table_sintomas.AddCell((this.tos == 0) ? "X" : " ");
            //Malestar General
            table_sintomas.AddCell("MALESTAR GENERAL");
            table_sintomas.AddCell((this.malestar == 1) ? "X" : " ");
            table_sintomas.AddCell((this.malestar == 0) ? "X" : " ");
            //Dolor de cabeza
            table_sintomas.AddCell("DOLOR DE CABEZA");
            table_sintomas.AddCell((this.dolor == 1) ? "X" : " ");
            table_sintomas.AddCell((this.dolor == 0) ? "X" : " ");
            //Dificultad para respirar
            table_sintomas.AddCell("DIFICULTAD PARA RESPIRAR");
            table_sintomas.AddCell((this.dificultad == 1) ? "X" : " ");
            table_sintomas.AddCell((this.dificultad == 0) ? "X" : " ");
            doc.Add(table_sintomas);
            doc.Add(Chunk.NEWLINE);

            Paragraph corte_aqui = new Paragraph(new Paragraph("--------------------------------------------------CORTE AQUI--------------------------------------------------"));

            corte_aqui.Alignment = Element.ALIGN_CENTER;
            doc.Add(corte_aqui);
            doc.Add(Chunk.NEWLINE);
            doc.Add(new Paragraph("Fecha de aplicación: " + this.fecha_aplicacion));
            doc.Add(Chunk.NEWLINE);
            doc.Add(new Paragraph("Nombre del entrevistado: " + this.nombre_completo));
            doc.Add(Chunk.NEWLINE);
            doc.Add(new Paragraph("SI PRESENTA FIEBRE, ASOCIADO CON EL RESTO DE LOS SÍNTOMAS, ACUDA A LA" +
                                  "UNIDAD DE SALUD MAS CERCANA A SU DOMICILIO Y SIGA LAS INDICACIONES DEL " +
                                  "PERSONAL MEDICO."));
            doc.Add(Chunk.NEWLINE);
            doc.Add(new Paragraph("SE RECOMIENDA PERMANECER EN CASA PARA EVITAR CONTAGIAR A OTRAS " +
                                  "PERSONAS Y TENER UNA PRONTA RECUPERACIÓN."));
            doc.Add(Chunk.NEWLINE);
            doc.Add(new Paragraph("CONSERVE ESTE TALÓN QUE COMPRUEBA TU ASISTENCIA."));
            doc.Add(Chunk.NEWLINE);

            doc.Close();
            //writer.Close();
        }
Exemplo n.º 32
0
        private void Generar_PDF()
        {
            try
            {
                SaveFileDialog Sfd_Ruta_Archivo = new SaveFileDialog();
                Sfd_Ruta_Archivo.Filter           = "PDF(*.pdf)|*.pdf";
                Sfd_Ruta_Archivo.FilterIndex      = 0;
                Sfd_Ruta_Archivo.RestoreDirectory = true;

                // Validación a la Ruta del Archivo.
                if (Sfd_Ruta_Archivo.ShowDialog() == DialogResult.OK)
                {
                    using (FileStream fs = new FileStream(Sfd_Ruta_Archivo.FileName, FileMode.Create))
                    {
                        DataTable Res = Grd_Resultado.DataSource as DataTable; // Se utilizan los datos del DataTable.
                        Document  doc = new Document(PageSize.LETTER);
                        PdfWriter.GetInstance(doc, fs);
                        doc.Open();

                        PdfPTable table  = new PdfPTable(Res.Columns.Count);
                        float     factor = 250 / 50;
                        float[]   widths = new float[Res.Columns.Count];

                        float max = (from A in Res.AsEnumerable()
                                     select A.Field <string>(0).Length).Max();

                        widths[0] = max * factor;
                        for (int i = 1; i < widths.Length; i++)
                        {
                            widths[i] = 55.0f;
                        }
                        table.SetWidths(widths);

                        // Options: Element.ALIGN_LEFT (or 0), Element.ALIGN_CENTER (1), Element.ALIGN_RIGHT (2).
                        table.HorizontalAlignment = Element.ALIGN_CENTER;

                        // Fuente para el Encabezado.
                        iTextSharp.text.Font fnt_Encabezados = new iTextSharp.text.Font(FontFactory.GetFont("Arial", 5,
                                                                                                            iTextSharp.text.Font.BOLD));

                        // Fuente para el Contenido.
                        iTextSharp.text.Font fnt = new iTextSharp.text.Font(FontFactory.GetFont("Arial", 5,
                                                                                                iTextSharp.text.Font.NORMAL));

                        // Se imprimen los Encabezados.
                        foreach (DataColumn Column in Res.Columns)
                        {
                            PdfPCell cell = new PdfPCell(new Phrase(Column.ColumnName,
                                                                    fnt_Encabezados));

                            if (Column.Ordinal != 0)
                            {
                                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                            }

                            table.AddCell(cell);
                        }

                        table.HeaderRows = 1;

                        // Se generan los resultados.
                        foreach (DataRow Row in Res.Rows)
                        {
                            foreach (DataColumn Column in Res.Columns)
                            {
                                PdfPCell cell = new PdfPCell(new Phrase(Row[Column].ToString(),
                                                                        fnt));

                                if (Column.Ordinal != 0)
                                {
                                    cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                                }

                                table.AddCell(cell);
                            }
                        }

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

                    MessageBox.Show("Archivo Guardado Correctamente", "Éxito",
                                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Exemplo n.º 33
0
        private void Imprimir_Reporte_Click(object sender, EventArgs e)
        {
            Paragraph paragraph      = new Paragraph(); //se crea el parrafo
            Paragraph paragraphfecha = new Paragraph();

            paragraph.Clear();//limpiar el parrago para agregar mas texto
            iTextSharp.text.Font text = new iTextSharp.text.Font(iTextSharp.text.Font.NORMAL, 11);
            if (Grid_Obras.RowCount == 0)
            {
                MessageBox.Show("No Hay Datos Para Realizar Un Reporte");
            }
            else
            {
                SaveFileDialog save = new SaveFileDialog();
                save.Filter = "PDF Files (*.pdf)|*.pdf|All Files (*.*)|*.*";
                if (save.ShowDialog() == DialogResult.OK)
                {
                    Document   doc      = new Document(PageSize.A2.Rotate(), 1, 1, 1, 1);
                    string     filename = save.FileName;
                    FileStream file     = new FileStream(filename, FileMode.OpenOrCreate);
                    PdfWriter  writer   = PdfWriter.GetInstance(doc, file);
                    writer.ViewerPreferences = PdfWriter.PageModeUseThumbs;
                    writer.ViewerPreferences = PdfWriter.PageLayoutOneColumn;
                    doc.Open();
                    paragraph.Font      = new iTextSharp.text.Font(FontFactory.GetFont("Arial", 22, BaseColor.BLACK));
                    paragraph.Alignment = Element.ALIGN_CENTER;
                    paragraph.Add("REPORTE DE OBRAS"); //agregar texto
                    doc.Add(paragraph);                //lo metes al documento
                    paragraph.Clear();
                    doc.Add(Chunk.NEWLINE);
                    paragraphfecha.Alignment = Element.ALIGN_RIGHT;
                    paragraphfecha.Add(DateTime.Now.ToString("dd/MM/yyyy"));
                    doc.Add(paragraphfecha);//lo metes al documento
                    paragraphfecha.Clear();
                    doc.Add(Chunk.NEWLINE);
                    PdfPTable pdftable = new PdfPTable(Grid_Obras.ColumnCount - 0);

                    for (int j = 0; j < Grid_Obras.Columns.Count - 0; j++)
                    {
                        PdfPCell cell = new PdfPCell(new Phrase(Grid_Obras.Columns[j].HeaderText, text));
                        cell.BackgroundColor = BaseColor.LIGHT_GRAY;
                        pdftable.AddCell(cell);
                    }

                    pdftable.HeaderRows = 0;
                    for (int i = 0; i < Grid_Obras.Rows.Count; i++)

                    {
                        for (int k = 0; k < Grid_Obras.Columns.Count - 0; k++)
                        {
                            if (Grid_Obras[k, i].Value != null)
                            {
                                pdftable.AddCell(new Phrase(Grid_Obras.Rows[i].Cells[k].Value.ToString(), text));
                                //pdftable.AddCell(new Phrase(dgvLoadAll[k, i].Value.ToString(), text));
                            }
                        }
                    }

                    //float[] widths = new float[] { 15f, 50f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f, 40f };

                    // pdftable.SetWidths(widths);
                    doc.Add(pdftable);
                    doc.Close();
                    System.Diagnostics.Process.Start(filename);
                }
            }
        }
        private void BtnExportPdf_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveDialog = new SaveFileDialog();

            saveDialog.Filter   = "PDF File(*.pdf)|*.pdf";
            saveDialog.FileName = "";
            saveDialog.ShowDialog();
            //위에는 저장하는 파트
            if (saveDialog.ShowDialog() == true)
            {
                //pdf변환
                try
                {
                    //0. PDF 사용 폰트 설정.
                    string   nanumPath    = Path.Combine(Environment.CurrentDirectory, @"NanumGothic.ttf");
                    BaseFont nanumBase    = BaseFont.CreateFont(nanumPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                    var      nanumTitle   = new iTextSharp.text.Font(nanumBase, 20f); //20 타이틀용 나눔폰트폰트라는 폴더가 2개가 있으니 명확하게 사용자가 어느 폰트를 사용할 건지 지정해줘야 한다.
                    var      nanumContent = new iTextSharp.text.Font(nanumBase, 12f); // 12내용 나눔폰트,

                    //iTextSharp.text.Font font = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12);
                    string pdfFilePath = saveDialog.FileName;

                    // 1. pdf 객체생성시작
                    Document pdfDoc = new Document(PageSize.A4);

                    // 2. pdf 내용 만들기

                    /* string nanumttf = Path.Combine(Environment.GetEnvironmentVariable("SystemRoot"), @"Fonts\NanumGothic.ttf");
                     * BaseFont nanumBase = BaseFont.CreateFont(nanumttf, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                     * var nanumFont = new iTextSharp.text.Font(nanumBase, 16f);//한글로 안나오는데에 대해서 하는 거임*/
                    Paragraph title    = new Paragraph($"부경대 재고 관리 시스템(SMS)\n", nanumTitle);                                                   //using문 중 모호한 참조가 있다면 지워줘야 한다.
                    Paragraph subtitle = new Paragraph($"사용자리스트 exported : {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}\n\n", nanumContent); //using문 중 모호한 참조가 있다면 지워줘야 한다.
                    PdfPTable pdfTable = new PdfPTable(GrdData.Columns.Count);
                    pdfTable.WidthPercentage = 100;                                                                                            //전체 사이즈 다 쓰는 것이다.
                    // 그리드 헤더 작업
                    var index = 0;
                    foreach (DataGridColumn column in GrdData.Columns)
                    {
                        PdfPCell cell = new PdfPCell(new Phrase(column.Header.ToString(), nanumContent));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        pdfTable.AddCell(cell);
                    }
                    float[] columnWdith = new float[] { 7f, 15f, 10f, 15f, 28f, 10f, 10f };
                    pdfTable.SetWidths(columnWdith);
                    //그리드 Row 작업
                    foreach (var item in GrdData.Items)
                    {
                        if (item is Model.User)
                        {
                            var temp = item as Model.User;
                            //UserId
                            PdfPCell cell = new PdfPCell(new Phrase(temp.UserID.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            pdfTable.AddCell(cell);
                            //UserIdentityNumber
                            cell = new PdfPCell(new Phrase(temp.UserIdentityNumber.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            pdfTable.AddCell(cell);
                            //UserSurName
                            cell = new PdfPCell(new Phrase(temp.UserSurname.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            pdfTable.AddCell(cell);
                            //UserName
                            cell = new PdfPCell(new Phrase(temp.UserName.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            pdfTable.AddCell(cell);
                            //UserEmail
                            cell = new PdfPCell(new Phrase(temp.UserEmail.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            pdfTable.AddCell(cell);
                            //UserAdmin
                            cell = new PdfPCell(new Phrase(temp.UserAdmin.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            pdfTable.AddCell(cell);
                            //UserActivated
                            cell = new PdfPCell(new Phrase(temp.UserActivated.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            pdfTable.AddCell(cell);
                        }
                    }

                    // 3. pdf 파일생성
                    using (FileStream stream = new FileStream(pdfFilePath, FileMode.OpenOrCreate))
                    {
                        PdfWriter.GetInstance(pdfDoc, stream);
                        pdfDoc.Open();
                        // 2번에서 만든 내용을 추가한다.
                        pdfDoc.Add(title);
                        pdfDoc.Add(subtitle);
                        pdfDoc.Add(pdfTable);
                        pdfDoc.Close();
                        stream.Close();//option
                    }
                    Commons.ShowMessageAsync("PDF변환", "PDF 익스포트 성공했습니다.");
                }
                catch (Exception ex)
                {
                    Commons.LOGGER.Error($"예외발생 BtnExportPdf_Click: {ex}");
                }
            }
        }
Exemplo n.º 35
0
        protected void btnExportToPdf_Click(object sender, EventArgs e)
        {
            try
            {
                grdLandRelatedDoc.AllowPaging = false;
                grdLandRelatedDoc.DataBind();

                BaseFont bf = BaseFont.CreateFont(Environment.GetEnvironmentVariable("windir") + @"\fonts\ARIALUNI.TTF", BaseFont.IDENTITY_H, true);

                iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(grdLandRelatedDoc.Columns.Count);
                int[] widths = new int[grdLandRelatedDoc.Columns.Count];
                for (int x = 0; x < grdLandRelatedDoc.Columns.Count; x++)
                {
                    widths[x] = (int)grdLandRelatedDoc.Columns[x].ItemStyle.Width.Value;
                    string cellText = Server.HtmlDecode(grdLandRelatedDoc.HeaderRow.Cells[x].Text);

                    //Set Font and Font Color
                    iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);
                    font.Color = new iTextSharp.text.BaseColor(Color.Black);
                    iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellText, font));

                    //Set Header Row BackGround Color
                    cell.BackgroundColor = new iTextSharp.text.BaseColor(Color.White);


                    table.AddCell(cell);
                }
                table.SetWidths(widths);

                for (int i = 0; i < grdLandRelatedDoc.Rows.Count; i++)
                {
                    if (grdLandRelatedDoc.Rows[i].RowType == DataControlRowType.DataRow)
                    {
                        {
                            for (int j = 0; j < grdLandRelatedDoc.Columns.Count; j++)
                            {
                                string cellText = Server.HtmlDecode(grdLandRelatedDoc.Rows[i].Cells[j].Text);

                                //Set Font and Font Color
                                iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);
                                font.Color = new iTextSharp.text.BaseColor(Color.Black);
                                iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellText, font));

                                //Set Color of row
                                if (i % 2 == 0)
                                {
                                    //Set Row BackGround Color
                                    cell.BackgroundColor = new iTextSharp.text.BaseColor(Color.White);
                                }

                                table.AddCell(cell);
                            }
                        }
                    }
                }

                //Create the PDF Document
                Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
                PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                pdfDoc.Open();
                pdfDoc.Add(table);
                pdfDoc.Close();
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.Write(pdfDoc);
                Response.End();
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemplo n.º 36
0
        public void exportGrid(DataGridView dataGrid, string fileName)
        {
            BaseFont baseFont = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, BaseFont.EMBEDDED);
            //Buradan aşağıda başlık bilgisi ekleniyor rapor'a
            PdfPTable pdfTitle = new PdfPTable(1);

            pdfTitle.DefaultCell.BorderWidth         = 0;
            pdfTitle.WidthPercentage                 = 300;
            pdfTitle.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;

            Chunk chnkTitle = new Chunk("Kullanici Raporu", FontFactory.GetFont("Times New Roman"));

            chnkTitle.Font.Size = 40;
            pdfTitle.AddCell(new Phrase(chnkTitle));

            //Buradan aşağısında tarihi yazdırıyoruz!
            PdfPTable pdfDateTime = new PdfPTable(1);

            pdfDateTime.DefaultCell.BorderWidth         = 0;
            pdfDateTime.WidthPercentage                 = 100;
            pdfDateTime.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;

            string thisDay    = DateTime.Now.ToString("dddd, dd MMMM yyyy");
            Chunk  dateString = new Chunk(thisDay, FontFactory.GetFont("Times New Roman"));

            dateString.Font.Size = 20;
            pdfDateTime.AddCell(new Phrase(dateString));

            //Alt tarafta pdf dosyasına ilgili tabşo yu yazdırıyoruz!
            PdfPTable pdfTable = new PdfPTable(dataGrid.Columns.Count);

            pdfTable.DefaultCell.Padding     = 5;
            pdfTable.WidthPercentage         = 100;
            pdfTable.HorizontalAlignment     = Element.ALIGN_LEFT;
            pdfTable.DefaultCell.BorderWidth = 1;

            iTextSharp.text.Font text = new iTextSharp.text.Font(baseFont, 10, iTextSharp.text.Font.NORMAL);

            //Başlık Ekleme
            foreach (DataGridViewColumn column in dataGrid.Columns)
            {
                PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText, text));
                cell.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240);
                pdfTable.AddCell(cell);
            }

            //Satırları Ekleme
            foreach (DataGridViewRow row in dataGrid.Rows)
            {
                foreach (DataGridViewCell cell in row.Cells)
                {
                    pdfTable.AddCell(new Phrase(cell.Value.ToString(), text));
                }
            }

            var saveFileDialog = new SaveFileDialog();

            saveFileDialog.FileName   = fileName;
            saveFileDialog.DefaultExt = ".pdf";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                using (FileStream stream = new FileStream(saveFileDialog.FileName, FileMode.Create))
                {
                    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
                    PdfWriter.GetInstance(pdfDoc, stream);

                    pdfDoc.Open();
                    pdfDoc.Add(pdfTitle);
                    pdfDoc.Add(pdfDateTime);//Burada pdf dosyasına tarih'i yazdırıyoruz!
                    pdfDoc.Add(pdfTable);
                    pdfDoc.Close();
                    stream.Close();
                }
            }
        }
Exemplo n.º 37
0
 /**
  * Constructs a chunk of text with a char and a certain <CODE>Font</CODE>.
  *
  * @param    c        the content
  * @param    font        the font
  */
 public Chunk(char c, Font font)
 {
     this.content = new StringBuilder();
     this.content.Append(c);
     this.font = font;
 }
Exemplo n.º 38
0
        // constructors

        /// <summary>
        /// Empty constructor.
        /// </summary>
        /// <overloads>
        /// Has six overloads.
        /// </overloads>
        public Chunk()
        {
            this.content = new StringBuilder();
            this.font    = new Font();
        }
Exemplo n.º 39
0
 /// <summary>
 /// Constructs a chunk of text with a certain content and a certain Font.
 /// </summary>
 /// <param name="content">the content</param>
 /// <param name="font">the font</param>
 public Chunk(string content, Font font)
 {
     this.content = new StringBuilder(content);
     this.font    = font;
 }
Exemplo n.º 40
0
        public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)
        {
            base.OnEndPage(writer, document);

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

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

            Phrase p1Header = new Phrase(null, null);

            //removing Header HTML COntent
            if (HeaderText != null)
            {
                FontFactory.RegisterDirectories();
                List <IElement> htmlarraylist = HTMLWorker.ParseToList(new StringReader(HeaderText), null);
                for (int k = 0; k < htmlarraylist.Count; k++)
                {
                    p1Header.Add((IElement)htmlarraylist[k]);
                }
            }

            Phrase p1Footer = new Phrase(null, null);

            //removing Footer HTML COntent
            if (FooterText != null)
            {
                FontFactory.RegisterDirectories();
                List <IElement> htmlarrayFooterlist = HTMLWorker.ParseToList(new StringReader(FooterText), null);
                for (int m = 0; m < htmlarrayFooterlist.Count; m++)
                {
                    p1Footer.Add((IElement)htmlarrayFooterlist[m]);
                }
            }
            //Create PdfTable object
            PdfPTable pdfTab = new PdfPTable(3);

            pdfTab.WidthPercentage = 90;

            float[] tblDescWidth52 = new float[3];
            tblDescWidth52[0] = 25;
            tblDescWidth52[1] = 72;
            tblDescWidth52[2] = 2;

            pdfTab.SetWidths(tblDescWidth52);
            String text = "Page " + writer.PageNumber + " of ";

            //We will have to create separate cells to include image logo and 2 separate strings
            //Row 1
            if (HeaderRequired)
            {
                PdfPCell pdfCell1 = new PdfPCell();
                PdfPCell pdfCell2 = new PdfPCell(p1Header);
                PdfPCell pdfCell3 = new PdfPCell();

                //  iTextSharp.text.Image imgLogo = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath("~/Images/customer Images/ReportLogo/" + LogoPath));

                //  iTextSharp.text.Image imgLogo = iTextSharp.text.Image.GetInstance("F:/MAIN V10/Sharda_Hospital/Sharda_12_08_2016/WinApps/ReportLogo/Win7645logo3.PNG");

                //  imgLogo.ScaleToFit(80, 60);
                //  pdfCell1.AddElement(imgLogo);

                string base64Image = LogoPath;                                                         // new 18-08
                Regex  regex       = new Regex(@"^data:image/(?<mediaType>[^;]+);base64,(?<data>.*)"); // new 18-08
                Match  match       = regex.Match(base64Image);                                         // new 18-08

                Image image = Image.GetInstance(                                                       // new 18-08
                    Convert.FromBase64String(match.Groups["data"].Value)                               // new 18-08
                    );

                image.ScaleToFit(80, 60);   // new 18-08
                pdfCell1.AddElement(image); // new 18-08


                //Row 2
                PdfPCell pdfCell4 = new PdfPCell(new Phrase(null, baseFontNormal));
                //Row 3

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

                pdfCell2.VerticalAlignment = Element.ALIGN_CENTER;
                pdfCell3.VerticalAlignment = Element.ALIGN_MIDDLE;
                pdfCell4.VerticalAlignment = Element.ALIGN_TOP;

                pdfCell4.Colspan = 3;

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

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

                pdfTab.TotalWidth      = document.PageSize.Width - 80f;
                pdfTab.WidthPercentage = 70;

                //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable
                //first param is start row. -1 indicates there is no end row and all the rows to be included to write
                //Third and fourth param is x and y position to start writing
                pdfTab.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 30, writer.DirectContent);

                //Move the pointer and draw line to separate header section from rest of page
                if (BorderRequired)
                {
                    cb.MoveTo(40, document.PageSize.Height - 100);
                    cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 100);
                    cb.Stroke();
                }
            }
            //footer code
            if (FooterRequired)
            {
                //Move the pointer and draw line to separate footer section from rest of page
                if (BorderRequired)
                {
                    cb.MoveTo(40, document.PageSize.GetBottom(50));
                    cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50));
                    cb.Stroke();
                }

                //Add Footer text to footer
                PdfPTable pdfTaba = new PdfPTable(1);



                PdfPCell pdfCellfooter = new PdfPCell(p1Footer);

                pdfCellfooter.HorizontalAlignment = Element.ALIGN_LEFT;
                pdfCellfooter.Border            = 0;
                pdfCellfooter.VerticalAlignment = Element.ALIGN_BOTTOM;
                if (PaperSize == "")
                {
                    pdfTaba.TotalWidth = document.PageSize.Width - 80f;
                }
                else
                {
                    pdfTaba.TotalWidth = document.PageSize.Width;
                }

                pdfTaba.WidthPercentage = 100;

                pdfTaba.AddCell(pdfCellfooter);
                //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
                // pdfTaba.WriteSelectedRows(0, -1, document.PageSize.GetRight(550), document.PageSize.GetBottom(50), writer.DirectContent);
                if (PaperSize == "A4 Size")
                {
                    pdfTaba.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 750, writer.DirectContent);
                }
                else
                {
                    pdfTaba.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 500, writer.DirectContent);
                }
            }
            if (PageRequired)
            {
                //Add paging to footer
                cb.BeginText();
                cb.SetFontAndSize(bf, 8);
                cb.SetTextMatrix(document.PageSize.GetRight(120), document.PageSize.GetBottom(35));
                cb.ShowText(text);
                cb.EndText();
                float len = bf.GetWidthPoint(text, 12);
                cb.AddTemplate(footerTemplate, document.PageSize.GetRight(120) + len, document.PageSize.GetBottom(35));
            }
            if (BorderRequired)
            {
                //Add Paging to Border
                var content        = writer.DirectContent;
                var pageBorderRect = new Rectangle(document.PageSize);

                pageBorderRect.Left   += 40f;
                pageBorderRect.Right  -= 40f;
                pageBorderRect.Top    -= 30f;
                pageBorderRect.Bottom += 30f;

                content.SetColorStroke(BaseColor.BLACK);
                content.Rectangle(pageBorderRect.Left, pageBorderRect.Bottom, pageBorderRect.Width, pageBorderRect.Height);
                content.Stroke();
            }
        }
Exemplo n.º 41
0
        /// <summary>
        /// Constructs a Font-object.
        /// </summary>
        /// <param name="attributes">the attributes of a Font object</param>
        /// <returns>a Font object</returns>
        public static Font getFont(Properties attributes)
        {
            string fontname = null;
            string encoding = defaultEncoding;
            bool   embedded = defaultEmbedding;
            float  size     = Font.UNDEFINED;
            int    style    = Font.NORMAL;
            Color  color    = null;
            string value    = attributes.Remove(MarkupTags.STYLE);

            if (value != null && value.Length > 0)
            {
                Properties styleAttributes = MarkupParser.parseAttributes(value);
                if (styleAttributes.Count == 0)
                {
                    attributes.Add(MarkupTags.STYLE, value);
                }
                else
                {
                    fontname = (string)styleAttributes.Remove(MarkupTags.CSS_FONTFAMILY);
                    if (fontname != null)
                    {
                        string tmp;
                        while (fontname.IndexOf(",") != -1)
                        {
                            tmp = fontname.Substring(0, fontname.IndexOf(","));
                            if (isRegistered(tmp))
                            {
                                fontname = tmp;
                            }
                            else
                            {
                                fontname = fontname.Substring(fontname.IndexOf(",") + 1);
                            }
                        }
                    }
                    if ((value = (string)styleAttributes.Remove(MarkupTags.CSS_FONTSIZE)) != null)
                    {
                        size = MarkupParser.parseLength(value);
                    }
                    if ((value = (string)styleAttributes.Remove(MarkupTags.CSS_FONTWEIGHT)) != null)
                    {
                        style |= Font.getStyleValue(value);
                    }
                    if ((value = (string)styleAttributes.Remove(MarkupTags.CSS_FONTSTYLE)) != null)
                    {
                        style |= Font.getStyleValue(value);
                    }
                    if ((value = (string)styleAttributes.Remove(MarkupTags.CSS_COLOR)) != null)
                    {
                        color = MarkupParser.decodeColor(value);
                    }
                    attributes.AddAll(styleAttributes);
                }
            }
            if ((value = attributes.Remove(ElementTags.ENCODING)) != null)
            {
                encoding = value;
            }
            if ("false".Equals(attributes.Remove(ElementTags.EMBEDDED)))
            {
                embedded = false;
            }
            if ((value = attributes.Remove(ElementTags.FONT)) != null)
            {
                fontname = value;
            }
            if ((value = attributes.Remove(ElementTags.SIZE)) != null)
            {
                size = float.Parse(value);
            }
            if ((value = attributes.Remove(MarkupTags.STYLE)) != null)
            {
                style |= Font.getStyleValue(value);
            }
            if ((value = attributes.Remove(ElementTags.STYLE)) != null)
            {
                style |= Font.getStyleValue(value);
            }
            string r = attributes.Remove(ElementTags.RED);
            string g = attributes.Remove(ElementTags.GREEN);
            string b = attributes.Remove(ElementTags.BLUE);

            if (r != null || g != null || b != null)
            {
                int red   = 0;
                int green = 0;
                int blue  = 0;
                if (r != null)
                {
                    red = int.Parse(r);
                }
                if (g != null)
                {
                    green = int.Parse(g);
                }
                if (b != null)
                {
                    blue = int.Parse(b);
                }
                color = new Color(red, green, blue);
            }
            else if ((value = attributes.Remove(ElementTags.COLOR)) != null)
            {
                color = MarkupParser.decodeColor(value);
            }
            if (fontname == null)
            {
                return(getFont(null, encoding, embedded, size, style, color));
            }
            return(getFont(fontname, encoding, embedded, size, style, color));
        }
Exemplo n.º 42
0
    public string GenerarTicket(bool esVtaTaller)
    {
        iTextSharp.text.Font fuenteT  = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
        iTextSharp.text.Font fuenteB  = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 6, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
        iTextSharp.text.Font fuenteBb = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10, iTextSharp.text.Font.BOLD, BaseColor.RED);
        iTextSharp.text.Font fuente   = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
        iTextSharp.text.Font fuenteS  = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 5, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
        iTextSharp.text.Font fuente6  = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 9, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

        // Crear documento
        Document documento = new Document(iTextSharp.text.PageSize.LETTER);

        documento.AddTitle("Ticket de Compra");
        documento.AddCreator("E-PuntoVenta");

        string ruta    = HttpContext.Current.Server.MapPath("~/Tickets");
        string archivo = ruta + "\\Ticket_" + _pv.ToString() + "_" + _ticket.ToString() + ".pdf";

        //si no existe la carpeta temporal la creamos
        if (!(Directory.Exists(ruta)))
        {
            Directory.CreateDirectory(ruta);
        }


        if (archivo.Trim() != "")
        {
            FileInfo info = new FileInfo(archivo);
            if (info.Exists)
            {
                info.Delete();
            }

            FileStream file = new FileStream(archivo,
                                             FileMode.OpenOrCreate,
                                             FileAccess.ReadWrite,
                                             FileShare.ReadWrite);
            PdfWriter.GetInstance(documento, file);
            // Abrir documento.
            documento.Open();

            //Insertar logo o imagen
            string rutaLogo            = HttpContext.Current.Server.MapPath("~/img/logo.png");
            iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(rutaLogo);
            logo.ScaleToFit(100, 50);
            logo.Alignment = iTextSharp.text.Image.ALIGN_LEFT;

            PdfPTable enc1 = new PdfPTable(3);
            enc1.DefaultCell.Border = 0;
            enc1.WidthPercentage    = 100f;
            int[] enc1cellwidth = { 20, 40, 40 };
            enc1.SetWidths(enc1cellwidth);


            PdfPCell img1 = new PdfPCell(logo);
            img1.Border = 0;
            img1.HorizontalAlignment = Element.ALIGN_CENTER;
            enc1.AddCell(img1);


            PdfPCell enca = new PdfPCell(new Phrase("\n COMERCIALIZADORA \n BURGOS MAGALLANES \n S. DE R.L. DE C.V. \n ", fuente));
            enca.HorizontalAlignment = Element.ALIGN_CENTER;

            enca.Border = 0;
            enc1.AddCell(enca);


            ImprimeTicket imp = new ImprimeTicket();
            imp.ticketc = _ticket;
            object[] camposcab = detTicket.obtieneenca(_ticket);
            DateTime fechav;

            if (Convert.ToBoolean(camposcab[0]))
            {
                DataSet datos = (DataSet)camposcab[1];


                foreach (DataRow fila in datos.Tables[0].Rows)
                {
                    fechav = Convert.ToDateTime(fila[0]);

                    PdfPCell enca2 = new PdfPCell(new Phrase("\n\n REMISION No." + _ticket + "    \n Requisicion : " + _requi.ToUpper() + "\n Entrada : " + _entrada.ToUpper(), fuente6));
                    enca2.HorizontalAlignment = Element.ALIGN_LEFT;
                    enca2.Border = 0;
                    enc1.AddCell(enca2);
                }
            }

            documento.Add(enc1);
            documento.Add(new Paragraph(" "));

            PdfPTable enc2 = new PdfPTable(1);
            enc2.DefaultCell.Border = 0;
            enc2.WidthPercentage    = 100f;
            int[] enc2cellwidth = { 50 };
            enc2.SetWidths(enc2cellwidth);

            PdfPCell enca3 = new PdfPCell(new Phrase("Cliente:   GOBIERNO DEL DISTRITO FEDERAL / SUBSECRETARIA DEL SISTEMA PENITENCIARIO \n                PLAZAS DE LA CONSTITUCION S/N CENTRO DE LA CIUDAD DE MEXICO C.P. 06000 AREA 1 \n                DISTRITO FEDERAL GDF-971205-4NA", fuente6));
            enca3.HorizontalAlignment = Element.ALIGN_LEFT;
            enca3.Border = 0;
            enc2.AddCell(enca3);



            documento.Add(enc2);


            string noOrden   = "";
            string nomTaller = "";
            string folio     = "";
            string cliente   = "";
            if (esVtaTaller)
            {
                object[] datosVtaTaller = detTicket.datosVtaTaller();
                DataSet  valVtaTaller   = (DataSet)datosVtaTaller[1];
                foreach (DataRow f in valVtaTaller.Tables[0].Rows)
                {
                    folio     = f[0].ToString();
                    noOrden   = f[1].ToString();
                    nomTaller = f[2].ToString();
                    cliente   = f[3].ToString();
                }
            }

            object[] datosTicket = detTicket.datosTicket();
            if (Convert.ToBoolean(datosTicket[0]))
            {
                DataSet              valores = (DataSet)datosTicket[1];
                DateTime             fecha;
                iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 13, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
                foreach (DataRow fila in valores.Tables[0].Rows)
                {
                    try
                    {
                        fecha  = Convert.ToDateTime(fila[0].ToString() + " " + fila[1].ToString());
                        _fecha = fecha.ToString("yyyy-MM-dd");
                        _hora  = fecha.ToString("HH:mm:ss");
                    }
                    catch (Exception)
                    {
                        _fecha = fila[0].ToString();
                        _hora  = fila[1].ToString().Substring(0, 10);
                    }

                    _usuario       = fila[3].ToString();
                    _forma         = fila[8].ToString();
                    _refe          = fila[9].ToString();
                    _ban           = fila[11].ToString();
                    _sub           = Convert.ToDecimal(fila[4].ToString());
                    _iva           = Convert.ToDecimal(fila[5].ToString());
                    _tot           = Convert.ToDecimal(fila[6].ToString());
                    _porc_dctoGral = Convert.ToDecimal(fila[13].ToString()) / 100;
                    _montoDecto    = Convert.ToDecimal(fila[14].ToString());
                    _porcIva       = Convert.ToDecimal(fila[7].ToString());
                    _notasTicket   = fila[12].ToString();
                    try { _esVtaCredito = bool.Parse(fila[15].ToString()); } catch (Exception) { _esVtaCredito = false; }
                    Encabezado(documento);

                    if (esVtaTaller)
                    {
                        Paragraph vtaTall = new Paragraph("Folio: " + folio.Trim() + " - Orden: " + noOrden + " - Cliente: " + cliente + " - Taller: " + nomTaller, fuente);
                        vtaTall.Alignment = Element.ALIGN_CENTER;
                        documento.Add(vtaTall);
                    }

                    Paragraph aten = new Paragraph("Atendio: " + _usuario.ToString(), fuente);
                    aten.Alignment = Element.ALIGN_CENTER;
                    documento.Add(aten);

                    if (_esVtaCredito)
                    {
                        Paragraph vtaCred = new Paragraph("-Venta a Crédito-", fuente);
                        vtaCred.Alignment = Element.ALIGN_CENTER;
                        documento.Add(vtaCred);
                    }

                    Paragraph pag = new Paragraph("Forma Pago: " + _forma.ToString(), fuente);
                    pag.Alignment = Element.ALIGN_CENTER;
                    documento.Add(pag);
                    if (_forma != "Efectivo" && _forma != "")
                    {
                        /*Paragraph refe = new Paragraph("Referencia Pago: " + _refe.ToString(), fuente);
                         * refe.Alignment = Element.ALIGN_CENTER;
                         * documento.Add(refe);*/
                        Paragraph banc = new Paragraph("Banco: " + _ban.ToString(), fuente);
                        banc.Alignment = Element.ALIGN_CENTER;
                        documento.Add(banc);
                    }
                }


                documento.AddCreationDate();
                documento.Add(new Paragraph(" "));
                documento.Add(new Paragraph(" "));
                ProductosTicket(documento);

                Paragraph lin = new Paragraph("", fuente);
                lin.Alignment = Element.ALIGN_CENTER;
                //documento.Add(lin);
                Paragraph subtotal = new Paragraph(" ", fuenteBb);
                subtotal.Alignment = Element.ALIGN_CENTER;

                Paragraph liva = new Paragraph("", fuenteB);
                liva.Alignment = Element.ALIGN_CENTER;

                documento.Add(new Paragraph(" "));
                documento.Add(new Paragraph(" "));
                Paragraph ltotal = new Paragraph("", fuenteT);
                ltotal.Alignment = Element.ALIGN_CENTER;
                Paragraph dctoGral = new Paragraph("HUEHUETAN MZA. 171 LOTE 14 COL. HEROES DE PADIERNA 14200 TLALPAN DISTRITO FEDERAL RFC. CMB140917L5A", fuenteT);
                dctoGral.Alignment = Element.ALIGN_CENTER;
                documento.Add(dctoGral);
                documento.Add(subtotal);
                documento.Add(liva);
                documento.Add(ltotal);

                Pagos pagosTicket = new Pagos();
                pagosTicket.ticket = _ticket;
                pagosTicket.caja   = _caja;
                pagosTicket.punto  = _pv;
                pagosTicket.obtienePagos();
                object[] datosTpagos = pagosTicket.retorno;
                if (Convert.ToBoolean(datosTpagos[0]))
                {
                    DataSet infoPago = (DataSet)datosTpagos[1];
                    foreach (DataRow fila in infoPago.Tables[0].Rows)
                    {
                        Paragraph pagf = new Paragraph("", fuente);
                        pagf.Alignment = Element.ALIGN_CENTER;
                        documento.Add(pagf);

                        /*if (fila[0].ToString() != "E")
                         * {
                         *  Paragraph refef = new Paragraph( "T.: "+fila[5]+  " Referencia Pago: " + fila[7].ToString(), fuente);
                         *  refef.Alignment = Element.ALIGN_CENTER;
                         *  documento.Add(refef);
                         * }*/

                        Paragraph lpago = new Paragraph("", fuenteB);
                        lpago.Alignment = Element.ALIGN_CENTER;
                        documento.Add(lpago);
                        Paragraph lcambio = new Paragraph("", fuente);
                        lcambio.Alignment = Element.ALIGN_CENTER;
                        documento.Add(lcambio);
                    }
                }

                documento.Add(new Paragraph(" "));
                //importe con letra
                ConvertirNumerosLetras conversion = new ConvertirNumerosLetras();
                conversion.IMporte = (_tot + _iva).ToString();
                string    textoLetras  = conversion.enletras();
                Paragraph importeLetra = new Paragraph("", fuente);
                importeLetra.Alignment = Element.ALIGN_CENTER;
                documento.Add(importeLetra);

                if (_notasTicket != "")
                {
                    documento.Add(new Paragraph(" "));
                    Paragraph notTi = new Paragraph("", fuente);
                    notTi.Alignment = Element.ALIGN_CENTER;
                    documento.Add(notTi);
                    documento.Add(new Paragraph(" "));
                    Paragraph notTciket = new Paragraph("", fuenteS);
                    notTciket.Alignment = Element.ALIGN_CENTER;
                    documento.Add(notTciket);
                }

                documento.Add(new Paragraph(" "));
                Paragraph not = new Paragraph(_notas, fuenteS);
                not.Alignment = Element.ALIGN_CENTER;
                documento.Add(not);
            }
            documento.Close();
        }
        return(archivo);
    }
Exemplo n.º 43
0
        public void ExportToPdf(System.Data.DataTable dt)
        {
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName   = "Izvjestaj";                  // Default file name
            dlg.DefaultExt = ".pdf";                       // Default file extension
            dlg.Filter     = "PDF documents (.pdf)|*.pdf"; // Filter files by extension

            // save file dialog box
            Nullable <bool> result = dlg.ShowDialog();

            try
            {
                if (result == true)
                {
                    // Save document
                    string filename = dlg.FileName;

                    iTextSharp.text.Document document = new iTextSharp.text.Document();
                    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create));
                    document.AddTitle("Izvjestaj");

                    document.AddCreationDate();

                    document.Open();
                    iTextSharp.text.Font font5 = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA, 7);

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

                    if (pom == "_Arhiva")
                    {
                        float[] widths = new float[] { 1f, 3f, 3f, 3f, 4f, 3f, 3f, 4f };
                        table.SetWidths(widths);

                        table.WidthPercentage = 100;
                        PdfPCell cell = new PdfPCell(new Phrase("Elementi"));

                        cell.Colspan = dt.Columns.Count;

                        foreach (DataColumn c in dt.Columns)
                        {
                            table.AddCell(new Phrase(c.ColumnName, font5));
                        }

                        foreach (DataRow r in dt.Rows)
                        {
                            if (dt.Rows.Count > 0)
                            {
                                table.AddCell(new Phrase(r[0].ToString(), font5));
                                table.AddCell(new Phrase(r[1].ToString(), font5));
                                table.AddCell(new Phrase(r[2].ToString(), font5));
                                table.AddCell(new Phrase(r[3].ToString(), font5));
                                table.AddCell(new Phrase(r[4].ToString(), font5));
                                table.AddCell(new Phrase(r[5].ToString(), font5));
                                table.AddCell(new Phrase(r[6].ToString(), font5));
                                table.AddCell(new Phrase(r[7].ToString(), font5));
                            }
                        }
                    }
                    else
                    {
                        float[] widths = new float[] { 1f, 3f, 3f, 3f, 4f, 3f, 3f, 4f, 4f };
                        table.SetWidths(widths);

                        table.WidthPercentage = 100;
                        // int iCol = 0;
                        // string colname = "";
                        PdfPCell cell = new PdfPCell(new Phrase("Elementi"));

                        cell.Colspan = dt.Columns.Count;

                        foreach (DataColumn c in dt.Columns)
                        {
                            table.AddCell(new Phrase(c.ColumnName, font5));
                        }

                        foreach (DataRow r in dt.Rows)
                        {
                            if (dt.Rows.Count > 0)
                            {
                                table.AddCell(new Phrase(r[0].ToString(), font5));
                                table.AddCell(new Phrase(r[1].ToString(), font5));
                                table.AddCell(new Phrase(r[2].ToString(), font5));
                                table.AddCell(new Phrase(r[3].ToString(), font5));
                                table.AddCell(new Phrase(r[4].ToString(), font5));
                                table.AddCell(new Phrase(r[5].ToString(), font5));
                                table.AddCell(new Phrase(r[6].ToString(), font5));
                                table.AddCell(new Phrase(r[7].ToString(), font5));
                                table.AddCell(new Phrase(r[8].ToString(), font5));
                            }
                        }
                    }
                    //dodavanje naslova

                    iTextSharp.text.Font      titleFont   = FontFactory.GetFont("Arial", 32);
                    iTextSharp.text.Font      regularFont = FontFactory.GetFont("Arial", 12);
                    iTextSharp.text.Paragraph title;
                    iTextSharp.text.Paragraph text;
                    title           = new iTextSharp.text.Paragraph("Izvještaj", titleFont);
                    title.Alignment = Element.ALIGN_CENTER;
                    document.Add(title);
                    text           = new iTextSharp.text.Paragraph("Datum:_____________", regularFont);
                    text.Alignment = Element.ALIGN_RIGHT;
                    document.Add(text);
                    document.Add(new iTextSharp.text.Paragraph(" "));
                    document.Add(new iTextSharp.text.Paragraph(" "));

                    document.Add(table);
                    document.Close();
                    this.Close();
                }
            }
            catch (Exception error)
            {
                MessageBox.Show("Error: " + error.Message);
            }
        }
Exemplo n.º 44
0
        private void BtnExportPdf_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveDialog = new SaveFileDialog();

            saveDialog.Filter   = "PDF File (*.pdf)|*.pdf";
            saveDialog.FileName = "";
            if (saveDialog.ShowDialog() == true)
            {
                // PDF 변환
                try
                {
                    // 0.PDF 사용 폰트 설정
                    string   nanumPath    = Path.Combine(Environment.CurrentDirectory, @"NanumGothic.ttf"); // 폰트경로
                    BaseFont nanumBase    = BaseFont.CreateFont(nanumPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                    var      nanumTitle   = new iTextSharp.text.Font(nanumBase, 20f);                       // 20 타이틀용 나눔폰트;
                    var      nanumContent = new iTextSharp.text.Font(nanumBase, 12f);                       // 12 내용 나눔폰트;

                    //iTextSharp.text.Font font = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12);
                    string pdfFilePath = saveDialog.FileName;

                    // 1.PDF 객체생성
                    iTextSharp.text.Document pdfDoc = new Document(PageSize.A4);

                    // 2.PDF 내용 만들기
                    Paragraph title    = new Paragraph("부경대 재고관리시스템(SMS)\n", nanumTitle);
                    Paragraph subTitle = new Paragraph($"사용자리스트 exported : {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}\n\n", nanumContent);

                    PdfPTable pdfTable = new PdfPTable(GrdData.Columns.Count);
                    pdfTable.WidthPercentage = 100; // 전체 사이즈 다 쓰는거

                    // 그리드 헤더 작업
                    foreach (DataGridColumn column in GrdData.Columns)
                    {
                        PdfPCell cell = new PdfPCell(new Phrase(column.Header.ToString(), nanumContent));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        pdfTable.AddCell(cell);
                    }

                    // 각 셀 사이즈 조정
                    float[] columnsWidth = new float[] { 7f, 15f, 10f, 15f, 28f, 12f, 10f };
                    pdfTable.SetWidths(columnsWidth);

                    // 그리드 Row 작업
                    foreach (var item in GrdData.Items)
                    {
                        if (item is Model.User)
                        {
                            var temp = item as Model.User;
                            // UserId
                            PdfPCell cell = new PdfPCell(new Phrase(temp.UserID.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            pdfTable.AddCell(cell);
                            // UserIdentityNumber
                            cell = new PdfPCell(new Phrase(temp.UserIdentityNumber.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            pdfTable.AddCell(cell);
                            // UserSurname
                            cell = new PdfPCell(new Phrase(temp.UserSurname.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            pdfTable.AddCell(cell);
                            // UserName
                            cell = new PdfPCell(new Phrase(temp.UserName.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            pdfTable.AddCell(cell);
                            // UserEmail
                            cell = new PdfPCell(new Phrase(temp.UserEmail.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            pdfTable.AddCell(cell);
                            // UserAdmin
                            cell = new PdfPCell(new Phrase(temp.UserAdmin.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            pdfTable.AddCell(cell);
                            // UserActivated
                            cell = new PdfPCell(new Phrase(temp.UserActivated.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            pdfTable.AddCell(cell);
                        }
                    }

                    // 3.PDF 파일생성
                    using (FileStream stream = new FileStream(pdfFilePath, FileMode.OpenOrCreate))
                    {
                        PdfWriter.GetInstance(pdfDoc, stream);
                        pdfDoc.Open();
                        // 2번에서 만들 내용 추가
                        pdfDoc.Add(title);
                        pdfDoc.Add(subTitle);
                        pdfDoc.Add(pdfTable);
                        pdfDoc.Close();
                        stream.Close(); // option
                    }

                    Commons.ShowMessageAsync("PDF변환", "PDF 익스포트 성공했습니다");
                }
                catch (Exception ex)
                {
                    Commons.LOGGER.Error($"예외발생 BtnExportPdf_Click : {ex}");
                }
            }
        }
Exemplo n.º 45
0
        private void button1_Click(object sender, EventArgs e)
        {
            /*
             * SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["conString"]);
             * if (conn.State != ConnectionState.Open)
             * {
             *  conn.Open();
             * }
             * SqlCommand cmd = conn.CreateCommand();
             * cmd.CommandText = "Select * From Usuarios";
             *
             * SqlDataReader reader = cmd.ExecuteReader();
             *
             *
             * Document doc = new Document();
             * PdfWriter.GetInstance(doc, new FileStream("MeuRelatorio.pdf", FileMode.Create)); // asignamos el nombre de archivo hola.pdf
             * doc.Open();
             * Paragraph title = new Paragraph();
             * title.Font = FontFactory.GetFont(FontFactory.TIMES, 28f, BaseColor.BLUE);
             * title.Add("Relatorio De usuários");
             * doc.Add(title);
             * doc.Add(new Paragraph(" "));
             *
             *
             * PdfPTable table = new PdfPTable(6);
             * table.AddCell("Id_User");
             * table.AddCell("iuser");
             * table.AddCell("senha");
             * table.AddCell("codigo_Setor");
             * table.AddCell("email_Interno");
             * table.AddCell("Cargo");
             *
             *
             * while (reader.Read())
             * {
             *  table.AddCell(reader.GetString(0).ToString());
             *  table.AddCell(reader.GetString(1).ToString());
             *  table.AddCell(reader.GetString(2).ToString());
             *  table.AddCell(reader.GetString(3).ToString());
             *  table.AddCell(reader.GetString(4).ToString());
             *  table.AddCell(reader.GetString(5).ToString());
             * }
             * doc.Add(table);
             * doc.Close();
             * conn.Close();
             *
             */



            Document doc = new Document(PageSize.A4.Rotate());

            doc.SetMargins(40, 40, 40, 80);
            doc.AddCreationDate();
            string Caminho = AppDomain.CurrentDomain.BaseDirectory + @"\application" + "RelatorioCarlos.pdf";

            PdfWriter.GetInstance(doc, new FileStream(Caminho, FileMode.Create));
            doc.Open();

            Paragraph title = new Paragraph();

            title.Font = FontFactory.GetFont(FontFactory.TIMES, 28f, BaseColor.BLUE);
            title.Add("Relatorio De usuários");
            doc.Add(title);

            doc.Add(new Paragraph(" "));
            DataRow dr = GetData("Select U.User_Id as user_id, U.iuser as iuser, U.senha as senha, U.codigo_setor as codigo_setor, U.email_Interno as email_Interno, U.cargo as cargo FROM  Usuarios U  Where U.iuser = iuser" + CbxCarregar.SelectedItem.ToString()).Rows[0];

            iTextSharp.text.Font fz = FontFactory.GetFont("Arial", 14, BaseColor.BLACK);
            Phrase    phase         = null;
            PdfPCell  cell          = null;
            PdfPTable table         = null;

            table             = new PdfPTable(2);
            table.TotalWidth  = 500f;
            table.LockedWidth = true;
            table.SetWidths(new float[] { 0.3f, 0.7f });
            phase = new Phrase();
            phase.Add(new Chunk("Tuscano Equipments Private Limited\n\n", FontFactory.GetFont("Arial", 16, BaseColor.RED)));
            phase.Add(new Chunk("Jammi Building,\n", FontFactory.GetFont("Arial", 14, BaseColor.BLUE)));
            phase.Add(new Chunk("Royapettah,Chennai", FontFactory.GetFont("Arial", 14, BaseColor.BLUE)));
            cell = PhraseCell(phase, PdfPCell.ALIGN_LEFT);
            cell.VerticalAlignment = PdfPCell.ALIGN_TOP;
            table.AddCell(cell);

            table = new PdfPTable(2);
            table.HorizontalAlignment = Element.ALIGN_LEFT;
            table.SetWidths(new float[] { 0.3f, 1f });
            table.SpacingBefore = 20f;

            cell         = new PdfPCell(new Phrase("Technician Record", FontFactory.GetFont("Arial", 12, BaseColor.BLACK)));
            cell.Colspan = 2;
            table.AddCell(cell);
            cell               = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER);
            cell.Colspan       = 2;
            cell.PaddingBottom = 30f;
            table.AddCell(cell);

            table = new PdfPTable(2);
            table.SetWidths(new float[] { 0.5f, 2f });
            table.TotalWidth          = 340f;
            table.LockedWidth         = true;
            table.SpacingBefore       = 20f;
            table.HorizontalAlignment = Element.ALIGN_RIGHT;

            table.AddCell(PhraseCell(new Phrase("Id De Usuario:", FontFactory.GetFont("Arial", 10, BaseColor.BLACK)), PdfPCell.ALIGN_LEFT));
            table.AddCell(PhraseCell(new Phrase("000" + dr["User_Id"], FontFactory.GetFont("Arial", 10, BaseColor.BLACK)), PdfPCell.ALIGN_LEFT));
            cell               = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER);
            cell.Colspan       = 2;
            cell.PaddingBottom = 10f;
            table.AddCell(cell);

            table.AddCell(PhraseCell(new Phrase("Nome De Usuário:", FontFactory.GetFont("Arial", 10, BaseColor.BLACK)), PdfPCell.ALIGN_LEFT));
            phase = new Phrase(new Chunk(dr["iuser"] + "\n", FontFactory.GetFont("Arial", 10, BaseColor.BLACK)));
            table.AddCell(PhraseCell(phase, PdfPCell.ALIGN_LEFT));
            cell               = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER);
            cell.Colspan       = 2;
            cell.PaddingBottom = 10f;
            table.AddCell(cell);

            table.AddCell(PhraseCell(new Phrase("Senha De usuário:", FontFactory.GetFont("Arial", 10, BaseColor.BLACK)), PdfPCell.ALIGN_LEFT));
            table.AddCell(PhraseCell(new Phrase(Convert.ToInt32(dr["senha"]).ToString(), FontFactory.GetFont("Arial", 10, BaseColor.BLACK)), PdfPCell.ALIGN_LEFT));
            cell               = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER);
            cell.Colspan       = 2;
            cell.PaddingBottom = 10f;
            table.AddCell(cell);

            table.AddCell(PhraseCell(new Phrase("Codigo do Setor:", FontFactory.GetFont("Arial", 10, BaseColor.BLACK)), PdfPCell.ALIGN_LEFT));
            table.AddCell(PhraseCell(new Phrase(dr["codigo_setor"] + "\n", FontFactory.GetFont("Arial", 10, BaseColor.BLACK)), PdfPCell.ALIGN_LEFT));
            cell               = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER);
            cell.Colspan       = 2;
            cell.PaddingBottom = 10f;
            table.AddCell(cell);

            table.AddCell(PhraseCell(new Phrase("Email Interno:", FontFactory.GetFont("Arial", 10, BaseColor.BLACK)), PdfPCell.ALIGN_LEFT));
            phase = new Phrase(new Chunk(dr["email_Interno"] + "\n", FontFactory.GetFont("Arial", 10, BaseColor.BLACK)));
            table.AddCell(PhraseCell(phase, PdfPCell.ALIGN_LEFT));
            cell               = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER);
            cell.Colspan       = 2;
            cell.PaddingBottom = 10f;
            table.AddCell(cell);

            table.AddCell(PhraseCell(new Phrase("Cargo Ocupacional:", FontFactory.GetFont("Arial", 10, BaseColor.BLACK)), PdfPCell.ALIGN_LEFT));
            phase = new Phrase(new Chunk(dr["cargo"] + "\n", FontFactory.GetFont("Arial", 10, BaseColor.BLACK)));
            table.AddCell(PhraseCell(phase, PdfPCell.ALIGN_LEFT));
            cell               = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER);
            cell.Colspan       = 2;
            cell.PaddingBottom = 10f;
            table.AddCell(cell);



            try
            {
                doc.Add(phase);
                doc.Add(table);
                doc.Add(cell);
                MessageBox.Show("Pfd Gerado com sucesso");

                RelatorioPdf relatorio = new RelatorioPdf();
                relatorio.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("Não Foi possivel Gerar O pdf", ex);
            }

            finally
            {
                doc.Close();
            }
        }
Exemplo n.º 46
0
    private void ProductosTicket(Document document)
    {
        iTextSharp.text.Font fuenteT = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
        iTextSharp.text.Font fuenteB = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 9, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
        iTextSharp.text.Font fuenten = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
        iTextSharp.text.Font fuente  = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
        iTextSharp.text.Font fuenter = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8, iTextSharp.text.Font.NORMAL, BaseColor.RED);
        iTextSharp.text.Font fuenteS = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 7, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

        PdfPTable tblProductos = new PdfPTable(3);

        PdfPCell cllcan = new PdfPCell(new Phrase("CANT", fuenteB));

        cllcan.BorderWidthBottom   = 1;
        cllcan.HorizontalAlignment = Element.ALIGN_MIDDLE;
        cllcan.VerticalAlignment   = Element.ALIGN_MIDDLE;
        cllcan.BackgroundColor     = BaseColor.LIGHT_GRAY;
        cllcan.Padding             = 1;
        PdfPCell cldesc = new PdfPCell(new Phrase("UNIDAD MEDIDA", fuenteB));

        cldesc.BorderWidthBottom   = 1;
        cldesc.VerticalAlignment   = Element.ALIGN_MIDDLE;
        cldesc.HorizontalAlignment = Element.ALIGN_MIDDLE;
        cldesc.VerticalAlignment   = 1;
        cldesc.BackgroundColor     = BaseColor.LIGHT_GRAY;
        cldesc.Padding             = 1;
        PdfPCell clpre = new PdfPCell(new Phrase("DESCRIPCIÓN", fuenteB));

        clpre.BorderWidthBottom   = 1;
        clpre.HorizontalAlignment = Element.ALIGN_MIDDLE;
        clpre.VerticalAlignment   = Element.ALIGN_MIDDLE;
        clpre.BackgroundColor     = BaseColor.LIGHT_GRAY;
        clpre.Padding             = 1;



        tblProductos.AddCell(cllcan);
        tblProductos.AddCell(cldesc);
        tblProductos.AddCell(clpre);


        ImprimeTicket imp = new  ImprimeTicket();

        imp.ticketc = _ticket;


        int    tamañodatos = 0;
        int    cantidad;
        string medidas;
        string descripcion;

        object[] camposcab = detTicket.obtieneDetalle(_ticket);
        if (Convert.ToBoolean(camposcab[0]))
        {
            DataSet datos = (DataSet)camposcab[1];


            foreach (DataRow fila in datos.Tables[0].Rows)
            {
                cantidad    = Convert.ToInt32(fila[0]);
                medidas     = Convert.ToString(fila[1]);
                descripcion = Convert.ToString(fila[2]);



                PdfPCell canti = new PdfPCell(new Phrase("" + cantidad, fuenteS));
                canti.HorizontalAlignment = Element.ALIGN_CENTER;
                canti.VerticalAlignment   = Element.ALIGN_MIDDLE;
                tblProductos.AddCell(canti);


                PdfPCell deta = new PdfPCell(new Phrase("" + medidas, fuenteS));
                deta.HorizontalAlignment = Element.ALIGN_CENTER;
                deta.VerticalAlignment   = Element.ALIGN_MIDDLE;
                tblProductos.AddCell(deta);

                PdfPCell desc = new PdfPCell(new Phrase("" + descripcion, fuenteS));
                desc.HorizontalAlignment = Element.ALIGN_CENTER;
                desc.VerticalAlignment   = Element.ALIGN_MIDDLE;
                tblProductos.AddCell(desc);
            }
        }



        document.Add(tblProductos);
        document.Add(new Paragraph(" "));
        document.Add(new Paragraph(" "));
    }
Exemplo n.º 47
0
        private void DoReport(string query, string firstParam, string secondParam)
        {
            SqlDataReader sqlReader = null; // инициализируем reader

            using (WinForms.SaveFileDialog saveFileDialog = new WinForms.SaveFileDialog()
            {
                Filter = "PDF file|*.pdf", ValidateNames = true // выбираем фильтр для сохранения
            })
                if (saveFileDialog.ShowDialog() == WinForms.DialogResult.OK)
                {
                    iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.A4);
                    try
                    {
                        if (tbPercent.Text == "" || cmbGroup.Text == "") // проверяем выбраны ли все параметры
                        {
                            MessageBox.Show("Необходимо выбрать все параметры", "Внимание", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        else if (Convert.ToDouble(tbPercent.Text) < 0 || Convert.ToDouble(tbPercent.Text) > 100) // проверяем правильный ли диапазон процента
                        {
                            MessageBox.Show("Введите коректный параметр процента посещения (от 0 до 100)", "Внимание", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                        else
                        {
                            PdfWriter.GetInstance(doc, new FileStream(saveFileDialog.FileName, FileMode.Create));

                            doc.Open();
                            BaseFont             bf    = BaseFont.CreateFont(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "Verdana.ttf"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                            BaseFont             italf = BaseFont.CreateFont(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "Verdanai.ttf"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                            iTextSharp.text.Font itf   = new iTextSharp.text.Font(bf, 10f, iTextSharp.text.Font.ITALIC);
                            iTextSharp.text.Font htf   = new iTextSharp.text.Font(bf, 20f, iTextSharp.text.Font.NORMAL);
                            iTextSharp.text.Font ttf   = new iTextSharp.text.Font(bf, 10f, iTextSharp.text.Font.NORMAL);
                            iTextSharp.text.Font stf   = new iTextSharp.text.Font(bf, 8f, iTextSharp.text.Font.NORMAL);

                            doc.Add(new iTextSharp.text.Paragraph("ХНЭУ", htf));
                            doc.Add(new iTextSharp.text.Paragraph("им. Семена Кузнеца", ttf));
                            PdfPTable table = new PdfPTable(5);
                            PdfPCell  cell  = new PdfPCell(new Phrase("Список студентов", ttf));
                            cell.Colspan             = 5;
                            cell.HorizontalAlignment = Element.ALIGN_CENTER;
                            table.AddCell(cell);
                            table.AddCell(new Phrase("ФИО", ttf));
                            table.AddCell(new Phrase("Тел.", ttf));
                            table.AddCell(new Phrase("Всего часов", ttf));
                            table.AddCell(new Phrase("Пропущено", ttf));
                            table.AddCell(new Phrase("По ув. причине", ttf));
                            doc.Add(new iTextSharp.text.Paragraph("\n", ttf));
                            if (rbMore.IsChecked == true)
                            {
                                doc.Add(new iTextSharp.text.Paragraph("Список студентов, у которых % пропусков больше " + tbPercent.Text, ttf));
                            }
                            else if (rbLess.IsChecked == true)
                            {
                                doc.Add(new iTextSharp.text.Paragraph("Список студентов, у которых % пропусков меньше " + tbPercent.Text, ttf));
                            }
                            doc.Add(new iTextSharp.text.Paragraph("Группа: " + cmbGroup.Text, ttf));
                            doc.Add(new iTextSharp.text.Paragraph("\n", ttf));
                            SqlCommand command = new SqlCommand(query, sqlConnection); // создаем SQL запрос к БД
                            command.Parameters.AddWithValue("@group", firstParam);     // подставляем параметры в запрос
                            command.Parameters.AddWithValue("@percent", secondParam);
                            sqlReader = command.ExecuteReader();                       // исполняем SQL запрос

                            while (sqlReader.Read())                                   // пока sqlReader содержит строки добавляем их в отчет
                            {
                                table.AddCell(new Phrase(sqlReader["name"].ToString(), stf));
                                table.AddCell(new Phrase(sqlReader["number"].ToString(), stf));
                                table.AddCell(new Phrase(sqlReader["allhours"].ToString(), stf));
                                table.AddCell(new Phrase(sqlReader["losthours"].ToString(), stf));
                                table.AddCell(new Phrase(sqlReader["reason"].ToString(), stf));
                            }
                            doc.Add(table);
                            doc.Add(new iTextSharp.text.Paragraph("\n", ttf));
                            PdfPTable dateTable = new PdfPTable(1);
                            cell = new PdfPCell(new Phrase("Дата: " + DateTime.Now, ttf));
                            cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            cell.Border = 0;
                            dateTable.AddCell(cell);
                            doc.Add(dateTable);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, ex.Source, MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                    finally
                    {
                        doc.Close();
                        sqlReader.Close();
                    }
                }
        }
Exemplo n.º 48
0
        private void CreateTable(DataTable dts, string path)
        {
            //定义一个Document,并设置页面大小为A4,竖向
            Document doc = new Document(PageSize.A4);

            try
            {
                //写实例
                PdfWriter.GetInstance(doc, new FileStream(path, FileMode.Create));
                // #endregion //打开document
                doc.Open();
                //载入字体
                string   str    = Application.StartupPath;//项目路径
                BaseFont baseFT = BaseFont.CreateFont(@str + "/fonts/simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

                string  filepath = "/companynemInfo.txt";
                frmMain fm       = new frmMain();
                string  name     = fm.textFileUpdate(@str + filepath);

                iTextSharp.text.Font fonttitle = new iTextSharp.text.Font(baseFT, 16); //标题字体 Paragraph
                iTextSharp.text.Font font      = new iTextSharp.text.Font(baseFT, 10); //内容字体

                //标题
                Paragraph pdftitle = new Paragraph(name + "登录日志查询结果" + "\r\n" + "(" + time1 + "-" + time2 + ")", fonttitle);
                pdftitle.Alignment = 1;
                doc.Add(pdftitle);
                //标题和内容间的空白行
                Paragraph null1 = new Paragraph("  ", fonttitle);
                null1.Leading = 10;
                doc.Add(null1);

                PdfPTable table = new PdfPTable(4);
                table.WidthPercentage = 100;//table占宽度百分比 100%
                table.SetWidths(new int[] { 10, 20, 35, 35 });
                PdfPCell cell;
                //   , "温度上限", "温度下限", "湿度上限", "湿度下限"
                string[] columnsnames = { "序号", "用户", "时间", "事件" };
                for (int i = 0; i < columnsnames.Length; i++)
                {
                    cell = new PdfPCell(new Phrase(columnsnames[i], font));
                    table.AddCell(cell);
                }

                for (int rowNum = 0; rowNum != dts.Rows.Count; rowNum++)
                {
                    table.AddCell(new Phrase((rowNum + 1).ToString(), font));
                    for (int columNum = 1; columNum != dts.Columns.Count; columNum++)
                    {
                        table.AddCell(new Phrase(dts.Rows[rowNum][columNum].ToString(), font));
                    }
                }
                doc.Add(table);
                //关闭document
                doc.Close();
                //打开PDF,看效果
                //Process.Start(path);
            }
            catch (DocumentException de)
            {
                Console.WriteLine(de.Message); Console.ReadKey();
            }
            catch (IOException io)
            {
                Console.WriteLine(io.Message); Console.ReadKey();
            }
        }
Exemplo n.º 49
0
        private void BtnPrn_Click(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            String date = "";

            date = DateTime.Now.ToString("yyyy-MM-dd");
            DataTable dt = new DataTable();

            dt = ebC.eB20DB.cntDB.selectByDate(date);
            if (dt.Rows.Count <= 0)
            {
                return;
            }

            BaseFont  bfR, bfR1;
            BaseColor clrBlack = new iTextSharp.text.BaseColor(0, 0, 0);
            String    myFont   = Environment.CurrentDirectory + "\\THSarabun.ttf";

            bfR  = BaseFont.CreateFont(myFont, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            bfR1 = BaseFont.CreateFont(myFont, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            iTextSharp.text.Font fntHead = new iTextSharp.text.Font(bfR, 12, iTextSharp.text.Font.NORMAL, clrBlack);
            var logo = iTextSharp.text.Image.GetInstance(Environment.CurrentDirectory + "\\logo.png");

            logo.SetAbsolutePosition(10, PageSize.A4.Height - 90);
            logo.ScaleAbsoluteHeight(70);
            logo.ScaleAbsoluteWidth(70);

            Document doc = new Document(PageSize.A4, 36, 36, 36, 36);

            try
            {
                if (File.Exists(Environment.CurrentDirectory + "\\report.pdf"))
                {
                    File.Delete(Environment.CurrentDirectory + "\\report.pdf");
                }

                FileStream output = new FileStream(Environment.CurrentDirectory + "\\report.pdf", FileMode.Create);
                PdfWriter  writer = PdfWriter.GetInstance(doc, output);
                doc.Open();

                doc.Add(logo);

                int i = 0, r = 0, row2 = 0, rowEnd = 24;
                r = dt.Rows.Count;
                int next = r / 24;
                for (int p = 0; p <= next; p++)
                {
                    PdfContentByte canvas = writer.DirectContent;
                    canvas.BeginText();
                    canvas.SetFontAndSize(bfR, 12);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "บริษัท เคาเตอร์ พลัส จำกัด", 100, 800, 0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "99/19 ซอยประเสริฐมนูกิจ 29 ถนนประเสริฐมนูกิจ แขวงจรเข้บัว เขตลาดพร้าว กรุงเทพฯ 10230", 100, 780, 0);
                    canvas.EndText();

                    canvas.BeginText();
                    canvas.SetFontAndSize(bfR, 18);
                    canvas.ShowTextAligned(Element.ALIGN_CENTER, "รายงานสรุปการนับเงินที่จำหน่ายจากตู้ ตามวันที่ ", PageSize.A4.Width / 2, 740, 0);
                    canvas.EndText();

                    canvas.BeginText();
                    canvas.SetFontAndSize(bfR, 16);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "ลำดับ ", 60, 720, 0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "สถานที่ ", 60, 700, 0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "จำนวนเงินที่นับได้จริง ", 60, 680, 0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "ยอดรวม ", 360, 720, 0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "รวมเงิน ", 360, 700, 0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "เงินเกิน ", 360, 680, 0);
                    canvas.ShowTextAligned(Element.ALIGN_LEFT, "เงินขาด ", 360, 660, 0);
                    canvas.EndText();

                    canvas.SaveState();
                    canvas.SetLineWidth(0.05f);
                    canvas.MoveTo(40, 640);//vertical
                    canvas.LineTo(40, 110);

                    canvas.MoveTo(40, 640);//Hericental
                    canvas.LineTo(560, 640);

                    canvas.MoveTo(560, 640);//vertical
                    canvas.LineTo(560, 110);

                    canvas.MoveTo(40, 610);//Hericental
                    canvas.LineTo(560, 610);

                    canvas.MoveTo(40, 110);//Hericental
                    canvas.LineTo(560, 110);

                    canvas.MoveTo(100, 640);//vertical
                    canvas.LineTo(100, 110);

                    canvas.MoveTo(400, 640);//vertical
                    canvas.LineTo(400, 110);

                    canvas.MoveTo(440, 640);//vertical QTY
                    canvas.LineTo(440, 110);

                    canvas.MoveTo(500, 640);//vertical Price
                    canvas.LineTo(500, 110);

                    //canvas.MoveTo(520, 640);//vertical Amount
                    //canvas.LineTo(520, 110);
                    canvas.Stroke();
                    canvas.RestoreState();
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                doc.Close();
                System.Threading.Thread.Sleep(1000);

                Process          pp = new Process();
                ProcessStartInfo s  = new ProcessStartInfo(Environment.CurrentDirectory + "\\report.pdf");
                //s.Arguments = "/c dir *.cs";
                pp.StartInfo = s;

                pp.Start();
            }
        }
Exemplo n.º 50
0
        public ActionResult reportePDF()
        {
            MemoryStream ms  = new MemoryStream();
            Document     doc = new Document(iTextSharp.text.PageSize.LETTER, 30f, 20f, 50f, 40f);
            PdfWriter    pw  = PdfWriter.GetInstance(doc, ms);

            pw.PageEvent = new HeaderFooter();

            BaseFont bf       = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, BaseFont.EMBEDDED);
            Font     fontText = new Font(bf, 12, 0, BaseColor.BLACK);


            // Abrimos el archivo
            doc.Open();
            // Agregar logo superior
            Image logo = Image.GetInstance(System.Web.HttpContext.Current.Server.MapPath("~/Content/assets/images/Logov2.png"));

            logo.ScalePercent(100f);
            logo.SetAbsolutePosition(24f, 700f);
            doc.Add(logo);
            doc.Add(Chunk.NEWLINE);

            // Agregar logo inferior
            Image inferior = Image.GetInstance(System.Web.HttpContext.Current.Server.MapPath("~/Content/assets/images/Logov2.png"));

            inferior.ScalePercent(100f);
            inferior.SetAbsolutePosition(0f, 0f);
            doc.Add(inferior);
            doc.Add(Chunk.NEWLINE);


            //Descripción del nombre de asociacion de Scouts
            Phrase parrafo = new Phrase(string.Format("Asociación de Scouts de Nicaragua", fontText));
            //PdfContentByte cb = pw.DirectContent();
            //ColumnText ct = new ColumnText(cb);
            //ct.SetSimpleColumn(parrafo,312f,530f,762f,580f,25,Element.ALIGN_CENTER);
            //ct.Go();
            PdfPTable table = new PdfPTable(3);

            table.WidthPercentage = 100;

            // Configuramos el título de las columnas de la tabla
            PdfPCell clCodigo = new PdfPCell(new Phrase("Código"));

            PdfPCell clNom_Distrito = new PdfPCell(new Phrase("Nombre Distrito"));

            PdfPCell clDescripcion = new PdfPCell(new Phrase("Descripción"));


            // Añadimos las celdas a la tabla
            table.AddCell(clCodigo);
            table.AddCell(clNom_Distrito);
            table.AddCell(clDescripcion);

            List <Distrito> distritos = db.Distritos.ToList();

            foreach (var item in distritos)
            {
                PdfPCell cel = new PdfPCell();

                cel = new PdfPCell(new Paragraph(item.Cod_Distrito));
                cel.HorizontalAlignment = Element.ALIGN_CENTER;
                table.AddCell(cel);

                cel = new PdfPCell(new Paragraph(item.Nombre_Distrito));
                cel.HorizontalAlignment = Element.ALIGN_CENTER;
                table.AddCell(cel);

                cel = new PdfPCell(new Paragraph(item.Descripcion));
                cel.HorizontalAlignment = Element.ALIGN_CENTER;
                table.AddCell(cel);
            }
            doc.Add(table);
            doc.Close();

            byte[] bytestream = ms.ToArray();
            ms = new MemoryStream();
            ms.Write(bytestream, 0, bytestream.Length);
            ms.Position = 0;

            return(new FileStreamResult(ms, "application/pdf"));
        }
Exemplo n.º 51
0
        //Exportaciones

        #region Crea_PDF
        public ActionResult CargFamPDF()
        {
            try
            {
                using (CargFam = new EmpleadosEntities())
                {
                    var ListCargFam = CargFam.Sp_Mues_CargFam().ToList();

                    MemoryStream             ms       = new MemoryStream();
                    iTextSharp.text.Document document = new iTextSharp.text.Document();
                    document.SetPageSize(PageSize.A4.Rotate());
                    document.SetMargins(14.2f, 14.2f, 29f, 31f);

                    PdfWriter pdf = PdfWriter.GetInstance(document, ms);

                    //hace la insercion del pie de pagina
                    pdf.PageEvent = new HeadFooter();

                    document.Open();
                    //insercion de imagenes
                    url = Server.MapPath("/Imagenes/bg.jpg");
                    iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(url);
                    image.ScaleToFit(140f, 120f);
                    image.Alignment = Element.ALIGN_LEFT;
                    document.Add(image);
                    // fin de insercion de imagenes

                    //fuente, tamaño y color de cabecera
                    BaseFont             bf        = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.EMBEDDED);
                    iTextSharp.text.Font fontText2 = new iTextSharp.text.Font(bf, 10, 4, BaseColor.BLUE);

                    //creacion e insercion de titulos al documento
                    iTextSharp.text.Paragraph titulo = new iTextSharp.text.Paragraph(string.Format("Listado de Cargas Familiares"), fontText2);
                    //titulo.SpacingBefore = 200;
                    //titulo.SpacingAfter = 0;
                    titulo.Alignment = 1; //0-Left, 1 middle,2 Right
                                          //inserta al documento
                    document.Add(titulo);
                    //inserta nueva linea al texto
                    document.Add(Chunk.NEWLINE);

                    //esto es para estilo de letra de la tabla
                    BaseFont bf2 = BaseFont.CreateFont(BaseFont.TIMES_BOLD, BaseFont.CP1250, BaseFont.EMBEDDED);
                    //tamaño y color
                    iTextSharp.text.Font fontText  = new iTextSharp.text.Font(bf2, 8, 0, BaseColor.BLACK);
                    iTextSharp.text.Font fontText3 = new iTextSharp.text.Font(bf2, 8, 0, BaseColor.WHITE);

                    // instancia la tabla y le indica la cantidad de columnas
                    PdfPTable table = new PdfPTable(15);

                    //indica q ancho de la hoja va a ocupar la tabla
                    table.WidthPercentage = 95;

                    // instancia para la generacion de celdas en la tabla
                    PdfPCell _cell = new PdfPCell();

                    //genera la cabecera de la tabla
                    _cell = new PdfPCell(new iTextSharp.text.Paragraph("Rut", fontText3));
                    _cell.BackgroundColor     = iTextSharp.text.BaseColor.DARK_GRAY;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    table.AddCell(_cell);

                    _cell = new PdfPCell(new iTextSharp.text.Paragraph("Nombre", fontText3));
                    _cell.BackgroundColor     = iTextSharp.text.BaseColor.DARK_GRAY;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    table.AddCell(_cell);

                    _cell = new PdfPCell(new iTextSharp.text.Paragraph("Ap. Paterno", fontText3));
                    _cell.BackgroundColor     = iTextSharp.text.BaseColor.DARK_GRAY;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    table.AddCell(_cell);

                    _cell = new PdfPCell(new iTextSharp.text.Paragraph("Ap. Materno", fontText3));
                    _cell.BackgroundColor     = iTextSharp.text.BaseColor.DARK_GRAY;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    table.AddCell(_cell);

                    _cell = new PdfPCell(new iTextSharp.text.Paragraph("Fono Movil", fontText3));
                    _cell.BackgroundColor     = iTextSharp.text.BaseColor.DARK_GRAY;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    table.AddCell(_cell);

                    _cell = new PdfPCell(new iTextSharp.text.Paragraph("Fono Fijo", fontText3));
                    _cell.BackgroundColor     = iTextSharp.text.BaseColor.DARK_GRAY;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    table.AddCell(_cell);

                    _cell = new PdfPCell(new iTextSharp.text.Paragraph("Fecha Nacimiento", fontText3));
                    _cell.BackgroundColor     = iTextSharp.text.BaseColor.DARK_GRAY;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    table.AddCell(_cell);

                    _cell = new PdfPCell(new iTextSharp.text.Paragraph("Sexo", fontText3));
                    _cell.BackgroundColor     = iTextSharp.text.BaseColor.DARK_GRAY;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    table.AddCell(_cell);

                    _cell = new PdfPCell(new iTextSharp.text.Paragraph("Dirección", fontText3));
                    _cell.BackgroundColor     = iTextSharp.text.BaseColor.DARK_GRAY;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    table.AddCell(_cell);

                    _cell = new PdfPCell(new iTextSharp.text.Paragraph("Villa", fontText3));
                    _cell.BackgroundColor     = iTextSharp.text.BaseColor.DARK_GRAY;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    table.AddCell(_cell);

                    _cell = new PdfPCell(new iTextSharp.text.Paragraph("Comuna", fontText3));
                    _cell.BackgroundColor     = iTextSharp.text.BaseColor.DARK_GRAY;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    table.AddCell(_cell);

                    _cell = new PdfPCell(new iTextSharp.text.Paragraph("Ciudad", fontText3));
                    _cell.BackgroundColor     = iTextSharp.text.BaseColor.DARK_GRAY;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    table.AddCell(_cell);

                    _cell = new PdfPCell(new iTextSharp.text.Paragraph("Correo", fontText3));
                    _cell.BackgroundColor     = iTextSharp.text.BaseColor.DARK_GRAY;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    table.AddCell(_cell);

                    _cell = new PdfPCell(new iTextSharp.text.Paragraph("Nombre Empleado", fontText3));
                    _cell.BackgroundColor     = iTextSharp.text.BaseColor.DARK_GRAY;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    table.AddCell(_cell);

                    _cell = new PdfPCell(new iTextSharp.text.Paragraph("Comentario", fontText3));
                    _cell.BackgroundColor     = iTextSharp.text.BaseColor.DARK_GRAY;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    table.AddCell(_cell);

                    //llena la tabla y ademas le da la alineacion a los datos
                    foreach (var item in ListCargFam)
                    {
                        PdfPCell _cell2 = new PdfPCell();

                        _cell2 = new PdfPCell(new iTextSharp.text.Paragraph(item.Rut_Carga, fontText));
                        _cell2.HorizontalAlignment = Element.ALIGN_CENTER;
                        table.AddCell(_cell2);

                        _cell2 = new PdfPCell(new iTextSharp.text.Paragraph(item.Nombre, fontText));
                        _cell2.HorizontalAlignment = Element.ALIGN_LEFT;
                        table.AddCell(_cell2);

                        _cell2 = new PdfPCell(new iTextSharp.text.Paragraph(item.Paterno, fontText));
                        _cell2.HorizontalAlignment = Element.ALIGN_LEFT;
                        table.AddCell(_cell2);

                        _cell2 = new PdfPCell(new iTextSharp.text.Paragraph(item.Materno, fontText));
                        _cell2.HorizontalAlignment = Element.ALIGN_LEFT;
                        table.AddCell(_cell2);

                        _cell2 = new PdfPCell(new iTextSharp.text.Paragraph(item.Fono_Movil, fontText));
                        _cell2.HorizontalAlignment = Element.ALIGN_LEFT;
                        table.AddCell(_cell2);

                        _cell2 = new PdfPCell(new iTextSharp.text.Paragraph(item.Fono_Fijo, fontText));
                        _cell2.HorizontalAlignment = Element.ALIGN_LEFT;
                        table.AddCell(_cell2);

                        _cell2 = new PdfPCell(new iTextSharp.text.Paragraph(item.Fecha_Nacimiento, fontText));
                        _cell2.HorizontalAlignment = Element.ALIGN_LEFT;
                        table.AddCell(_cell2);

                        _cell2 = new PdfPCell(new iTextSharp.text.Paragraph(item.Sexo, fontText));
                        _cell2.HorizontalAlignment = Element.ALIGN_LEFT;
                        table.AddCell(_cell2);

                        _cell2 = new PdfPCell(new iTextSharp.text.Paragraph(item.Direccion, fontText));
                        _cell2.HorizontalAlignment = Element.ALIGN_LEFT;
                        table.AddCell(_cell2);

                        _cell2 = new PdfPCell(new iTextSharp.text.Paragraph(item.Villa, fontText));
                        _cell2.HorizontalAlignment = Element.ALIGN_LEFT;
                        table.AddCell(_cell2);

                        _cell2 = new PdfPCell(new iTextSharp.text.Paragraph(item.Comuna, fontText));
                        _cell2.HorizontalAlignment = Element.ALIGN_LEFT;
                        table.AddCell(_cell2);

                        _cell2 = new PdfPCell(new iTextSharp.text.Paragraph(item.Ciudad, fontText));
                        _cell2.HorizontalAlignment = Element.ALIGN_LEFT;
                        table.AddCell(_cell2);

                        _cell2 = new PdfPCell(new iTextSharp.text.Paragraph(item.Email, fontText));
                        _cell2.HorizontalAlignment = Element.ALIGN_LEFT;
                        table.AddCell(_cell2);

                        _cell2 = new PdfPCell(new iTextSharp.text.Paragraph(item.Nombre_Empleado, fontText));
                        _cell2.HorizontalAlignment = Element.ALIGN_LEFT;
                        table.AddCell(_cell2);

                        _cell2 = new PdfPCell(new iTextSharp.text.Paragraph(item.Comentarios, fontText));
                        _cell2.HorizontalAlignment = Element.ALIGN_LEFT;
                        table.AddCell(_cell2);
                    }
                    //agrega la tabla al documento
                    document.Add(table);
                    //cierra el documento
                    document.Close();
                    //vacia la memoria(documento) hacia memory stream
                    byte[] byteStream = ms.ToArray();
                    ms = new MemoryStream();
                    ms.Write(byteStream, 0, byteStream.Length);
                    ms.Position = 0;
                    //esto permite que el archivo pdf se muestre por pantalla en el explorador y a su vez sea guardado en el disco
                    return(File(ms, "application/pdf", "ListaCargFam.pdf"));
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Error On:", ex);
                Response.StatusCode        = 500;
                Response.StatusDescription = ex.Message;
                return(Json(Response));
            }
        }
Exemplo n.º 52
0
        public void pdf_g(object sender, EventArgs e)
        {
            PageBase      pp = new PageBase();
            SqlDataReader dd = pp.Select(@"select v.matricule, p.nom+' '+p.prenom as name,ht.adr_depart,
ht.date_depart,ht.adr_fin,ht.date_fin,ht.duree,
ht.vitesse,ht.distance,a.titre+' : '+(cast( nt.Descriptione as nvarchar(max)))   as deescription
 from Historique_Trajet ht 
inner join vehicule_personnel vp on vp.vehiculeid=ht.vehiculeid  and vp.actif=1
inner join personnel p on p.personnelid=vp.personnelid
inner join vehicules v on v.vehiculeid=ht.vehiculeid 
inner join Notification nt on nt.vehiculeid=v.vehiculeid
inner join alerte a on a.alerteid=nt.alerteid
where v.vehiculeid in
    (select pv.vehiculeid from profil_vehicule pv  
  inner join profil_user pu on  pu.profilid=pv.profilid and    pu.utilisateurid='2' and pu.actif='1' 
    where pv.actif='1'   group by pv.vehiculeid  
     union  
     select gv.vehiculeid from groupe_vehicule gv 
      inner join Groupe_Profil gp on gp.groupeid=gv.groupeid and gp.actif='1'
       inner join profil_user pu on  pu.profilid=gp.profilid  and    pu.utilisateurid='2' and pu.actif='1'
         where gv.actif='1'  ) and cast(ht.date_depart AS datetime) >= '22/07/2014 08:00:00' 
 AND    cast(ht.date_depart AS datetime)  < '22/07/2014 18:00:00' and cast(ht.date_fin AS datetime) >= '22/07/2014 08:00:00' 
 AND    cast(ht.date_fin AS datetime)  < '22/07/2014 18:00:00' and v.vehiculeid='6' 
          ");
            DataTable     dt = new DataTable();

            dt.Load(dd);
            Document  document = new Document();
            PdfWriter writer   = PdfWriter.GetInstance(document, Response.OutputStream);

            document.Open();
            //   iTextSharp.text.Font font5 = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA, 5);

            iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(Server.MapPath("/Ressources/Images/logo.png"));
            jpg.ScaleToFit(80f, 50f);
            jpg.Alignment       = iTextSharp.text.Image.TEXTWRAP | iTextSharp.text.Image.ALIGN_RIGHT;
            jpg.IndentationLeft = 9f;
            jpg.SpacingAfter    = 9f;
            jpg.BorderWidthTop  = 36f;
            jpg.BorderColorTop  = Color.WHITE;
            document.Add(jpg);

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


            PdfPTable table = new PdfPTable(dt.Columns.Count);
            PdfPRow   row   = null;

            float[] widths             = new float[] { 5f, 5f, 6f, 6f, 6f, 6f, 4f, 4f, 4f, 11f };
            iTextSharp.text.Font font5 = FontFactory.GetFont("Arial", 8);
            iTextSharp.text.Font font6 = FontFactory.GetFont("Arial", 9);

            iTextSharp.text.Font font1 = FontFactory.GetFont("Arial", 18, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLUE);

            table.SetWidths(widths);

            table.WidthPercentage = 100;
            int      iCol    = 0;
            string   colname = "";
            PdfPCell cell    = new PdfPCell(new Phrase("Rapport d'activité", font1));

            cell.Colspan = dt.Columns.Count;

            cell.Border = 0;

            cell.HorizontalAlignment = 1;

            table.AddCell(cell);

            foreach (DataColumn c in dt.Columns)
            {
                table.AddCell(new Phrase(c.ColumnName, font6));
            }

            foreach (DataRow r in dt.Rows)
            {
                if (dt.Rows.Count > 0)
                {
                    table.AddCell(new Phrase(r[0].ToString(), font5));
                    table.AddCell(new Phrase(r[1].ToString(), font5));
                    table.AddCell(new Phrase(r[2].ToString(), font5));
                    table.AddCell(new Phrase(r[3].ToString(), font5));
                    table.AddCell(new Phrase(r[4].ToString(), font5));
                    table.AddCell(new Phrase(r[5].ToString(), font5));
                    table.AddCell(new Phrase(r[6].ToString(), font5));
                    table.AddCell(new Phrase(r[7].ToString(), font5));
                    table.AddCell(new Phrase(r[8].ToString(), font5));

                    table.AddCell(new Phrase(r[9].ToString(), font5));
                }
            }
            document.Add(table);
            document.Close();
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;" +

                               "filename=Rapport" + DateTime.Now.Ticks.ToString() + ".pdf");

            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Write(document);
            Response.End();
        }
Exemplo n.º 53
0
 /// <summary>
 /// Constructs an Anchor with a certain string
 /// and a certain Font.
 /// </summary>
 /// <param name="str">a string</param>
 /// <param name="font">a Font</param>
 public Anchor(string str, Font font) : base(str, font)
 {
 }
Exemplo n.º 54
0
        //--------------------------------------------------------
        protected void gvTodasLasSolicitudes_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int index, idBuscaSolicitud;

            try
            {
                //Se obtiene la celda del gridview donde se encuentra el id de la solicitud
                index = Convert.ToInt32(e.CommandArgument);
                GridViewRow row = gvTodasLasSolicitudes.Rows[index];
                HiddenField GvTxtIdSolicitud = (HiddenField)row.FindControl("IdSolicitud");
                idBuscaSolicitud = Convert.ToInt32(GvTxtIdSolicitud.Value);
            }
            catch
            {
                return;
            }
            //--------------------
            if (e.CommandName == "Consultar")
            {
                ConsultarEditarSolicitud(idBuscaSolicitud, "Consultar");
            }
            if (e.CommandName == "GenerarOficio")
            {
                nSolicitudSalidas = new N_SolicitudSalidas();
                E_SolicitudSalidasJoin solicitud   = nSolicitudSalidas.BuscaSolicitudPorIdJoin(idBuscaSolicitud);
                N_Profesor             nProfesor   = new N_Profesor();
                E_Profesor             profesorSol = nProfesor.BuscaProfesorPorId(solicitud.IdProfesor);
                Document doc = new Document(PageSize.LETTER);
                // Indicamos donde vamos a guardar el documento
                //PdfWriter writer = PdfWriter.GetInstance(doc,new FileStream(Server.MapPath("~/Resources") + "/prueba.pdf", FileMode.Create));
                //string nombreArchivo = Path.GetTempPath() + Guid.NewGuid().ToString() + ".pdf";
                string    nombreArchivo = Server.MapPath("~/OficioComisionSolicitud/") + solicitud.Folio + solicitud.CicloPeriodo + profesorSol.NumeroEmpleado + "OficioC.pdf";
                PdfWriter writer        = PdfWriter.GetInstance(doc, new FileStream(nombreArchivo, FileMode.Create));
                //---------------------
                doc.AddTitle("Oficio Comision");
                //------------------
                doc.Open();
                //---------------
                iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

                Font fuenteTitulo    = new Font(iTextSharp.text.Font.FontFamily.HELVETICA, 20, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
                Font fuenteSubtitulo = new Font(iTextSharp.text.Font.FontFamily.HELVETICA, 14, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
                // Escribimos el encabezamiento en el documento
                //doc.AddHeader("NAME","CONTENIDO");
                Paragraph tituloOficio = new Paragraph("Universidad Autónoma de Baja California", fuenteTitulo);
                tituloOficio.Alignment = Element.ALIGN_CENTER;
                doc.Add(tituloOficio);
                Paragraph subtituloOficio = new Paragraph("FACULTAD DE INGENIERIA, ARQUITECTURA Y DISEÑO", fuenteSubtitulo);
                subtituloOficio.Alignment = Element.ALIGN_CENTER;
                doc.Add(subtituloOficio);
                doc.Add(Chunk.NEWLINE);

                DateTime  diaActual   = Convert.ToDateTime(DateTime.Now);
                Paragraph infoEmision = new Paragraph("SUBDIRECCIÓN\n"
                                                      + solicitud.CicloPeriodo + " ASUNTO: Oficio Comisión\n" +
                                                      "Ensenada, B,C, a " + diaActual, fuenteSubtitulo);
                infoEmision.Alignment = Element.ALIGN_RIGHT;
                doc.Add(infoEmision);
                doc.Add(Chunk.NEWLINE);
                doc.Add(Chunk.NEWLINE);

                Paragraph encabezado = new Paragraph(profesorSol.APaternoProfesor + " " + profesor.AMaternoProfesor + " " + profesorSol.NombreProfesor + "\n"
                                                     + "No. De empleado: " + profesorSol.NumeroEmpleado, fuenteSubtitulo);
                encabezado.Alignment = Element.ALIGN_LEFT;
                doc.Add(encabezado);
                Paragraph encabezado2 = new Paragraph("PRESENTE", fuenteTitulo);
                encabezado2.Alignment = Element.ALIGN_LEFT;
                doc.Add(encabezado2);
                doc.Add(Chunk.NEWLINE);

                doc.Add(new Paragraph("Por medio del presente la subdirección a mi cargo comisiona a ustede el dia " + diaActual
                                      + " del año en curso"));
                doc.Add(Chunk.NEWLINE);

                Paragraph motivo = new Paragraph("MOTIVO: Solicitud de Salida", fuenteSubtitulo);
                motivo.Alignment = Element.ALIGN_LEFT;
                doc.Add(motivo);
                doc.Add(Chunk.NEWLINE);

                doc.Add(new Paragraph("     Asisimismo, se le solicita entregar a este Dependencia el reporte de actividades o la constancia respectiva" +
                                      "de forma impresa o electrónica"));
                doc.Add(Chunk.NEWLINE);
                doc.Add(Chunk.NEWLINE);

                doc.Add(new Paragraph("En espera que reciba de conformidad, me despido de usted con un cordial saludo."));
                doc.Add(Chunk.NEWLINE);
                doc.Add(Chunk.NEWLINE);

                Paragraph atentamente = new Paragraph("ATENTAMENTE", fuenteTitulo);
                atentamente.Alignment = Element.ALIGN_CENTER;
                doc.Add(atentamente);
                Paragraph atentamente2 = new Paragraph("\"POR LA REALIZACION PLENA DEL HOMBRE\"", fuenteSubtitulo);
                atentamente2.Alignment = Element.ALIGN_CENTER;
                doc.Add(atentamente2);
                doc.Add(Chunk.NEWLINE);
                doc.Add(Chunk.NEWLINE);

                Paragraph responable = new Paragraph(profesor.NombreProfesor + " " + profesor.APaternoProfesor + " " + profesor.AMaternoProfesor + "\n"
                                                     + cargoProfesor, fuenteTitulo);
                responable.Alignment = Element.ALIGN_CENTER;
                doc.Add(responable);



                doc.Close();
                writer.Close();
                //Server.
                //string script = string.Format("abrirPDF('{0}')", nombreArchivo);

                /*string script = string.Format("abrirPDF('{0}')", "../Resoruces/prueba.pdf");
                 * ScriptManager.RegisterStartupScript(Page, Page.ClientScript.GetType(), "abrirPDF", script, true);*/
                //Server.Transfer(nombreArchivo);
            }
            TABSeleccionada.Value = "administrador";
        }
Exemplo n.º 55
0
        void pdf()
        {
            try
            {
                SaveFileDialog fichero = new SaveFileDialog();
                fichero.FileName = "PDF";
                fichero.Filter   = "Pdf(*.pdf)|*.pdf";
                if (fichero.ShowDialog() == DialogResult.OK)
                {
                    Document  doc = new Document(PageSize.LETTER, 20, 20, 20, 20);
                    PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(fichero.FileName, FileMode.Create));
                    doc.Open();
                    PdfPTable encabezado = new PdfPTable(3);
                    var       chartimage = new MemoryStream();
                    encabezado.SetWidthPercentage(new float[] { 170, 170, 170 }, PageSize.LETTER);
                    encabezado.AddCell(iTextSharp.text.Image.GetInstance("imagenes/Logo.png"));
                    encabezado.AddCell(new Paragraph("E-Lectonic Inc. \n \nPartidos", FontFactory.GetFont("Arial", 11, iTextSharp.text.Font.NORMAL)));
                    encabezado.AddCell(new Paragraph("Partidos\n Voto Electronico\n", FontFactory.GetFont("Arial", 11, iTextSharp.text.Font.NORMAL)));
                    foreach (PdfPCell celda in encabezado.Rows[0].GetCells())
                    {
                        celda.BackgroundColor     = BaseColor.WHITE;
                        celda.HorizontalAlignment = 5;
                        celda.VerticalAlignment   = 5;
                        celda.Border            = 0;
                        celda.BorderWidthBottom = 4f;
                        celda.BorderWidthTop    = 4f;
                        celda.BorderColorBottom = new BaseColor(80, 80, 80);
                        celda.BorderColorTop    = new BaseColor(80, 80, 80);
                    }
                    doc.Add(encabezado);
                    doc.Add(new Paragraph(" "));
                    iTextSharp.text.Font fontTable = FontFactory.GetFont("Arial", 11, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
                    PdfPTable            table     = new PdfPTable(dataGridView1.Columns.Count);
                    table.DefaultCell.Phrase = new Phrase()
                    {
                        Font = fontTable
                    };
                    for (int j = 0; j < dataGridView1.Columns.Count; j++)
                    {
                        table.AddCell(new Phrase(dataGridView1.Columns[j].HeaderText, fontTable));
                        table.SetWidthPercentage(new float[] { 100, 100, }, PageSize.LETTER);
                    }
                    table.HeaderRows = 1;

                    for (int i = 0; i < dataGridView1.Rows.Count; i++)
                    {
                        foreach (PdfPCell celdas in table.Rows[i].GetCells())
                        {
                            celdas.BorderWidth = 1f;
                            celdas.BorderColor = new BaseColor(80, 80, 80);
                        }
                        foreach (PdfPCell celdas in table.Rows[0].GetCells())
                        {
                            celdas.BorderWidth     = 1f;
                            celdas.BackgroundColor = new BaseColor(129, 211, 255);
                        }
                        for (int k = 0; k < dataGridView1.Columns.Count; k++)
                        {
                            if (dataGridView1[k, i].Value != null)
                            {
                                table.AddCell(new Phrase(dataGridView1[k, i].Value.ToString(), fontTable));
                            }
                        }
                    }
                    doc.Add(table);
                    doc.Add(new Paragraph(" "));
                    chart1.SaveImage(chartimage, ChartImageFormat.Png);
                    iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance(chartimage.GetBuffer());
                    image1.Alignment = Element.ALIGN_CENTER;
                    doc.Add(image1);
                    Paragraph pie = new Paragraph("¡Gracias por utilizar nuestro sistema!", FontFactory.GetFont("Arial", 9, iTextSharp.text.Font.BOLDITALIC));
                    pie.Alignment = Element.ALIGN_CENTER;
                    doc.Add(pie);
                    doc.Close();
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Error al exportar la informacion debido a: " + e.ToString());
            }
        }
Exemplo n.º 56
0
        public void DoPdf(object sender, EventArgs e)
        {
            string _dateDebut = this.startdate.Text.ToString() + " " + hd.SelectedItem.Text;
            string _dateFin   = this.enddate.Text.ToString() + " " + hf.SelectedItem.Text;
            string _id        = _idv;
            ////string _contact = "L'Etat du moteur";
            ////string _speed = "Vitesse";

            string repp = "select v.matricule, p.nom+' '+p.prenom as name,ht.adr_depart,"
                          + " ht.date_depart,ht.adr_fin,ht.date_fin,ht.duree,"
                          + " ht.vitesse,ht.distance,a.titre+' : '+(cast( nt.Descriptione as nvarchar(max)))   as Alarme from Historique_Trajet ht "
                          + " inner join vehicule_personnel vp on vp.vehiculeid=ht.vehiculeid  and vp.actif=1"
                          + " inner join personnel p on p.personnelid=vp.personnelid"
                          + " inner join vehicules v on v.vehiculeid=ht.vehiculeid "
                          + " inner join Notification nt on nt.vehiculeid=v.vehiculeid"
                          + " inner join alerte a on a.alerteid=nt.alerteid"
                          + "  where v.vehiculeid in"
                          + "   (select pv.vehiculeid from profil_vehicule pv  "
                          + "  inner join profil_user pu on  pu.profilid=pv.profilid and   pu.utilisateurid='" + this.getCurrentUser().getUserId() + "' and pu.actif='1' "
                          + "   where pv.actif='1'   group by pv.vehiculeid  "
                          + "   union  "
                          + "    select gv.vehiculeid from groupe_vehicule gv "
                          + "     inner join Groupe_Profil gp on gp.groupeid=gv.groupeid and gp.actif='1'"
                          + "     inner join profil_user pu on  pu.profilid=gp.profilid  and    pu.utilisateurid='" + this.getCurrentUser().getUserId() + "' and pu.actif='1'"
                          + "       where gv.actif='1'  ) and cast(ht.date_depart AS datetime) >= '" + _dateDebut
                          + "'  AND    cast(ht.date_depart AS datetime)  < '" + _dateFin + "' and v.vehiculeid=" + _id;
            //  string _req = "select * from notification where idNoti <19 ";


            DataTable dat = GetData(repp);

            if (dat.Rows.Count > 0)
            {
                DataRow  dr         = dat.Rows[0];
                Document document   = new Document(PageSize.A4, 88f, 88f, 10f, 10f);
                Font     NormalFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, Color.BLACK);
                using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
                {
                    float[] widths             = new float[] { 5f, 5f, 6f, 6f, 6f, 6f, 4f, 4f, 4f, 11f };
                    iTextSharp.text.Font font5 = FontFactory.GetFont("Arial", 7);
                    iTextSharp.text.Font font6 = FontFactory.GetFont("Arial", 9);

                    PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
                    Phrase    phrase = null;
                    PdfPCell  cell   = null;
                    PdfPTable table  = null;
                    PdfPTable table2 = null;
                    Color     color  = null;

                    document.Open();

                    table             = new PdfPTable(2);
                    table.TotalWidth  = 800f;
                    table.LockedWidth = true;
                    table.SetWidths(new float[] { 0.4f, 0.6f });
                    double somkm = 0;
                    double tpm   = 0;
                    double vts   = 0;
                    int    ii    = 0;
                    foreach (DataRow row in dat.Rows)
                    {
                        somkm += (double)row["distance"];
                        tpm   += (double)row["duree"];
                        vts   += (double)row["vitesse"];
                        ii++;
                    }

                    vts = vts / ii;
                    //Company Logo
                    cell = ImageCell("~/Ressources/Images/logo.png", 70f, PdfPCell.ALIGN_CENTER);
                    table.AddCell(cell);

                    //Company Name and Address
                    phrase = new Phrase();
                    phrase.Add(new Chunk(" \n", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));
                    phrase.Add(new Chunk(" \n", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));

                    phrase.Add(new Chunk("Le rapport d'activité \n\n", FontFactory.GetFont("Arial", 16, Font.BOLD, Color.GRAY)));
                    phrase.Add(new Chunk(" \n", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));
                    phrase.Add(new Chunk("Reference vehicule :" + _idv, FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));
                    phrase.Add(new Chunk(" \n", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));

                    phrase.Add(new Chunk("De : " + startdate.Text, FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));
                    phrase.Add(new Chunk(" \n", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));
                    phrase.Add(new Chunk("A  : " + enddate.Text, FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));
                    phrase.Add(new Chunk(" \n", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));
                    phrase.Add(new Chunk("Kilometrage : " + somkm + " KM", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));
                    phrase.Add(new Chunk(" \n", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));

                    TimeSpan tm = TimeSpan.FromMinutes(tpm);
                    phrase.Add(new Chunk("Temps en marche : " + tm + " (J.hh:mm:ss) ", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));
                    phrase.Add(new Chunk(" \n", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));

                    DateTime d1  = DateTime.ParseExact(startdate.Text + " 00:00:00", "dd/MM/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
                    DateTime d2  = DateTime.ParseExact(enddate.Text + " 00:00:00", "dd/MM/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
                    TimeSpan ts  = d2 - d1;
                    TimeSpan def = ts - tm;

                    phrase.Add(new Chunk("Temps en arret : " + def + " (J.hh:mm:ss )", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));
                    phrase.Add(new Chunk(" \n", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));

                    phrase.Add(new Chunk("Vitesse moyenne : " + vts + " Km/h", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));
                    phrase.Add(new Chunk(" \n", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));

                    phrase.Add(new Chunk("\n", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));
                    phrase.Add(new Chunk(" \n", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));
                    phrase.Add(new Chunk(" \n", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));
                    phrase.Add(new Chunk(" \n", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));
                    phrase.Add(new Chunk(" \n", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));
                    cell = PhraseCell(phrase, PdfPCell.ALIGN_LEFT);
                    cell.VerticalAlignment = PdfCell.ALIGN_TOP;
                    table.AddCell(cell);

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


                    phrase.Add(new Chunk(" \n", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));
                    phrase.Add(new Chunk("\n", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));
                    phrase.Add(new Chunk(" \n", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));
                    phrase.Add(new Chunk(" \n", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));
                    phrase.Add(new Chunk(" \n", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));
                    phrase.Add(new Chunk(" \n", FontFactory.GetFont("Arial", 10, Font.NORMAL, Color.BLACK)));
                    cell = PhraseCell(phrase, PdfPCell.ALIGN_LEFT);
                    cell.VerticalAlignment = PdfCell.ALIGN_TOP;
                    table.AddCell(cell);



                    document.Add(table);



                    //Separater Line
                    table2                 = new PdfPTable(dat.Columns.Count);
                    table2.TotalWidth      = 500f;
                    table2.LockedWidth     = true;
                    table2.WidthPercentage = 100;
                    table2.SetWidths(widths);


                    //table2.SetWidths(new float[] { 0.4f, 0.6f });


                    for (int j = 0; j < dat.Columns.Count; j++)
                    {
                        table2.AddCell(new Phrase(dat.Columns[j].ColumnName, font6));
                    }

                    table2.HeaderRows = 1;


                    for (int i = 0; i < dat.Rows.Count; i++)
                    {
                        for (int k = 0; k < dat.Columns.Count; k++)
                        {
                            if (dat.Rows[i][k] != null)
                            {
                                table2.AddCell(new Phrase(dat.Rows[i][k].ToString(), font5));
                            }
                        }
                    }

                    string msg1 = "brrrrrr";
                    document.Add(table2);
                    document.Close();
                    byte[] bytes = memoryStream.ToArray();
                    memoryStream.Close();
                    Response.Clear();
                    Response.ContentType = "application/pdf";
                    Response.AddHeader("Content-Disposition", "attachment; filename=Rapport" + DateTime.Now.Ticks + ".pdf");
                    Response.Write(msg1);
                    Response.Buffer = true;
                    Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    Response.BinaryWrite(bytes);
                    Response.End();
                    Response.Close();
                }
            }
            else
            {
                System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('Aucun Rapport trouver dans cette periode ! ')</SCRIPT>");
            }
        }
Exemplo n.º 57
0
 /// <summary>
 /// Constructs an Anchor with a certain leading,
 /// a certain string and a certain Font.
 /// </summary>
 /// <param name="leading">the leading</param>
 /// <param name="str">a string</param>
 /// <param name="font">a Font</param>
 public Anchor(float leading, string str, Font font) : base(leading, str, font)
 {
 }
Exemplo n.º 58
0
        public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)
        {
            base.OnEndPage(writer, document);

            iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
            iTextSharp.text.Font baseFontBig    = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 14f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);
            iTextSharp.text.Font baseFontBold   = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);

            BaseFont baseFont = BaseFont.CreateFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

            if (writer.PageNumber == 1)
            {
                //Create PdfTable object
                PdfPTable pdfTab = new PdfPTable(3);

                //Row 2
                Phrase phrase = new Phrase();
                phrase.Add(new Chunk(recordHeader, language == "en-US" ? new Font(Font.FontFamily.TIMES_ROMAN, 10f, Font.NORMAL, BaseColor.BLACK) : new Font(baseFont, 10f, Font.NORMAL, BaseColor.BLACK)));
                phrase.Add(new Chunk(" " + startDate + " ", new Font(Font.FontFamily.TIMES_ROMAN, 10f, Font.NORMAL, BaseColor.BLACK)));
                phrase.Add(new Chunk(To, language == "en-US" ? new Font(Font.FontFamily.TIMES_ROMAN, 10f, Font.NORMAL, BaseColor.BLACK) : new Font(baseFont, 12f, Font.NORMAL, BaseColor.BLACK)));
                phrase.Add(new Chunk(" " + endDate, new Font(Font.FontFamily.TIMES_ROMAN, 10f, Font.NORMAL, BaseColor.BLACK)));

                PdfPCell pdfCell4 = new PdfPCell(phrase);
                pdfCell4.PaddingLeft = 70f;
                //Row 3

                iTextSharp.text.Image myImage = iTextSharp.text.Image.GetInstance(logoPath);
                myImage.ScaleToFit(50f, 50f);

                PdfPCell pdfCell5 = new PdfPCell(new Phrase(RenewalHeader, language == "en-US" ? baseFontBig : new Font(baseFont, 14f, 1, BaseColor.BLACK)));
                pdfCell5.PaddingTop  = 0f;
                pdfCell5.PaddingLeft = 70f;
                pdfCell5.Top         = 0f;
                PdfPCell pdfCell6 = new PdfPCell();
                pdfCell6.PaddingTop = 0f;
                pdfCell6.Top        = 0f;
                PdfPCell pdfCell7 = new PdfPCell(myImage);
                pdfCell7.Top          = 0f;
                pdfCell7.PaddingTop   = 4f;
                pdfCell7.PaddingRight = 10f;


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


                pdfCell4.VerticalAlignment = Element.ALIGN_TOP;
                pdfCell5.VerticalAlignment = Element.ALIGN_TOP;
                pdfCell6.VerticalAlignment = Element.ALIGN_TOP;
                pdfCell7.VerticalAlignment = Element.ALIGN_TOP;


                pdfCell4.Colspan = 3;

                pdfCell4.Border = 0;
                pdfCell5.Border = 0;
                pdfCell6.Border = 0;
                pdfCell7.Border = 0;

                pdfTab.AddCell(pdfCell5);
                pdfTab.AddCell(pdfCell6);
                pdfTab.AddCell(pdfCell7);

                if (!string.IsNullOrEmpty(fullName))
                {
                    PdfPCell pdfCell8 = new PdfPCell(new Phrase(fullName, baseFontBold));
                    pdfCell8.PaddingLeft         = 70f;
                    pdfCell8.HorizontalAlignment = Element.ALIGN_LEFT;
                    pdfCell8.VerticalAlignment   = Element.ALIGN_TOP;
                    pdfCell8.Colspan             = 3;
                    pdfCell8.Border = 0;
                    pdfTab.AddCell(pdfCell8);
                }
                else
                {
                    PdfPCell pdfCell8 = new PdfPCell(new Phrase(EmailId, baseFontBold));
                    pdfCell8.PaddingLeft         = 70f;
                    pdfCell8.HorizontalAlignment = Element.ALIGN_LEFT;
                    pdfCell8.VerticalAlignment   = Element.ALIGN_TOP;
                    pdfCell8.Colspan             = 3;
                    pdfCell8.Border = 0;
                    pdfTab.AddCell(pdfCell8);
                    PdfPCell pdfCell9 = new PdfPCell(new Phrase(Message, language == "en-US" ? new Font(Font.FontFamily.TIMES_ROMAN, 10f, Font.ITALIC, BaseColor.BLACK) : new Font(baseFont, 10f, Font.ITALIC, BaseColor.BLACK)));
                    pdfCell9.PaddingLeft         = 70f;
                    pdfCell9.PaddingBottom       = 10f;
                    pdfCell9.HorizontalAlignment = Element.ALIGN_LEFT;
                    pdfCell9.VerticalAlignment   = Element.ALIGN_TOP;
                    pdfCell9.Colspan             = 3;
                    pdfCell9.Border = 0;
                    pdfTab.AddCell(pdfCell9);
                }

                pdfTab.AddCell(pdfCell4);
                pdfTab.TotalWidth      = document.PageSize.Width;
                pdfTab.WidthPercentage = 100;

                //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable
                //first param is start row. -1 indicates there is no end row and all the rows to be included to write
                //Third and fourth param is x and y position to start writing
                if (!string.IsNullOrEmpty(fullName))
                {
                    pdfTab.WriteSelectedRows(0, -1, 0, document.PageSize.Height - 30, writer.DirectContent);
                }
                else
                {
                    pdfTab.WriteSelectedRows(0, -1, 0, document.PageSize.Height, writer.DirectContent);
                }
            }
            else
            {
            }
        }
        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);
                }
            }
        }
Exemplo n.º 60
-6
// ---------------------------------------------------------------------------    
    /**
     * Manipulates a PDF file src with the file dest as result
     * @param src the original PDF
     */
    public byte[] ManipulatePdf(byte[] src) {
    // Create a table with named actions
      Font symbol = new Font(Font.FontFamily.SYMBOL, 20);
      PdfPTable table = new PdfPTable(4);
      table.DefaultCell.Border = Rectangle.NO_BORDER;
      table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
      Chunk first = new Chunk( ((char)220).ToString() , symbol);
      first.SetAction(new PdfAction(PdfAction.FIRSTPAGE));
      table.AddCell(new Phrase(first));
      Chunk previous = new Chunk( ((char)172).ToString(), symbol);
      previous.SetAction(new PdfAction(PdfAction.PREVPAGE));
      table.AddCell(new Phrase(previous));
      Chunk next = new Chunk( ((char)174).ToString(), symbol);
      next.SetAction(new PdfAction(PdfAction.NEXTPAGE));
      table.AddCell(new Phrase(next));
      Chunk last = new Chunk( ((char)222).ToString(), symbol);
      last.SetAction(new PdfAction(PdfAction.LASTPAGE));
      table.AddCell(new Phrase(last));
      table.TotalWidth = 120;
      
      // Create a reader
      PdfReader reader = new PdfReader(src);
      using (MemoryStream ms = new MemoryStream()) {
        // Create a stamper
        using (PdfStamper stamper = new PdfStamper(reader, ms)) {
          // Add the table to each page
          PdfContentByte canvas;
          for (int i = 0; i < reader.NumberOfPages; ) {
            canvas = stamper.GetOverContent(++i);
            table.WriteSelectedRows(0, -1, 696, 36, canvas);
          }
        }
        return ms.ToArray();
      }    
    }