An Image is the representation of a graphic element (JPEG, PNG or GIF) that has to be inserted into the document
Inheritance: Rectangle
Exemplo n.º 1
1
        protected internal override void Render(PdfContentByte cb, Vector2D offset)
        {
            if (image == null)
                image = Image.GetInstance(filepath);

            image.ScaleAbsolute((float)Size.X.Value(UnitsOfMeasure.Points), (float)Size.Y.Value(UnitsOfMeasure.Points));
            image.SetAbsolutePosition((float)offset.X.Value(UnitsOfMeasure.Points), (float)offset.Y.Value(UnitsOfMeasure.Points));

            cb.AddImage(image);
        }
 public CountingWorksheet(string strTitle, string strFolder, int count, int max)
     : base(strTitle, strFolder)
 {
     m_iCount = count;
     m_iMax = max;
     rectangle = iTextSharp.text.Image.GetInstance("\\Resources\\rectangle.gif");
 }
Exemplo n.º 3
0
    public void demoPDF()
    {
        using (Stream inputPdfStream = new FileStream(Server.MapPath("~") + "/MyFiles/demo.pdf", FileMode.Open, FileAccess.Read, FileShare.Read))
            using (Stream inputImageStream = new FileStream(Server.MapPath("~") + "/Sign/Sign.png", FileMode.Open, FileAccess.Read, FileShare.Read))
                using (Stream outputPdfStream = new FileStream(Server.MapPath("~") + "/MyFiles/Result.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    var reader = new PdfReader(inputPdfStream);

                    int pages = reader.NumberOfPages;

                    for (int i = 0; i < pages; i++)
                    {
                        var stamper        = new PdfStamper(reader, outputPdfStream);
                        var pdfContentByte = stamper.GetOverContent(1);

                        iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);
                        // image.ScalePercent(18f);
                        image.ScaleAbsolute(100, 30);

                        image.SetAbsolutePosition(300, 310);
                        pdfContentByte.AddImage(image);


                        stamper.Close();
                    }
                }
    }
Exemplo n.º 4
0
    public void setPDF()
    {
        string imgpath       = Server.MapPath("~/Sign/21.jpg");
        string pdfpath       = Server.MapPath("~/TemplateStore/Forms/Nf packet.pdf");
        string pdfpathourput = Server.MapPath("~/TemplateStore/Forms/Demo.pdf");

        using (Stream inputPdfStream = new FileStream(pdfpath, FileMode.Open, FileAccess.Read, FileShare.Read))
            using (Stream inputImageStream = new FileStream(imgpath, FileMode.Open, FileAccess.Read, FileShare.Read))
                using (Stream outputPdfStream = new FileStream(pdfpathourput, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    var reader = new iTextSharp.text.pdf.PdfReader(inputPdfStream);

                    int val = reader.NumberOfPages;

                    var stamper = new iTextSharp.text.pdf.PdfStamper(reader, outputPdfStream);

                    var pdfContentByte = stamper.GetOverContent(1);

                    iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);

                    image.SetAbsolutePosition(759f, 459f);

                    pdfContentByte.AddImage(image);
                    stamper.Close();
                }
    }
Exemplo n.º 5
0
 public void FillEvent(float[] hdrTableLayout, string[] hdrNameList, int shid, string payeeName, string title, iTextSharp.text.Image imgLogo)
 {
     _hdrTableLayout = hdrTableLayout;
     _hdrNameList = hdrNameList;
     _payeeName = payeeName;
     _shid = shid.ToString();
     _title = title;
     _imgLogo = imgLogo;
 }
Exemplo n.º 6
0
 public void FillEvent(string title, iTextSharp.text.Image imgLogo, int pageNumber, string shid, string businessName, string landownerName)
 {
     _title = title;
     _imgLogo = imgLogo;
     _shid = shid;
     _businessName = businessName;
     _landownerName = landownerName;
     _pageNumber = pageNumber;
 }
Exemplo n.º 7
0
        public void FillEvent(string statementDate, int pageNumber, string title, iTextSharp.text.Image imgLogo)
        {
            if (statementDate != null && statementDate.Length > 0) {
                _statementDate = statementDate;
            } else {
                _statementDate = "";
            }

            _pageNumber = pageNumber;
            _title = title;
            _imgLogo = imgLogo;
        }
Exemplo n.º 8
0
        public PdfGrid RenderingReportHeader(Document pdfDoc, PdfWriter pdfWriter, IList<SummaryCellData> summaryData)
        {
            if (_image == null) //cache is empty
            {
                var templatePath = System.IO.Path.Combine(AppPath.ApplicationPath, "data\\PdfHeaderTemplate.pdf");
                _image = PdfImageHelper.GetITextSharpImageFromPdfTemplate(pdfWriter, templatePath);
            }

            var table = new PdfGrid(1);
            var cell = new PdfPCell(_image, true) { Border = 0 };
            table.AddCell(cell);
            return table;
        }
Exemplo n.º 9
0
        public void FillEvent(string shid, string busName, string addr1, string addr2, string csz, decimal checkAmount, int pageNumber, string title, iTextSharp.text.Image imgLogo)
        {
            _shid = shid;
            _businessName = busName;
            _memAddr1 = addr1;
            _memAddr2 = addr2;
            _memCSZ = csz;
            _checkAmount = checkAmount;

            _pageNumber = pageNumber;
            _title = title;
            _imgLogo = imgLogo;
        }
Exemplo n.º 10
0
 // ---------------------------------------------------------------------------    
 /**
  * Add content to a ColumnText object.
  * @param ct the ColumnText object
  * @param movie a Movie object
  * @param img the poster of the image
  */
 public void AddContent(ColumnText ct, Movie movie, Image img)
 {
     ct.AddElement(img);
     ct.AddElement(new Paragraph(movie.Title, FilmFonts.BOLD));
     if (!string.IsNullOrEmpty(movie.OriginalTitle))
     {
         ct.AddElement(new Paragraph(movie.OriginalTitle, FilmFonts.ITALIC));
     }
     ct.AddElement(PojoToElementFactory.GetDirectorList(movie));
     ct.AddElement(PojoToElementFactory.GetYearPhrase(movie));
     ct.AddElement(PojoToElementFactory.GetDurationPhrase(movie));
     ct.AddElement(PojoToElementFactory.GetCountryList(movie));
     ct.AddElement(Chunk.NEWLINE);
 }
Exemplo n.º 11
0
        public void FillEvent(DateTime reportDate,
            int shid, string taxID, string busName, string adrLine1, string adrLine2, string csz,
            int pageNumber, string title, iTextSharp.text.Image imgLogo)
        {
            _reportDate = reportDate;
            _shid = shid;
            _busName = busName;
            _adrLine1 = adrLine1;
            _adrLine2 = adrLine2;
            _csz = csz;

            _pageNumber = pageNumber;
            _title = title;
            _imgLogo = imgLogo;
        }
Exemplo n.º 12
0
        public PdfGrid RenderingReportHeader(Document pdfDoc, PdfWriter pdfWriter, IList<SummaryCellData> summaryData)
        {
            if (_image == null) //cache is empty
            {
                var templatePath = System.IO.Path.Combine(AppPath.ApplicationPath, "data\\PdfHeaderTemplate.pdf");
                _image = PdfImageHelper.GetITextSharpImageFromPdfTemplate(pdfWriter, templatePath);
            }

            var table = new PdfGrid(1);
            var cell = new PdfPCell(_image, true) { Border = 0 };
            table.AddCell(cell);
            return table;

            //Note: return null if you want to skip this callback and render nothing. Also in this case, you need to set the header.CacheHeader(cache: false) too.
        }
Exemplo n.º 13
0
        public void FillEvent(SqlDataReader dr, string statementDate, int pageNumber, string title, iTextSharp.text.Image imgLogo)
        {
            if (statementDate != null && statementDate.Length > 0) {
                _statementDate = statementDate;
            } else {
                _statementDate = "";
            }

            _groName = dr.GetString(dr.GetOrdinal("GrowerName"));
            _groAdr1 = dr.GetString(dr.GetOrdinal("GroAdr1"));
            _groAdr2 = dr.GetString(dr.GetOrdinal("GroAdr2"));
            _groCSZ = dr.GetString(dr.GetOrdinal("GroCSZ"));

            _pageNumber = pageNumber;
            _title = title;
            _imgLogo = imgLogo;
        }
Exemplo n.º 14
0
 public void FillEvent(string shareholderName, int shid, string deliveryDate,
     int pageNumber, string title, iTextSharp.text.Image imgLogo, string[] hdrTableNames, float[] hdrTableLayout)
 {
     ShareholderName = shareholderName;
     SHID = shid.ToString();
     DeliveryDate = deliveryDate;
     PageNumber = pageNumber;
     Title = title;
     _imgLogo = imgLogo;
     _hdrTableNames = hdrTableNames;
     _hdrTableLayout = hdrTableLayout;
 }
 /// <summary>
 /// ctor.
 /// </summary>        
 public TotalPagesNumberHTMLTagProcessor(Image image)
 {
     _image = image;
 }
