AddCreator() публичный Метод

Adds the creator to a Document.
public AddCreator ( string creator ) : bool
creator string the name of the creator
Результат bool
Пример #1
18
        public ReportPdf(Stream Output, Layout Layout, Template Template, Dictionary<string, string> ConfigParams)
            : base(Output, Layout, Template, ConfigParams)
        {
            Rectangle pageSize = new Rectangle(mm2pt(Template.PageSize.Width), mm2pt(Template.PageSize.Height));

            // Initialization
            m_Document = new Document(pageSize, mm2pt(Template.Margin.Left), mm2pt(Template.Margin.Right), mm2pt(Template.Margin.Top), mm2pt(Template.Margin.Bottom));
            m_Writer = PdfWriter.GetInstance(m_Document, Output);

            m_Document.AddCreationDate();
            m_Document.AddCreator("StrengthReport http://dev.progterv.info/strengthreport) and KeePass (http://keepass.info)");
            m_Document.AddKeywords("report");
            m_Document.AddTitle(Layout.Title+" (report)");

            // Header
            HeaderFooter header = new HeaderFooter(new Phrase(Layout.Title+", "+DateTime.Now.ToString(), m_Template.ReportFooter.getFont()), false);
            header.Alignment = Template.ReportFooter.getAlignment();
            m_Document.Header = header;

            // Footer
            HeaderFooter footer = new HeaderFooter(new Phrase(new Chunk("Page ", m_Template.ReportFooter.getFont())), new Phrase(new Chunk(".", m_Template.ReportFooter.getFont())));
            footer.Alignment = Template.ReportFooter.getAlignment();
            m_Document.Footer = footer;

            // TODO: Metadata
            // Open document
            m_Document.Open();

            // Report Heading
            {
                PdfPTable reportTitle = new PdfPTable(1);
                PdfPCell titleCell = new PdfPCell(new Phrase(Layout.Title, m_Template.ReportHeader.getFont()));
                titleCell.Border = 0;
                titleCell.FixedHeight = mm2pt(m_Template.ReportHeader.Height);
                titleCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                titleCell.HorizontalAlignment = m_Template.ReportHeader.getAlignment();
                reportTitle.AddCell(titleCell);
                reportTitle.WidthPercentage = 100;
                m_Document.Add(reportTitle);
            }

            // Create main table
            m_Table = new PdfPTable(Layout.GetColumnWidths());
            m_Table.WidthPercentage = 100;
            m_Table.HeaderRows = 1;
            foreach (LayoutElement element in Layout) {
                PdfPCell cell = new PdfPCell(new Phrase(element.Title, m_Template.Header.getFont()));
                cell.BackgroundColor = m_Template.Header.Background.ToColor();
                cell.MinimumHeight = mm2pt(m_Template.Header.Height);
                cell.VerticalAlignment = Element.ALIGN_MIDDLE;
                m_Table.AddCell(cell);
            }

            m_colorRow = new CMYKColor[] { m_Template.Row.BackgroundA.ToColor(), m_Template.Row.BackgroundB.ToColor() };
        }
Пример #2
5
        private void btnCreateReport_Click(object sender, EventArgs e)
        {
            // _______________________________________________________1_______________________________________________________
            // Setting pagetype, margins and encryption
            iTextSharp.text.Rectangle pageType = iTextSharp.text.PageSize.A4;
            float marginLeft = 72;
            float marginRight = 36;
            float marginTop = 60;
            float marginBottom = 50;
            String reportName = "Test.pdf";

            Document report = new Document(pageType, marginLeft, marginRight, marginTop, marginBottom);
            PdfWriter writer = PdfWriter.GetInstance(report, new FileStream(reportName, FileMode.Create));
            //writer.SetEncryption(PdfWriter.STRENGTH40BITS, "Good", "Bad", PdfWriter.ALLOW_COPY);
            report.Open();

            // _______________________________________________________2_______________________________________________________
            // Setting Document properties(Meta data)
            // 1. Title
            // 2. Subject
            // 3. Keywords
            // 4. Creator
            // 5. Author
            // 6. Header
            report.AddTitle("Employee Details Report");
            report.AddSubject("This file is generated for administrative use only");
            report.AddKeywords("Civil Security Department, Employee Management System, Version 1.0.0, Report Generator");
            report.AddCreator("Ozious Technologies");
            report.AddAuthor("Eranga Heshan");
            report.AddHeader("Owner", "Civil Security Department");

            // _______________________________________________________3_______________________________________________________
            // Setup the font factory
            /*
            int totalFonts = FontFactory.RegisterDirectory("C:\\WINDOWS\\Fonts");
            StringBuilder sb = new StringBuilder();
            foreach (string fontname in FontFactory.RegisteredFonts) { sb.Append(fontname + "\n"); }
            report.Add(new Paragraph("All Fonts:\n" + sb.ToString()));
            */
            iTextSharp.text.Font fontHeader_1 = FontFactory.GetFont("Calibri", 30, iTextSharp.text.Font.BOLD, new iTextSharp.text.BaseColor(0, 0, 0));
            iTextSharp.text.Font fontHeader_2 = FontFactory.GetFont("Calibri", 15, iTextSharp.text.Font.BOLD, new iTextSharp.text.BaseColor(125, 125, 125));

            // _______________________________________________________x_______________________________________________________
            // Create header
            PdfContentByte cb = writer.DirectContent;
            cb.MoveTo(marginLeft, marginTop);
            cb.LineTo(500, marginTop);
            cb.Stroke();

            Paragraph paraHeader_1 = new Paragraph("Civil Security Department", fontHeader_1);
            paraHeader_1.Alignment = Element.ALIGN_CENTER;
            paraHeader_1.SpacingAfter = 0f;
            report.Add(paraHeader_1);

            Paragraph paraHeader_2 = new Paragraph("Employee Detailed Report", fontHeader_2);
            paraHeader_2.Alignment = Element.ALIGN_CENTER;
            paraHeader_2.SpacingAfter = 10f;
            report.Add(paraHeader_2);

            // _______________________________________________________x_______________________________________________________
            // Adding employee image
            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imgEmployee.ImageLocation);
            img.ScaleToFit(100f, 100f);
            img.Border = iTextSharp.text.Rectangle.BOX;
            img.BorderColor = iTextSharp.text.BaseColor.BLACK;
            img.BorderWidth = 5f;
            img.Alignment = iTextSharp.text.Image.TEXTWRAP | iTextSharp.text.Image.ALIGN_RIGHT | iTextSharp.text.Image.ALIGN_TOP;
            img.IndentationLeft = 50f;
            img.SpacingAfter = 20f;
            img.SpacingBefore = 20f;
            report.Add(img);

            Paragraph para1 = new Paragraph("Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... Testing... ");
            para1.Alignment = Element.ALIGN_JUSTIFIED;
            report.Add(para1);

            report.Close();
            this.Close();
        }
 /// <summary>
 /// 读取或创建Pdf文档并打开写入文件流
 /// </summary>
 /// <param name="fileName"></param>
 /// <param name="folderPath"></param>
 public Document GetOrCreatePDF(string fileName, string folderPath)
 {
     string filePath = folderPath + fileName;
     FileStream fs = null;
     if (!File.Exists(filePath))
     {
         fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
     }
     else
     {
         fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.None);
     }
     //获取A4纸尺寸
     Rectangle rec = new Rectangle(PageSize.A4);
     Document doc = new Document(rec);
     //创建一个 iTextSharp.text.pdf.PdfWriter 对象: 它有助于把Document书写到特定的FileStream:
     PdfWriter writer = PdfWriter.GetInstance(doc, fs);
     doc.AddTitle(fileName.Remove(fileName.LastIndexOf('.')));
     doc.AddSubject(fileName.Remove(fileName.LastIndexOf('.')));
     doc.AddKeywords("Metadata, iTextSharp 5.4.4, Chapter 1, Tutorial");
     doc.AddCreator("MCS");
     doc.AddAuthor("Chingy");
     doc.AddHeader("Nothing", "No Header");
     //打开 Document:
     doc.Open();
     ////关闭 Document:
     //doc.Close();
     return doc;
 }
Пример #4
1
        private static void Main()
        {
            const string path = @"C:\Users\Santhosh\AppData\test.pdf";
            if (File.Exists(path))
                File.Delete(path);
            var doc = new Document();
            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(path, FileMode.Create));
            // Metadata
            doc.AddCreator("");
            doc.AddTitle("General Receipt");
            // Add content
            doc.Open();

            PdfContentByte cb = writer.DirectContent;

            cb.SetLineWidth(0.1f);
            cb.Rectangle(50f, 300f, 500f, 70f);
            cb.Stroke();

            doc.Close();
        }
Пример #5
1
        /// <summary>
        /// Render all data add and writes it to the specified writer
        /// </summary>
        /// <param name="model">
        /// The model to render
        /// </param>
        /// <param name="os">
        /// The output to write to
        /// </param>
        public override void RenderAllTables(IDataSetModel model, Stream os)
        {
            // TODO check the number of horizontal & vertical key values to determine the orientation of the page
            var doc = new Document(this._pageSize, 80, 50, 30, 65);

            // This doesn't seem to do anything...
            doc.AddHeader(Markup.HTML_ATTR_STYLESHEET, "style/pdf.css");
            doc.AddCreationDate();
            doc.AddCreator("NSI .NET Client");
            try
            {
                PdfWriter.GetInstance(doc, os);
                doc.Open();
                this.WriteTableModels(model, doc);
            }
            catch (DocumentException ex)
            {
                Trace.Write(ex.ToString());
                LogError.Instance.OnLogErrorEvent(ex.ToString());
            }
            catch (DbException ex)
            {
                Trace.Write(ex.ToString());
                LogError.Instance.OnLogErrorEvent(ex.ToString());
            }
            finally
            {
                if (doc.IsOpen())
                {
                    doc.Close();
                }
            }
        }
Пример #6
0
        //Alım Geçmişi Pdf Rapor Butonu
        private void PdfButton_Click(object sender, EventArgs e)
        {
            iTextSharp.text.Document pdfDosya = new iTextSharp.text.Document();

            PdfWriter.GetInstance(pdfDosya, new FileStream("D:Rapor.pdf", FileMode.Create));
            pdfDosya.Open();
            pdfDosya.AddCreator("Swap - Modern Dünyada Tarıma Dair Alışveriş");
            pdfDosya.AddAuthor("Kullanıcı");
            pdfDosya.AddTitle("SATIN ALMA RAPORU");

            SqlCommand     komut = new SqlCommand("Select * From AlimKayitTablosu Where Tarih BETWEEN @t1 and @t2 and KullaniciID=" + Login.UserId, baglanti.baglanti());
            SqlDataAdapter data  = new SqlDataAdapter(komut);

            data.SelectCommand.Parameters.AddWithValue("@t1", StartDatePicker.Value);
            data.SelectCommand.Parameters.AddWithValue("@t2", EndDatePicker.Value);
            SqlDataReader oku = komut.ExecuteReader();

            string id, tarih, miktar, alimtutar, komisyon, metin;

            metin = "KullaniciID / Tarih / Miktar / AlimTutari / UygulamaKomsiyon \n";
            pdfDosya.Add(new Paragraph(metin));
            while (oku.Read())
            {
                id        = Convert.ToString(oku["KullaniciID"]);
                tarih     = Convert.ToString(oku["Tarih"]);
                miktar    = Convert.ToString(oku["Miktar"]);
                alimtutar = Convert.ToString(oku["AlimTutari"]);
                komisyon  = Convert.ToString(oku["UygulamaKomisyonu"]);
                metin     = id + "  -  " + tarih + "  -  " + miktar + "  -  " + alimtutar + "  -  " + komisyon + "\n";
                pdfDosya.Add(new Paragraph(metin));
            }
            pdfDosya.Close();
            baglanti.baglanti().Close();
        }
Пример #7
0
        public void CreatePDF()
        {
            System.IO.FileStream fs = new FileStream("GeneratedDocument.pdf", FileMode.Create);

            iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.A4, 25, 25, 30, 30);

            PdfWriter writer = PdfWriter.GetInstance(document, fs);

            document.AddAuthor("UCV");

            document.AddCreator("UCV");

            document.AddKeywords("Note");

            document.AddSubject("Situatie Scolara");

            document.AddTitle("Situatie scolara");

            document.Open();

            document.Close();

            writer.Close();

            fs.Close();
        }
Пример #8
0
        public void CreatePdf(Project project, Stream writeStream)
        {
            var document = new Document();
            var writer = PdfWriter.GetInstance(document, writeStream);

            // landscape
            document.SetPageSize(PageSize.A4.Rotate());
            document.SetMargins(36f, 36f, 36f, 36f); // 0.5 inch margins

            // metadata
            document.AddCreator("EstimatorX.com");
            document.AddKeywords("estimation");
            document.AddAuthor(project.Creator);
            document.AddSubject(project.Name);
            document.AddTitle(project.Name);
            
            document.Open();

            AddName(project, document);
            AddDescription(project, document);
            AddAssumptions(project, document);
            AddFactors(project, document);
            AddTasks(project, document);
            AddSummary(project, document);

            writer.Flush();
            document.Close();
        }
        private void btn_Update_Click(object sender, EventArgs e)
        {
            //the library for create a new pdf document
            iTextSharp.text.Document report = new iTextSharp.text.Document();
            //file path of newly created pdf file to save
            PdfWriter.GetInstance(report, new FileStream(@"C:\Users\Asus\Desktop\UPLOADFILES\" + textboxFileName.Text, FileMode.Create));
            //Author name, need for create a new pdf document
            report.AddAuthor(lbl_Author.Text);
            //Creation Date, need for create a new pdf document
            report.AddCreationDate();
            //Creator, need for create a new pdf document
            report.AddCreator(lbl_Creator.Text);
            //Subject, need for create a new pdf document
            report.AddSubject(lbl_Subject.Text);
            //Keywords, need for create a new pdf document
            report.AddKeywords(lbl_Keyword.Text);

            if (report.IsOpen() == false)
            {
                //open report for create a new pdf document
                report.Open();
            }
            //Paragraph, need for create a new pdf document
            report.Add(new Paragraph(rtxt_Paragraph.Text));

            //open the connection
            db.openConnection();
            //a command line for update the document
            SqlCommand query = new SqlCommand("UPDATE Table_DOCUMENT SET file_Path = @fp, u_ID = @uid WHERE file_ID = @fid", db.getConnection());

            //add the value in the label to @fp
            query.Parameters.AddWithValue("@fp", labelFilePath.Text);
            //add the value in the combobox to @uid
            query.Parameters.AddWithValue("@uid", comboboxUserID.Text);
            //add the value in the label to @fid
            query.Parameters.AddWithValue("@fid", labelFileID.Text);

            //ecevute the query
            if (query.ExecuteNonQuery() == 1)
            {
                MessageBox.Show("DATA WERE UPDATED", "Message Box", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
                //return the default values
                labelFilePath.Text     = @"C:\Users\Asus\Desktop\UPLOADFILES";
                textboxFilePath.Text   = "";
                labelFileID.Text       = "";
                lbl_FileName.Text      = "";
                labelCreationDate.Text = "";
                comboboxUserID.Text    = " ";
                rtxt_Paragraph.Text    = "";
            }
            else
            {
                MessageBox.Show("ERROR", "Message Box", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
            }
            //close the report
            report.Close();
            //close the connection
            db.closeConnection();
        }
Пример #10
0
 private void SetPageProperties()
 {
     this.pageSize = new PDFPageSize();
     doc.SetPageSize(new iTextSharp.text.Rectangle(pageSize.Width, pageSize.Height));
     doc.SetMargins(pageSize.LeftMargin, pageSize.RightMargin, pageSize.TopMargin, pageSize.BottomMargin);
     doc.AddTitle("POC - Principal form");
     doc.AddCreator("CD ABM Logic");
 }
        public void Build()
        {
            iTextSharp.text.Document doc = null;

            try
            {
                // Initialize the PDF document
                doc = new Document();
                iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc,
                    new System.IO.FileStream(System.IO.Directory.GetCurrentDirectory() + "\\ScienceReport.pdf",
                        System.IO.FileMode.Create));

                // Set margins and page size for the document
                doc.SetMargins(50, 50, 50, 50);
                // There are a huge number of possible page sizes, including such sizes as
                // EXECUTIVE, POSTCARD, LEDGER, LEGAL, LETTER_LANDSCAPE, and NOTE
                doc.SetPageSize(new iTextSharp.text.Rectangle(iTextSharp.text.PageSize.LETTER.Width,
                    iTextSharp.text.PageSize.LETTER.Height));

                // Add metadata to the document.  This information is visible when viewing the
                // document properities within Adobe Reader.
                doc.AddTitle("My Science Report");
                doc.AddCreator("M. Lichtenberg");
                doc.AddKeywords("paper airplanes");

                // Add Xmp metadata to the document.
                this.CreateXmpMetadata(writer);

                // Open the document for writing content
                doc.Open();

                // Add pages to the document
                this.AddPageWithBasicFormatting(doc);
                this.AddPageWithInternalLinks(doc);
                this.AddPageWithBulletList(doc);
                this.AddPageWithExternalLinks(doc);
                this.AddPageWithImage(doc, System.IO.Directory.GetCurrentDirectory() + "\\FinalGraph.jpg");

                // Add page labels to the document
                iTextSharp.text.pdf.PdfPageLabels pdfPageLabels = new iTextSharp.text.pdf.PdfPageLabels();
                pdfPageLabels.AddPageLabel(1, iTextSharp.text.pdf.PdfPageLabels.EMPTY, "Basic Formatting");
                pdfPageLabels.AddPageLabel(2, iTextSharp.text.pdf.PdfPageLabels.EMPTY, "Internal Links");
                pdfPageLabels.AddPageLabel(3, iTextSharp.text.pdf.PdfPageLabels.EMPTY, "Bullet List");
                pdfPageLabels.AddPageLabel(4, iTextSharp.text.pdf.PdfPageLabels.EMPTY, "External Links");
                pdfPageLabels.AddPageLabel(5, iTextSharp.text.pdf.PdfPageLabels.EMPTY, "Image");
                writer.PageLabels = pdfPageLabels;
            }
            catch (iTextSharp.text.DocumentException dex)
            {
                // Handle iTextSharp errors
            }
            finally
            {
                // Clean up
                doc.Close();
                doc = null;
            }
        }
Пример #12
0
        private void button4_Click(object sender, EventArgs e)
        {
            /*-------------------------------------*/

            iTextSharp.text.Document raporum = new iTextSharp.text.Document();

            // PDF oluşturması ve konumun belirlenmesi
            Random r = new Random();

            PdfWriter.GetInstance(raporum, new FileStream("C:Raporum" + r.Next() + ".pdf", FileMode.Create));

            //PDF yi yazan özelliğine eklenecek

            raporum.AddAuthor("Selim Silgu"); // PDF Oluşturma Tarihi Ekle

            raporum.AddCreationDate();        // PDF Oluşturma Tarihi

            // PDF oluşturan kişi özelliğine yazılacak

            raporum.AddCreator("Selim Silgu");

            if (raporum.IsOpen() == false)
            {
                raporum.Open();
            }

            raporum.Add(new Paragraph("Ürün Fiyatı : " + urunFiyat.Text + " TL"));
            raporum.Add(new Paragraph("Seri Numarası : " + seriNumarasi.Text));
            raporum.Add(new Paragraph("Ürün ID : " + urunid.ToString()));
            raporum.Add(new Paragraph("Ürün Adı : " + urunAdText.Text));
            raporum.Add(new Paragraph("Ürün Modeli : " + UrunModel.Text));
            raporum.Add(new Paragraph("Islemci Hızı : " + islemciHız.Text));
            raporum.Add(new Paragraph("Cache Bellek : " + cache.Text));
            raporum.Add(new Paragraph("Islemci Teknolojisi : " + islemciTeknoloji.Text));
            raporum.Add(new Paragraph("Islemci Markası : " + islemciMarka.Text));
            raporum.Add(new Paragraph("Islemci Hızı : " + islemciHız.Text));
            raporum.Add(new Paragraph("Çekirdek Sayısı : " + cekirdekSayisi.Text));
            raporum.Add(new Paragraph("RAM Tipi :" + ramTip.Text));
            raporum.Add(new Paragraph("RAM Kapasitesi : " + ramKapasite.Text));
            raporum.Add(new Paragraph("RAM Markası : " + ramMarka.Text));
            raporum.Add(new Paragraph("Disk Türü : " + hddTur.Text));
            raporum.Add(new Paragraph("Disk Markası : " + hddMarka.Text));
            raporum.Add(new Paragraph("USB : " + usb.Text));
            raporum.Add(new Paragraph("Isletim Sistemi : " + isletimSistemi.Text));
            raporum.Add(new Paragraph("Ekran Kartı Tipi : " + ekranKartTip.Text));
            raporum.Add(new Paragraph("Ekran Kartı Markası : " + ekranMarka.Text));
            raporum.Add(new Paragraph("Ekran Kartı Chipset : " + chipset.Text));
            raporum.Add(new Paragraph("Ekran Kartı Kapasitesi : " + kapasite.Text));
            raporum.Add(new Paragraph("Çözünürlük : " + cozunurluk.Text));
            raporum.Add(new Paragraph("Kart Okuyucu : " + kartOkuyucu.Text));
            raporum.Add(new Paragraph("Kamera : " + kamera.Text));
            raporum.Add(new Paragraph("Garanti Süresi : " + GarantiSuresi.Text));
            MessageBox.Show("PDF Dosyanız Oluşmuştur.");

            raporum.Close();

            /*-------------------------------------*/
        }
Пример #13
0
		public override void Start()
		{
			base.Start();
			this.document = (this.reportSettings.Landscape)? new Document(PageSize.A4.Rotate(),0,0,0,0) : new Document(PageSize.A4,0,0,0,0);
			this.pdfUnitConverter = new PdfUnitConverter(this.document.PageSize,this.reportSettings);
			this.pdfWriter = PdfWriter.GetInstance(document, new FileStream(this.fileName,FileMode.Create));
			document.AddCreator(GlobalValues.ResourceString("ApplicationName"));
			FontFactory.RegisterDirectories();
			MyPageEvents events = new MyPageEvents();
			this.pdfWriter.PageEvent = events;
		}
Пример #14
0
        protected void GridViewDogalgaz_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "DogalgazOdeme")                       // Tıklanılan sütun (Kolon Adı == DogalgazOdeme ise)
            {
                int      index    = Convert.ToInt16(e.CommandArgument); // Seçili satır indexini alır..
                TableRow secili   = GridViewDogalgaz.Rows[index];       // Seçili Satırı değişkene aldık.
                String   aboneNo  = secili.Cells[1].Text;               // Seçili satırın abone numarasını aldık.
                String   faturaNo = secili.Cells[2].Text;               // Seçili satırın fatura numarasını aldık.
                yonet.dogalgazFaturaOde(aboneNo, faturaNo);             // Ödeme işlemi metodunu çağırdık...
                Response.Write("Ödeme Yapıldı...");                     // Mesaj verme



                /*-------------------------------------*/

                iTextSharp.text.Document     raporum = new iTextSharp.text.Document();
                iTextSharp.text.pdf.BaseFont STF_Helvetica_Turkish = iTextSharp.text.pdf.BaseFont.CreateFont("Helvetica", "CP1254", iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED);

                iTextSharp.text.Font fontNormal = new iTextSharp.text.Font(STF_Helvetica_Turkish, 12, iTextSharp.text.Font.NORMAL);
                // PDF oluşturması ve konumun belirlenmesi
                Random r = new Random();

                PdfWriter.GetInstance(raporum, new FileStream("C:\\Users\\süleyman\\Desktop\\E-Fatura" + r.Next() + ".pdf", FileMode.Create));

                //PDF yi yazan özelliğine eklenecek

                raporum.AddAuthor("Tüm Abone Listesi"); // PDF Oluşturma Tarihi Ekle

                raporum.AddCreationDate();              // PDF Oluşturma Tarihi

                // PDF oluşturan kişi özelliğine yazılacak

                raporum.AddCreator("Aboneler");

                if (raporum.IsOpen() == false)
                {
                    raporum.Open();
                }
                raporum.Add(new Paragraph("ABONE LISTESI"));
                raporum.Add(new Paragraph("__________________________________________________"));
                raporum.Add(new Paragraph("Abone Numarasi     : " + secili.Cells[0].Text));
                raporum.Add(new Paragraph("Fatura Numarası    : " + secili.Cells[1].Text));
                raporum.Add(new Paragraph("Fatura Bedeli      : " + secili.Cells[2].Text));
                raporum.Add(new Paragraph("Fatura Tarihi      : " + secili.Cells[3].Text));
                raporum.Add(new Paragraph("Son Ödeme Tarihi   : " + secili.Cells[4].Text));
                raporum.Add(new Paragraph("Odeme Durumu       : " + "Ödenmistir"));

                Response.Write("PDF Dosyanız Oluşmuştur.");

                raporum.Close();
                Response.Redirect("AboneDogalgaz.aspx");              // Yönlendirme...
                /*-------------------------------------*/
            }
        }
Пример #15
0
        protected override void WriteDocument(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            if (File.Exists(FilePath))
                throw new Pdf2KTException("File already exists.");

            Document document = null;
            PdfWriter writer = null;

            while(Converter.MoveNext())
            {
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }

                BitmapEncoder encoder = BitmapProcessor.GetBitmapEncoder();
                BitmapSource processed = BitmapProcessor.Convert(Converter.Current);

                if (document == null)
                {
                    document = new Document(new Rectangle(processed.PixelWidth, processed.PixelHeight));
                    writer = PdfWriter.GetInstance(document, new FileStream(FilePath, FileMode.Create));

                    document.Open();
                    document.AddTitle(Converter.Document.Title);
                    document.AddAuthor(Converter.Document.Author);
                    document.AddCreationDate();
                    document.AddCreator("Pdf2KT");
                }

                document.NewPage();

                using (MemoryStream ms = new MemoryStream())
                {
                    encoder.Frames.Add(BitmapFrame.Create(processed));
                    encoder.Save(ms);

                    ms.Position = 0;

                    Image pdfpage = Image.GetInstance(ms);
                    pdfpage.SetAbsolutePosition(0, 0);

                    document.Add(pdfpage);
                }

                worker.ReportProgress((int)((Converter.CurrentProcessedPageNumber * 1f) / Converter.PageCount * 100));
            }

            document.Close();
        }
Пример #16
0
        protected override void InitiateDocument(LnParameters lnParam, string language)
        {
            this.lnParameters    = lnParam;
            this.currentLanguage = language;

            pdf = new PdfDocument(PageSize.A4);
            foreach (string author in lnParam.authors)
            {
                pdf.AddAuthor(author);
            }
            pdf.AddCreationDate();
            pdf.AddLanguage(language);
            pdf.AddTitle(DocumentTitle);
            pdf.AddCreator(Globale.PUBLISHER);
            pdfChapters = new List <Chapter>();
        }
Пример #17
0
        protected void Button2_Click(object sender, EventArgs e)
        {
            /*-------------------------------------*/

            iTextSharp.text.Document     raporum = new iTextSharp.text.Document();
            iTextSharp.text.pdf.BaseFont STF_Helvetica_Turkish = iTextSharp.text.pdf.BaseFont.CreateFont("Helvetica", "CP1254", iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED);

            iTextSharp.text.Font fontNormal = new iTextSharp.text.Font(STF_Helvetica_Turkish, 12, iTextSharp.text.Font.NORMAL);
            // PDF oluşturması ve konumun belirlenmesi
            Random r = new Random();

            PdfWriter.GetInstance(raporum, new FileStream("C:\\Users\\süleyman\\Desktop\\E-Fatura" + r.Next() + ".pdf", FileMode.Create));

            //PDF yi yazan özelliğine eklenecek

            raporum.AddAuthor("Tüm Abone Listesi"); // PDF Oluşturma Tarihi Ekle

            raporum.AddCreationDate();              // PDF Oluşturma Tarihi

            // PDF oluşturan kişi özelliğine yazılacak

            raporum.AddCreator("Aboneler");

            if (raporum.IsOpen() == false)
            {
                raporum.Open();
            }
            yonet.TumAboneler();
            raporum.Add(new Paragraph("ABONE LISTESI"));
            while (yonet.dr.Read())
            {
                raporum.Add(new Paragraph("__________________________________________________"));
                raporum.Add(new Paragraph("Abone Numarasi     : " + yonet.dr["ABONENO"].ToString()));
                raporum.Add(new Paragraph("TC Kimlik Numarasi : " + yonet.dr["TCKIMLIKNO"].ToString()));
                raporum.Add(new Paragraph("Abone Ad Soyad     : " + yonet.dr["ADSOYAD"].ToString()));
                raporum.Add(new Paragraph("Abone Dogum Tarihi : " + yonet.dr["DOGTAR"].ToString()));
                raporum.Add(new Paragraph("Abone Telefon      : " + yonet.dr["TEL"].ToString()));
                raporum.Add(new Paragraph("Abone Adres        : " + yonet.dr["ADRES"].ToString()));
                raporum.Add(new Paragraph("Abone Cinsiyet     : " + yonet.dr["CINSIYET"].ToString()));
                raporum.Add(new Paragraph("Abone Turu         : " + yonet.dr["ABONETURU"].ToString()));
            }
            Response.Write("PDF Dosyanız Oluşmuştur.");

            raporum.Close();

            /*-------------------------------------*/
        }
    public static void CreateDocument(Stream stream, Action<Document> action)
    {
        using (var document = new Document(PageSize.A4))
            {
                var writer = PdfWriter.GetInstance(document, stream);
                document.Open();
                document.AddAuthor(Author);
                document.AddCreator(DocumentCreator);
                document.AddKeywords(DocumentKeywords);
                document.AddSubject(DocumentSubject);
                document.AddTitle(DocumentTitle);

                action.Invoke(document);

                document.Close();
            }
    }
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            iTextSharp.text.Document raporum = new iTextSharp.text.Document();
            PdfWriter.GetInstance(raporum, new FileStream("C:'" + LblHastaAdı.Text + LblRecerteKodu.Text + "'.pdf", FileMode.Create));
            raporum.AddAuthor(LblHastane.Text + "/" + LblDoktor.Text);
            raporum.AddCreationDate();
            raporum.AddCreator(LblHastane.Text + "/" + LblDoktor.Text);
            raporum.AddSubject("Recete" + LblRecerteKodu.Text);
            raporum.AddKeywords(LblHastaAdı.Text);

            if (raporum.IsOpen() == false)
            {
                raporum.Open();
            }
            raporum.Add(new Paragraph(LblRecete.Text));
            pictureBox1.Enabled = false;
            PdfOku();
        }
Пример #20
0
        public void Start()
        {
            //iTextSharp.text.pdf.BaseFont.AddToResourceSearch(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "iTextAsian.dll"));
            //iTextSharp.text.pdf.BaseFont.AddToResourceSearch(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "iTextAsianCmaps.dll"));

            iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(_Report.PageWidthPoints, _Report.PageHeightPoints);
            document = new iTextSharp.text.Document(pageSize, _Report.LeftMarginPoints, _Report.RightMarginPoints, _Report.TopMarginPoints, _Report.BottomMarginPoints);

            this.pdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(document, tw);

            document.SetMargins(_Report.LeftMarginPoints, _Report.RightMarginPoints, _Report.TopMarginPoints, _Report.BottomMarginPoints);

            document.Open();

            document.AddAuthor(_Report.Author);
            document.AddCreationDate();
            document.AddCreator(_Report.Author);
        }
Пример #21
0
// ---------------------------------------------------------------------------
/**
 * Creates a PDF document.
 */
    public byte[] CreatePdf() {
      using (MemoryStream ms = new MemoryStream()) {
        // step 1
        using (Document document = new Document()) {
          // step 2
          PdfWriter.GetInstance(document, ms);
          // step 3
          document.AddTitle("Hello World example");
          document.AddAuthor("Bruno Lowagie");
          document.AddSubject("This example shows how to add metadata");
          document.AddKeywords("Metadata, iText, PDF");
          document.AddCreator("My program using iText");
          document.Open();
          // step 4
          document.Add(new Paragraph("Hello World"));
        }
        return ms.ToArray();    
      }
    }    
Пример #22
0
        public void CreateGradesPDF(List <CourseModel> grades)
        {
            System.IO.FileStream fs = new FileStream("GeneratedDocument.pdf", FileMode.Create);

            iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.A4, 25, 25, 30, 30);

            PdfWriter writer = PdfWriter.GetInstance(document, fs);

            document.AddAuthor("UCV");

            document.AddCreator("UCV");

            document.AddKeywords("Note");

            document.AddSubject("Situatie Scolara");

            document.AddTitle("Situatie scolara");

            //document.Add(new Chunk(new LineSeparator(4f, 100f, BaseColor.GRAY, Element.ALIGN_CENTER, -1)));

            document.Open();

            document.Add(new Paragraph("UCV --- Situatie Scolara"));

            if (grades.Count == 0)
            {
                document.Add(new Paragraph("Nu exista situatie scolara."));
            }
            else
            {
                foreach (var grade in grades)
                {
                    document.Add(new Paragraph(grade.Name + "    " + grade.Teacher + "    " + grade.Credits));
                    //document.Add(new Chunk(new LineSeparator(4f, 100f, BaseColor.GRAY, Element.ALIGN_CENTER, -1)));
                }
            }
            document.Close();

            writer.Close();

            fs.Close();
        }
Пример #23
0
 void CreatePdf()
 {
     Itext.Document idoc = new Itext.Document(Itext.PageSize.A4);
     try
     {
         if (saveCWFileDialog.ShowDialog() == DialogResult.OK)
         {
             var newfilePath = saveCWFileDialog.FileName;
             PdfWriter.GetInstance(idoc, new FileStream(newfilePath, FileMode.Create));
             #region 设置PDF的头信息,一些属性设置,在Document.Open 之前完成
             idoc.AddAuthor("");
             idoc.AddCreationDate();
             idoc.AddCreator("");
             idoc.AddSubject("");
             idoc.AddTitle("");
             idoc.AddKeywords("");
             idoc.AddHeader("cw", "export pdf");
             #endregion
             idoc.Open();
             //载入字体
             idoc.Add(new Itext.Paragraph(editContentBox.Text, new Itext.Font(BaseFontAndSize(""))));
             idoc.Close();
             if (MessageBox.Show("是否打开文件?", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
             {
                 Process.Start(newfilePath);
             }
         }
     }
     catch (Itext.DocumentException de) {
         Console.WriteLine(de.Message); Console.ReadKey();
         WriteLog.Logging(de.Message);
     }
     catch (IOException io) {
         Console.WriteLine(io.Message); Console.ReadKey();
         WriteLog.Logging(io.Message);
     }
     catch (Exception err)
     {
         WriteLog.Logging(err);
     }
 }
        private void button1_Click(object sender, EventArgs e)
        {
            if (Directory.Exists("C:mezunOgrenciler.pdf"))
            {
                File.Delete("C:mezunOgrenciler.pdf");
            }
            //Kutuphane\Kutuphane\bin\Debug
            PdfWriter.GetInstance(pdfDosya, new FileStream("C:mezunOgrenciler.pdf", FileMode.Create));
            pdfDosya.Open();

            pdfDosya.AddCreator(main.ad); //Oluşturan kişinin isminin eklenmesi
            pdfDosya.AddHeader("PDF UYGULAMASI OLUSTUR", null);
            Paragraph eklenecekMetin = new Paragraph(richTextBox1.Text);

            pdfDosya.Add(eklenecekMetin);
            pdfDosya.Close();
            button1.Enabled = false;
            RaporEkle rp = new RaporEkle();

            rp.ShowDialog();
        }
Пример #25
0
        void WriteDocument(iTextSharp.text.Document doc, List <KeyValuePair <ISearchAlgorithm <string>, SearchReport <string> > > results, System.Drawing.Image initialGraph)
        {
            doc.AddCreationDate();
            doc.AddAuthor("GraphSEA");
            doc.AddCreator("GraphSEA");
            doc.AddHeader("Header", "GraphSEA - Graph search algorithms benchmark report");
            WriteHeader(doc);
            doc.NewPage();
            WriteGraph(doc, initialGraph, results[0].Value.Result.Start, results[0].Value.Result.End);
            doc.NewPage();
            WriteResultSummary(doc, results);
            doc.NewPage();
            // algorithms benchmarks
            foreach (var res in results)
            {
                CurrentReport = res.Value;
                WriteAlgorithmBenchmark(doc, res.Key, res.Value);
            }

            WriteTableOfContent(doc);
        }
        private void Btnpdfolustur_Click_1(object sender, EventArgs e)
        {
            iTextSharp.text.Document pdfdosya = new iTextSharp.text.Document();
            //pdf dosyamızı temsil edecek nesnemizi oluşturuyoruz
            PdfWriter.GetInstance(pdfdosya, new FileStream("C:CSharpPDF.pdf", FileMode.Create));
            //pdf dosyamızın yolunu belirledik ve dosyanın açılış biçimi olrarak pdf ayarladık
            pdfdosya.Open();                          //dosyayı aç
            pdfdosya.AddCreator(txtolusturulan.Text); //oluşturan ismi
            pdfdosya.AddCreationDate();               //tarih
            pdfdosya.AddAuthor(txticeriksahibi.Text); //yazarın ismi eklendi
            pdfdosya.AddHeader(txtustbaslik.Text, "PDF UYGULAMASI OLUŞTUR");
            pdfdosya.AddTitle(txtaltbaslik.Text);     //başlık ve title eklenmesi
            Paragraph eklenecekmetin = new Paragraph(txtaciklamametni.Text);

            pdfdosya.Add(eklenecekmetin);             //eklenecek metnimizin dosyaya eklenmesi
            decimal satir = numaricsatirsayisi.Value; //satir bilgisi
            decimal sutun = numaricsutunsayisi.Value; //sutun bilgisi

            iTextSharp.text.Table tablo = new Table((int)sutun, (int)satir);
            for (int i = 0; i < satir; i++)
            {
                for (int j = 0; j < sutun; j++)
                {
                    Cell hucre = new Cell((i + 1).ToString() + " " + (j + 1).ToString());
                    hucre.BackgroundColor = iTextSharp.text.Color.RED;
                    tablo.AddCell(hucre, i, j);
                }
            }
            tablo.cellspacing = 5;
            pdfdosya.Add(tablo);
            if (txtolusturulan.Text != "")
            {
                Uri yol = new Uri(txtolusturulan.Text);
                iTextSharp.text.Jpeg resim = new iTextSharp.text.Jpeg(yol);
                resim.ScalePercent((int)numaricsikistirmeorani.Value);
                pdfdosya.Add(resim);
            }
            pdfdosya.Close();
        }
Пример #27
0
        public static string generarPdf(Hashtable htFacturaxion, HttpContext hc)
        {
            string pathPdf = htFacturaxion["rutaDocumentoPdf"].ToString();
            FileStream fs = new FileStream(pathPdf, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);

            try
            {
                StringBuilder sbConfigFact = new StringBuilder();
                StringBuilder sbConfigFactParms = new StringBuilder();
                _ci.NumberFormat.CurrencyDecimalDigits = 2;

                DAL dal = new DAL();
                ElectronicDocument electronicDocument = (ElectronicDocument)htFacturaxion["electronicDocument"];
                Data objTimbre = (Data)htFacturaxion["objTimbre"];
                bool timbrar = Convert.ToBoolean(htFacturaxion["timbrar"]);
                //string pathPdf = htFacturaxion["rutaDocumentoPdf"].ToString();

                // Obtenemos el logo y plantilla

                StringBuilder sbLogo = new StringBuilder();

                sbLogo.
                    Append("SELECT S.rutaLogo, P.rutaEncabezado, P.rutaFooter ").
                    Append("FROM sucursales S ").
                    Append("LEFT OUTER JOIN tipoPlantillas P ON S.idTipoPlantilla = P.idTipoPlantilla AND P.ST = 1 ").
                    Append("WHERE idSucursal = @0 AND S.ST = 1");

                DataTable dtLogo = dal.QueryDT("DS_FE", sbLogo.ToString(), "F:I:" + htFacturaxion["idSucursalEmisor"], hc);

                string rutaLogo = dtLogo.Rows[0]["rutaLogo"].ToString();
                string rutaHeader = dtLogo.Rows[0]["rutaEncabezado"].ToString();
                string rutaFooter = dtLogo.Rows[0]["rutaFooter"].ToString();

                //Obtenemos Rol de la empresa
                StringBuilder sbRol = new StringBuilder();

                sbRol.
                    Append("DECLARE @iduser INT; ").
                    Append("SELECT DISTINCT @iduser = UxR.idUser FROM sucursales S ").
                    Append("LEFT OUTER JOIN sucursalesXUsuario SxU ON S.idSucursal = SxU.idSucursal LEFT OUTER JOIN r3TakeCore.dbo.SYS_UserXRol UxR ON UxR.idUser = SxU.idUser ").
                    Append("WHERE idEmpresa = @0 AND UxR.idRol IN(22,15) AND S.ST = 1 AND SxU.ST = 1; ").
                    Append("SELECT UxR.idRol FROM r3TakeCore.dbo.SYS_UserXRol UxR WHERE idUser = @idUser");  //Rol 15 > MIT ; 22 > Facturizate

                int idRol = dal.ExecuteScalar("DS_FE", sbRol.ToString(), "F:S:" + htFacturaxion["idEmisor"], hc);

                sbConfigFactParms.
                    Append("F:I:").Append(Convert.ToInt64(htFacturaxion["idSucursalEmisor"])).
                    Append(";").
                    Append("F:I:").Append(Convert.ToInt32(htFacturaxion["tipoComprobante"])).
                    Append(";").
                    Append("F:S:").Append(electronicDocument.Data.Total.Value).
                    Append(";").
                    Append("F:I:").Append(Convert.ToInt32(htFacturaxion["idMoneda"])).
                    Append(";").
                    Append("F:S:").Append(rutaLogo).
                    Append(";").
                    Append("F:S:").Append(rutaHeader).
                    Append(";").
                    Append("F:S:").Append(rutaFooter).
                    Append(";").
                    Append("F:I:").Append(Convert.ToInt64(htFacturaxion["idEmisor"]));

                if (idRol == 15)
                {
                    if (rutaHeader.Length > 0)
                    {
                        sbConfigFact.
                            Append("SELECT @5 AS rutaTemplateHeader, @6 AS rutaTemplateFooter, @4 AS rutaLogo, objDesc, posX, posY, fontSize, dbo.convertNumToTextFunction( @2, @3) AS cantidadLetra, ").
                            Append("logoPosX, logoPosY, headerPosX, headerPosY, footerPosX, footerPosY, conceptosColWidth, desgloseColWidth ").
                            Append("FROM configuracionFacturas CF ").
                            Append("LEFT OUTER JOIN sucursales S ON S.idSucursal = @0 ").
                            Append("LEFT OUTER JOIN configuracionFactDet CFD ON CF.idConFact = CFD.idConFact ").
                            Append("WHERE CF.ST = 1 AND CF.idEmpresa = -1 AND CF.idTipoComp = @1 AND idCFDProcedencia = 1 AND objDesc NOT LIKE 'nuevoLbl%' ");
                    }
                    else
                    {
                        sbConfigFact.
                            Append("SELECT rutaTemplateHeader, rutaTemplateFooter, @4 AS rutaLogo, objDesc, posX, posY, fontSize, dbo.convertNumToTextFunction( @2, @3) AS cantidadLetra, ").
                            Append("logoPosX, logoPosY, headerPosX, headerPosY, footerPosX, footerPosY, conceptosColWidth, desgloseColWidth ").
                            Append("FROM configuracionFacturas CF ").
                            Append("LEFT OUTER JOIN sucursales S ON S.idSucursal = @0 ").
                            Append("LEFT OUTER JOIN configuracionFactDet CFD ON CF.idConFact = CFD.idConFact ").
                            Append("WHERE CF.ST = 1 AND CF.idEmpresa = -1 AND CF.idTipoComp = @1 AND idCFDProcedencia = 1 AND objDesc NOT LIKE 'nuevoLbl%' ");
                    }
                }
                else
                {
                    sbConfigFact.
                        Append("DECLARE @idEmpresa AS INT;").
                        Append("IF EXISTS (SELECT * FROM configuracionFacturas WHERE idEmpresa = @7) ").
                        Append("SET @idEmpresa = @7; ").
                        Append("ELSE ").
                        Append("SET @idEmpresa = 0; ").
                        Append("SELECT rutaTemplateHeader, rutaTemplateFooter, S.rutaLogo, objDesc, posX, posY, fontSize, dbo.convertNumToTextFunction( @2, @3) AS cantidadLetra, ").
                        Append("logoPosX, logoPosY, headerPosX, headerPosY, footerPosX, footerPosY, conceptosColWidth, desgloseColWidth, S.nombreSucursal ").
                        Append("FROM configuracionFacturas CF ").
                        Append("LEFT OUTER JOIN sucursales S ON S.idSucursal = @0 ").
                        Append("LEFT OUTER JOIN configuracionFactDet CFD ON CF.idConFact = CFD.idConFact ").
                        Append("WHERE CF.ST = 1 AND CF.idEmpresa = @idEmpresa AND CF.idTipoComp = @1 AND idCFDProcedencia = 1 AND objDesc NOT LIKE 'nuevoLbl%' ");
                }

                DataTable dtConfigFact = dal.QueryDT("DS_FE", sbConfigFact.ToString(), sbConfigFactParms.ToString(), hc);

                // Creamos el Objeto Documento
                Document document = new Document(PageSize.LETTER, 25, 25, 25, 25);
                document.AddAuthor("Facturaxion");
                document.AddCreator("r3Take");
                document.AddCreationDate();
                //FileStream fs = new FileStream(pathPdf, FileMode.Create);
                //FileStream fs = new FileStream(pathPdf, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                PdfWriter writer = PdfWriter.GetInstance(document, fs);
                writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_7);

                Chunk cSaltoLinea = new Chunk("\n");
                Chunk cLineaSpace = new Chunk(cSaltoLinea + "________________________________________________________________________________________________________________________________________________________________________", new Font(Font.HELVETICA, 6, Font.BOLD));
                Chunk cLineaDiv = new Chunk(cSaltoLinea + "________________________________________________________________________________________________________________________________________________________________________" + cSaltoLinea, new Font(Font.HELVETICA, 6, Font.BOLD));
                Chunk cDataSpacer = new Chunk("      |      ", new Font(Font.HELVETICA, 6, Font.BOLD));

                BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                document.Open();
                PdfContentByte cb = writer.DirectContent;
                cb.BeginText();

                // Almacenamos en orden los objetos del Electronic Document para posteriormente añadidos al documento

                #region "Armamos las etiquetas que tienen posiciones absolutas para ser insertadas en el documento"

                Hashtable htDatosCfdi = new Hashtable();

                // Armamos las direcciones

                #region "Dirección Emisor"

                StringBuilder sbDirEmisor1 = new StringBuilder();
                StringBuilder sbDirEmisor2 = new StringBuilder();
                StringBuilder sbDirEmisor3 = new StringBuilder();

                if (electronicDocument.Data.Emisor.Domicilio.Calle.Value.Length > 0)
                {
                    sbDirEmisor1.Append("Calle ").Append(electronicDocument.Data.Emisor.Domicilio.Calle.Value).Append(" ");
                }

                if (electronicDocument.Data.Emisor.Domicilio.NumeroExterior.Value.Length > 0)
                {
                    sbDirEmisor1.Append(", No. Ext ").Append(electronicDocument.Data.Emisor.Domicilio.NumeroExterior.Value).Append(" ");
                }

                if (electronicDocument.Data.Emisor.Domicilio.NumeroInterior.Value.Length > 0)
                {
                    sbDirEmisor1.Append(", No. Int ").Append(electronicDocument.Data.Emisor.Domicilio.NumeroInterior.Value);
                }

                if (electronicDocument.Data.Emisor.Domicilio.Colonia.Value.Length > 0)
                {
                    sbDirEmisor2.Append("Col. ").Append(electronicDocument.Data.Emisor.Domicilio.Colonia.Value).Append(" ");
                }

                if (electronicDocument.Data.Emisor.Domicilio.CodigoPostal.Value.Length > 0)
                {
                    sbDirEmisor2.Append(", C.P. ").Append(electronicDocument.Data.Emisor.Domicilio.CodigoPostal.Value).Append(" ");
                }

                if (electronicDocument.Data.Emisor.Domicilio.Localidad.Value.Length > 0)
                {
                    sbDirEmisor2.Append(", ").Append(electronicDocument.Data.Emisor.Domicilio.Localidad.Value);
                }

                if (electronicDocument.Data.Emisor.Domicilio.Municipio.Value.Length > 0)
                {
                    sbDirEmisor3.Append("Mpio. / Del. ").Append(electronicDocument.Data.Emisor.Domicilio.Municipio.Value).Append(" ");
                }

                if (electronicDocument.Data.Emisor.Domicilio.Estado.Value.Length > 0)
                {
                    sbDirEmisor3.Append(", Estado ").Append(electronicDocument.Data.Emisor.Domicilio.Estado.Value).Append(" ");
                }

                sbDirEmisor3.Append(", ").Append(electronicDocument.Data.Emisor.Domicilio.Pais.Value);

                #endregion

                #region "Dirección Sucursal Expedido En"

                StringBuilder sbDirExpedido1 = new StringBuilder();
                StringBuilder sbDirExpedido2 = new StringBuilder();
                StringBuilder sbDirExpedido3 = new StringBuilder();

                if (electronicDocument.Data.Emisor.ExpedidoEn.Calle.Value.Length > 0)
                {
                    sbDirExpedido1.Append("Calle ").Append(electronicDocument.Data.Emisor.ExpedidoEn.Calle.Value).Append(" ");
                }

                if (electronicDocument.Data.Emisor.ExpedidoEn.NumeroExterior.Value.Length > 0)
                {
                    sbDirExpedido1.Append(", No. Ext ").Append(electronicDocument.Data.Emisor.ExpedidoEn.NumeroExterior.Value).Append(" ");
                }

                if (electronicDocument.Data.Emisor.ExpedidoEn.NumeroInterior.Value.Length > 0)
                {
                    sbDirExpedido1.Append(", No. Int ").Append(electronicDocument.Data.Emisor.ExpedidoEn.NumeroInterior.Value);
                }

                if (electronicDocument.Data.Emisor.ExpedidoEn.Colonia.Value.Length > 0)
                {
                    sbDirExpedido2.Append("Col. ").Append(electronicDocument.Data.Emisor.ExpedidoEn.Colonia.Value).Append(" ");
                }

                if (electronicDocument.Data.Emisor.ExpedidoEn.CodigoPostal.Value.Length > 0)
                {
                    sbDirExpedido2.Append(", C.P. ").Append(electronicDocument.Data.Emisor.ExpedidoEn.CodigoPostal.Value).Append(" ");
                }

                if (electronicDocument.Data.Emisor.ExpedidoEn.Localidad.Value.Length > 0)
                {
                    sbDirExpedido2.Append(", ").Append(electronicDocument.Data.Emisor.ExpedidoEn.Localidad.Value);
                }

                if (electronicDocument.Data.Emisor.ExpedidoEn.Municipio.Value.Length > 0)
                {
                    sbDirExpedido3.Append("Mpio. / Del. ").Append(electronicDocument.Data.Emisor.ExpedidoEn.Municipio.Value).Append(" ");
                }

                if (electronicDocument.Data.Emisor.ExpedidoEn.Estado.Value.Length > 0)
                {
                    sbDirExpedido3.Append(", Estado ").Append(electronicDocument.Data.Emisor.ExpedidoEn.Estado.Value).Append(" ");
                }

                sbDirExpedido3.Append(", ").Append(electronicDocument.Data.Emisor.ExpedidoEn.Pais.Value);

                #endregion

                #region "Dirección Receptor"

                StringBuilder sbDirReceptor1 = new StringBuilder();
                StringBuilder sbDirReceptor2 = new StringBuilder();
                StringBuilder sbDirReceptor3 = new StringBuilder();

                if (electronicDocument.Data.Receptor.Domicilio.Calle.Value.Length > 0)
                {
                    sbDirReceptor1.Append("Calle ").Append(electronicDocument.Data.Receptor.Domicilio.Calle.Value).Append(" ");
                }

                if (electronicDocument.Data.Receptor.Domicilio.NumeroExterior.Value.Length > 0)
                {
                    sbDirReceptor1.Append(", No. Ext ").Append(electronicDocument.Data.Receptor.Domicilio.NumeroExterior.Value).Append(" ");
                }

                if (electronicDocument.Data.Receptor.Domicilio.NumeroInterior.Value.Length > 0)
                {
                    sbDirReceptor1.Append(", No. Int ").Append(electronicDocument.Data.Receptor.Domicilio.NumeroInterior.Value);
                }

                if (electronicDocument.Data.Receptor.Domicilio.Colonia.Value.Length > 0)
                {
                    sbDirReceptor2.Append("Col. ").Append(electronicDocument.Data.Receptor.Domicilio.Colonia.Value).Append(" ");
                }

                if (electronicDocument.Data.Receptor.Domicilio.CodigoPostal.Value.Length > 0)
                {
                    sbDirReceptor2.Append(", C.P. ").Append(electronicDocument.Data.Receptor.Domicilio.CodigoPostal.Value).Append(" ");
                }

                if (electronicDocument.Data.Receptor.Domicilio.Localidad.Value.Length > 0)
                {
                    sbDirReceptor2.Append(", ").Append(electronicDocument.Data.Receptor.Domicilio.Localidad.Value);
                }

                if (electronicDocument.Data.Receptor.Domicilio.Municipio.Value.Length > 0)
                {
                    sbDirReceptor3.Append("Mpio. / Del. ").Append(electronicDocument.Data.Receptor.Domicilio.Municipio.Value).Append(" ");
                }

                if (electronicDocument.Data.Receptor.Domicilio.Estado.Value.Length > 0)
                {
                    sbDirReceptor3.Append(", Estado ").Append(electronicDocument.Data.Receptor.Domicilio.Estado.Value).Append(" ");
                }

                sbDirReceptor3.Append(", ").Append(electronicDocument.Data.Receptor.Domicilio.Pais.Value);

                #endregion

                htDatosCfdi.Add("rfcEmisor", electronicDocument.Data.Emisor.Rfc.Value);
                htDatosCfdi.Add("rfcEmpresa", electronicDocument.Data.Emisor.Rfc.Value);

                htDatosCfdi.Add("nombreEmisor", "Razón Social " + electronicDocument.Data.Emisor.Nombre.Value);
                htDatosCfdi.Add("empresa", "Razón Social " + electronicDocument.Data.Emisor.Nombre.Value);

                htDatosCfdi.Add("rfcReceptor", electronicDocument.Data.Receptor.Rfc.Value);
                htDatosCfdi.Add("rfcCliente", electronicDocument.Data.Receptor.Rfc.Value);

                htDatosCfdi.Add("nombreReceptor", "Razón Social " + electronicDocument.Data.Receptor.Nombre.Value);
                htDatosCfdi.Add("cliente", "Razón Social " + electronicDocument.Data.Receptor.Nombre.Value);

                htDatosCfdi.Add("sucursal", "Sucursal " + dtConfigFact.Rows[0]["nombreSucursal"]);

                htDatosCfdi.Add("serie", electronicDocument.Data.Serie.Value);
                htDatosCfdi.Add("folio", electronicDocument.Data.Folio.Value);

                htDatosCfdi.Add("fechaCfdi", electronicDocument.Data.Fecha.Value);
                htDatosCfdi.Add("fechaFactura", electronicDocument.Data.Fecha.Value);

                htDatosCfdi.Add("UUID", objTimbre.Uuid.Value);
                htDatosCfdi.Add("folioFiscal", objTimbre.Uuid.Value);

                htDatosCfdi.Add("direccionEmisor1", sbDirEmisor1.ToString());
                htDatosCfdi.Add("direccionEmpresa1", sbDirEmisor1.ToString());

                htDatosCfdi.Add("direccionEmisor2", sbDirEmisor2.ToString());
                htDatosCfdi.Add("direccionEmpresa2", sbDirEmisor2.ToString());

                htDatosCfdi.Add("direccionEmisor3", sbDirEmisor3.ToString());
                htDatosCfdi.Add("direccionEmpresa3", sbDirEmisor3.ToString());

                htDatosCfdi.Add("direccionExpedido1", sbDirExpedido1.ToString());
                htDatosCfdi.Add("direccionSucursal1", sbDirExpedido1.ToString());

                htDatosCfdi.Add("direccionExpedido2", sbDirExpedido2.ToString());
                htDatosCfdi.Add("direccionSucursal2", sbDirExpedido2.ToString());

                htDatosCfdi.Add("direccionExpedido3", sbDirExpedido3.ToString());
                htDatosCfdi.Add("direccionSucursal3", sbDirExpedido3.ToString());

                htDatosCfdi.Add("direccionReceptor1", sbDirReceptor1.ToString());
                htDatosCfdi.Add("direccionCliente1", sbDirReceptor1.ToString());

                htDatosCfdi.Add("direccionReceptor2", sbDirReceptor2.ToString());
                htDatosCfdi.Add("direccionCliente2", sbDirReceptor2.ToString());

                htDatosCfdi.Add("direccionReceptor3", sbDirReceptor3.ToString());
                htDatosCfdi.Add("direccionCliente3", sbDirReceptor3.ToString());

                // Leemos los objetos que se situaran en posiciones absolutas en el documento
                foreach (DataRow row in dtConfigFact.Rows)
                {
                    cb.SetFontAndSize(bf, Convert.ToInt32(row["fontSize"]));
                    cb.SetTextMatrix(Convert.ToSingle(row["posX"]), Convert.ToSingle(row["posY"]));
                    cb.ShowText(htDatosCfdi[row["objDesc"].ToString()].ToString());
                }
                /////////////////////////////////////////////////////////////
                DataTable dtGetOptional = new DataTable();

                dtGetOptional = dal.QueryDT("DS_FE", "SELECT idCFDI,campo1,campo2,campo3,campo4,campo5 FROM dbo.opcionalEncabezado WHERE idCFDI = @0", "F:I:" + htFacturaxion["idCfdi"], hc);

                if (dtGetOptional.Rows.Count > 0)
                {
                    cb.SetFontAndSize(bf, 7);
                    cb.SetTextMatrix(40, 606);
                    cb.ShowText(dtGetOptional.Rows[0]["campo1"].ToString());

                    cb.SetFontAndSize(bf, 7);
                    cb.SetTextMatrix(40, 597);
                    cb.ShowText(dtGetOptional.Rows[0]["campo2"].ToString());

                    cb.SetFontAndSize(bf, 7);
                    cb.SetTextMatrix(345, 615);
                    cb.ShowText(dtGetOptional.Rows[0]["campo3"].ToString());

                    cb.SetFontAndSize(bf, 7);
                    cb.SetTextMatrix(345, 606);
                    cb.ShowText(dtGetOptional.Rows[0]["campo4"].ToString());

                    cb.SetFontAndSize(bf, 7);
                    cb.SetTextMatrix(40, 597);
                    cb.ShowText(dtGetOptional.Rows[0]["campo5"].ToString());
                }
                ////////////////////////////////////////////////////////////////////

                #endregion

                cb.EndText();

                #region "Generamos Quick Response Code"

                byte[] bytesQRCode = new byte[0];

                if (timbrar)
                {
                    // Generamos el Quick Response Code (QRCode)
                    string re = electronicDocument.Data.Emisor.Rfc.Value;
                    string rr = electronicDocument.Data.Receptor.Rfc.Value;
                    string tt = String.Format("{0:F6}", electronicDocument.Data.Total.Value);
                    string id = objTimbre.Uuid.Value;

                    StringBuilder sbCadenaQRCode = new StringBuilder();

                    sbCadenaQRCode.
                        Append("?").
                        Append("re=").Append(re).
                        Append("&").
                        Append("rr=").Append(rr).
                        Append("&").
                        Append("tt=").Append(tt).
                        Append("&").
                        Append("id=").Append(id);

                    BarcodeLib.Barcode.QRCode.QRCode barcode = new BarcodeLib.Barcode.QRCode.QRCode();

                    barcode.Data = sbCadenaQRCode.ToString();
                    barcode.ModuleSize = 3;
                    barcode.LeftMargin = 0;
                    barcode.RightMargin = 10;
                    barcode.TopMargin = 0;
                    barcode.BottomMargin = 0;
                    barcode.Encoding = BarcodeLib.Barcode.QRCode.QRCodeEncoding.Auto;
                    barcode.Version = BarcodeLib.Barcode.QRCode.QRCodeVersion.Auto;
                    barcode.ECL = BarcodeLib.Barcode.QRCode.ErrorCorrectionLevel.L;
                    bytesQRCode = barcode.drawBarcodeAsBytes();
                }

                #endregion

                #region "Header"

                //Agregando Imagen de Encabezado de Página
                Image imgHeader = Image.GetInstance(dtConfigFact.Rows[0]["rutaTemplateHeader"].ToString());
                imgHeader.ScalePercent(47f);

                double posXH = Convert.ToDouble(dtConfigFact.Rows[0]["headerPosX"].ToString());
                double posYH = Convert.ToDouble(dtConfigFact.Rows[0]["headerPosY"].ToString());

                double PXH = posXH;
                double PYH = posYH;
                imgHeader.SetAbsolutePosition(Convert.ToSingle(PXH), Convert.ToSingle(PYH));
                document.Add(imgHeader);

                #endregion

                #region "Logotipo"

                //Agregando Imagen de Logotipo
                Image imgLogo = Image.GetInstance(dtConfigFact.Rows[0]["rutaLogo"].ToString());
                float imgLogoWidth = 100;
                float imgLogoHeight = 50;

                imgLogo.ScaleAbsolute(imgLogoWidth, imgLogoHeight);
                imgLogo.SetAbsolutePosition(Convert.ToSingle(dtConfigFact.Rows[0]["logoPosX"]), Convert.ToSingle(dtConfigFact.Rows[0]["logoPosY"]));
                document.Add(imgLogo);

                #endregion

                #region "Espaciador entre Header y Conceptos"

                Paragraph pRelleno = new Paragraph();
                Chunk cRelleno = new Chunk();

                for (int lineas = 0; lineas < 12; lineas++)
                {
                    cRelleno.Append("\n");
                }

                pRelleno.Add(cRelleno);
                document.Add(pRelleno);

                #endregion

                #region "Añadimos Detalle de Conceptos"

                // Creamos la tabla para insertar los conceptos de detalle de la factura
                PdfPTable tableConceptos = new PdfPTable(5);

                int[] colWithsConceptos = new int[5];
                String[] arrColWidthConceptos = dtConfigFact.Rows[0]["conceptosColWidth"].ToString().Split(new Char[] { ',' });

                for (int i = 0; i < arrColWidthConceptos.Length; i++)
                {
                    colWithsConceptos.SetValue(Convert.ToInt32(arrColWidthConceptos[i]), i);
                }

                tableConceptos.SetWidths(colWithsConceptos);
                tableConceptos.WidthPercentage = 93F;

                int numConceptos = electronicDocument.Data.Conceptos.Count;
                PdfPCell cellConceptos = new PdfPCell();
                PdfPCell cellMontos = new PdfPCell();

                for (int i = 0; i < numConceptos; i++)
                {
                    cellConceptos = new PdfPCell(new Phrase(electronicDocument.Data.Conceptos[i].Cantidad.Value.ToString(), new Font(Font.HELVETICA, 7, Font.NORMAL)));
                    cellConceptos.Border = 0;
                    cellConceptos.HorizontalAlignment = PdfCell.ALIGN_LEFT;
                    tableConceptos.AddCell(cellConceptos);

                    cellConceptos = new PdfPCell(new Phrase(electronicDocument.Data.Conceptos[i].Unidad.Value, new Font(Font.HELVETICA, 7, Font.NORMAL)));
                    cellConceptos.Border = 0;
                    cellConceptos.HorizontalAlignment = PdfCell.ALIGN_LEFT;
                    tableConceptos.AddCell(cellConceptos);

                    cellConceptos = new PdfPCell(new Phrase(electronicDocument.Data.Conceptos[i].Descripcion.Value, new Font(Font.HELVETICA, 7, Font.NORMAL)));
                    cellConceptos.Border = 0;
                    tableConceptos.AddCell(cellConceptos);

                    cellMontos = new PdfPCell(new Phrase(electronicDocument.Data.Conceptos[i].ValorUnitario.Value.ToString("C", _ci), new Font(Font.HELVETICA, 7, Font.NORMAL)));
                    cellMontos.Border = 0;
                    cellMontos.HorizontalAlignment = PdfCell.ALIGN_RIGHT;
                    tableConceptos.AddCell(cellMontos);

                    cellMontos = new PdfPCell(new Phrase(electronicDocument.Data.Conceptos[i].Importe.Value.ToString("C", _ci), new Font(Font.HELVETICA, 8, Font.NORMAL)));
                    cellMontos.Border = 0;
                    cellMontos.HorizontalAlignment = PdfCell.ALIGN_RIGHT;
                    tableConceptos.AddCell(cellMontos);
                }

                document.Add(tableConceptos);

                #endregion

                #region "Espaciador entre Conceptos y Desglose"

                Paragraph pRelleno2 = new Paragraph();
                Chunk cRelleno2 = new Chunk("\n");
                pRelleno2.Add(cRelleno2);
                document.Add(pRelleno2);

                #endregion

                #region "Desglose"

                PdfPTable tableDesglose = new PdfPTable(3);
                int[] colWithsDesglose = new int[3];
                String[] arrColWidthDesglose = dtConfigFact.Rows[0]["desgloseColWidth"].ToString().Split(new Char[] { ',' });

                for (int i = 0; i < arrColWidthDesglose.Length; i++)
                {
                    colWithsDesglose.SetValue(Convert.ToInt32(arrColWidthDesglose[i]), i);
                }

                tableDesglose.SetWidths(colWithsDesglose);
                tableDesglose.WidthPercentage = 93F;

                PdfPCell cellDesgloseRelleno = new PdfPCell();
                PdfPCell cellDesgloseDescripcion = new PdfPCell();
                PdfPCell cellDesgloseMonto = new PdfPCell();

                //Armamnos el Hashtable que conntiene el desglose del Cfdi

                Hashtable htDesglose = new Hashtable();
                ArrayList alDesgloseOrden = new ArrayList();

                alDesgloseOrden.Add("Subtotal");

                if (electronicDocument.Data.Descuento.Value != 0)
                {
                    alDesgloseOrden.Add("Descuento");
                }

                if (electronicDocument.Data.Impuestos.TotalTraslados.Value != 0)
                {
                    alDesgloseOrden.Add("Impuestos Trasladados");
                }

                if (electronicDocument.Data.Impuestos.TotalRetenciones.Value != 0)
                {
                    alDesgloseOrden.Add("Impuestos Retenidos");
                }

                alDesgloseOrden.Add("Total");

                htDesglose.Add("Subtotal", electronicDocument.Data.SubTotal.Value.ToString("C", _ci));
                htDesglose.Add("Descuento", electronicDocument.Data.Descuento.Value.ToString("C", _ci));
                htDesglose.Add("Impuestos Trasladados", electronicDocument.Data.Impuestos.TotalTraslados.Value.ToString("C", _ci));
                htDesglose.Add("Impuestos Retenidos", electronicDocument.Data.Impuestos.TotalRetenciones.Value.ToString("C", _ci));
                htDesglose.Add("Total", electronicDocument.Data.Total.Value.ToString("C", _ci));

                foreach (string desglose in alDesgloseOrden)
                {
                    cellDesgloseRelleno = new PdfPCell(new Phrase(string.Empty, new Font(Font.HELVETICA, 7, Font.BOLD)));
                    cellDesgloseRelleno.Border = 0;

                    cellDesgloseDescripcion = new PdfPCell(new Phrase(desglose, new Font(Font.HELVETICA, 7, Font.BOLD)));
                    cellDesgloseDescripcion.Border = 0;

                    cellDesgloseMonto = new PdfPCell(new Phrase(htDesglose[desglose].ToString(), new Font(Font.HELVETICA, 7, Font.NORMAL)));
                    cellDesgloseMonto.Border = 0;
                    cellDesgloseMonto.HorizontalAlignment = PdfCell.ALIGN_RIGHT;

                    tableDesglose.AddCell(cellDesgloseRelleno);
                    tableDesglose.AddCell(cellDesgloseDescripcion);
                    tableDesglose.AddCell(cellDesgloseMonto);
                }

                document.Add(tableDesglose);

                #endregion

                #region "Desglose Detalle"

                PdfPTable tableDesgloseDetalle = new PdfPTable(3);
                int[] colWithsDesgloseDetalle = new int[3];
                string colDesgloseDetalle = "8,8,84";
                String[] arrColWidthDesgloseDetalle = colDesgloseDetalle.Split(new Char[] { ',' });

                for (int i = 0; i < arrColWidthDesgloseDetalle.Length; i++)
                {
                    colWithsDesgloseDetalle.SetValue(Convert.ToInt32(arrColWidthDesgloseDetalle[i]), i);
                }

                tableDesgloseDetalle.SetWidths(colWithsDesgloseDetalle);
                tableDesgloseDetalle.WidthPercentage = 100F;

                #endregion

                #region "Creación e Inserción de Chunks en Paragraph"

                Paragraph pFooter = new Paragraph();
                pFooter.KeepTogether = true;
                pFooter.Alignment = PdfCell.ALIGN_LEFT;
                pFooter.SetLeading(1.6f, 1.6f);

                //AZUL Font fontLbl = new Font(Font.HELVETICA, 6, Font.BOLD, new Color(43, 145, 175));
                Font fontLbl = new Font(Font.HELVETICA, 6, Font.BOLD, new Color(25, 71, 6));
                Font fontVal = new Font(Font.HELVETICA, 6, Font.NORMAL);

                string cantidadLetra = dtConfigFact.Rows[0]["cantidadLetra"].ToString();
                Chunk cCantidadLetraVal = new Chunk(cantidadLetra, new Font(Font.HELVETICA, 7, Font.BOLD));

                Chunk cTipoComprobanteLbl = new Chunk("Tipo de Comprobante: ", fontLbl);
                Chunk cTipoComprobanteVal = new Chunk(electronicDocument.Data.TipoComprobante.Value, fontVal);

                Chunk cFormaPagoLbl = new Chunk("Forma de Pago: ", fontLbl);
                Chunk cFormaPagoVal = new Chunk(electronicDocument.Data.FormaPago.Value, fontVal);

                Chunk cMetodoPagoLbl = new Chunk("Método de Pago: ", fontLbl);
                Chunk cMetodoPagoVal = new Chunk(electronicDocument.Data.MetodoPago.Value, fontVal);

                Chunk cMonedaLbl = new Chunk("Moneda: ", fontLbl);
                Chunk cMonedaVal = new Chunk(electronicDocument.Data.Moneda.Value, fontVal);

                if (electronicDocument.Data.TipoCambio.Value.Length == 0)
                    electronicDocument.Data.TipoCambio.Value = "1";

                Chunk cTasaCambioLbl = new Chunk("Tasa de Cambio: ", fontLbl);
                Chunk cTasaCambioVal = new Chunk(Convert.ToDouble(electronicDocument.Data.TipoCambio.Value).ToString("C", _ci), fontVal);

                Chunk cCertificadoLbl = new Chunk("Certificado del Emisor: ", fontLbl);
                Chunk cCertificadoVal = new Chunk(electronicDocument.Data.NumeroCertificado.Value, fontVal);

                Chunk cCadenaOriginalLbl = new Chunk("Cadena Original", fontLbl);
                Chunk cCadenaOriginalVal = new Chunk(electronicDocument.FingerPrint, fontVal);

                Chunk cCadenaOriginalPACLbl = new Chunk("Cadena Original del Complemento de Certificación Digital del SAT", fontLbl);
                Chunk cCadenaOriginalPACVal = new Chunk(electronicDocument.FingerPrintPac, fontVal);

                Chunk cSelloDigitalLbl = new Chunk("Sello Digital del Emisor", fontLbl);
                Chunk cSelloDigitalVal = new Chunk(electronicDocument.Data.Sello.Value, fontVal);

                string regimenes = "";

                for (int u = 0; u < electronicDocument.Data.Emisor.Regimenes.Count; u++)
                    regimenes += electronicDocument.Data.Emisor.Regimenes[u].Regimen.Value.ToString() + ",";

                Chunk cNoTarjetaLbl = new Chunk("No. Tarjeta: ", fontLbl);
                Chunk cNoTarjetaVal = new Chunk(electronicDocument.Data.NumeroCuentaPago.Value, fontVal);

                Chunk cExpedidoEnLbl = new Chunk("Expedido En: ", fontLbl);
                Chunk cExpedidoEnVal = new Chunk(electronicDocument.Data.LugarExpedicion.Value, fontVal);

                pFooter.Add(cCantidadLetraVal);
                pFooter.Add(cSaltoLinea);

                pFooter.Add(cTipoComprobanteLbl);
                pFooter.Add(cTipoComprobanteVal);
                pFooter.Add(cDataSpacer);
                pFooter.Add(cMonedaLbl);
                pFooter.Add(cMonedaVal);
                pFooter.Add(cDataSpacer);
                pFooter.Add(cTasaCambioLbl);
                pFooter.Add(cTasaCambioVal);
                pFooter.Add(cDataSpacer);

                if (htFacturaxion["noOrdenCompra"].ToString().Length > 0)
                {
                    Chunk cOrdenCompraLbl = new Chunk("Orden de Compra: ", fontLbl);
                    Chunk cOrdenCompraVal = new Chunk(htFacturaxion["noOrdenCompra"].ToString(), fontVal);
                    pFooter.Add(cOrdenCompraLbl);
                    pFooter.Add(cOrdenCompraVal);
                    pFooter.Add(cDataSpacer);
                }

                pFooter.Add(cFormaPagoLbl);
                pFooter.Add(cFormaPagoVal);
                pFooter.Add(cDataSpacer);
                pFooter.Add(cMetodoPagoLbl);
                pFooter.Add(cMetodoPagoVal);

                if (electronicDocument.Data.NumeroCuentaPago.Value.ToString().Length > 0)
                {
                    pFooter.Add(cDataSpacer);
                    pFooter.Add(cNoTarjetaLbl);
                    pFooter.Add(cNoTarjetaVal);
                }

                if (electronicDocument.Data.Emisor.Regimenes.Count > 0)
                {
                    Chunk cRegimenLbl = new Chunk("Régimen Fiscal: ", fontLbl);
                    Chunk cRegimenVal = new Chunk(regimenes.Substring(0, regimenes.Length - 1).ToString(), fontVal);

                    pFooter.Add(cDataSpacer);
                    pFooter.Add(cRegimenLbl);
                    pFooter.Add(cRegimenVal);
                }

                if (electronicDocument.Data.FolioFiscalOriginal.Value.ToString().Length > 0)
                {
                    Chunk cFolioOriginal1Lbl = new Chunk("Datos CFDI Original - Serie: ", fontLbl);
                    Chunk cFolioOriginal1Val = new Chunk(electronicDocument.Data.SerieFolioFiscalOriginal.Value + "   ", fontVal);

                    Chunk cFolioOriginal2Lbl = new Chunk("Folio: ", fontLbl);
                    Chunk cFolioOriginal2Val = new Chunk(electronicDocument.Data.FolioFiscalOriginal.Value + "   ", fontVal);

                    Chunk cFolioOriginal3Lbl = new Chunk("Fecha: ", fontLbl);
                    Chunk cFolioOriginal3Val = new Chunk(electronicDocument.Data.FechaFolioFiscalOriginal.Value.ToString() + "   ", fontVal);

                    Chunk cFolioOriginal4Lbl = new Chunk("Monto: ", fontLbl);
                    Chunk cFolioOriginal4Val = new Chunk(electronicDocument.Data.MontoFolioFiscalOriginal.Value.ToString(), fontVal);

                    pFooter.Add(cSaltoLinea);
                    pFooter.Add(cFolioOriginal1Lbl);
                    pFooter.Add(cFolioOriginal1Val);
                    pFooter.Add(cFolioOriginal2Lbl);
                    pFooter.Add(cFolioOriginal2Val);
                    pFooter.Add(cFolioOriginal3Lbl);
                    pFooter.Add(cFolioOriginal3Val);
                    pFooter.Add(cFolioOriginal4Lbl);
                    pFooter.Add(cFolioOriginal4Val);
                }

                pFooter.Add(cLineaDiv);

                if (htFacturaxion["observaciones"].ToString().Length > 0)
                {
                    Chunk cObsLbl = new Chunk("Observaciones ", fontLbl);
                    Chunk cObsVal = new Chunk(htFacturaxion["observaciones"].ToString(), fontVal);
                    pFooter.Add(cObsLbl);
                    pFooter.Add(cSaltoLinea);
                    pFooter.Add(cObsVal);
                    pFooter.Add(cLineaDiv);
                }

                if (electronicDocument.Data.LugarExpedicion.Value.Length > 0)
                {
                    pFooter.Add(cExpedidoEnLbl);
                    pFooter.Add(cExpedidoEnVal);
                    pFooter.Add(cLineaDiv);
                }

                pFooter.Add(cCertificadoLbl);
                pFooter.Add(cCertificadoVal);
                pFooter.Add(cLineaDiv);

                if (timbrar)
                {
                    pFooter.Add(cCadenaOriginalPACLbl);
                    pFooter.Add(cSaltoLinea);
                    pFooter.Add(cCadenaOriginalPACVal);
                }
                else
                {
                    pFooter.Add(cCadenaOriginalLbl);
                    pFooter.Add(cSaltoLinea);
                    pFooter.Add(cCadenaOriginalVal);
                }

                pFooter.Add(cLineaDiv);
                pFooter.Add(cSelloDigitalLbl);
                pFooter.Add(cSaltoLinea);
                pFooter.Add(cSelloDigitalVal);
                pFooter.Add(cLineaSpace);

                document.Add(pFooter);

                #endregion

                #region "Añadimos Código Bidimensional"

                if (timbrar)
                {
                    Image imageQRCode = Image.GetInstance(bytesQRCode);
                    imageQRCode.Alignment = (Image.TEXTWRAP | Image.ALIGN_LEFT);
                    imageQRCode.ScaleToFit(90f, 90f);
                    imageQRCode.IndentationLeft = 9f;
                    imageQRCode.SpacingAfter = 9f;
                    imageQRCode.BorderColorTop = Color.WHITE;
                    document.Add(imageQRCode);
                    pFooter.Clear();

                    #region "Creación e Inserción de Chunks de Timbrado en Paragraph"

                    Chunk cFolioFiscalLbl = new Chunk("Folio Fiscal: ", fontLbl);
                    Chunk cFolioFiscalVal = new Chunk(objTimbre.Uuid.Value, fontVal);

                    Chunk cFechaTimbradoLbl = new Chunk("Fecha y Hora de Certificación: ", fontLbl);
                    DateTime fechaTimbrado = Convert.ToDateTime(objTimbre.FechaTimbrado.Value);
                    string formatoFechaTimbrado = fechaTimbrado.ToString("yyyy-MM-dd") + "T" + fechaTimbrado.ToString("HH:mm:ss");
                    Chunk cFechaTimbradoVal = new Chunk(formatoFechaTimbrado, fontVal);

                    Chunk cCertificadoSatLbl = new Chunk("Certificado SAT: ", fontLbl);
                    Chunk cCertificadoSatVal = new Chunk(objTimbre.NumeroCertificadoSat.Value, fontVal);

                    Chunk cSelloDigitalSatLbl = new Chunk("Sello Digital SAT", fontLbl);
                    Chunk cSelloDigitalSatVal = new Chunk(objTimbre.SelloSat.Value, fontVal);

                    pFooter.Add(cSaltoLinea);
                    pFooter.Add(cFolioFiscalLbl);
                    pFooter.Add(cFolioFiscalVal);
                    pFooter.Add(cDataSpacer);
                    pFooter.Add(cCertificadoSatLbl);
                    pFooter.Add(cCertificadoSatVal);
                    pFooter.Add(cSaltoLinea);
                    pFooter.Add(cFechaTimbradoLbl);
                    pFooter.Add(cFechaTimbradoVal);
                    pFooter.Add(cSaltoLinea);
                    pFooter.Add(cSelloDigitalSatLbl);
                    pFooter.Add(cSaltoLinea);
                    pFooter.Add(cSelloDigitalSatVal);

                    #endregion

                    document.Add(pFooter);
                }

                #endregion

                #region "Añadimos leyenda de CFDI"

                Paragraph pLeyendaCfdi = new Paragraph();
                string leyenda;

                if (timbrar)
                {
                    leyenda = "Este documento es una representación impresa de un CFDI";
                }
                else
                {
                    leyenda = "Este documento es una representación impresa de un Comprobante Fiscal Digital";
                }

                Chunk cLeyendaCfdi = new Chunk(leyenda, new Font(Font.HELVETICA, 8, Font.BOLD | Font.ITALIC));
                pLeyendaCfdi.Add(cLeyendaCfdi);
                pLeyendaCfdi.SetLeading(1.6f, 1.6f);
                document.Add(pLeyendaCfdi);

                #endregion

                #region "Footer"

                //Agregando Imagen de Pie de Página
                Image imgFooter = Image.GetInstance(dtConfigFact.Rows[0]["rutaTemplateFooter"].ToString());
                float imgFooterWidth = document.PageSize.Width - 70;
                float imgFooterHeight = imgFooter.Height / (imgFooter.Width / imgFooterWidth);

                imgFooter.ScaleAbsolute(imgFooterWidth, imgFooterHeight);
                imgFooter.SetAbsolutePosition(Convert.ToSingle(dtConfigFact.Rows[0]["footerPosX"]), Convert.ToSingle(dtConfigFact.Rows[0]["footerPosY"]));
                document.Add(imgFooter);

                // Si el rol del usuario es gratuito añadimos el footer las imagenes de facturaxion y r3take

                if (idRol == 16)
                {
                    Image facturaxionImgFooter = Image.GetInstance(ConfigurationManager.AppSettings["logoFacturaxion"]);
                    Image r3TakeImgFooter = Image.GetInstance(ConfigurationManager.AppSettings["logor3Take"]);

                    facturaxionImgFooter.ScaleAbsolute(70, 25);
                    r3TakeImgFooter.ScaleAbsolute(70, 25);

                    facturaxionImgFooter.SetAbsolutePosition(25, 10);
                    r3TakeImgFooter.SetAbsolutePosition(600, 10);

                    document.Add(facturaxionImgFooter);
                    document.Add(r3TakeImgFooter);
                }

                #endregion

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

                string filePdfExt = pathPdf.Replace(_rutaDocs, _rutaDocsExt);
                string urlPathFilePdf = filePdfExt.Replace(@"\", "/");

                //Subimos Archivo al Azure
                string res = App_Code.com.Facturaxion.facturaEspecial.wAzure.azureUpDownLoad(1, pathPdf);

                return "1#" + urlPathFilePdf;
            }
            catch (Exception ex)
            {
                fs.Flush();
                fs.Close();
                File.Delete(pathPdf);

                return "0#" + ex.Message;
            }
        }
Пример #28
0
        public ActionResult InformeEmpleado(int empno)
        {
            EMP empleado = this.entidad.EMP.Find(empno);
            Document doc = new Document(PageSize.LETTER);
            //CAPTURAMOS LA RUTA AL DOCUMENTO
            String ruta = HttpContext.Server.MapPath("/PDF/");
            ruta = ruta + "informe" + empno.ToString() + ".pdf";
            //PREGUNTAMOS SI EL DOCUMENTO EXISTE PREVIAMENTE
            if (System.IO.File.Exists(ruta))
            {
                return File(ruta, "application/pdf");
            }
            else
            {
                //CREAMOS EL DOCUMENTO
                PdfWriter writer = PdfWriter.GetInstance(doc,
                                            new FileStream(ruta, FileMode.Create));

                //INCLUIMOS TITULO Y AUTOR DEL DOCUMENTO
                doc.AddTitle("Informe empleado " + empleado.APELLIDO);
                doc.AddCreator("Ejemplo MVC");

                //ABRIMOS EL DOCUMENTO
                doc.Open();
                //DEFINIMOS LA FUENTE DEL DOCUMENTO
                iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 11, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

                //ENCABEZADO DEL DOCUMENTO
                doc.Add(new Paragraph("Informe del empleado: " + empleado.APELLIDO + ", " + DateTime.Now.ToLongDateString()));
                //DAMOS UN SALTO DE LINEA
                doc.Add(Chunk.NEWLINE);

                //CREAMOS UNA TABLA CON LOS DATOS PARA EL EMPLEADO
                //CON CUATRO DATOS A REPRESENTAR
                PdfPTable tabla = new PdfPTable(4);
                tabla.WidthPercentage = 100;

                //CREAMOS LAS COLUMNAS CON SU TITULO Y SU VALOR
                PdfPCell colapellido = new PdfPCell(new Phrase("APELLIDO", _standardFont));
                colapellido.BorderWidth = 0;
                colapellido.BorderWidthBottom = 0.75f;

                PdfPCell coloficio = new PdfPCell(new Phrase("OFICIO", _standardFont));
                coloficio.BorderWidth = 0;
                coloficio.BorderWidthBottom = 0.75f;

                PdfPCell colfecha = new PdfPCell(new Phrase("FECHA DE ALTA", _standardFont));
                colfecha.BorderWidth = 0;
                colfecha.BorderWidthBottom = 0.75f;

                PdfPCell colsalario = new PdfPCell(new Phrase("SALARIO", _standardFont));
                colsalario.BorderWidth = 0;
                colsalario.BorderWidthBottom = 0.75f;

                //AÑADIMOS LAS CELDAS A LA TABLA
                tabla.AddCell(colapellido);
                tabla.AddCell(coloficio);
                tabla.AddCell(colfecha);
                tabla.AddCell(colsalario);

                //AGREGAMOS DATOS A LAS CELDAS
                colapellido = new PdfPCell(new Phrase(empleado.APELLIDO, _standardFont));
                colapellido.BorderWidth = 0;

                coloficio = new PdfPCell(new Phrase(empleado.OFICIO, _standardFont));
                coloficio.BorderWidth = 0;

                colfecha = new PdfPCell(new Phrase(empleado.FECHA_ALT.ToString(), _standardFont));
                colfecha.BorderWidth = 0;

                colsalario = new PdfPCell(new Phrase(empleado.SALARIO.ToString() + "€", _standardFont));
                colsalario.BorderWidth = 0;

                //AÑADIMOS LAS CELDAS A LA TABLA
                tabla.AddCell(colapellido);
                tabla.AddCell(coloficio);
                tabla.AddCell(colfecha);
                tabla.AddCell(colsalario);
                //AGREGAMOS LA TABLA AL DOCUMENTO
                doc.Add(tabla);
                //CERRAMOS EL DOCUMENTO
                doc.Close();
                writer.Close();
                //DEVOLVEMOS EL DOCUMENTO CREADO
                return File(ruta, "application/pdf");

            }
        }
Пример #29
0
        public static string GenerateHerinnering(Factuur factuur)
        {
            try
            {
                var filename = GenerateFileNameHerinnering(factuur);
                using (var fs = new FileStream(Path.Combine(HerinneringFolder.FullName, filename), FileMode.Create))
                {
                    var document = new Document(PageSize.A4, 25, 25, 30, 1);
                    var writer = PdfWriter.GetInstance(document, fs);

                    // Add meta information to the document
                    document.AddAuthor("Dura - Vanseveren");
                    document.AddCreator("DuraFact");
                    document.AddKeywords("Herinnering");
                    document.AddSubject(string.Format("Herinnering voor factuur {0}", factuur.FactuurNummer));
                    document.AddTitle("Herinnering");

                    // Open the document to enable you to write to the document
                    document.Open();

                    // Makes it possible to add text to a specific place in the document using
                    // a X & Y placement syntax.
                    var content = writer.DirectContent;
                    // Add a footer template to the document
                    //	content.AddTemplate(PdfFooter(content, factuur), 30, 1);

                    // Add a logo to the invoice
                    var img = DuraLogo;
                    img.ScalePercent(80);
                    img.SetAbsolutePosition(40, 650);
                    content.AddImage(img);

                    // First we must activate writing
                    content.BeginText();

                    // First we write out the header information
                    AddKlantData(factuur, content);
                    WriteText(content, string.Format("Tielt, {0}", DateTime.Now.ToShortDateString()), 40, 600, 10);
                    WriteText(content, "Herinnering", 40, 550, 20, true);

                    WriteText(content, "Geachte heer/mevrouw", 40, 520, 10);
                    WriteText(content, string.Format("Wij hebben bij u een betalingsachterstand van {0:C} geconstateerd.", factuur.TotaalIncl), 40, 500, 10);
                    WriteText(content, "Dit bedrag heeft betrekking op de onderstaande factuur:", 40, 485, 10);

                    const int aantalMargin = 230, ehprijsMargin = 300, totaalMargin = 460;

                    WriteText(content, "Factuur", 140, 460, 12, true, PdfContentByte.ALIGN_RIGHT);
                    WriteText(content, "Datum", aantalMargin, 460, 12, true, PdfContentByte.ALIGN_RIGHT);
                    WriteText(content, "Bedrag", ehprijsMargin, 460, 12, true, PdfContentByte.ALIGN_RIGHT);
                    WriteText(content, "Betalingskenmerk", totaalMargin, 460, 12, true, PdfContentByte.ALIGN_RIGHT);

                    WriteText(content, factuur.FactuurNummer.ToString(), 140, 440, 10, false, PdfContentByte.ALIGN_RIGHT);
                    WriteText(content, factuur.FacturatieDatum.ToShortDateString(), aantalMargin, 440, 10, false, PdfContentByte.ALIGN_RIGHT);
                    WriteText(content, string.Format("{0:C}", factuur.TotaalIncl), ehprijsMargin, 440, 10, false, PdfContentByte.ALIGN_RIGHT);
                    WriteText(content, factuur.FacturatieDatum.ToShortDateString(), totaalMargin, 440, 10, false, PdfContentByte.ALIGN_RIGHT);

                    WriteText(content, string.Format("Wij verzoeken u nu vriendelijk het bovenstaande bedrag zulks ten bedrage van {0:C} te doen overmaken.", factuur.TotaalIncl), 40, 400, 10);
                    WriteText(content, "Dit kan op rekeningnummer 733-0318587-69 bij KBC of 001-6090654-03 bij BNP Paribas Fortis onder vermelding", 40, 385, 10);
                    WriteText(content, "van uw betalingskenmerk.", 40, 370, 10);
                    WriteText(content, "Wanneer u vragen mocht hebben over deze herinnering, verzoeken wij u zo spoedig mogelijk contact op te nemen", 40, 355, 10);
                    WriteText(content, "op het telefoonnummer (051) 40 34 77.", 40, 340, 10);
                    WriteText(content, "Heeft u inmiddels uw betalingsachterstand voldaan, dan is deze herinnering voor u niet meer van toepassing.", 40, 325, 10);
                    WriteText(content, "Hoogachtend,", 40, 280, 10);
                    WriteText(content, "Filip Vanseveren", 40, 180, 10);

                    // End the writing of text
                    content.EndText();

                    // Close the document, the writer and the filestream!
                    document.Close();
                    writer.Close();
                    fs.Close();
                    return Path.Combine(HerinneringFolder.FullName, filename);
                }
            }
            catch
            {
                return string.Empty;
            }
        }
Пример #30
0
        private void btnReporteMes_Click(object sender, RoutedEventArgs e)
        {
            if (!lfechareporte.Content.Equals(""))
            {
                if (!lventasMes.Content.Equals("0"))
                {
                    DateTime date = Convert.ToDateTime(lfechareporte.Content);
                    //MessageBox.Show(date.Month.ToString() + "/" + date.Year.ToString());
                    ventasFacade vfac = new ventasFacade();
                    List<MVentas> listVentasMes = vfac.getVentasByFechaMes(date);

                    if (listVentasMes.Count > 0)
                    {
                        SaveFileDialog exportSaveFileDialog = new SaveFileDialog();

                        exportSaveFileDialog.Title = "Guardar reporte ventas mensuales";
                        exportSaveFileDialog.Filter = "PDF(*.pdf)|*.pdf";
                        exportSaveFileDialog.FileName = "ReporteVentasMensuales";
                        exportSaveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                        if (exportSaveFileDialog.ShowDialog() == true)
                        {
                            // Creamos el documento con el tamaño de página tradicional
                            Document doc = new Document(PageSize.LETTER, 50, 50, 50, 50);
                            PdfWriter writer = null;
                            // Indicamos donde vamos a guardar el documento
                            try
                            {
                                writer = PdfWriter.GetInstance(doc, new FileStream(exportSaveFileDialog.FileName, FileMode.Create));
                                doc.AddCreator("Magnolia");
                                doc.Open();
                                iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance(urlLogo, System.Drawing.Imaging.ImageFormat.Png);
                                imagen.Alignment = Element.ALIGN_CENTER;
                                imagen.ScaleToFit(120f, 120f);
                                doc.Add(imagen);
                                doc.Add(Chunk.NEWLINE);

                                iTextSharp.text.Font _fontTitulo = new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 25, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);


                                iTextSharp.text.Paragraph titulo = new iTextSharp.text.Paragraph("Reporte de ventas mensual");
                                titulo.Alignment = Element.ALIGN_CENTER;
                                titulo.Font = _fontTitulo;
                                doc.Add(titulo);
                                doc.Add(Chunk.NEWLINE);

                                iTextSharp.text.Paragraph dgeneral = new iTextSharp.text.Paragraph("Detalles general");
                                dgeneral.Alignment = Element.ALIGN_LEFT;

                                //doc.AddTitle("Reporte de MVentas");
                                iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 8, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);


                                //////////////////////////////////////
                                ///////Tabla especificos    //////////
                                /////////////////////////////////////
                                iTextSharp.text.Paragraph despecifico = new iTextSharp.text.Paragraph("Detalles Especificos");
                                despecifico.Alignment = Element.ALIGN_LEFT;

                                // doc.Add(Chunk.NEWLINE);

                                categoriaFacade catFacEsp = new categoriaFacade();
                                ProductoFacade prodFacEsp = new ProductoFacade();
                                ventasFacade ventasFacEsp = new ventasFacade();
                                PdfPTable tblEspecifico = new PdfPTable(5);

                                string tempIdpro = "";

                                int dineroTotalbyCat = 0;
                                List<MVentas> listProductosinCatniInfoProd = new List<MVentas>();
                                List<MVentas> listProductoConCategoria = new List<MVentas>();

                                foreach (var item in listVentasMes)
                                {
                                    if (!tempIdpro.Equals(item.idProducto))
                                    {
                                        string IDCategoria = prodFacEsp.getIdCatbyidProd(item.idProducto);

                                        if (string.IsNullOrEmpty(IDCategoria))
                                        {
                                            //MessageBox.Show(item.idProducto + ":Sin categoria");
                                            //Agregar en celda distinta para obtener el total, no tienen categoria porque posiblemente se borra una categoria durante el mes o tiempo de uso.
                                            //Sin nombre de producto  ni categoria
                                            List<MVentas> listventaAgrupadabyFecha = ventasFacEsp.getVentasbyIdProdSinNombreGroupByFecha(item.idProducto, date);
                                            foreach (var i in listventaAgrupadabyFecha)
                                            {
                                                MVentas sinInfo = new MVentas(i.fecha, i.idProducto, i.nombreProducto, i.cantidad, i.total, i.idCategoria);
                                                bool exists = listProductosinCatniInfoProd.Any(x => x.fecha == sinInfo.fecha && x.idProducto == sinInfo.idProducto);
                                                if (!exists)
                                                {
                                                    listProductosinCatniInfoProd.Add(sinInfo);
                                                }

                                            }

                                            // existeSinCategoria = true;

                                        }
                                        else
                                        {
                                            //Con nombre de producto pero sin categoria
                                            string NombreCat = catFacEsp.getNombreCategoriaById(IDCategoria);
                                            if (string.IsNullOrEmpty(NombreCat))
                                            {

                                                List<MVentas> listventaAgrupadabyFecha = ventasFacEsp.getVentasbyIdProdGroupByFecha(item.idProducto, date);
                                                foreach (var i in listventaAgrupadabyFecha)
                                                {
                                                    MVentas sinInfo = new MVentas(i.fecha, i.idProducto, i.nombreProducto, i.cantidad, i.total, i.idCategoria);
                                                    listProductosinCatniInfoProd.Add(sinInfo);
                                                }

                                            }
                                            else
                                            {

                                                /*Agrupar por categoria los idproducto
                                                  Obtener todas las id categoria para obtener idprodudcto y buscar por idproducto en ventas 
                                                 * si no encuentra idproducto en ventas categoria no ha tenido ventas
                                                 * */
                                                //Obtiene el cantidadTotal , dineroTotal recaudado para producto agrupado por fecha
                                                List<MVentas> listVentaPorIdprod = ventasFacEsp.getVentasbyIdProdGroupByFecha(item.idProducto, date);
                                                foreach (var v in listVentaPorIdprod)
                                                {
                                                    //idcategoria que sera igual para distinto idproducto
                                                    MVentas ConInfo = new MVentas(v.fecha, v.idProducto, v.nombreProducto, v.cantidad, v.total, v.idCategoria);
                                                    bool exists = listProductoConCategoria.Any(x => x.fecha == ConInfo.fecha && x.idProducto == ConInfo.idProducto && x.idCategoria == ConInfo.idCategoria);
                                                    if (!exists)
                                                    {
                                                        listProductoConCategoria.Add(ConInfo);


                                                    }

                                                }

                                            }
                                        }
                                    }

                                }
                                //LLenar tabla especifico 
                                PdfPCell clFechaEsp = new PdfPCell();
                                PdfPCell clidprod = new PdfPCell();
                                PdfPCell clnombreprod = new PdfPCell();
                                PdfPCell clCant = new PdfPCell();
                                PdfPCell cltotalEsp = new PdfPCell();

                                listProductoConCategoria = listProductoConCategoria.OrderByDescending(i => i.idCategoria).ToList();

                                var q = from x in listProductoConCategoria
                                        group x.idCategoria by x.idCategoria into g
                                        let count = g.Count()
                                        /*orderby count descending*/
                                        select new { Value = g.Key, Count = count };


                                int posList = 0;
                                foreach (var x in q)
                                {
                                    tblEspecifico.WidthPercentage = 100;
                                    tblEspecifico.HorizontalAlignment = Element.ALIGN_LEFT;
                                    PdfPCell clnombreCat = new PdfPCell(new Phrase(catFacEsp.getNombreCategoriaById(x.Value.ToString()), _standardFont));
                                    clnombreCat.Colspan = 2;
                                    PdfPCell h1 = new PdfPCell(new Phrase(""));
                                    PdfPCell h2 = new PdfPCell(new Phrase(""));
                                    PdfPCell h3 = new PdfPCell(new Phrase(""));
                                    h1.Border = 0;
                                    h2.Border = 0;
                                    h3.Border = 0;
                                    tblEspecifico.AddCell(clnombreCat);
                                    tblEspecifico.AddCell(h1);
                                    tblEspecifico.AddCell(h2);
                                    tblEspecifico.AddCell(h3);

                                    clFechaEsp = new PdfPCell(new Phrase("Fecha", _standardFont));
                                    clidprod = new PdfPCell(new Phrase("IDProducto", _standardFont));
                                    clnombreprod = new PdfPCell(new Phrase("Nombre", _standardFont));
                                    clCant = new PdfPCell(new Phrase("Cantidad", _standardFont));
                                    //PdfPCell clTipoPag = new PdfPCell(new Phrase("Tipo Pago", _standardFont));
                                    cltotalEsp = new PdfPCell(new Phrase("Total", _standardFont));

                                    tblEspecifico.AddCell(clFechaEsp);
                                    tblEspecifico.AddCell(clidprod);
                                    tblEspecifico.AddCell(clnombreprod);
                                    tblEspecifico.AddCell(clCant);
                                    //tblEspecifico.AddCell(clTipoPag);
                                    tblEspecifico.AddCell(cltotalEsp);

                                    for (int i = 0; i < x.Count; i++)
                                    {
                                        var v = listProductoConCategoria[posList];

                                        clFechaEsp = new PdfPCell(new Phrase(v.fecha.ToString("d"), _standardFont));
                                        //clidprod = new PdfPCell(new Phrase(x.Value.ToString(), _standardFont));
                                        clidprod = new PdfPCell(new Phrase(v.idProducto.ToString(), _standardFont));

                                        //clnombreprod = new PdfPCell(new Phrase(v.idCategoria.ToString() + ":" + v.nombreProducto, _standardFont));
                                        clnombreprod = new PdfPCell(new Phrase(v.nombreProducto.ToString(), _standardFont));
                                        //clnombreprod= new PdfPCell(new Phrase(prodFacEsp.getnombreProdbyidProd(v.idProducto), _standardFont));
                                        clCant = new PdfPCell(new Phrase(v.cantidad.ToString(), _standardFont));
                                        //clTipoPag = new PdfPCell(new Phrase("", _standardFont));
                                        cltotalEsp = new PdfPCell(new Phrase(v.total.ToString(), _standardFont));

                                        tblEspecifico.AddCell(clFechaEsp);
                                        tblEspecifico.AddCell(clidprod);
                                        tblEspecifico.AddCell(clnombreprod);
                                        tblEspecifico.AddCell(clCant);
                                        //tblEspecifico.AddCell(clTipoPag);
                                        tblEspecifico.AddCell(cltotalEsp);
                                        dineroTotalbyCat = dineroTotalbyCat + Convert.ToInt32(v.total);
                                        tempIdpro = v.idProducto;
                                        posList = posList + 1;
                                    }
                                    //#################################
                                    //en cada categoria 
                                    //#################################
                                    clFechaEsp = new PdfPCell(new Phrase("", _standardFont));
                                    clidprod = new PdfPCell(new Phrase("", _standardFont));
                                    clnombreprod = new PdfPCell(new Phrase("", _standardFont));
                                    clCant = new PdfPCell(new Phrase("Subtotal($)", _standardFont));
                                    //clTipoPag = new PdfPCell(new Phrase("-----------", _standardFont));
                                    cltotalEsp = new PdfPCell(new Phrase(dineroTotalbyCat.ToString(), _standardFont));
                                    dineroTotalbyCat = 0;

                                    clFechaEsp.Border = 0;
                                    clidprod.Border = 0;
                                    clnombreprod.Border = 0;
                                    clCant.Border = 1;
                                    cltotalEsp.Border = 1;



                                    tblEspecifico.AddCell(clFechaEsp);
                                    tblEspecifico.AddCell(clidprod);
                                    tblEspecifico.AddCell(clnombreprod);
                                    tblEspecifico.AddCell(clCant);
                                    //tblEspecifico.AddCell(clTipoPag);
                                    tblEspecifico.AddCell(cltotalEsp);


                                    /////////////////////////////////////////////
                                    clFechaEsp = new PdfPCell(new Phrase("", _standardFont));
                                    clidprod = new PdfPCell(new Phrase("", _standardFont));
                                    clnombreprod = new PdfPCell(new Phrase("", _standardFont));
                                    clCant = new PdfPCell(new Phrase("", _standardFont));
                                    //clTipoPag = new PdfPCell(new Phrase("-----------", _standardFont));
                                    cltotalEsp = new PdfPCell(new Phrase("", _standardFont));
                                    clFechaEsp.Border = 0;
                                    clidprod.Border = 0;
                                    clnombreprod.Border = 0;
                                    clCant.Border = 0;
                                    cltotalEsp.Border = 0;

                                    cltotalEsp.FixedHeight = 30f;
                                    clFechaEsp.FixedHeight = 30f;
                                    clidprod.FixedHeight = 30f;
                                    clnombreprod.FixedHeight = 30f;
                                    clCant.FixedHeight = 30f;
                                    cltotalEsp.FixedHeight = 30f;

                                    tblEspecifico.AddCell(clFechaEsp);
                                    tblEspecifico.AddCell(clidprod);
                                    tblEspecifico.AddCell(clnombreprod);
                                    tblEspecifico.AddCell(clCant);
                                    //tblEspecifico.AddCell(clTipoPag);
                                    tblEspecifico.AddCell(cltotalEsp);
                                    //}
                                    // catActual = prodFac.getIdCatbyidProd(v.idProducto);
                                    //MessageBox.Show(catActual);


                                }


                                //#######################################################
                                //###### PRODUCTOS QUE SE HALLAN ELIMINADO ############
                                //#######################################################
                                //Tabla para tabla otros que no tengan una categoria asociada pero que igualmente deben estar en reportes de ventas.
                                bool otros = false;
                                PdfPTable tblOtros = new PdfPTable(5);
                                int totalOtros = 0;
                                int subtotalCosto_otros = 0;
                                int totalCosto_otros = 0;
                                int diferenciaVenta_otros = 0;
                                int totalDiferencia_otros = 0;
                                if (listProductosinCatniInfoProd.Count > 0)
                                {
                                    otros = true;
                                    tblOtros.WidthPercentage = 100;
                                    tblOtros.HorizontalAlignment = Element.ALIGN_LEFT;
                                    PdfPCell clnombreCat_otros = new PdfPCell(new Phrase("Otros", _standardFont));
                                    clnombreCat_otros.Colspan = 2;
                                    PdfPCell h11 = new PdfPCell(new Phrase(""));
                                    PdfPCell h22 = new PdfPCell(new Phrase(""));
                                    PdfPCell h33 = new PdfPCell(new Phrase(""));
                                    h11.Border = 0;
                                    h22.Border = 0;
                                    h33.Border = 0;
                                    tblOtros.AddCell(clnombreCat_otros);
                                    tblOtros.AddCell(h11);
                                    tblOtros.AddCell(h22);
                                    tblOtros.AddCell(h33);

                                    PdfPCell clFechaEsp_otros = new PdfPCell(new Phrase("Fecha", _standardFont));
                                    PdfPCell clidprod_otros = new PdfPCell(new Phrase("IDProducto", _standardFont));
                                    PdfPCell clnombreprod_otros = new PdfPCell(new Phrase("Nombre", _standardFont));
                                    PdfPCell clCant_otros = new PdfPCell(new Phrase("Cantidad", _standardFont));

                                    //PdfPCell clTipoPag = new PdfPCell(new Phrase("Tipo Pago", _standardFont));
                                    PdfPCell cltotalEsp_otros = new PdfPCell(new Phrase("Total", _standardFont));

                                    tblOtros.AddCell(clFechaEsp_otros);
                                    tblOtros.AddCell(clidprod_otros);
                                    tblOtros.AddCell(clnombreprod_otros);
                                    tblOtros.AddCell(clCant_otros);
                                    //tblEspecifico.AddCell(clTipoPag);
                                    tblOtros.AddCell(cltotalEsp_otros);


                                    foreach (var item in listProductosinCatniInfoProd)
                                    {
                                        clFechaEsp_otros = new PdfPCell(new Phrase(item.fecha.ToString("d"), _standardFont));
                                        clidprod_otros = new PdfPCell(new Phrase(item.idProducto, _standardFont));

                                        clnombreprod_otros = new PdfPCell(new Phrase(item.nombreProducto, _standardFont));
                                        //clnombreprod= new PdfPCell(new Phrase(prodFacEsp.getnombreProdbyidProd(v.idProducto), _standardFont));
                                        clCant_otros = new PdfPCell(new Phrase(item.cantidad.ToString(), _standardFont));
                                        //clTipoPag = new PdfPCell(new Phrase("", _standardFont));
                                        cltotalEsp_otros = new PdfPCell(new Phrase(item.total.ToString(), _standardFont));

                                        tblOtros.AddCell(clFechaEsp_otros);
                                        tblOtros.AddCell(clidprod_otros);
                                        tblOtros.AddCell(clnombreprod_otros);
                                        tblOtros.AddCell(clCant_otros);
                                        //tblEspecifico.AddCell(clTipoPag);
                                        tblOtros.AddCell(cltotalEsp_otros);
                                        totalOtros = totalOtros + Convert.ToInt32(item.total);

                                        if (string.IsNullOrEmpty(prodFacEsp.getPrecioCompraProducto(item.idProducto).ToString()))
                                        {
                                            subtotalCosto_otros = 0;
                                        }
                                        else
                                        {
                                            subtotalCosto_otros = item.cantidad * prodFacEsp.getPrecioCompraProducto(item.idProducto);
                                        }
                                        //MessageBox.Show("idProducto=" + item.idProducto);
                                        totalCosto_otros = totalCosto_otros + subtotalCosto_otros;
                                        diferenciaVenta_otros = totalOtros - subtotalCosto_otros; //subtotalCosto_otros - totalCosto_otros;
                                        totalDiferencia_otros = totalDiferencia_otros + diferenciaVenta_otros;


                                    }


                                    clFechaEsp_otros = new PdfPCell(new Phrase("", _standardFont));
                                    clidprod_otros = new PdfPCell(new Phrase("", _standardFont));
                                    clnombreprod_otros = new PdfPCell(new Phrase("", _standardFont));
                                    clCant_otros = new PdfPCell(new Phrase("Subtotal($)", _standardFont));
                                    //clTipoPag = new PdfPCell(new Phrase("-----------", _standardFont));
                                    cltotalEsp_otros = new PdfPCell(new Phrase(totalOtros.ToString(), _standardFont));
                                    clFechaEsp_otros.Border = 0;
                                    clidprod_otros.Border = 0;
                                    clnombreprod_otros.Border = 0;
                                    clCant_otros.Border = 1;
                                    cltotalEsp_otros.Border = 1;

                                    tblOtros.AddCell(clFechaEsp_otros);
                                    tblOtros.AddCell(clidprod_otros);
                                    tblOtros.AddCell(clnombreprod_otros);
                                    tblOtros.AddCell(clCant_otros);
                                    //tblEspecifico.AddCell(clTipoPag);
                                    tblOtros.AddCell(cltotalEsp_otros);
                                    clFechaEsp_otros = new PdfPCell(new Phrase("", _standardFont));
                                    clidprod_otros = new PdfPCell(new Phrase("", _standardFont));
                                    clnombreprod_otros = new PdfPCell(new Phrase("", _standardFont));
                                    clCant_otros = new PdfPCell(new Phrase("", _standardFont));
                                    //clTipoPag = new PdfPCell(new Phrase("-----------", _standardFont));
                                    cltotalEsp_otros = new PdfPCell(new Phrase("", _standardFont));
                                    clFechaEsp_otros.Border = 0;
                                    clidprod_otros.Border = 0;
                                    clnombreprod_otros.Border = 0;
                                    clCant_otros.Border = 0;
                                    cltotalEsp_otros.Border = 0;

                                    cltotalEsp_otros.FixedHeight = 50f;
                                    clFechaEsp_otros.FixedHeight = 50f;
                                    clidprod_otros.FixedHeight = 50f;
                                    clnombreprod_otros.FixedHeight = 50f;
                                    clCant_otros.FixedHeight = 50f;
                                    cltotalEsp_otros.FixedHeight = 50f;

                                    tblOtros.AddCell(clFechaEsp_otros);
                                    tblOtros.AddCell(clidprod_otros);
                                    tblOtros.AddCell(clnombreprod_otros);
                                    tblOtros.AddCell(clCant_otros);
                                    //tblEspecifico.AddCell(clTipoPag);
                                    tblOtros.AddCell(cltotalEsp_otros);

                                }

                                //#######################################################
                                //######            DETALLES GENERALES       ############
                                //#######################################################

                                PdfPTable tblGenerales = new PdfPTable(5);
                                //doc.SetMargins(0f, 0f, 0f, 0f);
                                tblGenerales.HorizontalAlignment = Element.ALIGN_LEFT;
                                // Configuramos el título de las columnas de la tabla
                                PdfPCell clFecha = new PdfPCell(new Phrase("Mes", _standardFont));
                                PdfPCell clCat = new PdfPCell(new Phrase("Categoria", _standardFont));
                                PdfPCell clSubtotal = new PdfPCell(new Phrase("Subtotal ventas", _standardFont));
                                PdfPCell clSubtotalCosto = new PdfPCell(new Phrase("Subtotal costo", _standardFont));
                                PdfPCell clDiferencia = new PdfPCell(new Phrase("Diferencia", _standardFont));
                                tblGenerales.AddCell(clFecha);
                                tblGenerales.AddCell(clCat);
                                tblGenerales.AddCell(clSubtotal);
                                tblGenerales.AddCell(clSubtotalCosto);
                                tblGenerales.AddCell(clDiferencia);

                                categoriaFacade catFac = new categoriaFacade();
                                ProductoFacade prodFac = new ProductoFacade();

                                int subtotal = 0;
                                int total = 0;
                                int posListG = 0;
                                int subtotalCosto = 0;
                                int totalCosto = 0;
                                int totalCostoVenta = 0;
                                int diferenciaVenta = 0;
                                int totalDiferencia = 0;

                                //Agrupar por categoria los idproducto
                                List<MVentas> ListcatGeneral = new List<MVentas>();
                                foreach (var x in q)
                                {
                                    for (int i = 0; i < x.Count; i++)
                                    {
                                        var v = listProductoConCategoria[posListG];


                                        subtotal = subtotal + Convert.ToInt32(v.total);
                                        subtotalCosto = v.cantidad * prodFac.getPrecioCompraProducto(v.idProducto);
                                        posListG = posListG + 1;
                                        totalCosto = totalCosto + subtotalCosto;
                                        diferenciaVenta = subtotal - totalCosto;
                                        totalDiferencia = totalDiferencia + diferenciaVenta;
                                        //gananciaReal = gananciaReal + totalDiferencia;

                                    }
                                    total = total + subtotal;
                                    clFecha = new PdfPCell(new Phrase(date.ToString("y"), _standardFont));
                                    clCat = new PdfPCell(new Phrase(catFac.getNombreCategoriaById(x.Value.ToString()), _standardFont));
                                    clSubtotal = new PdfPCell(new Phrase(subtotal.ToString(), _standardFont));
                                    clSubtotalCosto = new PdfPCell(new Phrase(subtotalCosto.ToString(), _standardFont));
                                    clDiferencia = new PdfPCell(new Phrase(diferenciaVenta.ToString(), _standardFont));
                                    tblGenerales.AddCell(clFecha);
                                    tblGenerales.AddCell(clCat);
                                    tblGenerales.AddCell(clSubtotal);
                                    tblGenerales.AddCell(clSubtotalCosto);
                                    tblGenerales.AddCell(clDiferencia);
                                    subtotal = 0;
                                    subtotalCosto = 0;
                                    diferenciaVenta = 0;
                                    totalCostoVenta = totalCostoVenta + totalCosto;
                                    totalCosto = 0;

                                }
                                if (otros)
                                {
                                    clFecha = new PdfPCell(new Phrase(date.ToString("y"), _standardFont));
                                    clCat = new PdfPCell(new Phrase("Otros", _standardFont));
                                    clSubtotal = new PdfPCell(new Phrase(totalOtros.ToString(), _standardFont));
                                    clSubtotalCosto = new PdfPCell(new Phrase(subtotalCosto_otros.ToString(), _standardFont));
                                    clDiferencia = new PdfPCell(new Phrase(diferenciaVenta_otros.ToString(), _standardFont));
                                    tblGenerales.AddCell(clFecha);
                                    tblGenerales.AddCell(clCat);
                                    tblGenerales.AddCell(clSubtotal);
                                    tblGenerales.AddCell(clSubtotalCosto);
                                    tblGenerales.AddCell(clDiferencia);
                                    total = total + totalOtros;

                                    subtotalCosto = subtotalCosto + totalCosto_otros;
                                    totalCosto = totalCosto + subtotalCosto;
                                    totalDiferencia = totalDiferencia + diferenciaVenta_otros;
                                    totalCostoVenta = totalCostoVenta + totalCosto_otros;
                                    //diferenciaVenta_otros = diferenciaVenta + diferenciaVenta_otros;
                                    //totalDiferencia_otros = totalDiferencia + diferenciaVenta_otros;
                                }

                                clFecha = new PdfPCell(new Phrase("", _standardFont));
                                clCat = new PdfPCell(new Phrase("Total ", _standardFont));
                                clSubtotal = new PdfPCell(new Phrase(total.ToString(), _standardFont));
                                clSubtotalCosto = new PdfPCell(new Phrase(totalCostoVenta.ToString(), _standardFont));
                                clDiferencia = new PdfPCell(new Phrase("", _standardFont));

                                clFecha.Border = 0;
                                tblGenerales.AddCell(clFecha);
                                tblGenerales.AddCell(clCat);
                                tblGenerales.AddCell(clSubtotal);
                                tblGenerales.AddCell(clSubtotalCosto);
                                tblGenerales.AddCell(clDiferencia);

                                //Ganancia Real

                                clFecha = new PdfPCell(new Phrase("", _standardFont));
                                clCat = new PdfPCell(new Phrase("", _standardFont));
                                clSubtotal = new PdfPCell(new Phrase("", _standardFont));
                                clSubtotalCosto = new PdfPCell(new Phrase("Ganancia Real", _standardFont));
                                clDiferencia = new PdfPCell(new Phrase(totalDiferencia.ToString(), _standardFont));

                                clFecha.Border = 0;
                                clCat.Border = 0;
                                clSubtotal.Border = 0;

                                tblGenerales.AddCell(clFecha);
                                tblGenerales.AddCell(clCat);
                                tblGenerales.AddCell(clSubtotal);
                                tblGenerales.AddCell(clSubtotalCosto);
                                tblGenerales.AddCell(clDiferencia);


                                int vtotales = listVentasMes.Count;
                                iTextSharp.text.Font _fontDe = new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 8, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);
                                iTextSharp.text.Paragraph ventasTotal = new iTextSharp.text.Paragraph("Total Ventas:" + vtotales.ToString(), _fontDe);
                                int efectivo = ventasFacEsp.getVentasByFechaMesPagoEfectivo(date);
                                int cuenta = ventasFacEsp.getVentasByFechaMesPagocuenta(date);
                                int debito = ventasFacEsp.getVentasByFechaMesPagodebito(date);
                                int cheque = ventasFacEsp.getVentasByFechaMesPagoCheque(date);
                                iTextSharp.text.Paragraph pago = new iTextSharp.text.Paragraph("Pago: Efectivo:" + efectivo.ToString() + "  Cuenta:" + cuenta.ToString() + "  Debito:" + debito.ToString() + "  Cheque:" + cheque.ToString(), _fontDe);
                                ventasTotal.Alignment = Element.ALIGN_LEFT;
                                if (otros)
                                {


                                    doc.Add(dgeneral);
                                    doc.Add(Chunk.NEWLINE);
                                    doc.Add(tblGenerales);
                                    doc.Add(ventasTotal);
                                    doc.Add(pago);
                                    doc.Add(Chunk.NEWLINE);
                                    doc.Add(despecifico);
                                    doc.Add(new Chunk("\n"));
                                    doc.Add(tblEspecifico);
                                    doc.Add(new Chunk("\n"));
                                    doc.Add(tblOtros);

                                }
                                else
                                {

                                    doc.Add(dgeneral);
                                    doc.Add(Chunk.NEWLINE);
                                    doc.Add(tblGenerales);
                                    doc.Add(ventasTotal);
                                    doc.Add(pago);
                                    doc.Add(Chunk.NEWLINE);
                                    doc.Add(despecifico);
                                    doc.Add(new Chunk("\n"));
                                    doc.Add(tblEspecifico);
                                    doc.Add(new Chunk("\n"));
                                }

                                int page = writer.PageNumber;
                                //iTextSharp.text.Paragraph p = new iTextSharp.text.Paragraph(page.ToString(), _standardFont);
                                //doc.Add(p);

                                doc.Close();
                                writer.Close();

                                //MessageBox.Show("Pdf Creado!");
                            }
                            // }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.ToString());
                            }
                            finally
                            {
                                doc.Close();
                                writer.Close();
                            }
                            System.Diagnostics.Process.Start(exportSaveFileDialog.FileName);
                        }


                    }
                    else
                    {
                        MessageBox.Show("Mes no ha tenido ventas", "Magnolia", MessageBoxButton.OK, MessageBoxImage.Error);
                    }


                }
                else
                {
                    MessageBox.Show("Mes no ha tenido ventas", "Magnolia", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            else
            {
                MessageBox.Show("Seleccionar fecha", "Magnolia", MessageBoxButton.OK, MessageBoxImage.Warning);
            }

        }
Пример #31
0
        public void PrintPDF()
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog()
            {
                Filter = "pdf|*.pdf"
            };

            saveFileDialog.ShowDialog();
            string fileName = saveFileDialog.FileName;

            iTextSharp.text.Document oDoc = new iTextSharp.text.Document(PageSize.A4, 25, 25, 30, 30);

            try {
                PdfWriter.GetInstance(oDoc, new FileStream(fileName, FileMode.Create));

                oDoc.Open();

                //Meta data
                oDoc.AddAuthor("Dariusz Momot & Łukasz Kudzia");
                oDoc.AddCreator("NutritionApp");
                oDoc.AddTitle("Grocery List");

                //Fonts
                Font titleFont = FontFactory.GetFont("Verdana", 8, Font.ITALIC);
                titleFont.Color = BaseColor.DARK_GRAY;

                Font cellFonnt = FontFactory.GetFont(FontFactory.COURIER, 12, BaseColor.DARK_GRAY);

                //Title
                Paragraph title = new Paragraph("Your grocery list from " + DateTime.Now, titleFont);
                title.Alignment = Element.ALIGN_CENTER;
                oDoc.Add(title);
                oDoc.Add(new Paragraph("\n"));
                oDoc.Add(new Paragraph("\n"));

                //Table
                PdfPTable table = new PdfPTable(3);
                foreach (var item in GroceryList)
                {
                    table.AddCell(item.Count.ToString());
                    table.AddCell(item.Units.ToString());
                    table.AddCell(item.Name);
                }
                table.HorizontalAlignment = Element.ALIGN_CENTER;
                table.PaddingTop          = 20f;
                oDoc.Add(table);
                oDoc.Add(new Paragraph("\n"));
                oDoc.Add(new Paragraph("\n"));

                Paragraph foter = new Paragraph("Create by NutritionApp", titleFont);
                oDoc.Add(foter);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Cannot save your list", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            finally
            {
                oDoc.Close();
            }
        }
Пример #32
0
        private void generateReport()
        {
            try
            {
                String equipmentName = "";

                document = new Document(PageSize.LETTER);

                String FilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\\Resources\\" + inspectionType.Text + "_" + DateTime.Today.ToString("yyyy-MM-dd") +".pdf";

                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(FilePath, FileMode.OpenOrCreate));
                document.Open();

                document.AddTitle("Report");
                document.AddSubject("Equipment Report");
                document.AddKeywords("Csharp, PDF, iText");
                document.AddAuthor("");
                document.AddCreator("");

                iTextSharp.text.Image pdfLogo = iTextSharp.text.Image.GetInstance(AppDomain.CurrentDomain.BaseDirectory + "\\Resources\\" + "logo.JPG");

                pdfLogo.Alignment = iTextSharp.text.Image.ALIGN_RIGHT;
                pdfLogo.ScaleAbsolute(150, 85);

                document.Add(pdfLogo);
                Paragraph preface = new Paragraph("Fire-Alert" + "\n" + "Report of " + inspectionType.Text + "\n", TimesTitle);

                preface.Alignment = Element.ALIGN_CENTER;

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

                #region Inspection table

                PdfPTable inspectionTable = new PdfPTable(1);

                if (inspectionType.Text.Contains("Extinguisher"))
                    equipmentName = "Extinguisher";
                else if (inspectionType.Text.Contains("Hose"))
                    equipmentName = "FireHoseCabinet";
                else if (inspectionType.Text.Contains("Light"))
                    equipmentName = "EmergencyLight";

                // Load XML inspection file from resources
                string url = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\\Resources\\inspection.xml";
                XmlDocument doc = new System.Xml.XmlDocument();
                doc.Load(url);
                XmlElement docElement = doc.DocumentElement;

                // loop through all childNodes
                XmlNode start = docElement.FirstChild;              // franchisee
                foreach (XmlNode c1 in start)                       // contracts
                {
                    foreach (XmlNode c2 in c1.ChildNodes)        // addresses
                    {

                        // Skip if not matching contract ID
                        if (Convert.ToInt32(c2.Attributes["id"].InnerText) == Convert.ToInt32(addressBox.SelectedValue))
                        {
                            Console.WriteLine(Convert.ToInt32(c1.Attributes["id"].InnerText));
                            Console.WriteLine(Convert.ToInt32(addressBox.SelectedValue));

                            #region Address info table

                            PdfPTable addrTable = new PdfPTable(4);
                            addrTable.HorizontalAlignment = Element.ALIGN_LEFT;
                            addrTable.TotalWidth = 530f;
                            addrTable.LockedWidth = true;

                            float[] addrWidths = new float[] { 50f, 100f, 50f, 100f };
                            addrTable.SetWidths(addrWidths);

                            XmlAttributeCollection billTo = c1.ParentNode.Attributes;
                            XmlAttributeCollection location = c2.Attributes;

                            string[] billToAddr = billTo["address"].InnerText.Split(',');

                            addCell(addrTable, "Bill To:", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT);
                            addCell(addrTable, billTo["name"].InnerText, 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);

                            addCell(addrTable, "Location:", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT);

                            addCell(addrTable, location["contact"].InnerText, 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);
                            addCell(addrTable, " ", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT);
                            addCell(addrTable, billToAddr[0], 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);

                            addCell(addrTable, " ", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT);
                            addCell(addrTable, location["address"].InnerText, 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);
                            addCell(addrTable, " ", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT);
                            addCell(addrTable, billToAddr[2] + "," + billToAddr[1], 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);

                            addCell(addrTable, " ", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT);
                            addCell(addrTable, location["city"].InnerText, 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);
                            addCell(addrTable, " ", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT);
                            addCell(addrTable, billToAddr[3], 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);

                            addCell(addrTable, " ", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT);
                            addCell(addrTable, location["postalCode"].InnerText, 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);

                            addCell(addrTable, "Tel:", 2, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT);
                            addCell(addrTable, new Franchisee().getAddress(Convert.ToInt32(start.Attributes["id"].InnerText))[0], 2, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);

                            String clientInfo = new Client().get(new ClientContract().getClient(addressBox.SelectedValue.ToString()));
                            String[] client = new String[9];
                            client = clientInfo.Split(',');

                            if (client.Length < 6)
                                client = new String[6] {"", "", "", "", "", "No client found" };

                            addCell(addrTable, "Contact:", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT);
                            addCell(addrTable, client[5], 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);
                            addCell(addrTable, "Tel:", 1, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT);
                            addCell(addrTable, client[3], 1, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);

                            addCell(addrTable, " ", 4, 4, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);

                            string technicianID = c2.Attributes["InspectorID"].InnerText;
                            string technicianName = new Users().getName(Convert.ToInt32(technicianID));
                            if (technicianName == null || technicianName == "")
                                technicianName = "Technician Not Found";

                            addCell(addrTable, "Technician: ", 2, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT);
                            addCell(addrTable, technicianName, 2, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);

                            addCell(addrTable, "Date: ", 2, 1, 0, BaseColor.WHITE, Times, PdfPCell.ALIGN_RIGHT);
                            addCell(addrTable, DateTime.Now.ToString("MMMM d, yyyy"), 2, 1, 0, BaseColor.WHITE, TimesRegular, PdfPCell.ALIGN_LEFT);

                            for (int i = 0; i < addrTable.Rows.Count; i++)
                                for (int j = 0; j < addrTable.Rows[i].GetCells().Length; j++)
                                {
                                    if (addrTable.Rows[i].GetCells()[j] == null)
                                        continue;

                                    if (j % 2 != 0)     // Add bottom border to info cells
                                        addrTable.Rows[i].GetCells()[j].Border = iTextSharp.text.Rectangle.BOTTOM_BORDER;
                                    else                // Remove bottom border from titles
                                        addrTable.Rows[i].GetCells()[j].Border = iTextSharp.text.Rectangle.NO_BORDER;
                                }

                            #endregion

                            document.Add(addrTable);

                            foreach (XmlNode c3 in c2.ChildNodes)   // floors
                            {
                                foreach (XmlNode c4 in c3.ChildNodes)    //rooms
                                {
                                    bool isFirstEquipment = true;
                                    int itemNum = 1;
                                    foreach (XmlNode c5 in c4.ChildNodes)    // equipment
                                    {
                                        if (c5.Name.Equals(equipmentName))
                                        {
                                            #region Set up header

                                            if (isFirstEquipment)   // Set up table header based on first piece of equipment
                                            {
                                                isFirstEquipment = false;

                                                inspectionTable = new PdfPTable(c5.Attributes.Count + c5.ChildNodes.Count + 1);
                                                inspectionTable.HorizontalAlignment = 0;
                                                inspectionTable.TotalWidth = 530f;
                                                inspectionTable.LockedWidth = true;
                                                float []iWidths = new float[c5.Attributes.Count + c5.ChildNodes.Count + 1];

                                                iWidths[0] = 20f;
                                                for (int i = 1; i < iWidths.Length; i++)
                                                {
                                                    if (i < c5.Attributes.Count + 1)
                                                        iWidths[i] = 35f;
                                                    else
                                                        iWidths[i] = 20f;
                                                }
                                                inspectionTable.SetWidths(iWidths);

                                                createHeader(inspectionTable, c5);
                                            }

                                            #endregion

                                            addEquipmentRow(inspectionTable, c5, itemNum);
                                            itemNum++;
                                        }

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

                #endregion

                document.Close();

            }
            catch (Exception ex)
            {
                MessageBox.Show("Could not display the document because " + ex.ToString());
            }
        }
Пример #33
0
        /// <summary>
        /// Exporta los datos de un grid a un archivo PDF.
        /// </summary>
        /// <param name="gvData">DataGridView donde se encuentra la información a exportar</param>
        /// <param name="sPath">Ruta donde se guardará el archivo fisico</param>
        /// <param name="Titulo">Título del documento a exportar</param>
        public void ExportGrid(DataGridView gvData, String sPath, String Titulo)
        {
            //Creating iTextSharp Table from the DataTable data
            if (gvData.Rows.Count < 1)
                throw new Exception("No Hay datos para exportar");
            PdfPTable pdfTable = new PdfPTable(gvData.ColumnCount);

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

            //Adding Header row
            foreach (DataGridViewColumn column in gvData.Columns)
            {
                PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText));
                cell.BackgroundColor = new iTextSharp.text.Color(240, 240, 240);
                pdfTable.AddCell(cell);
            }

            //Adding DataRow
            foreach (DataGridViewRow row in gvData.Rows)
            {
                foreach (DataGridViewCell cell in row.Cells)
                {
                    if (cell.Value.GetType().FullName.Equals("System.DateTime"))
                        pdfTable.AddCell(((DateTime)cell.Value).ToString("dd/MM/yyyy"));
                    else if (cell.Value.GetType().FullName.Equals("System.Decimal") || cell.Value.GetType().FullName.Equals("System.int"))
                    {
                        if (gvData.Columns[cell.ColumnIndex].Name.Equals("NoFactura"))
                            pdfTable.AddCell(((decimal)cell.Value).ToString("#,###"));
                        else if (gvData.Columns[cell.ColumnIndex].Name.Equals("Cantidad"))
                            pdfTable.AddCell(((decimal)cell.Value).ToString("N6"));
                        else
                            pdfTable.AddCell(((decimal)cell.Value).ToString("N2"));

                    }
                    else
                        pdfTable.AddCell(cell.Value.ToString());
                }
            }

            using (FileStream stream = new FileStream(sPath, FileMode.Create))
            {

                Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 10f);
                PdfWriter.GetInstance(pdfDoc, stream);
                iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 10, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK);

                pdfDoc.Open();
                pdfDoc.AddAuthor("LOS MEROS MEROS");
                pdfDoc.AddCreator("LOS MEROS MEROS");
                //pdfDoc.AddTitle("Generación de un pdf con itextSharp");
                Paragraph paragraph = new Paragraph();
                //paragraph.Font(iTextSharp.text.Font.BOLD);
                paragraph.Add(Titulo);
                paragraph.Font = _standardFont;
                paragraph.Alignment = Element.ALIGN_CENTER;
                pdfDoc.Add(new Paragraph(paragraph));

                pdfDoc.Add(Chunk.NEWLINE);
                pdfDoc.Add(pdfTable);
                pdfDoc.Close();
                stream.Close();

                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.StartInfo.FileName = sPath;
                proc.Start();
                proc.Close();
            }
        }
Пример #34
0
        public void ExtractPdf(DataGridView dataGridView, bool selectedParameter)
        {
            Phrase p = new Phrase("\n");

            #region Font seç
            BaseFont             trArial              = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\tahoma.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            iTextSharp.text.Font fontArial            = new iTextSharp.text.Font(trArial, 10, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.DARK_GRAY);
            iTextSharp.text.Font fontArialHeader      = new iTextSharp.text.Font(trArial, 11, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);
            iTextSharp.text.Font fontArialbold        = new iTextSharp.text.Font(trArial, 9, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.DARK_GRAY);
            iTextSharp.text.Font fontArialboldgeneral = new iTextSharp.text.Font(trArial, 10, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);
            #endregion

            #region Fatura pdf oluştur
            SaveFileDialog save = new SaveFileDialog();
            save.OverwritePrompt = false;
            save.Title           = "PDF Dosyaları";
            save.DefaultExt      = "pdf";
            save.Filter          = "pdf Dosyaları (*.pdf)|*.pdf|Tüm Dosyalar(*.*)|*.*";
            if (save.ShowDialog() == DialogResult.OK)
            {
                iTextSharp.text.Document pdfFile = new iTextSharp.text.Document();
                PdfWriter.GetInstance(pdfFile, new FileStream(save.FileName, FileMode.Create));
                pdfFile.Open();

                #region Fatura oluşturan bilgileri
                pdfFile.AddCreator("Hakedis");                     //Oluşturan kişinin isminin eklenmesi
                pdfFile.AddCreationDate();                         //Oluşturulma tarihinin eklenmesi
                pdfFile.AddAuthor("Hakedis" + applicationVersion); //Yazarın isiminin eklenmesi
                pdfFile.AddHeader(DateTime.Now.ToLongDateString(), "Hakediş " + DateTime.Now.ToLongDateString());
                pdfFile.AddTitle("Hakediş Rapor");                 //Başlık ve title eklenmesi
                #endregion

                #region Tablo Başlık tarih ve marka bilgileri
                PdfPTable markAndDateTable = new PdfPTable(2);
                markAndDateTable.TotalWidth         = 250f;
                markAndDateTable.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;

                PdfPCell markName = new PdfPCell(new Phrase("Hakediş " + applicationVersion, fontArialbold));
                markName.HorizontalAlignment = Element.ALIGN_LEFT;
                markName.VerticalAlignment   = Element.ALIGN_LEFT;
                markName.Border = 0;

                PdfPCell dateTimeReport = new PdfPCell(new Phrase(DateTime.Now.ToLongDateString(), fontArialbold));
                dateTimeReport.VerticalAlignment   = Element.ALIGN_RIGHT;
                dateTimeReport.HorizontalAlignment = Element.ALIGN_RIGHT;
                dateTimeReport.Border = 0;
                dateTimeReport.ExtraParagraphSpace = 5f;

                markAndDateTable.AddCell(markName);
                markAndDateTable.AddCell(dateTimeReport);
                #endregion

                #region Veri Tablosu İşlemleri

                #region Pdf Kolon Başlıklarını Belirleme
                int       columnCount     = dataGridView.Columns.Count;
                PdfPTable pdfColumnheader = new PdfPTable(columnCount - 2);
                pdfColumnheader.TotalWidth         = 400f;
                pdfColumnheader.LockedWidth        = true;
                pdfColumnheader.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
                if (selectedParameter == true)
                {
                    for (int i = 0; i < columnCount; i++)
                    {
                        if (i != 0 && i != 1)
                        {
                            PdfPCell columnName = new PdfPCell(new Phrase(dataGridView.Columns[i].HeaderText, fontArialHeader));
                            columnName.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                            columnName.VerticalAlignment   = PdfPCell.ALIGN_MIDDLE;
                            columnName.FixedHeight         = 30f;
                            columnName.Border = 1;
                            pdfColumnheader.AddCell(columnName);
                        }
                    }
                }
                else
                {
                    pdfColumnheader = new PdfPTable(columnCount - 1);
                    for (int i = 0; i < columnCount; i++)
                    {
                        if (i != 0)
                        {
                            PdfPCell columnName = new PdfPCell(new Phrase(dataGridView.Columns[i].HeaderText, fontArialHeader));
                            columnName.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                            columnName.VerticalAlignment   = PdfPCell.ALIGN_MIDDLE;
                            columnName.FixedHeight         = 30f;
                            columnName.Border = 1;
                            pdfColumnheader.AddCell(columnName);
                        }
                    }
                }

                #region Satır işlemleri

                int       rowsCount    = dataGridView.Rows.Count;
                PdfPTable pdfDataTable = new PdfPTable(columnCount - 2);
                if (selectedParameter == true)
                {
                    for (int i = 0; i <= rowsCount - 1; i++)
                    {
                        for (int j = 0; j < dataGridView.Rows[i].Cells.Count; j++)
                        {
                            if (j != 0 && j != 2)
                            {
                                PdfPCell cell2 = new PdfPCell(new Phrase(dataGridView.Rows[i].Cells[j].Value.ToString(), fontArial));
                                pdfDataTable.AddCell(cell2);
                            }
                        }
                    }
                }
                else
                {
                    pdfDataTable = new PdfPTable(columnCount - 1);
                    for (int i = 0; i <= rowsCount - 1; i++)
                    {
                        for (int j = 0; j < dataGridView.Rows[i].Cells.Count; j++)
                        {
                            if (j != 0)
                            {
                                PdfPCell cell2 = new PdfPCell(new Phrase(dataGridView.Rows[i].Cells[j].Value.ToString(), fontArial));
                                pdfDataTable.AddCell(cell2);
                            }
                        }
                    }
                }


                #endregion

                #region Toplam Bilgi Verileri
                PdfPTable tableTotalInfo = new PdfPTable(2);
                tableTotalInfo.TotalWidth         = 250f;
                tableTotalInfo.LockedWidth        = true;
                tableTotalInfo.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
                double totalManOfDay = 0;
                if (selectedParameter == true)
                {
                    for (int i = 0; i < dataGridView.Rows.Count; i++)
                    {
                        totalManOfDay += double.Parse(dataGridView.Rows[i].Cells[6].Value.ToString());
                    }
                }
                else
                {
                    for (int i = 0; i < dataGridView.Rows.Count; i++)
                    {
                        totalManOfDay += double.Parse(dataGridView.Rows[i].Cells[2].Value.ToString());
                    }
                }

                PdfPCell cellTotalManOfDay = new PdfPCell(new Phrase(totalManOfDay.ToString(), fontArial));
                cellTotalManOfDay.HorizontalAlignment = Element.ALIGN_CENTER;
                cellTotalManOfDay.VerticalAlignment   = Element.ALIGN_LEFT;
                PdfPCell cellTotal = new PdfPCell(new Phrase("Toplam İş Günü", fontArial));
                cellTotal.HorizontalAlignment = Element.ALIGN_CENTER;
                cellTotal.VerticalAlignment   = Element.ALIGN_LEFT;
                tableTotalInfo.AddCell(cellTotal);
                tableTotalInfo.AddCell(cellTotalManOfDay);
                #endregion

                #endregion

                #region Pdf Dosyasını yaz ve kapat
                if (pdfFile.IsOpen() == false)
                {
                    pdfFile.Open();
                }
                pdfFile.Add(markAndDateTable);
                pdfFile.Add(p);
                pdfFile.Add(pdfColumnheader);
                pdfFile.Add(p);
                pdfFile.Add(pdfDataTable);
                pdfFile.Add(p);
                pdfFile.Add(tableTotalInfo);
                //pdfFile.Add(p);
                //pdfFile.Add(p);
                //pdfFile.Add(p);
                //pdfFile.Add(nameSurname);
                //pdfFile.Add(p);
                //pdfFile.Add(signature);
                pdfFile.Close();
                #endregion
                #endregion
            }
            #endregion
        }
Пример #35
0
        private bool crearPdfCategorizado(string urlpdfcategorizado,List<Producto> listProducto,int numEtiq)
        {
            bool correct = false;
            try
            {
                //Etiqueta para rollo con 1 columnas de mica
                if (numEtiq == 0)
                {
                    // Creamos el documento con el tamaño de página tradicional
                    Document doc = new Document(PageSize.LETTER);
                    // Indicamos donde vamos a guardar el documento
                    PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(urlpdfcategorizado+".pdf", FileMode.Create));
                    doc.AddCreator("Magnolia");
                    doc.Open();
                    BaseFont serif = BaseFont.CreateFont(@"C:\Windows\Fonts\micross.ttf", "Identity-H", BaseFont.EMBEDDED);
                    iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(serif, Convert.ToInt32(txtTamanoFuente.Text), iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);

                    int col = 1;
                    int row = Convert.ToInt32(txtfila.Text);
                    PdfPTable tblPrueba = new PdfPTable(col);
                    doc.SetMargins(0f, 0f, 0f, 0f);
                    tblPrueba.HorizontalAlignment = Element.ALIGN_CENTER;
                    tblPrueba.WidthPercentage = 50;

                    foreach (var prod in listProducto)
                    {
                        int W = Convert.ToInt32(this.txtAncho.Text.Trim());
                        int H = Convert.ToInt32(this.txtAlto.Text.Trim());
                        b.Alignment = BarcodeLib.AlignmentPositions.CENTER;
                        BarcodeLib.TYPE type = BarcodeLib.TYPE.CODE128;
                        b.IncludeLabel = true;
                        b.LabelPosition = BarcodeLib.LabelPositions.BOTTOMCENTER;
                        b.Encode(type, prod.idProducto, W, H);
                        BarcodeLib.SaveTypes savetype = BarcodeLib.SaveTypes.PNG;
                        b.SaveImage(urlimagen, savetype);

                        iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance(urlimagen);
                        imagen.BorderWidth = 0;
                        imagen.Alignment = Element.ALIGN_CENTER;
                        imagen.ScaleToFit(150f, 150f);

                        string txtsobreBarra = "";
                        if (chkGenerateLabel.IsChecked.Value)
                        {
                            MessageBox.Show(prod.nombre.Length.ToString() + ";" + prod.nombre);
                            if (prod.nombre.Length > 25)
                            {
                                txtsobreBarra = prod.nombre.Substring(0, 25) + " $" + prod.precio;
                            }
                            else
                            {
                                txtsobreBarra = prod.nombre + " $" + prod.precio;
                            }
                            
                        }

                        for (int c = 0; c < col; c++)
                        {
                            for (int f = 0; f < row; f++)
                            {

                                PdfPCell clNombre = new PdfPCell { };
                                clNombre.BorderWidth = 0;
                                clNombre.Padding = 13;
                                clNombre.HorizontalAlignment = Element.ALIGN_CENTER;
                                iTextSharp.text.Paragraph textsobre = new iTextSharp.text.Paragraph(new Phrase(txtsobreBarra, _standardFont));
                                textsobre.Alignment = 1;
                                clNombre.AddElement(textsobre);
                                clNombre.AddElement(imagen);
                                tblPrueba.AddCell(clNombre);
                            }
                        }
                    }
                    doc.Add(tblPrueba);
                    doc.Close();
                    writer.Close();
                    //Etiqueta para rollo con 3 columnas de  mica
                    correct = true;
                }
                else if (numEtiq == 1)
                {
                    Document doc = new Document(PageSize.LETTER, 10f, 10f, 10f, 0f);
                    PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(urlpdfcategorizado + ".pdf", FileMode.Create));
                    doc.AddTitle("pdf");
                    doc.AddCreator("Magnolia");
                    doc.Open();
                    doc.Add(Chunk.NEWLINE);
                    BaseFont serif = BaseFont.CreateFont(@"C:\Windows\Fonts\micross.ttf", "Identity-H", BaseFont.EMBEDDED);
                    iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(serif, Convert.ToInt32(txtTamanoFuente.Text), iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);
                    int col = 3;
                    int row = Convert.ToInt32(txtfila.Text);
                    PdfPTable tblPrueba = new PdfPTable(col);
                    tblPrueba.WidthPercentage = 100;


                    foreach (var prod in listProducto)
                    {
                        int W = Convert.ToInt32(this.txtAncho.Text.Trim());
                        int H = Convert.ToInt32(this.txtAlto.Text.Trim());
                        b.Alignment = BarcodeLib.AlignmentPositions.CENTER;
                        BarcodeLib.TYPE type = BarcodeLib.TYPE.CODE128;
                        b.IncludeLabel = true;
                        b.LabelPosition = BarcodeLib.LabelPositions.BOTTOMCENTER;
                        b.Encode(type, prod.idProducto, W, H);
                        BarcodeLib.SaveTypes savetype = BarcodeLib.SaveTypes.PNG;
                        b.SaveImage(urlimagen, savetype);

                        iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance(urlimagen);
                        imagen.BorderWidth = 0;
                        imagen.Alignment = Element.ALIGN_CENTER;
                        imagen.ScaleToFit(150f, 150f);

                        string txtsobreBarra = "";
                        if (chkGenerateLabel.IsChecked.Value)
                        {
                            txtsobreBarra = prod.nombre + " $"+ prod.precio;
                        }

                        for (int c = 0; c < col; c++)
                        {
                            for (int f = 0; f < row; f++)
                            {

                                PdfPCell clNombre = new PdfPCell { };
                                clNombre.BorderWidth = 0;
                                clNombre.Padding = 13;
                                clNombre.HorizontalAlignment = Element.ALIGN_CENTER;
                                iTextSharp.text.Paragraph textsobre = new iTextSharp.text.Paragraph(new Phrase(txtsobreBarra, _standardFont));
                                textsobre.Alignment = 1;
                                clNombre.AddElement(textsobre);
                                clNombre.AddElement(imagen);
                                tblPrueba.AddCell(clNombre);
                            }
                        }
                    }
                    doc.Add(tblPrueba);
                    doc.Close();
                    writer.Close();
                    correct = true;
                }
                else if (numEtiq == 2)
                {

                    if (!string.IsNullOrEmpty(txtleft.Text))
                    {
                        if (!string.IsNullOrEmpty(txtright.Text))
                        {
                            if (!string.IsNullOrEmpty(txttop.Text))
                            {
                                if (!string.IsNullOrEmpty(txtbotom.Text))
                                {
                                    float left = float.Parse(txtleft.Text);
                                    float right = float.Parse(txtright.Text);
                                    float top = float.Parse(txttop.Text);
                                    float bottom = float.Parse(txtbotom.Text);


                                    Document doc = new Document(PageSize.LETTER, left, right, top, bottom);
                                    PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(urlpdfcategorizado + ".pdf", FileMode.Create));
                                    doc.AddTitle("pdf");
                                    doc.AddCreator("Magnolia");
                                    doc.Open();
                                    doc.Add(Chunk.NEWLINE);
                                    //System.Drawing.Font f=  new System.Drawing.Font("Microsoft Sans Serif", 10, System.Drawing.FontStyle.Regular);
                                    //FontFactory.GetFont("Microsoft Sans Serif", 10)
                                    BaseFont serif = BaseFont.CreateFont(@"C:\Windows\Fonts\micross.ttf", "Identity-H", BaseFont.EMBEDDED);
                                    iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(serif, Convert.ToInt32(txtTamanoFuente.Text), iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);

                                    int col = Convert.ToInt32(txtcolumnas.Text); ;
                                    int row = Convert.ToInt32(txtfila.Text);
                                    PdfPTable tblPrueba = new PdfPTable(col);
                                    tblPrueba.WidthPercentage = 100;

                                    foreach (var prod in listProducto)
                                    {
                                        int W = Convert.ToInt32(this.txtAncho.Text.Trim());
                                        int H = Convert.ToInt32(this.txtAlto.Text.Trim());
                                        b.Alignment = BarcodeLib.AlignmentPositions.CENTER;
                                        BarcodeLib.TYPE type = BarcodeLib.TYPE.CODE128;
                                        b.IncludeLabel = true;
                                        b.LabelPosition = BarcodeLib.LabelPositions.BOTTOMCENTER;
                                        b.Encode(type, prod.idProducto, W, H);
                                        BarcodeLib.SaveTypes savetype = BarcodeLib.SaveTypes.PNG;
                                        b.SaveImage(urlimagen, savetype);

                                        iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance(urlimagen);
                                        imagen.BorderWidth = 0;
                                        imagen.Alignment = Element.ALIGN_CENTER;
                                        imagen.ScaleToFit(150f, 150f);

                                        string txtsobreBarra = "";
                                        if (chkGenerateLabel.IsChecked.Value)
                                        {
                                            txtsobreBarra = prod.nombre + " $" + prod.precio;
                                        }

                                        for (int c = 0; c < col; c++)
                                        {
                                            for (int f = 0; f < row; f++)
                                            {

                                                PdfPCell clNombre = new PdfPCell { };
                                                clNombre.BorderWidth = 0;
                                                clNombre.Padding = 13;
                                                clNombre.HorizontalAlignment = Element.ALIGN_CENTER;
                                                iTextSharp.text.Paragraph textsobre = new iTextSharp.text.Paragraph(new Phrase(txtsobreBarra, _standardFont));
                                                textsobre.Alignment = 1;
                                                clNombre.AddElement(textsobre);
                                                clNombre.AddElement(imagen);
                                                tblPrueba.AddCell(clNombre);
                                            }
                                        }
                                    }
                                    doc.Add(tblPrueba);
                                    doc.Close();
                                    writer.Close();
                                    correct = true;

                                }
                                else
                                {
                                    MessageBox.Show("Ingresar margen: Abajo", "Magnolia", MessageBoxButton.OK, MessageBoxImage.Warning);

                                }
                            }
                            else
                            {
                                MessageBox.Show("Ingresar margen: Arriba", "Magnolia", MessageBoxButton.OK, MessageBoxImage.Warning);

                            }
                        }
                        else
                        {
                            MessageBox.Show("Ingresar margen:Derecho", "Magnolia", MessageBoxButton.OK, MessageBoxImage.Warning);

                        }
                    }
                    else
                    {
                        MessageBox.Show("Ingresar margen:Izquierdo", "Magnolia", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }

                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Cerrar PDf(s) abiertos", "Magnolia", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            return correct;
        }
        private void btnGenerar_Click(object sender, EventArgs e)
        {
            Document doc = new Document(PageSize.LETTER);
            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream("Disponibilidad para el cliente.pdf", FileMode.Create));
            doc.AddTitle("Disponibilidad para el cliente");
            doc.AddCreator("Dylan Corado");
            doc.Open();

            iTextSharp.text.Font fFontTitulo = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 13, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
            iTextSharp.text.Font fFontSubTitulo = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
            iTextSharp.text.Font fFontCuerpo = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

            iTextSharp.text.Image imagenEncabezado = iTextSharp.text.Image.GetInstance(@"C:\laboratoriologo.png");
            imagenEncabezado.Alignment = Element.ALIGN_LEFT;
            imagenEncabezado.ScaleToFit(50f, 50f);

            doc.Add(imagenEncabezado);

            Paragraph parrafoTitulo = new Paragraph("INSTRUCCIONES PARA EXAMENES", fFontTitulo);
            parrafoTitulo.Alignment = Element.ALIGN_CENTER;
            doc.Add(parrafoTitulo);

            Paragraph parrafoTitulo3 = new Paragraph("\n", fFontTitulo);
            parrafoTitulo.Alignment = Element.ALIGN_CENTER;
            doc.Add(parrafoTitulo3);

            iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

            // Creamos una tabla para el detalle
            PdfPTable tblPrueba = new PdfPTable(4);
            tblPrueba.WidthPercentage = 100;

            // Configuramos el título de las columnas de la tabla
            PdfPCell clExamen = new PdfPCell(new Phrase("Examen", _standardFont));
            clExamen.BorderWidth = 0;
            clExamen.BorderWidthBottom = 0.75f;

            PdfPCell clRequerimientos = new PdfPCell(new Phrase("Requerimientos", _standardFont));
            clRequerimientos.BorderWidth = 0;
            clRequerimientos.BorderWidthBottom = 0.75f;

            PdfPCell clMuestra = new PdfPCell(new Phrase("Muestra", _standardFont));
            clMuestra.BorderWidth = 0;
            clMuestra.BorderWidthBottom = 0.75f;

            PdfPCell clPrecio = new PdfPCell(new Phrase("Precio", _standardFont));
            clPrecio.BorderWidth = 0;
            clPrecio.BorderWidthBottom = 0.75f;

            // Añadimos las columnas a la tabla
            tblPrueba.AddCell(clExamen);
            tblPrueba.AddCell(clRequerimientos);
            tblPrueba.AddCell(clMuestra);
            tblPrueba.AddCell(clPrecio);

            try
            {
                MySqlCommand mComando = new MySqlCommand(String.Format("SELECT MaTIPOEXAMEN.cdesctipoexamen, MaMUESTRA.crequerimientos, MaMUESTRA.cdescmuestra, MaTIPOEXAMEN.cpreciotipoexamen FROM MaTIPOEXAMEN, MaMUESTRA WHERE MaTIPOEXAMEN.ncodmuestra = MaMUESTRA.ncodmuestra"), clasConexion.funConexion());
                MySqlDataReader mReader = mComando.ExecuteReader();

                string sExamen;
                string sRequerimientos;
                string sMuestra;
                string sPrecio;

                while (mReader.Read())
                {

                    sExamen = mReader.GetString(0);
                    sRequerimientos = mReader.GetString(1);
                    sMuestra = mReader.GetString(2);
                    sPrecio = mReader.GetString(3);

                    // Llenamos la tabla con información
                    clExamen = new PdfPCell(new Phrase(sExamen, _standardFont));
                    clExamen.BorderWidth = 0;

                    clRequerimientos = new PdfPCell(new Phrase(sRequerimientos, _standardFont));
                    clRequerimientos.BorderWidth = 0;

                    clMuestra = new PdfPCell(new Phrase(sMuestra, _standardFont));
                    clMuestra.BorderWidth = 0;

                    clPrecio = new PdfPCell(new Phrase(sPrecio, _standardFont));
                    clPrecio.BorderWidth = 0;

                    // Añadimos las celdas a la tabla
                    tblPrueba.AddCell(clExamen);
                    tblPrueba.AddCell(clRequerimientos);
                    tblPrueba.AddCell(clMuestra);
                    tblPrueba.AddCell(clPrecio);
                }

                // Finalmente, añadimos la tabla al documento PDF y cerramos el documento

                doc.Add(tblPrueba);

                doc.Close();
                writer.Close();
                MessageBox.Show("Reporte Generado con Exito", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Se produjo un error" + ex, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Пример #37
0
        private string crearPdf(int numEtiq)
        {
            string correct = "";
            try
            {
                //Etiqueta para rollo con 1 columnas de mica
                if (numEtiq == 0)
                {
                    // Creamos el documento con el tamaño de página tradicional
                    Document doc = new Document(PageSize.LETTER);
                    // Indicamos donde vamos a guardar el documento
                    PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(urlpdf+"//pdfGenerado1Col.pdf", FileMode.Create));
                    
                    doc.AddCreator("Magnolia");
                    doc.Open();
                    BaseFont serif = BaseFont.CreateFont(@"C:\Windows\Fonts\micross.ttf", "Identity-H", BaseFont.EMBEDDED);
                    iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(serif, Convert.ToInt32(txtTamanoFuente.Text), iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);

                    int col = 1;
                    int row = Convert.ToInt32(txtfila.Text);
                    PdfPTable tblPrueba = new PdfPTable(col);
                    doc.SetMargins(0f, 0f, 0f, 0f);
                    tblPrueba.HorizontalAlignment = Element.ALIGN_CENTER;
                    tblPrueba.WidthPercentage = 50;
                    iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance(urlimagen);
                    imagen.Alignment = Element.ALIGN_CENTER;
                    imagen.ScaleToFit(140f, 120f);

                    string txtsobreBarra = "";
                    if (chkGenerateLabel.IsChecked.Value)
                    {
                        txtsobreBarra = txtSobreBarra.Text;
                    }

                    for (int c = 0; c < col; c++)
                    {
                        for (int f = 0; f < row; f++)
                        {
                            PdfPCell clLabel = new PdfPCell(new Phrase(txtsobreBarra, _standardFont));
                            clLabel.HorizontalAlignment = Element.ALIGN_CENTER;
                            clLabel.BorderWidth = 0;

                            PdfPCell clNombre = new PdfPCell(imagen);
                            clNombre.HorizontalAlignment = Element.ALIGN_CENTER;
                            clNombre.BorderWidth = 0;
                            clNombre.PaddingBottom = 15;
                            tblPrueba.AddCell(clLabel);
                            tblPrueba.AddCell(clNombre);
                        }
                    }
                    doc.Add(tblPrueba);
                    doc.Close();
                    writer.Close();
                    //Etiqueta para rollo con 3 columnas de  mica
                    correct = urlpdf + "//pdfGenerado1Col.pdf";
                }
                else if (numEtiq == 1)
                {
                    Document doc = new Document(PageSize.LETTER, 10f, 10f, 10f, 0f);
                    PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(urlpdf + "//pdfGenerado3Col.pdf", FileMode.Create));
                    
                    doc.AddTitle("pdf");
                    doc.AddCreator("Magnolia");
                    doc.Open();
                    doc.Add(Chunk.NEWLINE);
                    BaseFont serif = BaseFont.CreateFont(@"C:\Windows\Fonts\micross.ttf", "Identity-H", BaseFont.EMBEDDED);
                    iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(serif, Convert.ToInt32(txtTamanoFuente.Text), iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);
                    int col = 3;
                    int row = Convert.ToInt32(txtfila.Text);
                    PdfPTable tblPrueba = new PdfPTable(col);
                    tblPrueba.WidthPercentage = 100;
                    iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance(urlimagen);
                    imagen.BorderWidth = 0;
                    imagen.Alignment = Element.ALIGN_CENTER;
                    imagen.ScaleToFit(150f, 150f);

                    string txtsobreBarra = "";
                    if (chkGenerateLabel.IsChecked.Value)
                    {
                        txtsobreBarra = txtSobreBarra.Text;
                    }

                    for (int c = 0; c < col; c++)
                    {
                        for (int f = 0; f < row; f++)
                        {

                            PdfPCell clNombre = new PdfPCell { };
                            clNombre.BorderWidth = 0;
                            clNombre.Padding = 13;
                            clNombre.HorizontalAlignment = Element.ALIGN_CENTER;
                            iTextSharp.text.Paragraph textsobre = new iTextSharp.text.Paragraph(new Phrase(txtsobreBarra, _standardFont));
                            textsobre.Alignment = 1;
                            clNombre.AddElement(textsobre);
                            clNombre.AddElement(imagen);
                            tblPrueba.AddCell(clNombre);
                        }
                    }
                    doc.Add(tblPrueba);
                    doc.Close();
                    writer.Close();
                    correct = urlpdf + "//pdfGenerado3Col.pdf";
                }
                else if (numEtiq == 2)
                {

                    if (!string.IsNullOrEmpty(txtleft.Text))
                    {
                        if (!string.IsNullOrEmpty(txtright.Text))
                        {
                            if (!string.IsNullOrEmpty(txttop.Text))
                            {
                                if (!string.IsNullOrEmpty(txtbotom.Text))
                                {
                                    float left = float.Parse(txtleft.Text);
                                    float right = float.Parse(txtright.Text);
                                    float top = float.Parse(txttop.Text);
                                    float bottom = float.Parse(txtbotom.Text);


                                    Document doc = new Document(PageSize.LETTER, left, right, top, bottom);
                                    PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(urlpdf + "//pdfGeneradoPersonalizado.pdf", FileMode.Create));
                                    correct = urlpdf + "//pdfGeneradoPersonalizado.pdf";
                                    doc.AddTitle("pdf");
                                    doc.AddCreator("Magnolia");
                                    doc.Open();
                                    doc.Add(Chunk.NEWLINE);
                                    //System.Drawing.Font f=  new System.Drawing.Font("Microsoft Sans Serif", 10, System.Drawing.FontStyle.Regular);
                                    //FontFactory.GetFont("Microsoft Sans Serif", 10)
                                    BaseFont serif = BaseFont.CreateFont(@"C:\Windows\Fonts\micross.ttf", "Identity-H", BaseFont.EMBEDDED);
                                    iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(serif, Convert.ToInt32(txtTamanoFuente.Text), iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);

                                    int col = Convert.ToInt32(txtcolumnas.Text); ;
                                    int row = Convert.ToInt32(txtfila.Text);
                                    PdfPTable tblPrueba = new PdfPTable(col);
                                    tblPrueba.WidthPercentage = 100;

                                    iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance(urlimagen);
                                    imagen.BorderWidth = 0;
                                    imagen.Alignment = Element.ALIGN_CENTER;
                                    imagen.ScaleToFit(150f, 150f);
                                    string txtsobreBarra = "";
                                    if (chkGenerateLabel.IsChecked.Value)
                                    {
                                        txtsobreBarra = txtSobreBarra.Text;
                                    }

                                    for (int c = 0; c < col; c++)
                                    {
                                        for (int f = 0; f < row; f++)
                                        {

                                            PdfPCell clNombre = new PdfPCell { };
                                            clNombre.BorderWidth = 0;
                                            clNombre.Padding = 13;
                                            clNombre.HorizontalAlignment = Element.ALIGN_CENTER;
                                            iTextSharp.text.Paragraph textsobre = new iTextSharp.text.Paragraph(new Phrase(txtsobreBarra, _standardFont));
                                            textsobre.Alignment = 1;
                                            clNombre.AddElement(textsobre);
                                            clNombre.AddElement(imagen);
                                            tblPrueba.AddCell(clNombre);
                                        }
                                    }
                                    doc.Add(tblPrueba);
                                    doc.Close();
                                    writer.Close();
                                    correct = urlpdf + "//pdfGeneradoPersonalizado.pdf";

                                }
                                else
                                {
                                    MessageBox.Show("Ingresar margen: Abajo", "Magnolia", MessageBoxButton.OK, MessageBoxImage.Warning);

                                }
                            }
                            else
                            {
                                MessageBox.Show("Ingresar margen: Arriba", "Magnolia", MessageBoxButton.OK, MessageBoxImage.Warning);

                            }
                        }
                        else
                        {
                            MessageBox.Show("Ingresar margen:Derecho", "Magnolia", MessageBoxButton.OK, MessageBoxImage.Warning);

                        }
                    }
                    else
                    {
                        MessageBox.Show("Ingresar margen:Izquierdo", "Magnolia", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }

                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Cerrar PDf(s) abiertos", "Magnolia", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            return correct;
        }
Пример #38
0
        private void SaveAsPDFA(ref string tempPDF, string pdfPath, MetaData md)
        {
            string tempdir = Path.Combine(Path.GetTempPath(), "GhostScriptWrapper");

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

            tempPDF = Path.Combine(tempdir, string.Format("{0}_tmp.pdf", Guid.NewGuid()));

            File.Copy(pdfPath, tempPDF);

            GhostScriptWrapper.CallAPI(GetArgs(tempPDF, pdfPath));

            var document = new it.Document();

            using (var fs = new FileStream(tempPDF, FileMode.Create))
            {
                // step 2: we create a writer that listens to the document
                //PdfCopy writer = new PdfCopy(document, fs);
                var pdfaWriter = ip.PdfAWriter.GetInstance(document, fs, ip.PdfAConformanceLevel.PDF_A_1B);

                pdfaWriter.SetTagged();
                pdfaWriter.CreateXmpMetadata();
                // step 3: we open the document
                document.Open();

                document.AddAuthor(md.Author);
                document.AddCreator(md.Creator);
                document.AddLanguage(md.Language);
                document.AddProducer();
                document.AddTitle(Path.GetFileNameWithoutExtension(pdfPath));

                // we create a reader for a certain document
                var reader = new ip.PdfReader(pdfPath);
                reader.ConsolidateNamedDestinations();

                document.NewPage();

                var icc = ip.ICC_Profile.GetInstance(Environment.GetEnvironmentVariable("SystemRoot") + @"\System32\spool\drivers\color\sRGB Color Space Profile.icm");
                pdfaWriter.SetOutputIntents("sRGB", null, "http://www.color.org", "sRGB IEC61966-2.1", icc.Data);

                // step 4: we add content
                for (var i = 1; i <= reader.NumberOfPages; i++)
                {
                    var page = pdfaWriter.GetImportedPage(reader, i);
                    pdfaWriter.DirectContentUnder.AddTemplate(page, 0, 0);

                    document.NewPage();
                }

                // step 5: we close the document and writer

                document.AddCreationDate();
                pdfaWriter.Flush();

                try
                {
                    pdfaWriter.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                reader.Close();
                try
                {
                    document.Close();
                }
                catch
                {
                }
            }

            ManipulatePdf(tempPDF, pdfPath, md);
        }
Пример #39
0
        void InventarioAlmacenToolStripMenuItemClick(object sender, EventArgs e)
        {
            Document document = new Document(PageSize.LETTER);
            PdfWriter.GetInstance(document, new FileStream("Administradores.pdf", FileMode.OpenOrCreate));
            document.Open();

            LoginMySql mostrar = new LoginMySql();
            MySqlDataReader reader = mostrar.mostrarAdministradores();
            document.AddAuthor("Eduardo y Oscar");
            document.AddCreator("Punto de venta Carniceria");
            document.Add(new  Paragraph("Administradores"));
            while(reader.Read())
            {
                string nombre = reader.GetValue(0).ToString();
                string password = reader.GetValue(1).ToString();
                string sueldo = reader.GetValue(2).ToString();
                string direccion = reader.GetValue(3).ToString();
                string telefono = reader.GetValue(4).ToString();

                document.Add(new Paragraph(nombre + " - " + password + " - " + sueldo + " - " + direccion + " - " + telefono));
            }
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo.FileName = "C:\\Users\\Cheyenne\\Desktop\\Proyecto\\puntodeventa\\bin\\Debug\\Administradores.pdf";
            proc.Start();
            proc.Close();
            document.Close();
        }
Пример #40
0
        public static string CreateFactuur(Factuur factuur)
        {
            try
            {
                var filename = GenerateFileName(factuur);
                using (var fs = new FileStream(Path.Combine(FactuurFolder.FullName, filename), FileMode.Create))
                {
                    var document = new Document(PageSize.A4, 25, 25, 30, 1);
                    var writer = PdfWriter.GetInstance(document, fs);
                    writer.PageEvent = new FactuurHelper();
                    // Add meta information to the document
                    document.AddAuthor("Dura - Vanseveren");
                    document.AddCreator("DuraFact");
                    document.AddKeywords("Factuur");
                    document.AddSubject(string.Format("Factuur {0}", factuur.FactuurNummer));
                    document.AddTitle("Factuur");

                    // Open the document to enable you to write to the document
                    document.Open();

                    // Makes it possible to add text to a specific place in the document using
                    // a X & Y placement syntax.
                    var content = writer.DirectContent;
                    // Add a footer template to the document
                    //	content.AddTemplate(PdfFooter(content, factuur), 30, 1);

                    // Add a logo to the invoice
                    var img = DuraLogo;
                    img.ScalePercent(80);
                    img.SetAbsolutePosition(40, 650);
                    content.AddImage(img);

                    // First we must activate writing
                    content.BeginText();

                    // First we write out the header information
                    AddKlantData(factuur, content);
                    WriteText(content, "Factuur", 40, 600, 20, true);
                    AddFactuurData(factuur, content);

                    // You need to call the EndText() method before we can write graphics to the document!
                    content.EndText();
                    // Separate the header from the rows with a line
                    // Draw a line by setting the line width and position
                    content.SetLineWidth(0f);
                    content.MoveTo(40, 590);
                    content.LineTo(560, 590);
                    content.Stroke();
                    // Don't forget to call the BeginText() method when done doing graphics!
                    content.BeginText();
                    // Before we write the lines, it's good to assign a "last position to write"
                    // variable to validate against if we need to make a page break while outputting.
                    // Change it to 510 to write to test a page break; the fourth line on a new page
                    const int lastwriteposition = 150;

                    // Loop thru the table of items and set the linespacing to 12 points.
                    // Note that we use the -= operator, the coordinates goes from the bottom of the page!
                    var topMargin = 570;
                    if (!string.IsNullOrEmpty(factuur.Opmerking))
                    {
                        WriteText(content, "Opmerking", 40, topMargin, 12, true);
                        topMargin -= 20;
                        foreach (string s in factuur.Opmerking.Split(new string[] { Environment.NewLine }, StringSplitOptions.None))
                        {
                            WriteText(content, s, 40, topMargin, 10);
                            topMargin -= 16;
                        }
                        topMargin -= 4;
                    }

                    AddItemData(factuur, document, lastwriteposition, content, ref topMargin);

                    // You need to call the EndText() method before we can write graphics to the document!
                    content.EndText();
                    // Separate the header from the rows with a line
                    // Draw a line by setting the line width and position
                    content.SetLineWidth(0f);
                    content.MoveTo(40, topMargin);
                    content.LineTo(560, topMargin);
                    content.Stroke();
                    // Don't forget to call the BeginText() method when done doing graphics!
                    content.BeginText();
                    topMargin -= 15;
                    AddBTWData(factuur, content, topMargin);

                    // End the writing of text
                    content.EndText();

                    // Close the document, the writer and the filestream!
                    document.Close();
                    writer.Close();
                    fs.Close();
                    return Path.Combine(FactuurFolder.FullName, filename);
                }
            }
            catch
            {
                return string.Empty;
            }
        }
Пример #41
0
        private Boolean AñadirDatos()
        {
            Document  doc    = new Document(PageSize.LETTER);
            PdfWriter writer = null;
            // Indicamos donde vamos a guardar el documento
            int numero = 0;

            for (int i = 0; i <= numero; i++)
            {
                if (System.IO.File.Exists("C:/Users/vichg/OneDrive/Escritorio/ControlAlumnos" + numero + ".pdf"))
                {
                    numero++;
                }
                else
                {
                    writer = PdfWriter.GetInstance(doc,
                                                   new FileStream(@"C:\Users\vichg\OneDrive\Escritorio\ControlAlumnos" + numero + ".pdf", FileMode.Create));
                }
            }

            // Le colocamos el título y el autor
            // **Nota: Esto no será visible en el documento
            doc.AddTitle("Lista de Alumnos ");
            doc.AddCreator("Luis Enrique García Rodríguez y Victor Hugo Gonzales Arreola");

            // Abrimos el archivo
            doc.Open();

            iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

            // Escribimos el encabezamiento en el documento
            doc.Add(new Paragraph("         Lista de ALumnos 2019 Clase Desarrollo Asp.NET"));
            doc.Add(Chunk.NEWLINE);

            // Creamos una tabla que contendrá el nombre, apellido y país
            // de nuestros visitante.
            PdfPTable tblPrueba = new PdfPTable(5);

            tblPrueba.WidthPercentage = 100;

            // Configuramos el título de las columnas de la tabla
            PdfPCell clControl = new PdfPCell(new Phrase("Numero Control", _standardFont));

            clControl.BorderWidth       = 0;
            clControl.BorderWidthBottom = 0.50f;

            PdfPCell clNombre = new PdfPCell(new Phrase("Nombre Alumno", _standardFont));

            clNombre.BorderWidth       = 0;
            clNombre.BorderWidthBottom = 0.50f;

            PdfPCell clCarrera = new PdfPCell(new Phrase("Carrera", _standardFont));

            clCarrera.BorderWidth       = 0;
            clCarrera.BorderWidthBottom = 0.50f;

            PdfPCell clSemestre = new PdfPCell(new Phrase("Semestre", _standardFont));

            clSemestre.BorderWidth       = 0;
            clSemestre.BorderWidthBottom = 0.50f;

            PdfPCell clCorreo = new PdfPCell(new Phrase("Correo", _standardFont));

            clCorreo.BorderWidth       = 0;
            clCorreo.BorderWidthBottom = 0.50f;


            // Añadimos las celdas a la tabla
            tblPrueba.AddCell(clControl);
            tblPrueba.AddCell(clNombre);
            tblPrueba.AddCell(clCarrera);
            tblPrueba.AddCell(clSemestre);
            tblPrueba.AddCell(clCorreo);

            int iPosicion = 0;

            foreach (GridViewRow row in GrdAlumnos.Rows)
            {
                doc.Add(Chunk.NEWLINE);
                iPosicion++;

                // Llenamos la tabla con información
                clControl             = new PdfPCell(new Phrase(row.Cells[0].Text, _standardFont));
                clControl.BorderWidth = 0;

                clNombre             = new PdfPCell(new Phrase(row.Cells[1].Text, _standardFont));
                clNombre.BorderWidth = 0;

                clCarrera             = new PdfPCell(new Phrase(row.Cells[2].Text, _standardFont));
                clCarrera.BorderWidth = 0;

                clSemestre             = new PdfPCell(new Phrase(row.Cells[3].Text, _standardFont));
                clSemestre.BorderWidth = 0;

                clCorreo             = new PdfPCell(new Phrase(row.Cells[4].Text, _standardFont));
                clCorreo.BorderWidth = 0;

                // Añadimos las celdas a la tabla
                tblPrueba.AddCell(clControl);
                tblPrueba.AddCell(clNombre);
                tblPrueba.AddCell(clCarrera);
                tblPrueba.AddCell(clSemestre);
                tblPrueba.AddCell(clCorreo);
            }
            doc.Add(tblPrueba);

            doc.Close();
            writer.Close();
            return(true);
        }
        protected void SonucYazdır_Click(object sender, EventArgs e)
        {
            MongoClient client        = new MongoClient();
            var         database      = client.GetDatabase("hastane");
            var         collection    = database.GetCollection <yatanhastalar>("yatanhastalar");
            var         servislistesi = collection.Find(x => x._id != null).ToList().SelectMany(x => x.ServisList).ToList();
            var         hastalistesi  = servislistesi.SelectMany(x => x.HastaList).ToList().Where(x => x._id == ObjectId.Parse(ddlHasta2.SelectedValue)).ToList().FirstOrDefault();

            var sonuc = database.GetCollection <islemsonuc>("sonuclistesi").Find(x => x._id == ObjectId.Parse(ddlsonuctarih.SelectedValue) && x.sonuc_cesidi == "Laboratuvar").ToList().SelectMany(x => x.SonucList).ToList();



            #region Font seç
            BaseFont             trArial              = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\tahoma.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            iTextSharp.text.Font fontArial            = new iTextSharp.text.Font(trArial, 10, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.DARK_GRAY);
            iTextSharp.text.Font fontArialHeader      = new iTextSharp.text.Font(trArial, 13, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);
            iTextSharp.text.Font fontArialbold        = new iTextSharp.text.Font(trArial, 9, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.DARK_GRAY);
            iTextSharp.text.Font fontArialboldgeneral = new iTextSharp.text.Font(trArial, 10, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);
            #endregion

            #region Sonuç pdf oluştur
            iTextSharp.text.Document pdfFile = new iTextSharp.text.Document();
            PdfWriter.GetInstance(pdfFile, new FileStream("C:\\Users\\Önder\\Desktop\\Yeni klasör\\Kan Sonucu (" + hastalistesi.hasta_adi + " " + hastalistesi.hasta_soyadi + " " + ddlsonuctarih.SelectedItem.Text + ").pdf", FileMode.Create));
            pdfFile.Open();
            #endregion

            #region Sonuç oluşturan bilgileri
            pdfFile.AddCreator("Önder");      //Oluşturan kişinin isminin eklenmesi
            pdfFile.AddCreationDate();        //Oluşturulma tarihinin eklenmesi
            pdfFile.AddAuthor("Laboratuvar"); //Yazarın isiminin eklenmesi
            pdfFile.AddHeader("Başlık", "PDF UYGULAMASI OLUSTUR");
            pdfFile.AddTitle("Sonuç Raporu"); //Başlık ve title eklenmesi
            #endregion

            #region Sonuç firma resmi ve tarihi oluştur
            iTextSharp.text.Image jpgimg = iTextSharp.text.Image.GetInstance(@"C:/Users/Önder/Desktop/Önder Fatih Buhurcu Staj Projesi/WebApplicationHastane/WebApplicationHastane/login/images/İsimsiz-1.png");
            jpgimg.ScalePercent(35);
            jpgimg.Alignment = iTextSharp.text.Image.LEFT_ALIGN;

            PdfPTable pdfTableHeader = new PdfPTable(3);
            pdfTableHeader.TotalWidth         = 500f;
            pdfTableHeader.LockedWidth        = true;
            pdfTableHeader.DefaultCell.Border = Rectangle.NO_BORDER;

            PdfPCell cellheader1 = new PdfPCell(jpgimg);
            cellheader1.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
            cellheader1.VerticalAlignment   = PdfPCell.ALIGN_BOTTOM;
            cellheader1.FixedHeight         = 60f;
            cellheader1.Border = 0;
            pdfTableHeader.AddCell(cellheader1);

            PdfPCell cellheader2 = new PdfPCell(new Phrase("SONUÇ RAPORU", fontArialHeader));
            cellheader2.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
            cellheader2.VerticalAlignment   = PdfPCell.ALIGN_MIDDLE;
            cellheader2.FixedHeight         = 60f;
            cellheader2.Border = 0;
            pdfTableHeader.AddCell(cellheader2);


            PdfPCell cellheader3 = new PdfPCell(new Phrase(DateTime.Now.ToShortDateString(), fontArial));
            cellheader3.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
            cellheader3.VerticalAlignment   = PdfPCell.ALIGN_MIDDLE;
            cellheader3.FixedHeight         = 60f;
            cellheader3.Border = 0;
            pdfTableHeader.AddCell(cellheader3);
            #endregion

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

            Paragraph yazi = new Paragraph("Hasta TC: " + hastalistesi.hasta_tc + "\nHasta Adı: " + hastalistesi.hasta_adi + "\nHasta Soyadı: " + hastalistesi.hasta_soyadi + "\n\n\n");


            #region Tabloyu Oluştur
            PdfPTable pdfTable = new PdfPTable(2);
            pdfTable.TotalWidth              = 500f;
            pdfTable.LockedWidth             = true;
            pdfTable.HorizontalAlignment     = 1;
            pdfTable.DefaultCell.Padding     = 5;
            pdfTable.DefaultCell.BorderColor = iTextSharp.text.BaseColor.GRAY;
            foreach (var item in sonuc)
            {
                pdfTable.AddCell(new Phrase(item.tahlil_adi, fontArialboldgeneral));
                pdfTable.AddCell(new Phrase(item.sonuc, fontArial));
            }
            #endregion

            #region Pdfe yaz ve dosyayı kapat
            if (pdfFile.IsOpen() == false)
            {
                pdfFile.Open();
            }
            pdfFile.Add(pdfTableHeader);
            pdfFile.Add(p);
            pdfFile.Add(yazi);
            pdfFile.Add(pdfTable);
            pdfFile.Close();
            #endregion
        }
        //create a new pdf document
        private void btn_Prepare_Click(object sender, EventArgs e)
        {
            //if all of these null
            if ((textboxAuthor.Text == "" || textboxCreator.Text == "" || textboxSubject.Text == "" || textboxKeyword.Text == "" || rtextboxParagraph.Text == "") || checkTextboxValues())
            {
                MessageBox.Show("PLEASE FILL IN THE TEXTBOXES", "Message Box", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
            }
            else
            {
                //the library for create a new pdf document
                iTextSharp.text.Document report = new iTextSharp.text.Document();
                //file path of newly created pdf file to save
                PdfWriter.GetInstance(report, new FileStream(@"C:\Users\Asus\Desktop\UPLOADFILES\" + textboxFileName.Text, FileMode.Create));
                //Author name, need for create a new pdf document
                report.AddAuthor(textboxAuthor.Text);
                //Creation Date, need for create a new pdf document
                report.AddCreationDate();
                //Creator, need for create a new pdf document
                report.AddCreator(textboxCreator.Text);
                //Subject, need for create a new pdf document
                report.AddSubject(textboxSubject.Text);
                //Keywords, need for create a new pdf document
                report.AddKeywords(textboxKeyword.Text);

                if (report.IsOpen() == false)
                {
                    //open report for create a new pdf document
                    report.Open();
                }
                //Paragraph, need for create a new pdf document
                report.Add(new Paragraph(rtextboxParagraph.Text));
                //open the connection
                db.openConnection();
                //a command line for add a new document
                SqlCommand query = new SqlCommand("INSERT INTO Table_DOCUMENT(file_Name,file_Path,file_CreationDate,u_ID) VALUES(@fn, @fp, @cd,@uid)", db.getConnection());
                //add the value in the textbox to @fn
                query.Parameters.AddWithValue("@fn", textboxFileName.Text);
                //add the value in the textbox to @fp
                query.Parameters.AddWithValue("@fp", textboxFilePath.Text + @"\" + textboxFileName.Text);
                //add the value in the combobox to @uid
                query.Parameters.AddWithValue("@uid", comboboxUserID.Text);
                //add the value in the textbox to @cd
                query.Parameters.AddWithValue("@cd", textboxFileDate.Text);

                if (textboxFileDate.Text == "" || textboxFileName.Text == "" || comboboxUserID.Text == "")
                {
                    MessageBox.Show("PLEASE ENTER THE NAME OF THE FILE: FILE NAME, CREATION DATE, OR USER ID", "Message Box", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                }
                else if (checkFileName())
                {
                    MessageBox.Show("This File Name Already Exist, Select A Different One", "Message Box", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                    textboxFileName.Text = "";
                }
                else
                {
                    //execute the query
                    if (query.ExecuteNonQuery() == 1)
                    {
                        //the record is successfully
                        MessageBox.Show("DATA WERE RECORDED", "Message Box", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);

                        //return the default values and colors
                        dateTimePicker1.ResetText();
                        textboxFileID.Text        = "file ID";
                        textboxFileID.ForeColor   = Color.DimGray;
                        textboxFileName.Text      = "filename.pdf";
                        textboxFileName.ForeColor = Color.DimGray;
                        comboboxUserID.Text       = "user id";
                        comboboxUserID.ForeColor  = Color.DimGray;
                        textboxFilePath.Text      = "file path";
                        textboxFilePath.ForeColor = Color.DimGray;
                        dateTimePicker1.ResetText();
                        textboxFileDate.Text      = "DD.MM.YYYY";
                        textboxFileDate.ForeColor = Color.DimGray;
                        textboxSubject.Text       = "";
                        rtextboxParagraph.Text    = "";
                        dateTimePicker1.Text      = "";
                        textboxAuthor.Text        = "";
                        textboxCreator.Text       = "";
                        textboxKeyword.Text       = "";
                    }
                    else
                    {
                        MessageBox.Show("ERROR", "Message Box", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                    }
                }
                //close the report
                report.Close();
                //close the connection
                db.closeConnection();
            }
        }
Пример #44
0
        /// <summary>
        /// Exports the chart to the specified output stream as binary. When 
        /// exporting to a web response the WriteToHttpResponse() method is likely
        /// preferred.
        /// </summary>
        /// <param name="outputStream">An output stream.</param>
        internal void WriteToStream(Stream outputStream)
        {
            switch (this.ContentType)
              {
            case "image/jpeg":
              CreateSvgDocument().Draw().Save(
            outputStream,
            ImageFormat.Jpeg);
              break;

            case "image/png":
              // PNG output requires a seekable stream.
              using (MemoryStream seekableStream = new MemoryStream())
              {
            CreateSvgDocument().Draw().Save(
                seekableStream,
                ImageFormat.Png);
            seekableStream.WriteTo(outputStream);
              }
              break;

            case "application/pdf":
              SvgDocument svgDoc = CreateSvgDocument();

              // Create PDF document.
              using (Document pdfDoc = new Document())
              {
            // Scalar to convert from 72 dpi to 150 dpi.
            float dpiScalar = 150f / 72f;

            // Set page size. Page dimensions are in 1/72nds of an inch.
            // Page dimensions are scaled to boost dpi and keep page
            // dimensions to a smaller size.
            pdfDoc.SetPageSize(new Rectangle(
              svgDoc.Width / dpiScalar,
              svgDoc.Height / dpiScalar));

            // Set margin to none.
            pdfDoc.SetMargins(0f, 0f, 0f, 0f);

            // Create PDF writer to write to response stream.
            using (PdfWriter pdfWriter = PdfWriter.GetInstance(
              pdfDoc,
              outputStream))
            {
              // Configure PdfWriter.
              pdfWriter.SetPdfVersion(PdfWriter.PDF_VERSION_1_5);
              pdfWriter.CompressionLevel = PdfStream.DEFAULT_COMPRESSION;

              // Add meta data.
              pdfDoc.AddCreator(PdfMetaCreator);
              pdfDoc.AddTitle(this.Name);

              // Output PDF document.
              pdfDoc.Open();
              pdfDoc.NewPage();

              // Create image element from SVG image.
              Image image = Image.GetInstance(svgDoc.Draw(), ImageFormat.Bmp);
              image.CompressionLevel = PdfStream.DEFAULT_COMPRESSION;

              // Must match scaling performed when setting page size.
              image.ScalePercent(100f / dpiScalar);

              // Add image element to PDF document.
              pdfDoc.Add(image);

              pdfDoc.CloseDocument();
            }
              }

              break;

            case "image/svg+xml":
              using (StreamWriter writer = new StreamWriter(outputStream))
              {
            writer.Write(this.Svg);
            writer.Flush();
              }

              break;

            default:
              throw new InvalidOperationException(string.Format(
            "ContentType '{0}' is invalid.", this.ContentType));
              }

              outputStream.Flush();
        }
Пример #45
0
 /// <summary>
 /// This function prints the invoice in pdf.
 /// </summary>
 /// <param name="_name">This parameter is customer's name.</param>
 /// <param name="_phoneNumber">This parameter is customer's phone number.</param>
 /// <param name="_adress">This parameter is customer's addres.</param>
 /// <param name="_paymentType">This parameter is Customer's payment type.</param>
 /// <param name="_delivery">This parameter is shipping cost.</param>
 /// <param name="_taxex">This parameter is tax.</param>
 /// <param name="_totalCost">This parameter is the total cost.</param>
 public void Document(string _name, string _phoneNumber, string _adress, string _paymentType, string _subtotal, string _delivery, string _taxex, string _totalCost)
 {
     try
     {
         NumberFormatInfo provider = new NumberFormatInfo();
         provider.NumberDecimalSeparator = ".";
         iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(PageSize.A4, 40f, 40f, 80f, 80f);
         PdfWriter.GetInstance(pdfDoc, new FileStream("InvoicePDF.pdf", FileMode.Create));
         pdfDoc.Open();
         pdfDoc.AddCreator("Dream Book Store");
         pdfDoc.AddCreationDate();
         pdfDoc.AddAuthor("Admin");
         pdfDoc.AddHeader("Dream Book Store", "Involce");
         pdfDoc.AddTitle("Dream Book Store");
         Paragraph spacer = new Paragraph("")
         {
             SpacingBefore = 30f,
             SpacingAfter  = 30f
         };
         string[] headers = new string[5];
         headers[0] = "ID";
         headers[1] = "Product Name";
         headers[2] = "Quantity";
         headers[3] = "Price";
         headers[4] = "Total Price";
         var logo = iTextSharp.text.Image.GetInstance(Resources.invoice, Resources.invoice.RawFormat);
         logo.ScalePercent(21f);
         logo.SetAbsolutePosition(pdfDoc.Left, pdfDoc.Top - 30);
         pdfDoc.Add(logo);
         var timeTable = new PdfPTable(new[] { .75f })
         {
             HorizontalAlignment = 2,
             WidthPercentage     = 40,
             DefaultCell         = { MinimumHeight = 12f, }
         };
         timeTable.AddCell("Date");
         timeTable.AddCell(DateTime.Now.ToString());
         pdfDoc.Add(timeTable);
         pdfDoc.Add(spacer);
         Paragraph elements1 = new Paragraph("Bill to :" +
                                             Environment.NewLine + "Dream Book Store" +
                                             Environment.NewLine + "Root" +
                                             Environment.NewLine + "Eskisehir Osmangazi University " +
                                             Environment.NewLine + "Computer Engineering Department " +
                                             Environment.NewLine + "0222 222 01 01" +
                                             Environment.NewLine + "*****@*****.**" +
                                             Environment.NewLine);
         Paragraph elements2 = new Paragraph("Ship to :" +
                                             Environment.NewLine + "Customer ID: " + MainWindow.cart.CustomerId1 +
                                             Environment.NewLine + _name +
                                             Environment.NewLine + _adress +
                                             Environment.NewLine + _phoneNumber +
                                             Environment.NewLine + _paymentType);
         elements1.Alignment = Element.ALIGN_LEFT;
         elements2.Alignment = Element.ALIGN_RIGHT;
         pdfDoc.Add(elements1);
         pdfDoc.Add(elements2);
         pdfDoc.Add(spacer);
         PdfPTable table = new PdfPTable(new[] { .75f, 2.5f, 1f, 1f, 1.5f })
         {
             HorizontalAlignment = 1,
             WidthPercentage     = 75,
             DefaultCell         = { MinimumHeight = 22f, }
         };
         for (int i = 0; i < headers.Length; i++)
         {
             PdfPCell cell = new PdfPCell(new PdfPCell());
             cell.AddElement(new Chunk(headers[i]));
             table.AddCell(cell);
         }
         for (int i = 0; i < ShoppingCart.ItemsToPurchase.Count; i++)
         {
             double TotalPrice = Convert.ToDouble((ShoppingCart.ItemsToPurchase[i].Product.Price), provider) * ShoppingCart.ItemsToPurchase[i].Quantity;
             table.AddCell(ShoppingCart.ItemsToPurchase[i].Product.Id);
             table.AddCell(ShoppingCart.ItemsToPurchase[i].Product.Name);
             table.AddCell(ShoppingCart.ItemsToPurchase[i].Quantity.ToString());
             table.AddCell(ShoppingCart.ItemsToPurchase[i].Product.Price);
             table.AddCell(TotalPrice.ToString());
         }
         pdfDoc.Add(table);
         Paragraph elements3 = new Paragraph("Subtotal :" + _subtotal +
                                             Environment.NewLine + "Delivery :" + _delivery +
                                             Environment.NewLine + "Taxex :" + _taxex +
                                             Environment.NewLine + "-----------------------" +
                                             Environment.NewLine + "Total Cost =" + _totalCost);
         elements3.Alignment = Element.ALIGN_RIGHT;
         pdfDoc.Add(elements3);
         pdfDoc.Close();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Пример #46
0
        public static string generarPdf(Hashtable htFacturaxion, HttpContext hc)
        {
            string pathPdf = htFacturaxion["rutaDocumentoPdf"].ToString();
            FileStream fs = new FileStream(pathPdf, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);

            try
            {
                DAL dal = new DAL();
                _ci.NumberFormat.CurrencyDecimalDigits = 2;

                ElectronicDocument electronicDocument = (ElectronicDocument)htFacturaxion["electronicDocument"];
                Data objTimbre = (Data)htFacturaxion["objTimbre"];
                timbrar = Convert.ToBoolean(htFacturaxion["timbrar"]);
                pathPdf = htFacturaxion["rutaDocumentoPdf"].ToString();
                Int64 idCfdi = Convert.ToInt64(htFacturaxion["idCfdi"]);

                #region "Obtenemos los datos del CFDI y Campos Opcionales"

                StringBuilder sbOpcionalEncabezado = new StringBuilder();
                DataTable dtOpcEnc = new DataTable();
                StringBuilder sbOpcionalDetalle = new StringBuilder();
                DataTable dtOpcDet = new DataTable();
                StringBuilder sbDataEmisor = new StringBuilder();
                DataTable dtDataEmisor = new DataTable();

                sbOpcionalEncabezado.
                    Append("SELECT ").
                    Append("campo3 AS ordenCompra, ").
                    Append("campo7 AS numCliente, ").
                    Append("campo8 AS NombreSuc, ").
                    Append("campo19 AS pedido, ").
                    Append("campo20 AS division, ").
                    Append("campo21 AS efectuarPago,  ").
                    Append("campo22 AS direccionPie,  ").
                    Append("campo23 AS paraConsultas, ").
                    Append("campo26 AS cantidadLetra, ").
                    Append("campo27 AS zona, ").
                    Append("campo28 AS vencimiento, ").
                    Append("campo29 AS corporateCode, ").
                    Append("campo31 AS hyperion, ").
                    Append("campo32 AS INTERICOM, ").
                    Append("campo30 AS oldCorporateCode, ").
                    Append("campo33 AS referencia, ").
                    Append("campo34 AS fechaRefDoc, ").
                    Append("campo36 AS codigoCorporativo, ").
                    Append("campo37 AS codigoCorporativoAnt, ").
                    Append("campo38 AS clienteNo, ").
                    Append("campo39 AS contacto, ").
                    Append("campo40 AS observaciones, ").
                    Append("campo41 AS NoAp, ").
                    Append("campo42 AS AnoAp, ").

                    Append("' ' AS [ENTREGADO-A-NOMBRE], ").
                    Append("campo10 + ' ' + campo11 + ' ' +  ").
                    Append("campo12 AS [ENTREGADO-A-CALLE], ").
                    Append("campo13 AS [ENTREGADO-A-COLONIA], ").
                    Append("campo18 AS [ENTREGADO-A-CP], ").
                    Append("campo15 AS [ENTREGADO-A-MUNIC], ").
                    Append("campo14 AS [ENTREGADO-A-LOCAL], ").
                    Append("campo16 AS [ENTREGADO-A-ESTADO], ").
                    Append("campo17 AS [ENTREGADO-A-PAIS] ").
                    Append("FROM opcionalEncabezado ").
                    Append("WHERE idCFDI = @0  AND ST = 1 ");

                sbOpcionalDetalle.
                    Append("SELECT ").
                    Append("COALESCE(campo1, '') AS codeLocal, ").
                    Append("COALESCE(campo3, '') AS lote, ").
                    Append("COALESCE(campo4, '') AS cantidad, ").
                    Append("COALESCE(campo5, '') AS expiracion, ").
                    Append("COALESCE(campo6, '') AS taxRate, ").
                    Append("COALESCE(campo7, '') AS taxPaid, ").
                    Append("COALESCE(campo10, '') AS codeOracle, ").
                    Append("COALESCE(campo11, '') AS codeISPC, ").
                    Append("COALESCE(campo12, '') AS codeImpuesto, ").
                    Append("COALESCE(campo13, '') AS centroCostos, ").
                    Append("COALESCE(campo14, '') AS clinico, ").
                    Append("COALESCE(campo15, '') AS proyecto, ").
                    Append("COALESCE(campo16, '') AS cantidadReal, ").
                    Append("COALESCE(campo17, '') AS descuento, ").
                    Append("COALESCE(campo18, '') AS codBarras ").
                    Append("FROM opcionalDetalle ").
                    Append("WHERE idCFDI = @0 ");

                sbDataEmisor.Append("SELECT nombreSucursal FROM sucursales WHERE idSucursal = @0 ");

                dtOpcEnc = dal.QueryDT("DS_FE", sbOpcionalEncabezado.ToString(), "F:I:" + idCfdi, hc);
                dtOpcDet = dal.QueryDT("DS_FE", sbOpcionalDetalle.ToString(), "F:I:" + idCfdi, hc);
                dtDataEmisor = dal.QueryDT("DS_FE", sbDataEmisor.ToString(), "F:I:" + htFacturaxion["idSucursalEmisor"].ToString(), hc);

                if (dtOpcDet.Rows.Count == 0)
                {
                    for (int i = 1; i <= electronicDocument.Data.Conceptos.Count; i++)
                    {
                        dtOpcDet.Rows.Add("", "0.00");
                    }
                }

                #endregion

                #region "Extraemos los datos del CFDI"

                Hashtable htDatosCfdi = new Hashtable();
                htDatosCfdi.Add("nombreEmisor", electronicDocument.Data.Emisor.Nombre.Value);
                htDatosCfdi.Add("rfcEmisor", electronicDocument.Data.Emisor.Rfc.Value);
                htDatosCfdi.Add("nombreReceptor", electronicDocument.Data.Receptor.Nombre.Value);
                htDatosCfdi.Add("rfcReceptor", electronicDocument.Data.Receptor.Rfc.Value);
                htDatosCfdi.Add("sucursal", dtDataEmisor.Rows[0]["nombreSucursal"]);
                htDatosCfdi.Add("serie", electronicDocument.Data.Serie.Value);
                htDatosCfdi.Add("folio", electronicDocument.Data.Folio.Value);
                htDatosCfdi.Add("fechaCfdi", electronicDocument.Data.Fecha.Value);
                htDatosCfdi.Add("UUID", objTimbre.Uuid.Value);

                #region "Dirección Emisor"

                StringBuilder sbDirEmisor1 = new StringBuilder();
                StringBuilder sbDirEmisor2 = new StringBuilder();
                StringBuilder sbDirEmisor3 = new StringBuilder();

                if (electronicDocument.Data.Emisor.Domicilio.Calle.Value.Length > 0)
                {
                    sbDirEmisor1.Append(electronicDocument.Data.Emisor.Domicilio.Calle.Value).Append(" ");
                }
                if (electronicDocument.Data.Emisor.Domicilio.NumeroExterior.Value.Length > 0)
                {
                    sbDirEmisor1.Append(electronicDocument.Data.Emisor.Domicilio.NumeroExterior.Value).Append(", ");
                }
                if (electronicDocument.Data.Emisor.Domicilio.NumeroInterior.Value.Length > 0)
                {
                    sbDirEmisor1.Append(" ").Append(electronicDocument.Data.Emisor.Domicilio.NumeroInterior.Value).Append(", ");
                }
                if (electronicDocument.Data.Emisor.Domicilio.Colonia.Value.Length > 0)
                {
                    sbDirEmisor2.Append(electronicDocument.Data.Emisor.Domicilio.Colonia.Value).Append(", ");
                }
                if (electronicDocument.Data.Emisor.Domicilio.Localidad.Value.Length > 0)
                {
                    sbDirEmisor2.Append(electronicDocument.Data.Emisor.Domicilio.Localidad.Value);
                }
                if (electronicDocument.Data.Emisor.Domicilio.Municipio.Value.Length > 0)
                {
                    sbDirEmisor3.Append(electronicDocument.Data.Emisor.Domicilio.Municipio.Value).Append(", ");
                }
                if (electronicDocument.Data.Emisor.Domicilio.Estado.Value.Length > 0)
                {
                    sbDirEmisor3.Append(electronicDocument.Data.Emisor.Domicilio.Estado.Value).Append(" ");
                }
                if (electronicDocument.Data.Emisor.Domicilio.CodigoPostal.Value.Length > 0)
                {
                    sbDirEmisor3.Append("CP ").Append(electronicDocument.Data.Emisor.Domicilio.CodigoPostal.Value).Append(", ");
                }
                sbDirEmisor3.Append(electronicDocument.Data.Emisor.Domicilio.Pais.Value);

                #endregion

                #region "Dirección Sucursal Expedido En"

                StringBuilder sbDirExpedido1 = new StringBuilder();
                StringBuilder sbDirExpedido2 = new StringBuilder();
                StringBuilder sbDirExpedido3 = new StringBuilder();

                if (electronicDocument.Data.Emisor.ExpedidoEn.Calle.Value.Length > 0)
                {
                    sbDirExpedido1.Append(electronicDocument.Data.Emisor.ExpedidoEn.Calle.Value).Append(" ");
                }
                if (electronicDocument.Data.Emisor.ExpedidoEn.NumeroExterior.Value.Length > 0)
                {
                    sbDirExpedido1.Append(" ").Append(electronicDocument.Data.Emisor.ExpedidoEn.NumeroExterior.Value).Append(", ");
                }
                if (electronicDocument.Data.Emisor.ExpedidoEn.NumeroInterior.Value.Length > 0)
                {
                    sbDirExpedido1.Append(" ").Append(electronicDocument.Data.Emisor.ExpedidoEn.NumeroInterior.Value);
                }
                if (electronicDocument.Data.Emisor.ExpedidoEn.Colonia.Value.Length > 0)
                {
                    sbDirExpedido2.Append(electronicDocument.Data.Emisor.ExpedidoEn.Colonia.Value).Append(", ");
                }
                if (electronicDocument.Data.Emisor.ExpedidoEn.Localidad.Value.Length > 0)
                {
                    sbDirExpedido2.Append(electronicDocument.Data.Emisor.ExpedidoEn.Localidad.Value);
                }
                if (electronicDocument.Data.Emisor.ExpedidoEn.Municipio.Value.Length > 0)
                {
                    sbDirExpedido3.Append(electronicDocument.Data.Emisor.ExpedidoEn.Municipio.Value).Append(", ");
                }
                if (electronicDocument.Data.Emisor.ExpedidoEn.Estado.Value.Length > 0)
                {
                    sbDirExpedido3.Append(electronicDocument.Data.Emisor.ExpedidoEn.Estado.Value).Append(" ");
                }
                if (electronicDocument.Data.Emisor.ExpedidoEn.CodigoPostal.Value.Length > 0)
                {
                    sbDirExpedido3.Append("CP ").Append(electronicDocument.Data.Emisor.ExpedidoEn.CodigoPostal.Value).Append(", ");
                }
                sbDirExpedido3.Append(electronicDocument.Data.Emisor.ExpedidoEn.Pais.Value);

                #endregion

                #region "Dirección Receptor"

                StringBuilder sbDirReceptor1 = new StringBuilder();
                StringBuilder sbDirReceptor2 = new StringBuilder();
                StringBuilder sbDirReceptor3 = new StringBuilder();

                if (electronicDocument.Data.Receptor.Domicilio.Calle.Value.Length > 0)
                {
                    sbDirReceptor1.Append(electronicDocument.Data.Receptor.Domicilio.Calle.Value).Append(" ");
                }
                if (electronicDocument.Data.Receptor.Domicilio.NumeroExterior.Value.Length > 0)
                {
                    sbDirReceptor1.Append(" ").Append(electronicDocument.Data.Receptor.Domicilio.NumeroExterior.Value).Append(" ");
                }
                if (electronicDocument.Data.Receptor.Domicilio.NumeroInterior.Value.Length > 0)
                {
                    sbDirReceptor1.Append(" ").Append(electronicDocument.Data.Receptor.Domicilio.NumeroInterior.Value);
                }
                if (electronicDocument.Data.Receptor.Domicilio.Colonia.Value.Length > 0)
                {
                    sbDirReceptor2.Append(electronicDocument.Data.Receptor.Domicilio.Colonia.Value).Append(", ");
                }
                if (electronicDocument.Data.Receptor.Domicilio.Localidad.Value.Length > 0)
                {
                    sbDirReceptor2.Append(electronicDocument.Data.Receptor.Domicilio.Localidad.Value);
                }
                if (electronicDocument.Data.Receptor.Domicilio.Municipio.Value.Length > 0)
                {
                    sbDirReceptor3.Append(electronicDocument.Data.Receptor.Domicilio.Municipio.Value).Append(", ");
                }
                if (electronicDocument.Data.Receptor.Domicilio.Estado.Value.Length > 0)
                {
                    sbDirReceptor3.Append(electronicDocument.Data.Receptor.Domicilio.Estado.Value).Append(" ");
                }
                if (electronicDocument.Data.Receptor.Domicilio.CodigoPostal.Value.Length > 0)
                {
                    sbDirReceptor3.Append("CP ").Append(electronicDocument.Data.Receptor.Domicilio.CodigoPostal.Value).Append(", ");
                }
                sbDirReceptor3.Append(electronicDocument.Data.Receptor.Domicilio.Pais.Value);

                #endregion

                htDatosCfdi.Add("direccionEmisor1", sbDirEmisor1.ToString());
                htDatosCfdi.Add("direccionEmisor2", sbDirEmisor2.ToString());
                htDatosCfdi.Add("direccionEmisor3", sbDirEmisor3.ToString());

                htDatosCfdi.Add("direccionExpedido1", sbDirExpedido1.ToString());
                htDatosCfdi.Add("direccionExpedido2", sbDirExpedido2.ToString());
                htDatosCfdi.Add("direccionExpedido3", sbDirExpedido3.ToString());

                htDatosCfdi.Add("direccionReceptor1", sbDirReceptor1.ToString());
                htDatosCfdi.Add("direccionReceptor2", sbDirReceptor2.ToString());
                htDatosCfdi.Add("direccionReceptor3", sbDirReceptor3.ToString());

                #endregion

                #region "Creamos el Objeto Documento y Tipos de Letra"

                Document document = new Document(PageSize.LETTER, 15, 15, 15, 40);
                document.AddAuthor("Facturaxion");
                document.AddCreator("r3Take");
                document.AddCreationDate();

                //FileStream fs = new FileStream(pathPdf, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                pdfPageEventHandlerPfizer pageEventHandler = new pdfPageEventHandlerPfizer();
                PdfWriter writer = PdfWriter.GetInstance(document, fs);
                writer.SetFullCompression();
                writer.ViewerPreferences = PdfWriter.PageModeUseNone;
                writer.PageEvent = pageEventHandler;
                writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_7);

                //document.Open();

                HTC = hc;
                pathIMGLOGO = @"C:\Inetpub\repositorioFacturaxion\imagesFacturaEspecial\PFI730206632\logo-pfizer.jpg";

                azul = new Color(13, 142, 244);
                blanco = new Color(255, 255, 255);
                Link = new Color(7, 73, 208);
                gris = new Color(13, 142, 244);
                grisOX = new Color(74, 74, 74);
                rojo = new Color(230, 7, 7);
                lbAzul = new Color(5, 146, 230);

                EM = BaseFont.CreateFont(@"C:\Windows\Fonts\VERDANA.TTF", BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
                f5 = new Font(EM, 5, Font.NORMAL, grisOX);
                f5B = new Font(EM, 5, Font.BOLD, grisOX);
                f5BBI = new Font(EM, 5, Font.BOLDITALIC, grisOX);
                f6 = new Font(EM, 6, Font.NORMAL, grisOX);
                f6B = new Font(EM, 6, Font.BOLD, grisOX);
                f6L = new Font(EM, 6, Font.BOLD, Link);
                f5L = new Font(EM, 5, Font.BOLD, lbAzul);
                titulo = new Font(EM, 6, Font.BOLD, blanco);
                folio = new Font(EM, 6, Font.BOLD, rojo);
                dSaltoLinea = new Chunk("\n\n ");

                #endregion

                #region "Generamos el Docuemto"

                string RFC = string.Empty;
                RFC = htDatosCfdi["rfcEmisor"].ToString();
                switch (RFC)
                {
                    case "PFI730206632":
                        #region "Docuemto PFI730206632"
                        switch (htDatosCfdi["serie"].ToString())
                        {
                            case "E":
                            case "G":
                                htDatosCfdi.Add("tipoDoc", "FACTURA");
                                formatoEGFH(document, electronicDocument, objTimbre, pageEventHandler, dtOpcEnc, dtOpcDet, htDatosCfdi, HTC);
                                break;
                            case "F":
                            case "H":
                                htDatosCfdi.Add("tipoDoc", "NOTA DE CRÉDITO");
                                formatoEGFH(document, electronicDocument, objTimbre, pageEventHandler, dtOpcEnc, dtOpcDet, htDatosCfdi, HTC);
                                break;
                            case "A":
                            case "C":
                            case "I":
                            case "K":
                            case "M":
                                htDatosCfdi.Add("tipoDoc", "FACTURA");
                                formatoABCDIJKLM(document, electronicDocument, objTimbre, pageEventHandler, idCfdi, dtOpcEnc, dtOpcDet, htDatosCfdi, HTC);
                                break;

                            case "B":
                            case "D":
                            case "J":
                            case "L":
                            case "N":
                                htDatosCfdi.Add("tipoDoc", "NOTA DE CRÉDITO");
                                formatoABCDIJKLM(document, electronicDocument, objTimbre, pageEventHandler, idCfdi, dtOpcEnc, dtOpcDet, htDatosCfdi, HTC);
                                break;

                            //case "N":
                            //    htDatosCfdi.Add("tipoDoc", "NOTA DE CRÉDITO");
                            //    formatoN(document, pageEventHandler, dtOpcEnc, dtOpcDet, htDatosCfdi, HTC);
                            //    break;

                            default:
                                break;
                        }
                        break;
                        #endregion
                    case "P&U960326AG7":
                        htDatosCfdi.Add("tipoDoc", "FACTURA");
                        PYU960326AG7(document, electronicDocument, objTimbre, pageEventHandler, dtOpcEnc, dtOpcDet, htDatosCfdi, HTC);
                        break;
                    case "PME970204V63":
                        #region "Documento PME970204V63"
                        switch (htDatosCfdi["serie"].ToString())
                        {
                            case "A":
                                htDatosCfdi.Add("tipoDoc", "FACTURA");
                                formatoABCDIJKLM(document, electronicDocument, objTimbre, pageEventHandler, idCfdi, dtOpcEnc, dtOpcDet, htDatosCfdi, HTC);
                                break;
                            case "B":
                                htDatosCfdi.Add("tipoDoc", "NOTA DE CRÉDITO");
                                formatoABCDIJKLM(document, electronicDocument, objTimbre, pageEventHandler, idCfdi, dtOpcEnc, dtOpcDet, htDatosCfdi, HTC);
                                break;
                        }
                        break;
                        #endregion
                    case "SP&040526HD3":
                        break;
                }

                #endregion

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

                string filePdfExt = pathPdf.Replace(_rutaDocs, _rutaDocsExt);
                string urlPathFilePdf = filePdfExt.Replace(@"\", "/");

                //Subimos Archivo al Azure
                wAzure.azureUpDownLoad(1, pathPdf);

                return "1#" + urlPathFilePdf;
            }
            catch (Exception ex)
            {
                fs.Flush();
                fs.Close();
                File.Delete(pathPdf);

                return "0#" + ex.Message;
            }
        }
Пример #47
0
        private void btnproductosXrubro_Click(object sender, RoutedEventArgs e)
        {

            categoriaFacade catFac1 = new categoriaFacade();

            int hay = catFac1.getTotalCategoriabyMes(MesRubroProd);
            if (!string.IsNullOrEmpty(month))
            {
                if (hay > 0)
                {

                    //buscar productos que fueron ingresados o modificados dentro de la fecha indicada
                    ProductoFacade prodFac = new ProductoFacade();
                    List<Producto> listProductoMes = prodFac.getALLProductosbyFechaMes(Convert.ToDateTime(month));
                    //MessageBox.Show(listProductoMes.Count.ToString());
                    //categorizar productos y obtener total de costo de compra en reporte

                    if (listProductoMes.Count > 0)
                    {
                        SaveFileDialog exportSaveFileDialog = new SaveFileDialog();
                        exportSaveFileDialog.Title = "Guardar reporte de costo para productos adquiridos";
                        exportSaveFileDialog.Filter = "PDF(*.pdf)|*.pdf";
                        exportSaveFileDialog.FileName = "ReporteCostoProdAdquiridos";
                        exportSaveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                        if (exportSaveFileDialog.ShowDialog() == true)
                        {

                            string tempIdpro = "";

                            int dineroTotalbyCat = 0;
                            List<Producto> listProductoConCategoria = listProductoMes;

                            foreach (var item in listProductoMes)
                            {
                                if (!tempIdpro.Equals(item.idProducto))
                                {

                                    Document doc = new Document(PageSize.LETTER, 50, 50, 50, 50);
                                    PdfWriter writer = null;
                                    // Indicamos donde vamos a guardar el documento
                                    try
                                    {
                                        writer = PdfWriter.GetInstance(doc, new FileStream(exportSaveFileDialog.FileName, FileMode.Create));
                                        doc.AddCreator("Magnolia");
                                        doc.Open();
                                        iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance(urlLogo, System.Drawing.Imaging.ImageFormat.Png);
                                        imagen.Alignment = Element.ALIGN_CENTER;
                                        imagen.ScaleToFit(120f, 120f);
                                        doc.Add(imagen);
                                        doc.Add(Chunk.NEWLINE);

                                        iTextSharp.text.Font _fontTitulo = new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 25, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);


                                        iTextSharp.text.Paragraph titulo = new iTextSharp.text.Paragraph("Reporte de costo ventas mensuales");
                                        titulo.Alignment = Element.ALIGN_CENTER;
                                        titulo.Font = _fontTitulo;
                                        doc.Add(titulo);
                                        doc.Add(Chunk.NEWLINE);

                                        iTextSharp.text.Paragraph dgeneral = new iTextSharp.text.Paragraph("Detalles general");
                                        dgeneral.Alignment = Element.ALIGN_LEFT;

                                        //doc.AddTitle("Reporte de MVentas");
                                        iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(iTextSharp.text.Font.HELVETICA, 8, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);


                                        //////////////////////////////////////
                                        ///////Tabla especificos    //////////
                                        /////////////////////////////////////

                                        categoriaFacade catFacEsp = new categoriaFacade();
                                        ProductoFacade prodFacEsp = new ProductoFacade();
                                        ventasFacade ventasFacEsp = new ventasFacade();
                                        PdfPTable tblEspecifico = new PdfPTable(5);

                                        iTextSharp.text.Paragraph despecifico = new iTextSharp.text.Paragraph("Detalles Especificos");
                                        despecifico.Alignment = Element.ALIGN_LEFT;
                                        //LLenar tabla especifico 
                                        PdfPCell clFechaEsp = new PdfPCell();
                                        //PdfPCell clidprod = new PdfPCell();
                                        PdfPCell clnombreprod = new PdfPCell();
                                        PdfPCell clPrecioReal = new PdfPCell();
                                        PdfPCell clCant = new PdfPCell();
                                        PdfPCell cltotalEsp = new PdfPCell();

                                        listProductoConCategoria = listProductoConCategoria.OrderByDescending(i => i.idCategoria).ToList();
                                        //MessageBox.Show("TotalProductos:" + listProductoConCategoria.Count().ToString());
                                        var q = from x in listProductoConCategoria
                                                group x.idCategoria by x.idCategoria into g
                                                let count = g.Count()
                                                /*orderby count descending*/
                                                select new { Value = g.Key, Count = count };


                                        int posList = 0;
                                        foreach (var x in q)
                                        {
                                            tblEspecifico.WidthPercentage = 100;
                                            tblEspecifico.HorizontalAlignment = Element.ALIGN_LEFT;
                                            PdfPCell clnombreCat = new PdfPCell(new Phrase(catFacEsp.getNombreCategoriaById(x.Value.ToString()), _standardFont));
                                            clnombreCat.Colspan = 2;
                                            PdfPCell h1 = new PdfPCell(new Phrase(""));
                                            PdfPCell h2 = new PdfPCell(new Phrase(""));
                                            PdfPCell h3 = new PdfPCell(new Phrase(""));
                                            h1.Border = 0;
                                            h2.Border = 0;
                                            h3.Border = 0;
                                            tblEspecifico.AddCell(clnombreCat);
                                            tblEspecifico.AddCell(h1);
                                            tblEspecifico.AddCell(h2);
                                            tblEspecifico.AddCell(h3);

                                            clFechaEsp = new PdfPCell(new Phrase("Fecha", _standardFont));
                                            //clidprod = new PdfPCell(new Phrase("IDProducto", _standardFont));
                                            clnombreprod = new PdfPCell(new Phrase("Nombre", _standardFont));
                                            clPrecioReal = new PdfPCell(new Phrase("Precio Compra", _standardFont));
                                            clCant = new PdfPCell(new Phrase("Stock", _standardFont));
                                            //PdfPCell clTipoPag = new PdfPCell(new Phrase("Tipo Pago", _standardFont));
                                            cltotalEsp = new PdfPCell(new Phrase("Total", _standardFont));

                                            tblEspecifico.AddCell(clFechaEsp);
                                            // tblEspecifico.AddCell(clidprod);
                                            tblEspecifico.AddCell(clnombreprod);
                                            tblEspecifico.AddCell(clPrecioReal);
                                            tblEspecifico.AddCell(clCant);
                                            //tblEspecifico.AddCell(clTipoPag);
                                            tblEspecifico.AddCell(cltotalEsp);

                                            for (int i = 0; i < x.Count; i++)
                                            {
                                                var v = listProductoConCategoria[posList];

                                                clFechaEsp = new PdfPCell(new Phrase(v.fecha.ToString("y"), _standardFont));
                                                //clidprod = new PdfPCell(new Phrase(x.Value.ToString(), _standardFont));
                                                // clidprod = new PdfPCell(new Phrase(v.idProducto.ToString(), _standardFont));

                                                //clnombreprod = new PdfPCell(new Phrase(v.idCategoria.ToString() + ":" + v.nombreProducto, _standardFont));
                                                clnombreprod = new PdfPCell(new Phrase(v.nombre.ToString(), _standardFont));
                                                //clnombreprod= new PdfPCell(new Phrase(prodFacEsp.getnombreProdbyidProd(v.idProducto), _standardFont));
                                                clPrecioReal = new PdfPCell(new Phrase(v.precioReal.ToString(), _standardFont));
                                                clCant = new PdfPCell(new Phrase(v.stock.ToString(), _standardFont));
                                                //clTipoPag = new PdfPCell(new Phrase("", _standardFont));
                                                cltotalEsp = new PdfPCell(new Phrase(v.total.ToString(), _standardFont));

                                                tblEspecifico.AddCell(clFechaEsp);
                                                //tblEspecifico.AddCell(clidprod);
                                                tblEspecifico.AddCell(clnombreprod);
                                                tblEspecifico.AddCell(clPrecioReal);
                                                tblEspecifico.AddCell(clCant);
                                                //tblEspecifico.AddCell(clTipoPag);
                                                tblEspecifico.AddCell(cltotalEsp);
                                                dineroTotalbyCat = dineroTotalbyCat + v.total;
                                                tempIdpro = v.idProducto;
                                                posList = posList + 1;
                                            }
                                            //#################################
                                            //en cada categoria 
                                            //#################################
                                            clFechaEsp = new PdfPCell(new Phrase("", _standardFont));
                                            ////clidprod = new PdfPCell(new Phrase("", _standardFont));
                                            clnombreprod = new PdfPCell(new Phrase("", _standardFont));
                                            clPrecioReal = new PdfPCell(new Phrase("", _standardFont));
                                            clCant = new PdfPCell(new Phrase("Subtotal($)", _standardFont));
                                            //clTipoPag = new PdfPCell(new Phrase("-----------", _standardFont));
                                            cltotalEsp = new PdfPCell(new Phrase(dineroTotalbyCat.ToString(), _standardFont));
                                            dineroTotalbyCat = 0;

                                            clFechaEsp.Border = 0;
                                            // clidprod.Border = 0;
                                            clnombreprod.Border = 0;
                                            clPrecioReal.Border = 0;
                                            clCant.Border = 1;
                                            cltotalEsp.Border = 1;



                                            tblEspecifico.AddCell(clFechaEsp);
                                            //tblEspecifico.AddCell(clidprod);
                                            tblEspecifico.AddCell(clnombreprod);
                                            tblEspecifico.AddCell(clPrecioReal);
                                            tblEspecifico.AddCell(clCant);
                                            //tblEspecifico.AddCell(clTipoPag);
                                            tblEspecifico.AddCell(cltotalEsp);


                                            /////////////////////////////////////////////
                                            clFechaEsp = new PdfPCell(new Phrase("", _standardFont));
                                            //clidprod = new PdfPCell(new Phrase("", _standardFont));
                                            clnombreprod = new PdfPCell(new Phrase("", _standardFont));
                                            clCant = new PdfPCell(new Phrase("", _standardFont));
                                            clPrecioReal = new PdfPCell(new Phrase("", _standardFont));
                                            //clTipoPag = new PdfPCell(new Phrase("-----------", _standardFont));
                                            cltotalEsp = new PdfPCell(new Phrase("", _standardFont));
                                            clFechaEsp.Border = 0;
                                            //clidprod.Border = 0;
                                            clnombreprod.Border = 0;
                                            clPrecioReal.Border = 0;
                                            clCant.Border = 0;
                                            cltotalEsp.Border = 0;

                                            cltotalEsp.FixedHeight = 30f;
                                            clFechaEsp.FixedHeight = 30f;
                                            // clidprod.FixedHeight = 30f;
                                            clnombreprod.FixedHeight = 30f;
                                            clPrecioReal.FixedHeight = 30f;
                                            clCant.FixedHeight = 30f;
                                            cltotalEsp.FixedHeight = 30f;

                                            tblEspecifico.AddCell(clFechaEsp);
                                            // tblEspecifico.AddCell(clidprod);
                                            tblEspecifico.AddCell(clnombreprod);
                                            tblEspecifico.AddCell(clPrecioReal);
                                            tblEspecifico.AddCell(clCant);
                                            //tblEspecifico.AddCell(clTipoPag);
                                            tblEspecifico.AddCell(cltotalEsp);

                                        }
                                        //#######################################################
                                        //######            DETALLES GENERALES       ############
                                        //#######################################################

                                        PdfPTable tblGenerales = new PdfPTable(3);
                                        //doc.SetMargins(0f, 0f, 0f, 0f);
                                        tblGenerales.HorizontalAlignment = Element.ALIGN_LEFT;
                                        // Configuramos el título de las columnas de la tabla
                                        PdfPCell clFecha = new PdfPCell(new Phrase("Mes", _standardFont));
                                        PdfPCell clCat = new PdfPCell(new Phrase("Categoria", _standardFont));
                                        PdfPCell clSubtotal = new PdfPCell(new Phrase("Subtotal", _standardFont));
                                        tblGenerales.AddCell(clFecha);
                                        tblGenerales.AddCell(clCat);
                                        tblGenerales.AddCell(clSubtotal);

                                        categoriaFacade catFac = new categoriaFacade();


                                        int subtotal = 0;
                                        int total = 0;
                                        int posListG = 0;
                                        //Agrupar por categoria los idproducto

                                        foreach (var x in q)
                                        {
                                            for (int i = 0; i < x.Count; i++)
                                            {
                                                var v = listProductoConCategoria[posListG];


                                                subtotal = subtotal + v.total;
                                                posListG = posListG + 1;
                                            }
                                            total = total + subtotal;
                                            clFecha = new PdfPCell(new Phrase(Convert.ToDateTime(month).ToString("y"), _standardFont));
                                            clCat = new PdfPCell(new Phrase(catFac.getNombreCategoriaById(x.Value.ToString()), _standardFont));
                                            clSubtotal = new PdfPCell(new Phrase(subtotal.ToString(), _standardFont));
                                            tblGenerales.AddCell(clFecha);
                                            tblGenerales.AddCell(clCat);
                                            tblGenerales.AddCell(clSubtotal);
                                            subtotal = 0;
                                        }


                                        clFecha = new PdfPCell(new Phrase("", _standardFont));
                                        clCat = new PdfPCell(new Phrase("Total Costo  Producto Adquiridos", _standardFont));
                                        clSubtotal = new PdfPCell(new Phrase(total.ToString(), _standardFont));

                                        clFecha.Border = 0;
                                        tblGenerales.AddCell(clFecha);
                                        tblGenerales.AddCell(clCat);
                                        tblGenerales.AddCell(clSubtotal);



                                        doc.Add(dgeneral);
                                        doc.Add(Chunk.NEWLINE);
                                        doc.Add(tblGenerales);
                                        doc.Add(Chunk.NEWLINE);
                                        doc.Add(despecifico);
                                        doc.Add(new Chunk("\n"));
                                        doc.Add(tblEspecifico);
                                        doc.Add(new Chunk("\n"));






                                        doc.Close();
                                        writer.Close();




                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show(ex.ToString());
                                    }
                                    finally
                                    {
                                        doc.Close();
                                        writer.Close();
                                    }

                                }

                            }
                            System.Diagnostics.Process.Start(exportSaveFileDialog.FileName);
                        }




                    }
                    else
                    {
                        MessageBox.Show("No hay Productos ingresados", "Magnolia", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
            else
            {
                MessageBox.Show("Seleccionar mes para generar reporte", "Magnolia", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
        }
Пример #48
0
        private void EndOfProductionButton_Click(object sender, EventArgs e)
        {
            string filename = "C:/OP2GUI/";

            if (System.IO.Directory.Exists(filename))
            {
            }
            else
            {
                Directory.CreateDirectory(filename);
            }



            DateTime now = DateTime.Now;

            rapor = new iTextSharp.text.Document();
            PdfWriter.GetInstance(rapor, new FileStream("C:/OP2GUI/" + Initialize.name + DateTime.Now.ToString("yyyyMMddHHmmss") + "OP2GUI.pdf", FileMode.Create));
            rapor.SetMargins(80, 80, 80, 80);
            Initialize.name = TurkceKarakter(Initialize.name);
            rapor.AddAuthor(Initialize.name);
            rapor.AddCreationDate();
            rapor.AddCreator(Initialize.name);
            rapor.AddSubject(Initialize.name + "|OP2-GUI");


            if (rapor.IsOpen() == false)
            {
                rapor.Open();
            }


            BaseFont times  = BaseFont.CreateFont("c:\\windows\\fonts\\times.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            Font     font16 = new Font(times, 16);
            Font     font14 = new Font(times, 14);
            Font     font12 = new Font(times, 12);

            ///Tarih Ekle
            Paragraph head0 = new Paragraph(now.ToString(), font12);

            head0.Alignment = Element.ALIGN_RIGHT;
            rapor.Add(head0);

            ////Başlık
            Paragraph head = new Paragraph("OP2-GUI", font16);

            head.Alignment = Element.ALIGN_CENTER;
            rapor.Add(head);

            ///Üretimden Sorumlu kişi
            Paragraph head2 = new Paragraph("Üretimden Sorumlu Kisi: " + Initialize.name, font14);

            head2.Alignment = Element.ALIGN_CENTER;
            rapor.Add(head2);

            /// Yeni Veriler
            PdfNewDataLeft("\n");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataCenter("Başlangıçta Belirlenen Parametreler");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataLeft("\n");


            PdfNewDataLeft("--------------------------------------------------");
            PdfNewDataLeft("Malzemenin Adı: " + RefProduction.materialNameTextRP);
            PdfNewDataLeft("Numume Adedi: " + RefProduction.numberOfSamplesTextRP);
            PdfNewDataLeft("Numune Boyutları: " + RefProduction.sampleSizeTextRP);
            PdfNewDataLeft("Üretim Türü: " + Initialize.publicrefProductiontext);
            PdfNewDataLeft("Solüsyon Bilgisi: " + ProductionParameters.publicsolutionInfoText);
            PdfNewDataLeft("--------------------------------------------------");

            PdfNewDataLeft("Başlangıç Saati: " + DateTime.Now.ToShortTimeString());
            PdfNewDataLeft("Kullanılan Program: " + programNameLabelOP.Text);
            PdfNewDataLeft("Alt-taş Sıcaklığı: " + substrateHeaterLabelOP.Text);
            PdfNewDataLeft("Akış Miktarı: " + flowRateLabelOP.Text);
            PdfNewDataLeft("Geçiş Sayısı: " + passCountLabelOP.Text);
            PdfNewDataLeft("Nozzle Gaz: " + nozzleGasPressureLabelOP.Text);
            PdfNewDataLeft("Oksijen Seviyesi (SET): " + oxygenLevelSetLabelOP.Text);
            PdfNewDataLeft("Oksijen Seviyesi (Başlangıç): " + oxygenLevelStartLabelOP.Text);
            PdfNewDataLeft("Ortam Sıcaklığı (SET): " + ambienceTemperatureSetLabelOP.Text);
            PdfNewDataLeft("Ortam Sıcaklığı (Başlangıç) :" + ambienceTemperatureStartLabelOP.Text);
            PdfNewDataLeft("Nem Seviyesi (SET) :" + humidityLevelSetLabelOP.Text);
            PdfNewDataLeft("Nem Seviyesi (Başlangıç) :" + humidityLevelStartLabelOP.Text);
            PdfNewDataLeft("Nemlendirici Gerilimi: " + humidityVoltageLabelOP.Text);
            PdfNewDataLeft("Fan Hızı : " + fanRPMLabelOP.Text);
            PdfNewDataLeft("--------------------------------------------------");

            PdfNewDataLeft("\n");
            PdfNewDataLeft("\n");
            PdfNewDataLeft("\n");
            PdfNewDataLeft("\n");
            PdfNewDataLeft("\n");
            PdfNewDataLeft("\n");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataCenter("Üretim Sırasında Belirlenen Parametreler");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataLeft("\n");


            if (changesListBox.Items.Count > 0)
            {
                PdfNewDataLeft("--------------------------------------------------");
                foreach (string item in changesListBox.Items)
                {
                    PdfNewDataLeft(item);
                }
                PdfNewDataLeft("--------------------------------------------------");
            }



            PdfNewDataLeft("\n");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataCenter("Üretim Sırasında Anlık Parametreler");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataLeft("\n");


            if (instantDataListBox.Items.Count > 0)
            {
                PdfNewDataLeft("--------------------------------------------------");
                foreach (string item in instantDataListBox.Items)
                {
                    PdfNewDataLeft(item);
                    Console.WriteLine(item);
                }
                PdfNewDataLeft("--------------------------------------------------");
            }


            PdfNewDataLeft("\n");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataCenter("Temizlik");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataLeft("\n");

            if (!(CleaningProcess.cleaningProcessCP == ""))
            {
                PdfNewDataLeft("--------------------------------------------------");
                PdfNewDataLeft(CleaningProcess.cleaningProcessCP);
                PdfNewDataLeft("--------------------------------------------------");
            }


            PdfNewDataLeft("\n");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataCenter("İleri İşlemler");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataLeft("\n");


            if (!(PostProcessing.postProcessPOP == ""))
            {
                PdfNewDataLeft("--------------------------------------------------");
                PdfNewDataLeft(PostProcessing.postProcessPOP);
                PdfNewDataLeft("--------------------------------------------------");
            }


            PdfNewDataLeft("\n");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataCenter("Alınacak Olçümler");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataLeft("\n");


            if (Measurements.measumentsMP.Length > 0)
            {
                PdfNewDataLeft("--------------------------------------------------");
                foreach (var item in Measurements.measumentsMP)
                {
                    PdfNewDataLeft(item);
                }
                PdfNewDataLeft("--------------------------------------------------");
            }


            PdfNewDataLeft("\n");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataCenter("Notlar");
            PdfNewDataCenter("--------------------------------------------------");
            PdfNewDataLeft("\n");


            if (!(takeNotesText.Text == ""))
            {
                PdfNewDataLeft("--------------------------------------------------");
                PdfNewDataLeft(takeNotesText.Text);
                PdfNewDataLeft("--------------------------------------------------");
            }

            rapor.Close();



            MessageBox.Show("Dosya Oluşturuldu.\n" + "C:/OP2GUI/" + Initialize.name + DateTime.Now.ToString("yyyyMMddHHmmss") + "OP2GUI.pdf");

            System.Diagnostics.Process.Start("C:/OP2GUI/");
        }
Пример #49
0
        //------------FACTURA-------------------------------
        public static void CrearFactura(string PATH, string Archivo)
        {
            var  Datos    = LeerCFDI(PATH + Archivo + ".xml");
            Font font     = new Font(Font.FontFamily.HELVETICA, 6, Font.NORMAL);
            Font sellos   = new Font(Font.FontFamily.HELVETICA, 5, Font.NORMAL);
            Font textBold = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 7);

            iTextSharp.text.Document      doc    = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER);
            iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream(PATH + Archivo + ".pdf", FileMode.Create));

            doc.AddTitle("Factura Electronica");
            doc.AddCreator("Avenzo Proteccion");
            doc.AddAuthor("Cristian Santiago Rosas");

            doc.Open();
            iTextSharp.text.Image         avenzo = iTextSharp.text.Image.GetInstance("~/Images/Avenzo_Logo_Header.png");
            iTextSharp.text.pdf.PdfPTable Header = new iTextSharp.text.pdf.PdfPTable(12);
            float[] widths = new float[] { .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f };
            iTextSharp.text.Rectangle page = doc.PageSize;
            Header.WidthPercentage = 80;
            Header.LockedWidth     = true;
            Header.SetWidths(widths);
            Header.TotalWidth = page.Width - 90;
            //---------------------------------------------
            //-----------CABEZERA DEL DOCUMENTO------------
            //---------------------------------------------
            iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell();//--Logo
            cell.AddElement(avenzo);
            cell.Colspan = 4;
            cell.Border  = BORDER;

            iTextSharp.text.pdf.PdfPCell cell2 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal
            cell2.AddElement(new iTextSharp.text.Paragraph(Datos["EmisorNombre"] + "\n" + Datos["EmisorRFC"] + "\nDomicilio Fiscal\n" + Datos["DomicilioFiscal"] + "\nTel. 6645266573", new Font(Font.FontFamily.HELVETICA, 5, Font.BOLD)));
            cell2.Colspan             = 4;
            cell2.Border              = BORDER;
            cell2.HorizontalAlignment = 1;
            Header.AddCell(cell);
            Header.AddCell(cell2);
            iTextSharp.text.pdf.PdfPCell cell51 = new iTextSharp.text.pdf.PdfPCell();
            cell51.Phrase = new Phrase("Factura No: " + Datos["folio"] + "\nFOLIO FISCAL (UUID):\n" + Datos["UUID"] + "\nNO. DE SERIE DEL CERTIFICADO DEL SAT:\n" + Datos["noCertificadoSAT"] + "\nNO. DE SERIE DEL CERTIFICADO DEL EMISOR:\n" + Datos["noCertificado"] + "\nFECHA Y HORA DE CERTIFICACIÓN:\n" + Datos["FechaTimbrado"] + "\nFECHA Y HORA DE EMISIÓN DE CFDI:\n" + Datos["FechaComprobante"], textBold);
            cell51.HorizontalAlignment = Element.ALIGN_CENTER;
            cell51.Colspan             = 4;
            Header.AddCell(cell51);
            iTextSharp.text.pdf.PdfPCell salto = new iTextSharp.text.pdf.PdfPCell();
            salto.AddElement(new Chunk("\n"));
            salto.Colspan = 12;
            salto.Border  = BORDER;
            Header.AddCell(salto);
            //---------------------------------------------
            //------------DATOS CLIENTE-------------------
            //---------------------------------------------
            iTextSharp.text.pdf.PdfPCell cell4 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal
            cell4.Colspan       = 1;
            cell4.Border        = BORDER;
            cell4.PaddingTop    = 0;
            cell4.PaddingBottom = 0;
            cell4.AddElement(new Paragraph("Cliente:", textBold));
            iTextSharp.text.pdf.PdfPCell cell5 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal
            cell5.Colspan       = 2;
            cell5.PaddingTop    = 0;
            cell5.PaddingBottom = 0;
            cell5.Border        = BORDER;
            cell5.AddElement(new Paragraph(Datos["ReceptorNombre"], font));
            iTextSharp.text.pdf.PdfPCell cell6 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal
            cell6.Colspan       = 2;
            cell6.Border        = BORDER;
            cell6.PaddingTop    = 0;
            cell6.PaddingBottom = 0;
            cell6.AddElement(new Paragraph("Régimen Fiscal:", textBold));
            iTextSharp.text.pdf.PdfPCell cell7 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal
            cell7.Colspan       = 7;
            cell7.Border        = BORDER;
            cell7.PaddingTop    = 0;
            cell7.PaddingBottom = 0;
            cell7.AddElement(new Paragraph(Datos["Regimen"], font));
            iTextSharp.text.pdf.PdfPCell cell8 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal
            cell8.Colspan       = 1;
            cell8.Border        = BORDER;
            cell8.PaddingTop    = 0;
            cell8.PaddingBottom = 0;
            cell8.AddElement(new Paragraph("RFC:", textBold));
            iTextSharp.text.pdf.PdfPCell cell9 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal
            cell9.Colspan       = 2;
            cell9.Border        = BORDER;
            cell9.PaddingTop    = 0;
            cell9.PaddingBottom = 0;
            cell9.AddElement(new Paragraph(Datos["ReceptorRFC"], font));
            iTextSharp.text.pdf.PdfPCell cell10 = new iTextSharp.text.pdf.PdfPCell();
            cell10.Colspan       = 2;
            cell10.Border        = BORDER;
            cell10.PaddingBottom = 0;
            cell10.PaddingTop    = 0;
            cell10.AddElement(new Paragraph("Lugar de Expedición:", textBold));
            iTextSharp.text.pdf.PdfPCell cell11 = new iTextSharp.text.pdf.PdfPCell();
            cell11.Colspan       = 3;
            cell11.Border        = BORDER;
            cell11.PaddingTop    = 0;
            cell11.PaddingBottom = 0;
            cell11.AddElement(new Paragraph(Datos["LugarExpedicion"], font));
            iTextSharp.text.pdf.PdfPCell cell12 = new iTextSharp.text.pdf.PdfPCell();
            cell12.AddElement(new Paragraph("Fecha de Expedicion:", textBold));
            cell12.Colspan       = 2;
            cell12.Border        = BORDER;
            cell12.PaddingBottom = 0;
            cell12.PaddingTop    = 0;
            iTextSharp.text.pdf.PdfPCell cell13 = new iTextSharp.text.pdf.PdfPCell();
            cell13.Colspan       = 3;
            cell13.Border        = BORDER;
            cell13.PaddingTop    = 0;
            cell13.PaddingBottom = 0;
            DateTime time = DateTime.Parse(Datos["FechaComprobante"]);

            System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("es-MX");
            cell13.AddElement(new Paragraph(time.ToString("dd", ci) + " de " + time.ToString("MMMM", ci) + " del " + time.ToString("yyyy", ci), font));
            //---
            iTextSharp.text.pdf.PdfPCell cell14 = new iTextSharp.text.pdf.PdfPCell();
            cell14.Colspan       = 1;
            cell14.Rowspan       = 2;
            cell14.PaddingTop    = 0;
            cell14.PaddingBottom = 0;
            cell14.Border        = BORDER;
            cell14.AddElement(new Paragraph("Direccion:", textBold));
            iTextSharp.text.pdf.PdfPCell cell15 = new iTextSharp.text.pdf.PdfPCell();
            cell15.Colspan       = 2;
            cell15.Rowspan       = 2;
            cell15.Border        = BORDER;
            cell15.PaddingBottom = 0;
            cell15.PaddingTop    = 0;
            cell15.AddElement(new Paragraph(Datos["ReceptorDomicilio"], font));
            iTextSharp.text.pdf.PdfPCell cell16 = new iTextSharp.text.pdf.PdfPCell();
            cell16.Colspan       = 2;
            cell16.PaddingTop    = 0;
            cell16.PaddingBottom = 0;
            cell16.AddElement(new Paragraph("Forma De Pago:", textBold));
            cell16.Border = BORDER;
            iTextSharp.text.pdf.PdfPCell cell17 = new iTextSharp.text.pdf.PdfPCell();
            cell17.PaddingBottom = 0;
            cell17.PaddingTop    = 0;
            cell17.Colspan       = 3;
            cell17.Border        = BORDER;
            cell17.AddElement(new Paragraph(Datos["formaDePago"], font));
            iTextSharp.text.pdf.PdfPCell cell18 = new iTextSharp.text.pdf.PdfPCell();
            cell18.AddElement(new Paragraph("Clave Moneda:", textBold));
            cell18.Colspan       = 2;
            cell18.Border        = BORDER;
            cell18.PaddingTop    = 0;
            cell18.PaddingBottom = 0;
            iTextSharp.text.pdf.PdfPCell cell19 = new iTextSharp.text.pdf.PdfPCell();
            cell19.Colspan       = 2;
            cell19.Border        = BORDER;
            cell19.PaddingBottom = 0;
            cell19.PaddingTop    = 0;
            cell19.AddElement(new Paragraph(Datos["Moneda"], font));
            iTextSharp.text.pdf.PdfPCell cell20 = new iTextSharp.text.pdf.PdfPCell();
            cell20.Colspan       = 2;
            cell20.Border        = BORDER;
            cell20.PaddingTop    = 0;
            cell20.PaddingBottom = 0;
            cell20.AddElement(new Paragraph("Método de Pago:", textBold));
            iTextSharp.text.pdf.PdfPCell cell21 = new iTextSharp.text.pdf.PdfPCell();
            cell21.Colspan       = 3;
            cell21.Border        = BORDER;
            cell21.PaddingTop    = 0;
            cell21.PaddingBottom = 0;
            cell21.AddElement(new Paragraph(Datos["metodoDePago"], font));
            iTextSharp.text.pdf.PdfPCell cell22 = new iTextSharp.text.pdf.PdfPCell();
            cell22.Colspan       = 2;
            cell22.Border        = BORDER;
            cell22.PaddingTop    = 0;
            cell22.PaddingBottom = 0;
            cell22.AddElement(new Paragraph("NumCtaPago:", textBold));
            iTextSharp.text.pdf.PdfPCell cell23 = new iTextSharp.text.pdf.PdfPCell();
            cell23.Colspan       = 2;
            cell23.Border        = BORDER;
            cell23.PaddingTop    = 0;
            cell23.PaddingBottom = 0;
            cell23.AddElement(new Paragraph(Datos["NumCtaPago"], font));
            //----------------------------------------------
            //-----------------PRODUCTOS--------------------
            //----------------------------------------------
            iTextSharp.text.pdf.PdfPCell cell24 = new iTextSharp.text.pdf.PdfPCell();
            cell24.Colspan = 1;
            cell24.AddElement(new Paragraph("Cantidad", textBold));
            iTextSharp.text.pdf.PdfPCell cell25 = new iTextSharp.text.pdf.PdfPCell();
            cell25.Colspan = 1;
            cell25.AddElement(new Paragraph("Unidad de Medida", textBold));
            iTextSharp.text.pdf.PdfPCell cell26 = new iTextSharp.text.pdf.PdfPCell();
            cell26.Colspan             = 6;
            cell26.HorizontalAlignment = Element.ALIGN_CENTER;
            cell26.VerticalAlignment   = Element.ALIGN_CENTER;
            cell26.AddElement(new Paragraph("Descripcion", textBold));
            iTextSharp.text.pdf.PdfPCell cell27 = new iTextSharp.text.pdf.PdfPCell();
            cell27.Colspan = 2;
            cell27.AddElement(new Paragraph("Producto Unitario", textBold));
            iTextSharp.text.pdf.PdfPCell cell28 = new iTextSharp.text.pdf.PdfPCell();
            cell28.Colspan             = 2;
            cell28.HorizontalAlignment = Element.ALIGN_CENTER;
            cell28.VerticalAlignment   = Element.ALIGN_CENTER;
            cell28.AddElement(new Paragraph("Importe", textBold));
            //-----------------------------------------------
            iTextSharp.text.pdf.PdfPCell cell29 = new iTextSharp.text.pdf.PdfPCell();
            cell29.AddElement(new Paragraph(Datos["cantidad"], font));
            cell29.Colspan = 1;
            iTextSharp.text.pdf.PdfPCell cell30 = new iTextSharp.text.pdf.PdfPCell();
            cell30.AddElement(new Paragraph(Datos["unidad"], font));
            cell30.Colspan = 1;
            iTextSharp.text.pdf.PdfPCell cell31 = new iTextSharp.text.pdf.PdfPCell();
            cell31.AddElement(new Paragraph(Datos["descripcion"], font));
            cell31.Colspan = 6;
            iTextSharp.text.pdf.PdfPCell cell32 = new iTextSharp.text.pdf.PdfPCell();
            cell32.AddElement(new Paragraph(Datos["valorUnitario"], font));
            cell32.Colspan = 2;
            iTextSharp.text.pdf.PdfPCell cell33 = new iTextSharp.text.pdf.PdfPCell();
            cell33.AddElement(new Paragraph(Datos["importe"], font));
            cell33.Colspan     = 2;
            cell33.FixedHeight = 200f;


            //-------------------------------------------------------
            //----------------------TOTAL----------------------------
            //-------------------------------------------------------
            iTextSharp.text.pdf.PdfPCell cell34 = new iTextSharp.text.pdf.PdfPCell();
            cell34.Colspan       = 2;
            cell34.Rowspan       = 3;
            cell34.Border        = BORDER;
            cell34.PaddingBottom = 0;
            cell34.PaddingTop    = 0;
            cell34.AddElement(new Paragraph(""));
            iTextSharp.text.pdf.PdfPCell cell35 = new iTextSharp.text.pdf.PdfPCell();
            cell35.Colspan       = 7;
            cell35.Border        = BORDER;
            cell35.Rowspan       = 3;
            cell35.PaddingTop    = 0;
            cell35.PaddingBottom = 0;
            NumLetra nl = new NumLetra();

            cell35.AddElement(new Paragraph("IMPORTE CON LETRA: " + nl.Convertir(Datos["total"], true, false), textBold));
            iTextSharp.text.pdf.PdfPCell cell36 = new iTextSharp.text.pdf.PdfPCell();
            cell36.Colspan             = 2;
            cell36.Border              = BORDER;
            cell36.PaddingBottom       = 0;
            cell36.PaddingTop          = 0;
            cell36.Phrase              = new Phrase("SubTotal:", textBold);
            cell36.HorizontalAlignment = Element.ALIGN_RIGHT;
            cell36.VerticalAlignment   = Element.ALIGN_BOTTOM;
            iTextSharp.text.pdf.PdfPCell cell37 = new iTextSharp.text.pdf.PdfPCell();
            cell37.Colspan       = 1;
            cell37.Border        = BORDER;
            cell37.PaddingTop    = 0;
            cell37.PaddingBottom = 0;
            cell37.AddElement(new Paragraph("$ " + Datos["subTotal"], font));
            //--
            iTextSharp.text.pdf.PdfPCell cell38 = new iTextSharp.text.pdf.PdfPCell();
            cell38.Colspan             = 2;
            cell38.PaddingBottom       = 0;
            cell38.PaddingTop          = 0;
            cell38.Border              = BORDER;
            cell38.Phrase              = new Phrase("IVA(IVA 16.00%):", textBold);
            cell38.HorizontalAlignment = Element.ALIGN_RIGHT;
            cell38.VerticalAlignment   = Element.ALIGN_BOTTOM;
            iTextSharp.text.pdf.PdfPCell cell39 = new iTextSharp.text.pdf.PdfPCell();
            cell39.Colspan       = 1;
            cell39.PaddingTop    = 0;
            cell39.PaddingBottom = 0;
            cell39.Border        = BORDER;
            cell39.AddElement(new Paragraph("$ " + Datos["totalImpuestosTrasladados"], font));
            //---
            iTextSharp.text.pdf.PdfPCell cell40 = new iTextSharp.text.pdf.PdfPCell();
            cell40.Colspan             = 2;
            cell40.Border              = BORDER;
            cell40.VerticalAlignment   = Element.ALIGN_BOTTOM;
            cell40.Phrase              = new Phrase("Total:", textBold);
            cell40.PaddingBottom       = 0;
            cell40.PaddingTop          = 0;
            cell40.HorizontalAlignment = Element.ALIGN_RIGHT;
            iTextSharp.text.pdf.PdfPCell cell41 = new iTextSharp.text.pdf.PdfPCell();
            cell41.Colspan       = 1;
            cell41.Border        = BORDER;
            cell41.PaddingTop    = 0;
            cell41.PaddingBottom = 0;
            cell41.AddElement(new Paragraph("$ " + Datos["total"], font));
            //---------------------------------------------------------
            //-------------------CDFI SELLOS---------------------------
            //---------------------------------------------------------
            iTextSharp.text.pdf.PdfPCell cell42 = new iTextSharp.text.pdf.PdfPCell();
            cell42.Colspan = 10;
            cell42.Border  = BORDER;
            cell42.Phrase  = new Phrase("SELLO DIGITAL DEL CFDI", textBold);
            iTextSharp.text.pdf.BarcodeQRCode QR = new iTextSharp.text.pdf.BarcodeQRCode(Datos["QR"], 300, 300, null);
            Image img = QR.GetImage();

            img.SetDpi(1400, 1400);
            iTextSharp.text.pdf.PdfPCell cell43 = new iTextSharp.text.pdf.PdfPCell();
            cell43.Colspan           = 2;
            cell43.Border            = BORDER;
            cell43.Rowspan           = 9;
            cell43.VerticalAlignment = Element.ALIGN_TOP;
            cell43.AddElement(img);
            iTextSharp.text.pdf.PdfPCell cell44 = new iTextSharp.text.pdf.PdfPCell();
            cell44.Colspan = 10;
            cell44.Phrase  = new Phrase(Datos["selloCFD"], sellos);
            iTextSharp.text.pdf.PdfPCell cell45 = new iTextSharp.text.pdf.PdfPCell();
            cell45.Colspan = 10;
            cell45.Phrase  = new Phrase("SELLO DIGITAL DEL SAT", textBold);
            cell45.Border  = BORDER;
            iTextSharp.text.pdf.PdfPCell cell46 = new iTextSharp.text.pdf.PdfPCell();
            cell46.Phrase  = new Phrase(Datos["SelloSAT"], sellos);
            cell46.Colspan = 10;
            iTextSharp.text.pdf.PdfPCell cell47 = new iTextSharp.text.pdf.PdfPCell();
            cell47.Phrase  = new Phrase("CADENA ORIGINAL DEL COMPLEMENTO DE CERTIFICACIÓN DIGITAL DEL SAT", textBold);
            cell47.Border  = BORDER;
            cell47.Colspan = 10;
            iTextSharp.text.pdf.PdfPCell cell48 = new iTextSharp.text.pdf.PdfPCell();
            cell48.Colspan = 10;
            cell48.Phrase  = new Phrase(Datos["CadenaOriginal"], sellos);
            iTextSharp.text.pdf.PdfPCell cell49 = new iTextSharp.text.pdf.PdfPCell();
            cell49.Colspan = 10;
            cell49.Phrase  = new Phrase("");
            cell49.Border  = BORDER;
            Header.AddCell(cell4);
            Header.AddCell(cell5);
            Header.AddCell(cell6);
            Header.AddCell(cell7);
            Header.AddCell(cell8);
            Header.AddCell(cell9);
            Header.AddCell(cell10);
            Header.AddCell(cell11);
            Header.AddCell(cell12);
            Header.AddCell(cell13);
            Header.AddCell(cell14);
            Header.AddCell(cell15);
            Header.AddCell(cell16);
            Header.AddCell(cell17);
            Header.AddCell(cell18);
            Header.AddCell(cell19);
            Header.AddCell(cell20);
            Header.AddCell(cell21);
            Header.AddCell(cell22);
            Header.AddCell(cell23);
            Header.AddCell(salto);
            Header.AddCell(cell24);
            Header.AddCell(cell25);
            Header.AddCell(cell26);
            Header.AddCell(cell27);
            Header.AddCell(cell28);
            Header.AddCell(cell29);
            Header.AddCell(cell30);
            Header.AddCell(cell31);
            Header.AddCell(cell32);
            Header.AddCell(cell33);
            Header.AddCell(cell34);
            Header.AddCell(cell35);
            Header.AddCell(cell36);
            Header.AddCell(cell37);
            Header.AddCell(cell38);
            Header.AddCell(cell39);
            Header.AddCell(cell40);
            Header.AddCell(cell41);
            Header.AddCell(salto);
            Header.AddCell(cell49);
            Header.AddCell(cell43);
            Header.AddCell(cell42);
            Header.AddCell(cell44);
            Header.AddCell(cell49);
            Header.AddCell(cell45);
            Header.AddCell(cell46);
            Header.AddCell(cell49);
            Header.AddCell(cell47);
            Header.AddCell(cell48);
            doc.Add(Header);
            doc.Close();
            writer.Close();
        }
Пример #50
0
        public Ausencia(AufenPortalReportesDataContext db, EMPRESA empresa, vw_Ubicacione departamento, DateTime FechaDesde, DateTime FechaHasta, string path, string rut)
        {
            //Nombre del archivo y ubiación en el árbol de carpetas
            NombreArchivo = String.Format("{0}/{1}/PersonalAusente.pdf", empresa.Descripcion, departamento.Descripcion);
            // Vamos a buscar los datos que nos permitirtán armar elreporte
            IEnumerable<sp_LibroInasistenciaResult> resultado = db.sp_LibroInasistencia(
                FechaDesde.ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture)
                , FechaHasta.ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture)
                , int.Parse(empresa.Codigo).ToString()
                , departamento.Codigo
                , rut).OrderBy(x => x.Fecha).ToList();
            IEnumerable<LibroInasistenciaDTO> inasistencias =
                Mapper.Map<IEnumerable<sp_LibroInasistenciaResult>, IEnumerable<LibroInasistenciaDTO>>(resultado);
            if (inasistencias.Any())
            {
                Configuracion();
                Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 50, 35);
                using (var ms = new MemoryStream())
                {
                    PdfWriter pdfWriter = PdfWriter.GetInstance(doc, ms);
                    pdfWriter.PageEvent = new Header(empresa, path);
                    doc.Open();
                    foreach (var reporte in inasistencias.Where(x=>x.Rut!=null).GroupBy(x => new { x.Rut, x.IdDepartamento, x.IdEmpresa }).Take(3))
                    {
                        doc.AddAuthor("Aufen");
                        doc.AddCreationDate();
                        doc.AddCreator("Aufen");
                        doc.AddTitle("Informe de Personal Ausente (sin marcas)");

                        Paragraph parrafo = new Paragraph();

                        parrafo.Add(new Paragraph("Informe de Personal Ausente (sin marcas)", Titulo) { Alignment = Element.ALIGN_CENTER });
                        parrafo.Add(new Paragraph(String.Format("Período: {0} a {1}", FechaDesde.ToShortDateString(), FechaHasta.ToShortDateString()), Normal) { Alignment = Element.ALIGN_CENTER });
                        parrafo.Add(new Paragraph("Centro de Costos:", Normal));

                        doc.Add(parrafo);
                        doc.Add(new Phrase());

                        PdfPTable tabla = new PdfPTable(new float[] {2, 2, 2, 2, 1, 1, 4 });
                        // Encabezado
                        tabla.AddCell(new PdfPCell(new Phrase("Empleado", Normal)) { Colspan = 4});
                        tabla.AddCell(new PdfPCell(new Phrase("Horario", Normal)) { Colspan = 2 });
                        tabla.AddCell(new PdfPCell(new Phrase("Autorizaciones", Normal)));

                        // 2 encabezado
                        tabla.AddCell(new PdfPCell(new Phrase("Fecha", Chico)));
                        tabla.AddCell(new PdfPCell(new Phrase("Rut", Chico)));
                        tabla.AddCell(new PdfPCell(new Phrase("Apellidos", Chico)));
                        tabla.AddCell(new PdfPCell(new Phrase("Nombres", Chico)));
                        tabla.AddCell(new PdfPCell(new Phrase("Ing.", Chico)));
                        tabla.AddCell(new PdfPCell(new Phrase("Sal.", Chico)));
                        tabla.AddCell(new PdfPCell(new Phrase("Autorizaciones", Chico)));

                        var empleado = db.vw_Empleados.FirstOrDefault(x => x.IdEmpresa == empresa.Codigo &&
                            x.IdUbicacion == reporte.Key.IdDepartamento &&  x.Codigo == reporte.Key.Rut);
                        foreach(var ausencia in reporte)
                        {
                            //Fecha
                            tabla.AddCell(new PdfPCell(new Phrase(ausencia.Fecha.HasValue ? ausencia.Fecha.Value.ToString("ddd dd/MM") : String.Empty, Chico)));
                            //Código
                            tabla.AddCell(new PdfPCell(new Phrase(empleado.RutAufen, Chico)));
                            //Apellidos
                            tabla.AddCell(new PdfPCell(new Phrase((ausencia.Apellidos ?? string.Empty).Trim(), Chico)));
                            //Nombres
                            tabla.AddCell(new PdfPCell(new Phrase((ausencia.Nombres ?? string.Empty).Trim(), Chico)));
                            //Ing.
                            tabla.AddCell(new PdfPCell(new Phrase(ausencia.EntradaTeorica.HasValue ? ausencia.EntradaTeorica.Value.ToString("HH:mm") : String.Empty, Chico)));
                            //Sal.
                            tabla.AddCell(new PdfPCell(new Phrase(ausencia.SalidaTeorica.HasValue ? ausencia.SalidaTeorica.Value.ToString("HH:mm") : String.Empty, Chico)));
                            //Autorizaciones
                            tabla.AddCell(new PdfPCell(new Phrase(ausencia.Observacion, Chico)));
                        }
                        doc.Add(tabla);
                        doc.NewPage();
                    }
                    doc.Close();
                    _Archivo = ms.ToArray();
                }
            }
        }
Пример #51
0
        public void bill(string siparisNo, string Kullaniciid)
        {
            this.siparisNo   = siparisNo;
            this.Kullaniciid = Kullaniciid;

            iTextSharp.text.pdf.BaseFont STF_Helvetica_Turkish = iTextSharp.text.pdf.BaseFont.CreateFont("Helvetica", "CP1254", iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED);
            iTextSharp.text.Font         fontTitle             = new iTextSharp.text.Font(STF_Helvetica_Turkish, 11, iTextSharp.text.Font.NORMAL);

            SqlCommand cdname = new SqlCommand("select *from Tbl_Kullanici where KullaniciId=@p1", conn.connection());

            cdname.Parameters.AddWithValue("@p1", Kullaniciid);
            SqlDataReader drname = cdname.ExecuteReader();

            while (drname.Read())
            {
                name   = drname[1].ToString() + " " + drname[2].ToString();
                e_mail = drname[3].ToString();
            }

            conn.connection().Close();

            iTextSharp.text.Document pdf = new iTextSharp.text.Document();
            filePath = HttpContext.Current.Server.MapPath("~/Bills/" + siparisNo + "_Fatura.Pdf");
            PdfWriter.GetInstance(pdf, new FileStream(filePath, FileMode.Create));
            pdf.AddAuthor("BookSite");
            pdf.AddCreator("BookSite");
            pdf.AddCreationDate();
            pdf.AddSubject("Fatura");


            PdfPTable table = new PdfPTable(4);
            PdfPCell  cell  = new PdfPCell(new Phrase(name + "        FATURA - " + siparisNo, fontTitle));

            cell.Colspan             = 4;
            cell.HorizontalAlignment = 1;
            table.AddCell(cell);

            table.AddCell(new Phrase("Kitap Adı", fontTitle));
            table.AddCell(new Phrase("Miktar", fontTitle));
            table.AddCell(new Phrase("Birim Fiyat", fontTitle));
            table.AddCell(new Phrase("Toplam Fiyat", fontTitle));

            SqlCommand cd = new SqlCommand("select *from Tbl_Sepet where SiparisNo=@p1", conn.connection());

            cd.Parameters.AddWithValue("@p1", siparisNo);
            SqlDataReader dr = cd.ExecuteReader();

            while (dr.Read())
            {
                table.AddCell(new Phrase(dr[7].ToString(), fontTitle));
                table.AddCell(new Phrase(dr[2].ToString(), fontTitle));
                table.AddCell(new Phrase(dr[6].ToString(), fontTitle));
                table.AddCell(new Phrase(dr[3].ToString(), fontTitle));
            }
            conn.connection().Close();


            if (pdf.IsOpen() == false)
            {
                pdf.Open();
            }
            pdf.Add(table);
            pdf.Close();
        }
Пример #52
0
        public Tuple <bool, string> GeneratePDF(DocumentStockReceiptList stockReceipt = null)
        {
            string fPath = string.Empty, subF_Path = string.Empty, fileName = string.Empty, filePath = string.Empty;

            try
            {
                fileName = stockReceipt.ReceivingCode + GlobalVariable.ReceiptAckFileName;
                fPath    = GlobalVariable.ReportPath + "Reports";
                report.CreateFolderIfnotExists(fPath);          // create a new folder if not exists
                subF_Path = fPath + "//" + stockReceipt.UserID; //ManageReport.GetDateForFolder();
                report.CreateFolderIfnotExists(subF_Path);
                //delete file if exists
                filePath = subF_Path + "//" + fileName + ".pdf";
                report.DeleteFileIfExists(filePath);

                iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.A4, 5f, 5f, 5f, 5f);
                //Create PDF Table
                FileStream fs = new FileStream(filePath, FileMode.Create);
                //Create a PDF file in specific path
                PdfWriter writer = PdfWriter.GetInstance(document, fs);
                // Add meta information to the document
                document.AddAuthor("Dulasiayya from BonTon");
                document.AddCreator("Acknolowdgement for particuar document");
                document.AddKeywords("TNCSC- Webcopy ");
                document.AddSubject("Document subject - Ack Web Copy ");
                document.AddTitle("The document title - PDF creation for Receipt Document");

                //Open the PDF document
                document.Open();
                string imagePath          = GlobalVariable.ReportPath + "layout\\images\\dashboard\\tncsc-logo.PNG";
                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imagePath);
                img.Alignment = Element.ALIGN_CENTER;
                img.ScaleToFit(80f, 60f);

                imagePath = GlobalVariable.ReportPath + "layout\\images\\dashboard\\watermark.PNG";
                iTextSharp.text.Image imgWaterMark = iTextSharp.text.Image.GetInstance(imagePath);
                imgWaterMark.ScaleToFit(300, 450);
                imgWaterMark.Alignment = iTextSharp.text.Image.UNDERLYING;
                imgWaterMark.SetAbsolutePosition(120, 450);
                document.Add(imgWaterMark);
                //|----------------------------------------------------------------------------------------------------------|
                //Create the table
                PdfPTable table = new PdfPTable(2);
                table.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
                //table.setBorder(Border.NO_BORDER);
                //set overall width
                table.WidthPercentage = 100f;
                //set column widths
                int[] firstTablecellwidth = { 20, 80 };
                table.SetWidths(firstTablecellwidth);
                //iTextSharp.text.Font fontTable = FontFactory.GetFont("Arial", "16", iTextSharp.text.Font.NORMAL);
                PdfPCell cell = new PdfPCell(img);
                cell.Rowspan     = 3;
                cell.BorderWidth = 0;
                // cell.Border = (Border.NO_BORDER);
                table.AddCell(cell);
                PdfPCell cell1 = new PdfPCell(new Phrase("TAMILNADU CIVIL SUPPLIES CORPORATION"));
                cell1.HorizontalAlignment = Element.ALIGN_CENTER;
                cell1.BorderWidth         = 0;
                table.AddCell(cell1);


                cell1 = new PdfPCell(new Phrase("Region Name : " + stockReceipt.RegionName));
                cell1.HorizontalAlignment = Element.ALIGN_CENTER;
                cell1.BorderWidth         = 0;
                table.AddCell(cell1);

                cell1             = new PdfPCell(new Phrase(""));
                cell1.BorderWidth = 0;
                table.AddCell(cell1);

                document.Add(table);
                Paragraph heading = new Paragraph("           STOCK RECEIPT ACKNOWLEDGMENT         WEB COPY");
                heading.Alignment = Element.ALIGN_CENTER;
                document.Add(heading);
                AddSpace(document);
                AddHRLine(document);
                //add header values
                AddheaderValues(document, stockReceipt);
                AddSpace(document);
                AddDetails(document, stockReceipt);
                AddSpace(document);
                AddLorryInfo(document, stockReceipt);
                AddSpace(document);
                AddFSSAI(document);
                AddSign(document, stockReceipt.ReceivingCode);
                AddSpace(document);
                AddRemarks(document, stockReceipt);
                AddSpace(document);
                AddHRLine(document);
                AddFooter(document, stockReceipt);
                //Add border to page
                PdfContentByte content   = writer.DirectContent;
                Rectangle      rectangle = new Rectangle(document.PageSize);
                rectangle.Left   += document.LeftMargin;
                rectangle.Right  -= document.RightMargin;
                rectangle.Top    -= document.TopMargin;
                rectangle.Bottom += document.BottomMargin;
                content.SetColorStroke(BaseColor.Black);
                content.Rectangle(rectangle.Left, rectangle.Bottom, rectangle.Width, rectangle.Height);
                content.Stroke();
                // Close the document
                document.Close();
                // Close the writer instance
                writer.Close();
                // Always close open filehandles explicity
                fs.Close();
            }
            catch (Exception ex)
            {
                AuditLog.WriteError(" GeneratePDF :  " + ex.Message + " " + ex.StackTrace);
                return(new Tuple <bool, string>(false, "Please Contact system Admin"));
            }
            return(new Tuple <bool, string>(true, "Print Generated Successfully"));
        }
Пример #53
0
        protected void btntetkikkaydet_Click(object sender, EventArgs e)
        {
            MongoClient client           = new MongoClient();
            var         database         = client.GetDatabase("hastane");
            var         collection       = database.GetCollection <yatanhastalar>("yatanhastalar");
            var         servislistesi    = collection.Find(x => x._id != null).ToList().SelectMany(x => x.ServisList).ToList();
            var         hastalistesi     = servislistesi.SelectMany(x => x.HastaList).ToList().Where(x => x._id == ObjectId.Parse(ddlHasta.SelectedValue)).ToList();
            var         radyolojilistesi = hastalistesi.SelectMany(x => x.RadyolojiList).ToList().Where(x => x._id == ObjectId.Parse(ddlRadyoloji.SelectedValue));
            var         tetkiklistesi    = radyolojilistesi.SelectMany(x => x.TetkiklerList).ToList().Where(x => x.tahlil_adi == ListBox1.SelectedItem.Text);
            var         hst = hastalistesi.FirstOrDefault();
            var         rad = radyolojilistesi.FirstOrDefault();

            #region Font seç
            BaseFont             trArial              = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\tahoma.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            iTextSharp.text.Font fontArial            = new iTextSharp.text.Font(trArial, 10, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.DARK_GRAY);
            iTextSharp.text.Font fontArialHeader      = new iTextSharp.text.Font(trArial, 13, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);
            iTextSharp.text.Font fontArialbold        = new iTextSharp.text.Font(trArial, 9, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.DARK_GRAY);
            iTextSharp.text.Font fontArialboldgeneral = new iTextSharp.text.Font(trArial, 10, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);
            #endregion

            #region Sonuç pdf oluştur
            iTextSharp.text.Document pdfFile = new iTextSharp.text.Document();
            PdfWriter.GetInstance(pdfFile, new FileStream("C:\\Users\\Önder\\Desktop\\Yeni klasör\\Radyoloji Sonuç (" + hst.hasta_tc + " " + hst.hasta_adi + " " + hst.hasta_soyadi + " " + DateTime.UtcNow.ToShortDateString() + ").pdf", FileMode.Create));
            pdfFile.Open();
            #endregion

            #region Sonuç oluşturan bilgileri
            pdfFile.AddCreator("Önder");      //Oluşturan kişinin isminin eklenmesi
            pdfFile.AddCreationDate();        //Oluşturulma tarihinin eklenmesi
            pdfFile.AddAuthor("Radyoloji");   //Yazarın isiminin eklenmesi
            pdfFile.AddHeader("Başlık", "PDF UYGULAMASI OLUSTUR");
            pdfFile.AddTitle("Sonuç Raporu"); //Başlık ve title eklenmesi
            #endregion

            #region Sonuç firma resmi ve tarihi oluştur
            iTextSharp.text.Image jpgimg = iTextSharp.text.Image.GetInstance(@"C:/Users/Önder/Desktop/Önder Fatih Buhurcu Staj Projesi/WebApplicationHastane/WebApplicationHastane/login/images/İsimsiz-1.png");
            jpgimg.ScalePercent(35);
            jpgimg.Alignment = iTextSharp.text.Image.LEFT_ALIGN;

            PdfPTable pdfTableHeader = new PdfPTable(3);
            pdfTableHeader.TotalWidth  = 500f;
            pdfTableHeader.LockedWidth = true;
            //pdfTableHeader.DefaultCell.Border = Rectangle;

            PdfPCell cellheader1 = new PdfPCell(jpgimg);
            cellheader1.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
            cellheader1.VerticalAlignment   = PdfPCell.ALIGN_BOTTOM;
            cellheader1.FixedHeight         = 60f;
            cellheader1.Border = 0;
            pdfTableHeader.AddCell(cellheader1);

            PdfPCell cellheader2 = new PdfPCell(new Phrase("SONUÇ RAPORU", fontArialHeader));
            cellheader2.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
            cellheader2.VerticalAlignment   = PdfPCell.ALIGN_MIDDLE;
            cellheader2.FixedHeight         = 60f;
            cellheader2.Border = 0;
            pdfTableHeader.AddCell(cellheader2);


            PdfPCell cellheader3 = new PdfPCell(new Phrase(DateTime.Now.ToShortDateString(), fontArial));
            cellheader3.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
            cellheader3.VerticalAlignment   = PdfPCell.ALIGN_MIDDLE;
            cellheader3.FixedHeight         = 60f;
            cellheader3.Border = 0;
            pdfTableHeader.AddCell(cellheader3);
            #endregion

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

            Paragraph yazi = new Paragraph("Hasta TC: " + hst.hasta_tc + "\nHasta Adı: " + hst.hasta_adi + "\nHasta Soyadı: " + hst.hasta_soyadi + "\n\n\n");


            #region Tabloyu Oluştur
            PdfPTable pdfTable = new PdfPTable(1);
            pdfTable.TotalWidth              = 500f;
            pdfTable.LockedWidth             = true;
            pdfTable.HorizontalAlignment     = 1;
            pdfTable.DefaultCell.Padding     = 5;
            pdfTable.DefaultCell.BorderColor = iTextSharp.text.BaseColor.GRAY;

            pdfTable.AddCell(new Phrase(ListBox1.SelectedItem.Text + " Sonucu", fontArialboldgeneral));
            pdfTable.AddCell(new Phrase(sonucText.Value, fontArial));

            #endregion

            #region Pdfe yaz ve dosyayı kapat
            if (pdfFile.IsOpen() == false)
            {
                pdfFile.Open();
            }
            pdfFile.Add(pdfTableHeader);
            pdfFile.Add(p);
            pdfFile.Add(yazi);
            pdfFile.Add(pdfTable);
            pdfFile.Close();
            #endregion

            var filter = Builders <yatanhastalar> .Filter.ElemMatch(x => x.ServisList, Builders <servis> .Filter.ElemMatch(x => x.HastaList, Builders <hasta> .Filter.And(Builders <hasta> .Filter.Eq(x => x._id, ObjectId.Parse(ddlHasta.SelectedValue)), Builders <hasta> .Filter.ElemMatch(x => x.RadyolojiList, Builders <radyolojitetkikler> .Filter.And(Builders <radyolojitetkikler> .Filter.Eq(x => x._id, ObjectId.Parse(ddlRadyoloji.SelectedValue)), Builders <radyolojitetkikler> .Filter.ElemMatch(x => x.TetkiklerList, Builders <tetkikler> .Filter.Eq(x => x.tahlil_adi, ListBox1.SelectedItem.Text)))))));

            var update = Builders <yatanhastalar> .Update.Pull("ServisList.$[].HastaList.$[].RadyolojiList.$[].TetkiklerList", tetkiklistesi);

            collection.UpdateOne(filter, update);

            var sayı = radyolojilistesi.SelectMany(x => x.TetkiklerList).ToList();
            if (sayı.Count == 0)
            {
                var filter2 = Builders <yatanhastalar> .Filter.ElemMatch(x => x.ServisList, Builders <servis> .Filter.ElemMatch(x => x.HastaList, Builders <hasta> .Filter.Eq(x => x._id, ObjectId.Parse(ddlHasta.SelectedValue))));

                hst.hasta_radyoloji_durum = "Sonuçlandı";
                var update2 = Builders <yatanhastalar> .Update.Set(b => b.ServisList, servislistesi);
            }
        }
Пример #54
0
        private void btnFactura_Click(object sender, EventArgs e)
        {
            try
            {
                Document documento = new Document(PageSize.LETTER);
                PdfWriter escritor = PdfWriter.GetInstance(documento, new FileStream(@"C:\Users\Vic Kenshin\Desktop\Facturas\" + this.ventaActual.IdFactura.ToString() + ".pdf", FileMode.OpenOrCreate));
                documento.AddTitle(this.ventaActual.IdFactura + " " + this.ventaActual.Cliente.Nombre);
                documento.AddCreator("littleWhiteBlueEyes");
                documento.Open();
                iTextSharp.text.Font fuenteTitulo = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 12, iTextSharp.text.Font.NORMAL, BaseColor.CYAN);
                iTextSharp.text.Font fuenteHead = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 10, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
                iTextSharp.text.Font fuenteCuerpo = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
                iTextSharp.text.Font fuenteFooter = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 8, iTextSharp.text.Font.ITALIC, BaseColor.BLACK);
                Paragraph titulo = new Paragraph("littleWhiteBlueEyes Enterprise", fuenteTitulo);
                titulo.Alignment = Element.ALIGN_CENTER;
                documento.Add(new Paragraph(titulo));
                documento.Add(Chunk.NEWLINE);
                documento.Add(Chunk.NEWLINE);
                documento.Add(new Paragraph("Factura No: " + this.ventaActual.IdFactura.ToString(), fuenteCuerpo));
                documento.Add(new Paragraph("Total: $" + this.ventaActual.Total.ToString(), fuenteCuerpo));
                documento.Add(new Paragraph("Sub-Total: $" + this.ventaActual.SubTotal.ToString(), fuenteCuerpo));
                documento.Add(new Paragraph("Total Iva: $" + this.ventaActual.TotalIva.ToString(), fuenteCuerpo));
                documento.Add(new Paragraph("Cargo (Envio): $" + this.ventaActual.Cargo.ToString(), fuenteCuerpo));
                documento.Add(new Paragraph("Fecha: " + this.ventaActual.FechaCompra.ToShortDateString(), fuenteCuerpo));
                documento.Add(new Paragraph("Cliente: " + this.ventaActual.Cliente.Nombre, fuenteCuerpo));
                documento.Add(new Paragraph("RFC: " + this.ventaActual.Cliente.Rfc, fuenteCuerpo));
                documento.Add(new Paragraph("Dirección: " + this.ventaActual.Cliente.Dir, fuenteCuerpo));
                documento.Add(Chunk.NEWLINE);
                documento.Add(Chunk.NEWLINE);
                PdfPTable tablaProductos = new PdfPTable(5);
                tablaProductos.WidthPercentage = 80;
                PdfPCell colProducto = new PdfPCell(new Phrase("Producto", fuenteCuerpo));
                colProducto.BorderWidth = 0;
                colProducto.BorderWidthBottom = .75f;
                PdfPCell colPrecio = new PdfPCell(new Phrase("Precio", fuenteCuerpo));
                colProducto.BorderWidth = 0;
                colProducto.BorderWidthBottom = .75f;
                PdfPCell colCantidad = new PdfPCell(new Phrase("Cantidad", fuenteCuerpo));
                colProducto.BorderWidth = 0;
                colProducto.BorderWidthBottom = .75f;
                PdfPCell colIva = new PdfPCell(new Phrase("Iva", fuenteCuerpo));
                colProducto.BorderWidth = 0;
                colProducto.BorderWidthBottom = .75f;
                PdfPCell colTotal = new PdfPCell(new Phrase("Total", fuenteCuerpo));
                colProducto.BorderWidth = 0;
                colProducto.BorderWidthBottom = .75f;

                tablaProductos.AddCell(colProducto);
                tablaProductos.AddCell(colPrecio);
                tablaProductos.AddCell(colCantidad);
                tablaProductos.AddCell(colIva);
                tablaProductos.AddCell(colTotal);
                foreach (producto producto in this.ventaActual.Productos)
                {
                    colProducto = new PdfPCell(new Phrase(producto.Nombre, fuenteCuerpo));
                    colPrecio = new PdfPCell(new Phrase("$" + producto.Precio.ToString(), fuenteCuerpo));
                    colCantidad = new PdfPCell(new Phrase(producto.Existencia.ToString(), fuenteCuerpo));
                    colIva = new PdfPCell(new Phrase(producto.Iva.ToString(), fuenteCuerpo));
                    colTotal = new PdfPCell(new Phrase("$" + (producto.Existencia * producto.Precio).ToString(), fuenteCuerpo));
                    tablaProductos.AddCell(colProducto);
                    tablaProductos.AddCell(colPrecio);
                    tablaProductos.AddCell(colCantidad);
                    tablaProductos.AddCell(colIva);
                    tablaProductos.AddCell(colTotal);
                }
                documento.Add(tablaProductos);
                documento.Add(Chunk.NEWLINE);
                Paragraph footer = new Paragraph("littleWhiteBlueEyes Enterprise TradeMark 910 bandit México Developed by ViCross", fuenteFooter);
                footer.Alignment = Element.ALIGN_CENTER;
                documento.Add(new Paragraph(footer));
                documento.Close();
                escritor.Close();
                MessageBox.Show("La factura se ha generado con exito");
                //this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("La factura no se ha generado con exito debido a " + ex.Data);
            }
        }
Пример #55
0
        public LibroAtrasos(AufenPortalReportesDataContext db, EMPRESA empresa, vw_Ubicacione departamento, DateTime FechaDesde, DateTime FechaHasta, string path, string rut)
        {
            //Nombre del archivo y ubiación en el árbol de carpetas
            NombreArchivo = String.Format("{0}/{1}/LibroAtrasos.pdf", empresa.Descripcion, departamento.Descripcion);
            // Vamos a buscar los datos que nos permitirtán armar elreporte
            IEnumerable<sp_LibroAsistenciaResult> resultadoLibroAtrasos =
                                           db.sp_LibroAsistencia(
                                           FechaDesde.ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture),
                                           FechaHasta.ToString("yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture),
                                           int.Parse(empresa.Codigo).ToString(),
                                           departamento.Codigo,
                                           rut).ToList();
            IEnumerable<LibroAsistenciaDTO> libroAtrasos = Mapper.Map<IEnumerable<sp_LibroAsistenciaResult>,
                IEnumerable<LibroAsistenciaDTO>>(resultadoLibroAtrasos)
            .Where(x =>x.Entrada.HasValue && x.Salida.HasValue && x.SalidaTeorica.HasValue && x.EntradaTeorica.HasValue &&
                x.Entrada > x.EntradaTeorica);
            // Comenzaremos a crear el reporte
            if (libroAtrasos.Any())
            {
                Configuracion();
                Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 50, 35);
                using (var ms = new MemoryStream())
                {
                    PdfWriter pdfWriter = PdfWriter.GetInstance(doc, ms);
                    pdfWriter.PageEvent = new Header(empresa, path);
                    doc.Open();
                    foreach (var reporte in libroAtrasos.GroupBy(x => new { x.Rut, x.IdDepartamento, x.IdEmpresa }))
                    {
                        var empleado = db.vw_Empleados.FirstOrDefault(x => x.IdEmpresa == empresa.Codigo &&
                            x.IdUbicacion == reporte.Key.IdDepartamento &&
                                  x.Codigo == reporte.Key.Rut);
                        if (empleado == null)
                        {
                            empleado = new vw_Empleado();
                        }

                        doc.AddAuthor("Aufen");
                        doc.AddCreationDate();
                        doc.AddCreator("Aufen");
                        doc.AddTitle("Libro de Atrasos");
                        // Texto
                        Paragraph parrafo = new Paragraph();
                        parrafo.Add(new Paragraph(
                            String.Format("Departamento: {1}, Fecha de Reporte: {0}",
                            DateTime.Now.ToShortDateString(),
                            departamento.SucursalPlanta), Normal) { Alignment = Element.ALIGN_CENTER });
                        parrafo.Add(new Paragraph("Informe de Atrasos por Área", Titulo) { Alignment = Element.ALIGN_CENTER });
                        doc.Add(parrafo);
                        doc.Add(new Phrase());
                        doc.Add(new Phrase());

                        PdfPTable informacionPersonal = new PdfPTable(new float[] { 1,5});
                        informacionPersonal.AddCell(new PdfPCell(new Phrase("Rut:", Normal)));
                        informacionPersonal.AddCell(new PdfPCell(new Phrase(empleado.RutAufen, NormalNegrita)));
                        informacionPersonal.AddCell(new PdfPCell(new Phrase("Nombre:", Normal)));
                        informacionPersonal.AddCell(new PdfPCell(new Phrase(empleado.NombreCompleto, NormalNegrita)));
                        informacionPersonal.AddCell(new PdfPCell(new Phrase("Centro de Costos:", Normal)));
                        informacionPersonal.AddCell(new PdfPCell(new Phrase(String.Empty, NormalNegrita)));
                        doc.Add(new Phrase());

                        doc.Add(informacionPersonal);
                        // tabla
                        PdfPTable tabla = new PdfPTable(new float[] {2, 2, 2, 2, 2, 2, 2, 4 });
                        // Primera lìnea cabecera
                        tabla.AddCell(new PdfPCell(new Phrase("Fecha", Chico)) { Rowspan = 2 });
                        //tabla.AddCell(new PdfPCell(new Phrase("Empleado", Chico)) { Colspan = 3 });
                        tabla.AddCell(new PdfPCell(new Phrase("Horario", Chico)) { Colspan = 2 });
                        tabla.AddCell(new PdfPCell(new Phrase("Marcas", Chico)) { Colspan = 2 });
                        tabla.AddCell(new PdfPCell(new Phrase("Horas Trabajadas", Chico)) { Colspan = 2 });
                        tabla.AddCell(new PdfPCell(new Phrase("Autorizaciones", Chico)));
                        // Segunda lìnea cabecera
                        //tabla.AddCell(new PdfPCell(new Phrase("Rut", Chico)));
                        //tabla.AddCell(new PdfPCell(new Phrase("Apellidos", Chico)));
                        //tabla.AddCell(new PdfPCell(new Phrase("Nombres", Chico)));
                        tabla.AddCell(new PdfPCell(new Phrase("Ing.", Chico)));
                        tabla.AddCell(new PdfPCell(new Phrase("Sal.", Chico)));
                        tabla.AddCell(new PdfPCell(new Phrase("Ing.", Chico)));
                        tabla.AddCell(new PdfPCell(new Phrase("Sal.", Chico)));
                        tabla.AddCell(new PdfPCell(new Phrase("Atrasos", Chico)));
                        tabla.AddCell(new PdfPCell(new Phrase("H.T.N.", Chico)));
                        tabla.AddCell(new PdfPCell(new Phrase("Permisos", Chico)));

                        foreach (var atraso in reporte)
                        {
                            TimeSpan tiempoAtraso =
                                (atraso.Salida.HasValue && atraso.Entrada.HasValue ? atraso.Salida.Value.Subtract(atraso.Entrada.Value) : new TimeSpan(0)) -
                                (atraso.SalidaTeorica.HasValue && atraso.EntradaTeorica.HasValue ? atraso.SalidaTeorica.Value.Subtract(atraso.EntradaTeorica.Value) : new TimeSpan(0));
                            TimeSpan tiempoNormal = atraso.SalidaTeorica.HasValue && atraso.EntradaTeorica.HasValue ? atraso.SalidaTeorica.Value.Subtract(atraso.EntradaTeorica.Value) : new TimeSpan(0);
                            tabla.AddCell(new PdfPCell(new Phrase(atraso.Fecha.Value.ToString("ddd dd/MM"), Chico)) { HorizontalAlignment = Element.ALIGN_LEFT });
                            //tabla.AddCell(new PdfPCell(new Phrase(atraso.Rut.ToStringConGuion(), Chico)));
                            //tabla.AddCell(new PdfPCell(new Phrase(atraso.Apellidos, Chico)));
                            //tabla.AddCell(new PdfPCell(new Phrase(atraso.Nombres, Chico)));
                            tabla.AddCell(new PdfPCell(new Phrase(atraso.Entrada.HasValue ? atraso.Entrada.Value.ToString("HH:mm") : String.Empty, Chico)));
                            tabla.AddCell(new PdfPCell(new Phrase(atraso.Salida.HasValue ? atraso.Salida.Value.ToString("HH:mm") : String.Empty, Chico)));
                            tabla.AddCell(new PdfPCell(new Phrase(atraso.EntradaTeorica.HasValue ? atraso.EntradaTeorica.Value.ToString("HH:mm") : String.Empty, Chico)));
                            tabla.AddCell(new PdfPCell(new Phrase(atraso.SalidaTeorica.HasValue ? atraso.SalidaTeorica.Value.ToString("HH:mm") : String.Empty, Chico)));
                            tabla.AddCell(new PdfPCell(new Phrase(atraso.printAtraso, Chico)));
                            tabla.AddCell(new PdfPCell(new Phrase("", Chico)));
                            tabla.AddCell(new PdfPCell(new Phrase(atraso.Observacion, Chico)));
                        }
                        tabla.AddCell(new PdfPCell(new Phrase("Total", ChicoNegrita)) { Colspan=5 });
                        //TODO: aqí va la suma de astrasos
                        tabla.AddCell(new PdfPCell(new Phrase(reporte.CalculaAtrasoEntrada(), Chico)));
                        //TODO: aqí va la suma de H.T.N.
                        tabla.AddCell(new PdfPCell(new Phrase("", Chico)));
                        tabla.AddCell(new PdfPCell(new Phrase("", Chico)));
                        doc.Add(tabla);
                        doc.NewPage();
                    }
                    doc.Close();
                    _Archivo = ms.ToArray();
                }
            }
        }
        protected void grvConsultaSolicitud_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            String strNombreArchivoPDF = String.Empty;
            string strRutUsuario = String.Empty;
            string strNombreAlumno = String.Empty;
            string strNombreCarrera = String.Empty;
            string strNumCelular = String.Empty;
            string strCorreo = String.Empty;
            string strDescTipoSolicitud = String.Empty;
            string strGlosaSolicitud = String.Empty;
            string strFechaSolicitud = String.Empty;
            string strGlosaEstadoSolicitud = String.Empty;
            int intCodTipoSolicitud = 0;

            DateTime Hoy = DateTime.Today;
            string fecha_actual = Hoy.ToString("dd-MM-yyyy");

            int intFolioSolicitud = (int)grvConsultaSolicitud.DataKeys[e.RowIndex].Values[0];

            strNombreArchivoPDF = @"C:\Solicitud" + "_" + intFolioSolicitud + "_" + fecha_actual + ".pdf";

            List<Solicitud> lstSolicitud = new List<Solicitud>();
            NegSolicitud NegSolicitudes = new NegSolicitud();

            Document doc = new Document(PageSize.LETTER);
            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(strNombreArchivoPDF, FileMode.Create));

            doc.AddTitle("Detalle de la Solicitud");
            doc.AddCreator("Workflow Solicitudes CIISA");
            string ruta = Server.MapPath("/") + "/imagenes/logoCiisaPDF.jpg";

            doc.Open();
            iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance(@ruta);
            imagen.BorderWidth = 0;
            imagen.Alignment = Element.ALIGN_LEFT;
            float percentage = 0.0f;
            percentage = 45 / imagen.Width;
            imagen.ScalePercent(percentage * 100);
            doc.Add(imagen);

            iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

            lstSolicitud = NegSolicitudes.ObtenerSolicitudesByFolio(intFolioSolicitud);

            foreach (Solicitud Solicitudes in lstSolicitud)
            {
                strRutUsuario = Solicitudes.strRutAlumno;
                strNumCelular = Solicitudes.strCelularContacto;
                strCorreo = Solicitudes.strEmailContacto;
                strDescTipoSolicitud = Solicitudes.strDescripcionSolicitud;
                strGlosaSolicitud = Solicitudes.strGlosaSolicitud;
                strFechaSolicitud = Convert.ToString(Solicitudes.dtmFechaSolicitud);
                intCodTipoSolicitud = Solicitudes.intCodTipoSolicitud;
                strGlosaEstadoSolicitud = Solicitudes.strGlosaEstado;
            }

            // Escribimos el encabezamiento en el documento
            doc.Add(new Paragraph("Información de la Solicitud"));
            doc.Add(new Paragraph("Instituto de Ciencias Tecnológicas"));
            doc.Add(Chunk.NEWLINE);

            iTextSharp.text.Font myfontEncabezado = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 16, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
            Paragraph myParagraph = new Paragraph("Datos del solicitante \n\n", myfontEncabezado);
            doc.Add(myParagraph);

            doc.Add(new Paragraph("Rut Solicitante    :" + strRutUsuario));
            doc.Add(new Paragraph("Nombre Solicitante :" + strNombreAlumno));
            doc.Add(new Paragraph("N° Teléfono        :" + strNumCelular));
            doc.Add(new Paragraph("Correo Electrónico :" + strCorreo));
            doc.Add(new Paragraph("Unidad             :" + strNombreCarrera));
            doc.Add(Chunk.NEWLINE);

            Paragraph myParagraph2 = new Paragraph("Datos de la solicitud \n\n", myfontEncabezado);
            doc.Add(myParagraph2);

            doc.Add(new Paragraph("Folio Solicitud  :" + intFolioSolicitud));
            doc.Add(new Paragraph("Fecha Solicitud  :" + strFechaSolicitud));
            doc.Add(new Paragraph("Tipo Solicitud   :" + strDescTipoSolicitud));
            doc.Add(new Paragraph("Petición         :" + strGlosaSolicitud));
            doc.Add(new Paragraph("Estado Solicitud :" + strGlosaEstadoSolicitud));
            doc.Add(Chunk.NEWLINE);

            List<WorkflowSolicitudes.Entidades.DetalleSolicitud> LstHistory = new List<WorkflowSolicitudes.Entidades.DetalleSolicitud>();
            NegDetalleSolicitud NegDetSol = new NegDetalleSolicitud();
            LstHistory = NegDetSol.HistorialDetalleSolicitud(intFolioSolicitud);

            if (!LstHistory.Count.Equals(0))
            {

                Paragraph myParagraph3 = new Paragraph("Detalles de la Solicitud \n\n", myfontEncabezado);
                doc.Add(myParagraph3);

                PdfPTable tblPrueba = new PdfPTable(6);
                tblPrueba.WidthPercentage = 100;

                PdfPCell clSecuencia = new PdfPCell(new Phrase("Secuencia", _standardFont));
                clSecuencia.BorderWidth = 0;
                clSecuencia.BorderWidthBottom = 0.75f;

                PdfPCell clNombre = new PdfPCell(new Phrase("Nombre", _standardFont));
                clNombre.BorderWidth = 0;
                clNombre.BorderWidthBottom = 0.75f;

                PdfPCell clApellido = new PdfPCell(new Phrase("Apellido", _standardFont));
                clApellido.BorderWidth = 0;
                clApellido.BorderWidthBottom = 0.75f;

                PdfPCell clObservacion = new PdfPCell(new Phrase("Observación", _standardFont));
                clObservacion.BorderWidth = 0;
                clObservacion.BorderWidthBottom = 0.75f;

                PdfPCell clFechaResolucion = new PdfPCell(new Phrase("Fecha Resolución", _standardFont));
                clFechaResolucion.BorderWidth = 0;
                clFechaResolucion.BorderWidthBottom = 0.75f;

                PdfPCell clEstado = new PdfPCell(new Phrase("Estado", _standardFont));
                clEstado.BorderWidth = 0;
                clEstado.BorderWidthBottom = 0.75f;

                foreach (WorkflowSolicitudes.Entidades.DetalleSolicitud Detalle in LstHistory)
                {
                    // Añadimos las celdas a la tabla
                    tblPrueba.AddCell(clSecuencia);
                    tblPrueba.AddCell(clNombre);
                    tblPrueba.AddCell(clApellido);
                    tblPrueba.AddCell(clObservacion);
                    tblPrueba.AddCell(clFechaResolucion);
                    tblPrueba.AddCell(clEstado);

                    clSecuencia = new PdfPCell(new Phrase(Convert.ToString(Detalle.intSecuencia), _standardFont));
                    clSecuencia.BorderWidth = 0;

                    clNombre = new PdfPCell(new Phrase(Detalle.strnombre, _standardFont));
                    clNombre.BorderWidth = 0;

                    clApellido = new PdfPCell(new Phrase(Detalle.strApellido, _standardFont));
                    clApellido.BorderWidth = 0;

                    clObservacion = new PdfPCell(new Phrase(Detalle.StrGlosaDetalleSolictud, _standardFont));
                    clObservacion.BorderWidth = 0;

                    clFechaResolucion = new PdfPCell(new Phrase(Detalle.strApellido, _standardFont));
                    clFechaResolucion.BorderWidth = 0;

                    clEstado = new PdfPCell(new Phrase(Detalle.strEstado, _standardFont));
                    clEstado.BorderWidth = 0;

                    //tblPrueba.AddCell(clSecuencia);
                    //tblPrueba.AddCell(clNombre);
                    //tblPrueba.AddCell(clApellido);
                    //tblPrueba.AddCell(clObservacion);
                    //tblPrueba.AddCell(clFechaResolucion);
                    //tblPrueba.AddCell(clEstado);

                   doc.Add(tblPrueba);
                }

            }
            doc.Close();
            writer.Close();

            System.Diagnostics.Process.Start("AcroRd32.exe", strNombreArchivoPDF);
        }
Пример #57
0
        void CreateRem()
        {
            string namefile = comboBox1.Text + "-Рем.pdf";
            //var Документ = new iTextSharp.text.Document();
            var Документ = new Document(); //создаем pdf документ iTextSharp.text.
            var Писатель = PdfWriter.GetInstance(Документ, new System.IO.FileStream(namefile, System.IO.FileMode.Create)); // в текущем каталоге, если файл есть - создаст новый
            Документ.SetPageSize(PageSize.A4.Rotate());
            Документ.AddAuthor("Безверхий О.А.");
            Документ.AddTitle("Отчёт");
            Документ.AddCreator("Программа учёта ТО и Ремонта");
            Документ.Open();
            //Rectangle rec2 = new Rectangle(PageSize.A4);
            //var БазовыйШрифт = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\comic.ttf", "CP1251", BaseFont.EMBEDDED);
            var БазовыйШрифт = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\times.ttf", "CP1251", BaseFont.EMBEDDED);
            var Шрифт = new Font(БазовыйШрифт, 12, iTextSharp.text.Font.NORMAL);

            Paragraph para = new Paragraph("КАРТА УЧЕТА РЕМОНТА " + comboBox2.Text.ToUpper() + "\n", Шрифт);
            para.Alignment = Element.ALIGN_CENTER;
            Документ.Add(para);

            para = new Paragraph(label2.Text, Шрифт);
            para.Alignment = Element.ALIGN_LEFT;
            Документ.Add(para);

            /*para = new Paragraph("МАРКА: КЗС-1218-40 гос. № А283БВ 28rus инв. № 27" + "\n", Шрифт);
            para.Alignment = Element.ALIGN_LEFT;
            Документ.Add(para);

            para = new Paragraph("МЕХАНИЗАТОР: Вася Петя" + "\n\n", Шрифт);
            Документ.Add(para);*/

            /**/
            para = new Paragraph("" + "\n", Шрифт);
            Документ.Add(para);

            /*var Tabla = new PdfPTable(6);
            Документ.Add(Tabla);*/
            PdfPTable table = new PdfPTable(dataGridView1.Columns.Count);
            for (int j = 0; j < dataGridView1.Columns.Count; j++)
            {
                table.AddCell(new Phrase(dataGridView1.Columns[j].HeaderText, Шрифт));
            }
            table.HeaderRows = 1;
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                for (int k = 0; k < dataGridView1.Columns.Count; k++)
                {
                    if (dataGridView1[k, i].Value != null)
                    {
                        table.AddCell(new Phrase(dataGridView1[k, i].Value.ToString(), Шрифт));
                    }
                }
            }
            Документ.Add(table);

            para = new Paragraph("" + "\n", Шрифт);
            Документ.Add(para);

            para = new Paragraph("Подпись руководителя: ", Шрифт);
            para.Alignment = Element.ALIGN_LEFT;
            Документ.Add(para);

            //Документ.Add(new iTextSharp.text.Paragraph("Текст после таблицы", Шрифт));
            Документ.Close();
            Писатель.Close();
            System.Diagnostics.Process.Start(namefile);
        }
        public string GeneratePdfFile(List <Photo> photos, string tag, string fileName, int mode, int columnsNumber)
        {
            string root = null;

            if (ContextCompat.CheckSelfPermission(Application.Context, Manifest.Permission.WriteExternalStorage)
                != Permission.Granted)
            {
                ActivityCompat.RequestPermissions((Android.App.Activity)
                                                  Application.Context, new string[] { Manifest.Permission.WriteExternalStorage }, 1);
            }

            if (Android.OS.Environment.IsExternalStorageEmulated)
            {
                root = Android.OS.Environment.ExternalStorageDirectory.ToString();
            }
            else
            {
                root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
            }

            Java.IO.File myDir = new Java.IO.File(root + "/DocAndComPDFs");
            if (myDir.Exists() == false)
            {
                myDir.Mkdir();
            }

            var _path = Path.Combine(root, "DocAndComPDFs", fileName);

            FileStream fs = new FileStream(_path, FileMode.Create, FileAccess.Write);

            var doc = new iTextSharp.text.Document(PageSize.A4, 14f, 14f, 30f, 0);

            PdfWriter writer = PdfWriter.GetInstance(doc, fs);

            writer.StrictImageSequence = true;

            doc.Open();
            doc.AddTitle($"docAndCompare result for {tag} tag");
            doc.AddKeywords("docAndCompare");
            doc.AddCreator("iTextSharp lib");

            var titleFont = FontFactory.GetFont("Arial", 34.0f, Color.BLACK);
            var title     = new Paragraph(ResourceLoader.Instance.GetString("pdfTitle"), titleFont);

            var subTitleFont = FontFactory.GetFont("Arial", 14.0f, Color.BLACK);
            var subTitle     = new Paragraph(ResourceLoader.Instance.GetString("pdfSubTitle"), subTitleFont);

            var subSubTitleFont = FontFactory.GetFont("Arial", 10.0f, Color.BLACK);
            var subSubTitle     = new Paragraph(ResourceLoader.Instance.GetString("pdfSubSubTitle") + tag, subSubTitleFont);

            doc.Add(title);
            doc.Add(subTitle);
            doc.Add(subSubTitle);

            doc.Add(new Paragraph(" ")
            {
                SpacingBefore = 8f
            });

            if (mode == 0) // List
            {
                foreach (var photo in photos)
                {
                    var p = new Paragraph(
                        ResourceLoader.Instance.GetString("pdfDataText") + photo.CreatedOn.ToString("dd.MM.yyyy"));
                    p.SpacingAfter = 75f;
                    var img = Image.GetInstance(photo.Path);
                    img.ScalePercent(12f);
                    p.Alignment   = Element.ALIGN_TOP;
                    img.Alignment = Element.ALIGN_MIDDLE;
                    doc.Add(p);
                    doc.Add(img);
                    doc.NewPage();
                }
            }
            else if (mode == 1)   // Tabular
            {
                var numberOfImages = photos.Count;
                var numberOfRows   = 0;

                if (numberOfImages == 3)
                {
                    numberOfRows = 2;
                }
                else if (numberOfImages > 3)
                {
                    numberOfRows = CalculateRowsAmount(numberOfImages, columnsNumber);
                }

                PdfPTable table = new PdfPTable(columnsNumber);
                table.KeepTogether    = true;
                table.WidthPercentage = 90;

                int dateId  = 0;
                int photoId = 0;

                for (int i = 0; i < numberOfRows; i++)
                {
                    for (int x = 0; x < columnsNumber; x++)
                    {
                        // even
                        if (i % 2 == 0)
                        {
                            Paragraph p;

                            if (dateId < numberOfImages)
                            {
                                p = new Paragraph(photos[dateId].CreatedOn.ToString("dd.MM.yyyy"));
                            }
                            else
                            {
                                p = new Paragraph(ResourceLoader.Instance.GetString("pdfEmptyText"));
                            }
                            p.Alignment = Element.ALIGN_CENTER;
                            table.AddCell(p);
                            dateId++;
                        }
                        else
                        {
                            if (photoId < numberOfImages)
                            {
                                var img = Image.GetInstance(photos[photoId].Path);
                                img.ScalePercent(22f);
                                img.Alignment = Element.ALIGN_CENTER;
                                table.AddCell(img);
                            }
                            else
                            {
                                Paragraph p = new Paragraph(ResourceLoader.Instance.GetString("pdfEmptyText"));
                                p.Alignment = Element.ALIGN_CENTER;
                                table.AddCell(p);
                            }
                            photoId++;
                        }
                    }
                }

                doc.Add(table);
            }

            doc.Close();

            return(_path);
        }
        /// <inheritdoc />
        public override async Task <ExportedRoleplay> ExportAsync(Roleplay roleplay)
        {
            // Create our document
            var pdfDoc = new Document();

            var filePath = Path.GetTempFileName();

            using (var of = File.Create(filePath))
            {
                var writer = PdfWriter.GetInstance(pdfDoc, of);
                writer.Open();
                pdfDoc.Open();

                var owner = await this.Guild.GetUserAsync((ulong)roleplay.Owner.DiscordID);

                pdfDoc.AddAuthor(owner.Nickname);
                pdfDoc.AddCreationDate();
                pdfDoc.AddCreator("DIGOS Ambassador");
                pdfDoc.AddTitle(roleplay.Name);

                var joinedUsers = await Task.WhenAll
                                  (
                    roleplay.JoinedUsers.Select
                    (
                        async p =>
                {
                    var guildUser = await this.Guild.GetUserAsync((ulong)p.User.DiscordID);
                    if (guildUser is null)
                    {
                        var messageByUser = roleplay.Messages.FirstOrDefault
                                            (
                            m => m.AuthorDiscordID == p.User.DiscordID
                                            );

                        if (messageByUser is null)
                        {
                            return($"Unknown user ({p.User.DiscordID})");
                        }

                        return(messageByUser.AuthorNickname);
                    }

                    return(guildUser.Username);
                }
                    )
                                  );

                pdfDoc.Add(CreateTitle(roleplay.Name));
                pdfDoc.Add(CreateParticipantList(joinedUsers));

                pdfDoc.NewPage();

                var messages = roleplay.Messages.OrderBy(m => m.Timestamp).DistinctBy(m => m.Contents);
                foreach (var message in messages)
                {
                    pdfDoc.Add(CreateMessage(message.AuthorNickname, message.Contents));
                }

                pdfDoc.Close();
                writer.Flush();
                writer.Close();
            }

            var resultFile = File.OpenRead(filePath);
            var exported   = new ExportedRoleplay(roleplay.Name, ExportFormat.PDF, resultFile);

            return(exported);
        }
Пример #60
0
        public static byte[] CrearRecibo(string Nombre, string RFC, Dictionary <string, string> conceptos, string direccion, string telefono, float Total, bool leyenda, string Imagen, bool Moneda)
        {
            Font     font     = new Font(Font.FontFamily.HELVETICA, 6, Font.NORMAL);
            Font     sellos   = new Font(Font.FontFamily.HELVETICA, 5, Font.NORMAL);
            Font     textBold = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 7);
            DateTime now      = DateTime.Now;

            iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER);

            MemoryStream memStream = new MemoryStream();

            iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, memStream);
            doc.AddTitle("Recibo Electronico");
            doc.AddCreator("Avenzo Proteccion");
            doc.AddAuthor("Cristian Santiago Rosas");
            doc.Open();
            iTextSharp.text.Image         avenzo = iTextSharp.text.Image.GetInstance(Imagen);
            iTextSharp.text.pdf.PdfPTable Header = new iTextSharp.text.pdf.PdfPTable(12);
            float[] widths = new float[] { .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f, .8f };
            iTextSharp.text.Rectangle page = doc.PageSize;
            Header.WidthPercentage = 80;
            Header.LockedWidth     = true;
            Header.SetWidths(widths);
            Header.TotalWidth = page.Width - 90;
            //---------------------------------------------
            //-----------CABEZERA DEL DOCUMENTO------------
            //---------------------------------------------
            iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell();//--Logo
            cell.AddElement(avenzo);
            cell.Colspan = 4;
            cell.Border  = BORDER;
            iTextSharp.text.pdf.PdfPCell cell2 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal
            cell2.AddElement(new iTextSharp.text.Paragraph("AVENZO BUSINESS GROUP S de RL de CV" + "\n" + "ABG1512109U1" + "\nDomicilio Fiscal\n" + "AVENIDA GRANDES LAGOS 19702 6\nFRACC. EL LAGO 22210\nTIJUANA, Baja California Mexico" + "\nTel. 6645266573", new Font(Font.FontFamily.HELVETICA, 7, Font.BOLD)));
            cell2.Colspan             = 4;
            cell2.Border              = BORDER;
            cell2.HorizontalAlignment = 1;
            Header.AddCell(cell);
            Header.AddCell(cell2);
            iTextSharp.text.pdf.PdfPCell cell51 = new iTextSharp.text.pdf.PdfPCell();
            cell51.Phrase = new Phrase("", textBold);
            cell51.HorizontalAlignment = Element.ALIGN_CENTER;
            cell51.Colspan             = 4;
            cell51.Border = 0;
            Header.AddCell(cell51);
            iTextSharp.text.pdf.PdfPCell salto = new iTextSharp.text.pdf.PdfPCell();
            salto.AddElement(new Chunk("\n"));
            salto.Colspan = 12;
            salto.Border  = BORDER;
            Header.AddCell(salto);
            //---------------------------------------------
            //------------DATOS CLIENTE-------------------
            //---------------------------------------------
            iTextSharp.text.pdf.PdfPCell cell4 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal
            cell4.Colspan       = 1;
            cell4.Border        = BORDER;
            cell4.PaddingTop    = 0;
            cell4.PaddingBottom = 0;
            cell4.AddElement(new Paragraph("Cliente:", textBold));
            iTextSharp.text.pdf.PdfPCell cell5 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal
            cell5.Colspan       = 2;
            cell5.PaddingTop    = 0;
            cell5.PaddingBottom = 0;
            cell5.Border        = BORDER;
            cell5.AddElement(new Paragraph(Nombre, font));
            iTextSharp.text.pdf.PdfPCell cell6 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal
            cell6.Colspan       = 2;
            cell6.Border        = BORDER;
            cell6.PaddingTop    = 0;
            cell6.PaddingBottom = 0;
            cell6.AddElement(new Paragraph("", textBold));
            iTextSharp.text.pdf.PdfPCell cell7 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal
            cell7.Colspan       = 7;
            cell7.Border        = BORDER;
            cell7.PaddingTop    = 0;
            cell7.PaddingBottom = 0;
            cell7.AddElement(new Paragraph("", font));
            iTextSharp.text.pdf.PdfPCell cell8 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal
            cell8.Colspan       = 1;
            cell8.Border        = BORDER;
            cell8.PaddingTop    = 0;
            cell8.PaddingBottom = 0;
            cell8.AddElement(new Paragraph("RFC:", textBold));
            iTextSharp.text.pdf.PdfPCell cell9 = new iTextSharp.text.pdf.PdfPCell();//--Domicilio Fiscal
            cell9.Colspan       = 2;
            cell9.Border        = BORDER;
            cell9.PaddingTop    = 0;
            cell9.PaddingBottom = 0;
            cell9.AddElement(new Paragraph(RFC, font));
            iTextSharp.text.pdf.PdfPCell cell10 = new iTextSharp.text.pdf.PdfPCell();
            cell10.Colspan       = 2;
            cell10.Border        = BORDER;
            cell10.PaddingBottom = 0;
            cell10.PaddingTop    = 0;
            cell10.AddElement(new Paragraph("Lugar de Expedición:", textBold));
            iTextSharp.text.pdf.PdfPCell cell11 = new iTextSharp.text.pdf.PdfPCell();
            cell11.Colspan       = 3;
            cell11.Border        = BORDER;
            cell11.PaddingTop    = 0;
            cell11.PaddingBottom = 0;
            cell11.AddElement(new Paragraph("TIJUANA, Baja California", font));
            iTextSharp.text.pdf.PdfPCell cell12 = new iTextSharp.text.pdf.PdfPCell();
            cell12.AddElement(new Paragraph("Fecha de Expedicion:", textBold));
            cell12.Colspan       = 2;
            cell12.Border        = BORDER;
            cell12.PaddingBottom = 0;
            cell12.PaddingTop    = 0;
            iTextSharp.text.pdf.PdfPCell cell13 = new iTextSharp.text.pdf.PdfPCell();
            cell13.Colspan       = 3;
            cell13.Border        = BORDER;
            cell13.PaddingTop    = 0;
            cell13.PaddingBottom = 0;
            DateTime time = DateTime.Now;

            System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("es-MX");
            cell13.AddElement(new Paragraph(time.ToString("dd", ci) + " de " + time.ToString("MMMM", ci) + " del " + time.ToString("yyyy", ci), font));
            //---
            iTextSharp.text.pdf.PdfPCell cell14 = new iTextSharp.text.pdf.PdfPCell();
            cell14.Colspan       = 1;
            cell14.Rowspan       = 2;
            cell14.PaddingTop    = 0;
            cell14.PaddingBottom = 0;
            cell14.Border        = BORDER;
            cell14.AddElement(new Paragraph("Direccion:", textBold));
            iTextSharp.text.pdf.PdfPCell cell15 = new iTextSharp.text.pdf.PdfPCell();
            cell15.Colspan       = 2;
            cell15.Rowspan       = 2;
            cell15.Border        = BORDER;
            cell15.PaddingBottom = 0;
            cell15.PaddingTop    = 0;
            if (direccion.Split('|').Count() == 1)
            {
                cell15.AddElement(new Paragraph(direccion, font));
            }
            else
            {
                cell15.AddElement(new Paragraph(direccion.Split('|')[0] + direccion.Split('|')[1] + direccion.Split('|')[2], font));
            }
            iTextSharp.text.pdf.PdfPCell cell16 = new iTextSharp.text.pdf.PdfPCell();
            cell16.Colspan       = 2;
            cell16.PaddingTop    = 0;
            cell16.PaddingBottom = 0;
            cell16.AddElement(new Paragraph("Mes de Pago:", textBold));
            cell16.Border = BORDER;
            iTextSharp.text.pdf.PdfPCell cell17 = new iTextSharp.text.pdf.PdfPCell();
            cell17.PaddingBottom = 0;
            cell17.PaddingTop    = 0;
            cell17.Colspan       = 3;
            cell17.Border        = BORDER;
            cell17.AddElement(new Paragraph("" + time.ToString("MMMM", ci).ToUpper(), font));
            iTextSharp.text.pdf.PdfPCell cell18 = new iTextSharp.text.pdf.PdfPCell();
            cell18.AddElement(new Paragraph("", textBold));
            cell18.Colspan       = 2;
            cell18.Border        = BORDER;
            cell18.PaddingTop    = 0;
            cell18.PaddingBottom = 0;
            iTextSharp.text.pdf.PdfPCell cell19 = new iTextSharp.text.pdf.PdfPCell();
            cell19.Colspan       = 2;
            cell19.Border        = BORDER;
            cell19.PaddingBottom = 0;
            cell19.PaddingTop    = 0;
            cell19.AddElement(new Paragraph("", font));
            iTextSharp.text.pdf.PdfPCell cell20 = new iTextSharp.text.pdf.PdfPCell();
            cell20.Colspan       = 2;
            cell20.Border        = BORDER;
            cell20.PaddingTop    = 0;
            cell20.PaddingBottom = 0;
            cell20.AddElement(new Paragraph("", textBold));
            iTextSharp.text.pdf.PdfPCell cell21 = new iTextSharp.text.pdf.PdfPCell();
            cell21.Colspan       = 3;
            cell21.Border        = BORDER;
            cell21.PaddingTop    = 0;
            cell21.PaddingBottom = 0;
            cell21.AddElement(new Paragraph("", font));
            iTextSharp.text.pdf.PdfPCell cell22 = new iTextSharp.text.pdf.PdfPCell();
            cell22.Colspan       = 2;
            cell22.Border        = BORDER;
            cell22.PaddingTop    = 0;
            cell22.PaddingBottom = 0;
            cell22.AddElement(new Paragraph("No. Cuenta Pago:", textBold));
            iTextSharp.text.pdf.PdfPCell cell23 = new iTextSharp.text.pdf.PdfPCell();
            cell23.Colspan       = 2;
            cell23.Border        = BORDER;
            cell23.PaddingTop    = 0;
            cell23.PaddingBottom = 0;
            cell23.AddElement(new Paragraph("", font));
            //----------------------------------------------
            //-----------------PRODUCTOS--------------------
            //----------------------------------------------
            iTextSharp.text.pdf.PdfPCell cell24 = new iTextSharp.text.pdf.PdfPCell();
            cell24.Colspan = 1;
            cell24.AddElement(new Paragraph("Cantidad", textBold));
            iTextSharp.text.pdf.PdfPCell cell25 = new iTextSharp.text.pdf.PdfPCell();
            cell25.Colspan = 1;
            cell25.AddElement(new Paragraph("Unidad de Medida", textBold));
            iTextSharp.text.pdf.PdfPCell cell26 = new iTextSharp.text.pdf.PdfPCell();
            cell26.Colspan             = 6;
            cell26.HorizontalAlignment = Element.ALIGN_CENTER;
            cell26.VerticalAlignment   = Element.ALIGN_CENTER;
            cell26.AddElement(new Paragraph("Descripcion", textBold));
            iTextSharp.text.pdf.PdfPCell cell27 = new iTextSharp.text.pdf.PdfPCell();
            cell27.Colspan = 2;
            cell27.AddElement(new Paragraph("Producto Unitario", textBold));
            iTextSharp.text.pdf.PdfPCell cell28 = new iTextSharp.text.pdf.PdfPCell();
            cell28.Colspan             = 2;
            cell28.HorizontalAlignment = Element.ALIGN_CENTER;
            cell28.VerticalAlignment   = Element.ALIGN_CENTER;
            cell28.AddElement(new Paragraph("Importe", textBold));
            //-----------------------------------------------
            iTextSharp.text.pdf.PdfPCell cell29 = new iTextSharp.text.pdf.PdfPCell();
            cell29.AddElement(new Paragraph(conceptos["cantidad"], font));
            cell29.Colspan = 1;
            iTextSharp.text.pdf.PdfPCell cell30 = new iTextSharp.text.pdf.PdfPCell();
            cell30.AddElement(new Paragraph(conceptos["unidad"], font));
            cell30.Colspan = 1;
            iTextSharp.text.pdf.PdfPCell cell31 = new iTextSharp.text.pdf.PdfPCell();
            cell31.AddElement(new Paragraph(conceptos["descripcion"], font));
            cell31.Colspan = 6;
            iTextSharp.text.pdf.PdfPCell cell32 = new iTextSharp.text.pdf.PdfPCell();
            cell32.AddElement(new Paragraph(conceptos["valorUnitario"], font));
            cell32.Colspan = 2;
            iTextSharp.text.pdf.PdfPCell cell33 = new iTextSharp.text.pdf.PdfPCell();
            cell33.AddElement(new Paragraph(conceptos["importe"], font));
            cell33.Colspan     = 2;
            cell33.FixedHeight = 200f;


            //-------------------------------------------------------
            //----------------------TOTAL----------------------------
            //-------------------------------------------------------
            iTextSharp.text.pdf.PdfPCell cell34 = new iTextSharp.text.pdf.PdfPCell();
            cell34.Colspan       = 2;
            cell34.Rowspan       = 3;
            cell34.Border        = BORDER;
            cell34.PaddingBottom = 0;
            cell34.PaddingTop    = 0;
            cell34.AddElement(new Paragraph(""));
            iTextSharp.text.pdf.PdfPCell cell35 = new iTextSharp.text.pdf.PdfPCell();
            cell35.Colspan       = 7;
            cell35.Border        = BORDER;
            cell35.Rowspan       = 3;
            cell35.PaddingTop    = 0;
            cell35.PaddingBottom = 0;
            NumLetra nl = new NumLetra();

            cell35.AddElement(new Paragraph("IMPORTE CON LETRA: " + nl.Convertir("" + Total, true, Moneda), textBold));
            iTextSharp.text.pdf.PdfPCell cell36 = new iTextSharp.text.pdf.PdfPCell();
            cell36.Colspan             = 2;
            cell36.Border              = BORDER;
            cell36.PaddingBottom       = 0;
            cell36.PaddingTop          = 0;
            cell36.Phrase              = new Phrase("SubTotal:", textBold);
            cell36.HorizontalAlignment = Element.ALIGN_RIGHT;
            cell36.VerticalAlignment   = Element.ALIGN_BOTTOM;
            iTextSharp.text.pdf.PdfPCell cell37 = new iTextSharp.text.pdf.PdfPCell();
            cell37.Colspan       = 1;
            cell37.Border        = BORDER;
            cell37.PaddingTop    = 0;
            cell37.PaddingBottom = 0;
            cell37.AddElement(new Paragraph("$ " + ((Total / 1.16)).ToString("f2"), font));
            //--
            iTextSharp.text.pdf.PdfPCell cell38 = new iTextSharp.text.pdf.PdfPCell();
            cell38.Colspan             = 2;
            cell38.PaddingBottom       = 0;
            cell38.PaddingTop          = 0;
            cell38.Border              = BORDER;
            cell38.Phrase              = new Phrase("IVA(IVA 16.00%):", textBold);
            cell38.HorizontalAlignment = Element.ALIGN_RIGHT;
            cell38.VerticalAlignment   = Element.ALIGN_BOTTOM;
            iTextSharp.text.pdf.PdfPCell cell39 = new iTextSharp.text.pdf.PdfPCell();
            cell39.Colspan       = 1;
            cell39.PaddingTop    = 0;
            cell39.PaddingBottom = 0;
            cell39.Border        = BORDER;
            cell39.AddElement(new Paragraph("$ " + (Total - (Total / 1.16)).ToString("f2"), font));
            //---
            iTextSharp.text.pdf.PdfPCell cell40 = new iTextSharp.text.pdf.PdfPCell();
            cell40.Colspan             = 2;
            cell40.Border              = BORDER;
            cell40.VerticalAlignment   = Element.ALIGN_BOTTOM;
            cell40.Phrase              = new Phrase("Total:", textBold);
            cell40.PaddingBottom       = 0;
            cell40.PaddingTop          = 0;
            cell40.HorizontalAlignment = Element.ALIGN_RIGHT;
            iTextSharp.text.pdf.PdfPCell cell41 = new iTextSharp.text.pdf.PdfPCell();
            cell41.Colspan       = 1;
            cell41.Border        = BORDER;
            cell41.PaddingTop    = 0;
            cell41.PaddingBottom = 0;
            cell41.AddElement(new Paragraph("$ " + Total.ToString("f2"), font));
            //---------------------------------------------------------------------
            iTextSharp.text.pdf.PdfPCell cell42 = new iTextSharp.text.pdf.PdfPCell();
            cell42.Colspan = 12;
            cell42.Border  = BORDER;
            cell42.AddElement(new Paragraph("CONDICIONES GENERALES", textBold));
            iTextSharp.text.pdf.PdfPCell cell43 = new iTextSharp.text.pdf.PdfPCell();
            cell43.Colspan = 12;
            cell43.Border  = BORDER;
            cell43.Rowspan = 9;
            string condiciones = "1.- Unicamente se atenderán productos comercializados por Avenzo Business Group S.de R.L.de C.V.";

            condiciones = condiciones + "\n2.- Todos los equipos cuentan con 1(un) año de garantía después de su fecha de facturación, excepto que se indique lo contrario en la factura.";
            condiciones = condiciones + "\n3.- Esta garantía es valida solo hasta el " + time.ToString("dd", ci) + " de " + time.ToString("MMMM", ci) + " del " + (time.AddYears(1).ToString("yyyy", ci));
            condiciones = condiciones + "\n4.- Es indispensable indicar la descripción clara del problema.No se aceptará equipo a reparación y / o garantía con descripciones tales como \"NO FUNCIONA\", \"NO SIRVE\", etc.";
            condiciones = condiciones + "\n5.- Se recomienda conservar su factura o recibo de compra como protección adicional ya que puede sustituir a la póliza de garantía en caso de que ésta se extravíe o exista alguna discrepancia para comprobar la vigencia de la póliza.";
            condiciones = condiciones + "\n6.- Avenzo Business Group S.R.L.de C.V.se compromete a cambiar el producto defectuoso o en caso que se haya descontinuado cambiarlo por uno nuevo igual, similar o bien se ofrecerá una nota de crédito por el equipo a valor actual, cuando no sea posible la reparación a consecuencia de un defecto de fabricación previo diagnostico realizado en las oficinas sin ningún cargo para el cliente.";
            condiciones = condiciones + "\n7.- El tiempo de cambio no será mayor de 30(treinta) dias naturales contados a partir de la fecha de recepción del producto.";
            condiciones = condiciones + "\n\nNOTA: Esta garantía incluye los gastos de transportación internos del producto que se deriven en el cumplimiento de la misma.";
            cell43.AddElement(new Paragraph(condiciones, font));
            iTextSharp.text.pdf.PdfPCell cell44 = new iTextSharp.text.pdf.PdfPCell();
            cell44.Colspan = 12;
            cell44.Border  = BORDER;
            cell44.AddElement(new Paragraph("EXEPCIONES Y RESTRICCIONES", textBold));
            iTextSharp.text.pdf.PdfPCell cell45 = new iTextSharp.text.pdf.PdfPCell();
            cell45.Colspan = 12;
            cell45.Rowspan = 9;
            cell45.Border  = BORDER;
            string casos = "\na. La garantía No cubre desperfectos ocacionados:\n •Por Variaciones de voltaje(equipo quemado).";

            casos = casos + "\n  •Equipo mutilado en cables, accesorios o cualquiera de sus partes.";
            casos = casos + "\n  •Cuando se demuestre que se hizo algun cambio ala instalación original  o se ha hecho mal uso del equipo (de acuerdo a manuales).";
            casos = casos + "\nb. Para servicio posterior al periodo de garantia o por equipo dañada que no aplica la garantia Avenzo ofrecerá";
            casos = casos + "\n  •Reparación en un periodo de 30-90 días previa cotización autorizaada por el distribuidor.";
            casos = casos + "\n  •Remplazar el equipo ofreciendo el máximo descuento.";
            cell45.AddElement(new Paragraph("Avenzo Business Group S.de R.L.de C.V. SE EXIME DE HACER EFECTIVA ESTA PÓLIZA DE GARANTIA EN LOS SIGUINTES CASOS:" + casos, font));
            Header.AddCell(cell4);
            Header.AddCell(cell5);
            Header.AddCell(cell6);
            Header.AddCell(cell7);
            Header.AddCell(cell8);
            Header.AddCell(cell9);
            Header.AddCell(cell10);
            Header.AddCell(cell11);
            Header.AddCell(cell12);
            Header.AddCell(cell13);
            Header.AddCell(cell14);
            Header.AddCell(cell15);
            Header.AddCell(cell16);
            Header.AddCell(cell17);
            Header.AddCell(cell18);
            Header.AddCell(cell19);
            Header.AddCell(cell20);
            Header.AddCell(cell21);
            Header.AddCell(cell22);
            Header.AddCell(cell23);
            Header.AddCell(salto);
            Header.AddCell(cell24);
            Header.AddCell(cell25);
            Header.AddCell(cell26);
            Header.AddCell(cell27);
            Header.AddCell(cell28);
            Header.AddCell(cell29);
            Header.AddCell(cell30);
            Header.AddCell(cell31);
            Header.AddCell(cell32);
            Header.AddCell(cell33);
            Header.AddCell(cell34);
            Header.AddCell(cell35);
            Header.AddCell(cell36);
            Header.AddCell(cell37);
            Header.AddCell(cell38);
            Header.AddCell(cell39);
            Header.AddCell(cell40);
            Header.AddCell(cell41);
            Header.AddCell(salto);
            if (leyenda == true)
            {
                Header.AddCell(cell42);
                Header.AddCell(cell43);
                Header.AddCell(cell44);
                Header.AddCell(cell45);
            }
            doc.Add(Header);
            doc.Close();
            writer.Close();
            return(memStream.ToArray());
        }