Exemplo n.º 16
0
        private void btnExport_Click(object sender, EventArgs e)
        {
            saveFileDialog1.Title            = "Export to PDF";
            saveFileDialog1.Filter           = "(*.pdf)|*.pdf";
            saveFileDialog1.InitialDirectory = @"D:\";
            saveFileDialog1.FileName         = "AHP_" + mainForm.getCurrentTopic().topicName + "_" + mainForm.getCurrentUser().userName;
            saveFileDialog1.FileOk          += saveFileDialog1_FileOk;

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    iTextSharp.text.Document doc = new iTextSharp.text.Document();
                    PdfWriter pdfWriter          = PdfWriter.GetInstance(doc, new FileStream(saveFileDialog1.FileName, FileMode.Create));
                    //pdfWriter.PageEvent = new ITextEvents(mainForm.getCurrentTopic().topicName.ToUpper());

                    // FONT DEFINITION
                    //iTextSharp.text.pdf.BaseFont bfTitle = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA_BOLD, iTextSharp.text.pdf.BaseFont.CP1252, iTextSharp.text.pdf.BaseFont.EMBEDDED);
                    //iTextSharp.text.Font fontTitle = new iTextSharp.text.Font(bfTitle, 15);
                    //fontTitle.SetStyle(iTextSharp.text.Font.UNDERLINE);
                    iTextSharp.text.pdf.BaseFont bfNormal       = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA, iTextSharp.text.pdf.BaseFont.CP1252, iTextSharp.text.pdf.BaseFont.EMBEDDED);
                    iTextSharp.text.pdf.BaseFont bfBold         = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA_BOLD, iTextSharp.text.pdf.BaseFont.CP1252, iTextSharp.text.pdf.BaseFont.EMBEDDED);
                    iTextSharp.text.Font         fontSubtitle   = new iTextSharp.text.Font(bfBold, 13);
                    iTextSharp.text.Font         fontColHeader  = new iTextSharp.text.Font(bfBold, 11);
                    iTextSharp.text.Font         fontTable      = new iTextSharp.text.Font(bfNormal, 10);
                    iTextSharp.text.Font         fontConclusion = new iTextSharp.text.Font(bfNormal, 10);
                    fontConclusion.SetStyle(iTextSharp.text.Font.UNDERLINE);

                    // HEADER AND FOOTER
                    TwoColumnHeaderFooter PageEventHandler = new TwoColumnHeaderFooter(mainForm.getCurrentUser().userName);
                    pdfWriter.PageEvent          = PageEventHandler;
                    PageEventHandler.Title       = "AHP RESULT";
                    PageEventHandler.HeaderFont  = FontFactory.GetFont(BaseFont.COURIER_BOLD, 10, iTextSharp.text.Font.BOLD);
                    PageEventHandler.HeaderLeft  = "Topic";
                    PageEventHandler.HeaderRight = mainForm.getCurrentTopic().topicName.ToUpper();

                    doc.Open();

                    // TITLE
                    //Paragraph title = new Paragraph(mainForm.getCurrentTopic().topicName.ToUpper(), fontTitle);
                    //title.Alignment = Element.ALIGN_CENTER;
                    //doc.Add(title);

                    doc.Add(new Paragraph(" "));
                    // SUBTITLE: DETAIL ALTERNATIVE
                    Paragraph subtitle1 = new Paragraph("DETAIL ALTERNATIVE", fontSubtitle);
                    subtitle1.Alignment     = Element.ALIGN_CENTER;
                    subtitle1.SpacingBefore = 25;
                    subtitle1.SpacingAfter  = 20;
                    doc.Add(subtitle1);

                    // TABLE DETAIL
                    bool switchCloseAlternativeListForm     = true;
                    AlternativeListForm alternativeListForm = null;
                    if (mainForm.isFormOpened(typeof(AlternativeListForm)) != null)
                    {
                        switchCloseAlternativeListForm = false;
                        alternativeListForm            = (AlternativeListForm)mainForm.isFormOpened(typeof(AlternativeListForm));
                        alternativeListForm.MdiParent  = mainForm;
                        alternativeListForm.Show();
                    }
                    else
                    {
                        alternativeListForm = mainForm.getAlternativeListForm();
                    }

                    DataGridView dataGridView = alternativeListForm.getDGV();

                    PdfPTable pdfPTable = new PdfPTable(dataGridView.ColumnCount);
                    // Header Column
                    foreach (DataGridViewColumn column in dataGridView.Columns)
                    {
                        PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText, fontColHeader));
                        //cell.BackgroundColor = new iTextSharp.text.Color(240, 240, 240);
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.VerticalAlignment   = Element.ALIGN_MIDDLE;
                        pdfPTable.AddCell(cell);
                    }
                    // Adding DataRow
                    foreach (DataGridViewRow row in dataGridView.Rows)
                    {
                        foreach (DataGridViewCell cell in row.Cells)
                        {
                            PdfPCell pdfPCell = new PdfPCell(new Phrase(cell.Value.ToString(), fontTable));
                            pdfPCell.HorizontalAlignment = Element.ALIGN_CENTER;
                            pdfPCell.VerticalAlignment   = Element.ALIGN_MIDDLE;
                            pdfPTable.AddCell(pdfPCell);
                        }
                    }
                    doc.Add(pdfPTable);

                    mainForm.refreshAllChildrenForm();
                    if (switchCloseAlternativeListForm)
                    {
                        alternativeListForm.Close();
                    }

                    // SUBTITLE: COMPARISON
                    Paragraph subtitle2 = new Paragraph("COMPARISON", fontSubtitle);
                    subtitle2.Alignment     = Element.ALIGN_CENTER;
                    subtitle2.SpacingBefore = 25;
                    doc.Add(subtitle2);

                    // CHART IMAGE
                    MemoryStream ms = new MemoryStream();
                    chart1.SaveImage(ms, ChartImageFormat.Png);
                    iTextSharp.text.Image chart_img = iTextSharp.text.Image.GetInstance(ms.ToArray());
                    chart_img.SetDpi(300, 300);
                    chart_img.ScaleToFit(300f, 300f);
                    chart_img.Alignment = Element.ALIGN_CENTER;
                    doc.Add(chart_img);

                    // SUBTITLE: CONCLUSION
                    Paragraph subtitle3 = new Paragraph("CONCLUSION", fontSubtitle);
                    subtitle3.Alignment     = Element.ALIGN_CENTER;
                    subtitle3.SpacingBefore = 25;
                    doc.Add(subtitle3);

                    // CONCLUSION
                    List <List <string> > conclusion = resultController.conclusionBestWorst(currentTopicId);

                    if (conclusion == null)
                    {
                        doc.Add(new Paragraph("Cannot conclude anything, since the data is all the same.", fontTable));
                    }
                    else
                    {
                        // SUB SUBTITLE BEST ALTERNATIVE
                        Paragraph subtitleBest = new Paragraph("Best Alternative(s)", fontConclusion);
                        subtitleBest.SpacingBefore = 10;
                        subtitleBest.SpacingAfter  = 5;
                        subtitleBest.Alignment     = Element.ALIGN_CENTER;
                        doc.Add(subtitleBest);

                        int numbering = 1;
                        foreach (List <string> conc in conclusion)
                        {
                            if (conc[0] == "Best")
                            {
                                string oneLine = /*numbering + ". " +*/ conc[1] + " (Best criteria: ";
                                foreach (string crit in resultController.bestWorstCriteria(currentTopicId, conc))
                                {
                                    oneLine += crit + ", ";
                                }

                                Paragraph text = new Paragraph(oneLine.Substring(0, oneLine.Length - 2) + ")\n", fontTable);
                                text.Alignment = Element.ALIGN_CENTER;
                                doc.Add(text);
                                numbering++;
                            }
                        }

                        // SUB SUBTITLE WORST ALTERNATIVE
                        Paragraph subtitleWorst = new Paragraph("Worst Alternative(s)", fontConclusion);
                        subtitleWorst.SpacingBefore = 10;
                        subtitleWorst.SpacingAfter  = 5;
                        subtitleWorst.Alignment     = Element.ALIGN_CENTER;
                        doc.Add(subtitleWorst);

                        numbering = 1;
                        foreach (List <string> conc in conclusion)
                        {
                            if (conc[0] == "Worst")
                            {
                                string oneLine = /*numbering + ". " +*/ conc[1] + " (Worst criteria: ";
                                foreach (string crit in resultController.bestWorstCriteria(currentTopicId, conc))
                                {
                                    oneLine += crit + ", ";
                                }

                                Paragraph text = new Paragraph(oneLine.Substring(0, oneLine.Length - 2) + ")\n", fontTable);
                                text.Alignment = Element.ALIGN_CENTER;
                                doc.Add(text);
                                numbering++;
                            }
                        }
                    }

                    doc.Close();

                    // DIALOG
                    int start  = saveFileDialog1.FileName.LastIndexOf('\\') + 1;
                    int length = saveFileDialog1.FileName.Length;

                    var mboxResponse = MessageBox.Show(this, "Successfully exported \"" + saveFileDialog1.FileName.Substring(start, length - start) + "\" to\n" + saveFileDialog1.FileName.Substring(0, start) + "\nDo you want to open the file?", "Export to PDF", MessageBoxButtons.YesNo, MessageBoxIcon.Information);

                    if (mboxResponse == DialogResult.Yes)
                    {
                        System.Diagnostics.Process.Start(saveFileDialog1.FileName);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, "An error occured:\n" + ex.Message, "Export to PDF", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }
            }
        }
        private void button3_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count == 0)
            {
                MessageBox.Show("Search Data & Try Again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            else
            {
                var pgSize = new iTextSharp.text.Rectangle(594, 841);
                var doc    = new iTextSharp.text.Document(pgSize, 22, 22, 22, 22);

                PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(System.AppDomain.CurrentDomain.BaseDirectory.ToString() + "\\Documents\\Account Ledger " + textBoxQuery.Text + DateTime.Now.Date.ToString("ddMMyyyy") + ".pdf", FileMode.Create));



                MessageBox.Show("Your Document Is Ready To Be Printed. Press OK Button.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);

                doc.Open();

                iTextSharp.text.Image headerImage = iTextSharp.text.Image.GetInstance("logo.jpg");
                headerImage.ScalePercent(16f);
                headerImage.SetAbsolutePosition(doc.PageSize.Width - 390f - 22f, doc.PageSize.Height - 30f - 16f);
                //doc.Add(headerImage);

                iTextSharp.text.Font fontTitle = FontFactory.GetFont("Arial", 16, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

                Paragraph title = new Paragraph(shopName, fontTitle);

                title.Alignment = Element.ALIGN_CENTER;

                doc.Add(title);



                iTextSharp.text.Font fontAddress = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

                Paragraph address = new Paragraph(shopAddress, fontAddress);

                address.Alignment = Element.ALIGN_CENTER;

                doc.Add(address);

                iTextSharp.text.Font fontTable3 = FontFactory.GetFont("Times New Roman", 10, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);


                PdfPTable tableInfo = new PdfPTable(3);

                tableInfo.SpacingBefore   = 16f;
                tableInfo.WidthPercentage = 100;
                PdfPCell cell = new PdfPCell(new Phrase("Account Ledger"));

                cell.Colspan = 3;

                cell.HorizontalAlignment = 1;

                cell.BackgroundColor = BaseColor.LIGHT_GRAY;

                tableInfo.AddCell(cell);

                tableInfo.AddCell(new Phrase("Account Name: " + labelAccountName.Text, fontTable3));
                tableInfo.AddCell(new Phrase("Account No: " + labelAccountNumber.Text, fontTable3));
                tableInfo.AddCell(new Phrase("Contact Number: " + labelContactNumber.Text, fontTable3));

                tableInfo.AddCell(new Phrase("Credit Amount (+): " + labelTotalCredit.Text, fontTable3));
                tableInfo.AddCell(new Phrase("Debit Amount (-): " + labelTotalDebit.Text, fontTable3));
                tableInfo.AddCell(new Phrase("Current Balance: " + labelCurrentBalance.Text, fontTable3));

                tableInfo.AddCell(new Phrase("Search By: " + comboBoxSearchBy.Text, fontTable3));
                tableInfo.AddCell(new Phrase("Query: " + textBoxQuery.Text, fontTable3));
                tableInfo.AddCell(new Phrase("Date Period: " + dateTimePicker1.Value.ToString("dd/MM/yyyy") + "-" + dateTimePicker2.Value.ToString("dd/MM/yyyy"), fontTable3));

                tableInfo.AddCell(new Phrase("Number Of Transaction: " + labelTotalTrxn.Text, fontTable3));
                tableInfo.AddCell(new Phrase("Time & Date: " + DateTime.Now.ToString("hh:mm:ss tt") + " " + DateTime.Now.ToString("dd/MM/yyyy"), fontTable3));
                tableInfo.AddCell(new Phrase("Printed By: " + realName, fontTable3));



                doc.Add(tableInfo);



                iTextSharp.text.Font fontTable = FontFactory.GetFont("Arial", 11, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

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

                table.SpacingBefore       = 6f;
                table.WidthPercentage     = 100;
                table.HorizontalAlignment = Element.ALIGN_CENTER;
                table.SetWidths(new float[] { 3f, 4f, 6f, 3f, 3f, 3f });

                for (int j = 1; j < dataGridView1.Columns.Count; j++)
                {
                    table.AddCell(new Phrase(dataGridView1.Columns[j].HeaderText, fontTable));
                }

                table.HeaderRows = 1;

                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                    for (int k = 1; k < dataGridView1.Columns.Count; k++)
                    {
                        if (dataGridView1[k, i].Value != null)
                        {
                            if (k == 4 || k == 5 || k == 6)
                            {
                                PdfPCell CellEight = new PdfPCell(new Phrase(dataGridView1[k, i].Value.ToString(), fontTable3));

                                //CellEight.Border = iTextSharp.text.Rectangle.NO_BORDER;
                                CellEight.HorizontalAlignment = Element.ALIGN_RIGHT;
                                //CellEight.BackgroundColor = BaseColor.LIGHT_GRAY;
                                table.AddCell(CellEight);
                            }

                            else
                            {
                                PdfPCell CellEight = new PdfPCell(new Phrase(dataGridView1[k, i].Value.ToString(), fontTable3));

                                // CellEight.Border = iTextSharp.text.Rectangle.NO_BORDER;
                                CellEight.HorizontalAlignment = Element.ALIGN_LEFT;
                                //CellEight.BackgroundColor = BaseColor.LIGHT_GRAY;
                                table.AddCell(CellEight);
                            }
                        }
                    }
                }

                doc.Add(table);


                PdfPTable tableTotal = new PdfPTable(4);

                //tableTotal.SpacingBefore = 10f;
                tableTotal.WidthPercentage = 100;
                tableTotal.SetWidths(new float[] { 13f, 3f, 3f, 3f });

                PdfPCell CellNine111 = new PdfPCell(new Phrase("Total", fontTable));
                //CellNine111.Colspan = 6;
                //CellNine111.Border = iTextSharp.text.Rectangle.TOP_BORDER;
                CellNine111.HorizontalAlignment = Element.ALIGN_RIGHT;
                tableTotal.AddCell(CellNine111);


                PdfPCell CellNine222 = new PdfPCell(new Phrase(labelTotalCredit.Text, fontTable));
                //CellNine222.Colspan = 7;
                //CellNine222.Border = iTextSharp.text.Rectangle.TOP_BORDER;
                CellNine222.HorizontalAlignment = Element.ALIGN_RIGHT;
                tableTotal.AddCell(CellNine222);

                PdfPCell CellNine333 = new PdfPCell(new Phrase(labelTotalDebit.Text, fontTable));
                //CellNine333.Colspan = 6;
                //CellNine333.Border = iTextSharp.text.Rectangle.NO_BORDER;
                CellNine333.HorizontalAlignment = Element.ALIGN_RIGHT;
                tableTotal.AddCell(CellNine333);


                PdfPCell CellNine444 = new PdfPCell(new Phrase(labelCurrentBalance.Text, fontTable));
                //CellNine444.Colspan = 7;
                //CellNine444.Border = iTextSharp.text.Rectangle.NO_BORDER;
                CellNine444.HorizontalAlignment = Element.ALIGN_RIGHT;
                tableTotal.AddCell(CellNine444);

                doc.Add(tableTotal);

                iTextSharp.text.Font footerFont = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
                Paragraph            footer     = new Paragraph("", footerFont);
                footer.SpacingBefore = 20f;
                footer.Alignment     = Element.ALIGN_RIGHT;
                doc.Add(footer);


                doc.Close();



                System.Diagnostics.Process.Start(System.AppDomain.CurrentDomain.BaseDirectory.ToString() + "\\Documents\\Account Ledger " + textBoxQuery.Text + DateTime.Now.Date.ToString("ddMMyyyy") + ".pdf");
            }
        }
Exemplo n.º 18
0
        public static void CreateDeclaracionJurada(string filePDF,
                                                   PacientList datosPac,
                                                   organizationDto infoEmpresaPropietaria, PacientList filiationData,
                                                   List <ServiceComponentList> serviceComponent)
        {
            Document document = new Document(PageSize.A4, 40f, 40f, 40f, 50f);


            document.SetPageSize(iTextSharp.text.PageSize.A4);

            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(filePDF, FileMode.Create));
            pdfPage   page   = new pdfPage();

            writer.PageEvent = page;
            document.Open();

            #region Declaration Tables
            var             subTitleBackGroundColor = new BaseColor(System.Drawing.Color.Gray);
            string          include      = string.Empty;
            List <PdfPCell> cells        = null;
            float[]         columnWidths = null;
            PdfPTable       header2      = new PdfPTable(6);
            header2.HorizontalAlignment = Element.ALIGN_CENTER;
            header2.WidthPercentage     = 100;
            float[] widths1 = new float[] { 16.6f, 18.6f, 16.6f, 16.6f, 16.6f, 16.6f };
            header2.SetWidths(widths1);
            PdfPTable companyData = new PdfPTable(6);
            companyData.HorizontalAlignment = Element.ALIGN_CENTER;
            companyData.WidthPercentage     = 100;
            float[] widthscolumnsCompanyData = new float[] { 16.6f, 16.6f, 16.6f, 16.6f, 16.6f, 16.6f };
            companyData.SetWidths(widthscolumnsCompanyData);
            PdfPTable filiationWorker = new PdfPTable(4);
            PdfPTable table           = null;
            document.Add(new Paragraph("\r\n"));
            #endregion

            #region Fonts
            Font fontTitle1               = FontFactory.GetFont("Calibri", 13, iTextSharp.text.Font.BOLD, new BaseColor(System.Drawing.Color.Black));
            Font fontTitle2               = FontFactory.GetFont("Calibri", 7, iTextSharp.text.Font.NORMAL, new BaseColor(System.Drawing.Color.Black));
            Font fontTitleTable           = FontFactory.GetFont("Calibri", 6, iTextSharp.text.Font.BOLD, new BaseColor(System.Drawing.Color.Black));
            Font fontTitleTableNegro      = FontFactory.GetFont("Calibri", 6, iTextSharp.text.Font.BOLD, new BaseColor(System.Drawing.Color.Black));
            Font fontSubTitle             = FontFactory.GetFont("Calibri", 6, iTextSharp.text.Font.BOLD, new BaseColor(System.Drawing.Color.White));
            Font fontSubTitleNegroNegrita = FontFactory.GetFont("Calibri", 6, iTextSharp.text.Font.BOLD, new BaseColor(System.Drawing.Color.Black));

            Font fontColumnValue         = FontFactory.GetFont("Calibri", 10, iTextSharp.text.Font.NORMAL, new BaseColor(System.Drawing.Color.Black));
            Font fontColumnValueBold     = FontFactory.GetFont("Calibri", 7, iTextSharp.text.Font.BOLD, new BaseColor(System.Drawing.Color.Black));
            Font fontColumnValueApendice = FontFactory.GetFont("Calibri", 5, iTextSharp.text.Font.BOLD, new BaseColor(System.Drawing.Color.Black));
            #endregion

            #region TÍTULO

            cells = new List <PdfPCell>();

            if (infoEmpresaPropietaria.b_Image != null)
            {
                iTextSharp.text.Image imagenEmpresa = iTextSharp.text.Image.GetInstance(HandlingItextSharp.GetImage(infoEmpresaPropietaria.b_Image));
                imagenEmpresa.ScalePercent(25);
                imagenEmpresa.SetAbsolutePosition(40, 790);
                document.Add(imagenEmpresa);
            }
            //iTextSharp.text.Image imagenMinsa = iTextSharp.text.Image.GetInstance("C:/Banner/Minsa.png");
            //imagenMinsa.ScalePercent(10);
            //imagenMinsa.SetAbsolutePosition(400, 785);
            //document.Add(imagenMinsa);


            var cellsTit = new List <PdfPCell>()
            {
                new PdfPCell(new Phrase("DECLARACION JURADA", fontTitle1))
                {
                    Colspan = 3, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 30f, UseVariableBorders = true, BorderColorLeft = BaseColor.WHITE, BorderColorRight = BaseColor.WHITE, BorderColorBottom = BaseColor.WHITE, BorderColorTop = BaseColor.WHITE
                },
            };
            columnWidths = new float[] { 20f, 60f, 20f };
            table        = HandlingItextSharp.GenerateTableFromCells(cellsTit, columnWidths, null, fontTitleTable);
            document.Add(table);
            #endregion
            var    tamaño_celda = 25f;
            string tipodoc      = "";
            if (datosPac.i_DocTypeId == 1)
            {
                tipodoc = "DNI";
            }
            else if (datosPac.i_DocTypeId == 2)
            {
                tipodoc = "Pasaporte";
            }
            else if (datosPac.i_DocTypeId == 3)
            {
                tipodoc = "Licencia de Conducir";
            }
            else if (datosPac.i_DocTypeId == 4)
            {
                tipodoc = "Carnet de Extranjeria";
            }

            #region Contenido
            cells = new List <PdfPCell>()
            {
                new PdfPCell(new Phrase("\n \n", fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.WHITE, BorderColorRight = BaseColor.WHITE, BorderColorBottom = BaseColor.WHITE, BorderColorTop = BaseColor.WHITE
                },
                new PdfPCell(new Phrase("\n \n YO, ", fontColumnValue))
                {
                    Colspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.WHITE, BorderColorRight = BaseColor.WHITE, BorderColorBottom = BaseColor.WHITE, BorderColorTop = BaseColor.WHITE
                },
                new PdfPCell(new Phrase("\n \n" + datosPac.v_FirstLastName + " " + datosPac.v_SecondLastName + " " + datosPac.v_FirstName, fontColumnValue))
                {
                    Colspan = 16, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.WHITE, BorderColorRight = BaseColor.WHITE, BorderColorBottom = BaseColor.BLACK, BorderColorTop = BaseColor.WHITE
                },
                new PdfPCell(new Phrase("\n \n", fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.WHITE, BorderColorRight = BaseColor.WHITE, BorderColorBottom = BaseColor.WHITE, BorderColorTop = BaseColor.WHITE
                },

                new PdfPCell(new Phrase("\n", fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.WHITE, BorderColorRight = BaseColor.WHITE, BorderColorBottom = BaseColor.WHITE, BorderColorTop = BaseColor.WHITE
                },
                new PdfPCell(new Phrase("\nIdentificado (a) con " + tipodoc + " N°  ", fontColumnValue))
                {
                    Colspan = 6, HorizontalAlignment = iTextSharp.text.Element.ALIGN_JUSTIFIED_ALL, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, BorderColor = BaseColor.WHITE, UseVariableBorders = true, BorderColorLeft = BaseColor.WHITE, BorderColorRight = BaseColor.WHITE, BorderColorBottom = BaseColor.WHITE, BorderColorTop = BaseColor.WHITE
                },
                new PdfPCell(new Phrase("\n" + datosPac.v_DocNumber, fontColumnValue))
                {
                    Colspan = 4, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, BorderColor = BaseColor.WHITE, UseVariableBorders = true, BorderColorLeft = BaseColor.WHITE, BorderColorRight = BaseColor.WHITE, BorderColorBottom = BaseColor.BLACK, BorderColorTop = BaseColor.WHITE
                },
                new PdfPCell(new Phrase("\ndeclaro por medio de este documento", fontColumnValue))
                {
                    Colspan = 8, HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, BorderColor = BaseColor.WHITE, UseVariableBorders = true, BorderColorLeft = BaseColor.WHITE, BorderColorRight = BaseColor.WHITE, BorderColorBottom = BaseColor.WHITE, BorderColorTop = BaseColor.WHITE
                },
                new PdfPCell(new Phrase("\n", fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.WHITE, BorderColorRight = BaseColor.WHITE, BorderColorBottom = BaseColor.WHITE, BorderColorTop = BaseColor.WHITE
                },

                new PdfPCell(new Phrase("\n", fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.WHITE, BorderColorRight = BaseColor.WHITE, BorderColorBottom = BaseColor.WHITE, BorderColorTop = BaseColor.WHITE
                },
                new PdfPCell(new Phrase("\nmédico legal que me encuentro en buen estado de salud física y mental y que toda la", fontColumnValue))
                {
                    Colspan = 18, HorizontalAlignment = iTextSharp.text.Element.ALIGN_JUSTIFIED_ALL, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, BorderColor = BaseColor.WHITE, UseVariableBorders = true, BorderColorLeft = BaseColor.WHITE, BorderColorRight = BaseColor.WHITE, BorderColorBottom = BaseColor.WHITE, BorderColorTop = BaseColor.WHITE
                },
                new PdfPCell(new Phrase("\n", fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.WHITE, BorderColorRight = BaseColor.WHITE, BorderColorBottom = BaseColor.WHITE, BorderColorTop = BaseColor.WHITE
                },

                new PdfPCell(new Phrase("\n", fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.WHITE, BorderColorRight = BaseColor.WHITE, BorderColorBottom = BaseColor.WHITE, BorderColorTop = BaseColor.WHITE
                },
                new PdfPCell(new Phrase("\ninformación proporcionada al médico o funcionario responsable es de carácter verídico,", fontColumnValue))
                {
                    Colspan = 18, HorizontalAlignment = iTextSharp.text.Element.ALIGN_JUSTIFIED_ALL, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, BorderColor = BaseColor.WHITE, UseVariableBorders = true, BorderColorLeft = BaseColor.WHITE, BorderColorRight = BaseColor.WHITE, BorderColorBottom = BaseColor.WHITE, BorderColorTop = BaseColor.WHITE
                },
                new PdfPCell(new Phrase("\n", fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.WHITE, BorderColorRight = BaseColor.WHITE, BorderColorBottom = BaseColor.WHITE, BorderColorTop = BaseColor.WHITE
                },

                new PdfPCell(new Phrase("\n ", fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.WHITE, BorderColorRight = BaseColor.WHITE, BorderColorBottom = BaseColor.WHITE, BorderColorTop = BaseColor.WHITE
                },
                new PdfPCell(new Phrase("\npara el cargo correspondiente.", fontColumnValue))
                {
                    Colspan = 18, HorizontalAlignment = iTextSharp.text.Element.ALIGN_JUSTIFIED, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, BorderColor = BaseColor.WHITE, UseVariableBorders = true, BorderColorLeft = BaseColor.WHITE, BorderColorRight = BaseColor.WHITE, BorderColorBottom = BaseColor.WHITE, BorderColorTop = BaseColor.WHITE
                },
                new PdfPCell(new Phrase("\n", fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.WHITE, BorderColorRight = BaseColor.WHITE, BorderColorBottom = BaseColor.WHITE, BorderColorTop = BaseColor.WHITE
                },
            };

            columnWidths = new float[] { 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f };
            table        = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, null, fontTitleTable);
            document.Add(table);
            #endregion

            string[] fechaServicio = datosPac.FechaServicio.ToString().Split('/', ' ');
            string   mes           = "";
            if (fechaServicio[1] == "01")
            {
                mes = "Enero";
            }
            else if (fechaServicio[1] == "02")
            {
                mes = "Febrero";
            }
            else if (fechaServicio[1] == "03")
            {
                mes = "Marzo";
            }
            else if (fechaServicio[1] == "04")
            {
                mes = "Abril";
            }
            else if (fechaServicio[1] == "05")
            {
                mes = "Mayo";
            }
            else if (fechaServicio[1] == "06")
            {
                mes = "Junio";
            }
            else if (fechaServicio[1] == "07")
            {
                mes = "Julio";
            }
            else if (fechaServicio[1] == "08")
            {
                mes = "Agosto";
            }
            else if (fechaServicio[1] == "09")
            {
                mes = "Setiembre";
            }
            else if (fechaServicio[1] == "10")
            {
                mes = "Octubre";
            }
            else if (fechaServicio[1] == "11")
            {
                mes = "Noviembre";
            }
            else if (fechaServicio[1] == "12")
            {
                mes = "Diciembre";
            }

            PdfPCell cellFirmaTrabajador = null;

            PdfPCell cellHuellaTrabajador = null;

            if (filiationData.FirmaTrabajador != null)
            {
                cellFirmaTrabajador = new PdfPCell(HandlingItextSharp.GetImage(filiationData.FirmaTrabajador, null, null, 100, 35));
            }
            else
            {
                cellFirmaTrabajador = new PdfPCell(new Phrase(" ", fontColumnValue));
            }

            cellFirmaTrabajador.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
            cellFirmaTrabajador.VerticalAlignment   = PdfPCell.ALIGN_MIDDLE;

            if (filiationData.HuellaTrabajador != null)
            {
                cellHuellaTrabajador = new PdfPCell(HandlingItextSharp.GetImage(filiationData.HuellaTrabajador, null, null, 60, 80));
            }
            else
            {
                cellHuellaTrabajador = new PdfPCell(new Phrase(" ", fontColumnValue));
            }

            cellHuellaTrabajador.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
            cellHuellaTrabajador.VerticalAlignment   = PdfPCell.ALIGN_MIDDLE;

            #region Fecha / Firmma
            cells = new List <PdfPCell>()
            {
                new PdfPCell(new Phrase("\n \n \n \n" + infoEmpresaPropietaria.v_SectorName + ", " + fechaServicio[0] + " de " + mes + " del " + fechaServicio[2], fontColumnValue))
                {
                    Colspan = 19, HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, BorderColor = BaseColor.WHITE
                },
                new PdfPCell(new Phrase("\n", fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.WHITE, BorderColorRight = BaseColor.WHITE, BorderColorBottom = BaseColor.WHITE, BorderColorTop = BaseColor.WHITE
                },

                new PdfPCell(cellFirmaTrabajador)
                {
                    Colspan = 10, HorizontalAlignment = iTextSharp.text.Element.ALIGN_RIGHT, VerticalAlignment = iTextSharp.text.Element.ALIGN_BOTTOM, FixedHeight = 180, BorderColor = BaseColor.WHITE
                },
                new PdfPCell(cellHuellaTrabajador)
                {
                    Colspan = 10, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_BOTTOM, FixedHeight = 180, BorderColor = BaseColor.WHITE
                },
                new PdfPCell(new Phrase("_____________________________________", fontColumnValue))
                {
                    Colspan = 20, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda, BorderColor = BaseColor.WHITE
                },
                new PdfPCell(new Phrase("       Firma y Post Firma        ", fontColumnValue))
                {
                    Colspan = 20, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda, BorderColor = BaseColor.WHITE
                },

                new PdfPCell(new Phrase("N° de " + tipodoc + ": " + datosPac.v_DocNumber, fontColumnValue))
                {
                    Colspan = 20, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda, BorderColor = BaseColor.WHITE
                },
            };

            columnWidths = new float[] { 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f };
            table        = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, null, fontTitleTable);
            document.Add(table);
            #endregion
            document.Close();
            writer.Close();
            writer.Dispose();
        }
Exemplo n.º 19
0
    private void PrintChart()
    {
        ds = GetTeamName(Convert.ToInt32(Session["team"]));

        if (ds.Tables["Team"].Rows.Count > 0)
        {
            TeamName = ds.Tables["Team"].Rows[0]["T_TeamName"].ToString();
        }

        BindPieChart1();

        Document pdfDoc = new Document(PageSize.A3, 10f, 10f, 10f, 0f);

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

        using (MemoryStream stream = new MemoryStream())
        {
            //iTextSharp.text.Image gif = iTextSharp.text.Image.GetInstance(imagePath);

            //gif.ScalePercent(24f);
            //gif.Alignment = iTextSharp.text.Image.ALIGN_RIGHT;

            Chart1.SaveImage(stream, ChartImageFormat.Png);
            iTextSharp.text.Image chartImage = iTextSharp.text.Image.GetInstance(stream.GetBuffer());
            chartImage.ScalePercent(75f);
            //pdfDoc.Add(gif);
            pdfDoc.Add(chartImage);
        }

        pdfDoc.Close();
        Response.ContentType = "application/pdf";
        if (type == "TeamClientsUsage")
        {
            Response.AddHeader("content-disposition", "attachment;" +
                               "filename=RTM Client Usage - " + TeamName + ".pdf");
        }
        else if (type == "Tasks")
        {
            Response.AddHeader("content-disposition", "attachment;" +
                               "filename=RTM Task Usage - " + TeamName + ".pdf");
        }

        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Write(pdfDoc);
        Response.End();

        //Response.ContentType = "application/pdf";


        //Response.AddHeader("content-disposition", "inline;filename=TestPage.pdf");


        ////Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf");

        //Response.Cache.SetCacheability(HttpCacheability.NoCache);
        //StringWriter sw = new StringWriter();
        //HtmlTextWriter hw = new HtmlTextWriter(sw);
        //this.Page.RenderControl(hw);
        //StringReader sr = new StringReader(sw.ToString());
        //Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
        //HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        //PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        //pdfDoc.Open();
        ////htmlparser.Parse(sr);
        //pdfDoc.Close();
        //Response.Write(pdfDoc);
        //Response.End();
    }
Exemplo n.º 20
0
        private void button1_Click(object sender, EventArgs e)
        {
            label2.Text = "Generando archivos pdf. Por favor espere!";
            String     filepath = label1.Text;
            FileStream stream   = null;

            try
            {
                stream = File.Open(filepath, FileMode.Open, FileAccess.Read);
            }
            catch
            {
                MessageBox.Show("Por favor cierre el Archivo Excel ingresado y vuelva a intentar", "Mensaje de error");
                Application.Exit();
            }
            IExcelDataReader excelReader;

            if (Path.GetExtension(filepath) == ".xls")
            {
                //excel xls
                excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
            }
            else
            {
                //excel xlsx
                excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
            }
            //DataSet result = excelReader;
            var       result = excelReader.AsDataSet();
            DataTable table  = result.Tables[0];
            DataRow   row    = table.Rows[0];
            //String cell = row[0].ToString();
            String cell   = result.Tables[0].Rows.Count.ToString();
            String valor1 = table.Rows[1][1].ToString();

            //label2.Text = cell;

            //fuentes
            iTextSharp.text.pdf.BaseFont bf        = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.COURIER, iTextSharp.text.pdf.BaseFont.CP1252, iTextSharp.text.pdf.BaseFont.EMBEDDED);
            iTextSharp.text.Font         font      = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 11, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
            iTextSharp.text.Font         fontBlack = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 11, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
            //end fuentes

            String pathOrigin = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            String folder     = "pdfs_" + DateTime.Now.ToString("dd-MM-yyyy_HH-mm-ss");
            String pathString = System.IO.Path.Combine(pathOrigin, folder);

            System.IO.Directory.CreateDirectory(pathString);
            for (int i = 1; i < table.Rows.Count; i++)
            {
                //System.Console.WriteLine(table.Rows[i][4].ToString());
                //String valorRow0 = result.Tables[0].Rows[i][1].ToString();// fila 1 columna1
                //Paragraph c = new Paragraph(valorRow0, font);
                //doc.Add(c);
                String dni = table.Rows[i][4].ToString(); // cuil

                //verifico si existe el archivo
                //String pathFile1 = pathString + "/" + dni + ".pdf";
                //String pathFile = File.Exists(pathFile1) ? pathString + "/" + dni + "_" + i + ".pdf" : pathFile1  ;
                Document doc          = new Document(PageSize.A4, 90f, 50f, 140f, 0f);
                int      dniRepetidos = 0;
                bool     repetido     = true;
                while (repetido)
                {
                    if (File.Exists(pathString + "/" + dni + ".pdf"))
                    {
                        dniRepetidos = dniRepetidos + 1;
                        if (File.Exists(pathString + "/" + dni + "_" + dniRepetidos + ".pdf"))
                        {
                        }
                        else
                        {
                            repetido = false;
                            PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(pathString + "/" + dni + "_" + dniRepetidos + ".pdf", FileMode.Create));
                        }
                    }
                    else
                    {
                        repetido = false;

                        PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(pathString + "/" + dni + ".pdf", FileMode.Create));
                    }
                }


                doc.Open();

                //Image image = Image.GetInstance("c:/users/franco/desktop/01.jpg");
                Image image   = Image.GetInstance(@"01.jpg");
                Image image02 = Image.GetInstance(@"02.jpg");
                //image.ScalePercent(18f);
                image.ScaleToFit(150f, 110f);
                image02.ScaleToFit(50f, 30f);
                image.SetAbsolutePosition(90, 770);
                image02.SetAbsolutePosition(480, 770);
                //image.ScaleAbsoluteHeight(50);
                //image.ScaleAbsoluteWidth(100);
                doc.Add(image);
                doc.Add(image02);

                //header
                String    anio        = DateTime.Today.ToString("yyyy");                                                                 //2020
                String    nombreDia   = DateTime.Today.ToString("dddd");                                                                 //martes
                String    numeroDia   = DateTime.Today.ToString("dd");                                                                   //22
                String    mes         = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Now.Month); //abril
                String    fechaActual = numeroDia + " de " + mes + " del " + anio;
                Paragraph p           = new Paragraph("SAN MIGUEL DE TUCUMÁN, " + fechaActual, fontBlack);
                p.Alignment = Element.ALIGN_CENTER;
                doc.Add(p);
                doc.Add(Chunk.NEWLINE);
                Paragraph p2 = new Paragraph("CONSTANCIA RG (DGR) N° 44/20", fontBlack);
                p2.Alignment = Element.ALIGN_CENTER;
                doc.Add(p2);
                doc.Add(Chunk.NEWLINE);
                doc.Add(Chunk.NEWLINE);
                //end header

                //String f = "                Conforme lo dispuesto por el 2° párrafo del artículo 282 del Código Tributario Provincial, se deja constancia que el contribuyente identificado con la CUIT/CUIL:  ";
                //Paragraph texto = new Paragraph(f, font);
                //texto.Alignment = (int)HorizontalAlignment.Left;

                //doc.Add(texto);

                //Paragraph razonsocial = new Paragraph(" CECILIA", fontBlack);
                dni = dni + ", ";
                String razon_social = table.Rows[i][5].ToString();

                if (razon_social == "")
                {
                }
                else
                {
                    razon_social = razon_social + " ";
                }

                //Paragraph dni1 = new Paragraph(dni + razon_social, fontBlack);
                //doc.Add(dni1);

                //clase para convertir numeros a letras
                convertirNumerosALetras convertir = new convertirNumerosALetras();
                //
                String obligacion = table.Rows[i][3].ToString();
                //String fechaHoy = DateTime.Today.ToString("dd-MM-yyyy") + ", ";

                DateTime fechaDeOtorgamiento = Convert.ToDateTime(table.Rows[i][16].ToString());
                //fechaDeOtorgamiento = fechaDeOtorgamiento.AddDays(-15);


                String texto3 = obligacion + " por el instrumento otorgado en fecha " + fechaDeOtorgamiento.ToString("dd/MM/yyyy") + ", ";
                //String nombrePrecio = " (pesos ________________________).-";
                String precioNro    = table.Rows[i][10].ToString(); // TOTAL
                String nombrePrecio = " (pesos " + convertir.convertir(float.Parse(precioNro)) + ").-";

                String    precio = precioNro + nombrePrecio;
                String    texto4 = texto3 + "que fue presentado en copia ante la DIRECCIÓN GENERAL DE RENTAS, emitiéndose a los fines del pago del Impuesto de Sellos el formulario 600 (F.600), por un importe total de $ " + precio;
                String    texto1 = "Conforme lo dispuesto por el 2° párrafo del artículo 282 del Código Tributario Provincial, se deja constancia que el contribuyente identificado con la CUIT/CUIL: " + dni + razon_social + "presentó ante este Organismo Declaración Jurada del Impuesto de Sellos – F.950, Obligación N° " + texto4;
                Paragraph texto2 = new Paragraph();
                texto2.TabSettings = new TabSettings(100f);
                texto2.Add(Chunk.TABBING);
                texto2.Font = font;
                texto2.Add(texto1);
                texto2.Alignment = Element.ALIGN_JUSTIFIED;
                doc.Add(texto2);

                string    textoAgregado = "EL INSTRUMENTO AL QUE SE REFIERE LA PRESENTE CONSTANCIA SE CONSIDERARÁ HABILITADO CON EL IMPUESTO DE SELLOS SIEMPRE QUE SE ENCUENTRE ACOMPAÑADO POR LA RESPECTIVA DECLARACIÓN JURADA - F950 Y EL COMPROBANTE DE PAGO O INSTRUMENTO DE CANCELACIÓN CORRESPONDIENTE.";
                Paragraph parrafoUltimo = new Paragraph();
                parrafoUltimo.TabSettings = new TabSettings(100f);
                parrafoUltimo.Add(Chunk.TABBING);
                parrafoUltimo.Font = font;
                parrafoUltimo.Add(textoAgregado);
                parrafoUltimo.Alignment = Element.ALIGN_JUSTIFIED;
                doc.Add(parrafoUltimo);

                doc.Close();
            }//end for

            MessageBox.Show("PDFs creados en\n" + pathString);
            Close();
            Application.Exit();
        }
Exemplo n.º 21
0
        private string CreatePDF(User student, Dictionary <Test, double> tests, Dictionary <Task, double> tasks, double percent, string review, List <Activity> activities)
        {
            var      document = new Document(PageSize.A4, 15, 15, 20, 15);
            string   filename = System.Guid.NewGuid().ToString() + ".pdf";
            string   path     = System.Web.HttpContext.Current.Server.MapPath("~/Content/Uploads/") + filename;
            BaseFont font     = BaseFont.CreateFont(System.Web.HttpContext.Current.Server.MapPath("~/fonts/times-new-roman.ttf"),
                                                    BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            var fontBase   = new iTextSharp.text.Font(font, 14, iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black));
            var fontHeader = new iTextSharp.text.Font(font, 14, iTextSharp.text.Font.BOLD, new BaseColor(Color.Black));


            PdfWriter.GetInstance(document, new FileStream(path, FileMode.Create));
            document.Open();
            #region Shape
            #region Emblem
            System.Drawing.Image  image  = System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Server.MapPath("~/Content/assets/emblem.png"));
            iTextSharp.text.Image emblem = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Png);
            emblem.Alignment = Element.ALIGN_CENTER;
            emblem.ScaleToFit(1000f, 60f);
            document.Add(emblem);
            #endregion
            document.Add(new Paragraph(new Phrase($"Отчет по практике с {student.Group.Start.ToShortDateString()} по {student.Group.End.ToShortDateString()}", fontBase))
            {
                Alignment = Element.ALIGN_CENTER
            });
            document.Add(new Paragraph(5, "\u00a0"));
            document.Add(new Paragraph(new Phrase($"Руководитель {student.CurrentCurator.User.Surname} " +
                                                  $"{student.CurrentCurator.User.Name} {student.CurrentCurator.User.Midname}", fontBase))
            {
                Alignment = Element.ALIGN_RIGHT,
            });
            document.Add(new Paragraph(new Phrase($"{student.CurrentCurator.User.Role.Value}", fontBase))
            {
                Alignment = Element.ALIGN_RIGHT,
            });
            document.Add(new Paragraph(new Phrase($"Студент {student.Surname} {student.Name} {student.Midname}",
                                                  fontBase))
            {
                Alignment = Element.ALIGN_RIGHT,
            });
            document.Add(new Paragraph(new Phrase($"группы {student.Group.Description}",
                                                  fontBase))
            {
                Alignment = Element.ALIGN_RIGHT,
            });
            #endregion
            PdfPTable table;
            #region Activities
            document.Add(new Paragraph(new Phrase($"Посещаемость", fontHeader))
            {
                Alignment = Element.ALIGN_CENTER
            });
            document.Add(new Paragraph(10, "\u00a0"));
            table = new PdfPTable(4)
            {
                WidthPercentage = 90,
            };
            table.DefaultCell.BorderWidth = 0;
            table.DefaultCell.HasBorder(iTextSharp.text.Rectangle.NO_BORDER);
            table.SetWidths(new float[] { 0.3f, 0.3f, 0.3f, 0.3f });

            #region HEADERS
            string[] headers = new string[]
            {
                "Дата", "Присутствие", "Дата", "Присутствие"
            };
            for (int i = 0; i < headers.Length; ++i)
            {
                table.AddCell(new PdfPCell(new Phrase(headers[i], fontHeader))
                {
                    HorizontalAlignment = Element.ALIGN_CENTER,
                    VerticalAlignment   = Element.ALIGN_MIDDLE
                });
            }
            #endregion

            if (activities.Count > 0)
            {
                int days = (student.Group.End - student.Group.Start).Days;
                for (int i = 0; i < days; i++)
                {
                    var day = student.Group.Start.AddDays(i);
                    table.AddCell(new PdfPCell(new Phrase($"{day.ToShortDateString()}", fontBase))
                    {
                        Padding             = 10,
                        HorizontalAlignment = Element.ALIGN_RIGHT,
                        VerticalAlignment   = Element.ALIGN_MIDDLE,
                        BorderColor         = BaseColor.BLACK,
                        BorderWidth         = 1
                    });
                    if (activities.FirstOrDefault(x => x.Date.Date.Equals(day.Date)) != null)
                    {
                        table.AddCell(new PdfPCell(new Phrase($"+", fontBase))
                        {
                            Padding             = 10,
                            HorizontalAlignment = Element.ALIGN_LEFT,
                            VerticalAlignment   = Element.ALIGN_MIDDLE,
                            BorderColor         = BaseColor.BLACK,
                            BorderWidth         = 1
                        });
                    }
                    else
                    {
                        table.AddCell(new PdfPCell(new Phrase($"-", fontBase))
                        {
                            Padding             = 10,
                            HorizontalAlignment = Element.ALIGN_LEFT,
                            VerticalAlignment   = Element.ALIGN_MIDDLE,
                            BorderColor         = BaseColor.BLACK,
                            BorderWidth         = 1
                        });
                    }
                }
            }
            document.Add(table);
            table = new PdfPTable(2)
            {
                WidthPercentage = 90,
            };
            table.DefaultCell.BorderWidth = 0;
            table.DefaultCell.HasBorder(iTextSharp.text.Rectangle.NO_BORDER);
            table.SetWidths(new float[] { 0.8f, 0.2f });
            PdfPCell cellActivity = new PdfPCell(new Phrase($"Посещаемость студента составила", fontHeader))
            {
                Padding             = 10,
                HorizontalAlignment = Element.ALIGN_RIGHT,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                BorderColor         = BaseColor.BLACK,
                BorderWidth         = 1
            };
            table.AddCell(cellActivity);
            PdfPCell cellActivityBase = new PdfPCell(new Phrase($"{(int)percent}%", fontBase))
            {
                Padding             = 10,
                HorizontalAlignment = Element.ALIGN_LEFT,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                BorderColor         = BaseColor.BLACK,
                BorderWidth         = 1
            };
            table.AddCell(cellActivityBase);
            document.Add(table);
            document.Add(new Paragraph(30, "\u00a0"));
            #endregion
            #region TESTS
            int coef = 5;
            document.Add(new Paragraph(new Phrase($"Успеваемость по тестам", fontHeader))
            {
                Alignment = Element.ALIGN_CENTER
            });
            document.Add(new Paragraph(10, "\u00a0"));
            table = new PdfPTable(2)
            {
                WidthPercentage = 90
            };
            table.DefaultCell.BorderWidth = 0;
            table.DefaultCell.HasBorder(iTextSharp.text.Rectangle.NO_BORDER);
            table.SetWidths(new float[] { 0.9f, 0.1f });
            #region HEADERS
            headers = new string[]
            {
                "Название теста", "Оценка"
            };
            for (int i = 0; i < headers.Length; ++i)
            {
                table.AddCell(new PdfPCell(new Phrase(headers[i], fontHeader))
                {
                    HorizontalAlignment = Element.ALIGN_CENTER,
                    VerticalAlignment   = Element.ALIGN_MIDDLE
                });
            }
            #endregion
            foreach (var item in tests)
            {
                table.AddCell(new PdfPCell(new Phrase($"{item.Key.Title}", fontBase))
                {
                    Padding             = 10,
                    HorizontalAlignment = Element.ALIGN_RIGHT,
                    VerticalAlignment   = Element.ALIGN_MIDDLE,
                    BorderColor         = BaseColor.BLACK,
                    BorderWidth         = 1
                });
                if (item.Value != 0)
                {
                    table.AddCell(new PdfPCell(new Phrase(string.Format("{0:0.#}", item.Value * coef), fontBase))
                    {
                        Padding             = 10,
                        HorizontalAlignment = Element.ALIGN_LEFT,
                        VerticalAlignment   = Element.ALIGN_MIDDLE,
                        BorderColor         = BaseColor.BLACK,
                        BorderWidth         = 1
                    });
                }
                else
                {
                    table.AddCell(new PdfPCell(new Phrase($"{item.Value}", fontBase))
                    {
                        Padding             = 10,
                        HorizontalAlignment = Element.ALIGN_LEFT,
                        VerticalAlignment   = Element.ALIGN_MIDDLE,
                        BorderColor         = BaseColor.BLACK,
                        BorderWidth         = 1
                    });
                }
            }
            PdfPCell cellGrade = new PdfPCell(new Phrase("Средняя оценка по тестированию составяет", fontHeader))
            {
                Padding             = 10,
                HorizontalAlignment = Element.ALIGN_RIGHT,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                BorderColor         = BaseColor.BLACK,
                BorderWidth         = 1
            };
            table.AddCell(cellGrade);
            double   gradeTestAVG  = tests.Sum(x => x.Value) / tests.Count();
            PdfPCell cellGradeBase = new PdfPCell(new Phrase(string.Format("{0:0.#}", gradeTestAVG * coef), fontBase))
            {
                Padding             = 10,
                HorizontalAlignment = Element.ALIGN_LEFT,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                BorderColor         = BaseColor.BLACK,
                BorderWidth         = 1
            };
            table.AddCell(cellGradeBase);
            document.Add(table);
            document.Add(new Paragraph(15, "\u00a0"));
            #endregion
            #region TASKS
            document.Add(new Paragraph(new Phrase($"Успеваемость по заданиям", fontHeader))
            {
                Alignment = Element.ALIGN_CENTER
            });
            document.Add(new Paragraph(10, "\u00a0"));
            table = new PdfPTable(2)
            {
                WidthPercentage = 90,
            };
            table.DefaultCell.BorderWidth = 0;
            table.DefaultCell.HasBorder(iTextSharp.text.Rectangle.NO_BORDER);
            table.SetWidths(new float[] { 0.9f, 0.1f });
            #region HEADERS
            headers = new string[]
            {
                "Название задания", "Оценка"
            };
            for (int i = 0; i < headers.Length; ++i)
            {
                table.AddCell(new PdfPCell(new Phrase(headers[i], fontHeader))
                {
                    HorizontalAlignment = Element.ALIGN_CENTER,
                    VerticalAlignment   = Element.ALIGN_MIDDLE
                });
            }
            #endregion
            foreach (var item in tasks)
            {
                table.AddCell(new PdfPCell(new Phrase($"{item.Key.Title}", fontBase))
                {
                    Padding             = 10,
                    HorizontalAlignment = Element.ALIGN_RIGHT,
                    VerticalAlignment   = Element.ALIGN_MIDDLE,
                    BorderColor         = BaseColor.BLACK,
                    BorderWidth         = 1
                });
                if (item.Value != 0)
                {
                    table.AddCell(new PdfPCell(new Phrase(string.Format("{0:0.#}", item.Value * coef), fontBase))
                    {
                        Padding             = 10,
                        HorizontalAlignment = Element.ALIGN_LEFT,
                        VerticalAlignment   = Element.ALIGN_MIDDLE,
                        BorderColor         = BaseColor.BLACK,
                        BorderWidth         = 1
                    });
                }
                else
                {
                    table.AddCell(new PdfPCell(new Phrase($"{item.Value}", fontBase))
                    {
                        Padding             = 10,
                        HorizontalAlignment = Element.ALIGN_LEFT,
                        VerticalAlignment   = Element.ALIGN_MIDDLE,
                        BorderColor         = BaseColor.BLACK,
                        BorderWidth         = 1
                    });
                }
            }
            PdfPCell cellGradeTask = new PdfPCell(new Phrase("Средняя оценка по заданиям составяет", fontHeader))
            {
                Padding             = 10,
                HorizontalAlignment = Element.ALIGN_RIGHT,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                BorderColor         = BaseColor.BLACK,
                BorderWidth         = 1
            };
            table.AddCell(cellGradeTask);
            double   gradeTaskAVG      = tasks.Sum(x => x.Value) / tasks.Count();
            PdfPCell cellGradeTaskBase = new PdfPCell(new Phrase(string.Format("{0:0.#}", gradeTaskAVG * coef), fontBase))
            {
                Padding             = 10,
                HorizontalAlignment = Element.ALIGN_LEFT,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                BorderColor         = BaseColor.BLACK,
                BorderWidth         = 1
            };
            table.AddCell(cellGradeTaskBase);
            document.Add(table);
            #endregion
            #region Templates
            if (!string.IsNullOrEmpty(review))
            {
                document.Add(new Paragraph(new Phrase($"Отзыв руководителя практики", fontHeader))
                {
                    Alignment = Element.ALIGN_CENTER
                });
                document.Add(new Paragraph(10, "\u00a0"));
                table = new PdfPTable(1)
                {
                    WidthPercentage = 90,
                };
                table.DefaultCell.BorderWidth = 0;
                table.DefaultCell.HasBorder(iTextSharp.text.Rectangle.NO_BORDER);
                PdfPCell cellAnswer = new PdfPCell(new Phrase(review, fontBase))
                {
                    Padding             = 10,
                    HorizontalAlignment = Element.ALIGN_JUSTIFIED,
                    VerticalAlignment   = Element.ALIGN_MIDDLE,
                    Border      = iTextSharp.text.Rectangle.NO_BORDER,
                    BorderWidth = 0
                };
                table.AddCell(cellAnswer);
                document.Add(table);
            }
            #endregion
            document.Close();
            return(filename);
        }
Exemplo n.º 22
0
        private void btnGenerarPDF_Click_1(object sender, EventArgs e)
        {
            string FileName = "Reporte generado el " + dtefechaInicial + " a " + dtefechaFinal + " " + cmbE.SelectedItem.ToString() + ".pdf";


            //genera el documento
            Document  document = new Document(iTextSharp.text.PageSize.A4, 10, 10, 42, 35);
            PdfWriter wri      = PdfWriter.GetInstance(document, new FileStream(FileName, FileMode.Create));

            document.Open();

            document.AddAuthor("Empresa SATOM-MEX");
            document.AddCreator("Reporte generado para la toma de desiciones.");
            document.AddKeywords("Reporte en PDF Histograma");
            document.AddSubject("Estadística de la fecha " + dtefechaInicial + " a " + dtefechaFinal + "");
            document.AddTitle("Reporte");


            //Cargo la imagen desde el almacenamiento
            iTextSharp.text.Image PNG = iTextSharp.text.Image.GetInstance(@"C:\datos\SATOM-MEX.png");
            PNG.ScaleToFit(100f, 100f);
            PNG.Border = iTextSharp.text.Rectangle.BOX;
            //PNG.BorderColor = iTextSharp.text.BaseColor.WHITE;
            //PNG.BorderWidth = 5f;
            document.Add(PNG);

            //Ingreso los titulos que tendra el documento

            Chunk Titulo       = new Chunk("SATOM-MEX", FontFactory.GetFont("Times New Roman", 15, iTextSharp.text.Font.BOLD));
            Chunk secundario   = new Chunk("Salud Alimentaria y Tratamientos Orgánicos Medicinales de México", FontFactory.GetFont("Times New Roman", 13, iTextSharp.text.Font.BOLD));
            Chunk datosMuestra = new Chunk("Datos de la población del cliente: " + txtDatosTotales.Text + " entre la fecha " + dtefechaInicial + " y " + dtefechaFinal + ".", FontFactory.GetFont("Times New Roman", 13, iTextSharp.text.Font.BOLD));

            document.Add(new Paragraph(Titulo));
            document.Add(new Paragraph(secundario));
            document.Add(new Paragraph(datosMuestra));
            document.Add(new Paragraph("Grado de confianza: " + cmbE.SelectedItem.ToString() + "."));
            document.Add(new Paragraph("Total de muestra: " + txtDatosMuestra.Text + "."));
            document.Add(new Paragraph(" "));
            document.Add(new Paragraph(" "));
            document.Add(new Paragraph("Se muestran los siguientes datos: "));



            //Agrego los datos del reporte
            //document.Add(new Paragraph("Reporte de " + dtefechaInicial + " al " + dtefechaFinal + ".", FontFactory.GetFont("Times New Roman", 12, iTextSharp.text.Font.ITALIC)));
            document.Add(new Paragraph("Tamaño de clases: " + txtMostrarNClases.Text, FontFactory.GetFont("Times New Roman", 12, iTextSharp.text.Font.ITALIC)));
            document.Add(new Paragraph("Rango: " + txtMostrarRango.Text, FontFactory.GetFont("Times New Roman", 12, iTextSharp.text.Font.ITALIC)));
            document.Add(new Paragraph("Anchura de clases: " + txtMostrarAnchura.Text, FontFactory.GetFont("Times New Roman", 12, iTextSharp.text.Font.ITALIC)));
            document.Add(new Paragraph("Media: " + txtMostrarMedia.Text, FontFactory.GetFont("Times New Roman", 12, iTextSharp.text.Font.ITALIC)));
            document.Add(new Paragraph("Desviación estándar: " + txtMostrarDesviacionEstandar.Text, FontFactory.GetFont("Times New Roman", 12, iTextSharp.text.Font.ITALIC)));
            document.Add(new Paragraph("Mediana: " + txtMostrarMediana.Text, FontFactory.GetFont("Times New Roman", 12, iTextSharp.text.Font.ITALIC)));
            document.Add(new Paragraph("Moda: " + txtMostrarModa.Text, FontFactory.GetFont("Times New Roman", 12, iTextSharp.text.Font.ITALIC)));
            document.Add(new Paragraph("Varianza: " + txtMostrarVarianza.Text, FontFactory.GetFont("Times New Roman", 12, iTextSharp.text.Font.ITALIC)));
            document.Add(new Paragraph(""));
            document.Add(new Paragraph("Histograma con polígonos de frecuencias", FontFactory.GetFont("Times New Roman", 12, iTextSharp.text.Font.BOLDITALIC)));



            //Agrego la imagen que es capturada desde el módulo y lo cargo en el documento
            var chartImage = new MemoryStream();

            chart1.SaveImage(chartImage, ChartImageFormat.Png);
            iTextSharp.text.Image Chart_image = iTextSharp.text.Image.GetInstance(chartImage.GetBuffer());
            Chart_image.ScaleToFit(600f, 600f);
            document.Add(Chart_image);



            document.Close();

            MessageBox.Show("Reporte creado exitosamente!!");
        }
Exemplo n.º 23
0
        public async Task <MemoryStream> GenerarPDF(int id, string descripcionEmpresa)
        {
            BE_TxSIMConsolidado p = context.ExecuteSqlViewId <BE_TxSIMConsolidado>(SP_GET_POR_ID, new BE_TxSIMConsolidado {
                IdSIMConsolidado = id
            });

            var listaDocumentoSIM = context.ExecuteSqlViewFindByCondition <BE_TxSIM>(SP_GET_CONSOLIDADO_SIM, new BE_TxSIMConsolidado {
                IdSIMConsolidado = id
            }).ToList();

            var listaIndiceBursal = context.ExecuteSqlViewFindByCondition <BE_TxSIMIndiceBursal>(SP_GET_CONSOLIDADO_INDICE_BURSAL, new BE_TxSIMConsolidado {
                IdSIMConsolidado = id
            }).ToList();

            var listaLesionBursa = context.ExecuteSqlViewFindByCondition <BE_TxSIMLesionBursa>(SP_GET_CONSOLIDADO_LESION_BURSAL, new BE_TxSIMConsolidado {
                IdSIMConsolidado = id
            }).ToList();

            var listaLesionTimo = context.ExecuteSqlViewFindByCondition <BE_TxSIMLesionTimo>(SP_GET_CONSOLIDADO_LESION_TIMO, new BE_TxSIMConsolidado {
                IdSIMConsolidado = id
            }).ToList();

            var listaLesiones = context.ExecuteSqlViewFindByCondition <BE_TxSIMLesiones>(SP_GET_CONSOLIDADO_LESIONES, new BE_TxSIMConsolidado {
                IdSIMConsolidado = id
            }).ToList();

            var listaFotos = context.ExecuteSqlViewFindByCondition <BE_TxSIMFotos>(SP_GET_CONSOLIDADO_FOTOS, new BE_TxSIMConsolidado {
                IdSIMConsolidado = id
            }).ToList();

            return(await Task.Run(() =>
            {
                Document doc = new Document();
                doc.SetPageSize(PageSize.Letter);
                // points to cm
                doc.SetMargins(28.34f, 28.34f, 85f, 85f);
                MemoryStream ms = new MemoryStream();
                PdfWriter write = PdfWriter.GetInstance(doc, ms);
                doc.AddAuthor("Grupo SBA");
                doc.AddTitle("Invetsa");

                var pe = new PageEventHelper();
                pe.FlagCerrado = true;
                pe.FlagModulo = "SIM";
                write.PageEvent = pe;
                // Colocamos la fuente que deseamos que tenga el documento
                BaseFont helvetica = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, true);
                // Titulo
                iTextSharp.text.Font titulo = new iTextSharp.text.Font(helvetica, 16f, iTextSharp.text.Font.BOLD, new BaseColor(103, 93, 152));
                iTextSharp.text.Font tituloBlanco = new iTextSharp.text.Font(helvetica, 18f, iTextSharp.text.Font.NORMAL, BaseColor.White);
                iTextSharp.text.Font subTitulo = new iTextSharp.text.Font(helvetica, 10f, iTextSharp.text.Font.BOLD, new BaseColor(103, 93, 152));
                iTextSharp.text.Font subTituloParticiones = new iTextSharp.text.Font(helvetica, 10f, iTextSharp.text.Font.BOLD, new BaseColor(103, 93, 152));
                iTextSharp.text.Font parrafoBlanco = new iTextSharp.text.Font(helvetica, 10f, iTextSharp.text.Font.BOLD, BaseColor.White);
                iTextSharp.text.Font parrafoNegrita = new iTextSharp.text.Font(helvetica, 10f, iTextSharp.text.Font.BOLD, BaseColor.Black);
                iTextSharp.text.Font parrafoNegro = new iTextSharp.text.Font(helvetica, 10f, iTextSharp.text.Font.NORMAL, BaseColor.Black);
                iTextSharp.text.Font parrafoRojo = new iTextSharp.text.Font(helvetica, 10f, iTextSharp.text.Font.NORMAL, BaseColor.Red);
                pe.HeaderLeft = " ";
                pe.HeaderFont = parrafoBlanco;
                pe.HeaderRight = " ";
                doc.Open();

                var tbl = new PdfPTable(new float[] { 100f })
                {
                    WidthPercentage = 100
                };

                var title = string.Format("INFORME DEL SISTEMA INTEGRADO DE MONITOREO DE CAMPO - {0}", id, titulo);
                var c1 = new PdfPCell(new Phrase(title, titulo))
                {
                    Border = 0
                };
                c1.HorizontalAlignment = Element.ALIGN_CENTER;
                c1.VerticalAlignment = Element.ALIGN_MIDDLE;
                tbl.AddCell(c1);
                c1 = new PdfPCell(new Phrase(p.DescripcionEmpresa, titulo))
                {
                    Border = 0
                };
                c1.HorizontalAlignment = Element.ALIGN_CENTER;
                c1.VerticalAlignment = Element.ALIGN_MIDDLE;
                tbl.AddCell(c1);
                c1.Phrase = new Phrase("", parrafoNegro);
                tbl.AddCell(c1);
                c1.Phrase = new Phrase("", parrafoNegro);
                tbl.AddCell(c1);
                doc.Add(tbl);

                tbl = new PdfPTable(new float[] { 7f, 20f, 30f, 29f, 7f, 7f })
                {
                    WidthPercentage = 100f
                };
                c1 = new PdfPCell();
                c1.Phrase = new Phrase("LISTA DE SISTEMA INTEGRADO DE MONITOREO DE CAMPO", subTitulo);
                c1.Border = 0;
                c1.Colspan = 6;
                tbl.AddCell(c1);
                c1 = new PdfPCell();
                c1.Phrase = new Phrase("", parrafoNegro);
                c1.Border = 0;
                c1.Colspan = 6;
                tbl.AddCell(c1);
                c1 = new PdfPCell();
                c1 = new PdfPCell(new Phrase("Edad", parrafoBlanco))
                {
                    BackgroundColor = new BaseColor(51, 153, 68), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                };
                tbl.AddCell(c1);
                c1.Phrase = new Phrase("Fecha/Hora", parrafoBlanco);
                tbl.AddCell(c1);
                c1.Phrase = new Phrase("Granja", parrafoBlanco);
                tbl.AddCell(c1);
                c1.Phrase = new Phrase("Zona", parrafoBlanco);
                tbl.AddCell(c1);
                c1.Phrase = new Phrase("Galpón", parrafoBlanco);
                tbl.AddCell(c1);
                c1.Phrase = new Phrase("Nro Pollos", parrafoBlanco);
                tbl.AddCell(c1);
                foreach (BE_TxSIM item in listaDocumentoSIM)
                {
                    c1 = new PdfPCell();
                    c1.Phrase = new Phrase(item.Edad.ToString(), parrafoNegro);
                    c1.HorizontalAlignment = Element.ALIGN_CENTER;
                    tbl.AddCell(c1);
                    c1.Phrase = new Phrase(item.FecHoraRegistro.ToString(), parrafoNegro);
                    tbl.AddCell(c1);
                    c1.Phrase = new Phrase(item.CodigoPlanta, parrafoNegro);
                    tbl.AddCell(c1);
                    c1.Phrase = new Phrase(item.Zona, parrafoNegro);
                    tbl.AddCell(c1);
                    c1.Phrase = new Phrase(item.Galpon.ToString(), parrafoNegro);
                    tbl.AddCell(c1);
                    c1.Phrase = new Phrase(item.NroPollos.ToString(), parrafoNegro);
                    tbl.AddCell(c1);
                }
                c1 = new PdfPCell();
                c1.Phrase = new Phrase("", parrafoNegro);
                c1.Border = 0;
                c1.Colspan = 6;
                tbl.AddCell(c1);
                doc.Add(tbl);

                tbl = new PdfPTable(new float[] { 7f, 10f, 10f, 10f, 10f, 10f, 10f, 10f, 10f, 13f })
                {
                    WidthPercentage = 100f
                };
                c1 = new PdfPCell();
                c1.Phrase = new Phrase("I.ÍNDICE DE ÓRGANOS LINFOIDES", subTitulo);
                c1.Border = 0;
                c1.Colspan = 10;
                tbl.AddCell(c1);
                c1 = new PdfPCell();
                c1.Phrase = new Phrase("", parrafoNegro);
                c1.Border = 0;
                c1.Colspan = 10;
                tbl.AddCell(c1);
                c1 = new PdfPCell();
                c1 = new PdfPCell(new Phrase("Edad", parrafoBlanco))
                {
                    BackgroundColor = new BaseColor(51, 153, 68), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                };
                tbl.AddCell(c1);
                c1.Phrase = new Phrase("Peso Corporal (g)", parrafoBlanco);
                tbl.AddCell(c1);
                c1.Phrase = new Phrase("Peso de Bursa (g)", parrafoBlanco);
                tbl.AddCell(c1);
                c1.Phrase = new Phrase("Peso de Bazo (g)", parrafoBlanco);
                tbl.AddCell(c1);
                c1.Phrase = new Phrase("Peso de Timo (g)", parrafoBlanco);
                tbl.AddCell(c1);
                c1.Phrase = new Phrase("Peso de Hígado (g)", parrafoBlanco);
                tbl.AddCell(c1);
                c1.Phrase = new Phrase("Índice Bursal", parrafoBlanco);
                tbl.AddCell(c1);
                c1.Phrase = new Phrase("Índice Timico", parrafoBlanco);
                tbl.AddCell(c1);
                c1.Phrase = new Phrase("Índice Hepático", parrafoBlanco);
                tbl.AddCell(c1);
                c1.Phrase = new Phrase("Bursómetro", parrafoBlanco);
                tbl.AddCell(c1);
                foreach (BE_TxSIMIndiceBursal item in listaIndiceBursal)
                {
                    c1 = new PdfPCell();
                    c1.Phrase = new Phrase(item.Edad.ToString(), parrafoNegro);
                    c1.HorizontalAlignment = Element.ALIGN_CENTER;
                    tbl.AddCell(c1);
                    c1.Phrase = new Phrase(((int)item.PesoCorporal).ToString(), parrafoNegro);
                    tbl.AddCell(c1);
                    c1.Phrase = new Phrase(item.PesoBursa.ToString(), parrafoNegro);
                    tbl.AddCell(c1);
                    c1.Phrase = new Phrase(item.PesoBazo.ToString(), parrafoNegro);
                    tbl.AddCell(c1);
                    c1.Phrase = new Phrase(item.PesoTimo.ToString(), parrafoNegro);
                    tbl.AddCell(c1);
                    c1.Phrase = new Phrase(item.PesoHigado.ToString(), parrafoNegro);
                    tbl.AddCell(c1);
                    c1.Phrase = new Phrase(item.IndiceBursal.ToString(), parrafoNegro);
                    tbl.AddCell(c1);
                    c1.Phrase = new Phrase(item.IndiceTimico.ToString(), parrafoNegro);
                    tbl.AddCell(c1);
                    c1.Phrase = new Phrase(item.IndiceHepatico.ToString(), parrafoNegro);
                    tbl.AddCell(c1);
                    c1.Phrase = new Phrase(item.Bursometro.ToString(), parrafoNegro);
                    tbl.AddCell(c1);
                }
                c1 = new PdfPCell();
                c1.Phrase = new Phrase("", parrafoNegro);
                c1.Border = 0;
                c1.Colspan = 10;
                tbl.AddCell(c1);
                doc.Add(tbl);

                tbl = new PdfPTable(new float[] { 10f, 15f, 15f, 15f, 15f, 15f, 15f })
                {
                    WidthPercentage = 100f
                };
                c1 = new PdfPCell();
                c1.Phrase = new Phrase("II.	SCORE DE LESIONES HISTOPATOLÓGICAS DE BURSA Y TIMO", subTitulo);
                c1.Border = 0;
                c1.Colspan = 7;
                tbl.AddCell(c1);
                c1 = new PdfPCell();
                c1.Phrase = new Phrase("", parrafoNegro);
                c1.Border = 0;
                c1.Colspan = 7;
                tbl.AddCell(c1);
                c1 = new PdfPCell();
                c1 = new PdfPCell(new Phrase("EDAD", parrafoBlanco))
                {
                    BackgroundColor = new BaseColor(51, 153, 68), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                };
                tbl.AddCell(c1);
                c1.Phrase = new Phrase("SCORE DE LESIÓN DE BURSA", parrafoBlanco);
                c1.Colspan = 5;
                tbl.AddCell(c1);
                c1.Phrase = new Phrase("PROMEDIO", parrafoBlanco);
                tbl.AddCell(c1);

                int v_Edad = 0;

                foreach (BE_TxSIMLesionBursa item in listaLesionBursa)
                {
                    c1 = new PdfPCell();
                    if (v_Edad != item.Edad)
                    {
                        c1.Phrase = new Phrase(item.Edad.ToString(), parrafoNegro);
                        c1.HorizontalAlignment = Element.ALIGN_CENTER;
                        tbl.AddCell(c1);
                    }

                    c1.Phrase = new Phrase(item.Valor.ToString(), parrafoNegro);
                    c1.HorizontalAlignment = Element.ALIGN_CENTER;
                    tbl.AddCell(c1);

                    v_Edad = item.Edad;
                }

                c1 = new PdfPCell();
                c1.Phrase = new Phrase("", parrafoNegro);
                c1.Border = 0;
                c1.Colspan = 7;
                tbl.AddCell(c1);


                c1 = new PdfPCell();
                c1 = new PdfPCell(new Phrase("EDAD", parrafoBlanco))
                {
                    BackgroundColor = new BaseColor(51, 153, 68), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                };
                tbl.AddCell(c1);
                c1.Phrase = new Phrase("SCORE DE LESIÓN DE TIMO", parrafoBlanco);
                c1.Colspan = 5;
                tbl.AddCell(c1);
                c1.Phrase = new Phrase("PROMEDIO", parrafoBlanco);
                tbl.AddCell(c1);

                v_Edad = 0;

                foreach (BE_TxSIMLesionTimo item in listaLesionTimo)
                {
                    c1 = new PdfPCell();
                    if (v_Edad != item.Edad)
                    {
                        c1.Phrase = new Phrase(item.Edad.ToString(), parrafoNegro);
                        c1.HorizontalAlignment = Element.ALIGN_CENTER;
                        tbl.AddCell(c1);
                    }

                    c1.Phrase = new Phrase(item.Valor.ToString(), parrafoNegro);
                    c1.HorizontalAlignment = Element.ALIGN_CENTER;
                    tbl.AddCell(c1);

                    v_Edad = item.Edad;
                }
                c1 = new PdfPCell();
                c1.Phrase = new Phrase("", parrafoNegro);
                c1.Border = 0;
                c1.Colspan = 7;
                tbl.AddCell(c1);

                doc.Add(tbl);

                tbl = new PdfPTable(new float[] { 10f, 30f, 30f, 30f })
                {
                    WidthPercentage = 100f
                };
                c1 = new PdfPCell();
                c1.Phrase = new Phrase("III.	HALLAZGO DE LESIONES HISTOPATOLÓGICAS DE ÓRGANOS", subTitulo);
                c1.Border = 0;
                c1.Colspan = 4;
                tbl.AddCell(c1);
                c1 = new PdfPCell();
                c1.Phrase = new Phrase("", parrafoNegro);
                c1.Border = 0;
                c1.Colspan = 4;
                tbl.AddCell(c1);
                c1 = new PdfPCell();
                c1 = new PdfPCell(new Phrase("EDAD", parrafoBlanco))
                {
                    BackgroundColor = new BaseColor(51, 153, 68), HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE
                };
                tbl.AddCell(c1);
                c1.Phrase = new Phrase("LESIONES DE DUODENO", parrafoBlanco);
                tbl.AddCell(c1);
                c1.Phrase = new Phrase("LESIONES EN INSTESTINO MEDIO", parrafoBlanco);
                tbl.AddCell(c1);
                c1.Phrase = new Phrase("LESIONES EN HÍGADO", parrafoBlanco);
                tbl.AddCell(c1);

                foreach (BE_TxSIMLesiones item in listaLesiones)
                {
                    c1 = new PdfPCell();
                    c1.Phrase = new Phrase(item.Edad.ToString(), parrafoNegro);
                    c1.HorizontalAlignment = Element.ALIGN_CENTER;
                    tbl.AddCell(c1);
                    c1.Phrase = new Phrase(item.LesionesDeudemo, parrafoNegro);
                    c1.HorizontalAlignment = Element.ALIGN_LEFT;
                    tbl.AddCell(c1);
                    c1.Phrase = new Phrase(item.LesionesIntestinoMedio, parrafoNegro);
                    c1.HorizontalAlignment = Element.ALIGN_LEFT;
                    tbl.AddCell(c1);
                    c1.Phrase = new Phrase(item.LesionesHigado, parrafoNegro);
                    c1.HorizontalAlignment = Element.ALIGN_LEFT;
                    tbl.AddCell(c1);
                }

                c1 = new PdfPCell();
                c1.Phrase = new Phrase("", parrafoNegro);
                c1.Border = 0;
                c1.Colspan = 4;
                tbl.AddCell(c1);

                doc.Add(tbl);

                tbl = new PdfPTable(new float[] { 100f })
                {
                    WidthPercentage = 100f
                };
                c1 = new PdfPCell();
                c1.Phrase = new Phrase("IV. COMENTARIO", subTitulo);
                c1.Border = 0;
                c1.VerticalAlignment = Element.ALIGN_MIDDLE;
                tbl.AddCell(c1);
                c1.Phrase = new Phrase(p.Observacion, parrafoNegro);
                tbl.AddCell(c1);

                c1 = new PdfPCell();
                c1.Phrase = new Phrase("", parrafoNegro);
                c1.Border = 0;
                tbl.AddCell(c1);
                doc.Add(tbl);

                tbl = new PdfPTable(new float[] { 50f, 50f })
                {
                    WidthPercentage = 100f
                };
                c1 = new PdfPCell();
                c1.Phrase = new Phrase("V. FOTOS", subTitulo);
                c1.Border = 0;
                c1.Colspan = 2;
                tbl.AddCell(c1);
                c1 = new PdfPCell();
                c1.Phrase = new Phrase("", parrafoNegro);
                c1.Border = 0;
                c1.Colspan = 2;
                tbl.AddCell(c1);

                var countFotos = listaFotos.Count();
                iTextSharp.text.Image foto = null;

                foreach (BE_TxSIMFotos item in listaFotos)
                {
                    foto = ImagenBase64ToImagen(item.Foto, 270f, 200f);

                    if (foto != null)
                    {
                        c1 = new PdfPCell(foto);
                        c1.HorizontalAlignment = Element.ALIGN_CENTER;
                        c1.VerticalAlignment = Element.ALIGN_MIDDLE;
                        c1.Border = 0;
                        tbl.AddCell(c1);
                    }
                }

                if ((countFotos % 2) != 0)
                {
                    c1 = new PdfPCell(new Phrase(" "));
                    c1.Border = 0;
                    tbl.AddCell(c1);
                }

                c1 = new PdfPCell();
                c1.Phrase = new Phrase("", parrafoNegro);
                c1.Border = 0;
                c1.Colspan = 2;
                tbl.AddCell(c1);

                doc.Add(tbl);

                write.Close();
                doc.Close();
                ms.Seek(0, SeekOrigin.Begin);
                var file = ms;

                return file;
            }));
        }
Exemplo n.º 24
0
 public void FillEvent(string shareholderName, int shid, int pageNumber, string title, iTextSharp.text.Image imgLogo, float[] primaryTableLayout)
 {
     _shareholderName = shareholderName;
     _shid = shid.ToString();
     _pageNumber = pageNumber;
     _title = title;
     _imgLogo = imgLogo;
     _primaryTableLayout = primaryTableLayout;
 }
Exemplo n.º 25
0
        public IcjDocument(string logoFile, string fileName, FileMode fileMode, string output, int marginLeft, int marginRight, int marginTop, int marginBottom)
        {
            document = new Document(PageSize.A4, marginLeft, marginRight, marginTop, marginBottom);
            this.marginLeft = marginLeft;
            this.marginRight = marginRight;
            this.marginTop = marginTop;
            this.marginBottom = marginBottom;
            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }
            if (output == "file")
            {
                writer = PdfWriter.GetInstance(document, new FileStream(fileName, fileMode));
            }
            else if (output == "memory")
            {
                stream = new MemoryStream();
                writer = PdfWriter.GetInstance(document, stream);
            }
            width = PageSize.A4.Width - marginLeft - marginRight;
            height = PageSize.A4.Height - marginTop - marginBottom;

            jpg = iTextSharp.text.Image.GetInstance(logoFile);

            //Resize image depend upon your need
            //For give the size to image
            //jpg.ScaleToFit(2500, 500);

            //If you want to choose image as background then,

            jpg.Alignment = iTextSharp.text.Image.UNDERLYING;

            //If you want to give absolute/specified fix position to image.
            jpg.SetAbsolutePosition(15, 40);
            

        }
 /// <summary>
 /// ctor.
 /// </summary>        
 public TotalPagesNumberXmlWorkerProcessor(iTextSharp.text.Image image)
 {
     _image = image;
 }
Exemplo n.º 27
0
 /// <summary>
 ///     Converts an iText image to a Bitmap
 /// </summary>
 /// <param name="img">The iText image</param>
 /// <returns>The bitmap for this image</returns>
 public Bitmap ImageToBitmap(Image img)
 {
     var bmp = new Bitmap((int) img.Width, (int) img.Height, CSImaging.PixelFormat.Format24bppRgb);
     var rect = new CSRectangle(0, 0, bmp.Width, bmp.Height);
     var bmpdat = bmp.LockBits(rect, CSImaging.ImageLockMode.ReadWrite, CSImaging.PixelFormat.Format24bppRgb);
     Marshal.Copy(img.RawData, 0, bmpdat.Scan0, img.RawData.Length);
     bmp.UnlockBits(bmpdat);
     return bmp;
 }
Exemplo n.º 28
0
        public override void OnEndPage(PdfWriter writer, Document doc)
        {
            // code for Rectangel border
            //.......................................
            base.OnEndPage(writer, doc);
            var content        = writer.DirectContent;
            var pageBorderRect = new Rectangle(doc.PageSize);

            pageBorderRect.Left   += doc.LeftMargin;
            pageBorderRect.Right  -= doc.RightMargin;
            pageBorderRect.Top    -= doc.TopMargin;
            pageBorderRect.Bottom += doc.BottomMargin;
            content.SetColorStroke(Color.BLACK);
            content.Rectangle(pageBorderRect.Left, pageBorderRect.Bottom, pageBorderRect.Width, pageBorderRect.Height);
            content.Stroke();
            //.....................................


            Color grey = new Color(128, 128, 128);

            iTextSharp.text.Font font = FontFactory.GetFont("Arial", 9, iTextSharp.text.Font.COURIER, grey);

            PdfPTable footerTbl = new PdfPTable(1);

            footerTbl.TotalWidth = doc.PageSize.Width;

            Chunk    myFooter = new Chunk("Page " + (doc.PageNumber), FontFactory.GetFont(FontFactory.HELVETICA_OBLIQUE, 8, grey));
            PdfPCell footer   = new PdfPCell(new Phrase(myFooter));

            footer.Border = iTextSharp.text.Rectangle.NO_BORDER;
            footer.HorizontalAlignment = Element.ALIGN_CENTER;
            footerTbl.AddCell(footer);
            footerTbl.WriteSelectedRows(0, -1, 6, 39, writer.DirectContent);

            //code for watermark.................
            PdfGState graphicsState = new PdfGState();

            iTextSharp.text.Image watermark = iTextSharp.text.Image.GetInstance(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\Images\\Watermark.jpg");
            PdfContentByte        canvas    = writer.DirectContentUnder;
            Image image = Image.GetInstance(watermark);

            image.SetAbsolutePosition(190, 400);
            canvas.SaveState();
            PdfGState state = new PdfGState();

            state.FillOpacity = 0.2f;
            canvas.SetGState(state);
            canvas.AddImage(image);
            canvas.RestoreState();
            //....................................

            // return null;

            Rectangle pageSize = doc.PageSize;


            string time    = DateTime.Now.ToString("HH:mm:ss");
            string timeNew = "Time " + time;


            // string date = "Stability Report P15B";
            Paragraph header = new Paragraph(timeNew, FontFactory.GetFont(FontFactory.TIMES, 8, iTextSharp.text.Font.BOLD, Color.GRAY));

            header.Alignment = Element.ALIGN_LEFT;
            PdfPTable headerTbl = new PdfPTable(1);

            headerTbl.TotalWidth          = doc.PageSize.Width - 520;
            headerTbl.HorizontalAlignment = 100;
            PdfPCell cell1 = new PdfPCell(header);

            cell1.HorizontalAlignment = 100;
            cell1.VerticalAlignment   = Element.ALIGN_MIDDLE;
            cell1.Border          = 0;
            cell1.PaddingLeft     = 10;
            cell1.BackgroundColor = Color.WHITE;
            headerTbl.AddCell(cell1);


            string date1   = DateTime.Now.ToString("yyyy-MM-dd");
            string Datenew = "Date " + date1;

            Paragraph header1 = new Paragraph(Datenew, FontFactory.GetFont(FontFactory.TIMES, 8, iTextSharp.text.Font.BOLD, Color.GRAY));

            header1.Alignment = Element.ALIGN_RIGHT;
            PdfPCell cell2 = new PdfPCell(header1);

            cell2.Border              = 0;
            cell2.PaddingLeft         = 10;
            cell2.VerticalAlignment   = Element.ALIGN_TOP;
            cell2.HorizontalAlignment = 0;
            cell2.BackgroundColor     = Color.WHITE;
            headerTbl.AddCell(cell2);
            headerTbl.WriteSelectedRows(0, 2, pageSize.GetLeft(45), pageSize.GetTop(33), writer.DirectContent);

            //if (doc.PageNumber == 2) { doc.Add(new iTextSharp.text.Paragraph("  ")); doc.Add(new iTextSharp.text.Paragraph("  ")); }
        }
 private Image[,] SameImage(string path)
 {
     var images = new Image[3, 3];
     for (int i = 0; i < 3; i++)
     {
         for (int j = 0; j < 3; j++)
         {
             var imageStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
             images[i,j] = Image.GetInstance(imageStream);
         }
     }
     return images;
 }
Exemplo n.º 30
0
        /// <summary>
        ///  PDF加水印
        /// </summary>
        /// <param name="inputfilepath">源PDF文件</param>
        /// <param name="outputfilepath">加水印后PDF文件 </param>
        /// <param name="ModelPicName">水印文件路径</param>
        /// <param name="top">离顶部距离</param>
        /// <param name="left">离左边距离,如果为负,则为离右边距离</param>
        /// <param name="strMsg">返回信息</param>
        /// <returns>返回</returns>
        public bool PDFWatermark(string inputfilepath, string outputfilepath, string ModelPicName, float top, float left, int Pages)
        {
            PdfReader  pdfReader    = null;
            PdfStamper pdfStamper   = null;
            FileStream outputStream = null;

            iTextSharp.text.Rectangle psize            = null;
            PdfContentByte            waterMarkContent = null;

            iTextSharp.text.Image image = null;
            try
            {
                pdfReader = new PdfReader(inputfilepath);
                int numberOfPages = pdfReader.NumberOfPages;
                psize = pdfReader.GetPageSize(1);
                float width  = psize.Width;
                float height = psize.Height;
                outputStream   = new FileStream(outputfilepath, FileMode.Create);
                pdfStamper     = new PdfStamper(pdfReader, outputStream);
                image          = iTextSharp.text.Image.GetInstance(ModelPicName);
                image.GrayFill = 20;//透明度,灰色填充

                //image.Rotation//旋转
                //image.RotationDegrees//旋转角度
                //水印的位置
                if (left < 0)
                {
                    left = width - image.Width + left;
                }
                image.SetAbsolutePosition(left, (height - image.Height) - top);

                //每一页加水印,也可以设置某一页加水印
                for (int i = 1; i <= Pages && i <= numberOfPages; i++)
                {
                    waterMarkContent = pdfStamper.GetOverContent(i);
                    waterMarkContent.AddImage(image);
                }
                return(true);
            }
            catch (Exception ex)
            {
                Loger.logger(ex);
                return(false);
            }
            finally
            {
                if (pdfStamper != null)
                {
                    pdfStamper.Close();
                }
                if (pdfReader != null)
                {
                    pdfReader.Close();
                }
                if (outputStream != null)
                {
                    outputStream.Close();
                }
                psize            = null;
                waterMarkContent = null;
                image            = null;
            }
        }
Exemplo n.º 31
0
        private string CreatePDF(Group group, List <ReportStudents> students)
        {
            var      document = new Document(PageSize.A4, 15, 15, 20, 15);
            string   filename = System.Guid.NewGuid().ToString() + ".pdf";
            string   path     = System.Web.HttpContext.Current.Server.MapPath("~/Content/Uploads/") + filename;
            BaseFont font     = BaseFont.CreateFont(System.Web.HttpContext.Current.Server.MapPath("~/fonts/times-new-roman.ttf"),
                                                    BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            var fontBase   = new iTextSharp.text.Font(font, 14, iTextSharp.text.Font.NORMAL, new BaseColor(Color.Black));
            var fontHeader = new iTextSharp.text.Font(font, 14, iTextSharp.text.Font.BOLD, new BaseColor(Color.Black));

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

            System.Drawing.Image  image  = System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Server.MapPath("~/Content/assets/emblem.png"));
            iTextSharp.text.Image emblem = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Png);
            emblem.Alignment = Element.ALIGN_CENTER;
            emblem.ScaleToFit(1000f, 60f);
            document.Add(emblem);

            document.Add(new Paragraph(new Phrase($"Отчет по практике группы {group.Description}", fontBase))
            {
                Alignment = Element.ALIGN_CENTER
            });
            document.Add(new Paragraph(new Phrase($"проходящей с {group.Start.ToShortDateString()} по {group.End.ToShortDateString()}", fontBase))
            {
                Alignment = Element.ALIGN_CENTER
            });
            document.Add(new Paragraph(70, "\u00a0"));
            document.Add(new Paragraph(new Phrase($"Успеваемость группы", fontHeader))
            {
                Alignment = Element.ALIGN_CENTER
            });
            document.Add(new Paragraph(10, "\u00a0"));
            PdfPTable table = new PdfPTable(6)
            {
                WidthPercentage = 90,
            };

            table.DefaultCell.BorderWidth = 0;
            table.DefaultCell.HasBorder(iTextSharp.text.Rectangle.NO_BORDER);
            PdfPCell cellHeader1 = new PdfPCell(new Phrase("Фамилия", fontHeader))
            {
                Padding             = 2,
                HorizontalAlignment = Element.ALIGN_CENTER,
                VerticalAlignment   = Element.ALIGN_MIDDLE
            };

            table.AddCell(cellHeader1);
            PdfPCell cellHeader2 = new PdfPCell(new Phrase("Имя", fontHeader))
            {
                Padding             = 2,
                HorizontalAlignment = Element.ALIGN_CENTER,
                VerticalAlignment   = Element.ALIGN_MIDDLE
            };

            table.AddCell(cellHeader2);
            PdfPCell cellHeader3 = new PdfPCell(new Phrase("Отчество", fontHeader))
            {
                Padding             = 2,
                HorizontalAlignment = Element.ALIGN_CENTER,
                VerticalAlignment   = Element.ALIGN_MIDDLE
            };

            table.AddCell(cellHeader3);
            PdfPCell cellHeader4 = new PdfPCell(new Phrase("Оценка по тестам", fontHeader))
            {
                Padding             = 2,
                HorizontalAlignment = Element.ALIGN_CENTER,
                VerticalAlignment   = Element.ALIGN_MIDDLE
            };

            table.AddCell(cellHeader4);
            PdfPCell cellHeader5 = new PdfPCell(new Phrase("Оценка по заданиям", fontHeader))
            {
                Padding             = 2,
                HorizontalAlignment = Element.ALIGN_CENTER,
                VerticalAlignment   = Element.ALIGN_MIDDLE
            };

            table.AddCell(cellHeader5);
            PdfPCell cellHeader6 = new PdfPCell(new Phrase("Общая оценка", fontHeader))
            {
                Padding             = 2,
                HorizontalAlignment = Element.ALIGN_CENTER,
                VerticalAlignment   = Element.ALIGN_MIDDLE
            };

            table.AddCell(cellHeader6);
            int coef = 5;

            foreach (var student in students)
            {
                PdfPCell cellSurname = new PdfPCell(new Phrase(student.Student.Surname, fontBase))
                {
                    PaddingBottom       = 2,
                    HorizontalAlignment = Element.ALIGN_CENTER,
                    VerticalAlignment   = Element.ALIGN_MIDDLE
                };
                table.AddCell(cellSurname);
                PdfPCell cellName = new PdfPCell(new Phrase(student.Student.Name, fontBase))
                {
                    PaddingBottom       = 2,
                    HorizontalAlignment = Element.ALIGN_CENTER,
                    VerticalAlignment   = Element.ALIGN_MIDDLE
                };
                table.AddCell(cellName);
                PdfPCell cellMidname = new PdfPCell(new Phrase(student.Student.Midname, fontBase))
                {
                    PaddingBottom       = 2,
                    HorizontalAlignment = Element.ALIGN_CENTER,
                    VerticalAlignment   = Element.ALIGN_MIDDLE
                };
                table.AddCell(cellMidname);
                PdfPCell cellGradeTest = new PdfPCell(new Phrase(string.Format("{0:0.#}", student.TestAVG * coef), fontBase))
                {
                    PaddingBottom       = 2,
                    HorizontalAlignment = Element.ALIGN_CENTER,
                    VerticalAlignment   = Element.ALIGN_MIDDLE
                };
                table.AddCell(cellGradeTest);
                PdfPCell cellGradeTask = new PdfPCell(new Phrase(string.Format("{0:0.#}", student.TaskAVG * coef), fontBase))
                {
                    PaddingBottom       = 2,
                    HorizontalAlignment = Element.ALIGN_CENTER,
                    VerticalAlignment   = Element.ALIGN_MIDDLE
                };
                table.AddCell(cellGradeTask);
                PdfPCell cellGradeSum = new PdfPCell(new Phrase(string.Format("{0:0.#}", student.SUM * coef), fontBase))
                {
                    PaddingBottom       = 2,
                    HorizontalAlignment = Element.ALIGN_CENTER,
                    VerticalAlignment   = Element.ALIGN_MIDDLE
                };
                table.AddCell(cellGradeSum);
            }
            document.Add(table);
            document.Close();
            return(filename);
        }
Exemplo n.º 32
0
        public string GenerarCredencial()
        {
            string fileName = string.Empty;

            #region iniciandoDocumento
            doc.AddAuthor("CODESUR");
            doc.AddKeywords("pdf, PdfWriter; Documento; iTextSharp");
            fileName = string.Format("CredencialAcreditacion_{0}_{1:yyyyMMddHHss}.pdf", Usuario, DateTime.Now);
            string path = PathResources;
            path = string.Format("{0}Reportes\\{1}", path, fileName);
            PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(path, FileMode.Create));
            doc.Open();
            #endregion
            try
            {
                AgregarFondoAnverso();
                AgregarFoto();
                AgregarQR();
                AgregarCodigoRol();
                AgregarNombre();
                AgregarDatosDelegacion();
                AgregarPrivilegios();
                AgregarFondoReverso();
                AgregarCodigoBarras(wri);
                AgregarTextoFoto();
                AgregarNombreReverso();
                AgregarPrivilegiosReverso();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                doc.Close();
            }

            Spire.Pdf.PdfDocument pdfdocument = new Spire.Pdf.PdfDocument();
            try
            {
                pdfdocument.LoadFromFile(path);
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                Document  realDoc = new Document(new Rectangle(566f, 454f), 0f, 0f, 0f, 0f);
                PdfPTable Reporte = new PdfPTable(new float[] { 283f, 283f });
                for (int i = 0; i < pdfdocument.Pages.Count; i++)
                {
                    System.Drawing.Image image = pdfdocument.SaveAsImage(i);
                    MemoryStream         ms    = new MemoryStream();
                    image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    iTextSharp.text.Image imgpdf = iTextSharp.text.Image.GetInstance(ms.ToArray());
                    PdfPCell imgCell             = new PdfPCell(imgpdf, true);
                    imgCell.Border          = PdfPCell.NO_BORDER;
                    imgCell.BackgroundColor = BaseColor.BLACK;
                    Reporte.AddCell(imgCell);
                }
                PdfWriter realWri = PdfWriter.GetInstance(realDoc, new FileStream(path, FileMode.Create));
                realDoc.Open();
                realDoc.Add(Reporte);
                realDoc.Close();
            }
            catch
            {
            }

            return(path);
        }
Exemplo n.º 33
0
        protected void GenerarReporte(object sender, EventArgs e)
        {
            // Creamos el documento con el tamaño de página tradicional
            Document doc = new Document(PageSize.LETTER);
            // Indicamos donde vamos a guardar el documento
            string mdoc = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            // PdfWriter writer = PdfWriter.GetInstance(doc,
            // new FileStream(@"C:\Users\edu08\Downloads\prueba.pdf", FileMode.Create));

            PdfWriter writer = PdfWriter.GetInstance(doc,
                                                     new FileStream(@"C:\Users\Public\Downloads\prueba.pdf", FileMode.Create));

            // Le colocamos el título y el autor
            // **Nota: Esto no será visible en el documento
            doc.AddTitle("Detalles de reservas");
            doc.AddCreator("STS");

            // Abrimos el archivo
            doc.Open();
            // Creamos el tipo de Font que vamos utilizar
            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
            Font fuenteT = new Font();

            fuenteT.Size = 18;
            fuenteT.SetStyle(Font.BOLD | Font.UNDERLINE);
            doc.Add(new Paragraph("Detalles de reservas                Escuela: " + usu.IdEscuela, fuenteT));
            Font fuent = new Font();

            fuent.Size = 10;
            doc.Add(new Paragraph("Fecha y hora de realización: " + DateTime.Now.ToString("dd/MM/yyyy hh:mm tt") + "    Usuario: " + usu.Nombre + " " + usu.Apellidos, fuent));
            doc.Add(Chunk.NEWLINE);
            doc.Add(Chunk.NEWLINE);

            //imagen
            string imageURL = Server.MapPath(".") + "/ccss/star-1-3/Static HTML/img/logo-dark.png";

            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imageURL);

            img.ScaleToFit(125f, 60F);
            //Imagen - Movio en el eje de las Y
            img.SetAbsolutePosition(500, 750);
            doc.Add(img);

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

            tblPrueba.WidthPercentage = 100;

            PdfPCell clNombre;
            PdfPCell clApellido;

            Font fuente = new Font();

            fuente.Size = 9;
            fuente.SetStyle(Font.BOLD);

            clNombre                     = new PdfPCell(new Phrase("Fecha: ", fuente));
            clNombre.BorderWidth         = 0;
            clNombre.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
            tblPrueba.AddCell(clNombre);

            clNombre                     = new PdfPCell(new Phrase("Almno(a):  ", fuente));
            clNombre.BorderWidth         = 0;
            clNombre.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
            tblPrueba.AddCell(clNombre);

            clNombre                     = new PdfPCell(new Phrase("Escuela: ", fuente));
            clNombre.BorderWidth         = 0;
            clNombre.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
            tblPrueba.AddCell(clNombre);

            clNombre                     = new PdfPCell(new Phrase("Dificultad: ", fuente));
            clNombre.BorderWidth         = 0;
            clNombre.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
            tblPrueba.AddCell(clNombre);

            clNombre                     = new PdfPCell(new Phrase("Instr(a): ", fuente));
            clNombre.BorderWidth         = 0;
            clNombre.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
            tblPrueba.AddCell(clNombre);

            clNombre                     = new PdfPCell(new Phrase("Hra Inicio: ", fuente));
            clNombre.BorderWidth         = 0;
            clNombre.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
            tblPrueba.AddCell(clNombre);

            clNombre                     = new PdfPCell(new Phrase("Alquiler: ", fuente));
            clNombre.BorderWidth         = 0;
            clNombre.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
            tblPrueba.AddCell(clNombre);

            clNombre                     = new PdfPCell(new Phrase("Precio Alquiler: ", fuente));
            clNombre.BorderWidth         = 0;
            clNombre.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
            tblPrueba.AddCell(clNombre);

            clNombre                     = new PdfPCell(new Phrase("Precio Clase: ", fuente));
            clNombre.BorderWidth         = 0;
            clNombre.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
            tblPrueba.AddCell(clNombre);

            clNombre                     = new PdfPCell(new Phrase("Total: ", fuente));
            clNombre.BorderWidth         = 0;
            clNombre.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
            tblPrueba.AddCell(clNombre);

            clNombre                     = new PdfPCell(new Phrase("Estado:  ", fuente));
            clNombre.BorderWidth         = 0;
            clNombre.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
            tblPrueba.AddCell(clNombre);

            PdfContentByte cb = writer.DirectContent;

            cb.MoveTo(15, doc.Top - 94f);
            cb.LineTo(600, doc.Top - 94f);
            cb.Stroke();
            foreach (Reserva usu in listaReservaF)
            {
                // Configuramos el título de las columnas de la tabla

                //Contenido
                Font fuente2 = new Font();
                fuente2.Size = 8;

                Font fuente3 = new Font();
                fuente3.Size = 7;

                Font fuente4 = new Font();
                fuente4.Size = 6;

                clApellido                   = new PdfPCell(new Phrase(usu.Fecha, fuente2));
                clApellido.BorderWidth       = 0;
                clNombre.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                tblPrueba.AddCell(clApellido);


                clApellido                   = new PdfPCell(new Phrase(usu.NombreUsu, fuente2));
                clApellido.BorderWidth       = 0;
                clNombre.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                tblPrueba.AddCell(clApellido);


                clApellido                   = new PdfPCell(new Phrase(usu.IdEscuela, fuente2));
                clApellido.BorderWidth       = 0;
                clNombre.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                tblPrueba.AddCell(clApellido);


                clApellido                   = new PdfPCell(new Phrase(usu.Dificultad, fuente4));
                clApellido.BorderWidth       = 0;
                clNombre.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                tblPrueba.AddCell(clApellido);


                clApellido                   = new PdfPCell(new Phrase(usu.NombreIns, fuente2));
                clApellido.BorderWidth       = 0;
                clNombre.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                tblPrueba.AddCell(clApellido);

                clApellido                   = new PdfPCell(new Phrase(usu.Horainicio, fuente2));
                clApellido.BorderWidth       = 0;
                clNombre.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                tblPrueba.AddCell(clApellido);

                clApellido                   = new PdfPCell(new Phrase(usu.Marca, fuente2));
                clApellido.BorderWidth       = 0;
                clNombre.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                tblPrueba.AddCell(clApellido);

                clApellido                   = new PdfPCell(new Phrase(usu.Precioreserva.ToString(), fuente2));
                clApellido.BorderWidth       = 0;
                clNombre.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                tblPrueba.AddCell(clApellido);

                clApellido                   = new PdfPCell(new Phrase(usu.PrecioCl.ToString(), fuente2));
                clApellido.BorderWidth       = 0;
                clNombre.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                tblPrueba.AddCell(clApellido);

                clApellido                   = new PdfPCell(new Phrase(usu.PrecioTotal.ToString(), fuente2));
                clApellido.BorderWidth       = 0;
                clNombre.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                tblPrueba.AddCell(clApellido);

                clApellido                   = new PdfPCell(new Phrase(usu.Estado, fuente3));
                clApellido.BorderWidth       = 0;
                clNombre.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                tblPrueba.AddCell(clApellido);


                //linea
                PdfPCell linea = new PdfPCell(new Phrase(" ", fuente));
                linea.BorderWidth            = 0;
                clNombre.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                linea.Colspan = 11;
                tblPrueba.AddCell(linea);
            }
            doc.Add(tblPrueba);
            //
            //Font fuente4 = new Font();
            //fuente4.Size = 10;
            //tabla precio
            //PdfPTable tblPrecio = new PdfPTable(2);
            //tblPrueba.WidthPercentage = 50;
            ////
            //PdfPCell cldetalle = new PdfPCell(new Phrase("Lecciones:  ", fuente4));
            //cldetalle.BorderWidth = 0;
            //cldetalle.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;

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

            Response.ContentType     = "application/pdf";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.AppendHeader("content-disposition", "attachment;filename=ReporteReserva.pdf");
            // Response.TransmitFile("C:/Users/edu08/Downloads/prueba.pdf");
            Response.TransmitFile("C:/Users/Public/Downloads/prueba.pdf");
            Response.End();
        }
Exemplo n.º 34
0
        public void SaveToPDF(string iCreatePDFdir, string iCreatePDFTest, string txtContent, string NPPersianDate, string NewsPaperNo, string PageNumber, string SabtNumber, string SabtDate, string RefernceNumber, string LogoFile, string IndikatorNumber, string strNewsDate, string CompanySabtNumber, string CompanyNationalID)
        {
            Document     pdfDocCreatePDF = new Document();
            FileStream   myFileStream    = new FileStream(iCreatePDFTest, FileMode.Create);
            StreamReader FinalStream     = new StreamReader(myFileStream, Encoding.UTF8);

            PdfWriter.GetInstance(pdfDocCreatePDF, FinalStream.BaseStream);
            pdfDocCreatePDF.Open();
            //pdfDocCreatePDF.Add(new Paragraph(richTextBox1.Text));

            //FileStream myFileStream = new FileStream(iCreatePDFTest, FileMode.Create);
            pdfDocCreatePDF.Open();
            BaseFont fntBase = BaseFont.CreateFont("c:\\windows\\fonts\\bNazanin.ttf", BaseFont.IDENTITY_H, true);

            iTextSharp.text.Font fntWrite      = new iTextSharp.text.Font(fntBase, 10, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
            iTextSharp.text.Font fntWriteSmall = new iTextSharp.text.Font(fntBase, 10, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);


            PdfPTable table = new PdfPTable(6);

            table.DefaultCell.Border      = iTextSharp.text.Rectangle.NO_BORDER;
            table.DefaultCell.BorderWidth = 0;
            table.DefaultCell.BorderColor = iTextSharp.text.BaseColor.WHITE;
            table.RunDirection            = PdfWriter.RUN_DIRECTION_RTL;


            PdfPCell cell11 = new PdfPCell(new Phrase(2, "تاریخ انتشار: ", fntWriteSmall));

            cell11.Border       = iTextSharp.text.Rectangle.NO_BORDER;
            cell11.Padding      = 2;
            cell11.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
            table.AddCell(cell11);


            PdfPCell cellSabtDateVal = new PdfPCell(new Phrase(10, strNewsDate, fntWriteSmall));

            cellSabtDateVal.Border              = iTextSharp.text.Rectangle.NO_BORDER;
            cellSabtDateVal.Padding             = 4;
            cellSabtDateVal.RunDirection        = PdfWriter.RUN_DIRECTION_RTL;
            cellSabtDateVal.HorizontalAlignment = Element.ALIGN_LEFT;
            cellSabtDateVal.Colspan             = 5;
            table.AddCell(cellSabtDateVal);

            if (!string.IsNullOrEmpty(LogoFile))
            {
                iTextSharp.text.Image imageLogo = iTextSharp.text.Image.GetInstance(@"D:\IONS\WebApp\Files\News\Logos\" + LogoFile);
                imageLogo.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
                imageLogo.ScalePercent(50);
                PdfPCell cellLogo = new PdfPCell(imageLogo);
                cellLogo.Border = iTextSharp.text.Rectangle.NO_BORDER;
                cellLogo.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                cellLogo.VerticalAlignment   = PdfPCell.ALIGN_CENTER;
                cellLogo.Colspan             = 6;
                cellLogo.Padding             = 10;
                table.AddCell(cellLogo);
            }


            PdfPCell cellText = new PdfPCell(new Phrase(10, txtContent, fntWrite));

            cellText.Border  = iTextSharp.text.Rectangle.NO_BORDER;
            cellText.Padding = 10;
            cellText.Colspan = 6;
            table.AddCell(cellText);



            pdfDocCreatePDF.Add(table);

            //PdfWriter PDFWriter = PdfWriter.GetInstance(pdfDocCreatePDF, myFileStream);
            //PDFWriter.ViewerPreferences = PdfWriter.PageModeUseOutlines;
            //// Our custom Header and Footer is done using Event Handler
            //TwoColumnHeaderFooter PageEventHandler = new TwoColumnHeaderFooter();
            //PDFWriter.PageEvent = PageEventHandler;

            //// Define the page header
            //PageEventHandler.Title = "Test Title";
            //PageEventHandler.HeaderFont = FontFactory.GetFont(BaseFont.COURIER_BOLD, 10, Font.BOLD);
            //PageEventHandler.HeaderLeft = "Group";
            //PageEventHandler.HeaderRight = "1";


            pdfDocCreatePDF.Close();
        }
Exemplo n.º 35
0
        //Exportaciones

        #region Crea_Pdf

        public ActionResult GetPdf()
        {
            try
            {
                using (var ManNac = new EmpleadosEntities())
                {
                    var ListNac = ManNac.Nacionalidad.ToList();

                    MemoryStream ms = new MemoryStream();

                    iTextSharp.text.Document document = new iTextSharp.text.Document();
                    document.SetPageSize(PageSize.A4);
                    document.SetMargins(50, 50, 50, 50);

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

                    //agrega el autor del documento
                    document.AddAuthor("Rodrigo Menares Guzman");
                    // document.AddTitle("Listado_de_Cargos");

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

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

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

                    //creacion e insercion de titulos al documento
                    iTextSharp.text.Paragraph titulo = new iTextSharp.text.Paragraph(string.Format("Listado de Nacionalidades"), fontText2);
                    titulo.Alignment = 1; //0-Left, 1 middle,2 Right

                    //inserta al documento
                    document.Add(titulo);
                    //inserta nueva linea al texto
                    document.Add(iTextSharp.text.Chunk.NEWLINE);

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

                    iTextSharp.text.Font fontText3 = new iTextSharp.text.Font(bf2, 10, 0, BaseColor.WHITE);

                    // instancia la tabla y le indica la cantidad de columnas
                    PdfPTable table = new PdfPTable(2);
                    //indica q ancho de la hoja va a ocupar la tabla
                    table.WidthPercentage = 95;

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

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

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

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

                        _cell2 = new PdfPCell(new iTextSharp.text.Paragraph(item.Id_Nac.ToString(), fontText));
                        _cell2.HorizontalAlignment = Element.ALIGN_RIGHT;
                        table.AddCell(_cell2);

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

                    //agrega la tabla al documento
                    document.Add(table);

                    //cierra el documento
                    document.Close();

                    //vacia la memoria(documento) hacia memory stream
                    byte[] byteStream = ms.ToArray();
                    ms = new MemoryStream();
                    ms.Write(byteStream, 0, byteStream.Length);
                    ms.Position = 0;

                    //esto permite que el archivo pdf se muestre por pantalla en el explorador y a su vez sea guardado en el disco
                    return(File(ms, "application/pdf", "ListaNacionalidades.pdf"));
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Error On:", ex);
                Response.StatusCode        = 500;
                Response.StatusDescription = ex.Message;
                return(Json(Response));
            }
        }
Exemplo n.º 36
0
        public static void ReportBuilder(int cropYear, int contractNumber, string logoUrl, System.IO.FileStream fs)
        {
            const string METHOD_NAME             = "ReportBuilder";
            Document     document                = null;
            PdfWriter    writer                  = null;
            PdfPTable    table                   = null;
            ContractDeliverySummaryEvent pgEvent = null;

            iTextSharp.text.Image imgLogo = null;

            int contractID = 0;
            int stationNo  = 0;
            int factoryNo  = 0;

            int acresContracted = 0;
            int acresHarvested  = 0;
            int acresLost       = 0;
            int acresPlanted    = 0;

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

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

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

                    // Attach my override event handler(s)
                    pgEvent = new ContractDeliverySummaryEvent();
                    pgEvent.FillEvent(imgLogo, cropYear.ToString());
                    writer.PageEvent = pgEvent;

                    // Open the document
                    document.Open();
                }

                // =======================================================
                // Build Report
                // =======================================================

                int       staExSugar             = 0;
                int       ftyExSugar             = 0;
                decimal   extractableSugarPerTon = 0;
                PdfPTable addrTable = null;

                List <ContractGorwerLandownerItem> stateList = WSCReportsExec.ContractDeliverySummary1(cropYear, contractNumber);

                float[] addrLayout = new float[] { 9.3F, 67.6F, 23.1F };

                addrTable = PdfReports.CreateTable(addrLayout, 0);

                if (stateList.Count > 0)
                {
                    ContractGorwerLandownerItem item = stateList[0];

                    PdfReports.AddText2Table(addrTable, "Contract", _normalFont);
                    PdfReports.AddText2Table(addrTable,
                                             "Grower#: " + item.Gro_Address_Number, _normalFont);
                    PdfReports.AddText2Table(addrTable,
                                             "Landowner#: " + item.Ldo_Address_Number, _normalFont);

                    PdfReports.AddText2Table(addrTable, item.Contract_Number, _normalFont);

                    Paragraph p = PdfReports.GetAddressBlock(item.Grower_Name,
                                                             item.Gro_Address_1,
                                                             item.Gro_Address_2,
                                                             item.Grower_City + ", " +
                                                             item.Grower_State + " " +
                                                             item.Grower_Zip,
                                                             0F, 12F, iTextSharp.text.Element.ALIGN_LEFT, _uspsFont);
                    PdfReports.AddText2Table(addrTable, p);

                    p = PdfReports.GetAddressBlock(item.Landowner_Name,
                                                   item.Ldo_Address_1,
                                                   item.Ldo_Address_2,
                                                   item.Ldo_City + ", " +
                                                   item.Ldo_State + " " +
                                                   item.Ldo_Zip,
                                                   0F, 12F, iTextSharp.text.Element.ALIGN_LEFT, _normalFont);
                    PdfReports.AddText2Table(addrTable, p);

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

                    PdfReports.AddTableNoSplit(document, pgEvent, addrTable);

                    acresContracted = item.Contract_Acres;
                    acresHarvested  = item.Harvest_Acres;
                    acresPlanted    = item.Planted_Acres;
                    acresLost       = acresPlanted - acresHarvested;

                    contractID = item.cnt_contract_id;
                    stationNo  = Convert.ToInt32(item.Station_Number);
                    factoryNo  = Convert.ToInt32(item.Factory_Number);
                }

                table = PdfReports.CreateTable(_primaryTableLayout, 0);

                List <ContractDeliverySummary2Item> cntDelSumList = WSCReportsExec.ContractDeliverySummary2(contractID);

                if (cntDelSumList.Count > 0)
                {
                    ContractDeliverySummary2Item cntdsItem = cntDelSumList[0];

                    PdfReports.AddText2Table(table, "Contract Tons: " + cntdsItem.ContractTons.ToString("#,###.0000"),
                                             _normalFont, 3);
                    PdfReports.AddText2Table(table, "Contract % Sugar: " + cntdsItem.SugarPct.ToString("0.00") + "%",
                                             _normalFont, 3);
                    PdfReports.AddText2Table(table, "Contract % SLM: " + cntdsItem.SLMPct.ToString("0.0000") + "%",
                                             _normalFont, 3);

                    string tonsPerAcre = null;
                    if (acresHarvested == 0)
                    {
                        tonsPerAcre = String.Format("{0:#,##0.00}", 0);
                    }
                    else
                    {
                        tonsPerAcre = (cntdsItem.ContractTons / acresHarvested).ToString("#,###.00");
                    }
                    PdfReports.AddText2Table(table, "Tons Per Acre: " + tonsPerAcre, _normalFont, 3);

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

                    extractableSugarPerTon = cntdsItem.ExtractableSugarPerTon;
                    PdfReports.AddText2Table(table, "Pounds Extractable Sugar Per Ton Contract: " +
                                             extractableSugarPerTon.ToString("#,##0"),
                                             _normalFont, 3);
                }


                int factoryExtSugarAvg, stationExtSugarAvg;

                WSCReportsExec.FactoryStationGetExtractSugarAvg(factoryNo, stationNo, cropYear, out factoryExtSugarAvg, out stationExtSugarAvg);

                if (stationExtSugarAvg != 0)
                {
                    PdfReports.AddText2Table(table, "Pounds Extractable Sugar Per Ton Receiving Station: " +
                                             stationExtSugarAvg.ToString("#,##0"), _normalFont, 3);
                }

                if (factoryExtSugarAvg != 0)
                {
                    PdfReports.AddText2Table(table, "Pounds Extractable Sugar Per Ton Factory: " +
                                             factoryExtSugarAvg.ToString("#,##0"), _normalFont, 3);
                }

                string percentOfStation = String.Format("{0:##0.00}", 0);
                string percentOfFactory = String.Format("{0:##0.00}", 0);

                if (stationExtSugarAvg != 0)
                {
                    percentOfStation = String.Format("{0:##0.00}", (extractableSugarPerTon / stationExtSugarAvg) * 100);
                }
                if (factoryExtSugarAvg != 0)
                {
                    percentOfFactory = String.Format("{0:##0.00}", (extractableSugarPerTon / factoryExtSugarAvg) * 100);
                }

                PdfReports.AddText2Table(table, "Percent of Station: " +
                                         percentOfStation + "%", _normalFont, 3);

                PdfReports.AddText2Table(table, "Percent of Factory: " +
                                         percentOfFactory + "%", _normalFont, 3);

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

                PdfReports.AddText2Table(table, "Acres Contracted: " + acresContracted.ToString("#,##0"),
                                         _normalFont, 3);
                PdfReports.AddText2Table(table, "Acres Planted: " + acresPlanted.ToString("#,##0"),
                                         _normalFont, 3);
                PdfReports.AddText2Table(table, "Acres Lost: " + acresLost.ToString("#,##0"),
                                         _normalFont, 3);
                PdfReports.AddText2Table(table, "Acres Harvested: " + acresHarvested.ToString("#,##0"),
                                         _normalFont, 3);

                PdfReports.AddTableNoSplit(document, pgEvent, table);

                // ======================================================
                // Close document
                // ======================================================
                if (document != null)
                {
                    pgEvent.IsDocumentClosing = true;
                    document.Close();
                    document = null;
                }
                if (addrTable == null)
                {
                    // Warn that we have no data.
                    WSCIEMP.Common.CWarning warn = new WSCIEMP.Common.CWarning("No records matched your report criteria.");
                    throw (warn);
                }
            }
            catch (Exception ex) {
                string errMsg = "document is null: " + (document == null).ToString() + "; " +
                                "writer is null: " + (writer == null).ToString();
                WSCIEMP.Common.CException wscex = new WSCIEMP.Common.CException(METHOD_NAME + errMsg, ex);
                throw (wscex);
            }
            finally {
                if (document != null)
                {
                    pgEvent.IsDocumentClosing = true;
                    document.Close();
                }
                if (writer != null)
                {
                    writer.Close();
                }
            }
        }
Exemplo n.º 37
0
        public string GenerarPDF_Documento(bool Mostrar)
        {
            _ServerPath        = _Server.MapPath(".").Replace("\\Documentos", string.Empty);
            _tempFilePath      = string.Format("{0}\\PDFDocs\\tempPDF", _ServerPath);
            _ImagenApliredPath = string.Format("{0}\\LogosEmpresa\\LogoAplired.png", _ServerPath);

            try
            {
                if (!Directory.Exists(_tempFilePath))
                {
                    Directory.CreateDirectory(_tempFilePath);
                }

                long           IdDocumento     = long.Parse(Session["IdDocumento"].ToString());
                long           IdEmpresa       = long.Parse(Session["IdEmpresa"].ToString());
                long           IdUsuario       = long.Parse(Session["UserId"].ToString());
                long           IdTipoDocumento = long.Parse(Session["IdTipoDocumento"].ToString());
                eSystemModules Modulo          = (eSystemModules)IdTipoDocumento;
                string         TipoDocumento   = Modulo.ToString();
                string         NombreModulo    = string.Empty;

                if (GenerarArchivosTemporales())
                {
                    List <PdfReader> reader = new List <PdfReader>();
                    PdfImportedPage  page;
                    int rotation;
                    int i = 0;
                    int n = 0;
                    _TableOfContent  = new List <objContenido>();
                    _ActualPageWidth = PageSize.LETTER.Width;

                    using (Entities db = new Entities())
                    {
                        tblDocumento dataDocumento = (from d in db.tblDocumento
                                                      where d.IdEmpresa == IdEmpresa &&
                                                      d.IdDocumento == IdDocumento &&
                                                      d.IdTipoDocumento == IdTipoDocumento
                                                      select d).FirstOrDefault();

                        eEstadoDocumento EstadoDocumento = (eEstadoDocumento)dataDocumento.IdEstadoDocumento;

                        //string _docPassowrd = string.Format("BcmWeb_30.{0}.{1}", (dataDocumento.Negocios ? "N" : "T"), IdEmpresa.ToString("000"));
                        //string _ownerPassowrd = string.Format("{0}.{1}.{2}.BCMWEB", TipoDocumento, (dataDocumento.Negocios ? "N" : "T"), IdEmpresa.ToString("000"));
                        string _CodigoInforme = string.Format("{0}_{1}_{2}_{3}_{4}.{5}", TipoDocumento, IdEmpresa.ToString(), dataDocumento.NroDocumento.ToString("#000"), (EstadoDocumento == eEstadoDocumento.Certificado ? dataDocumento.FechaEstadoDocumento.ToString("MM-yyyy") : DateTime.Now.ToString("MM-yyyy")), dataDocumento.VersionOriginal, dataDocumento.NroVersion);
                        _FileName  = string.Format("{0}.pdf", _CodigoInforme.Replace("-", "_"));
                        _pathFile  = String.Format("{0}\\PDFDocs\\{1}", _ServerPath, _FileName);
                        _strDocURL = String.Format("{0}/PDFDocs/{1}", _AppUrl, _FileName);
                        string _LogoEmpresaPath = string.Format("{0}{1}", _ServerPath, dataDocumento.tblEmpresa.LogoURL.Replace("/", "\\").Replace("~", ""));

                        _ImagenEmpresa           = Image.GetInstance(_LogoEmpresaPath);
                        _ImagenEmpresa.Alignment = Element.ALIGN_CENTER;

                        if (File.Exists(_pathFile))
                        {
                            File.Delete(_pathFile);
                        }

                        string _pattern = string.Format("tmp{0}_{1}???_{2}*.pdf",
                                                        TipoDocumento,
                                                        IdEmpresa.ToString("000"),
                                                        dataDocumento.IdDocumento.ToString("000"));

                        List <string> _pdfFiles = Directory.GetFiles(_tempFilePath, _pattern,
                                                                     SearchOption.AllDirectories).OrderBy(q => q).ToList();

                        _Documento          = new Document();
                        _pdfWrite           = PdfWriter.GetInstance(_Documento, new FileStream(_pathFile, FileMode.Create));
                        _pdfWrite.PageEvent = _PDF_Events;
                        //_pdfWrite.SetEncryption(
                        //      System.Text.Encoding.UTF8.GetBytes(_docPassowrd)
                        //    , System.Text.Encoding.UTF8.GetBytes(_ownerPassowrd)
                        //    , PdfWriter.AllowPrinting
                        //    , PdfWriter.ENCRYPTION_AES_256);

                        string[] docKeywords = new string[]
                        {
                            _FileName,
                            dataDocumento.tblEmpresa.NombreComercial,
                            TipoDocumento,
                        };

                        _Documento.Open();
                        _Documento.AddAuthor("www.BcmWeb_30.net");
                        _Documento.AddCreator("www.BcmWeb_30.net");
                        _Documento.AddKeywords(string.Join(",", docKeywords));

                        int _PaginaInicioCapitulo = 1;
                        foreach (string _fileName in _pdfFiles)
                        {
                            List <string> _fileSplit = _fileName.Split('_').ToList();
                            long          _IdModulo  = long.Parse(_fileSplit.Last().Split('.').First());

                            tblModulo dataModulo = db.tblModulo.Where(x => x.IdEmpresa == IdEmpresa && x.IdModulo == _IdModulo).FirstOrDefault();

                            _TableOfContent.Add(new objContenido
                            {
                                Capitulo = dataModulo.Nombre,
                                Indent   = false,
                                Page     = _PaginaInicioCapitulo
                            });

                            reader.Add(new PdfReader(_fileName));
                            i = 0;
                            n = reader[reader.Count - 1].NumberOfPages;
                            while (i < n)
                            {
                                i++;
                                _Documento.SetPageSize(reader[reader.Count - 1].GetPageSizeWithRotation(i));
                                _Documento.NewPage();
                                page = _pdfWrite.GetImportedPage(reader[reader.Count - 1], i);
                                PdfContentByte cb = _pdfWrite.DirectContent;
                                rotation = reader[reader.Count - 1].GetPageRotation(i);
                                if (rotation == 90 || rotation == 270)
                                {
                                    cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, reader[reader.Count - 1].GetPageSizeWithRotation(i).Height);
                                }
                                else
                                {
                                    cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0);
                                }
                            }
                            _ActualPageWidth       = PageSize.LETTER.Width;
                            _PaginaInicioCapitulo += n;
                        }
                        long IdModuloPadre = IdTipoDocumento * 1000000;
                        NombreModulo = db.tblModulo.Where(x => x.IdEmpresa == IdEmpresa && x.IdModulo == IdModuloPadre).FirstOrDefault().Nombre;

                        GenerarIndice(NombreModulo);
                        _Documento.Close();
                        foreach (PdfReader _reader in reader)
                        {
                            _reader.Close();
                            _reader.Dispose();
                        }

                        if (Modulo == eSystemModules.PMI)
                        {
                            MoverDocumentosEscenarios(dataDocumento.Negocios, _CodigoInforme);
                        }

                        _pdfFiles = Directory.GetFiles(_tempFilePath, _pattern,
                                                       SearchOption.AllDirectories).OrderBy(q => q).ToList();

                        foreach (string _fileName in _pdfFiles)
                        {
                            File.Delete(_fileName);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //_Documento.Close();
                throw ex;
            }
            return(_strDocURL);
        }
Exemplo n.º 38
0
        public static byte[] ConvertToPdf(string fileName)
        {
            string       contentType = MimeMapping.GetMimeMapping(fileName);
            MemoryStream mem         = new MemoryStream();

            switch (contentType.ToLower())
            {
            case "image/gif":
            case "image/jpg":
            case "image/png":
            case "image/jpeg":
            case "application/BMP":
            case "image/bmp":
            case "image/tiff":
                if (!string.IsNullOrEmpty(fileName))
                {
                    Document document = new Document(PageSize.LETTER, 10, 10, 10, 10);
                    //using ( var stream = new MemoryStream() )
                    //{
                    PdfWriter.GetInstance(document, mem);

                    document.Open();
                    using (var imageStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        var image = Image.GetInstance(imageStream);
                        image.ScaleAbsolute(585, 750);
                        //image.ScaleAbsoluteHeight(PageSize.A4.Height - 20);
                        //image.ScaleToFit(PageSize.LETTER);

                        document.Add(image);
                    }
                    document.Close();

                    // return stream.ToArray();
                    //}
                }

                break;

            case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
            case "application/vnd.ms-excel":
            case "application/xlsx":
            case "application/xls":
            case "application/vnd.ms-excel.sheet.macroEnabled.12":
            case "application/XLSM":
                if (!string.IsNullOrEmpty(fileName))
                {
                    Spire.Xls.Workbook workbook = new Spire.Xls.Workbook();
                    workbook.LoadFromFile(fileName, true);
                    workbook.SaveToStream(mem, Spire.Xls.FileFormat.PDF);
                }

                break;

            case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
            case "application/msword":
            case "application/docx":
            case "application/doc":
                if (!string.IsNullOrEmpty(fileName))
                {
                    Spire.Doc.Document document = new Spire.Doc.Document();
                    document.LoadFromFile(fileName, Spire.Doc.FileFormat.Auto);
                    document.SaveToStream(mem, Spire.Doc.FileFormat.PDF);
                    document.Close();
                }

                break;

            case "application/html":
            case "application/txt":
            case "application/htm":
            case "text/html":
            case "application/xml":
            case "text/plain":
                if (!string.IsNullOrEmpty(fileName))
                {
                    Spire.Pdf.PdfDocument pdf = new Spire.Pdf.PdfDocument();
                    PdfHtmlLayoutFormat   htmlLayoutFormat = new PdfHtmlLayoutFormat
                    {
                        Layout          = PdfLayoutType.Paginate,
                        FitToPage       = Clip.Width,
                        LoadHtmlTimeout = 60 * 1000
                    };
                    htmlLayoutFormat.IsWaiting = true;
                    PdfPageSettings setting = new PdfPageSettings();
                    setting.Size = PdfPageSize.A4;
                    Thread thread = new Thread(() => { pdf.LoadFromHTML(fileName, true, true, true); });
                    thread.SetApartmentState(ApartmentState.STA);
                    thread.Start();
                    thread.Join();
                    pdf.SaveToStream(mem, Spire.Pdf.FileFormat.PDF);
                }
                break;

            case "application/msg":
            case "application/octet-stream":
            case "multipart/related":
            case "application/ZIP":
            case "application/VCF":
            default:
                break;
            }

            return(mem.ToArray());
        }
Exemplo n.º 39
0
        internal void SaveNewsToPDF(string iCreatePDFdir, string iCreatePDFTest, int Code, string Title, string NewsBody, string NewsNo, DateTime NewsDate)
        {
            Document     pdfDocCreatePDF = new Document();
            FileStream   myFileStream    = new FileStream(iCreatePDFTest, FileMode.Create);
            StreamReader FinalStream     = new StreamReader(myFileStream, Encoding.UTF8);

            PdfWriter.GetInstance(pdfDocCreatePDF, FinalStream.BaseStream);
            pdfDocCreatePDF.Open();

            //FileStream myFileStream = new FileStream(iCreatePDFTest, FileMode.Create);
            pdfDocCreatePDF.Open();
            BaseFont fntBase = BaseFont.CreateFont("c:\\windows\\fonts\\bNazanin.ttf", BaseFont.IDENTITY_H, true);

            iTextSharp.text.Font fntWrite      = new iTextSharp.text.Font(fntBase, 10, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
            iTextSharp.text.Font fntWriteBold  = new iTextSharp.text.Font(fntBase, 10, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);
            iTextSharp.text.Font fntWriteLarge = new iTextSharp.text.Font(fntBase, 14, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);


            PdfPTable table = new PdfPTable(2);

            table.DefaultCell.Border      = iTextSharp.text.Rectangle.NO_BORDER;
            table.DefaultCell.BorderWidth = 0;
            table.DefaultCell.BorderColor = iTextSharp.text.BaseColor.WHITE;
            table.RunDirection            = PdfWriter.RUN_DIRECTION_RTL;

            string LogoPath = "~/images/Site/PrintLogo.jpg";

            iTextSharp.text.Image imageLogo = iTextSharp.text.Image.GetInstance(HttpContext.Current.Request.MapPath(LogoPath));
            imageLogo.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
            imageLogo.ScalePercent(50);
            PdfPCell cellLogo = new PdfPCell(imageLogo);

            cellLogo.Border = iTextSharp.text.Rectangle.NO_BORDER;
            //cellLogo.CellEvent = 150;
            cellLogo.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
            cellLogo.VerticalAlignment   = PdfPCell.ALIGN_CENTER;
            cellLogo.Padding             = 2;
            table.AddCell(cellLogo);

            PdfPCell cellShata = new PdfPCell(new Phrase(10, "چند ثانیه", fntWriteLarge));

            cellShata.Border       = iTextSharp.text.Rectangle.NO_BORDER;
            cellShata.Padding      = 2;
            cellShata.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
            table.AddCell(cellShata);

            PdfPCell cellLine  = new PdfPCell();
            Chunk    linebreak = new Chunk(new LineSeparator(1f, 100f, BaseColor.GRAY, Element.ALIGN_CENTER, -1));

            cellLine.AddElement(linebreak);
            cellLine.Border  = iTextSharp.text.Rectangle.NO_BORDER;
            cellLine.Padding = 0;
            cellLine.Colspan = 2;
            table.AddCell(cellLine);

            PdfPCell cellTitle = new PdfPCell(new Phrase(10, Title, fntWriteBold));

            cellTitle.Border       = iTextSharp.text.Rectangle.NO_BORDER;
            cellTitle.Padding      = 2;
            cellTitle.Colspan      = 2;
            cellTitle.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
            table.AddCell(cellTitle);

            PdfPCell cellBody = new PdfPCell(new Phrase(0, NewsBody, fntWrite));

            cellBody.Border       = iTextSharp.text.Rectangle.NO_BORDER;
            cellBody.Padding      = 2;
            cellBody.Colspan      = 2;
            cellBody.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
            table.AddCell(cellBody);

            table.AddCell(cellLine);

            PdfPCell cellNewsNo = new PdfPCell(new Phrase(10, "کد خبر: " + NewsNo, fntWrite));

            cellNewsNo.Border       = iTextSharp.text.Rectangle.NO_BORDER;
            cellNewsNo.Padding      = 2;
            cellNewsNo.Colspan      = 2;
            cellNewsNo.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
            table.AddCell(cellNewsNo);

            DateTimeMethods dtm = new DateTimeMethods();

            PdfPCell cellNewsDate = new PdfPCell(new Phrase(10, dtm.GetPersianDate(NewsDate) + "تاریخ خبر: ", fntWrite));

            cellNewsDate.Border       = iTextSharp.text.Rectangle.NO_BORDER;
            cellNewsDate.Padding      = 2;
            cellNewsDate.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
            cellNewsDate.Colspan      = 2;
            table.AddCell(cellNewsDate);

            //PdfPCell cellNewsDateVal = new PdfPCell(new Phrase(10, dtm.GetPersianDate(NewsDate), fntWrite));
            //cellNewsDateVal.Border = iTextSharp.text.Rectangle.NO_BORDER;
            //cellNewsDateVal.Padding = 2;
            //cellNewsDateVal.HorizontalAlignment = Element.ALIGN_RIGHT;
            //cellNewsDateVal.RunDirection = PdfWriter.RUN_DIRECTION_LTR;
            //table.AddCell(cellNewsDateVal);



            pdfDocCreatePDF.Add(table);
            pdfDocCreatePDF.Close();
        }
Exemplo n.º 40
0
        public void FillEvent(TransmittalPaymentItem payItem, int cropYear, string statementDate, int pageNumber, string title, string paymentDescription, iTextSharp.text.Image imgLogo)
        {
            _paymentDesc = paymentDescription;
            _cropYear = cropYear.ToString();
            if (statementDate.Length > 0) {
                _statementDate = DateTime.Parse(statementDate).ToString("MMMM dd, yyyy");
            } else {
                _statementDate = statementDate;
            }

            _growerName = payItem.Business_Name;
            _adr1 = payItem.Address_1;
            _adr2 = payItem.Address_2;
            _city = payItem.City;
            _state = payItem.State;
            _postalCode = payItem.Zip;
            _contractNumber = payItem.Contract_Number;
            _factoryName = payItem.Factory_Name;
            _stationName = payItem.Station_Name;
            _pageNumber = pageNumber;
            _title = title;
            _imgLogo = imgLogo;
        }
Exemplo n.º 41
0
 public void FillEvent(iTextSharp.text.Image imgLogo, string cropYear)
 {
     _imgLogo  = imgLogo;
     _cropYear = cropYear;
 }
Exemplo n.º 42
0
        /// <summary>
        /// This method create the image on the base of the byte array
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public iTextSharp.text.Image GetImage(byte[] data)
        {
            image = iTextSharp.text.Image.GetInstance(byteArrayToImage1(data), System.Drawing.Imaging.ImageFormat.Jpeg);

            image.ScalePercent(200);

            return image;
        }
Exemplo n.º 43
0
        public string GenerarCredencial()
        {
            string fileName = string.Empty;

            #region iniciandoDocumento
            doc.AddAuthor("CODESUR");
            doc.AddKeywords("pdf, PdfWriter; Documento; iTextSharp");
            fileName = string.Format("CredencialAcreditacion_{0}_{1:yyyyMMddHHss}.pdf", Usuario, DateTime.Now);
            string path = PathResources;
            path = string.Format("{0}Reportes\\{1}", path, fileName);
            PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(path, FileMode.Create));
            doc.Open();
            #endregion
            try
            {
                AgregarFondoAnverso();
                AgregarFoto();
                AgregarQR();
                AgregarCodigoRol();
                AgregarNombre();
                AgregarDatosDelegacion();
                AgregarPrivilegios();
                AgregarFondoReverso();
                AgregarCodigoBarras(wri);
                AgregarTextoFoto();
                AgregarNombreReverso();
                AgregarPrivilegiosReverso();
                PdfContentByte cb = wri.DirectContent;
                //PdfPTable table = new PdfPTable(1);
                ////PdfPCell[] cells = new PdfPCell[] { new PdfPCell(new Phrase("HOLAAA"))};
                ////PdfPRow p = new PdfPRow(cells);
                ////p.
                //table.TotalWidth = 400f;
                //table.AddCell("Test");
                //table.WriteSelectedRows(0, -1, 200, 50, cb);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                doc.Close();
            }
            Spire.License.LicenseProvider.SetLicenseFileFullPath(@"C:\Hammer\ExternalReferences\license.lic");
            Spire.Pdf.PdfDocument pdfdocument = new Spire.Pdf.PdfDocument();
            try
            {
                pdfdocument.LoadFromFile(path);
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                Document  realDoc = new Document(new Rectangle(566f, 454f), 0f, 0f, 0f, 0f);
                PdfPTable Reporte = new PdfPTable(new float[] { 283f, 283f });
                Reporte.WidthPercentage = 100;
                for (int i = 0; i < pdfdocument.Pages.Count; i++)
                {
                    System.Drawing.Image image = pdfdocument.SaveAsImage(i, 480, 500);
                    MemoryStream         ms    = new MemoryStream();
                    image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                    iTextSharp.text.Image imgpdf = iTextSharp.text.Image.GetInstance(ms.ToArray());
                    PdfPCell imgCell             = new PdfPCell(imgpdf, true);
                    Reporte.AddCell(imgCell);
                }
                PdfWriter realWri = PdfWriter.GetInstance(realDoc, new FileStream(path, FileMode.Create));
                realDoc.Open();
                realDoc.Add(Reporte);


                realDoc.Close();
            }
            catch
            {
            }
            return(path);
        }
Exemplo n.º 44
0
        public void FillEvent(ListNoticeOfPassthrough state, int pageNumber, string title, iTextSharp.text.Image imgLogo)
        {
            _statementDate = state.ReportDate.ToString("MMMM dd, yyyy");

            _memberName = state.MemberName;
            _adr1 = state.AdrLine1;
            _adr2 = state.AdrLine2;
            _city = state.AdrCity;
            _state = state.AdrState;
            _postalCode = state.AdrZip;
            _pageNumber = pageNumber;
            _title = title;
            _imgLogo = imgLogo;
        }
        public override void OnStartPage(PdfWriter writer, Document document)
        {
            PdfContentByte cb = writer.DirectContent;

            cb.AddTemplate(pdfPage1, 0, 0);

            BaseFont fDetB = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            BaseFont fDet = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

            iTextSharp.text.Image imgEmpresa = iTextSharp.text.Image.GetInstance(strMapPath + strLogoEmpresa);
            imgEmpresa.SetAbsolutePosition(45, 700);
            imgEmpresa.ScalePercent(flEscala, flEscala);
            document.Add(imgEmpresa);

            StringBuilder strTemp = new StringBuilder();

            //          -------------------------- urx, ury
            //          |                        |
            //          |                        |
            //          |                        |
            //          |________________________|
            //       llx, lly

            //Dibujar linea para ver de donde a donde es
            //cb.MoveTo(50, 550);  
            //cb.LineTo(360, 660);
            //cb.Stroke();

            ColumnText ct = new ColumnText(cb);
            ct.SetSimpleColumn(new Phrase(new Chunk(strRazonSocial,
                                                    FontFactory.GetFont(BaseFont.HELVETICA_BOLD, 8))),
                                                    150, 700, 410, 744, 10, Element.ALIGN_LEFT);
            ct.Go();

            strTemp.Clear();
            //strTemp.Append(objDirEmisor.Direccion_Lineas_SinPais);
            strTemp.Append(objDirEmisor.Direccion_Lineas);
            strTemp.Append(" RFC: " + CRutinas.RFC_Guiones(strRFC));
            if (!string.IsNullOrEmpty(strTelefono))
                strTemp.Append("\nTel. " + strTelefono);
            if (!string.IsNullOrEmpty(strEmail))
                strTemp.Append("\nEmail: " + strEmail);
            ct = new ColumnText(cb);
            ct.SetSimpleColumn(new Phrase(new Chunk(strTemp.ToString(),
                                                    FontFactory.GetFont(BaseFont.HELVETICA, 7))),
                                                    150, 600, 390, 730, 10, Element.ALIGN_LEFT);
            ct.Go();

            ct = new ColumnText(cb);
            ct.SetSimpleColumn(new Phrase(new Chunk(strNota,
                                                    FontFactory.GetFont(BaseFont.HELVETICA, 10))),
                                                    425, 720, 567, 740, 10, Element.ALIGN_CENTER);
            ct.Go();


            ct = new ColumnText(cb);
            ct.SetSimpleColumn(new Phrase(new Chunk(dtFecha.ToString("dd"),
                                                    FontFactory.GetFont(BaseFont.HELVETICA, 8))),
                                                    425, 670, 472, 685, 10, Element.ALIGN_CENTER);
            ct.Go();

            ct = new ColumnText(cb);
            ct.SetSimpleColumn(new Phrase(new Chunk(dtFecha.ToString("MM"),
                                                    FontFactory.GetFont(BaseFont.HELVETICA, 8))),
                                                    472, 670, 519, 685, 10, Element.ALIGN_CENTER);
            ct.Go();

            ct = new ColumnText(cb);
            ct.SetSimpleColumn(new Phrase(new Chunk(dtFecha.ToString("yyyy"),
                                                    FontFactory.GetFont(BaseFont.HELVETICA, 8))),
                                                    519, 670, 567, 685, 10, Element.ALIGN_CENTER);
            ct.Go();

            strTemp.Clear();
            strTemp.Append(strCliente + "\n");
            strTemp.Append(objDirReceptor.Direccion_Lineas + "\n");
            strTemp.Append("RFC: " + CRutinas.RFC_Guiones(strClienteRFC) + "\n");

            ct = new ColumnText(cb);
            ct.SetSimpleColumn(new Phrase(new Chunk(strTemp.ToString(),
                                                    FontFactory.GetFont(BaseFont.HELVETICA, 7))),
                                                    50, 550, 315, 645, 10, Element.ALIGN_LEFT);
            ct.Go();

            ct = new ColumnText(cb);
            ct.SetSimpleColumn(new Phrase(new Chunk(objEnvio.Direccion_Lineas,
                                                    FontFactory.GetFont(BaseFont.HELVETICA, 7))),
                                                    310, 550, 567, 645, 10, Element.ALIGN_LEFT);
            ct.Go();

            ct = new ColumnText(cb);
            ct.SetSimpleColumn(new Phrase(new Chunk(strContacto,
                                                    FontFactory.GetFont(BaseFont.HELVETICA, 7))),
                                                    310, 500, 567, 575, 10, Element.ALIGN_LEFT);
            ct.Go();

            ct = new ColumnText(cb);
            ct.SetSimpleColumn(new Phrase(new Chunk(strOrdenCompra,
                                                    FontFactory.GetFont(BaseFont.HELVETICA, 7))),
                                                    150, 500, 300, 560, 10, Element.ALIGN_LEFT);
            ct.Go();

            ct = new ColumnText(cb);
            ct.SetSimpleColumn(new Phrase(new Chunk(strNumeroCliente,
                                                    FontFactory.GetFont(BaseFont.HELVETICA, 7))),
                                                    365, 500, 567, 560, 10, Element.ALIGN_LEFT);
            ct.Go();

            ct = new ColumnText(cb);
            ct.SetSimpleColumn(new Phrase(new Chunk(strCotizacion,
                                                    FontFactory.GetFont(BaseFont.HELVETICA, 7))),
                                                    150, 500, 300, 546, 10, Element.ALIGN_LEFT);
            ct.Go();

            ct = new ColumnText(cb);
            ct.SetSimpleColumn(new Phrase(new Chunk(strEjecutivoVentas,
                                                    FontFactory.GetFont(BaseFont.HELVETICA, 7))),
                                                    400, 500, 567, 546, 10, Element.ALIGN_LEFT);
            ct.Go();

            strTemp.Clear();
            strTemp.Append("SUBTOTAL:\n\n");
            if (dcmDescuento != 0)
                strTemp.Append("SUBTOTAL CON DESCUENTO:\n\n");
            strTemp.Append("IVA:\n\n");
            strTemp.Append("TOTAL:");
            ct = new ColumnText(cb);
            ct.SetSimpleColumn(new Phrase(new Chunk(strTemp.ToString(),
                                                    FontFactory.GetFont(BaseFont.HELVETICA_BOLD, 7))),
                                                    410, 40, 490, 120, 10, Element.ALIGN_RIGHT);
            ct.Go();

            strTemp.Clear();
            strTemp.Append(dcmSubtotal.ToString("c") + " " + strMoneda + "\n\n");
            if (dcmDescuento != 0)
                strTemp.Append(dcmDescuento.ToString("c") + " " + strMoneda + "\n\n");
            strTemp.Append(dcmIVA.ToString("c") + " " + strMoneda + "\n\n");
            strTemp.Append(dcmTotal.ToString("c") + " " + strMoneda + "");
            ct = new ColumnText(cb);
            ct.SetSimpleColumn(new Phrase(new Chunk(strTemp.ToString(),
                                                    FontFactory.GetFont(BaseFont.HELVETICA_BOLD, 7))),
                                                    490, 40, 566, 120, 10, Element.ALIGN_RIGHT);
            ct.Go();

            cb.BeginText();
            cb.SetFontAndSize(fDet, 7);
            cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "Hoja " + writer.PageNumber + " de " + intTotalPaginas, 580, 20, 0);
            cb.EndText();
        }
Exemplo n.º 46
0
        public void FillEvent(SHPaySumListItem item, int cropYear, string statementDate,
            int pageNumber, string title, iTextSharp.text.Image imgLogo)
        {
            _paymentDesc = item.s_PaymentDesc;
            _cropYear = cropYear.ToString();

            if (statementDate != null && statementDate.Length > 0) {
                _statementDate = DateTime.Parse(statementDate).ToString("MMMM dd, yyyy");
            } else {
                _statementDate = "";
            }

            _growerName = item.s_PayeeName;
            _adr1 = item.s_Address1;
            _adr2 = item.s_Address2;
            _city = item.s_City;
            _state = item.s_State;
            _postalCode = item.s_PostalCode;
            _shid = item.i_SHID.ToString();
            _checkAmount = item.d_checkAmount;
            _pageNumber = pageNumber;
            _title = title;
            _imgLogo = imgLogo;
        }
Exemplo n.º 47
0
        public override void OnStartPage(PdfWriter writer, Document document)
        {
            base.OnStartPage(writer, document);

            if (SameGroup())
            {
                AddPageNo();
            }
            else
            {
                template.BeginText();
                template.SetFontAndSize(BF_Light, ContentFontSize);
                template.SetTextMatrix(0, 0);
                template.ShowText("" + (CurrentPage.ToString()));
                template.EndText();

                //new start
                ResetPage();
                AddPageNo();
                GroupIdentity = CurrentGroup;
                template      = cb.CreateTemplate(50, 50);
            }

            //float linePosition = 115f;
            if ((!printCode) && (hData.PRINT_LOGO == CHubConstValues.IndN))
            {
                //document.Add(new Paragraph(Environment.NewLine));
                //document.Add(new Paragraph(Environment.NewLine));
                //document.Add(new Paragraph(Environment.NewLine));
                if (document.PageSize.Height > 500f)
                {
                    document.Add(new Paragraph(Environment.NewLine));
                    document.Add(new Paragraph(Environment.NewLine));
                }
                //else
                //    linePosition = 70f;
            }
            else
            {
                PdfPTable hTable = new PdfPTable(1);
                hTable.WidthPercentage = 100f;

                PdfPCell hUnit = new PdfPCell();

                /////

                #region for adding header part for each page

                PdfPTable imgTable = new PdfPTable(5);
                imgTable.WidthPercentage = 100f;
                //empty  / wechat /empty  /qrcode
                imgTable.SetWidths(new float[] { 100f, 245f, 120f, 12f, 120f });//215f, 75f, 200f, 85f
                imgTable.HorizontalAlignment = Element.ALIGN_RIGHT;
                PdfPCell imgCell;

                //logo2 part
                if (printCode && !string.IsNullOrEmpty(hData.LOGO2))
                {
                    string logo2Path = BasePath.Replace("temp", "images") + hData.LOGO2;
                    iTextSharp.text.Image Logo2Image = iTextSharp.text.Image.GetInstance(logo2Path);
                    Logo2Image.Alignment = Element.ALIGN_LEFT;
                    imgCell = new PdfPCell(Logo2Image, true);
                    imgCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                }
                else
                {
                    imgCell = new PdfPCell();
                }

                imgCell.BorderWidth = 0;
                imgTable.AddCell(imgCell);

                //title part
                if (printCode && !string.IsNullOrEmpty(hData.TITLE))
                {
                    Paragraph p1 = new Paragraph(hData.TITLE, new iTextSharp.text.Font(BF_Light, TitleFontSize));

                    imgCell = new PdfPCell(p1);
                }
                else
                {
                    imgCell = new PdfPCell();
                }

                imgCell.HorizontalAlignment = Element.ALIGN_CENTER;
                imgCell.VerticalAlignment   = Element.ALIGN_MIDDLE;
                imgCell.BorderWidth         = 0;
                imgTable.AddCell(imgCell);


                if (hData.PRINT_LOGO == CHubConstValues.IndY)
                {
                    string wechartPath = BasePath.Replace("temp", "images") + (hData.LOGO ?? "wechat.jpg");
                    iTextSharp.text.Image wechatImage = iTextSharp.text.Image.GetInstance(wechartPath);
                    wechatImage.Alignment = Element.ALIGN_RIGHT;
                    imgCell = new PdfPCell(wechatImage, true);
                    imgCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                }
                else
                {
                    imgCell = new PdfPCell();
                }

                imgCell.BorderWidth = 0;
                imgTable.AddCell(imgCell);

                //margin between two pictures
                imgCell             = new PdfPCell();
                imgCell.BorderWidth = 0;
                imgTable.AddCell(imgCell);

                if (printCode)
                {
                    iTextSharp.text.Image tImg = iTextSharp.text.Image.GetInstance(QRPath);
                    tImg.Alignment = Element.ALIGN_RIGHT;
                    imgCell        = new PdfPCell(tImg, true);
                    imgCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                }
                else
                {
                    imgCell = new PdfPCell();
                }

                imgCell.BorderWidth = 0;
                imgTable.AddCell(imgCell);

                hUnit.AddElement(imgTable);

                if (printCode)
                {
                    Paragraph p1 = new Paragraph(codeString, new iTextSharp.text.Font(BF_Light, CodeFontSize));
                    p1.Alignment = Element.ALIGN_RIGHT;
                    hUnit.AddElement(p1);
                }

                //Paragraph p2 = new Paragraph(line1String, new iTextSharp.text.Font(BF_Light, HeaderFontSize));
                //hUnit.AddElement(p2);
                //hUnit.AddElement(new Paragraph(Environment.NewLine));

                hUnit.BorderWidth = 0;
                hTable.AddCell(hUnit);
                document.Add(hTable);

                #endregion
            }

            //add a line  -- no need for now
            //cb.MoveTo(0, document.PageSize.Height - linePosition);
            //cb.LineTo(document.PageSize.Width, document.PageSize.Height - linePosition);
            //cb.SetLineWidth(0.5f);
            //cb.Stroke();

            document.Add(new Paragraph(Environment.NewLine));
            Paragraph p2 = new Paragraph(line1String, new iTextSharp.text.Font(BF_Light, HeaderFontSize));
            document.Add(p2);

            //content table
            PdfPTable contentTable = new PdfPTable(4);
            contentTable.WidthPercentage = 100f;
            contentTable.SetWidths(new float[] { 215f, 70f, 205f, 85f });
            PdfPCell cellUnit;

            Paragraph p11 = new Paragraph();
            p11.Add(new Phrase(string.Format("{0}    {1}", hData.NOTE1, hData.FLEX1), new iTextSharp.text.Font(BF_Light, ContentFontSize)));
            p11.Add(System.Environment.NewLine);
            p11.Add(new Phrase(string.Format("{0}    {1}", hData.COMPANY, hData.SENDER), new iTextSharp.text.Font(BF_Light, ContentFontSize)));
            p11.Add(System.Environment.NewLine);
            p11.Add(new Phrase(string.Format("{0}", hData.ADDRESS), new iTextSharp.text.Font(BF_Light, ContentFontSize)));
            p11.Add(System.Environment.NewLine);
            p11.Add(new Phrase(string.Format("{0}    {1}", hData.CONTACT, hData.TELEPHONE), new iTextSharp.text.Font(BF_Light, ContentFontSize)));
            p11.Add(System.Environment.NewLine);
            p11.Add(System.Environment.NewLine);


            cellUnit             = new PdfPCell(p11);
            cellUnit.BorderWidth = 0;
            contentTable.AddCell(cellUnit);

            //wechat imag p12
            //if (hData.PRINT_LOGO == CHubConstValues.IndY)
            //{
            //    string imagePath = BasePath.Replace("temp", "images") + (hData.LOGO?? "wechat.jpg");
            //    iTextSharp.text.Image logoImage = iTextSharp.text.Image.GetInstance(imagePath);
            //    cellUnit = new PdfPCell(logoImage, true);
            //}
            //else
            //{
            //    cellUnit = new PdfPCell();
            //}
            cellUnit             = new PdfPCell();
            cellUnit.BorderWidth = 0;
            contentTable.AddCell(cellUnit);


            Paragraph p13 = new Paragraph();
            p13.Add(new Phrase(string.Format("{0}    {1}", hData.NOTE2, hData.FLEX2), new iTextSharp.text.Font(BF_Light, ContentFontSize)));
            p13.Add(System.Environment.NewLine);
            p13.Add(new Phrase(string.Format("{0}    {1}", hData.R_ADRNAM, hData.R_ADRCTY), new iTextSharp.text.Font(BF_Light, ContentFontSize)));
            p13.Add(System.Environment.NewLine);
            p13.Add(new Phrase(string.Format("{0}", hData.R_ADRLN1), new iTextSharp.text.Font(BF_Light, ContentFontSize)));
            p13.Add(System.Environment.NewLine);
            p13.Add(new Phrase(string.Format("{0}    {1}", hData.R_ADRLN2, hData.R_ADRLN3), new iTextSharp.text.Font(BF_Light, ContentFontSize)));
            p13.Add(System.Environment.NewLine);
            p13.Add(new Phrase(string.Format("{0}    {1}", hData.R_LAST_NAME, hData.R_PHNNUM), new iTextSharp.text.Font(BF_Light, ContentFontSize)));
            p13.Add(System.Environment.NewLine);

            cellUnit             = new PdfPCell(p13);
            cellUnit.BorderWidth = 0;
            contentTable.AddCell(cellUnit);

            //p14 signature part
            Paragraph p14 = new Paragraph();
            p14.Add(System.Environment.NewLine);
            p14.Add(System.Environment.NewLine);
            p14.Add(System.Environment.NewLine);
            p14.Add(new Phrase(string.Format("{0}", hData.SIGNATURE3), new iTextSharp.text.Font(BF_Light, ContentFontSize)));
            p14.Add(System.Environment.NewLine);

            cellUnit             = new PdfPCell(p14);
            cellUnit.BorderWidth = 0;
            contentTable.AddCell(cellUnit);


            //Line 2 cells
            Paragraph p21 = new Paragraph();
            p21.Add(new Phrase(string.Format("{0}    {1}", hData.NOTE3, hData.FLEX3), new iTextSharp.text.Font(BF_Light, ContentFontSize)));
            p21.Add(System.Environment.NewLine);
            p21.Add(new Phrase(string.Format("{0}    {1}", hData.L_ADRNAM, hData.L_ADRCTY), new iTextSharp.text.Font(BF_Light, ContentFontSize)));
            p21.Add(System.Environment.NewLine);
            p21.Add(new Phrase(string.Format("{0}", hData.L_ADRLN1), new iTextSharp.text.Font(BF_Light, ContentFontSize)));
            p21.Add(System.Environment.NewLine);
            p21.Add(new Phrase(string.Format("{0}    {1}", hData.L_ADRLN2, hData.L_ADRLN3), new iTextSharp.text.Font(BF_Light, ContentFontSize)));
            p21.Add(System.Environment.NewLine);
            p21.Add(new Phrase(string.Format("{0}    {1}", hData.L_LAST_NAME, hData.L_PHNNUM), new iTextSharp.text.Font(BF_Light, ContentFontSize)));
            p21.Add(System.Environment.NewLine);
            p21.Add(System.Environment.NewLine);

            p21.Add(new Phrase(string.Format("{0}    {1}", hData.NOTE4, hData.FLEX4), new iTextSharp.text.Font(BF_Light, ContentFontSize)));
            p21.Add(System.Environment.NewLine);
            p21.Add(new Phrase(string.Format("{0}", hData.SIGNATURE1), new iTextSharp.text.Font(BF_Light, ContentFontSize)));
            p21.Add(System.Environment.NewLine);


            cellUnit             = new PdfPCell(p21);
            cellUnit.BorderWidth = 0;
            contentTable.AddCell(cellUnit);

            //line 2 mid empty cell
            cellUnit             = new PdfPCell();
            cellUnit.BorderWidth = 0;
            contentTable.AddCell(cellUnit);

            //2-3  empty cell
            cellUnit             = new PdfPCell();
            cellUnit.BorderWidth = 0;
            contentTable.AddCell(cellUnit);

            //p24 signature part
            Paragraph p24 = new Paragraph();
            p24.Add(System.Environment.NewLine);
            p24.Add(System.Environment.NewLine);
            p24.Add(System.Environment.NewLine);
            p24.Add(System.Environment.NewLine);
            p24.Add(new Phrase(string.Format("{0}", hData.SIGNATURE3), new iTextSharp.text.Font(BF_Light, ContentFontSize)));

            cellUnit             = new PdfPCell(p24);
            cellUnit.BorderWidth = 0;
            contentTable.AddCell(cellUnit);


            document.Add(contentTable);

            document.Add(new Paragraph(Environment.NewLine));
        }
Exemplo n.º 48
0
        public void FillEvent(int cropYear, string shid, string busName, string rptTitle, string regionName, string areaName, iTextSharp.text.Image imgLogo)
        {
            if (_shid == 0) {
                _lastShid = Convert.ToInt32(shid);
                _lastAreaName = areaName;
            }

            _cropYear = cropYear;
            _shid = Convert.ToInt32(shid);
            _busName = busName;
            _rptTitle = rptTitle;
            _regionName = regionName;
            _areaName = areaName;
            _imgLogo = imgLogo;
        }
Exemplo n.º 49
0
		/// <summary>
		/// Draw page background image.
		/// </summary>
		internal void DrawBackgroundImage()
		{
			if(_backgroundImage == null)return;
			try{
				iTextSharp.text.Image imageToDraw = null;
				
				if(_backgroundImageCache == null){
					
					iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(_backgroundImage.Source);
					if(img == null){
						Console.WriteLine("Image its null. Don't draw it.");
						return;
					}
					
					float docAvailableW = (pageSize.Width - (_backgroundImage.UseDocMargins?(Margin_right + Margin_left):0F) );
					float docAvailableH = (pageSize.Height - (_backgroundImage.UseDocMargins?(Margin_top + Margin_bottom):0F) );
					
					//process dim if scale to fit
					if( (img.Width > docAvailableW ||img.Height > docAvailableH) && _backgroundImage.ScaleToFit ){
						
						float imgAspectRatio = img.Width / img.Height; //aspect ratio for resize
						float docAspectRatio = docAvailableW / docAvailableH; //document aspect ratio
						
						//control
						if(imgAspectRatio > docAspectRatio){
							// width it's the reference
							img.ScaleToFit(docAvailableW , (docAvailableW / imgAspectRatio )); //included footer, mantain aspect ratio
						}
						else{
							// height it's the reference
							img.ScaleToFit((docAvailableH * imgAspectRatio), docAvailableH); //included footer, mantain aspect ratio
						}
					}
					
					//to debug
//					img.Border= iTextSharp.text.Rectangle.BOTTOM_BORDER | iTextSharp.text.Rectangle.LEFT_BORDER | iTextSharp.text.Rectangle.RIGHT_BORDER | iTextSharp.text.Rectangle.TOP_BORDER;
//					img.BorderColor = BaseColor.BLACK;
//					img.BorderWidth = 2;
					img.Alignment = iTextSharp.text.Image.ALIGN_TOP | iTextSharp.text.Image.ALIGN_LEFT;
					
					//position
					// SetAbsolute uses x document value without margins and botton y diff value.
					switch(_backgroundImage.ImageAligment){
							
						case BackgroundImageDefinition.Alignment.Center:
							img.SetAbsolutePosition( ((pageSize.Width  - img.ScaledWidth) /2) , (docAvailableH - img.ScaledHeight) /2 );
							break;
							
						case BackgroundImageDefinition.Alignment.TopLeft:
							img.SetAbsolutePosition( (_backgroundImage.UseDocMargins?Margin_left:0F), docAvailableH - img.ScaledHeight);
							break;
							
						case BackgroundImageDefinition.Alignment.TopRight:
							img.SetAbsolutePosition( pageSize.Width - (_backgroundImage.UseDocMargins?Margin_right:0F) - img.ScaledWidth , docAvailableH - img.ScaledHeight );
							break;
							
						case BackgroundImageDefinition.Alignment.TopCenter:
							//float docWMiddle = (pageSize.Width - Margin_right - Margin_left) / 2;
							img.SetAbsolutePosition(  (((pageSize.Width  - img.ScaledWidth ) / 2) /*+  (_backgroundImage.UseDocMargins?Margin_left:0F)*/ ) , (docAvailableH - img.ScaledHeight) );
							break;
							
						default:
							img.SetAbsolutePosition( 0, 0 );
							break;
					}
					
					// common attributes
					img.Alignment = iTextSharp.text.Image.UNDERLYING; //behind
					
					if(UseCachedBackgroundImage){
						_backgroundImageCache = img;
					}
					
					
					imageToDraw = img;
					
				}
				else{
					imageToDraw = _backgroundImageCache;
				}
				
				
				if(imageToDraw != null){
					iPDFContent.AddImage(imageToDraw);
				}
				
			}catch(Exception ex){
				Console.WriteLine(ex.ToString());
			}
		}
Exemplo n.º 50
0
        protected void Save_Click(object sender, EventArgs e)
        {
            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                Document document = new Document(PageSize.A4, 10, 10, 10, 10);

                PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
                document.Open();

                String logo = "pic/logo_back.png";
                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(logo);
                img.Alignment = Element.ALIGN_LEFT;
                img.ScaleToFit(205f, 205f);
                document.Add(img);
                document.Add(new Paragraph(" "));

                Paragraph title = new Paragraph("VAT Return Form for The period: " + home.firstDate.Date + " To " + home.lastDate.Date);
                title.Alignment = Element.ALIGN_CENTER;
                document.Add(title);
                document.Add(new Paragraph(" "));
                document.Add(new Paragraph(" "));
                document.Add(new Paragraph(" "));

                PdfPTable table = new PdfPTable(5);

                //set width of the table
                table.TotalWidth  = (float)((PageSize.A4.Width / 2) * 1.7);
                table.LockedWidth = true;
                //set table alignment
                table.HorizontalAlignment = Element.ALIGN_CENTER;

                //create a cell objects and set their properties
                PdfPCell cell1 = new PdfPCell(new Phrase(" "));
                cell1.HorizontalAlignment = Element.ALIGN_CENTER;
                cell1.BackgroundColor     = BaseColor.LIGHT_GRAY;


                PdfPCell amount = new PdfPCell(new Phrase("Amount (SAR)"));
                amount.HorizontalAlignment = Element.ALIGN_CENTER;
                amount.BackgroundColor     = BaseColor.LIGHT_GRAY;
                amount.Padding             = 5;
                amount.HorizontalAlignment = Element.ALIGN_CENTER;

                PdfPCell adjusment = new PdfPCell(new Phrase("Adjustment (SAR)"));
                adjusment.HorizontalAlignment = Element.ALIGN_CENTER;
                adjusment.BackgroundColor     = BaseColor.LIGHT_GRAY;
                adjusment.Padding             = 5;
                adjusment.HorizontalAlignment = Element.ALIGN_CENTER;

                PdfPCell vat = new PdfPCell(new Phrase("VAT Amount (SAR)"));
                vat.HorizontalAlignment = Element.ALIGN_CENTER;
                vat.BackgroundColor     = BaseColor.LIGHT_GRAY;
                vat.Padding             = 5;
                vat.HorizontalAlignment = Element.ALIGN_CENTER;


                //add cells to the tables

                table.AddCell(cell1);
                table.AddCell(cell1);
                table.AddCell(amount);
                table.AddCell(adjusment);
                table.AddCell(vat);

                PdfPCell sales = new PdfPCell(new Phrase("VAT on Sales"));
                sales.HorizontalAlignment = Element.ALIGN_CENTER;
                sales.BackgroundColor     = BaseColor.LIGHT_GRAY;
                sales.Rowspan             = 6;
                sales.Rotation            = 90;
                table.AddCell(sales);

                cell1 = new PdfPCell(new Phrase("1-Standered rated sales"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(sAmount5.Text));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(sAdj5.Text));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(s5.Text));
                table.AddCell(vat);

                cell1 = new PdfPCell(new Phrase("2-Private Healthcare/Private Education sales to citizens"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(sAmountCitizens.Text));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(sAdjCitizens.Text));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(" "));
                table.AddCell("");

                cell1 = new PdfPCell(new Phrase("3-Zero related domestic sales"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(sAmount0.Text));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(sAdj0.Text));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(" "));
                table.AddCell("");

                cell1 = new PdfPCell(new Phrase("4-Exports"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(sAmountExport.Text));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(sAdjExports.Text));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(" "));
                table.AddCell("");

                cell1 = new PdfPCell(new Phrase("5-Exempt sales"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(sAmountExempt.Text));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(sAdjExempt.Text));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(" "));
                table.AddCell("");

                cell1 = new PdfPCell(new Phrase("6-Total Sales"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(sTotalAmount.Text));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(sTotalAdj.Text));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(totalSale.Text));
                table.AddCell(vat);

                ////// purchase
                ///
                PdfPCell purchases = new PdfPCell(new Phrase("VAT on Purchases"));
                purchases.HorizontalAlignment = Element.ALIGN_CENTER;
                purchases.BackgroundColor     = BaseColor.LIGHT_GRAY;
                purchases.Rowspan             = 6;
                purchases.Rotation            = 90;

                table.AddCell(purchases);


                cell1 = new PdfPCell(new Phrase("7-Standered rated domestic purchases"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(pAmount5.Text));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(pAdj5.Text));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(p5.Text));
                table.AddCell(vat);

                cell1 = new PdfPCell(new Phrase("8-Imports subject to VAT paid at customs"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(pAmountImports.Text));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(pAdjImports.Text));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(pImports.Text));
                table.AddCell(vat);

                cell1 = new PdfPCell(new Phrase("9-Import subject to VAT accounted for through reverse charge mechanism"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(pAmountRCM.Text));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(pAdjRCM.Text));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(pRCM.Text));
                table.AddCell(vat);

                cell1 = new PdfPCell(new Phrase("10-Zero rated purchases"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(pAmount0.Text));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(pAmount0.Text));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(" "));
                table.AddCell("");

                cell1 = new PdfPCell(new Phrase("11-Exempt purchases"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(pAmountExempt.Text));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(pAdjExempt.Text));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(" "));
                table.AddCell(vat);

                cell1 = new PdfPCell(new Phrase("12-total purchases"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(pTotalAmount.Text));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(pTotalAdj.Text));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(totalPurchases.Text));
                table.AddCell(vat);
                //

                table.AddCell("");
                cell1 = new PdfPCell(new Phrase("13-Total VAT due for current period"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(""));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(""));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(totalVAT.Text));
                table.AddCell(vat);

                table.AddCell("");
                cell1 = new PdfPCell(new Phrase("14-Corrections from previous period (between SAR +-5000)"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(""));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(""));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(correction.Text));
                table.AddCell(vat);

                table.AddCell("");
                cell1 = new PdfPCell(new Phrase("15-VAT credit carried forward from pervious period(s)"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(""));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(""));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(carried.Text));
                table.AddCell(vat);

                table.AddCell("");
                cell1 = new PdfPCell(new Phrase("Net VAT due (or clairn)"));
                table.AddCell(cell1);
                amount = new PdfPCell(new Phrase(""));
                table.AddCell(amount);
                adjusment = new PdfPCell(new Phrase(""));
                table.AddCell(adjusment);
                vat = new PdfPCell(new Phrase(net.Text));
                table.AddCell(vat);


                document.Add(table);
                document.Close();

                byte[] bytes = memoryStream.ToArray();

                memoryStream.Close();
                Response.Clear();
                Response.ContentType = "application/pdf";

                Response.AddHeader("Content-Disposition", "attachment; filename=" + "From " + home.firstDate.GetDateTimeFormats('d')[0] + " To " + home.lastDate.GetDateTimeFormats('d')[0] + ".pdf");
                Response.ContentType = "application/pdf";
                Response.Buffer      = true;
                Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
                Response.BinaryWrite(bytes);

                Response.End();
                Response.Close();
            }
        }
Exemplo n.º 51
0
    //public void GetLowStockProduct()
    //{
    //    SqlConnection ConnectionString = new SqlConnection(ConfigurationManager.ConnectionStrings["cnstring"].ConnectionString);
    //    DataTable dtTable = new DataTable();
    //    SqlDataAdapter da = new SqlDataAdapter();

    //    SqlCommand cmd = new SqlCommand();
    //    cmd.CommandText = "getLowStockProduct";
    //    cmd.CommandType = CommandType.StoredProcedure;
    //    cmd.Connection = ConnectionString;
    //    ConnectionString.Open();
    //    try
    //    {
    //        da = new SqlDataAdapter(cmd);
    //        da.Fill(dtTable);
    //        if (dtTable != null)
    //        {
    //            if (dtTable.Rows.Count > 0)
    //            {
    //                gvLowProductList.DataSource = dtTable;
    //                gvLowProductList.DataBind();
    //            }
    //        }
    //    }
    //    catch (Exception ex)
    //    {
    //        ErrHandler.writeError(ex.Message, ex.StackTrace);
    //    }
    //    finally
    //    {
    //        ConnectionString.Close();
    //    }
    //}


    protected void btnpdf_Click(object sender, EventArgs e)
    {
        try
        {
            DataTable dt = new DataTable();
            if (Session["dtProduct"] != null)
            {
                dt = (DataTable)Session["dtProduct"];
            }
            StringBuilder sb = new StringBuilder();
            string        s  = "";


            //string finalResult = string.Empty;
            Paragraph paragraph = new Paragraph();
            paragraph.Add(("Date: " + DateTime.Now.ToString("dd/MM/yyyy")).Replace('-', '/'));
            paragraph.Alignment = Element.ALIGN_RIGHT;

            Document              documnent     = new Document(iTextSharp.text.PageSize.A4, 20f, 20f, 20f, 20f);
            PdfPTable             tableCategory = new PdfPTable(3);
            iTextSharp.text.Image myImg         = iTextSharp.text.Image.GetInstance(Server.MapPath("Uploads/MooryaTools.png"));
            myImg.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
            myImg.ScaleAbsolute(220f, 75f);
            //tableCategory.AddCell("Category Name:" + dtProducts.Rows[0]["Categoryname"]);
            //tableCategory.AddCell(("Date: " + DateTime.Now.ToString("dd/MM/yyyy")).Replace('-', '/'));
            //tableCategory.SpacingAfter = 12.5f;
            documnent.Open();
            //documnent.Add(tableCategory);
            Chunk        glue        = new Chunk(new VerticalPositionMark());
            Paragraph    para        = new Paragraph();
            string       finalResult = string.Empty;
            MemoryStream mstr        = new MemoryStream();

            String path    = Server.MapPath("uploads");
            string PDFName = Guid.NewGuid().ToString();
            // string PDFName = Convert.ToString(dtProducts.Rows[0]["Categoryname"]);
            //PdfWriter writer = PdfWriter.GetInstance(documnent, new FileStream(path + "/" + PDFName + ".pdf", FileMode.Create));
            PdfWriter writer = PdfWriter.GetInstance(documnent, mstr);
            //PdfWriter writer = PdfWriter.GetInstance(documnent,mstr);


            Paragraph paragraph1 = new Paragraph();
            paragraph1.Add("------------------------------------------------------------------");
            paragraph1.Add("\n");
            paragraph1.Add(ddlUserType.SelectedItem.ToString() + " Ledger:");
            paragraph1.Add("\n");
            paragraph1.Add(ddlUserName.SelectedItem.ToString());
            //paragraph1.Add("\n");
            //paragraph1.Add(ddlUserType.SelectedItem.ToString());
            paragraph1.Alignment = Element.ALIGN_CENTER;
            //paragraph1.Add("\n");
            //paragraph1.Add("Below mention price including GST");
            paragraph1.SpacingAfter = 12.5f;

            paragraph.SetLeading(1.0f, 3.0f);
            documnent.Open();
            paragraph.Add("");



            Phrase ph1 = new Phrase();

            Paragraph mm    = new Paragraph();
            PdfPTable table = new PdfPTable(6);

            table.SetWidths(new float[] { 1f, 2f, 3f, 2f, 2f, 2f });
            table.AddCell("sr");
            table.AddCell("Invoice No");
            table.AddCell("Date");
            table.AddCell("Total");
            table.AddCell("Paid");
            table.AddCell("Balance");



            for (int i = 0; i < dt.Rows.Count; i++)
            {
                try
                {
                    table.AddCell(dt.Rows[i]["RowId"].ToString());
                    table.AddCell(dt.Rows[i]["oid"].ToString());
                    table.AddCell(dt.Rows[i]["orderdate"].ToString());
                    table.AddCell(dt.Rows[i]["totalamount"].ToString());
                    table.AddCell(dt.Rows[i]["paid"].ToString());
                    table.AddCell(dt.Rows[i]["remain"].ToString());
                }
                catch (Exception)
                {
                }
            }
            table.AddCell("");
            table.AddCell("");
            table.AddCell("Total");
            table.AddCell(lblTotalAmount.Text.ToString());
            table.AddCell(lblPaid.Text.ToString());
            table.AddCell(lblRemaining.Text.ToString());



            //Paragraph paragraph2 = new Paragraph();
            //var titleFontBlue = FontFactory.GetFont("Arial", 14, Font.NORMAL, Color.BLUE);
            //string ssss = " ''Morya Tools'' ";
            //paragraph2.Add("Above mention price including GST" + Environment.NewLine + "For iOS");
            //paragraph2.Add(Environment.NewLine + Environment.NewLine + "To Know the Prices,Please Download our app" + ssss);
            //paragraph2.Add(Environment.NewLine + "For Android" + Environment.NewLine);
            ////   paragraph2.Add(Environment.NewLine + Environment.NewLine + "https://play.google.com/store/apps/details?id=in.co.vsys.moryatools&hl=en");
            //var c1 = new Chunk("https://play.google.com/store/apps/details?id=in.co.vsys.moryatools&hl=en", titleFontBlue);

            //c1.SetAnchor("https://play.google.com/store/apps/details?id=in.co.vsys.moryatools&hl=en");
            //paragraph2.Add(c1);

            ////----
            //var c11 = new Chunk("https://itunes.apple.com/in/app/morya-tools/id1315540530?mt=8", titleFontBlue);

            //c11.SetAnchor("https://itunes.apple.com/in/app/morya-tools/id1315540530?mt=8");

            //paragraph2.Add(Environment.NewLine + "For iOS" + Environment.NewLine);

            //paragraph2.Alignment = Element.ALIGN_CENTER;
            //paragraph2.Add(c11);

            //paragraph2.Alignment = Element.ALIGN_CENTER;

            documnent.Add(paragraph);

            documnent.Add(myImg);
            documnent.Add(paragraph1);
            documnent.Add(table);
            //  documnent.Add(paragraph2);
            mm.Add(ph1);
            para.Add(mm);
            documnent.Add(para);
            Paragraph p2 = new Paragraph();
            p2.SetLeading(5f, 5f);
            documnent.Add(paragraph);
            documnent.Add(p2);
            documnent.Close();
            //DataTable dtPDFPath = new DataTable();
            //dtPDFPath.Columns.Add("PDFPath", typeof(string));
            //dtPDFPath.Rows.Add(@"http://moryaapp.moryatools.com/uploads/" + PDFName + ".pdf");

            DownloadPDF(mstr, "Customer Ledger");

            //String po = "PDFName";
            //DownloadPDF(mstr, po);

            ////-----
            //Response.ContentType = "application/pdf";
            //Response.AppendHeader("Content-Disposition", "attachment; filename=MyFile.pdf");
            //Response.TransmitFile(Server.MapPath("~/uploads/" + PDFName + ".pdf"));
            //Response.End();
        }
        catch (Exception o)
        { }
        finally { }
    }
Exemplo n.º 52
0
    protected void SendMail(object sender, EventArgs e)
    {
        try
        {
            //-----------------
            DataTable dt = new DataTable();
            if (Session["dtProduct"] != null)
            {
                dt = (DataTable)Session["dtProduct"];
            }
            StringBuilder sb = new StringBuilder();



            //string finalResult = string.Empty;
            Paragraph paragraph = new Paragraph();
            paragraph.Add(("Date: " + DateTime.Now.ToString("dd/MM/yyyy")).Replace('-', '/'));
            paragraph.Alignment = Element.ALIGN_RIGHT;

            Document              documnent     = new Document(iTextSharp.text.PageSize.A4, 20f, 20f, 20f, 20f);
            PdfPTable             tableCategory = new PdfPTable(3);
            iTextSharp.text.Image myImg         = iTextSharp.text.Image.GetInstance(Server.MapPath("Uploads/MooryaTools.png"));
            myImg.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
            myImg.ScaleAbsolute(220f, 75f);
            //tableCategory.AddCell("Category Name:" + dtProducts.Rows[0]["Categoryname"]);
            //tableCategory.AddCell(("Date: " + DateTime.Now.ToString("dd/MM/yyyy")).Replace('-', '/'));
            //tableCategory.SpacingAfter = 12.5f;
            documnent.Open();
            //documnent.Add(tableCategory);
            Chunk        glue        = new Chunk(new VerticalPositionMark());
            Paragraph    para        = new Paragraph();
            string       finalResult = string.Empty;
            MemoryStream mstr        = new MemoryStream();

            String path = Server.MapPath("uploads");

            string PDFName = Guid.NewGuid().ToString();
            // string PDFName = Convert.ToString(dtProducts.Rows[0]["Categoryname"]);
            //PdfWriter writer = PdfWriter.GetInstance(documnent, new FileStream(path + "/" + PDFName + ".pdf", FileMode.Create));
            PdfWriter writer = PdfWriter.GetInstance(documnent, mstr);
            //PdfWriter writer = PdfWriter.GetInstance(documnent,mstr);
            if (File.Exists(path + "/" + "CustomerLedger" + ".pdf"))
            {
                File.Delete(path + "/" + "CustomerLedger" + ".pdf");
            }
            PdfWriter writer1 = PdfWriter.GetInstance(documnent, new FileStream(path + "/" + "CustomerLedger" + ".pdf", FileMode.Create));

            Paragraph paragraph1 = new Paragraph();
            paragraph1.Add("------------------------------------------------------------------");
            paragraph1.Add("\n");
            paragraph1.Add(ddlUserType.SelectedItem.ToString() + " Ledger:");
            paragraph1.Add("\n");
            paragraph1.Add(ddlUserName.SelectedItem.ToString());
            //paragraph1.Add("\n");
            //paragraph1.Add(ddlUserType.SelectedItem.ToString());
            paragraph1.Alignment = Element.ALIGN_CENTER;
            //paragraph1.Add("\n");
            //paragraph1.Add("Below mention price including GST");
            paragraph1.SpacingAfter = 12.5f;

            paragraph.SetLeading(1.0f, 3.0f);
            documnent.Open();
            paragraph.Add("");



            Phrase ph1 = new Phrase();

            Paragraph mm    = new Paragraph();
            PdfPTable table = new PdfPTable(6);

            table.SetWidths(new float[] { 1f, 2f, 3f, 2f, 2f, 2f });
            table.AddCell("sr");
            table.AddCell("Invoice No");
            table.AddCell("Date");
            table.AddCell("Total");
            table.AddCell("Paid");
            table.AddCell("Balance");



            for (int i = 0; i < dt.Rows.Count; i++)
            {
                try
                {
                    table.AddCell(dt.Rows[i]["RowId"].ToString());
                    table.AddCell(dt.Rows[i]["oid"].ToString());
                    table.AddCell(dt.Rows[i]["orderdate"].ToString());
                    table.AddCell(dt.Rows[i]["totalamount"].ToString());
                    table.AddCell(dt.Rows[i]["paid"].ToString());
                    table.AddCell(dt.Rows[i]["remain"].ToString());
                }
                catch (Exception)
                {
                }
            }
            table.AddCell("");
            table.AddCell("");
            table.AddCell("Total");
            table.AddCell(lblTotalAmount.Text.ToString());
            table.AddCell(lblPaid.Text.ToString());
            table.AddCell(lblRemaining.Text.ToString());



            //Paragraph paragraph2 = new Paragraph();
            //var titleFontBlue = FontFactory.GetFont("Arial", 14, Font.NORMAL, Color.BLUE);
            //string ssss = " ''Morya Tools'' ";
            //paragraph2.Add("Above mention price including GST" + Environment.NewLine + "For iOS");
            //paragraph2.Add(Environment.NewLine + Environment.NewLine + "To Know the Prices,Please Download our app" + ssss);
            //paragraph2.Add(Environment.NewLine + "For Android" + Environment.NewLine);
            ////   paragraph2.Add(Environment.NewLine + Environment.NewLine + "https://play.google.com/store/apps/details?id=in.co.vsys.moryatools&hl=en");
            //var c1 = new Chunk("https://play.google.com/store/apps/details?id=in.co.vsys.moryatools&hl=en", titleFontBlue);

            //c1.SetAnchor("https://play.google.com/store/apps/details?id=in.co.vsys.moryatools&hl=en");
            //paragraph2.Add(c1);

            ////----
            //var c11 = new Chunk("https://itunes.apple.com/in/app/morya-tools/id1315540530?mt=8", titleFontBlue);

            //c11.SetAnchor("https://itunes.apple.com/in/app/morya-tools/id1315540530?mt=8");

            //paragraph2.Add(Environment.NewLine + "For iOS" + Environment.NewLine);

            //paragraph2.Alignment = Element.ALIGN_CENTER;
            //paragraph2.Add(c11);

            //paragraph2.Alignment = Element.ALIGN_CENTER;

            documnent.Add(paragraph);

            documnent.Add(myImg);
            documnent.Add(paragraph1);
            documnent.Add(table);
            //  documnent.Add(paragraph2);
            mm.Add(ph1);
            para.Add(mm);
            documnent.Add(para);
            Paragraph p2 = new Paragraph();
            p2.SetLeading(5f, 5f);
            documnent.Add(paragraph);
            documnent.Add(p2);
            documnent.Close();
            DataTable dtPDFPath = new DataTable();
            dtPDFPath.Columns.Add("PDFPath", typeof(string));
            //dtPDFPath.Rows.Add(@"http://moryaapp.moryatools.com/uploads/" + PDFName + ".pdf");
            dtPDFPath.Rows.Add(AppDomain.CurrentDomain.BaseDirectory + "//uploads//a.pdf");

            //path + "/" +"a"+ ".pdf"

            string email = "";
            try
            {
                //----
                con.Open();
                DataTable dtq = new DataTable();
                string    s   = "";
                if (ddlUserType.SelectedIndex == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "alert('Please Select User Type')", "", true);
                }
                else if (ddlUserType.SelectedValue.ToString().Trim() == "D")
                {
                    s = "select * from dealermaster where isdeleted=0 and did=" + ddlUserName.SelectedValue.ToString() + "";//email
                }
                else if (ddlUserType.SelectedValue.ToString().Trim() == "U")
                {
                    s = "select * from userregistration where isdelete=0 and uid=" + ddlUserName.SelectedValue.ToString() + "";//email
                }

                SqlDataAdapter da = new SqlDataAdapter(s, con);
                da.Fill(dtq);
                con.Close();

                for (int i = 0; i < dtq.Rows.Count; i++)
                {
                    if (dtq.Rows[0]["email"].ToString() == "")
                    {
                    }
                    else
                    {
                        email = dtq.Rows[0]["email"].ToString();
                    }
                }
                con.Close();
            }
            catch { }
            finally { con.Close(); }
            if (email == "")
            {
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "", "alert('Email ID Not Found')", true);
            }
            else
            {
                bool        send = false;
                MailMessage mail = new MailMessage();
                //mail.To.Add(ConfigurationManager.AppSettings["LoginToEmail"].ToString());
                mail.To.Add("*****@*****.**");

                mail.From    = new MailAddress("*****@*****.**", "Engineering Tools");
                mail.Subject = "Customer Ledger";
                //StringBuilder strBul = new StringBuilder("<div>");
                //strBul = strBul.Append("<div>Dear Sir,</div>");
                //strBul = strBul.Append("<br />");
                //strBul = strBul.Append("<br />");
                //strBul = strBul.Append("<div>" + "" + " Login Morya Tool Website After 7 PM , Login Date & Time " + System.DateTime.Now.ToString() + "</div>");
                //strBul = strBul.Append("<br />");
                //strBul = strBul.Append("<br />");
                //strBul = strBul.Append("<div>Thank you,</div>");
                //strBul = strBul.Append("<div>Morya App - Support Team.</div>");
                //strBul = strBul.Append("</div>");
                Attachment data = new Attachment(path + "/" + "CustomerLedger" + ".pdf", MediaTypeNames.Application.Octet);
                // your path may look like Server.MapPath("~/file.ABC")
                mail.Attachments.Add(data);

                //mail.Body = strBul.ToString();
                mail.IsBodyHtml = true;
                SmtpClient smtp = new SmtpClient();
                smtp.Host = "103.250.184.62";
                smtp.Port = 25;
                smtp.UseDefaultCredentials = false;
                smtp.Credentials           = new System.Net.NetworkCredential("*****@*****.**", "T@0e1sj8");
                try
                {
                    smtp.Send(mail);
                    send = true;
                    ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "", "alert('Mail Sent Successfully')", true);
                }
                catch (Exception ex)
                {
                    send = false;
                    ErrHandler.writeError(ex.Message, ex.StackTrace);
                }
            }
            //String po = "PDFName";
            //DownloadPDF(mstr, po);

            ////-----
            //Response.ContentType = "application/pdf";
            //Response.AppendHeader("Content-Disposition", "attachment; filename=MyFile.pdf");
            //Response.TransmitFile(Server.MapPath("~/uploads/" + PDFName + ".pdf"));
            //Response.End();
        }
        catch (Exception o)
        { }
        finally { }
    }
Exemplo n.º 53
0
        public void FillEvent(SqlDataReader dr, int cropYear, string statementDate,
            int pageNumber, string title, string paymentDescription, iTextSharp.text.Image imgLogo)
        {
            _paymentDesc = paymentDescription;
            _cropYear = cropYear.ToString();

            if (statementDate != null && statementDate.Length > 0) {
                _statementDate = DateTime.Parse(statementDate).ToString("MMMM dd, yyyy");
            } else {
                _statementDate = "";
            }

            _growerName = dr.GetString(dr.GetOrdinal("Business_Name"));
            _adr1 = dr.GetString(dr.GetOrdinal("Address_1"));
            _adr2 = dr.GetString(dr.GetOrdinal("Address_2"));
            _city = dr.GetString(dr.GetOrdinal("City"));
            _state = dr.GetString(dr.GetOrdinal("State"));
            _postalCode = dr.GetString(dr.GetOrdinal("Zip"));
            _contractNumber = dr.GetString(dr.GetOrdinal("Contract_Number"));
            _factoryName = dr.GetString(dr.GetOrdinal("Factory_Name"));
            _stationName = dr.GetString(dr.GetOrdinal("Station_Name"));
            _pageNumber = pageNumber;
            _title = title;
            _imgLogo = imgLogo;
        }
Exemplo n.º 54
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // server folder path which is stored your PDF documents
            string pdfFileName = Request.PhysicalApplicationPath + "\\files\\" + "GenerateHTMLTOPDF.pdf";

            string imagepath = Server.MapPath("Images");

            //Create new PDF document
            Document document = new Document(PageSize.A4, 20f, 20f, 20f, 20f);

            document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());

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

            //Se carga la imagen
            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imagepath + "/r.jpg");
            image.Alignment = Element.ALIGN_CENTER;
            document.Add(image);

            //Caracteristicas de la letra
            Font      arial     = FontFactory.GetFont("Arial", 28, Font.BOLDITALIC, new BaseColor(50, 205, 50));
            Paragraph paragraph = new Paragraph("Events more cost one hundred dollars", arial);

            paragraph.Alignment = Element.ALIGN_CENTER;

            document.Add(paragraph);

            //Generate table
            PdfPTable tableTitles = new PdfPTable(13);

            tableTitles.HorizontalAlignment = Element.ALIGN_LEFT;
            //actual width of table in points
            tableTitles.TotalWidth = 800f;
            //fix the absolute width of the table
            tableTitles.LockedWidth = true;

            //ancho de cada cuadro en puntos
            float[] values = new float[] { 20f, 20f, 20f, 20f, 20f, 20f, 20f, 20f, 20f, 20f, 20f, 20f, 35f };
            tableTitles.SetWidths(values);
            tableTitles.SpacingBefore = 20f;

            PdfPCell cellTitles = new PdfPCell();

            cellTitles.Colspan             = 2;
            cellTitles.Border              = 0;
            cellTitles.HorizontalAlignment = -1;
            tableTitles.AddCell(cellTitles);

            //Nombre de las columnas
            tableTitles.AddCell(new Paragraph("Code", FontFactory.GetFont("Arial", 10, Font.BOLDITALIC, new BaseColor(255, 140, 0))));
            tableTitles.AddCell(new Paragraph("Name", FontFactory.GetFont("Arial", 10, Font.BOLDITALIC, new BaseColor(255, 140, 0))));
            tableTitles.AddCell(new Paragraph("Type", FontFactory.GetFont("Arial", 10, Font.BOLDITALIC, new BaseColor(255, 140, 0))));
            tableTitles.AddCell(new Paragraph("Place", FontFactory.GetFont("Arial", 10, Font.BOLDITALIC, new BaseColor(255, 140, 0))));
            tableTitles.AddCell(new Paragraph("Date", FontFactory.GetFont("Arial", 10, Font.BOLDITALIC, new BaseColor(255, 140, 0))));
            tableTitles.AddCell(new Paragraph("Max persons", FontFactory.GetFont("Arial", 10, Font.BOLDITALIC, new BaseColor(255, 140, 0))));
            tableTitles.AddCell(new Paragraph("Cost", FontFactory.GetFont("Arial", 10, Font.BOLDITALIC, new BaseColor(255, 140, 0))));
            tableTitles.AddCell(new Paragraph("Start Time", FontFactory.GetFont("Arial", 10, Font.BOLDITALIC, new BaseColor(255, 140, 0))));
            tableTitles.AddCell(new Paragraph("Ending Time", FontFactory.GetFont("Arial", 10, Font.BOLDITALIC, new BaseColor(255, 140, 0))));
            tableTitles.AddCell(new Paragraph("Lucrative", FontFactory.GetFont("Arial", 10, Font.BOLDITALIC, new BaseColor(255, 140, 0))));
            tableTitles.AddCell(new Paragraph("Description", FontFactory.GetFont("Arial", 10, Font.BOLDITALIC, new BaseColor(255, 140, 0))));

            document.Add(tableTitles);


            PdfPTable table = new PdfPTable(13);

            table.HorizontalAlignment = Element.ALIGN_LEFT;
            //actual width of table in points
            table.TotalWidth = 800f;
            //fix the absolute width of the table
            table.LockedWidth = true;

            //ancho de cada cuadro en puntos
            float[] widths = new float[] { 20f, 20f, 20f, 20f, 20f, 20f, 20f, 20f, 20f, 20f, 20f, 20f, 35f };
            table.SetWidths(widths);

            //Query in database


            PdfPCell cell = new PdfPCell();

            cell.Colspan             = 2;
            cell.Border              = 0;
            cell.HorizontalAlignment = -1;
            table.AddCell(cell);

            table.AddCell("Code");
            table.AddCell("Name");
            table.AddCell("Type_Event");
            table.AddCell("Place_Event");
            table.AddCell("getDate");
            table.AddCell("Quantity_Persons");

            table.AddCell("Total_Cost");
            table.AddCell("Start_Time");
            table.AddCell("Ending_Time");
            table.AddCell("Lucrative");
            table.AddCell("Descriptionn");

            document.Add(table);
            //n += 1;

            document.Close();

            ShowPdf(pdfFileName);
            //}
        }
Exemplo n.º 55
0
 public void FillEvent(iTextSharp.text.Image imgLogo, string cropYear)
 {
     _imgLogo = imgLogo;
     _cropYear = cropYear;
 }
Exemplo n.º 56
0
        public void DownloadPDFFormat()
        {
            log4net.ILog logger = log4net.LogManager.GetLogger("File");
            try
            {
                Document pdfReport = new Document(PageSize.A4, 100, 91, 100, 93);
                System.IO.MemoryStream msReport = new System.IO.MemoryStream();
                PdfWriter writer = PdfWriter.GetInstance(pdfReport, msReport);
                pdfReport.Open();
                DBConnectionHandler1 db = new DBConnectionHandler1();
                SqlConnection        cn = db.getconnection();
                cn.Open();
                SqlCommand    cmd = new SqlCommand("select * from UploadLogo", cn);
                SqlDataReader dr  = cmd.ExecuteReader();
                if (dr.Read())
                {
                    if (dr.GetString(1).ToString() != "")
                    {
                        iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance(@dr.GetString(1).ToString().Trim());
                        image1.SetAbsolutePosition(70, 100);
                        PdfContentByte by = writer.DirectContent;
                        PdfTemplate    tp = by.CreateTemplate(170, 190);
                        tp.AddImage(image1);
                        by.AddTemplate(tp, 175, 660);
                        cn.Close();
                        dr.Close();
                    }
                }
                string datetime = string.Empty;
                datetime = Convert.ToString(System.DateTime.Now);

                string str = string.Empty;

                if (txtitemno.Text != "")
                {
                    str = ("   Model_No. : " + txtitemno.Text);
                }
                if (ddlStatus.Text != "")
                {
                    str = ("   LostStatus : " + ddlStatus.Text);
                }
                if (ddllocation.Text != "")
                {
                    str = ("    Location : " + ddllocation.Text);
                }
                //if (txtfoundby.Text != "")
                //    str = ("   Found By : " + txtfoundby.Text);
                if (txtsignoutby.Text != "")
                {
                    str = ("   IssuedTo_Name : " + txtsignoutby.Text);
                }
                if (txtsigninby.Text != "")
                {
                    str = ("   IssuedBy_Name : " + txtsigninby.Text);
                }

                if (txtdatefrom.Text != "" && txtdateto.Text != "")
                {
                    str = ("   Date  From :" + txtdatefrom.Text + "      To :" + txtdateto.Text);
                }



                Phrase headerPhrase = new Phrase("                                     Item Report                                                       ", FontFactory.GetFont("Garamond", 14));

                headerPhrase.Add("      Generated On : ");
                headerPhrase.Add(datetime);
                //headerPhrase.Add("                                                                           Searching Parameter  : ");
                //headerPhrase.Add(str);


                HeaderFooter header = new HeaderFooter(headerPhrase, false);
                header.Border    = Rectangle.NO_BORDER;
                header.Alignment = Element.ALIGN_CENTER;
                header.Alignment = Element.ALIGN_BOTTOM;
                pdfReport.Header = header;
                pdfReport.Add(headerPhrase);


                // Creates the Table
                PdfPTable ptData = new PdfPTable(gvItemTable1.Columns.Count - 1);
                ptData.SpacingBefore       = 8;
                ptData.DefaultCell.Padding = 1;
                float[] headerwidths = new float[gvItemTable1.Columns.Count - 1]; // percentage

                headerwidths[0] = 3.2F;
                headerwidths[1] = 3.2F;
                headerwidths[2] = 3.2F;
                headerwidths[3] = 3.2F;
                headerwidths[4] = 3.2F;
                headerwidths[5] = 3.2F;
                // headerwidths[6] = 3.2F;
                // headerwidths[7] = 3.2F;
                //headerwidths[8] = 3.2F;

                ptData.SetWidths(headerwidths);
                ptData.WidthPercentage = 100;
                ptData.DefaultCell.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
                ptData.DefaultCell.VerticalAlignment   = Element.ALIGN_MIDDLE;

                //Insert the Table Headers
                for (int intK = 0; intK < gvItemTable1.Columns.Count - 1; intK++)
                {
                    PdfPCell cell = new PdfPCell();
                    cell.BorderWidth     = 0.001f;
                    cell.BackgroundColor = new Color(200, 200, 200);
                    cell.BorderColor     = new Color(100, 100, 100);
                    if (gvItemTable1.Columns[intK + 1].HeaderText.ToString() != "")
                    {
                        cell.Phrase = new Phrase(gvItemTable1.Columns[intK + 1].HeaderText.ToString(), FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7, Font.BOLD));
                        ptData.AddCell(cell);
                    }
                }

                ptData.HeaderRows = 1; // this is the end of the table header

                //Insert the Table Data

                for (int intJ = 0; intJ < gvItemTable1.Items.Count; intJ++)
                {
                    for (int intK = 0; intK < gvItemTable1.Columns.Count - 1; intK++)
                    {
                        PdfPCell cell = new PdfPCell();
                        cell.BorderWidth     = 0.001f;
                        cell.BorderColor     = new Color(100, 100, 100);
                        cell.BackgroundColor = new Color(250, 250, 250);
                        if (gvItemTable1.Items[intJ].Cells[intK + 3].Text.ToString() != "")
                        {
                            cell.Phrase = new Phrase(gvItemTable1.Items[intJ].Cells[intK + 3].Text.ToString(), FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 6));
                            ptData.AddCell(cell);
                        }
                        else
                        {
                            cell.Phrase = new Phrase("", FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 6));
                            ptData.AddCell(cell);
                        }
                    }
                }

                //Insert the Table

                pdfReport.Add(ptData);

                //Closes the Report and writes to Memory Stream

                pdfReport.Close();

                //Writes the Memory Stream Data to Response Object
                Response.Clear();

                Response.AddHeader("content-disposition", string.Format("attachment;filename=InventoryReport.pdf"));
                Response.Charset     = "";
                Response.ContentType = "application/pdf";
                Response.BinaryWrite(msReport.ToArray());
                Response.End();
            }
            catch (Exception ex)
            {
                logger.Info(ex.Message);
            }
        }
Exemplo n.º 57
0
 public void FillEvent(iTextSharp.text.Image imgLogo, string statementDate, string ldoBusinessName, string ldoAddressLine1, string ldoAddressLine2, string ldoCityStateZip)
 {
     _imgLogo = imgLogo;
     _statementDate = statementDate;
     _ldoBusinessName = ldoBusinessName;
     _ldoAddressLine1 = ldoAddressLine1;
     _ldoAddressLine2 = ldoAddressLine2;
     _ldoCityStateZip = ldoCityStateZip;
 }
 private Image[,] RandomImages(string dir)
 {
     var rnd = _rnd;
     var files = Directory.GetFiles(dir, "*.jpg");
     var images = new Image[3, 3];
     for (int i = 0; i < 3; i++)
     {
         for (int j = 0; j < 3; j++)
         {
             var path = files[rnd.Next(files.Length)];
             var imageStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
             images[i,j] = Image.GetInstance(imageStream);
         }
     }
     return images;
 }