Inheritance: ILargeElement, ISpaceable
Example #1
2
 public static void CreateHardwareReport(string fileName, IEnumerable<HardwareCountReport> hardwares)
 {
     try
     {
         Document document = new Document(PageSize.A4, 72, 72, 72, 72);
         PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None));
         document.Open();
         document.Add(new Paragraph(Element.ALIGN_CENTER, "Hardware Report", new Font(iTextSharp.text.Font.FontFamily.HELVETICA, 16, Font.BOLD)));
         document.Add(new Chunk(Chunk.NEWLINE));
         var table = new PdfPTable(3);
         table.SetTotalWidth(new float[] { 25f, 50f, 25f });
         table.WidthPercentage = 100;
         table.AddCell(new Phrase("Category"));
         table.AddCell(new Phrase("Hardware Model/Type"));
         table.AddCell(new Phrase("Total"));
         foreach (var hw in hardwares)
         {
             table.AddCell(new Phrase(hw.Category));
             table.AddCell(new Phrase(hw.Model));
             table.AddCell(new Phrase(hw.Count));
         }
         document.Add(table);
         document.Close();
     }
     catch (Exception x)
     {
         Log.Error("Error when creating report.", x);
     }
 }
        private static void GenerateRow(PdfPTable table, PlayerInfo player, Font font, BaseColor backgroundColor)
        {
            var jpg = Image.GetInstance(player.PictureUrl);
            table.AddCell(jpg);

            PdfPCell cell;

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

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

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

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

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

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

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

            cell = new PdfPCell(new Phrase(player.BirthPlace, font)) {BackgroundColor = backgroundColor};
            table.AddCell(cell);
        }
 public void TestKeepTogether(bool tagged, bool keepTogether) {
     Document document = new Document();
     String file = "tagged_" + tagged + "-keeptogether_" + keepTogether + ".pdf";
     PdfWriter writer = PdfWriter.GetInstance(document, File.Create(outFolder + file));
     if (tagged)
         writer.SetTagged();
     document.Open();
     int columns = 3;
     int tables = 3;
     for (int tableCount = 0; tableCount < tables; tableCount++) {
         PdfPTable table = new PdfPTable(columns);
         for (int rowCount = 0; rowCount < 50; rowCount++) {
             PdfPCell cell1 = new PdfPCell(new Paragraph("t" + tableCount + " r:" + rowCount));
             PdfPCell cell2 = new PdfPCell(new Paragraph("t" + tableCount + " r:" + rowCount));
             PdfPCell cell3 = new PdfPCell(new Paragraph("t" + tableCount + " r:" + rowCount));
             table.AddCell(cell1);
             table.AddCell(cell2);
             table.AddCell(cell3);
         }
         table.SpacingAfter = 10f;
         table.KeepTogether = keepTogether;
         document.Add(table);
     }
     document.Close();
 }
Example #4
0
        /// <summary>
        /// Create pdf table.
        /// </summary>
        /// <returns>The PDF table.</returns>
        private iTextSharp.text.pdf.PdfPTable CreateTable()
        {
            // A table with three colums
            iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(3);

            // The cell
            iTextSharp.text.pdf.PdfPCell cell = null;

            // Add a cell with colspan 3
            cell         = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase("Cell with colspan 3"));
            cell.Colspan = 3;
            table.AddCell(cell);

            // Add a cell with colspan 2
            cell         = new iTextSharp.text.pdf.PdfPCell(new iTextSharp.text.Phrase("Cell with colspan 2"));
            cell.Colspan = 2;
            table.AddCell(cell);

            // Add the four remaining cells.
            table.AddCell("row 1; cell 1");
            table.AddCell("row 1; cell 2");
            table.AddCell("row 2; cell 1");
            table.AddCell("row 2; cell 2");

            // Return the table.
            return(table);
        }
        /// <summary>
        /// Save a pdf file in  "../../test.pdf".
        /// </summary>
        /// <param name="deals">Expect Collection of objects that have Name, Address, ProductName and formula.</param>
        public void GenerateReport(IEnumerable<PdfReportModel> deals)
        {
            FileStream fileStream = new FileStream(ReportsPath, FileMode.Create, FileAccess.Write, FileShare.None);
            Rectangle pageSize = new Rectangle(PageSize.A4);
            Document reportDocument = new Document(pageSize);
            PdfWriter pdfWriter = PdfWriter.GetInstance(reportDocument, fileStream);
            var boldFont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 17);

            reportDocument.Open();

            PdfPTable reportTable = new PdfPTable(6);
            reportTable.HorizontalAlignment = Element.ALIGN_LEFT;
            PdfPCell headerCell = new PdfPCell(new Phrase("Produced products information", boldFont));
            headerCell.Colspan = 6;
            headerCell.HorizontalAlignment = 0;
            reportTable.AddCell(headerCell);

            this.PutHeadCells(reportTable);

            foreach (var deal in deals)
            {
                reportTable.AddCell(deal.ProductName);
                reportTable.AddCell(deal.Quantity);
                reportTable.AddCell(deal.PricePerUnit);
                reportTable.AddCell(deal.Formula);
                reportTable.AddCell(deal.Address);
                reportTable.AddCell(deal.Total);
            }

            reportDocument.Add(reportTable);
            reportDocument.Close();
        }
Example #6
0
 private void AddRow(PdfPTable table, ExpenseTableRow dataRow)
 {
     table.AddCell(new Paragraph(dataRow.Cost, FontFactory.GetFont(BaseFont.COURIER, BaseFont.CP1257, 10)));
     table.AddCell(new Paragraph(dataRow.Date, FontFactory.GetFont(BaseFont.COURIER, BaseFont.CP1257, 10)));
     table.AddCell(new Paragraph(dataRow.Paid, FontFactory.GetFont(BaseFont.COURIER, BaseFont.CP1257, 10)));
     table.AddCell(new Paragraph(dataRow.ResposiblePerson, FontFactory.GetFont(BaseFont.COURIER, BaseFont.CP1257, 10)));
 }
Example #7
0
        public static bool generate(User user, string path)
        {
            document = new Document(PageSize.A4, 50, 50, 25, 25);

            var output = new MemoryStream();
            var writer = PdfWriter.GetInstance(document, new FileStream(path + "/BS-" + DateTime.Now.Month + "-" + DateTime.Now.Year + "-" + user.Firstname + "-" + user.Lastname + ".pdf", FileMode.Create));

            document.Open();

            // création du logo
            Image logo = iTextSharp.text.Image.GetInstance("logo.png");
            logo.ScaleAbsoluteWidth(200);
            logo.ScaleAbsoluteHeight(50);
            PdfPCell cellLogo = new PdfPCell(logo);
            cellLogo.Border = Rectangle.NO_BORDER;
            cellLogo.PaddingBottom = 8;

            // création du titre
            var title = new Paragraph("BULLETIN DE SALAIRE", titleFont);
            title.Alignment = Element.ALIGN_RIGHT;
            PdfPCell cellTitle = new PdfPCell(title);
            cellTitle.Border = Rectangle.NO_BORDER;
            cellTitle.HorizontalAlignment = 2; //0=Left, 1=Centre, 2=Right

            // création du tableau
            PdfPTable tableTitle = new PdfPTable(2);
            tableTitle.DefaultCell.Border = Rectangle.NO_BORDER;
            tableTitle.WidthPercentage = 100;

            PdfPCell cellAdresseSuperp = new PdfPCell(new Paragraph("89, quais des Chartrons \n33000 BORDEAUX", subTitleFont));
            cellAdresseSuperp.HorizontalAlignment = 0;
            cellAdresseSuperp.Border = Rectangle.NO_BORDER;

            PdfPCell cellDUMec = new PdfPCell(new Paragraph(user.Lastname + " " + user.Firstname + "\n" + user.Address, subTitleFont));
            cellDUMec.HorizontalAlignment = 2;
            cellDUMec.Border = Rectangle.NO_BORDER;

            // ajout de la cell du logo
            tableTitle.AddCell(cellLogo);

            // ajout de la cell du titre
            tableTitle.AddCell(cellTitle);

            tableTitle.AddCell(cellAdresseSuperp);
            tableTitle.AddCell(cellDUMec);

            // Ajout du titre principal
            tableTitle.AddCell(getTitle());

            //******************************************************************************/
            //***********************   ABSENCES   *****************************************/
            //******************************************************************************/

            generateAbsences(tableTitle, user);

            generateTableSalary(user);

            document.Close();
            return true;
        }
Example #8
0
        public void AddTable(List <CellRow> tableRows, float[] cellWidths)
        {
            iPdf.PdfPTable table = new iPdf.PdfPTable(cellWidths.Length);
            for (int i = 0; i < cellWidths.Length; i++)
            {
                table.AbsoluteWidths[i] = cellWidths[i];
            }
            table.WidthPercentage = 100F;
            table.SetWidths(cellWidths);
            table.SpacingBefore      = 10F;
            table.SpacingAfter       = 10F;
            table.SplitRows          = false;
            table.SplitLate          = false;
            table.DefaultCell.Border = 0;             //

            foreach (CellRow row in tableRows)
            {
                for (int i = 0; i < row.CellTexts.Length; i++)
                {
                    iText.Chunk cellChunk = new iText.Chunk(row.CellTexts[i]);
                    cellChunk.Font = iText.FontFactory.GetFont(baseFont, row.IsRowImportant ? leadSize : normalSize, row.CellBolds[i] ? iText.Font.BOLD : iText.Font.NORMAL);
                    iPdf.PdfPCell cell = new iPdf.PdfPCell(new iText.Phrase(cellChunk));
                    //cell.Width = (float)(cellWidths[i] * (document.PageSize.Width / 100));
                    cell.Border = iText.Rectangle.NO_BORDER;
                    cell.NoWrap = false;
                    table.AddCell(cell);
                }
            }
            table.SetWidths(cellWidths);
            document.Add(table);
        }
 public void SplitTable(PdfPTable table)
 {
     foreach (IPdfPTableEvent eventa in events) {
         if (eventa is IPdfPTableEventSplit)
             ((IPdfPTableEventSplit)eventa).SplitTable(table);
     }
 }
 private void button2_Click(object sender, EventArgs e)
 {
     BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
     iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 12, iTextSharp.text.Font.ITALIC, BaseColor.DARK_GRAY);
     Document doc = new Document(iTextSharp.text.PageSize.LETTER,10,10,42,42);
     PdfWriter pdw = PdfWriter.GetInstance(doc, new FileStream(naziv + ".pdf", FileMode.Create));
     doc.Open();
     Paragraph p = new Paragraph("Word Count for : "+naziv,times);
     doc.Add(p);
     p.Alignment = 1;
     PdfPTable pdt = new PdfPTable(2);
     pdt.HorizontalAlignment = 1;
     pdt.SpacingBefore = 20f;
     pdt.SpacingAfter = 20f;
     pdt.AddCell("Word");
     pdt.AddCell("No of repetitions");
     foreach (Rijec r in lista_rijeci)
     {
         pdt.AddCell(r.Tekst);
         pdt.AddCell(Convert.ToString(r.Ponavljanje));
     }
     using (MemoryStream stream = new MemoryStream())
     {
         chart1.SaveImage(stream, ChartImageFormat.Png);
         iTextSharp.text.Image chartImage = iTextSharp.text.Image.GetInstance(stream.GetBuffer());
         chartImage.ScalePercent(75f);
         chartImage.Alignment = 1;
         doc.Add(chartImage);
     }
     doc.Add(pdt);
     doc.Close();
     MessageBox.Show("PDF created!");
 }
Example #11
0
        private static void AddDetails(ref PdfPTable table, ref Claim claim)
        {
            table.AddCell(CreateDetailTitleCell("Customer Complaint"));
            table.AddCell(CreateDetailCell(claim.CustomerComplaint.ToUpper()));
            table.AddCell(CreateSpacerCell());
            table.AddCell(CreateDetailTitleCell("Cause of Failure"));
            table.AddCell(CreateDetailCell(claim.CauseOfFailure.ToUpper()));
            table.AddCell(CreateSpacerCell());
            table.AddCell(CreateDetailTitleCell("Corrective Action"));
            table.AddCell(CreateDetailCell(claim.CorrectiveAction.ToUpper()));
            table.AddCell(CreateSpacerCell());

            if(claim.MiscAmountExplanation.Trim().Length > 0 && !claim.MiscAmountExplanation.Trim().ToUpper().Equals("NONE"))
            {
                table.AddCell(CreateDetailTitleCell("Misc Amount Explanation"));
                table.AddCell(CreateDetailCell(claim.MiscAmountExplanation.ToUpper()));
                table.AddCell(CreateSpacerCell());
            }

            if(claim.ReimbursementComment.Trim().Length > 0 && !claim.ReimbursementComment.Trim().ToUpper().Equals("NONE"))
            {
                table.AddCell(CreateDetailTitleCell("Reimbursement Comment"));
                table.AddCell(CreateDetailCell(claim.ReimbursementComment.ToUpper()));
                table.AddCell(CreateSpacerCell());
            }
        }
Example #12
0
        public virtual void Rowspan_Test() {
            String file = "rowspantest.pdf";

            string fileE = CMP_FOLDER + file;
            Console.Write(File.Exists(fileE));
            Document document = new Document();
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(OUTPUT_FOLDER + file, FileMode.Create));
            document.Open();
            PdfContentByte contentByte = writer.DirectContent;

            Rectangle rect = document.PageSize;

            PdfPTable table = new PdfPTable(4);

            table.TotalWidth = rect.Right - rect.Left + 1;
            table.LockedWidth = true;

            float[] widths = new float[] {
                0.1f, 0.54f, 0.12f, 0.25f
            };

            table.SetWidths(widths);

            PdfPCell cell_1_1 = new PdfPCell(new Phrase("1-1"));
            cell_1_1.Colspan = 4;
            table.AddCell(cell_1_1);

            PdfPCell cell_2_1 = new PdfPCell(new Phrase("2-1"));
            cell_2_1.Rowspan = 2;
            table.AddCell(cell_2_1);

            PdfPCell cell_2_2 = new PdfPCell(new Phrase("2-2"));
            cell_2_2.Colspan = 2;
            table.AddCell(cell_2_2);

            PdfPCell cell_2_4 = new PdfPCell(new Phrase("2-4"));
            cell_2_4.Rowspan = 3;
            table.AddCell(cell_2_4);

            PdfPCell cell_3_2 = new PdfPCell(new Phrase("3-2"));
            table.AddCell(cell_3_2);

            PdfPCell cell_3_3 = new PdfPCell(new Phrase("3-3"));
            table.AddCell(cell_3_3);

            PdfPCell cell_4_1 = new PdfPCell(new Phrase("4-1"));
            cell_4_1.Colspan = 3;
            table.AddCell(cell_4_1);

            table.WriteSelectedRows(0, -1, rect.Left, rect.Top, contentByte);

            document.Close();

            // compare
            CompareTool compareTool = new CompareTool();
            String errorMessage = compareTool.CompareByContent(OUTPUT_FOLDER + file, CMP_FOLDER + file, OUTPUT_FOLDER, "diff");
            if (errorMessage != null) {
                Assert.Fail(errorMessage);
            }
        }
Example #13
0
// ===========================================================================
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        PdfPTable table = new PdfPTable(4);
        PdfPTable nested1 = new PdfPTable(2);
        nested1.AddCell("1.1");
        nested1.AddCell("1.2");
        PdfPTable nested2 = new PdfPTable(1);
        nested2.AddCell("12.1");
        nested2.AddCell("12.2");
        for (int k = 0; k < 16; ++k) {
          if (k == 1) {
            table.AddCell(nested1);
          } else if (k == 12) {
            table.AddCell(new PdfPCell(nested2));
          } else {
            table.AddCell("cell " + k);
          }
        }
        document.Add(table);
      }
    }
 // ---------------------------------------------------------------------------
 public void Write(Stream stream)
 {
     // Use old example to create PDF
     MovieTemplates mt = new MovieTemplates();
     byte[] pdf = Utility.PdfBytes(mt);
     using (ZipFile zip = new ZipFile())
     {
         using (MemoryStream ms = new MemoryStream())
         {
             // step 1
             using (Document document = new Document())
             {
                 // step 2
                 PdfWriter writer = PdfWriter.GetInstance(document, ms);
                 // step 3
                 document.Open();
                 // step 4
                 PdfPTable table = new PdfPTable(2);
                 PdfReader reader = new PdfReader(pdf);
                 int n = reader.NumberOfPages;
                 PdfImportedPage page;
                 for (int i = 1; i <= n; i++)
                 {
                     page = writer.GetImportedPage(reader, i);
                     table.AddCell(Image.GetInstance(page));
                 }
                 document.Add(table);
             }
             zip.AddEntry(RESULT, ms.ToArray());
         }
         zip.AddEntry(Utility.ResultFileName(mt.ToString() + ".pdf"), pdf);
         zip.Save(stream);
     }
 }
Example #15
0
 private void AddAirlineReportsTableColumns(PdfPTable table)
 {
     table.AddCell(AirlineNameColumnHeader);
     table.AddCell(TotalFlightsColumnHeader);
     table.AddCell(AverageFlightDurationColumnHeader);
     table.AddCell(TotalFlightDurationColumnHeader);
 }
        public void VerticalPositionTest0() {
            String file = "vertical_position.pdf";

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

            writer.PageEvent = new CustomPageEvent();

            PdfPTable table = new PdfPTable(2);
            for (int i = 0; i < 100; i++) {
                table.AddCell("Hello " + i);
                table.AddCell("World " + i);
            }

            document.Add(table);

            document.NewPage();

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 1000; i++) {
                sb.Append("some more text ");
            }
            document.Add(new Paragraph(sb.ToString()));

            document.Close();

            // compare
            CompareTool compareTool = new CompareTool();
            String errorMessage = compareTool.CompareByContent(OUTPUT_FOLDER + file, TEST_RESOURCES_PATH + file,
                OUTPUT_FOLDER, "diff");
            if (errorMessage != null) {
                Assert.Fail(errorMessage);
            }
        }
        protected void generatePDFButton_Click(object sender, EventArgs e)
        {
            PdfPTable pdfPTable = new PdfPTable(CreatedStudentInformationGridView.HeaderRow.Cells.Count);

            foreach (TableCell headerCell in CreatedStudentInformationGridView.HeaderRow.Cells)
            {
                PdfPCell pfdPCell = new PdfPCell(new Phrase(headerCell.Text));
                //pfdPCell.BackgroundColor = new BaseColor(newCenterGridView.HeaderStyle.ForeColor);
                pdfPTable.AddCell(pfdPCell);
            }

            foreach (GridViewRow gridViewRow in CreatedStudentInformationGridView.Rows)
            {
                foreach (TableCell tableCell in gridViewRow.Cells)
                {

                    PdfPCell pfdPCell = new PdfPCell(new Phrase(tableCell.Text));
                    //pfdPCell.BackgroundColor = new BaseColor(newCenterGridView.HeaderStyle.ForeColor);
                    pdfPTable.AddCell(pfdPCell);
                }
            }
            Document pdfDocument = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
            PdfWriter.GetInstance(pdfDocument, Response.OutputStream);

            pdfDocument.Open();
            pdfDocument.Add(pdfPTable);
            pdfDocument.Close();

            Response.ContentType = "application/pdf";
            Response.AppendHeader("content-disposition", "attachment;filename=NewCenter.pdf");
            Response.Write(pdfDocument);
            Response.Flush();
            Response.End();
        }
        public static void GeneratePdfReport(string filepath)
        {
            FileStream fileStream = new FileStream(filepath, FileMode.Create);
            Document document = new Document();
            PdfWriter writer = PdfWriter.GetInstance(document, fileStream);
            document.SetPageSize(PageSize.A3);
            document.Open();

            var paragraph = new Paragraph("Aggregated Sales Report",
                FontFactory.GetFont("Arial", 19, Font.BOLD));
            paragraph.SpacingAfter = 20.0f;
            paragraph.Alignment = 1;

            document.Add(paragraph);

            PdfPTable mainTable = new PdfPTable(1);
            var reports = GetDayReports();
            foreach (var dayReport in reports)
            {
                var headerCell = new PdfPCell(new Phrase("Date: " + dayReport.FormattedDate));
                headerCell.BackgroundColor = new BaseColor(175, 166, 166);
                mainTable.AddCell(headerCell);
                var table = GenerateReportTable(dayReport);
                mainTable.AddCell(table);
            }

            document.Add(mainTable);
            document.Close();
        }
        public override void OnEndPage(PdfWriter writer, Document document)
        {
            PdfPTable footer = new PdfPTable(3);
            footer.SetWidths(new float[] { 88f, 7f, 5f });
            footer.WidthPercentage = 100;
            footer.TotalWidth = document.PageSize.Width - (document.LeftMargin + document.RightMargin);

            PdfPCell emptycell = new PdfPCell();
            emptycell.Border = 0;
            footer.AddCell(emptycell);

            Chunk text = new Chunk(string.Format(GlobalStringResource.PageOfFooter,
                document.PageNumber), FontFactory.GetFont(FontFactory.HELVETICA, 8));

            PdfPCell footerCell = new PdfPCell(new Phrase(text));
            footerCell.Border = 0;
            footerCell.HorizontalAlignment = Element.ALIGN_RIGHT;
            footer.AddCell(footerCell);

            PdfPCell cell = new PdfPCell(iTextSharp.text.Image.GetInstance(total));
            cell.Border = 0;
            cell.HorizontalAlignment = Element.ALIGN_LEFT;
            footer.AddCell(cell);
            footer.WriteSelectedRows(0, -1, 50, (document.BottomMargin - 10), writer.DirectContent);
        }
Example #20
0
// ---------------------------------------------------------------------------
    /**
     * Creates a table with film festival screenings.
     * @param day a film festival day
     * @return a table with screenings.
     */
    public PdfPTable GetTable(string day) {
      PdfPTable table = new PdfPTable(new float[] { 2, 1, 2, 5, 1 });
      table.WidthPercentage = 100f;
      table.DefaultCell.Padding = 3;
      table.DefaultCell.UseAscender = true;
      table.DefaultCell.UseDescender = true;
      table.DefaultCell.Colspan = 5;
      table.DefaultCell.BackgroundColor = BaseColor.RED;
      table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
      table.AddCell(day);
      table.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
      table.DefaultCell.Colspan = 1;
      table.DefaultCell.BackgroundColor = BaseColor.ORANGE;
      for (int i = 0; i < 2; i++) {
        table.AddCell("Location");
        table.AddCell("Time");
        table.AddCell("Run Length");
        table.AddCell("Title");
        table.AddCell("Year");
      }
      table.DefaultCell.BackgroundColor = null;
      table.HeaderRows = 3;
      table.FooterRows = 1;
      List<Screening> screenings = PojoFactory.GetScreenings(day);
      Movie movie;
      foreach (Screening screening in screenings) {
        movie = screening.movie;
        table.AddCell(screening.Location);
        table.AddCell(screening.Time.Substring(0, 5));
        table.AddCell(movie.Duration.ToString() + " '");
        table.AddCell(movie.MovieTitle);
        table.AddCell(movie.Year.ToString());
      }
      return table;
    }
        public override void writePdf(bool bBlackAndWhite=false)
        {
            initFile();
            PdfPTable table = new PdfPTable(m_iCount + 1);
            int cellHeight = ((int)m_doc.PageSize.Height - 200) / m_iCount;
            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance("");
            image.ScaleAbsolute(cellHeight / 2, cellHeight / 2);
            for (int j = 0; j < m_iCount; j++)
            {
                int cnt = s_random.Next(1, m_iMax);

                for (int i = 0; i < m_iMax; i++)
                {
                    if (i < cnt)
                    {
                        table.AddCell(image);
                    }
                    else
                    {
                        table.AddCell(new Phrase(" "));
                    }

                }

                table.AddCell(rectangle);

            }
            m_doc.Add(table);

            printSiteName();
            m_doc.Close();
        }
        // to generate the report call the GeneratePDFReport static method.
        // The pdf file will be generated in the SupermarketChain.ConsoleClient folder
        // TODO measures are missing
        // TODO code refactoring to limitr repeated chunks
        public static void GeneratePDFReport()
        {
            Document doc = new Document(iTextSharp.text.PageSize.A4, 10, 10, 40, 35);
            string filePath = @"..\..\..\..\Reports\salesReports.pdf";
            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Create));
            doc.Open();
            PdfPTable table = new PdfPTable(5);

            Font verdana = FontFactory.GetFont("Verdana", 16, Font.BOLD);
            Font verdana2 = FontFactory.GetFont("Verdana", 12, Font.BOLD);

            PdfPCell header = new PdfPCell(new Phrase("Aggregated Sales Report", verdana));
            header.Colspan = 5;
            header.HorizontalAlignment = 1;
            table.AddCell(header);

            double totalSales = PourReportData(table);

            PdfPCell totalSum = new PdfPCell(new Phrase("Grand total:"));
            totalSum.Colspan = 4;
            totalSum.HorizontalAlignment = 2;
            totalSum.BackgroundColor = new BaseColor(161, 212, 224);
            table.AddCell(totalSum);

            PdfPCell totalSumNumber = new PdfPCell(new Phrase(String.Format("{0:0.00}", totalSales), verdana));
            totalSumNumber.BackgroundColor = new BaseColor(161, 212, 224);
            table.AddCell(totalSumNumber);

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

            DirectoryInfo directoryInfo = new DirectoryInfo(filePath);
            Console.WriteLine("Pdf report generated.");
            Console.WriteLine("File:  {0}", directoryInfo.FullName);
        }
Example #23
0
        public override iTextSharp.text.IElement GeneratePdfElement()
        {
            TableStyle style = (Manifest != null) ? Manifest.Styles.GetMergedFromConfiguration(Style) : Style;

            int columnCount = (Rows.Any()) ? Rows.First().Cells.Count : 0;
            iTextPdf.PdfPTable table = new iTextPdf.PdfPTable(columnCount)
            {
                HorizontalAlignment = (int) (style.HorizontalAlignment ?? TableStyle.Default.HorizontalAlignment.Value),
                SpacingBefore = style.SpacingBefore ?? TableStyle.Default.SpacingBefore.Value,
                SpacingAfter = style.SpacingAfter ?? TableStyle.Default.SpacingAfter.Value,
                LockedWidth = style.LockedWidth ?? TableStyle.Default.LockedWidth.Value,
            };

            Rows.SelectMany(r => r.Cells).ForEach(c => table.AddCell((iTextPdf.PdfPCell) c.GeneratePdfElement()));

            if (style.Widths != null && style.Widths.Any())
            {
                table.SetTotalWidth(style.Widths);
            }
            if (style.WidthPercentage.HasValue)
            {
                table.WidthPercentage = style.WidthPercentage.Value;
            }

            return table;
        }
 public void CreatePdf(String dest)
 {
     Document document = new Document();
     PdfWriter.GetInstance(document, new FileStream(dest, FileMode.Create));
     document.Open();
     PdfPTable table = new PdfPTable(5);
     table.SetWidths(new int[] {1, 2, 2, 2, 1});
     PdfPCell cell;
     cell = new PdfPCell(new Phrase("S/N"));
     cell.Rowspan = 2;
     table.AddCell(cell);
     cell = new PdfPCell(new Phrase("Name"));
     cell.Colspan = 3;
     table.AddCell(cell);
     cell = new PdfPCell(new Phrase("Age"));
     cell.Rowspan = 2;
     table.AddCell(cell);
     table.AddCell("SURNAME");
     table.AddCell("FIRST NAME");
     table.AddCell("MIDDLE NAME");
     table.AddCell("1");
     table.AddCell("James");
     table.AddCell("Fish");
     table.AddCell("Stone");
     table.AddCell("17");
     document.Add(table);
     document.Close();
 }
        private static PdfPTable GenerateReportTable(DayReport report)
        {
            PdfPTable table = new PdfPTable(5);
            
            string[] headerTitles = {"Product", "Quantity", "Unit Price", "Location", "Sum"};
            foreach (var title in headerTitles)
            {
                Phrase phrase = new Phrase(title);
                phrase.Font = FontFactory.GetFont("Arial", 14, Font.BOLD);
                PdfPCell cell = new PdfPCell(phrase);
                cell.BackgroundColor = new BaseColor(175, 166, 166);
                table.AddCell(cell);
                cell.Padding = 0;
            }

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

            PdfPCell footerCell = new PdfPCell(new Phrase("Total sum for " + report.FormattedDate + ": "));
            footerCell.Colspan = 4;
            footerCell.HorizontalAlignment = 2;
            table.AddCell(footerCell);
            table.AddCell(new Phrase(report.TotalSum.ToString()));
            return table;
        }
Example #26
0
 public void GenerarDocumento(Document document)
 {
     int i, j;
     PdfPTable datatable = new PdfPTable(dataGridView1.ColumnCount);
     datatable.DefaultCell.Padding = 3;
     float[] headerwidths = GetTamañoColumnas(dataGridView1);
     datatable.SetWidths(headerwidths);
     datatable.WidthPercentage = 100;
     datatable.DefaultCell.BorderWidth = 2;
     datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
     for (i = 0; i < dataGridView1.ColumnCount; i++)
     {
         datatable.AddCell(dataGridView1.Columns[i].HeaderText);
     }
     datatable.HeaderRows = 1;
     datatable.DefaultCell.BorderWidth = 1;
     for (i = 0; i < dataGridView1.Rows.Count; i++)
     {
         for (j = 0; j < dataGridView1.Columns.Count; j++)
         {
             if (dataGridView1[j, i].Value != null)
             {
                 datatable.AddCell(new Phrase(dataGridView1[j, i].Value.ToString()));//En esta parte, se esta agregando un renglon por cada registro en el datagrid
             }
         }
         datatable.CompleteRow();
     }
     document.Add(datatable);
 }
Example #27
0
    protected void Button2_Click(object sender, EventArgs e)
    {
        int columnsCount = GridView1.HeaderRow.Cells.Count;
        // Create the PDF Table specifying the number of columns
        PdfPTable pdfTable = new PdfPTable(columnsCount);

        // Loop thru each cell in GrdiView header row
        foreach(TableCell gridViewHeaderCell in GridView1.HeaderRow.Cells)
        {
        // Create the Font Object for PDF document
        Font font = new Font();
        // Set the font color to GridView header row font color
        font.Color = new BaseColor(GridView1.HeaderStyle.ForeColor);

        // Create the PDF cell, specifying the text and font
        PdfPCell pdfCell = new PdfPCell(new Phrase(gridViewHeaderCell.Text, font));

        // Set the PDF cell backgroundcolor to GridView header row BackgroundColor color
        pdfCell.BackgroundColor = new BaseColor(GridView1.HeaderStyle.BackColor);

        // Add the cell to PDF table
        pdfTable.AddCell(pdfCell);
        }

        // Loop thru each datarow in GrdiView
        foreach (GridViewRow gridViewRow in GridView1.Rows)
        {
        if (gridViewRow.RowType == DataControlRowType.DataRow)
        {
            // Loop thru each cell in GrdiView data row
            foreach (TableCell gridViewCell in gridViewRow.Cells)
            {
                Font font = new Font();
                font.Color = new BaseColor(GridView1.RowStyle.ForeColor);

                PdfPCell pdfCell = new PdfPCell(new Phrase(gridViewCell.Text, font));

                pdfCell.BackgroundColor = new BaseColor(GridView1.RowStyle.BackColor);

                pdfTable.AddCell(pdfCell);
            }
        }
        }

        // Create the PDF document specifying page size and margins
        Document pdfDocument = new Document(PageSize.A4, 10f, 10f, 10f, 10f);

        PdfWriter.GetInstance(pdfDocument, Response.OutputStream);

        pdfDocument.Open();
        pdfDocument.Add(pdfTable);
        pdfDocument.Close();

        Response.ContentType = "application/pdf";
        Response.AppendHeader("content-disposition",
        "attachment;filename=Employees.pdf");
        Response.Write(pdfDocument);
        Response.Flush();
        Response.End();
    }
Example #28
0
        /// <summary>
        /// 创建测试者信息和测试信息表格
        /// </summary>
        /// <param name="tableEle"></param>
        /// <param name="columnCount"></param>
        protected void CreateTestInfoTable(XElement tableEle, int columnCount)
        {
            string    remark         = tableEle.Attribute("remark").Value;
            Paragraph parTableRemark = new Paragraph(remark, fontTableRemark);

            parTableRemark.IndentationLeft = 24;
            parTableRemark.SpacingBefore   = 20;
            pdfDoc.Add(parTableRemark);

            PdfPTable      table   = new iTextSharp.text.pdf.PdfPTable(columnCount);
            List <PdfPRow> rowList = new List <iTextSharp.text.pdf.PdfPRow>();

            foreach (XElement rowEle in tableEle.Elements())
            {
                List <PdfPCell> cellList = new List <iTextSharp.text.pdf.PdfPCell>();
                foreach (XElement cellEle in rowEle.Elements())
                {
                    string label = cellEle.Attribute("label").Value;
                    string value = cellEle.Attribute("value").Value;
                    if (value.Trim().Equals(""))
                    {
                        value = "/";
                    }

                    iTextSharp.text.pdf.PdfPCell cellLabel = new iTextSharp.text.pdf.PdfPCell(new Phrase(label, fontLabel));
                    cellLabel.FixedHeight         = 24;
                    cellLabel.Padding             = 4;
                    cellLabel.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                    cellLabel.VerticalAlignment   = PdfPCell.ALIGN_MIDDLE;

                    PdfPCell cellContent = new iTextSharp.text.pdf.PdfPCell(new Phrase(value, fontContent));
                    cellContent.FixedHeight       = 24;
                    cellContent.PaddingTop        = 4;
                    cellContent.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
                    XAttribute colSpanAtt = cellEle.Attribute("colspan");
                    if (colSpanAtt != null)
                    {
                        string colspan = colSpanAtt.Value;
                        if (colspan != "")
                        {
                            cellContent.Colspan = int.Parse(colspan);
                        }
                    }
                    cellList.Add(cellLabel);
                    cellList.Add(cellContent);
                }
                PdfPRow row = new iTextSharp.text.pdf.PdfPRow(cellList.ToArray <PdfPCell>());
                rowList.Add(row);
            }
            table.Rows.AddRange(rowList);
            table.KeepTogether  = true;
            table.SpacingBefore = 10;
            table.TotalWidth    = 750;
            table.LockedWidth   = true;
            Paragraph pTable = new Paragraph();

            pTable.Add(table);
            pdfDoc.Add(pTable);
        }
Example #29
0
        private void exportAsPDFToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            saveFileDialog1.Title            = "Save the PDF file!";
            saveFileDialog1.FileName         = "users";
            saveFileDialog1.Filter           = "*.pdf|*.pdf";
            if (saveFileDialog1.ShowDialog() != DialogResult.Cancel)
            {
                if (dataGridView1.Rows.Count == 0)
                {
                    MessageBox.Show("The DataGridView is empty. Please fill it!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    try
                    {
                        Document  doc = new Document(iTextSharp.text.PageSize.A4);
                        PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(saveFileDialog1.FileName.ToString(), FileMode.Create));
                        doc.Open(); // Open document to be written

                        iTextSharp.text.Image PNG = iTextSharp.text.Image.GetInstance(System.Reflection.Assembly.GetExecutingAssembly().Location + "\\..\\..\\..\\Resources\\logoprogram.png");

                        PNG.SetAbsolutePosition(doc.PageSize.Width / 2 - 200f, doc.PageSize.Height - 250f);
                        doc.Add(PNG);

                        Paragraph paragraphTable = new Paragraph();
                        paragraphTable.SpacingBefore = 200f;


                        iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(dataGridView1.Columns.Count);

                        // Add the headers to the PDF
                        for (int j = 0; j < dataGridView1.Columns.Count; j++)
                        {
                            table.AddCell(new Phrase(dataGridView1.Columns[j].HeaderText));
                        }

                        table.HeaderRows = 1;

                        for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
                        {
                            for (int j = 0; j < dataGridView1.Columns.Count; j++)
                            {
                                table.AddCell(new Phrase(dataGridView1.Rows[i].Cells[j].Value.ToString()));
                            }
                        }
                        paragraphTable.Add(table);

                        doc.Add(paragraphTable);
                        doc.Close();
                        MessageBox.Show("File exported succesfully!", "Succes!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Can't export the file!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
    private bool AddColumnHeader(DataTable dt, ref iTextSharp.text.pdf.PdfPTable mainTable, List <int> lstColumnNums, Dictionary <int, Helper.Alignment> dicDataType, List <int> lstColumnsDisplay)
    {
        try {
            mainTable.DefaultCell.BackgroundColor = iTextSharp.text.BaseColor.BLACK;

            // Sets the gridview column names as table headers.

            foreach (int iCol in lstColumnNums)
            {
                if (lstColumnsDisplay.Count > 0 && lstColumnsDisplay.Contains(iCol) == false)
                {
                    continue;
                }

                Phrase ph = default(Phrase);
                //Dim strText As String = If(iCol = 999, String.Empty, dt.Columns(iCol).Caption)
                if (iCol == 999)
                {
                    PdfPCell cell = EmptyCell();
                    cell.BackgroundColor = iTextSharp.text.BaseColor.WHITE;
                    mainTable.AddCell(cell);
                }
                else
                {
                    ph            = new Phrase(dt.Columns[iCol].Caption, FontFactory.GetFont(SelectedFont, ColumnHeaderTextSize, iTextSharp.text.Font.NORMAL));
                    ph.Font.Color = iTextSharp.text.BaseColor.WHITE;

                    PdfPCell cell = new PdfPCell(ph);
                    //cell.HorizontalAlignment = GetAlignMent(dicDataType[iCol]);

                    if ((int)dicDataType[iCol] == (int)Helper.Alignment.Center)
                    {
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    }
                    if ((int)dicDataType[iCol] == (int)Helper.Alignment.Right)
                    {
                        cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    }
                    if ((int)dicDataType[iCol] == (int)Helper.Alignment.Left)
                    {
                        cell.HorizontalAlignment = Element.ALIGN_LEFT;
                    }

                    cell.BackgroundColor = iTextSharp.text.BaseColor.GREEN;
                    //cell. Color == iTextSharp.text.BaseColor.BLACK
                    cell.NoWrap = true;
                    mainTable.AddCell(cell);
                }
            }
            mainTable.CompleteRow();
            mainTable.DefaultCell.BackgroundColor = iTextSharp.text.BaseColor.WHITE;
        } catch (Exception ex) {
            //PHLog.ErrorLogException(ex, oGV, System.Reflection.MethodBase.GetCurrentMethod.Name);
        }
        return(true);
    }
 private static void GenerateHeaders(iTextSharp.text.pdf.PdfPTable aTable, PdfPCell headers, string NameHeader)
 {
     headers = new PdfPCell(new Phrase(NameHeader));
     headers.BorderWidthRight    = 1;
     headers.HorizontalAlignment = 1;
     headers.BackgroundColor     = new iTextSharp.text.BaseColor(247, 150, 70);
     headers.BorderColor         = new iTextSharp.text.BaseColor(0, 0, 0);
     headers.Colspan             = 1;
     aTable.AddCell(headers);
 }
Example #32
0
        private void myWriteButton_Click(object sender, RoutedEventArgs e)
        {
            String fileName = SaveFileDialog();

            if (String.IsNullOrWhiteSpace(fileName))
            {
                return;
            }


            using (WaitDlg dlg = new WaitDlg())
            {
                Document document = new Document(PageSize.LETTER);

                //document.SetMargins(0, 0, 10, 0);
                // WORKING! document.SetMargins(document.LeftMargin, document.RightMargin, 25, 25);
                document.SetMargins(document.LeftMargin, document.RightMargin, 15, 10);


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


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



                iTextSharp.text.Paragraph paragraph = new iTextSharp.text.Paragraph();
                PdfPTable table = new pdf.PdfPTable(3);
                table.SpacingBefore = 0;
                table.SpacingAfter  = 10;
                table.TotalWidth    = 175.5f * 3.0f + 30f;
                table.LockedWidth   = true;


                List <Card> smallCards = GetSelectedCards(true, false);
                List <Card> bigCards   = GetSelectedCards(false, true);


                WriteCards(bigCards, table);
                WriteCards(smallCards, table);


                table.AddCell(new PdfPCell());
                table.AddCell(new PdfPCell());
                table.AddCell(new PdfPCell());

                document.Add(table);

                document.Close();
            }

            MessageBox.Show("PDF Generation Complete!");
        }
Example #33
0
        public override void BeginTable(int columnsCount, int rowsCount)
        {
            fTable = new itTable(columnsCount);

            //table.WidthPercentage = 100f;
            //table.TableFitsPage = true;
            //table.Padding = 2f;
            //table.Spacing = 0f;
            //table.Cellpadding = 2f;
            //table.Cellspacing = 0f;
            //table.SpaceInsideCell = 2f;
            //table.BorderColor = Color.BLACK;
            //table.BorderWidth = 1f;
            //table.DefaultCellBackgroundColor = new Color(System.Drawing.Color.CornflowerBlue);
            //table.DefaultVerticalAlignment = Element.ALIGN_TOP;
            //int[] widths = new int[] { 5, 20, 10, 15, 10, 15, 20 };
            //table.SetWidths(widths);
        }
Example #34
0
        private static void SetTable(Document doc, string title, Dictionary <string, string> rowItems)
        {
            var table = new iTextSharp.text.pdf.PdfPTable(2);

            table.WidthPercentage = 100;

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

            // table title
            var titleCell = new PdfPCell(new Phrase(title, fontTableHeader))
            {
                Colspan             = 2,
                MinimumHeight       = 28f,
                BackgroundColor     = lightblue,
                HorizontalAlignment = Element.ALIGN_CENTER,
                VerticalAlignment   = Element.ALIGN_MIDDLE
            };

            table.AddCell(titleCell);

            // table rows
            var itemsCount = 0;

            foreach (var item in rowItems)
            {
                var color = itemsCount % 2 == 0
                        ? BaseColor.WHITE : lightblue;

                SetRowCell(table, item.Key, Element.ALIGN_LEFT, color);

                SetRowCell(table, string.IsNullOrEmpty(item.Value) ? "-" : item.Value, Element.ALIGN_RIGHT, color);

                itemsCount++;
            }

            doc.Add(table);

            // Empty rows after title
            doc.Add(new Paragraph(" "));
        }
Example #35
0
        public void SetHeader(DateTime data, string casa, string tipoEvento, string homenageados, int pax, string horario, string cerimonial, string produtor, string contatoProdutor, string assessoria, string contatoAssessoria, string responsavel, string contatoResponsavel, string perfil)
        {
            header = new iPdf.PdfPTable(3);
            header.WidthPercentage = 100F;
            header.SetWidths(new float[] { 1F, 1F, 1F });
            header.SpacingBefore = 10F;
            header.SpacingAfter  = 10F;

            iText.Chunk headChunk = new iText.Chunk(
                string.Format("{0} > {1} > {2} > {3}", data.ToString("dd/MM/yyyy"), casa, tipoEvento, homenageados));
            headChunk.Font = iText.FontFactory.GetFont(baseFont, leadSize, iText.Font.BOLD);
            iPdf.PdfPCell headerCell = new iPdf.PdfPCell(new iText.Phrase(headChunk));
            headerCell.Colspan = 3;
            header.AddCell(headerCell);

            header.AddCell(new iPdf.PdfPCell(MakePhrase("Pax: ", string.Format("{0} +10% ({1})", pax, (int)(pax * 1.1)))));
            header.AddCell(new iPdf.PdfPCell(MakePhrase("Horário:", horario)));
            header.AddCell(new iPdf.PdfPCell(MakePhrase("Cerimonial: ", cerimonial)));

            iPdf.PdfPCell detailCell = new iPdf.PdfPCell(MakePhrase("Observações: ", perfil));
            detailCell.Rowspan = 3;
            header.AddCell(new iPdf.PdfPCell(detailCell));

            header.AddCell(new iPdf.PdfPCell(MakePhrase("Produtor(a): ", produtor)));
            header.AddCell(new iPdf.PdfPCell(MakePhrase("Contato: ", contatoProdutor)));

            header.AddCell(new iPdf.PdfPCell(MakePhrase("Assessoria: ", assessoria)));
            if (string.IsNullOrEmpty(contatoAssessoria))
            {
                header.AddCell(new iPdf.PdfPCell(new iText.Phrase("")));
            }
            else
            {
                header.AddCell(new iPdf.PdfPCell(MakePhrase("Contato: ", contatoAssessoria)));
            }

            header.AddCell(new iPdf.PdfPCell(MakePhrase("Responsável(a): ", responsavel)));
            header.AddCell(new iPdf.PdfPCell(MakePhrase("Contato: ", contatoResponsavel)));
        }
Example #36
0
        public ActionResult SavePDFOnDirectory()
        {
            var    FileTime     = DateTime.Now.ToFileTime();
            string pdfFilePath  = Server.MapPath("~/Rotativa/PDF");
            string FileName     = FileTime + ".pdf";
            string fullFilePath = pdfFilePath + "\\" + FileName;

            for (int i = 0; i < Request.Files.Count; i++)
            {
                var Imagefile = Request.Files[i];
                var fileName  = Path.GetFileName(Imagefile.FileName + ".png");
                var Imagepath = Path.Combine(Server.MapPath("~/Rotativa/blob"), fileName);
                Imagefile.SaveAs(Imagepath);
                Guid      guid   = Guid.NewGuid();
                Document  doc    = new Document(PageSize.A4_LANDSCAPE, 10f, 10f, 5f, 10f);
                PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(fullFilePath, FileMode.Create));
                doc.Open();
                try
                {
                    Paragraph                     paragraph = new Paragraph("Calender Event Details");
                    iTextSharp.text.Image         Png       = iTextSharp.text.Image.GetInstance(Imagepath);
                    iTextSharp.text.pdf.PdfPCell  cell      = new iTextSharp.text.pdf.PdfPCell(Png);
                    iTextSharp.text.pdf.PdfPTable table     = new iTextSharp.text.pdf.PdfPTable(1);
                    cell.FixedHeight         = 250;
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell.VerticalAlignment   = Element.ALIGN_CENTER;
                    Png.ScaleAbsolute(550, 350);
                    table.AddCell(cell);
                    doc.Add(paragraph);
                    doc.Add(Png);
                    doc.Close();
                }
                catch (Exception ex)
                { return(RedirectToAction("Index", "Login", new { ReturnUrl = "/BoomRoom" })); }
            }
            return(Json(new { fileName = FileName }, JsonRequestBehavior.AllowGet));
        }
        protected void OnExportToPDF()
        {
            try
            {
                int noOfColumns = 0, noOfRows = 0;
                noOfColumns = 4;
                noOfRows    = AllSales.Count;

                float HeaderTextSize      = 8;
                float ReportNameSize      = 10;
                float ReportTextSize      = 8;
                float ApplicationNameSize = 7;

                // Creates a PDF document

                document = null;
                document = new Document(PageSize.A4, 0, 0, 15, 5);

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

                // Sets the first 4 rows of the table as the header rows which will be repeated in all the pages.
                mainTable.HeaderRows = 4;

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

                // Creates a phrase to hold the application name at the left hand side of the header.
                Phrase phApplicationName = new Phrase("Total Month Sales", FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));

                // Creates a PdfPCell which accepts a phrase as a parameter.
                PdfPCell clApplicationName = new PdfPCell(phApplicationName);
                // Sets the border of the cell to zero.
                clApplicationName.Border = PdfPCell.NO_BORDER;
                // Sets the Horizontal Alignment of the PdfPCell to left.
                clApplicationName.HorizontalAlignment = Element.ALIGN_LEFT;

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

                // Creates a PdfPCell which accepts the date phrase as a parameter.
                PdfPCell clDate = new PdfPCell(phDate);
                // Sets the Horizontal Alignment of the PdfPCell to right.
                clDate.HorizontalAlignment = Element.ALIGN_RIGHT;
                // Sets the border of the cell to zero.
                clDate.Border = PdfPCell.NO_BORDER;

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

                // Creates a PdfPCell that accepts the headerTable as a parameter and then adds that cell to the main PdfPTable.
                PdfPCell cellHeader = new PdfPCell(headerTable);
                cellHeader.Border = PdfPCell.NO_BORDER;
                // Sets the column span of the header cell to noOfColumns.
                cellHeader.Colspan = noOfColumns;
                // Adds the above header cell to the table.
                mainTable.AddCell(cellHeader);

                // Creates a phrase which holds the file name.
                Phrase   phHeader = new Phrase("Sales for " + SelectedMonth, FontFactory.GetFont("Arial", ReportNameSize, iTextSharp.text.Font.BOLD));
                PdfPCell clHeader = new PdfPCell(phHeader);
                clHeader.Colspan             = noOfColumns;
                clHeader.Border              = PdfPCell.NO_BORDER;
                clHeader.HorizontalAlignment = Element.ALIGN_CENTER;
                mainTable.AddCell(clHeader);

                // Creates a phrase for a new line.
                Phrase   phSpace = new Phrase("\n");
                PdfPCell clSpace = new PdfPCell(phSpace);
                clSpace.Border  = PdfPCell.NO_BORDER;
                clSpace.Colspan = noOfColumns;
                mainTable.AddCell(clSpace);

                // Sets the gridview column names as table headers.

                mainTable.AddCell(new Phrase("Seller", FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD)));
                mainTable.AddCell(new Phrase("Product", FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD)));
                mainTable.AddCell(new Phrase("Qty", FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD)));
                mainTable.AddCell(new Phrase("Total", FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD)));

                // Reads the gridview rows and adds them to the mainTable
                foreach (var item in AllSales)
                {
                    {
                        mainTable.AddCell(new Phrase(item.Seller, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL)));
                        mainTable.AddCell(new Phrase(item.OrderItems.Name, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL)));
                        mainTable.AddCell(new Phrase(item.OrderItems.Quantity.ToString(), FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL)));
                        mainTable.AddCell(new Phrase(item.ItemTotal.ToString(), FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL)));
                    }
                    // Tells the mainTable to complete the row even if any cell is left incomplete.
                    mainTable.CompleteRow();
                }


                // Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
                PdfWriter wri = PdfWriter.GetInstance(document, new System.IO.FileStream("SalesReport.pdf", FileMode.Create));

                document.Open();//Open Document to write


                Paragraph paragraph = new Paragraph("data Exported From DataGridview!");

                document.Add(mainTable);
                //doc.Add(t1);
                document.Close(); //Close document
                //Ope the pdf file just created
                System.Diagnostics.Process.Start(@"SalesReport.pdf");
            }
            catch
            {
                MessageBox.Show("The Pdf could not be created or it could not be opened", "Error PDF", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Example #38
0
        public static ActionResult PDF(
            int companyId,
            bool externa,
            string from,
            bool interna,
            bool provider,
            bool status0,
            bool status1,
            bool status2,
            bool status3,
            bool status4,
            bool status5,
            string to,
            string filterText,
            string listOrder)
        {
            var source = "AuditoryExportList";
            var res    = ActionResult.NoAction;
            var user   = HttpContext.Current.Session["User"] as ApplicationUser;

            Dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
            var    company = new Company(companyId);
            string path    = HttpContext.Current.Request.PhysicalApplicationPath;

            if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
            {
                path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
            }

            var formatedDescription = ToolsPdf.NormalizeFileName(company.Name);

            string fileName = string.Format(
                CultureInfo.InvariantCulture,
                @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf",
                Dictionary["Item_Auditories"],
                formatedDescription,
                DateTime.Now);


            var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50);
            var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc,
                                                                   new FileStream(
                                                                       string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName),
                                                                       FileMode.Create));

            writer.PageEvent = new TwoColumnHeaderFooter
            {
                CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id),
                IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
                Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
                CreatedBy   = user.UserName,
                CompanyId   = company.Id,
                CompanyName = company.Name,
                Title       = Dictionary["Item_Auditories"].ToUpperInvariant()
            };

            pdfDoc.Open();

            var titleTable = new iTSpdf.PdfPTable(1);

            titleTable.SetWidths(new float[] { 50f });
            titleTable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", Dictionary["Item_EquipmentList"], company.Name), ToolsPdf.LayoutFonts.TitleFont))
            {
                HorizontalAlignment = iTS.Element.ALIGN_CENTER,
                Border = iTS.Rectangle.NO_BORDER
            });

            //------ CRITERIA
            var criteriatable = new iTSpdf.PdfPTable(4)
            {
                WidthPercentage = 100
            };

            criteriatable.SetWidths(new float[] { 10f, 50f, 10f, 80f });

            #region texts

            string criteriaProccess = Dictionary["Common_All_Male_Plural"];

            string periode = string.Empty;
            if (!string.IsNullOrEmpty(from) && string.IsNullOrEmpty(to))
            {
                periode = Dictionary["Item_Incident_List_Filter_From"] + " " + from;
            }
            else if (string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to))
            {
                periode = Dictionary["Item_Incident_List_Filter_To"] + " " + to;
            }
            else if (!string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to))
            {
                periode = from + " - " + to;
            }
            else
            {
                periode = Dictionary["Common_All_Male"];
            }

            string typetext  = string.Empty;
            bool   firtsType = false;
            if (interna)
            {
                typetext += Dictionary["Item_Adutory_Type_Label_0"];
                firtsType = false;
            }
            if (externa)
            {
                typetext += firtsType ? string.Empty : ", ";
                typetext += Dictionary["Item_Adutory_Type_Label_1"];
                firtsType = false;
            }
            if (provider)
            {
                typetext += firtsType ? string.Empty : ", ";
                typetext += Dictionary["Item_Adutory_Type_Label_2"];
            }
            if (firtsType)
            {
                typetext = Dictionary["Common_All_Female_Plural"];
            }

            string statustext  = string.Empty;
            bool   firstStatus = false;
            if (status0)
            {
                statustext += Dictionary["Item_Adutory_Status_Label_0"];
                firstStatus = false;
            }
            if (status1)
            {
                statustext += firstStatus ? string.Empty : ", ";
                statustext += Dictionary["Item_Adutory_Status_Label_1"];
                firstStatus = false;
            }
            if (status2)
            {
                statustext += firstStatus ? string.Empty : ", ";
                statustext += Dictionary["Item_Adutory_Status_Label_2"];
                firstStatus = false;
            }
            if (status3)
            {
                statustext += firstStatus ? string.Empty : ", ";
                statustext += Dictionary["Item_Adutory_Status_Label_3"];
                firstStatus = false;
            }
            if (status4)
            {
                statustext += firstStatus ? string.Empty : ", ";
                statustext += Dictionary["Item_Adutory_Status_Label_4"];
                firstStatus = false;
            }
            if (status5)
            {
                statustext += firstStatus ? string.Empty : ", ";
                statustext += Dictionary["Item_Adutory_Status_Label_5"];
            }
            if (firstStatus)
            {
                statustext = Dictionary["Common_All_Male_Plural"];
            }


            #endregion

            criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(Dictionary["Common_Period"]));
            criteriatable.AddCell(ToolsPdf.CriteriaCellData(periode));
            criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(Dictionary["Item_Auditory_Filter_Type"]));
            criteriatable.AddCell(ToolsPdf.CriteriaCellData(typetext));
            criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(Dictionary["Item_Auditory_Filter_Status"]));
            criteriatable.AddCell(ToolsPdf.CriteriaCellData(statustext));
            if (!string.IsNullOrEmpty(filterText))
            {
                criteriatable.AddCell(ToolsPdf.CriteriaCellLabel(Dictionary["Common_PDF_Filter_Contains"]));
                criteriatable.AddCell(ToolsPdf.CriteriaCellData(filterText));
            }
            else
            {
                criteriatable.AddCell(ToolsPdf.CriteriaCellData(string.Empty));
                criteriatable.AddCell(ToolsPdf.CriteriaCellData(string.Empty));
            }

            pdfDoc.Add(criteriatable);
            //---------------------------

            var tableWidths = new float[] { 40f, 10f, 10f, 10f, 10f, 10f };
            var table       = new iTSpdf.PdfPTable(tableWidths.Length)
            {
                WidthPercentage     = 100,
                HorizontalAlignment = 1,
                SpacingBefore       = 20f,
                SpacingAfter        = 30f
            };

            table.SetWidths(tableWidths);

            table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Auditory_ListHeader_Name"]));
            table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Auditory_Filter_Type"]));
            table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Auditory_ListHeader_Status"]));
            table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Auditory_ListHeader_Planned"]));
            table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Auditory_ListHeader_Closed"]));
            table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Auditory_ListHeader_Ammount"]));

            int cont = 0;
            var data = new List <Auditory>();
            using (var cmd = new SqlCommand("Auditory_Filter"))
            {
                using (var cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["cns"].ConnectionString))
                {
                    cmd.Connection  = cnn;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add(DataParameter.Input("@CompanyId", companyId));
                    cmd.Parameters.Add(DataParameter.Input("@From", from));
                    cmd.Parameters.Add(DataParameter.Input("@To", to));
                    cmd.Parameters.Add(DataParameter.Input("@TypeInterna", interna));
                    cmd.Parameters.Add(DataParameter.Input("@TypeExterna", externa));
                    cmd.Parameters.Add(DataParameter.Input("@TypeProveedor", provider));
                    cmd.Parameters.Add(DataParameter.Input("@Status0", status0));
                    cmd.Parameters.Add(DataParameter.Input("@Status1", status1));
                    cmd.Parameters.Add(DataParameter.Input("@Status2", status2));
                    cmd.Parameters.Add(DataParameter.Input("@Status3", status3));
                    cmd.Parameters.Add(DataParameter.Input("@Status4", status4));
                    cmd.Parameters.Add(DataParameter.Input("@Status5", status5));
                    try
                    {
                        cmd.Connection.Open();
                        using (var rdr = cmd.ExecuteReader())
                        {
                            while (rdr.Read())
                            {
                                var newAuditory = new Auditory
                                {
                                    Id          = rdr.GetInt64(ColumnsAuditoryFilter.Id),
                                    Description = rdr.GetString(ColumnsAuditoryFilter.Nombre),
                                    Amount      = rdr.GetDecimal(ColumnsAuditoryFilter.Amount),
                                    Status      = rdr.GetInt32(ColumnsAuditoryFilter.Status),
                                    Type        = rdr.GetInt32(ColumnsAuditoryFilter.Type)
                                };

                                if (!rdr.IsDBNull(ColumnsAuditoryFilter.PlannedOn))
                                {
                                    newAuditory.PlannedOn = rdr.GetDateTime(ColumnsAuditoryFilter.PlannedOn);
                                }

                                if (!rdr.IsDBNull(ColumnsAuditoryFilter.ValidatedOn))
                                {
                                    newAuditory.ValidatedOn = rdr.GetDateTime(ColumnsAuditoryFilter.ValidatedOn);
                                }

                                data.Add(newAuditory);
                            }
                        }
                    }
                    catch (SqlException ex)
                    {
                        ExceptionManager.Trace(ex, source);
                    }
                    catch (FormatException ex)
                    {
                        ExceptionManager.Trace(ex, source);
                    }
                    catch (NullReferenceException ex)
                    {
                        ExceptionManager.Trace(ex, source);
                    }
                    finally
                    {
                        if (cmd.Connection.State != ConnectionState.Closed)
                        {
                            cmd.Connection.Close();
                        }
                    }
                }
            }

            switch (listOrder.ToUpperInvariant())
            {
            default:
            case "TH1|ASC":
                data = data.OrderBy(d => d.Status).ToList();
                break;

            case "TH1|DESC":
                data = data.OrderByDescending(d => d.Status).ToList();
                break;

            case "TH2|ASC":
                data = data.OrderBy(d => d.Description).ToList();
                break;

            case "TH2|DESC":
                data = data.OrderByDescending(d => d.Description).ToList();
                break;

            case "TH3|ASC":
                data = data.OrderBy(d => d.PlannedOn).ToList();
                break;

            case "TH3|DESC":
                data = data.OrderByDescending(d => d.PlannedOn).ToList();
                break;

            case "TH4|ASC":
                data = data.OrderBy(d => d.ValidatedOn).ToList();
                break;

            case "TH4|DESC":
                data = data.OrderByDescending(d => d.ValidatedOn).ToList();
                break;

            case "TH5|ASC":
                data = data.OrderBy(d => d.Amount).ToList();
                break;

            case "TH5|DESC":
                data = data.OrderByDescending(d => d.Amount).ToList();
                break;
            }

            foreach (var auditory in data)
            {
                if (!string.IsNullOrEmpty(filterText))
                {
                    var match = auditory.Description;
                    if (match.IndexOf(filterText, StringComparison.OrdinalIgnoreCase) == -1)
                    {
                        continue;
                    }
                }
                cont++;
                string statustextCell = string.Empty;
                switch (auditory.Status)
                {
                case 0: statustextCell = Dictionary["Item_Adutory_Status_Label_0"]; break;

                case 1: statustextCell = Dictionary["Item_Adutory_Status_Label_1"]; break;

                case 2: statustextCell = Dictionary["Item_Adutory_Status_Label_2"]; break;

                case 3: statustextCell = Dictionary["Item_Adutory_Status_Label_3"]; break;

                case 4: statustextCell = Dictionary["Item_Adutory_Status_Label_4"]; break;

                case 5: statustextCell = Dictionary["Item_Adutory_Status_Label_5"]; break;
                }

                string typetextCell = string.Empty;
                switch (auditory.Type)
                {
                case 0: typetextCell = Dictionary["Item_Adutory_Type_Label_0"]; break;

                case 1: typetextCell = Dictionary["Item_Adutory_Type_Label_1"]; break;

                case 2: typetextCell = Dictionary["Item_Adutory_Type_Label_2"]; break;
                }

                table.AddCell(ToolsPdf.DataCell(auditory.Description));
                table.AddCell(ToolsPdf.DataCellCenter(typetextCell));
                table.AddCell(ToolsPdf.DataCellCenter(statustextCell));
                table.AddCell(ToolsPdf.DataCellCenter(auditory.PlannedOn));
                table.AddCell(ToolsPdf.DataCellCenter(auditory.ValidatedOn));
                table.AddCell(ToolsPdf.DataCellMoney(auditory.Amount));
            }

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(
                                                                 CultureInfo.InvariantCulture,
                                                                 @"{0}: {1}",
                                                                 Dictionary["Common_RegisterCount"],
                                                                 cont), ToolsPdf.LayoutFonts.Times))
            {
                Border     = iTS.Rectangle.TOP_BORDER,
                Padding    = 6f,
                PaddingTop = 4f,
                Colspan    = 4
            });

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times))
            {
                Border  = iTS.Rectangle.TOP_BORDER,
                Colspan = 4
            });

            pdfDoc.Add(table);
            pdfDoc.CloseDocument();
            res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
            return(res);
        }
    public static ActionResult PDF(
        long equipmentId,
        int companyId,
        bool calibrationInternal,
        bool calibrationExternal,
        bool verificationInternal,
        bool verificationExternal,
        bool maintenanceInternal,
        bool maintenanceExternal,
        bool repairInternal,
        bool repairExternal,
        DateTime?dateFrom,
        DateTime?dateTo,
        string listOrder)
    {
        var res  = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;

        dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var equipment = Equipment.ById(equipmentId, companyId);
        var company   = new Company(equipment.CompanyId);
        var data      = HttpContext.Current.Session["EquipmentRecordsFilter"] as List <EquipmentRecord>;

        string path = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_Equipment"],
            equipment.Description,
            DateTime.Now);

        var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50);
        var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc,
                                                               new FileStream(
                                                                   string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName),
                                                                   FileMode.Create));

        writer.PageEvent = new TwoColumnHeaderFooter()
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = string.Format(CultureInfo.InvariantCulture, "{0}", user.UserName),
            CompanyId   = equipment.CompanyId,
            CompanyName = company.Name,
            Title       = dictionary["Item_Equipment_PDFTitle"].ToUpperInvariant()
        };

        pdfDoc.Open();

        var backgroundColor = new iTS.BaseColor(220, 220, 220);

        string periode = string.Empty;

        if (dateFrom.HasValue && dateTo.HasValue)
        {
            periode = string.Format(
                CultureInfo.InvariantCulture,
                @"Periode: {0:dd/MM/yyyy} - {1:dd/MM/yyyy}",
                dateFrom.Value,
                dateTo.Value);
        }
        else if (dateFrom.HasValue && dateTo == null)
        {
            periode = string.Format(
                CultureInfo.InvariantCulture,
                @"{1}: {0:dd/MM/yyyy}",
                dateFrom.Value,
                dictionary["Common_From"]);
        }
        else if (dateFrom == null && dateTo.HasValue)
        {
            periode = string.Format(
                CultureInfo.InvariantCulture,
                @"{1}: {0:dd/MM/yyyy}",
                dateTo.Value,
                dictionary["Common_To"]);
        }

        if (string.IsNullOrEmpty(periode))
        {
            periode = dictionary["Common_PeriodAll"];
        }

        var criteriatable = new iTSpdf.PdfPTable(2)
        {
            WidthPercentage = 100
        };

        criteriatable.SetWidths(new float[] { 25f, 250f });

        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_Equipment"], ToolsPdf.LayoutFonts.TimesBold))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });

        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(equipment.Description, ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });

        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Period"], ToolsPdf.LayoutFonts.TimesBold))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });

        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(periode, ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });

        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_Customer_Header_Type"], ToolsPdf.LayoutFonts.TimesBold))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });

        string typeText  = string.Empty;
        bool   firstType = true;

        if (calibrationInternal)
        {
            firstType = false;
            typeText += dictionary["Item_EquipmentRecord_Filter_CalibrationInternal"];
        }

        if (calibrationExternal)
        {
            if (!firstType)
            {
                typeText += " - ";
            }

            typeText += dictionary["Item_EquipmentRecord_Filter_CalibrationExternal"];
            firstType = false;
        }

        if (verificationInternal)
        {
            if (!firstType)
            {
                typeText += " - ";
            }

            typeText += dictionary["Item_EquipmentRecord_Filter_VerificationInternal"];
            firstType = false;
        }

        if (verificationExternal)
        {
            if (!firstType)
            {
                typeText += " - ";
            }

            typeText += dictionary["Item_EquipmentRecord_Filter_VerificationExternal"];
            firstType = false;
        }
        if (maintenanceInternal)
        {
            if (!firstType)
            {
                typeText += " - ";
            }

            typeText += dictionary["Item_EquipmentRecord_Filter_MaintenanceInternal"];
            firstType = false;
        }

        if (maintenanceExternal)
        {
            if (!firstType)
            {
                typeText += " - ";
            }

            typeText += dictionary["Item_EquipmentRecord_Filter_MaintenanceExternal"];
            firstType = false;
        }

        if (repairInternal)
        {
            if (!firstType)
            {
                typeText += " - ";
            }

            typeText += dictionary["Item_EquipmentRecord_Filter_RepairInternal"];
            firstType = false;
        }

        if (repairExternal)
        {
            if (!firstType)
            {
                typeText += " - ";
            }

            typeText += dictionary["Item_EquipmentRecord_Filter_RepairExternal"];
        }

        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(typeText, ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });

        pdfDoc.Add(criteriatable);

        var table = new iTSpdf.PdfPTable(5)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 0,
            SpacingBefore       = 20f,
            SpacingAfter        = 30f
        };

        //relative col widths in proportions - 1/3 and 2/3
        table.SetWidths(new float[] { 10f, 20f, 15f, 30f, 15f });

        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_EquipmentRepair_HeaderList_Date"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_EquipmentRepair_HeaderList_Type"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_EquipmentRepair_HeaderList_Operation"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_EquipmentRepair_HeaderList_Responsible"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_EquipmentRepair_HeaderList_Cost"]));

        decimal totalCost = 0;
        int     cont      = 0;

        // Poner el tipo de registro diccionarizado
        foreach (var record in data)
        {
            record.RecordTypeText = dictionary[record.Item + "-" + (record.RecordType == 0 ? "Int" : "Ext")];
        }

        switch (listOrder.ToUpperInvariant())
        {
        default:
        case "TH0|ASC":
            data = data.OrderBy(d => d.Date).ToList();
            break;

        case "TH0|DESC":
            data = data.OrderByDescending(d => d.Date).ToList();
            break;

        case "TH1|ASC":
            data = data.OrderBy(d => d.RecordTypeText).ToList();
            break;

        case "TH1|DESC":
            data = data.OrderByDescending(d => d.RecordTypeText).ToList();
            break;

        case "TH2|ASC":
            data = data.OrderBy(d => d.Operation).ToList();
            break;

        case "TH2|DESC":
            data = data.OrderByDescending(d => d.Operation).ToList();
            break;

        case "TH3|ASC":
            data = data.OrderBy(d => d.Responsible.FullName).ToList();
            break;

        case "TH3|DESC":
            data = data.OrderByDescending(d => d.Responsible.FullName).ToList();
            break;

        case "TH4|ASC":
            data = data.OrderBy(d => d.Cost).ToList();
            break;

        case "TH4|DESC":
            data = data.OrderByDescending(d => d.Cost).ToList();
            break;
        }

        foreach (var equipmentRecord in data)
        {
            table.AddCell(ToolsPdf.DataCellCenter(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", equipmentRecord.Date), ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCell(equipmentRecord.RecordTypeText, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCell(equipmentRecord.Operation, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCell(equipmentRecord.Responsible.FullName, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCellMoney(equipmentRecord.Cost, ToolsPdf.LayoutFonts.Times));

            if (equipmentRecord.Cost.HasValue)
            {
                totalCost += equipmentRecord.Cost.Value;
            }

            cont++;
        }


        string totalRegistros = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}: {1}",
            dictionary["Common_RegisterCount"],
            cont);

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalRegistros, ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = ToolsPdf.SummaryBackgroundColor,
            Padding         = 6f,
            PaddingTop      = 4f,
            Colspan         = 2
        });

        table.AddCell(new PdfPCell(new iTS.Phrase(dictionary["Common_Total"], ToolsPdf.LayoutFonts.Times))
        {
            Border = iTS.Rectangle.TOP_BORDER,
            HorizontalAlignment = iTS.Element.ALIGN_RIGHT,
            BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
            Colspan             = 2
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:#,##0.00}", totalCost), ToolsPdf.LayoutFonts.Times))
        {
            Border              = iTS.Rectangle.TOP_BORDER,
            BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
            HorizontalAlignment = iTS.Element.ALIGN_RIGHT
        });

        pdfDoc.Add(table);
        pdfDoc.CloseDocument();
        res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
        return(res);
    }
Example #40
0
        private void button1_Click_1(object sender, EventArgs e)
        {
            /* try
             * {*/
            String comando = String.Format("SELECT * FROM equipo WHERE codigo = '{0}'", id);
            string paths   = Application.StartupPath.Substring(0, (Application.StartupPath.Length - 10));

            //Se lee los datos de la base de datos
            DataRow reader = Conexion.Data(comando).Rows[0];
            //Variable de salto de linea
            Paragraph saltoDeLinea = new Paragraph("                                                                                                                                                                                                                                                                                                                                                                                   ");

            //Se trae la fecha actual
            DateTime fecha_actual = DateTime.Now;

            //Se inicializa el documento PDF
            Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);

            doc.SetMargins(0, 0, 10, 10);
            PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(@"C:\fichas_tecnicas\" + reader["nombre"] + ".pdf", FileMode.Create));

            doc.Open();

            iTextSharp.text.Image PNG = iTextSharp.text.Image.GetInstance("Cabecera.PNG");
            doc.Add(PNG);

            Paragraph paragrah1 = new Paragraph("Ficha técnica", FontFactory.GetFont("Arial", 20));

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

            doc.Add(saltoDeLinea);


            //Se crea la tabla para mostrar los datos de la BD
            iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(10);
            PdfPCell celda1 = new PdfPCell(new Paragraph("Código", FontFactory.GetFont("Tahoma", 10)));

            table.AddCell(celda1);
            PdfPCell celda2 = new PdfPCell(new Paragraph("Nombre", FontFactory.GetFont("Tahoma", 10)));

            table.AddCell(celda2);
            PdfPCell celda3 = new PdfPCell(new Paragraph("Costo del equipo", FontFactory.GetFont("Tahoma", 10)));

            table.AddCell(celda3);
            PdfPCell celda4 = new PdfPCell(new Paragraph("Modelo del equipo", FontFactory.GetFont("Tahoma", 10)));

            table.AddCell(celda4);
            PdfPCell celda5 = new PdfPCell(new Paragraph("Capacidad de producción", FontFactory.GetFont("Tahoma", 10)));

            table.AddCell(celda5);
            PdfPCell celda6 = new PdfPCell(new Paragraph("Peso equipo", FontFactory.GetFont("Tahoma", 10)));

            table.AddCell(celda6);
            PdfPCell celda7 = new PdfPCell(new Paragraph("Altura equipo", FontFactory.GetFont("Tahoma", 10)));

            table.AddCell(celda7);
            PdfPCell celda8 = new PdfPCell(new Paragraph("Ancho equipo", FontFactory.GetFont("Tahoma", 10)));

            table.AddCell(celda8);
            PdfPCell celda9 = new PdfPCell(new Paragraph("Largo equipo".ToString(), FontFactory.GetFont("Tahoma", 10)));

            table.AddCell(celda9);
            PdfPCell celda10 = new PdfPCell(new Paragraph("Marca equipo", FontFactory.GetFont("Tahoma", 10)));

            table.AddCell(celda10);
            PdfPCell celda12 = new PdfPCell(new Paragraph(reader["codigo"].ToString(), FontFactory.GetFont("Times New Roman", 8)));

            table.AddCell(celda12);
            PdfPCell celda13 = new PdfPCell(new Paragraph(reader["nombre"].ToString(), FontFactory.GetFont("Times New Roman", 8)));

            table.AddCell(celda13);
            PdfPCell celda14 = new PdfPCell(new Paragraph(reader["costo_equipo"].ToString(), FontFactory.GetFont("Times New Roman", 8)));

            table.AddCell(celda14);
            PdfPCell celda15 = new PdfPCell(new Paragraph(reader["modelo_equipo"].ToString(), FontFactory.GetFont("Times New Roman", 8)));

            table.AddCell(celda15);
            PdfPCell celda16 = new PdfPCell(new Paragraph(reader["capacidad_produccion"].ToString(), FontFactory.GetFont("Times New Roman", 8)));

            table.AddCell(celda16);
            PdfPCell celda17 = new PdfPCell(new Paragraph(reader["peso"].ToString(), FontFactory.GetFont("Times New Roman", 8)));

            table.AddCell(celda17);
            PdfPCell celda18 = new PdfPCell(new Paragraph(reader["altura"].ToString(), FontFactory.GetFont("Times New Roman", 8)));

            table.AddCell(celda18);
            PdfPCell celda19 = new PdfPCell(new Paragraph(reader["ancho"].ToString(), FontFactory.GetFont("Times New Roman", 8)));

            table.AddCell(celda19);
            PdfPCell celda20 = new PdfPCell(new Paragraph(reader["largo"].ToString(), FontFactory.GetFont("Times New Roman", 8)));

            table.AddCell(celda20);
            PdfPCell celda21 = new PdfPCell(new Paragraph(reader["marca"].ToString(), FontFactory.GetFont("Times New Romanº", 8)));

            table.AddCell(celda21);
            doc.Add(table);

            doc.Add(saltoDeLinea);
            //Se muestran las caracteristicas del equipo
            Paragraph paragrah5 = new Paragraph("Características técnicas", FontFactory.GetFont("Arial", 15));

            paragrah5.Alignment = Element.ALIGN_CENTER;
            doc.Add(paragrah5);
            Paragraph paragrah3 = new Paragraph("El equipo tiene las siguientes características técnicas: " + reader["caract_tecni"].ToString(), FontFactory.GetFont("Arial", 12));

            paragrah3.Alignment = Element.ALIGN_JUSTIFIED;
            doc.Add(paragrah3);
            doc.Add(saltoDeLinea);

            // Se muestra fecha actual
            Paragraph paragraph4 = new Paragraph("" + fecha_actual, FontFactory.GetFont("Arial", 13));

            doc.Add(saltoDeLinea);
            paragraph4.Alignment = Element.ALIGN_RIGHT;
            doc.Add(paragraph4);
            //Se coloca imagen de pie de pagina
            iTextSharp.text.Image PNG1 = iTextSharp.text.Image.GetInstance("PieDePagina.PNG");
            PNG1.SetAbsolutePosition(0, -10);
            doc.Add(PNG1);

            if (doc.ToString() != "")
            {
                MessageBox.Show("El documento se ha descargado satisfactoriamente", "Correcto", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("El documento no se pudo descargar, vuelva a intentar en unos minutos", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            doc.NewPage();

            doc.Close();

            /*}
             * catch (Exception)
             * {
             *  MessageBox.Show("Error al descargar el PDF", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
             * }*/
        }
Example #41
0
    public static ActionResult PDF(int companyId, string yearFrom, string yearTo, string mode, string listOrder, string textFilter)
    {
        var res  = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;

        dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var    company = new Company(companyId);
        string path    = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(company.Name);

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_LearningList"],
            formatedDescription,
            DateTime.Now);

        // FONTS
        string pathFonts = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts);
        }

        var headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        var arial      = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

        var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50);
        var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc,
                                                               new FileStream(
                                                                   string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName),
                                                                   FileMode.Create));

        // evento para poner titulo y pie de página cada vez que salta de página
        writer.PageEvent = new TwoColumnHeaderFooter
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = user.UserName,
            CompanyId   = company.Id,
            CompanyName = company.Name,
            Title       = dictionary["Item_LearningList"].ToUpperInvariant()
        };

        pdfDoc.Open();

        var backgroundColor = new iTS.BaseColor(225, 225, 225);
        var rowEven         = new iTS.BaseColor(240, 240, 240);

        var titleTable = new iTSpdf.PdfPTable(1);

        titleTable.SetWidths(new float[] { 50f });
        titleTable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_EquipmentList"], company.Name), ToolsPdf.LayoutFonts.TitleFont))
        {
            HorizontalAlignment = iTS.Element.ALIGN_CENTER,
            Border = iTS.Rectangle.NO_BORDER
        });

        //------ CRITERIA
        var criteriatable = new iTSpdf.PdfPTable(4)
        {
            WidthPercentage = 100
        };

        criteriatable.SetWidths(new float[] { 3f, 12f, 3f, 22f });

        string periode = string.Empty;

        if (!string.IsNullOrEmpty(yearFrom) && yearFrom != "0" && !string.IsNullOrEmpty(yearTo) && yearTo != "0")
        {
            periode = yearFrom + " - " + yearTo;
        }
        else if (!string.IsNullOrEmpty(yearFrom) && yearFrom != "0")
        {
            periode = dictionary["Common_From"] + " " + yearFrom;
        }
        else if (!string.IsNullOrEmpty(yearTo) && yearTo != "0")
        {
            periode = dictionary["Item_Incident_List_Filter_To"] + " " + yearTo;
        }

        if (string.IsNullOrEmpty(periode))
        {
            periode = dictionary["Item_Learning_Filter_AllPeriode"];
        }
        ;

        string modeText = dictionary["Common_All_Female_Plural"];

        if (!string.IsNullOrEmpty(mode))
        {
            modeText = string.Empty;
            bool first = true;
            if (mode.IndexOf("0") != -1)
            {
                modeText += dictionary["Item_Learning_Status_InProgress"];
                first     = false;
            }

            if (mode.IndexOf("1") != -1)
            {
                if (!first)
                {
                    modeText += ", ";
                }
                modeText += dictionary["Item_Learning_Status_Started"];
                first     = false;
            }
            if (mode.IndexOf("2") != -1)
            {
                if (!first)
                {
                    modeText += ", ";
                }
                modeText += dictionary["Item_Learning_Status_Finished"];
                first     = false;
            }
            if (mode.IndexOf("3") != -1)
            {
                if (!first)
                {
                    modeText += ", ";
                }
                modeText += dictionary["Item_Learning_Status_Evaluated"];
            }
        }

        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Period"] + " :", ToolsPdf.LayoutFonts.TimesBold))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });

        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(periode, ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });

        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Status"] + " :", ToolsPdf.LayoutFonts.TimesBold))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });

        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(modeText, ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });

        if (!string.IsNullOrEmpty(textFilter))
        {
            criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_PDF_Filter_Contains"] + " :", ToolsPdf.LayoutFonts.TimesBold))
            {
                Border = ToolsPdf.BorderNone,
                HorizontalAlignment = iTS.Element.ALIGN_LEFT,
                Padding             = 6f,
                PaddingTop          = 4f
            });

            criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(textFilter, ToolsPdf.LayoutFonts.Times))
            {
                Border = ToolsPdf.BorderNone,
                HorizontalAlignment = iTS.Element.ALIGN_LEFT,
                Padding             = 6f,
                PaddingTop          = 4f,
                Colspan             = 5
            });
        }

        pdfDoc.Add(criteriatable);

        var table = new iTSpdf.PdfPTable(5)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1,
            SpacingBefore       = 20f,
            SpacingAfter        = 30f
        };

        table.SetWidths(new float[] { 15f, 5f, 5f, 5f, 5f });
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Learning_FieldLabel_Course"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Learning_FieldLabel_EstimatedDate"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Learning_ListHeader_DateComplete"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Learning_FieldLabel_Status"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Learning_FieldLabel_Cost"]));
        int cont = 0;

        DateTime?yFrom = null;
        DateTime?yTo   = null;

        if (!string.IsNullOrEmpty(yearFrom) && yearFrom != "0")
        {
            // yFrom = Tools.TextToDate(yearFrom);
            var parts = yearFrom.Split('/');
            yFrom = new DateTime(Convert.ToInt32(parts[2]), Convert.ToInt32(parts[1]), Convert.ToInt32(parts[0]));
        }

        if (!string.IsNullOrEmpty(yearTo) && yearTo != "0")
        {
            // yTo = Tools.TextToDate(yearTo);
            var parts = yearTo.Split('/');
            yTo = new DateTime(Convert.ToInt32(parts[2]), Convert.ToInt32(parts[1]), Convert.ToInt32(parts[0]));
        }

        var learningFilter = new LearningFilter(companyId)
        {
            Pendent   = mode.IndexOf("0") != -1,
            Started   = mode.IndexOf("1") != -1,
            Finished  = mode.IndexOf("2") != -1,
            Evaluated = mode.IndexOf("3") != -1,
            YearFrom  = yFrom,
            YearTo    = yTo
        };

        decimal totalCost = 0;
        int     count     = 0;

        var data = learningFilter.Filter().ToList();

        if (!string.IsNullOrEmpty(listOrder))
        {
            switch (listOrder.ToUpperInvariant())
            {
            default:
            case "TH0|ASC":
                data = data.OrderBy(d => d.Description).ToList();
                break;

            case "TH0|DESC":
                data = data.OrderByDescending(d => d.Description).ToList();
                break;

            case "TH1|ASC":
                data = data.OrderBy(d => d.RealStart).ToList();
                break;

            case "TH1|DESC":
                data = data.OrderByDescending(d => d.RealStart).ToList();
                break;

            case "TH2|ASC":
                data = data.OrderBy(d => d.RealFinish).ToList();
                break;

            case "TH2|DESC":
                data = data.OrderByDescending(d => d.RealFinish).ToList();
                break;

            case "TH3|ASC":
                data = data.OrderBy(d => d.Status).ToList();
                break;

            case "TH3|DESC":
                data = data.OrderByDescending(d => d.Status).ToList();
                break;

            case "TH4|ASC":
                data = data.OrderBy(d => d.Amount).ToList();
                break;

            case "TH4|DESC":
                data = data.OrderByDescending(d => d.Amount).ToList();
                break;
            }
        }

        // aplicar filtro de texto
        if (!string.IsNullOrEmpty(textFilter))
        {
            data = data.Where(d => d.Description.IndexOf(textFilter, StringComparison.OrdinalIgnoreCase) != -1).ToList();
        }

        foreach (var learning in data)
        {
            count++;
            learning.ObtainAssistance();
            string assist = string.Empty;
            bool   first  = true;
            foreach (var alumno in learning.Assistance)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    assist += ", ";
                }

                assist += alumno.Employee.FullName;
            }

            if (string.IsNullOrEmpty(assist))
            {
                assist = "(" + dictionary["Item_LearningList_NoAssistants"] + ")";
            }

            int border = 0;
            table.AddCell(ToolsPdf.DataCell(learning.Description));
            table.AddCell(ToolsPdf.DataCellCenter(learning.DateEstimated));

            /*
             * string fecha = Tools.TranslatedMonth(learning.DateEstimated.Month, dictionary) + " " + learning.DateEstimated.Year;
             * table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(fecha, ToolsPdf.LayoutFonts.Times))
             * {
             *  Border = border,
             *  Padding = 6f,
             *  PaddingTop = 4f,
             *  HorizontalAlignment = Rectangle.ALIGN_CENTER
             * });
             */
            if (learning.RealFinish != null)
            {
                if (learning.RealFinish.Value.Year == 1970)
                {
                    table.AddCell(ToolsPdf.DataCell(string.Empty));
                }
                else
                {
                    table.AddCell(ToolsPdf.DataCellCenter(learning.RealFinish));
                }
            }
            else
            {
                table.AddCell(ToolsPdf.DataCell(string.Empty));
            }

            string statusText = string.Empty;
            switch (learning.Status)
            {
            default:
            case 0: statusText = dictionary["Item_Learning_Status_InProgress"]; break;

            case 1: statusText = dictionary["Item_Learning_Status_Started"]; break;

            case 2: statusText = dictionary["Item_Learning_Status_Finished"]; break;

            case 3: statusText = dictionary["Item_Learning_Status_Evaluated"]; break;
            }

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(statusText, ToolsPdf.LayoutFonts.Times))
            {
                Border              = border,
                Padding             = ToolsPdf.PaddingTableCell,
                PaddingTop          = ToolsPdf.PaddingTopTableCell,
                HorizontalAlignment = Rectangle.ALIGN_CENTER
            });

            table.AddCell(ToolsPdf.DataCellMoney(learning.Amount));
            totalCost += learning.Amount;

            cont++;
        }

        string totalRegistros = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}: {1}",
            dictionary["Common_RegisterCount"],
            count);

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalRegistros, ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = rowEven,
            Padding         = 6f,
            PaddingTop      = 4f,
            Colspan         = 3
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant(), ToolsPdf.LayoutFonts.Times))
        {
            Border              = iTS.Rectangle.TOP_BORDER,
            BackgroundColor     = rowEven,
            Padding             = 6f,
            PaddingTop          = 4f,
            HorizontalAlignment = 2
        });

        string totalText = string.Format("{0:#,##0.00}", totalCost);

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalText, ToolsPdf.LayoutFonts.Times))
        {
            Border              = iTS.Rectangle.TOP_BORDER,
            BackgroundColor     = rowEven,
            Padding             = 6f,
            PaddingTop          = 4f,
            HorizontalAlignment = 2
        });

        pdfDoc.Add(table);
        pdfDoc.CloseDocument();
        res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
        return(res);
    }
    private bool AddPageHeaderToPDFDataTableLogo(ref iTextSharp.text.pdf.PdfPTable mainTable, string sName, int noOfColumns)
    {
        //As iTextSharp.text.pdf.PdfPTable

        try {
            string strPath             = ""; //My.Application.Info.DirectoryPath + "\\syneco_rgb.jpg"
            iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(strPath);
            //'mainTable.LockedWidth = True
            float ReportNameSize      = 11;
            float ApplicationNameSize = 11;
            float FooterTextSize      = 8;
            float HeaderTextSize      = 9;


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

            // Creates a phrase to hold the application name at the left hand side of the header.
            Phrase phApplicationName = new Phrase("Eagle", FontFactory.GetFont(SelectedFont, ApplicationNameSize, iTextSharp.text.Font.NORMAL));
            //phApplicationName.Font = SelectedFont
            //'phApplicationName.Font.SetFamily(iTextSharp.text.Font.FontFamily.COURIER) ' .Font.SetFamily(SelectedFont)
            //'With phApplicationName.Font
            //'    .Size = ApplicationNameSize
            //'    '.SetFamily(iTextSharp.text.Font.FontFamily.COURIER)
            //'    .SetStyle(iTextSharp.text.Font.NORMAL)
            //'End With
            // Creates a PdfPCell which accepts a phrase as a parameter.
            PdfPCell clApplicationName = new PdfPCell(phApplicationName);

            // Sets the border of the cell to zero.
            clApplicationName.Border = PdfPCell.NO_BORDER;

            // Sets the Horizontal Alignment of the PdfPCell to left.
            clApplicationName.HorizontalAlignment = Element.ALIGN_CENTER;

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

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

            // Sets the Horizontal Alignment of the PdfPCell to right.
            clDate.HorizontalAlignment = Element.ALIGN_RIGHT;

            // Sets the border of the cell to zero.
            clDate.Border = PdfPCell.NO_BORDER;
            PdfPCell cllogo = new PdfPCell(logo);

            cllogo.HorizontalAlignment = Element.ALIGN_LEFT;

            cllogo.Border = PdfPCell.NO_BORDER;
            headerTable.AddCell(cllogo);

            // Adds the cell which holds the application name to the headerTable.
            headerTable.AddCell(clApplicationName);

            // Adds the cell which holds the date to the headerTable.
            headerTable.AddCell(clDate);

            // Creates a phrase which holds the file name.
            Phrase phHeader = new Phrase(sName, FontFactory.GetFont(SelectedFont, ReportNameSize, iTextSharp.text.Font.BOLD));
            //phHeader.Font = SelectedFont
            //'phHeader.Font.SetFamily(iTextSharp.text.Font.FontFamily.COURIER) '.Font.SetFamily(SelectedFont)
            //'With phHeader.Font
            //'    .Size = ReportNameSize
            //'    '.SetFamily(iTextSharp.text.Font.FontFamily.COURIER)
            //'    .SetStyle(iTextSharp.text.Font.BOLD)
            //'End With

            PdfPCell clHeader = new PdfPCell(phHeader);
            clHeader.Colspan             = noOfColumns;
            clHeader.Border              = PdfPCell.NO_BORDER;
            clHeader.HorizontalAlignment = Element.ALIGN_CENTER;
            headerTable.AddCell(clHeader);

            // Dim phFilter As New Phrase(strFormulaToPrint)

            //With phFilter.Font
            //    .Size = HeaderTextSize ' ReportTextSize
            //    .SetFamily(iTextSharp.text.Font.FontFamily.COURIER)
            //    .SetStyle(iTextSharp.text.Font.NORMAL)
            //End With

            //Dim clFilter As New PdfPCell(phFilter)
            //clFilter.Colspan = noOfColumns
            //clFilter.HorizontalAlignment = Element.ALIGN_LEFT
            //clFilter.Border = PdfPCell.NO_BORDER
            //headerTable.AddCell(clFilter)

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

            // Sets the column span of the header cell to noOfColumns.
            cellHeader.Colspan = noOfColumns;

            mainTable.AddCell(cellHeader);

            //mainTable.AddCell(clph)
            Phrase ph = new Phrase();
            // Creates a phrase for a new line.
            Phrase phSpace = new Phrase("\r\n");
            phSpace.Font.Size = 1;

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

            mainTable.CompleteRow();
            return(true);
        } catch (Exception ex) {
            //PHLog.ErrorLogException(ex, oGV, System.Reflection.MethodBase.GetCurrentMethod.Name);
        }
        return(true);
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        var learningId = Convert.ToInt32(Request.QueryString["id"]);
        var companyId = Convert.ToInt32(Request.QueryString["companyId"]);
        var company = new Company(companyId);
        var res = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;
        var dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary<string, string>;
        var learning = new Learning(learningId, companyId);

        string path = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(learning.Description);

        var fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_Learning"],
            formatedDescription,
            DateTime.Now);

        // FONTS
        var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath;
        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts);
        }

        this.headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        this.arial = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        var descriptionFont = new Font(this.headerFont, 12, Font.BOLD, BaseColor.BLACK);

        var document = new iTextSharp.text.Document(PageSize.A4, 40, 40, 65, 55);

        var writer = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create));
        var pageEventHandler = new TwoColumnHeaderFooter()
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId),
            IssusLogo = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy = string.Format(CultureInfo.InvariantCulture, "{0}", user.UserName),
            CompanyId = learning.CompanyId,
            CompanyName = company.Name,
            Title = dictionary["Item_Learning"]
        };

        writer.PageEvent = pageEventHandler;

        var borderSides = Rectangle.RIGHT_BORDER + Rectangle.LEFT_BORDER + Rectangle.BOTTOM_BORDER;

        document.Open();

        #region Dades bàsiques
        // Ficha pincipal
        var table = new PdfPTable(6)
        {
            WidthPercentage = 100,
            HorizontalAlignment = 0
        };

        table.SetWidths(new float[] { 30f, 30f, 30f, 30f, 30f, 30f });

        table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_Course"]));
        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(learning.Description, descriptionFont))
        {
            Border = 0,
            BackgroundColor = new iTS.BaseColor(255, 255, 255),
            Padding = 6f,
            PaddingTop = 4f,
            HorizontalAlignment = Rectangle.ALIGN_LEFT,
            Colspan = 5
        });

        table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_EstimatedDate"]));
        table.AddCell(ToolsPdf.DataCell(learning.DateEstimated, descriptionFont));

        table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_Hours"]));
        table.AddCell(ToolsPdf.DataCell(learning.Hours, descriptionFont));

        string statusText = string.Empty;
        switch (learning.Status)
        {
            case 1: statusText = dictionary["Item_Learning_Status_Started"]; break;
            case 2: statusText = dictionary["Item_Learning_Status_Finished"]; break;
            case 3: statusText = dictionary["Item_Learning_Status_Evaluated"]; break;
            default: statusText = dictionary["Item_Learning_Status_InProgress"]; break;
        }

        table.AddCell(TitleLabel(dictionary["Item_Learning_ListHeader_Status"]));
        table.AddCell(ToolsPdf.DataCell(statusText, descriptionFont));

        table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_StartDate"]));
        table.AddCell(ToolsPdf.DataCell(learning.RealStart, descriptionFont));

        table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_EndDate"]));
        table.AddCell(ToolsPdf.DataCell(learning.RealFinish, descriptionFont));

        table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_Amount"]));
        table.AddCell(ToolsPdf.DataCellMoney(learning.Amount, descriptionFont));

        table.AddCell(TitleLabel(dictionary["Item_Learning_FieldLabel_Coach"]));
        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(learning.Master, descriptionFont))
        {
            Border = 0,
            BackgroundColor = new iTS.BaseColor(255, 255, 255),
            Padding = 6f,
            PaddingTop = 4f,
            HorizontalAlignment = Rectangle.ALIGN_LEFT,
            Colspan = 5
        });

        // Objective
        table.AddCell(SeparationRow());
        table.AddCell(TitleAreaCell(dictionary["Item_Learning_Objetive"]));
        table.AddCell(TextAreaCell(Environment.NewLine + learning.Objective, borderSides, Rectangle.ALIGN_LEFT, 6));

        // Methodology
        table.AddCell(SeparationRow());
        table.AddCell(TitleAreaCell(dictionary["Item_Learning_FieldLabel_Methodology"]));
        table.AddCell(TextAreaCell(Environment.NewLine + learning.Methodology, borderSides, Rectangle.ALIGN_LEFT, 6));

        // Notes
        table.AddCell(SeparationRow());
        table.AddCell(TitleAreaCell(dictionary["Item_Learning_FieldLabel_Notes"]));
        table.AddCell(TextAreaCell(Environment.NewLine + learning.Notes, borderSides, Rectangle.ALIGN_LEFT, 6));

        document.Add(table);
        #endregion

        #region Asistentes
        var backgroundColor = new iTS.BaseColor(225, 225, 225);
        var rowPair = new iTS.BaseColor(255, 255, 255);
        var rowEven = new iTS.BaseColor(240, 240, 240);
        var headerFontFinal = new iTS.Font(headerFont, 9, iTS.Font.NORMAL, iTS.BaseColor.BLACK);

        document.SetPageSize(PageSize.A4.Rotate());
        document.NewPage();

        var tableAssistants = new iTSpdf.PdfPTable(3)
        {
            WidthPercentage = 100,
            HorizontalAlignment = 1,
            SpacingBefore = 20f
        };

        tableAssistants.SetWidths(new float[] { 90f, 20f, 20f });
        tableAssistants.AddCell(new PdfPCell(new Phrase(learning.Description, descriptionFont))
        {
            Colspan = 5,
            Border = Rectangle.NO_BORDER,
            PaddingTop = 20f,
            PaddingBottom = 20f,
            HorizontalAlignment = Element.ALIGN_CENTER
        });

        tableAssistants.AddCell(ToolsPdf.HeaderCell(dictionary["Item_LearningAssistants"]));
        tableAssistants.AddCell(ToolsPdf.HeaderCell(dictionary["Item_LearningAssistant_Status_Done"]));
        tableAssistants.AddCell(ToolsPdf.HeaderCell(dictionary["Item_LearningAssistant_Status_Evaluated"]));

        int cont = 0;
        bool pair = false;
        var times = new iTS.Font(arial, 8, iTS.Font.NORMAL, iTS.BaseColor.BLACK);
        var timesBold = new iTS.Font(arial, 8, iTS.Font.BOLD, iTS.BaseColor.BLACK);
        learning.ObtainAssistance();
        foreach (var assistance in learning.Assistance)
        {
            int border = 0;
            var lineBackground = pair ? rowEven : rowPair;

            tableAssistants.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(assistance.Employee.FullName, times))
            {
                Border = border,
                BackgroundColor = lineBackground,
                Padding = ToolsPdf.PaddingTableCell,
                PaddingTop = ToolsPdf.PaddingTopTableCell
            });

            string completedText = string.Empty;
            if (assistance.Completed.HasValue)
            {
                completedText = assistance.Completed.Value ? dictionary["Common_Yes"] : dictionary["Common_No"];
            }

            tableAssistants.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(completedText, times))
            {
                Border = border,
                BackgroundColor = lineBackground,
                HorizontalAlignment = Element.ALIGN_CENTER,
                Padding = ToolsPdf.PaddingTableCell,
                PaddingTop = ToolsPdf.PaddingTopTableCell
            });

            string successText = string.Empty;
            if (assistance.Success.HasValue)
            {
                successText = assistance.Success.Value ? dictionary["Common_Yes"] : dictionary["Common_No"];
            }

            tableAssistants.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(successText, times))
            {
                Border = border,
                BackgroundColor = lineBackground,
                HorizontalAlignment = Element.ALIGN_CENTER,
                Padding = ToolsPdf.PaddingTableCell,
                PaddingTop = ToolsPdf.PaddingTopTableCell
            });
            cont++;
        }

        // TotalRow
        if(learning.Assistance.Count == 0)
        {
            tableAssistants.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_LearningList_NoAssistants"], descriptionFont))
            {
                Border = iTS.Rectangle.TOP_BORDER,
                BackgroundColor = rowEven,
                Padding = ToolsPdf.PaddingTableCell,
                PaddingTop = ToolsPdf.PaddingTopTableCell,
                Colspan = 3,
                HorizontalAlignment = Rectangle.ALIGN_CENTER
            });
        }

        tableAssistants.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(
            CultureInfo.InvariantCulture,
            @"{0}: {1}",
            dictionary["Common_RegisterCount"],
            cont), times))
        {
            Border = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = rowEven,
            Padding = ToolsPdf.PaddingTableCell,
            PaddingTop = ToolsPdf.PaddingTopTableCell,
            Colspan = 3
        });

        document.Add(tableAssistants);
        #endregion

        document.Close();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "inline;filename=outfile.pdf");
        Response.ContentType = "application/pdf";
        Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName);
        Response.Flush();
        Response.Clear();
    }
Example #44
0
    public static ActionResult PDF(int companyId, string filter, string listOrder)
    {
        var res  = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;

        Dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var    company = new Company(companyId);
        string path    = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(company.Name);

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf",
            Dictionary["Item_DocumentList"],
            formatedDescription,
            DateTime.Now);

        var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50);
        var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc,
                                                               new FileStream(
                                                                   string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName),
                                                                   FileMode.Create));

        writer.PageEvent = new TwoColumnHeaderFooter
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = user.UserName,
            CompanyId   = company.Id,
            CompanyName = company.Name,
            Title       = Dictionary["Item_DocumentList"].ToUpperInvariant()
        };

        pdfDoc.Open();

        var titleTable = new iTSpdf.PdfPTable(1);

        titleTable.SetWidths(new float[] { 20f });
        titleTable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", Dictionary["Item_EquipmentList"], company.Name), ToolsPdf.LayoutFonts.TitleFont))
        {
            HorizontalAlignment = iTS.Element.ALIGN_CENTER,
            Border = iTS.Rectangle.NO_BORDER
        });

        var criteriatable = new iTSpdf.PdfPTable(6)
        {
            WidthPercentage = 100
        };

        criteriatable.SetWidths(new float[] { 10f, 20f, 12f, 30f, 10f, 80f });

        var criteria1Label = new iTSpdf.PdfPCell(new iTS.Phrase(Dictionary["Common_Status"] + " :", ToolsPdf.LayoutFonts.TimesBold))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        };

        var criteria2Label = new iTSpdf.PdfPCell(new iTS.Phrase(Dictionary["Item_Document_FieldLabel_Category"] + " :", ToolsPdf.LayoutFonts.TimesBold))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        };

        var criteria3Label = new iTSpdf.PdfPCell(new iTS.Phrase(Dictionary["Item_Document_FieldLabel_Origin"] + " :", ToolsPdf.LayoutFonts.TimesBold))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        };

        string statusText = Dictionary["Common_All_Male_Plural"];
        string category   = Dictionary["Common_All_Female_Plural"];
        string origin     = Dictionary["Common_All_Male_Plural"];

        if (filter.IndexOf("A|") != -1)
        {
            statusText = Dictionary["Common_Active_Plural"];
        }

        if (filter.StartsWith("I", StringComparison.OrdinalIgnoreCase))
        {
            statusText = Dictionary["Common_Inactive_Plural"];
        }

        if (filter.StartsWith("|", StringComparison.OrdinalIgnoreCase))
        {
            statusText = Dictionary["Common_None"];
        }

        var documents = GisoFramework.Item.Document.ByCompany(companyId);
        var data      = new List <GisoFramework.Item.Document>();

        // @alex: "A" indica que en el filtro se ha marcado "activos"
        if (filter.IndexOf("A") != -1)
        {
            data = documents.Where(d => d.EndDate.HasValue == false).ToList();
        }

        // @alex: "I" indica que en el filtro se ha marcado "inactivos"
        if (filter.IndexOf("I") != -1)
        {
            data.AddRange(documents.Where(d => d.EndDate.HasValue).ToList());
        }

        var parts = filter.Split('|');

        if (parts[1] != "-1")
        {
            data = data.Where(d => d.Category.Id == Convert.ToInt32(parts[1])).ToList();
            var cats = DocumentCategory.ByCompany(companyId);
            var cat  = cats.First(c => c.Id == Convert.ToInt32(parts[1]));
            category = cat.Description;
        }

        if (parts[2] == "0")
        {
            data   = data.Where(d => d.Origin.Id == 0).ToList();
            origin = Dictionary["Common_Internal"];
        }

        if (parts[2] == "1")
        {
            data   = data.Where(d => d.Origin.Id > 0).ToList();
            origin = Dictionary["Common_External"];
        }

        criteriatable.AddCell(criteria1Label);
        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(statusText, ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });
        criteriatable.AddCell(criteria2Label);
        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(category, ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });
        criteriatable.AddCell(criteria3Label);
        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(origin, ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });

        // @alex-20200605: hay que indicr que son 7 columnas en lugar de 6
        var table = new iTSpdf.PdfPTable(7)
                    //var table = new iTSpdf.PdfPTable(6)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1
        };

        // @alex-20200605: supongo que te petaba aquí porque le enviarías 7 anchos cuando sólo había 6 columnas (mensaje anterior)
        table.SetWidths(new float[] { 20f, 5f, 12f, 9f, 9f, 5f, 5f });
        //table.SetWidths(new float[] { 20f, 5f, 15f, 15f, 10f, 5f });
        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Document_ListHeader_Name"]));
        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Document_ListHeader_Code"]));
        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Document_ListHeader_Category"]));
        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Document_ListHeader_Origin"]));
        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Document_ListHeader_Location"]));
        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Document_ListHeader_Revision"]));
        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_BusinessRisk_LabelField_DateStart"]));

        switch (listOrder.ToUpperInvariant())
        {
        default:
        case "TH0|ASC":
            data = data.OrderBy(d => d.Description).ToList();
            break;

        case "TH0|DESC":
            data = data.OrderByDescending(d => d.Description).ToList();
            break;

        case "TH1|ASC":
            data = data.OrderBy(d => d.Code).ToList();
            break;

        case "TH1|DESC":
            data = data.OrderByDescending(d => d.Code).ToList();
            break;

        case "TH2|ASC":
            data = data.OrderBy(d => d.LastNumber).ToList();
            break;

        case "TH2|DESC":
            data = data.OrderByDescending(d => d.LastNumber).ToList();
            break;

        case "TH3|ASC":
            data = data.OrderBy(d => d.Origin).ToList();
            break;

        case "TH3|DESC":
            data = data.OrderByDescending(d => d.Origin).ToList();
            break;

        // @alex-20200605: toda columna ordenable en pantalla debe aparece aquí para replicar el orden en el pdf
        case "TH4|ASC":
            data = data.OrderBy(d => d.Location).ToList();
            break;

        case "TH4|DESC":
            data = data.OrderByDescending(d => d.Location).ToList();
            break;

        case "TH5|ASC":
            data = data.OrderBy(d => d.LastNumber).ToList();
            break;

        case "TH5|DESC":
            data = data.OrderByDescending(d => d.LastNumber).ToList();
            break;

        case "TH6|ASC":
            data = data.OrderBy(d => d.StartDate).ToList();
            break;

        case "TH6|DESC":
            data = data.OrderByDescending(d => d.StartDate).ToList();
            break;
        }

        int count = 0;

        foreach (var document in data)
        {
            count++;
            table.AddCell(ToolsPdf.DataCell(document.Description));
            table.AddCell(ToolsPdf.DataCell(document.Code));
            table.AddCell(ToolsPdf.DataCell(document.Category.Description));
            table.AddCell(ToolsPdf.DataCell(document.Origin.Id == 0 ? Dictionary["Common_Internal"] : Dictionary["Common_External"]));
            table.AddCell(ToolsPdf.DataCell(document.Location));
            table.AddCell(ToolsPdf.DataCell(document.LastNumber));
            table.AddCell(ToolsPdf.DataCell(document.StartDate));
        }

        string totalRegistros = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}: {1}",
            Dictionary["Common_RegisterCount"],
            count);

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalRegistros, ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = ToolsPdf.SummaryBackgroundColor,
            Padding         = 6f,
            PaddingTop      = 4f
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = ToolsPdf.SummaryBackgroundColor,
            Colspan         = 5
        });

        pdfDoc.Add(criteriatable);
        pdfDoc.Add(table);
        pdfDoc.CloseDocument();
        res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
        return(res);
    }
Example #45
0
    public static ActionResult PDF(int companyId, string listOrder)
    {
        var res  = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;

        dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var    company = new Company(companyId);
        string path    = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(company.Name);

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_EquipmentList"],
            formatedDescription,
            DateTime.Now);

        // FONTS
        string pathFonts = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts);
        }

        var headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        var arial      = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

        var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50);
        var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc,
                                                               new FileStream(
                                                                   string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName),
                                                                   FileMode.Create));

        writer.PageEvent = new TwoColumnHeaderFooter()
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = user.UserName,
            CompanyId   = company.Id,
            CompanyName = company.Name,
            Title       = dictionary["Item_EquipmentList"].ToUpperInvariant()
        };

        pdfDoc.Open();

        var backgroundColor = new iTS.BaseColor(225, 225, 225);
        var rowPair         = new iTS.BaseColor(255, 255, 255);
        var rowEven         = new iTS.BaseColor(240, 240, 240);

        var titleTable = new iTSpdf.PdfPTable(1);

        titleTable.SetWidths(new float[] { 50f });
        var titleCell = new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_EquipmentList"], company.Name), ToolsPdf.LayoutFonts.TitleFont))
        {
            HorizontalAlignment = iTS.Element.ALIGN_CENTER,
            Border = iTS.Rectangle.NO_BORDER
        };

        titleTable.AddCell(titleCell);

        // @alex: hay que indicar que hay una columna menos por fila
        //// var table = new iTSpdf.PdfPTable(4)
        var table = new iTSpdf.PdfPTable(3)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1,
            SpacingBefore       = 20f,
            SpacingAfter        = 30f
        };

        table.SetWidths(new float[] { 20f, 10f, 5f, 15f });

        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Equipment_Header_Code"] + " - " + dictionary["Item_Equipment_Header_Description"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Equipment_Header_Location"]));

        // @alex: se omite la columna de la cabecera
        //// table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Equipment_Header_Cost"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Equipment_Header_Responsible"]));

        int cont = 0;
        var data = Equipment.ByCompany(companyId).ToList();

        string filter = GetFilter();

        if (filter.IndexOf("1", StringComparison.OrdinalIgnoreCase) != -1)
        {
            data = data.Where(d => !d.EndDate.HasValue).ToList();
        }

        if (filter.IndexOf("2", StringComparison.OrdinalIgnoreCase) != -1)
        {
            data = data.Where(d => d.EndDate.HasValue).ToList();
        }

        var dataC = new List <Equipment>();

        if (filter.IndexOf("C", StringComparison.OrdinalIgnoreCase) != -1)
        {
            dataC = data.Where(d => d.IsCalibration).ToList();
        }

        var dataV = new List <Equipment>();

        if (filter.IndexOf("V", StringComparison.OrdinalIgnoreCase) != -1)
        {
            dataV = data.Where(d => d.IsVerification).ToList();
        }

        var dataM = new List <Equipment>();

        if (filter.IndexOf("M", StringComparison.OrdinalIgnoreCase) != -1)
        {
            dataM = data.Where(d => d.IsMaintenance).ToList();
        }

        data = dataC;
        foreach (var equipmentV in dataV)
        {
            if (!data.Any(d => d.Id == equipmentV.Id))
            {
                data.Add(equipmentV);
            }
        }

        foreach (var equipmentM in dataM)
        {
            if (!data.Any(d => d.Id == equipmentM.Id))
            {
                data.Add(equipmentM);
            }
        }

        // aplicar filtros

        //------ CRITERIA
        var criteriatable = new iTSpdf.PdfPTable(2)
        {
            WidthPercentage = 100
        };

        criteriatable.SetWidths(new float[] { 8f, 50f });

        string statusText    = string.Empty;
        string operativaText = string.Empty;

        if (filter.IndexOf("0") != -1)
        {
            statusText = dictionary["Common_All"];
        }
        else if (filter.IndexOf("1") != -1)
        {
            statusText = dictionary["Item_Equipment_List_Filter_ShowActive"];
        }
        else if (filter.IndexOf("2") != -1)
        {
            statusText = dictionary["Item_Equipment_List_Filter_ShowClosed"];
        }

        bool first = true;

        if (filter.IndexOf("C") != -1)
        {
            first         = false;
            operativaText = dictionary["Item_Equipment_List_Filter_ShowCalibration"];
        }
        if (filter.IndexOf("V") != -1)
        {
            if (!first)
            {
                operativaText += ", ";
            }
            first          = false;
            operativaText += dictionary["Item_Equipment_List_Filter_ShowVerification"];
        }
        if (filter.IndexOf("M") != -1)
        {
            if (!first)
            {
                operativaText += ", ";
            }
            first          = false;
            operativaText += dictionary["Item_Equipment_List_Filter_ShowMaintenance"];
        }

        ToolsPdf.AddCriteria(criteriatable, dictionary["Item_Equipment_List_Filter_ShowByOperation"], operativaText);
        ToolsPdf.AddCriteria(criteriatable, dictionary["Item_Equipment_List_Filter_ShowByStatus"], statusText);

        bool    pair   = false;
        decimal total  = 0;
        int     border = 0;

        if (!string.IsNullOrEmpty(listOrder))
        {
            switch (listOrder.ToUpperInvariant())
            {
            default:
            case "TH0|ASC":
                data = data.OrderBy(d => d.Code).ToList();
                break;

            case "TH0|DESC":
                data = data.OrderByDescending(d => d.Code).ToList();
                break;

            case "TH1|ASC":
                data = data.OrderBy(d => d.Location).ToList();
                break;

            case "TH1|DESC":
                data = data.OrderByDescending(d => d.Location).ToList();
                break;

            case "TH2|ASC":
                data = data.OrderBy(d => d.Responsible.FullName).ToList();
                break;

            case "TH2|DESC":
                data = data.OrderByDescending(d => d.Responsible.FullName).ToList();
                break;

            case "TH3|ASC":
                data = data.OrderBy(d => d.TotalCost).ToList();
                break;

            case "TH3|DESC":
                data = data.OrderByDescending(d => d.TotalCost).ToList();
                break;
            }
        }

        foreach (Equipment equipment in data)
        {
            total += equipment.TotalCost;

            var lineBackground = pair ? rowEven : rowPair;

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(equipment.Code + " - " + equipment.Description, ToolsPdf.LayoutFonts.Times))
            {
                Border          = border,
                BackgroundColor = lineBackground,
                Padding         = 6f,
                PaddingTop      = 4f
            });

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(equipment.Location, ToolsPdf.LayoutFonts.Times))
            {
                Border          = border,
                BackgroundColor = lineBackground,
                Padding         = 6f,
                PaddingTop      = 4f
            });

            // @alex: se omite la celda de los datos del coste

            /*string totalCost = string.Format("{0:#,##0.00}", equipment.TotalCost);
             * table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalCost, ToolsPdf.LayoutFonts.Times))
             * {
             *  Border = border,
             *  BackgroundColor = lineBackground,
             *  Padding = 6f,
             *  PaddingTop = 4f,
             *  HorizontalAlignment = 2
             * });*/

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(equipment.Responsible.FullName, ToolsPdf.LayoutFonts.Times))
            {
                Border          = border,
                BackgroundColor = lineBackground,
                Padding         = 6f,
                PaddingTop      = 4f
            });

            cont++;
        }

        string totalRegistros = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}: {1}",
            dictionary["Common_RegisterCount"],
            cont);

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalRegistros, ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = rowEven,
            Padding         = 6f,
            PaddingTop      = 4f
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant(), ToolsPdf.LayoutFonts.Times))
        {
            Border              = iTS.Rectangle.TOP_BORDER,
            BackgroundColor     = rowEven,
            Padding             = 6f,
            PaddingTop          = 4f,
            HorizontalAlignment = 2
        });

        string totalText = string.Format("{0:#,##0.00}", total);

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalText, ToolsPdf.LayoutFonts.Times))
        {
            Border              = iTS.Rectangle.TOP_BORDER,
            BackgroundColor     = rowEven,
            Padding             = 6f,
            PaddingTop          = 4f,
            HorizontalAlignment = 2
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = rowEven,
            Colspan         = 2
        });

        pdfDoc.Add(criteriatable);
        pdfDoc.Add(table);
        pdfDoc.CloseDocument();
        res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
        return(res);
    }
Example #46
0
    public static ActionResult PDF(
        int companyId,
        DateTime?from,
        DateTime?to,
        int status,
        string listOrder,
        string filterText)
    {
        var res  = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;

        dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var    company = new Company(companyId);
        string path    = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(company.Name);

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_Objetivo_List"],
            formatedDescription,
            DateTime.Now);

        // FONTS
        string pathFonts = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts);
        }

        var headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        var arial      = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

        var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50);
        var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc,
                                                               new FileStream(
                                                                   string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName),
                                                                   FileMode.Create));

        writer.PageEvent = new TwoColumnHeaderFooter()
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = user.UserName,
            CompanyId   = company.Id,
            CompanyName = company.Name,
            Title       = dictionary["Item_Objetivo_List"].ToUpperInvariant()
        };

        pdfDoc.Open();

        var rowEven = new iTS.BaseColor(240, 240, 240);

        var titleTable = new iTSpdf.PdfPTable(1);

        titleTable.SetWidths(new float[] { 50f });
        titleTable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_EquipmentList"], company.Name), ToolsPdf.LayoutFonts.TitleFont))
        {
            HorizontalAlignment = iTS.Element.ALIGN_CENTER,
            Border = iTS.Rectangle.NO_BORDER
        });


        #region Criteria
        var criteriatable = new iTSpdf.PdfPTable(4)
        {
            WidthPercentage = 100
        };

        criteriatable.SetWidths(new float[] { 20f, 50f, 20f, 150f });

        #region texts
        string periode = string.Empty;
        if (from.HasValue && to == null)
        {
            periode = string.Format(CultureInfo.InvariantCulture, @"{0} {1:dd/MM/yyyy}", dictionary["Item_IncidentAction_List_Filter_From"], from);
        }
        else if (from == null && to.HasValue)
        {
            periode = string.Format(CultureInfo.InvariantCulture, @"{0} {1:dd/MM/yyyy}", dictionary["Item_IncidentAction_List_Filter_To"], to);
        }
        else if (from.HasValue && to.HasValue)
        {
            periode = string.Format(CultureInfo.InvariantCulture, @"{0:dd/MM/yyyy} {1:dd/MM/yyyy}", from, to);
        }
        else
        {
            periode = dictionary["Common_All_Male"];
        }

        string statusText = dictionary["Common_All"];
        if (status == 1)
        {
            statusText = dictionary["Item_ObjetivoAction_List_Filter_ShowActive"];
        }

        if (status == 2)
        {
            statusText = dictionary["Item_ObjetivoAction_List_Filter_ShowClosed"];
        }
        #endregion

        ToolsPdf.AddCriteria(criteriatable, dictionary["Common_Period"], periode);
        ToolsPdf.AddCriteria(criteriatable, dictionary["Item_IncidentAction_Header_Status"], statusText);

        if (!string.IsNullOrEmpty(filterText))
        {
            ToolsPdf.AddCriteria(criteriatable, dictionary["Common_PDF_Filter_Contains"], filterText);
        }
        pdfDoc.Add(criteriatable);
        #endregion

        var table = new iTSpdf.PdfPTable(5)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1,
            SpacingBefore       = 20f,
            SpacingAfter        = 30f
        };

        table.SetWidths(new float[] { 7f, 50f, 30f, 12f, 12f });

        table.AddCell(ToolsPdf.HeaderCell(dictionary["Common_Status"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_Header_Name"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_Header_Responsible"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_Header_StartDate"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_Objetivo_Header_PreviewEndDate"]));

        int cont = 0;
        var data = Objetivo.Filter(companyId, from, to, status).ToList();
        foreach (var item in data)
        {
            if (!item.Objetivo.EndDate.HasValue)
            {
                item.Objetivo.EndDate = item.Objetivo.PreviewEndDate;
            }
        }

        switch (listOrder.ToUpperInvariant())
        {
        default:
        case "TH0|ASC":
            data = data.OrderBy(d => d.Objetivo.Name).ToList();
            break;

        case "TH0|DESC":
            data = data.OrderByDescending(d => d.Objetivo.Name).ToList();
            break;

        case "TH1|ASC":
            data = data.OrderBy(d => d.Objetivo.Responsible.FullName).ToList();
            break;

        case "TH1|DESC":
            data = data.OrderByDescending(d => d.Objetivo.Responsible.FullName).ToList();
            break;

        case "TH2|ASC":
            data = data.OrderBy(d => d.Objetivo.StartDate).ToList();
            break;

        case "TH2|DESC":
            data = data.OrderByDescending(d => d.Objetivo.StartDate).ToList();
            break;

        case "TH3|ASC":
            data = data.OrderBy(d => d.Objetivo.EndDate).ToList();
            break;

        case "TH3|DESC":
            data = data.OrderByDescending(d => d.Objetivo.EndDate).ToList();
            break;
        }

        cont = 0;
        foreach (var item in data)
        {
            if (!string.IsNullOrEmpty(filterText))
            {
                var show = false;
                if (item.Objetivo.Name.IndexOf(filterText, StringComparison.OrdinalIgnoreCase) != -1)
                {
                    show = true;
                }

                if (item.Objetivo.Responsible.FullName.IndexOf(filterText, StringComparison.OrdinalIgnoreCase) != -1)
                {
                    show = true;
                }

                if (!show)
                {
                    continue;
                }
            }

            string endDateText = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", item.Objetivo.PreviewEndDate);
            if (item.Objetivo.EndDate.HasValue)
            {
                endDateText = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", item.Objetivo.EndDate);
            }

            table.AddCell(ToolsPdf.DataCell(item.Objetivo.Active ? dictionary["Common_Active"] : dictionary["Common_Inactve"], ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCell(item.Objetivo.Name, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCell(item.Objetivo.Responsible.FullName, ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCellCenter(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", item.Objetivo.StartDate), ToolsPdf.LayoutFonts.Times));
            table.AddCell(ToolsPdf.DataCellCenter(endDateText, ToolsPdf.LayoutFonts.Times));
            cont++;
        }

        string totalRegistros = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}: {1}",
            dictionary["Common_RegisterCount"],
            cont);

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(totalRegistros, ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = rowEven,
            Padding         = 6f,
            PaddingTop      = 4f,
            Colspan         = 2
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = rowEven,
            Colspan         = 3
        });

        pdfDoc.Add(table);

        pdfDoc.CloseDocument();
        res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
        return(res);
    }
        protected void GenerateReport(BarcodeGenerateModel model)
        {
            var img = (from p in db.tbl_RawMaterials  where p.RawMaterialId == model.RawMaterialsId select p).SingleOrDefault();

            string imgPath = Server.MapPath("~/barcodes/" + img.barcode + ".png");

            Font   Font15          = FontFactory.GetFont("Verdana", 12, Font.BOLDITALIC);
            string str_pdffilename = "barcode.pdf";
            string str_pdfpath     = Server.MapPath("~/barcodes/") + str_pdffilename;

            Document  doc    = new Document(PageSize.A4, 50, 50, 55, 25);
            PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);

            doc.Open();

            PdfPTable table = new iTextSharp.text.pdf.PdfPTable(4);

            table.WidthPercentage = 100;
            float[] intwidth = new float[4] {
                1, 1, 1, 1
            };
            table.SetWidths(intwidth);
            table.DefaultCell.BorderColor = new BaseColor(0, 0, 0, 0);
            table.DefaultCell.BorderWidth = 1;
            table.SpacingAfter            = 1;
            table.HorizontalAlignment     = Element.ALIGN_CENTER;

            PdfPCell cellPdf1 = new PdfPCell();

            cellPdf1                   = new PdfPCell(new Phrase(img.Name, Font15));
            cellPdf1.Border            = 0;
            cellPdf1.Colspan           = 4;
            cellPdf1.BorderWidthBottom = 1F;
            cellPdf1.BorderWidthLeft   = 0;
            cellPdf1.BorderWidthRight  = 0;
            cellPdf1.BorderWidthTop    = 0;
            cellPdf1.SetLeading(.5F, .5F);
            cellPdf1.BorderWidthBottom   = 0;
            cellPdf1.HorizontalAlignment = Element.ALIGN_MIDDLE;
            cellPdf1.VerticalAlignment   = Element.ALIGN_MIDDLE;
            table.AddCell(cellPdf1);

            for (int i = 0; i < model.NoOfBarcode; i++)
            {
                Image    png     = Image.GetInstance(imgPath);
                PdfPCell cellPdf = new PdfPCell((Image.GetInstance(png)));
                png.ScaleToFit(1F, 2F);
                png.SpacingBefore      = 0F;
                png.Alignment          = Element.ALIGN_MIDDLE;
                cellPdf.Border         = 0;
                cellPdf.Colspan        = 0;
                cellPdf.Rowspan        = 1;
                cellPdf.BorderWidthTop = 0;
                cellPdf.SetLeading(0F, 0F);
                cellPdf.BorderWidthBottom   = 0;
                cellPdf.HorizontalAlignment = Element.ALIGN_MIDDLE;
                cellPdf.VerticalAlignment   = Element.ALIGN_MIDDLE;
                table.AddCell(cellPdf);
            }



            doc.Add(table);

            writer.CloseStream = false;
            doc.Close();
            Response.Buffer      = true;
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=" + img.Name + " - Barcode.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Write(doc);
            Response.End();
            string script = string.Format(@"showDialogfile('{0}')", str_pdffilename);
            //ScriptManager.RegisterClientScriptBlock(this, typeof(Page), UniqueID, script, true);
        }
Example #48
0
    public static ActionResult PDF(
        int companyId,
        string from,
        string to,
        long rulesId,
        long processId,
        string listOrder)
    {
        var res  = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;

        Dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var    company = new Company(companyId);
        string path    = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(company.Name);

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf",
            Dictionary["Item_Oportunities"],
            formatedDescription,
            DateTime.Now);

        var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50);
        var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc,
                                                               new FileStream(
                                                                   string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName),
                                                                   FileMode.Create));

        writer.PageEvent = new TwoColumnHeaderFooter()
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = user.UserName,
            CompanyId   = company.Id,
            CompanyName = company.Name,
            Title       = Dictionary["Item_Oportunities"].ToUpperInvariant()
        };

        pdfDoc.Open();
        var titleTable = new iTSpdf.PdfPTable(1);

        titleTable.SetWidths(new float[] { 50f });
        titleTable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", Dictionary["Item_EquipmentList"], company.Name), ToolsPdf.LayoutFonts.TitleFont))
        {
            HorizontalAlignment = iTS.Element.ALIGN_CENTER,
            Border = iTS.Rectangle.NO_BORDER
        });

        #region Criteria
        var criteriatable = new iTSpdf.PdfPTable(6)
        {
            WidthPercentage = 100
        };

        criteriatable.SetWidths(new float[] { 15f, 50f, 15f, 50f, 15f, 50f });

        #region texts

        string criteriaProccess = Dictionary["Common_All_Male_Plural"];
        if (processId > 0)
        {
            var process = new Process(processId, companyId);
            if (!string.IsNullOrEmpty(process.Description))
            {
                criteriaProccess = process.Description;
            }
        }

        string periode = string.Empty;
        if (!string.IsNullOrEmpty(from) && string.IsNullOrEmpty(to))
        {
            periode = Dictionary["Item_Incident_List_Filter_From"] + " " + from;
        }
        else if (string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to))
        {
            periode = Dictionary["Item_Incident_List_Filter_To"] + " " + to;
        }
        else if (!string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to))
        {
            periode = from + " - " + to;
        }
        else
        {
            periode = Dictionary["Common_All_Male"];
        }

        string typetext = Dictionary["Common_All_Male_Plural"];

        string ruleDescription = Dictionary["Common_All_Female_Plural"];
        if (rulesId > 0)
        {
            var rule = Rules.GetById(companyId, rulesId);
            if (!string.IsNullOrEmpty(rule.Description))
            {
                ruleDescription = rule.Description;
            }
        }
        #endregion

        ToolsPdf.AddCriteria(criteriatable, Dictionary["Common_Period"], periode);
        ToolsPdf.AddCriteria(criteriatable, Dictionary["Item_BusinesRisk_ListHeader_Process"], typetext);
        ToolsPdf.AddCriteria(criteriatable, Dictionary["Item_BusinesRisk_ListHeader_Rule"], ruleDescription);
        pdfDoc.Add(criteriatable);
        #endregion

        var table = new iTSpdf.PdfPTable(7)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1,
            SpacingBefore       = 20f,
            SpacingAfter        = 30f
        };

        table.SetWidths(new float[] { 10f, 10f, 30f, 20f, 20f, 10f, 10f });

        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_IncidentAction_Header_Type"]));
        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_BusinesRisk_ListHeader_Date"]));
        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_Oportunity"]));
        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_BusinesRisk_ListHeader_Process"]));
        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_BusinesRisk_ListHeader_Rule"]));
        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_BusinesRisk_ListHeader_StartValue"]));
        table.AddCell(ToolsPdf.HeaderCell(Dictionary["Item_BusinesRisk_ListHeader_IPR"]));

        int cont = 0;
        var data = HttpContext.Current.Session["OportunityFilterData"] as List <OportunityFilterItem>;

        switch (listOrder.ToUpperInvariant())
        {
        default:
        case "TH1|ASC":
            data = data.OrderBy(d => d.OpenDate).ToList();
            break;

        case "TH1|DESC":
            data = data.OrderByDescending(d => d.OpenDate).ToList();
            break;

        case "TH2|ASC":
            data = data.OrderBy(d => d.Description).ToList();
            break;

        case "TH2|DESC":
            data = data.OrderByDescending(d => d.Description).ToList();
            break;

        case "TH3|ASC":
            data = data.OrderBy(d => d.Process.Description).ToList();
            break;

        case "TH3|DESC":
            data = data.OrderByDescending(d => d.Process.Description).ToList();
            break;

        case "TH4|ASC":
            data = data.OrderBy(d => d.Rule.Description).ToList();
            break;

        case "TH4|DESC":
            data = data.OrderByDescending(d => d.Rule.Description).ToList();
            break;

        case "TH5|ASC":
            data = data.OrderBy(d => d.Rule.Limit).ToList();
            break;

        case "TH5|DESC":
            data = data.OrderByDescending(d => d.Rule.Limit).ToList();
            break;
        }

        foreach (OportunityFilterItem risk in data)
        {
            cont++;
            string typeText = string.Empty;
            if (risk.Result == 0)
            {
                typeText = Dictionary["Item_BusinessRisk_Status_Unevaluated"];
            }
            else if (risk.Result < risk.Rule.Limit)
            {
                typeText = Dictionary["Item_BusinessRisk_Status_NotSignificant"];
            }
            else
            {
                typeText = Dictionary["Item_BusinessRisk_Status_Significant"];
            }

            string initialResultText = risk.Result == 0 ? string.Empty : risk.Result.ToString();

            table.AddCell(ToolsPdf.DataCellCenter(typeText));
            table.AddCell(ToolsPdf.DataCellCenter(risk.OpenDate));
            table.AddCell(ToolsPdf.DataCell(risk.Description));
            table.AddCell(ToolsPdf.DataCell(risk.Process.Description));
            table.AddCell(ToolsPdf.DataCellCenter(risk.Rule.Description));
            table.AddCell(ToolsPdf.DataCellCenter(initialResultText));
            table.AddCell(ToolsPdf.DataCellRight(risk.Rule.Limit));
        }

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(
                                                             CultureInfo.InvariantCulture,
                                                             @"{0}: {1}",
                                                             Dictionary["Common_RegisterCount"],
                                                             cont), ToolsPdf.LayoutFonts.Times))
        {
            Border     = iTS.Rectangle.TOP_BORDER,
            Padding    = 6f,
            PaddingTop = 4f,
            Colspan    = 4
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times))
        {
            Border  = iTS.Rectangle.TOP_BORDER,
            Colspan = 4
        });

        pdfDoc.Add(table);
        pdfDoc.CloseDocument();
        res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
        return(res);
    }
    private bool AddPageHeaderToPDFDataTable(ref iTextSharp.text.pdf.PdfPTable mainTable, string sName, string strFilter, int noOfColumns)
    {
        try {
            //'mainTable.LockedWidth = True
            float ReportNameSize      = 11;
            float ApplicationNameSize = 11;
            float FooterTextSize      = 8;
            float HeaderTextSize      = 9;

            float[] arColWidth1 = new float[3];
            arColWidth1[0] = 350;
            arColWidth1[1] = 300;
            arColWidth1[2] = 150;

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

            // Creates a phrase to hold the application name at the left hand side of the header.
            Phrase phApplicationName = new Phrase("Peacock", FontFactory.GetFont(SelectedFont, ApplicationNameSize, iTextSharp.text.Font.NORMAL));
            phApplicationName.Font.Color = HeaderFontColor;
            // iTextSharp.text.BaseColor.BLUE

            PdfPCell clApplicationName = new PdfPCell(phApplicationName);
            clApplicationName.Border = PdfPCell.NO_BORDER;
            clApplicationName.HorizontalAlignment = Element.ALIGN_LEFT;

            // Creates a phrase to show the current date at the right hand side of the header.
            Phrase phDate = new Phrase(DateTime.Now.ToString("dd-MM-yy HH:mm"), FontFactory.GetFont(SelectedFont, HeaderTextSize, iTextSharp.text.Font.NORMAL));
            phDate.Font.Color = HeaderFontColor;
            //iTextSharp.text.BaseColor.BLUE

            PdfPCell clDate = new PdfPCell(phDate);
            clDate.HorizontalAlignment = Element.ALIGN_RIGHT;
            clDate.Border = PdfPCell.NO_BORDER;

            Phrase phName = new Phrase(sName, FontFactory.GetFont(SelectedFont, HeaderTextSize, iTextSharp.text.Font.NORMAL));
            phName.Font.Color = HeaderFontColor;
            //iTextSharp.text.BaseColor.BLUE

            PdfPCell cellName = new PdfPCell(phName);
            cellName.HorizontalAlignment = Element.ALIGN_LEFT;
            cellName.Border = PdfPCell.NO_BORDER;

            HeaderTable.AddCell(cellName);
            HeaderTable.AddCell(clApplicationName);
            HeaderTable.AddCell(clDate);


            Phrase phFilter = new Phrase(strFilter, FontFactory.GetFont(SelectedFont, HeaderTextSize, iTextSharp.text.Font.NORMAL));
            phFilter.Font.Color = HeaderFontColor;
            //iTextSharp.text.BaseColor.BLUE
            PdfPCell clFilter = new PdfPCell(phFilter);
            clFilter.Colspan             = 2;
            clFilter.Border              = PdfPCell.NO_BORDER;
            clFilter.HorizontalAlignment = Element.ALIGN_LEFT;


            Phrase phUserid = new Phrase("Elaiya Kumar", FontFactory.GetFont(SelectedFont, HeaderTextSize, iTextSharp.text.Font.NORMAL));
            phUserid.Font.Color = HeaderFontColor;
            //iTextSharp.text.BaseColor.BLUE
            PdfPCell clUserid = new PdfPCell(phUserid);
            clUserid.HorizontalAlignment = Element.ALIGN_RIGHT;
            clUserid.Border = PdfPCell.NO_BORDER;

            HeaderTable.AddCell(clFilter);
            //rowTabe1.AddCell(EmptyCell())
            HeaderTable.AddCell(clUserid);

            // Creates a PdfPCell that accepts the headerTable as a parameter and then adds that cell to the main PdfPTable.
            PdfPCell cellHeader1 = new PdfPCell(HeaderTable);
            cellHeader1.Border  = PdfPCell.NO_BORDER;
            cellHeader1.Colspan = noOfColumns + 1;
            mainTable.AddCell(cellHeader1);


            //mainTable.AddCell(clph)
            Phrase ph = new Phrase();
            // Creates a phrase for a new line.
            Phrase phSpace = new Phrase("\r\n");
            phSpace.Font.Size = 1;

            PdfPCell clSpace = new PdfPCell(phSpace);
            clSpace.Border  = PdfPCell.NO_BORDER;
            clSpace.Colspan = noOfColumns + 1;
            // noOfColumns
            mainTable.AddCell(clSpace);

            mainTable.CompleteRow();

            return(true);
        } catch (Exception ex) {
            //PHLog.ErrorLogException(ex, oGV, System.Reflection.MethodBase.GetCurrentMethod.Name);
        }
        return(true);
    }
        private void ExportToPDF(GridView gvReport, string tenBang, bool LandScape)
        {
            int       noOfColumns = 0, noOfRows = 0;
            DataTable tbl = null;

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

            float ApplicationNameSize = 7;

            // Creates a PDF document

            Document document = null;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                mainTable.AddCell(ph);
            }

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

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

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

            // Creates a footer for the PDF document.

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

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

            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment; filename= SampleExport.pdf");
            Response.End();
        }
Example #51
0
    public ActionResult PDF(
        int companyId,
        string from,
        string to,
        bool statusIdentified,
        bool statusAnalyzed,
        bool statusInProgress,
        bool statusClose,
        bool typeImprovement,
        bool typeFix,
        bool typePrevent,
        int origin,
        int reporter,
        string listOrder,
        string filterText)
    {
        var res  = ActionResult.NoAction;
        var user = HttpContext.Current.Session["User"] as ApplicationUser;

        dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var    company = new Company(companyId);
        string path    = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(company.Name);

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_IncidentActionList"],
            formatedDescription,
            DateTime.Now);

        var pdfDoc = new iTS.Document(iTS.PageSize.A4.Rotate(), 40, 40, 80, 50);
        var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc,
                                                               new FileStream(
                                                                   string.Format(CultureInfo.InvariantCulture, @"{0}Temp\{1}", path, fileName),
                                                                   FileMode.Create));

        writer.PageEvent = new TwoColumnHeaderFooter
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, company.Id),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = user.UserName,
            CompanyId   = company.Id,
            CompanyName = company.Name,
            Title       = dictionary["Item_IncidentActions"].ToUpperInvariant()
        };

        pdfDoc.Open();

        var backgroundColor = new iTS.BaseColor(225, 225, 225);
        var rowPair         = new iTS.BaseColor(255, 255, 255);
        var rowEven         = new iTS.BaseColor(240, 240, 240);

        var titleTable = new iTSpdf.PdfPTable(1);

        titleTable.SetWidths(new float[] { 50f });
        var titleCell = new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", dictionary["Item_EquipmentList"], company.Name), ToolsPdf.LayoutFonts.TitleFont))
        {
            HorizontalAlignment = iTS.Element.ALIGN_CENTER,
            Border = ToolsPdf.BorderNone
        };

        titleTable.AddCell(titleCell);

        //------ CRITERIA
        var criteriatable = new iTSpdf.PdfPTable(4);

        criteriatable.SetWidths(new float[] { 20f, 50f, 15f, 100f });
        criteriatable.WidthPercentage = 100;

        #region texts

        string criteriaOrigin = dictionary["Common_All_Male"];
        if (origin == 1)
        {
            criteriaOrigin = dictionary["Item_IncidentAction_Origin1"];
        }
        if (origin == 2)
        {
            criteriaOrigin = dictionary["Item_IncidentAction_Origin2"];
        }
        if (origin == 3)
        {
            criteriaOrigin = dictionary["Item_IncidentAction_Origin3"];
        }
        if (origin == 4)
        {
            criteriaOrigin = dictionary["Item_IncidentAction_Origin46"];
        }
        if (origin == 5)
        {
            criteriaOrigin = dictionary["Item_IncidentAction_Origin5"];
        }

        string reporterText = dictionary["Common_All_Male"];
        if (reporter == 1)
        {
            reporterText = dictionary["Item_IncidentAction_ReporterType1"];
        }
        if (reporter == 2)
        {
            reporterText = dictionary["Item_IncidentAction_ReporterType2"];
        }
        if (reporter == 3)
        {
            reporterText = dictionary["Item_IncidentAction_ReporterType3"];
        }


        string periode = string.Empty;
        if (!string.IsNullOrEmpty(from) && string.IsNullOrEmpty(to))
        {
            periode = dictionary["Item_IncidentAction_List_Filter_From"] + " " + from;
        }
        else if (string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to))
        {
            periode = dictionary["Item_IncidentAction_List_Filter_To"] + " " + to;
        }
        else if (!string.IsNullOrEmpty(from) && !string.IsNullOrEmpty(to))
        {
            periode = from + " " + to;
        }
        else
        {
            periode = dictionary["Common_All_Male"];
        }

        string typetext = string.Empty;

        bool firstType = false;
        if (typeImprovement)
        {
            typetext  = dictionary["Item_IncidentAction_Type1"];
            firstType = false;
        }
        if (typeFix)
        {
            if (!firstType)
            {
                typetext += " - ";
            }
            typetext += dictionary["Item_IncidentAction_Type2"];
            firstType = false;
        }
        if (typePrevent)
        {
            if (!firstType)
            {
                typetext += " - ";
            }
            typetext += dictionary["Item_IncidentAction_Type3"];
        }

        string statusText  = string.Empty;
        bool   firstStatus = true;
        if (statusIdentified)
        {
            firstStatus = false;
            statusText += dictionary["Item_IndicentAction_Status1"];
        }

        if (statusAnalyzed)
        {
            if (!firstStatus)
            {
                statusText += " - ";
            }
            statusText += dictionary["Item_IndicentAction_Status2"];
            firstStatus = false;
        }

        if (statusInProgress)
        {
            if (!firstStatus)
            {
                statusText += " - ";
            }
            statusText += dictionary["Item_IndicentAction_Status3"];
            firstType   = false;
        }

        if (statusClose)
        {
            if (!firstType)
            {
                statusText += " - ";
            }
            statusText += dictionary["Item_IndicentAction_Status4"];

            firstType = false;
        }
        #endregion

        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Period"], ToolsPdf.LayoutFonts.TimesBold))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });
        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(periode, ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });
        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_Customer_Header_Type"] + " :", ToolsPdf.LayoutFonts.TimesBold))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });
        criteriatable.AddCell(new PdfPCell(new iTS.Phrase(typetext, ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });
        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_IncidentAction_Header_Status"] + " :", ToolsPdf.LayoutFonts.TimesBold))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });
        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(statusText, ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });
        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_IncidentAction_Header_Origin"] + " :", ToolsPdf.LayoutFonts.TimesBold))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });
        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(criteriaOrigin, ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });
        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Item_IncidentAction_Label_Reporter"] + " :", ToolsPdf.LayoutFonts.TimesBold))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });

        criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(reporterText, ToolsPdf.LayoutFonts.Times))
        {
            Border = ToolsPdf.BorderNone,
            HorizontalAlignment = iTS.Element.ALIGN_LEFT,
            Padding             = 6f,
            PaddingTop          = 4f
        });

        if (string.IsNullOrEmpty(filterText))
        {
            criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.TimesBold))
            {
                Border = ToolsPdf.BorderNone,
                HorizontalAlignment = iTS.Element.ALIGN_LEFT,
                Padding             = 6f,
                PaddingTop          = 4f,
                Colspan             = 2
            });
        }
        else
        {
            criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_PDF_Filter_Contains"] + " :", ToolsPdf.LayoutFonts.TimesBold))
            {
                Border = ToolsPdf.BorderNone,
                HorizontalAlignment = iTS.Element.ALIGN_LEFT,
                Padding             = 6f,
                PaddingTop          = 4f
            });

            criteriatable.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(filterText, ToolsPdf.LayoutFonts.Times))
            {
                Border = ToolsPdf.BorderNone,
                HorizontalAlignment = iTS.Element.ALIGN_LEFT,
                Padding             = 6f,
                PaddingTop          = 4f
            });
        }

        pdfDoc.Add(criteriatable);
        //---------------------------

        var table = new iTSpdf.PdfPTable(8)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 1,
            SpacingBefore       = 20f,
            SpacingAfter        = 30f
        };

        table.SetWidths(new float[] { 3f, 10f, 10f, 30f, 10f, 10f, 10f, 10f });
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Label_Number"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Status"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Open"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Description"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Origin"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Type"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_ImplementDate"]));
        // table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Close"]));
        table.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Cost"]));

        int     cont      = 0;
        decimal totalCost = 0;
        var     data      = HttpContext.Current.Session["IncidentActionFilterData"] as List <IncidentActionFilterItem>;

        // @alex: necesitamos el texto del tipo de acción y el origen para ordenarlos alfbéticamente
        //       independientemente del id en la bbdd
        foreach (var item in data)
        {
            string originText = string.Empty;
            if (item.Origin == 1)
            {
                originText = dictionary["Item_IncidentAction_Origin1"];
            }
            if (item.Origin == 2)
            {
                originText = dictionary["Item_IncidentAction_Origin2"];
            }
            if (item.Origin == 3)
            {
                originText = dictionary["Item_IncidentAction_Origin3"];
            }
            if (item.Origin == 4)
            {
                originText = dictionary["Item_IncidentAction_Origin4"];
            }
            if (item.Origin == 5)
            {
                originText = dictionary["Item_IncidentAction_Origin5"];
            }
            if (item.Origin == 6)
            {
                originText = dictionary["Item_IncidentAction_Origin6"];
            }
            item.OriginText = originText;

            string typeText = string.Empty;
            if (item.ActionType == 1)
            {
                typeText = dictionary["Item_IncidentAction_Type1"];
            }
            if (item.ActionType == 2)
            {
                typeText = dictionary["Item_IncidentAction_Type2"];
            }
            if (item.ActionType == 3)
            {
                typeText = dictionary["Item_IncidentAction_Type3"];
            }
            item.ActionTypeText = typeText;
        }

        switch (listOrder.ToUpperInvariant())
        {
        default:
        case "TH0|ASC":
            data = data.OrderBy(d => d.Status).ToList();
            break;

        case "TH0|DESC":
            data = data.OrderByDescending(d => d.Status).ToList();
            break;

        case "TH1|ASC":
            data = data.OrderBy(d => d.OpenDate).ToList();
            break;

        case "TH1|DESC":
            data = data.OrderByDescending(d => d.OpenDate).ToList();
            break;

        case "TH2|ASC":
            data = data.OrderBy(d => d.Description).ToList();
            break;

        case "TH2|DESC":
            data = data.OrderByDescending(d => d.Description).ToList();
            break;

        case "TH3|ASC":
            data = data.OrderBy(d => d.OriginText).ToList();
            break;

        case "TH3|DESC":
            data = data.OrderByDescending(d => d.OriginText).ToList();
            break;

        case "TH4|ASC":
            data = data.OrderBy(d => d.ActionTypeText).ToList();
            break;

        case "TH4|DESC":
            data = data.OrderByDescending(d => d.ActionTypeText).ToList();
            break;

        case "TH5|ASC":
            data = data.OrderBy(d => d.ImplementationDate).ToList();
            break;

        case "TH5|DESC":
            data = data.OrderByDescending(d => d.ImplementationDate).ToList();
            break;

        case "TH6|ASC":
            data = data.OrderBy(d => d.CloseDate).ToList();
            break;

        case "TH6|DESC":
            data = data.OrderByDescending(d => d.CloseDate).ToList();
            break;
        }

        foreach (IncidentActionFilterItem action in data)
        {
            if (!string.IsNullOrEmpty(filterText))
            {
                if (action.Description.IndexOf(filterText, StringComparison.OrdinalIgnoreCase) == -1 &&
                    action.Number.IndexOf(filterText, StringComparison.OrdinalIgnoreCase) == -1)
                {
                    continue;
                }
            }

            int border = 0;
            totalCost += action.Amount;

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(action.Number, ToolsPdf.LayoutFonts.Times))
            {
                Border              = border,
                BackgroundColor     = ToolsPdf.LineBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = Rectangle.ALIGN_CENTER
            });

            string actionTypeText = string.Empty;
            switch (action.ActionType)
            {
            default:
            case 1: actionTypeText = dictionary["Item_IncidentAction_Type1"]; break;

            case 2: actionTypeText = dictionary["Item_IncidentAction_Type2"]; break;

            case 3: actionTypeText = dictionary["Item_IncidentAction_Type3"]; break;
            }

            string statustext = string.Empty;
            if (action.Status == 1)
            {
                statustext = dictionary["Item_IndicentAction_Status1"];
            }
            if (action.Status == 2)
            {
                statustext = dictionary["Item_IndicentAction_Status2"];
            }
            if (action.Status == 3)
            {
                statustext = dictionary["Item_IndicentAction_Status3"];
            }
            if (action.Status == 4)
            {
                statustext = dictionary["Item_IndicentAction_Status4"];
            }

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(statustext, ToolsPdf.LayoutFonts.Times))
            {
                Border              = border,
                BackgroundColor     = ToolsPdf.LineBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = Rectangle.ALIGN_CENTER
            });

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.OpenDate), ToolsPdf.LayoutFonts.Times))
            {
                Border              = border,
                BackgroundColor     = ToolsPdf.LineBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = Rectangle.ALIGN_CENTER
            });

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0} - {1}", action.Number, action.Description), ToolsPdf.LayoutFonts.Times))
            {
                Border          = border,
                BackgroundColor = ToolsPdf.LineBackgroundColor,
                Padding         = 6f,
                PaddingTop      = 4f
            });

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(action.OriginText, ToolsPdf.LayoutFonts.Times))
            {
                Border              = border,
                BackgroundColor     = ToolsPdf.LineBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = Rectangle.ALIGN_CENTER
            });

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(actionTypeText, ToolsPdf.LayoutFonts.Times))
            {
                Border              = border,
                BackgroundColor     = ToolsPdf.LineBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = Rectangle.ALIGN_CENTER
            });

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.ImplementationDate), ToolsPdf.LayoutFonts.Times))
            {
                Border              = border,
                BackgroundColor     = ToolsPdf.LineBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = Rectangle.ALIGN_CENTER
            });

            /*table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.CloseDate), ToolsPdf.LayoutFonts.Times))
             * {
             *  Border = border,
             *  BackgroundColor = ToolsPdf.LineBackgroundColor,
             *  Padding = 6f,
             *  PaddingTop = 4f,
             *  HorizontalAlignment = Rectangle.ALIGN_CENTER
             * });*/

            table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(Tools.PdfMoneyFormat(action.Amount), ToolsPdf.LayoutFonts.Times))
            {
                Border              = border,
                BackgroundColor     = ToolsPdf.LineBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                HorizontalAlignment = Rectangle.ALIGN_RIGHT
            });

            cont++;
        }

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Format(
                                                             CultureInfo.InvariantCulture,
                                                             @"{0}: {1}",
                                                             dictionary["Common_RegisterCount"],
                                                             cont), ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = ToolsPdf.SummaryBackgroundColor,
            Padding         = 6f,
            PaddingTop      = 4f,
            Colspan         = 4
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant(), ToolsPdf.LayoutFonts.Times))
        {
            Border              = iTS.Rectangle.TOP_BORDER,
            BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
            Padding             = 6f,
            PaddingTop          = 4f,
            HorizontalAlignment = 2
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(Tools.PdfMoneyFormat(totalCost), ToolsPdf.LayoutFonts.Times))
        {
            Border              = iTS.Rectangle.TOP_BORDER,
            BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
            Padding             = 6f,
            PaddingTop          = 4f,
            HorizontalAlignment = 2
        });

        table.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times))
        {
            Border          = iTS.Rectangle.TOP_BORDER,
            BackgroundColor = ToolsPdf.SummaryBackgroundColor,
            Colspan         = 1
        });

        pdfDoc.Add(table);
        pdfDoc.CloseDocument();
        res.SetSuccess(string.Format(CultureInfo.InvariantCulture, @"{0}Temp/{1}", ConfigurationManager.AppSettings["siteUrl"], fileName));
        return(res);
    }
    /// <summary>
    ///
    /// </summary>
    /// <param name="dt">Input Datatable to Export to PDF</param>
    /// <param name="strFilter">Filter conditions or remarks to display on report header</param>
    /// <param name="dicDataType">(ColumnIndex, XLDatattype)</param>
    /// <param name="lstRepeatColumn">Left most ColumnIndex to repeat on all pages</param>
    /// <param name="lstColumnsDisplay">ColumnIndex to display. Count = 0  or Nothing will Display All columns</param>
    /// <returns></returns>
    /// <remarks></remarks>
    public bool ExportToPDF(DataTable dt, string strFilter, Dictionary <int, Helper.Alignment> dicDataType, List <int> lstRepeatColumn = null, List <int> lstColumnsDisplay = null)
    {
        try {
            ICollection <string> myCol;           // = ICollection<string>;
            //'/Returns the list of all font families included in iTextSharp.
            myCol = iTextSharp.text.FontFactory.RegisteredFamilies;
            //'Returns the list of all fonts included in iTextSharp.
            myCol = iTextSharp.text.FontFactory.RegisteredFonts;

            //FontFactory.Register("F:\Transfer\SEGOEUI.TTF")
            //SelectedFont = FontFactory.GetFont("SEGOEUI")

            // Dim Segoe As Font = FontFactory.GetFont("SegoeUI") ' , BaseFont.IDENTITY_H, 8)
            //Dim bfTimes As BaseFont = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, False)
            //Dim customfont As BaseFont
            //Try
            //    'customfont = BaseFont.CreateFont("F:\Transfer\SEGOEUI.TTF", BaseFont.CP1252, BaseFont.EMBEDDED)
            //    ' customfont = BaseFont.CreateFont(Segoe) '"F:\Transfer\SEGOEUI.TTF", BaseFont.CP1252, BaseFont.EMBEDDED)
            //    FontFactory.Register("F:\Transfer\SEGOEUI.TTF")
            //Catch ex As Exception
            //    Dim s = ex.Message
            //End Try


            int noOfColumns = dt.Columns.Count;
            int noOfRows    = dt.Rows.Count;
            Dictionary <int, float> dicWidth = new Dictionary <int, float>();

            if ((lstRepeatColumn == null))
            {
                lstRepeatColumn = new List <int>();
            }
            if ((lstColumnsDisplay == null))
            {
                lstColumnsDisplay = new List <int>();
            }
            if ((dicDataType == null))
            {
                dicDataType = new Dictionary <int, Helper.Alignment>();
                for (int icol = 0; icol <= noOfColumns - 1; icol++)
                {
                    dicDataType.Add(icol, Helper.Alignment.Left);
                }
            }

            SelectedFont = "Arial";
            // "Arial"  SEGOEUI COURIER HELVETICA
            HeaderFontColor = iTextSharp.text.BaseColor.BLUE;

            List <iTextSharp.text.pdf.PdfPTable> lstTables = new List <iTextSharp.text.pdf.PdfPTable>();
            // Creates a PDF document
            Document document = null;
            //If LandScape = True Then
            //document = new Document( PageSize.A4.Rotate   , 0.0f, 0.0f, 40.0f, 15.0f);
            document = new Document(new RectangleReadOnly(595, 842, 90), 0.0f, 0.0f, 40.0f, 15.0f);
            //LandScape  (W x H, 842 x 595) points
            //Else
            //'document = New Document(PageSize.A4, 0, 0, 15, 5) 'Portrait (W x H, 595 × 842) points
            //End If

            //dicWidth = GetColumnWidth(dt)
            dicWidth = GetColumnWidth(dt, SelectedFont, ColumnHeaderTextSize);

            Dictionary <int, List <int> > dicColsPerPage = new Dictionary <int, List <int> >();

            dicColsPerPage = GetColumnsPerPageByWidth(dt, dicWidth, lstRepeatColumn, lstColumnsDisplay);

            foreach (int intDt in dicColsPerPage.Keys)
            {
                List <int> lstColumnNums = dicColsPerPage[intDt];

                float[] arrColsrelativeWidths = new float[lstColumnNums.Count];
                dynamic dblTotalWidth         = dicWidth.Sum(t => t.Value);

                int iArrIndex = 0;

                foreach (int iCol in lstColumnNums)
                {
                    arrColsrelativeWidths[iArrIndex] = dicWidth[iCol];
                    //dblTotalWidth = dblTotalWidth + dicWidth(iCol)
                    iArrIndex = iArrIndex + 1;
                }

                iTextSharp.text.pdf.PdfPTable mainTable = new iTextSharp.text.pdf.PdfPTable(arrColsrelativeWidths);

                mainTable.TotalWidth = document.PageSize.Width * 0.9f;

                AddPageHeaderToPDFDataTable(ref mainTable, dt.TableName, strFilter, lstColumnNums.Count - 1);
                AddColumnHeader(dt, ref mainTable, lstColumnNums, dicDataType, lstColumnsDisplay);

                //'  If dblTotalWidth <= A4Dimension.Width * 0.9 - 30 Then mainTable.LockedWidth = True
                Phrase ph = default(Phrase);

                //' Date - centre, Double Right, String Left, INteger centre
                // Reads the gridview rows and adds them to the mainTable


                for (int rowNo = 0; rowNo <= noOfRows - 1; rowNo++)
                {
                    foreach (int iCol in lstColumnNums)
                    {
                        if (lstColumnsDisplay.Count > 0 && lstColumnsDisplay.Contains(iCol) == false)
                        {
                            continue;
                        }
                        if (iCol == 999)
                        {
                            mainTable.AddCell(EmptyCell());
                        }
                        else
                        {
                            string sData = (dt.Rows[rowNo][iCol] == null) ? string.Empty : dt.Rows[rowNo][iCol].ToString().Trim();
                            ph = new Phrase(sData, FontFactory.GetFont(SelectedFont, ReportTextSize, iTextSharp.text.Font.NORMAL));

                            PdfPCell cell = new PdfPCell(ph);
                            //cell.HorizontalAlignment =  GetAlignMent(dicDataType[iCol]);
                            if ((int)dicDataType[iCol] == (int)Helper.Alignment.Center)
                            {
                                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                            }
                            if ((int)dicDataType[iCol] == (int)Helper.Alignment.Right)
                            {
                                cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            }
                            if ((int)dicDataType[iCol] == (int)Helper.Alignment.Left)
                            {
                                cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            }

                            if (lstRepeatColumn.Contains(iCol))
                            {
                                cell.BackgroundColor = iTextSharp.text.BaseColor.YELLOW;
                            }

                            cell.NoWrap            = true;
                            cell.VerticalAlignment = Element.ALIGN_TOP;
                            //Element.ALIGN_TOP
                            mainTable.AddCell(cell);
                        }
                    }

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

                    if (mainTable.TotalHeight >= 595 - 65)                     // A4Dimension.Height - 65) {
                    {
                        lstTables.Add(mainTable);

                        mainTable            = new iTextSharp.text.pdf.PdfPTable(arrColsrelativeWidths);
                        mainTable.TotalWidth = document.PageSize.Width * 0.9f;

                        AddPageHeaderToPDFDataTable(ref mainTable, dt.TableName, strFilter, lstColumnNums.Count - 1);
                        AddColumnHeader(dt, ref mainTable, lstColumnNums, dicDataType, lstColumnsDisplay);
                    }
                }

                mainTable.CompleteRow();
                lstTables.Add(mainTable);
            }
            //Dict

            string strFileName = @"C:\Code\Project\TrailCode\eCatenate" + "\\" + dt.TableName + "_" + DateTime.Now.ToString("yyyyMMdd HHmmss") + ".pdf";

            // Gets the instance of the document created and writes it to the output stream of the Response object.
            PdfWriter pdfWrite = PdfWriter.GetInstance(document, new FileStream(strFileName, FileMode.Create));
            // Response.OutputStream)
            pdfPage _pdfpage = new pdfPage(SelectedFont, HeaderFontColor);

            pdfWrite.PageEvent = _pdfpage;
            // Creates a footer for the PDF document.
            //Dim pdfFooter As New HeaderFooter(New Phrase("Page : ", FontFactory.GetFont(FontFactory.COURIER, FooterTextSize, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.DARK_GRAY)), True)

            //pdfFooter.Alignment = Element.ALIGN_CENTER
            //pdfFooter.Border = iTextSharp.text.Rectangle.NO_BORDER

            var _with1 = document;
            //.Footer = pdfFooter
            _with1.Open();

            //document.Add(New Paragraph(strFont, times))

            _with1.AddCreator("ElaiyaKumar");
            _with1.AddAuthor("By ElaiyaKumar");
            foreach (iTextSharp.text.pdf.PdfPTable oMainTable in lstTables)
            {
                _with1.Add(oMainTable);
                _with1.NewPage();
            }
            _with1.Close();

            document = null;
            Console.WriteLine("Any key to save ....");
            Console.ReadKey();
            //Interaction.MsgBox("Report Saved as " + strFileName, MsgBoxStyle.Information, "Export PDF");
            Console.WriteLine(strFileName);
            Console.WriteLine();

            Process.Start(strFileName);
            return(true);
        } catch (Exception ex) {
            //PHLog.ErrorLogException(ex, oGV, System.Reflection.MethodBase.GetCurrentMethod.Name);
        }
        return(false);
    }
        private void button1_Click(object sender, EventArgs e)
        {
            connectionString = "Server = 127.0.0.1; Port = 3306; Database = db_user; Uid = root; Pwd =; ";
            querry           = "SELECT DATE(transaction.date) AS 'Date',"
                               + " transaction.transactionID AS 'Transaction Number',"
                               + " material.name AS 'Material Name',"
                               + " contract.quantity AS 'Quantity',"
                               + " supplier.name AS 'Supplier'"
                               + " FROM transaction, material, contract, supplier"
                               + " WHERE";

            if (value1 != 0)
            {
                querry = querry + " DAY(transaction.date) = " + value1 + " AND";
            }

            if (value2 != 0)
            {
                querry = querry + " MONTH(transaction.date) = " + value2 + " AND";
            }

            if (value3 != 0)
            {
                querry = querry + " YEAR(transaction.date) = " + value3 + " AND";
            }

            querry = querry + " transaction.materialID = material.materialID AND"
                     + " transaction.contractID = contract.contractID AND"
                     + " contract.supplierID = supplier.supplierID";
            connection  = new MySqlConnection(connectionString);
            dataAdapter = new MySqlDataAdapter(querry, connection);
            DataTable dt = new DataTable();

            connection.Open();
            dataAdapter.Fill(dt);

            saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            saveFileDialog1.Title            = "Save report file";
            saveFileDialog1.FileName         = "report";
            saveFileDialog1.Filter           = "*.pdf|*.pdf";
            if (saveFileDialog1.ShowDialog() != DialogResult.Cancel)
            {
                try
                {
                    Document  doc = new Document(PageSize.A4);
                    PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(saveFileDialog1.FileName.ToString(), FileMode.Create));
                    doc.Open();

                    iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(System.Reflection.Assembly.GetExecutingAssembly().Location + "\\..\\..\\..\\Resources\\logoprogram.png");
                    logo.SetAbsolutePosition(doc.PageSize.Width / 2 - 200f, doc.PageSize.Height - 250f);
                    doc.Add(logo);

                    Paragraph dateParagraph = new Paragraph("Report created: " + DateTime.Now.ToString("dd-MM-yyyy H:mm:ss"));
                    dateParagraph.SpacingBefore = 200f;
                    doc.Add(dateParagraph);

                    Paragraph tableParagraph;
                    if (dt.Rows.Count == 0)
                    {
                        tableParagraph = new Paragraph("There are no records in the database");
                        doc.Add(tableParagraph);
                        doc.Close();
                        MessageBox.Show("Report created succesfully!", "Succes!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.Close();
                    }
                    else
                    {
                        iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(dt.Columns.Count);

                        // Add the headers to the PDF
                        foreach (DataColumn column in dt.Columns)
                        {
                            table.AddCell(new Phrase(column.ColumnName));
                        }

                        table.HeaderRows = 1;

                        List <string> dates = new List <string>();
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            DateTime date = DateTime.ParseExact(dt.Rows[i][0].ToString(), "M/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
                            string   s    = date.ToString("dd-MM-yyyy");
                            dates.Add(s);
                        }
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            table.AddCell(new Phrase(dates.ElementAt(i)));
                            for (int j = 1; j < dt.Columns.Count; j++)
                            {
                                table.AddCell(new Phrase(dt.Rows[i][j].ToString()));
                            }
                        }
                        tableParagraph = new Paragraph();
                        tableParagraph.Add(table);
                        tableParagraph.SpacingBefore = 30f;
                        doc.Add(tableParagraph);

                        int   sum = 0;
                        float avg;

                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            sum = sum + Int32.Parse(dt.Rows[i]["Quantity"].ToString());
                        }
                        avg = sum / dt.Rows.Count;

                        Paragraph conclusionParagraph = new Paragraph("The average quantity bought from suppliers based on the date selected is " + avg);
                        conclusionParagraph.SpacingBefore = 30f;
                        doc.Add(conclusionParagraph);

                        doc.Close();
                        MessageBox.Show("Report created succesfully!", "Succes!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.Close();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("There was an error while trying  to create the report!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        public void GetPDFValue(TestRequestClass aTestRequestClass)
        {
            int       noOfColumns = 0, noOfRows = 0;
            DataTable tbl = null;

            if (showGridView.AutoGenerateColumns)
            {
                tbl         = showGridView.DataSource as DataTable; // Gets the DataSource of the GridView Control.
                noOfColumns = tbl.Columns.Count;
                noOfRows    = tbl.Rows.Count;
            }
            else
            {
                noOfColumns = showGridView.Columns.Count;
                noOfRows    = showGridView.Rows.Count;
            }
            float HeaderTextSize      = 8;
            float ReportNameSize      = 10;
            float ReportTextSize      = 8;
            float ApplicationNameSize = 12;

            Document document = null;

            if (LandScape == true)
            {
                document = new Document(PageSize.A4.Rotate(), 0, 0, 15, 5);
            }
            else
            {
                document = new Document(PageSize.A4, 0, 0, 15, 5);
            }
            iTextSharp.text.pdf.PdfPTable mainTable = new iTextSharp.text.pdf.PdfPTable(noOfColumns);
            mainTable.HeaderRows = 5;
            iTextSharp.text.pdf.PdfPTable headerTable = new iTextSharp.text.pdf.PdfPTable(2);
            Phrase phApplicationName =
                new Phrase(
                    "Bill No:" + aTestRequestClass.BillNo + "\nName: " + aTestRequestClass.Name + "\nMobile No: " +
                    aTestRequestClass.MobileNo + "\nDate Of Birth: " + aTestRequestClass.DateofBirth + " ",
                    FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.BOLD));
            PdfPCell clApplicationName = new PdfPCell(phApplicationName);

            clApplicationName.Border = PdfPCell.NO_BORDER;
            clApplicationName.HorizontalAlignment = Element.ALIGN_LEFT;
            Phrase aphSpace = new Phrase("\n");

            PdfPCell aclSpace = new PdfPCell(aphSpace);

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


            Phrase phDate = new Phrase("Entry Date: " + DateTime.Now.Date.ToString("dd/MM/yyyy"),
                                       FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));
            PdfPCell clDate = new PdfPCell(phDate);

            clDate.HorizontalAlignment = Element.ALIGN_RIGHT;
            clDate.Border = PdfPCell.NO_BORDER;
            headerTable.AddCell(clApplicationName);
            headerTable.AddCell(clDate);
            headerTable.DefaultCell.Border = PdfPCell.NO_BORDER;

            Phrase phHeader = new Phrase("PATIENT BILL ",
                                         FontFactory.GetFont("Arial", ReportNameSize, iTextSharp.text.Font.BOLD));
            PdfPCell clHeader = new PdfPCell(phHeader);

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

            PdfPCell cellHeader = new PdfPCell(headerTable);

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

            Phrase   phSpace = new Phrase("\n");
            PdfPCell clSpace = new PdfPCell(phSpace);

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

            for (int i = 0; i < noOfColumns; i++)
            {
                Phrase ph = null;
                if (showGridView.AutoGenerateColumns)
                {
                    ph = new Phrase(tbl.Columns[i].ColumnName,
                                    FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));
                }
                else
                {
                    ph = new Phrase(showGridView.Columns[i].HeaderText,
                                    FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));
                }
                mainTable.AddCell(ph);
            }
            for (int rowNo = 0; rowNo < noOfRows; rowNo++)
            {
                for (int columnNo = 0; columnNo < noOfColumns; columnNo++)
                {
                    if (showGridView.AutoGenerateColumns)
                    {
                        string s  = showGridView.Rows[rowNo].Cells[columnNo].Text.Trim();
                        Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
                        mainTable.AddCell(ph);
                    }
                    else
                    {
                        if (showGridView.Columns[columnNo] is TemplateField)
                        {
                            DataBoundLiteralControl lc =
                                showGridView.Rows[rowNo].Cells[columnNo].Controls[0] as DataBoundLiteralControl;
                            string s  = lc.Text.Trim();
                            Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
                            mainTable.AddCell(ph);
                        }
                        else
                        {
                            string s  = showGridView.Rows[rowNo].Cells[columnNo].Text.Trim();
                            Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
                            mainTable.AddCell(ph);
                        }
                    }
                }
                mainTable.CompleteRow();
            }

            Phrase phHeaderTotal = new Phrase("Total: " + aTestRequestClass.TotalFee + " TK ",
                                              FontFactory.GetFont("Arial", ReportNameSize, iTextSharp.text.Font.BOLD));
            PdfPCell clHeaderTotal = new PdfPCell(phHeaderTotal);

            clHeaderTotal.Colspan             = noOfColumns;
            clHeaderTotal.Border              = PdfPCell.BOX;
            clHeaderTotal.HorizontalAlignment = Element.ALIGN_RIGHT;
            mainTable.AddCell(clHeaderTotal);

            PdfWriter.GetInstance(document, Response.OutputStream);
            document.Open();
            document.Add(mainTable);
            document.Close();
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment; filename= PatientBill.pdf");
            Response.End();
        }
Example #55
0
    protected void Page_Load(object sender, EventArgs e)
    {
        var borderSides = Rectangle.RIGHT_BORDER + Rectangle.LEFT_BORDER;
        var borderBL    = Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER;
        var borderBR    = Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER;
        var borderTBL   = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER;
        var borderTBR   = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER;
        var alignRight  = Element.ALIGN_RIGHT;

        long oportunityId = Convert.ToInt64(Request.QueryString["id"]);
        int  companyId    = Convert.ToInt32(Request.QueryString["companyId"]);
        var  company      = new Company(companyId);
        var  res          = ActionResult.NoAction;
        var  user         = HttpContext.Current.Session["User"] as ApplicationUser;
        var  dictionary   = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var  oportunity   = Oportunity.ById(oportunityId, user.CompanyId);

        string path = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(oportunity.Description);

        var alignLeft = Element.ALIGN_LEFT;

        string fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_Oportunity"],
            formatedDescription,
            DateTime.Now);

        var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts);
        }

        this.headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        this.arial      = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        var descriptionFont = new Font(this.headerFont, 12, Font.BOLD, BaseColor.BLACK);
        var document        = new iTextSharp.text.Document(PageSize.A4, 40, 40, 65, 55);

        var writer           = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create));
        var pageEventHandler = new TwoColumnHeaderFooter
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = string.Format(CultureInfo.InvariantCulture, "{0}", user.UserName),
            CompanyId   = oportunity.CompanyId,
            CompanyName = company.Name,
            Title       = dictionary["Item_Oportunity"]
        };

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

        #region Dades bàsiques
        var table = new PdfPTable(4)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 0
        };

        table.SetWidths(new float[] { 30f, 50f, 30f, 50f });

        table.AddCell(new PdfPCell(new Phrase(oportunity.Description, descriptionFont))
        {
            Colspan             = 4,
            Border              = Rectangle.NO_BORDER,
            PaddingTop          = 10f,
            PaddingBottom       = 10f,
            HorizontalAlignment = Element.ALIGN_CENTER
        });

        table.AddCell(TitleCell(dictionary["Item_BusinessRisk_Tab_Basic"], 4));

        table.AddCell(TitleLabel(dictionary["Item_BusinessRisk_LabelField_DateStart"]));
        table.AddCell(TitleData(string.Format(CultureInfo.InvariantCulture, @"{0:dd/MM/yyyy}", oportunity.DateStart)));

        table.AddCell(TitleLabel(dictionary["Item_Process"]));
        table.AddCell(TitleData(oportunity.Process.Description));

        table.AddCell(TitleLabel(dictionary["Item_Rule"]));
        table.AddCell(TitleData(oportunity.Rule.Description));

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_IPR"]));
        table.AddCell(TitleData(oportunity.Rule.Limit.ToString()));

        string costText = oportunity.Cost.ToString();
        if (costText == "0")
        {
            costText = "-";
        }

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Cost"]));
        table.AddCell(TitleData(costText));

        string impactText = oportunity.Impact.ToString();
        if (impactText == "0")
        {
            impactText = "-";
        }

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Impact"]));
        table.AddCell(TitleData(impactText));

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Status"]));
        table.AddCell(TitleData(dictionary["Item_BusinessRisk_Status_Assumed"]));

        table.AddCell(SeparationRow());
        table.AddCell(TitleCell(dictionary["Item_Oportunity_LabelField_Description"]));
        table.AddCell(TextAreaCell(Environment.NewLine + oportunity.Description, ToolsPdf.BorderAll, alignLeft, 4));

        table.AddCell(SeparationRow());
        table.AddCell(TitleCell(dictionary["Item_Oportunity_LabelField_Causes"]));
        table.AddCell(TextAreaCell(Environment.NewLine + oportunity.Causes, ToolsPdf.BorderAll, alignLeft, 4));

        table.AddCell(SeparationRow());
        table.AddCell(TitleCell(dictionary["Item_Oportunity_LabelField_Control"]));
        table.AddCell(TextAreaCell(Environment.NewLine + oportunity.Control, ToolsPdf.BorderAll, alignLeft, 4));

        table.AddCell(SeparationRow());
        table.AddCell(TitleCell(dictionary["Item_Oportunity_LabelField_Notes"]));
        table.AddCell(TextAreaCell(Environment.NewLine + oportunity.Notes, ToolsPdf.BorderAll, alignLeft, 4));

        table.AddCell(SeparationRow());

        table.AddCell(TitleCell(dictionary["Item_Oportunity_Tab_Graphics"], 4));

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_IPR"]));
        table.AddCell(TitleData(oportunity.Rule.Limit.ToString()));

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Status"]));
        table.AddCell(TitleData(dictionary["Item_BusinessRisk_Status_Assumed"]));

        string finalCostText = oportunity.FinalCost.ToString();
        if (finalCostText == "0")
        {
            finalCostText = "-";
        }

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Cost"]));
        table.AddCell(TitleData(finalCostText));

        string finalImpactText = oportunity.FinalImpact.ToString();
        if (finalImpactText == "0")
        {
            finalImpactText = "-";
        }

        table.AddCell(TitleLabel(dictionary["Item_Oportunity_LabelField_Impact"]));
        table.AddCell(TitleData(finalImpactText));

        document.Add(table);
        #endregion

        if (user.HasGrantToRead(ApplicationGrant.IncidentActions))
        {
            // Añadir posible acción
            var action = IncidentAction.ByOportunityId(oportunity.Id, companyId);
            if (action.Id > 0)
            {
                var tableAction = new PdfPTable(4)
                {
                    WidthPercentage     = 100,
                    HorizontalAlignment = 0
                };

                tableAction.SetWidths(new float[] { 15f, 30f, 15f, 30f });

                // Descripción
                var headerFont = new Font(this.arial, 15, Font.NORMAL, BaseColor.BLACK);
                tableAction.AddCell(new PdfPCell(new Phrase(dictionary["Item_Incident_PDF_ActionPageTitle"], headerFont))
                {
                    Colspan             = 4,
                    Border              = ToolsPdf.BorderBottom,
                    HorizontalAlignment = Rectangle.ALIGN_CENTER
                });
                tableAction.AddCell(LabelCell(dictionary["Item_IncidentAction_Label_Description"], Rectangle.NO_BORDER));
                tableAction.AddCell(ValueCell(action.Description, ToolsPdf.BorderNone, alignLeft, 3));

                // WhatHappend
                tableAction.AddCell(SeparationRow());
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_WhatHappened"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.WhatHappened, borderSides, alignLeft, 4));
                tableAction.AddCell(BlankRow());
                tableAction.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + action.WhatHappenedBy.FullName, borderBL, alignLeft, 2));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_Date"], action.WhatHappenedOn), borderBR, alignRight, 2));

                // Causes
                var causesFullName = string.Empty;
                var causesDate     = string.Empty;
                if (action.CausesBy != null)
                {
                    causesFullName = action.CausesBy.FullName;
                    causesDate     = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.CausesOn);
                }
                tableAction.AddCell(SeparationRow());
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Causes"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Causes, borderSides, alignLeft, 4));
                tableAction.AddCell(BlankRow());
                tableAction.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + causesFullName, borderBL, alignLeft, 2));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1}", dictionary["Common_Date"], causesDate), borderBR, alignRight, 2));

                // Actions
                var actionFullName = string.Empty;
                var actionDate     = string.Empty;
                if (action.ActionsBy != null)
                {
                    actionFullName = action.ActionsBy.FullName;
                    actionDate     = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.ActionsOn);
                }
                tableAction.AddCell(SeparationRow());
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Actions"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Actions, borderSides, alignLeft, 4));
                tableAction.AddCell(BlankRow());
                tableAction.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + actionFullName, borderBL, alignLeft, 2));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1}", dictionary["Common_DateExecution"], actionDate), borderBR, alignRight, 2));

                // Monitoring
                tableAction.AddCell(SeparationRow());
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Monitoring"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Monitoring, ToolsPdf.BorderAll, alignLeft, 4));

                // Close
                var closedFullName = string.Empty;
                var closedDate     = string.Empty;
                if (action.ClosedBy != null)
                {
                    closedFullName = action.ClosedBy.FullName;
                    closedDate     = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.ClosedOn);
                }
                tableAction.AddCell(SeparationRow());
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Close"]));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1}", dictionary["Item_IncidentAction_Field_Responsible"], closedFullName), borderTBL, alignLeft, 2));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1}", dictionary["Common_DateClose"], closedDate), borderTBR, alignRight, 2));

                // Notes
                tableAction.AddCell(SeparationRow());
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Notes"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Notes, ToolsPdf.BorderAll, alignLeft, 4));

                document.NewPage();
                document.Add(tableAction);
            }

            #region Historico acciones
            var historico = IncidentAction.ByOportunityCode(oportunity.Code, company.Id).Where(ia => ia.Oportunity.Id != oportunity.Id).OrderBy(incidentAction => incidentAction.WhatHappenedOn).ToList();
            if (historico.Count > 0)
            {
                var backgroundColor = new iTS.BaseColor(225, 225, 225);
                var rowPair         = new iTS.BaseColor(255, 255, 255);
                var rowEven         = new iTS.BaseColor(240, 240, 240);
                var headerFontFinal = new iTS.Font(headerFont, 9, iTS.Font.NORMAL, iTS.BaseColor.BLACK);

                document.SetPageSize(PageSize.A4.Rotate());
                document.NewPage();

                var tableHistoric = new iTSpdf.PdfPTable(5)
                {
                    WidthPercentage     = 100,
                    HorizontalAlignment = 1,
                    SpacingBefore       = 20f
                };

                tableHistoric.SetWidths(new float[] { 20f, 30f, 120f, 20f, 20f });

                tableHistoric.AddCell(new PdfPCell(new Phrase(dictionary["Item_BusinessRisk_Tab_HistoryActions"], descriptionFont))
                {
                    Colspan             = 5,
                    Border              = Rectangle.NO_BORDER,
                    PaddingTop          = 20f,
                    PaddingBottom       = 20f,
                    HorizontalAlignment = Element.ALIGN_CENTER
                });

                var valueFont = new Font(this.headerFont, 11, Font.BOLD, BaseColor.BLACK);
                tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Open"]));
                tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Status"]));
                tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Description"]));
                tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_ImplementDate"]));
                tableHistoric.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentAction_Header_Close"]));

                int cont = 0;
                foreach (var accion in historico)
                {
                    string statusText = dictionary["Item_Incident_Status1"];

                    if (accion.CausesOn.HasValue)
                    {
                        statusText = dictionary["Item_Incident_Status2"];
                    }

                    if (accion.ActionsOn.HasValue)
                    {
                        statusText = dictionary["Item_Incident_Status3"];
                    }

                    if (accion.ClosedOn.HasValue)
                    {
                        statusText = dictionary["Item_Incident_Status4"];
                    }

                    tableHistoric.AddCell(ToolsPdf.DataCellCenter(accion.WhatHappenedOn, ToolsPdf.LayoutFonts.Times));
                    tableHistoric.AddCell(ToolsPdf.DataCell(statusText, ToolsPdf.LayoutFonts.Times));
                    tableHistoric.AddCell(ToolsPdf.DataCell(accion.Description, ToolsPdf.LayoutFonts.Times));
                    tableHistoric.AddCell(ToolsPdf.DataCellCenter(accion.ActionsOn, ToolsPdf.LayoutFonts.Times));
                    tableHistoric.AddCell(ToolsPdf.DataCellCenter(accion.ClosedOn, ToolsPdf.LayoutFonts.Times));

                    cont++;
                }

                tableHistoric.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant() + ": " + cont.ToString(), ToolsPdf.LayoutFonts.Times))
                {
                    Border  = ToolsPdf.BorderTop,
                    Colspan = 5,
                    Padding = 8f
                });

                document.Add(tableHistoric);
            }
            #endregion

            #region Costes
            var costs = IncidentActionCost.ByOportunityId(oportunity.Id, company.Id);
            if (costs.Count > 0)
            {
                var backgroundColor = new iTS.BaseColor(225, 225, 225);
                var rowPair         = new iTS.BaseColor(255, 255, 255);
                var rowEven         = new iTS.BaseColor(240, 240, 240);
                var headerFontFinal = new iTS.Font(headerFont, 9, iTS.Font.NORMAL, iTS.BaseColor.BLACK);

                document.SetPageSize(PageSize.A4.Rotate());
                document.NewPage();

                var tableCost = new iTSpdf.PdfPTable(5)
                {
                    WidthPercentage     = 100,
                    HorizontalAlignment = 1,
                    SpacingBefore       = 20f
                };

                tableCost.SetWidths(new float[] { 90f, 40f, 30f, 60f, 20f });

                tableCost.AddCell(new PdfPCell(new Phrase(dictionary["Item_Incident_Tab_Costs"], descriptionFont))
                {
                    Colspan             = 5,
                    Border              = Rectangle.NO_BORDER,
                    PaddingTop          = 20f,
                    PaddingBottom       = 20f,
                    HorizontalAlignment = Element.ALIGN_CENTER
                });

                var valueFont = new Font(this.headerFont, 11, Font.BOLD, BaseColor.BLACK);
                tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Description"]));
                tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Amount"]));
                tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Quantity"]));
                tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Total"]));
                tableCost.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_ReportedBy"]));

                int     cont      = 0;
                decimal costTotal = 0;
                foreach (var cost in costs)
                {
                    tableCost.AddCell(ToolsPdf.DataCell(cost.Description, ToolsPdf.LayoutFonts.Times));
                    tableCost.AddCell(ToolsPdf.DataCellMoney(cost.Amount, ToolsPdf.LayoutFonts.Times));
                    tableCost.AddCell(ToolsPdf.DataCellMoney(cost.Quantity, ToolsPdf.LayoutFonts.Times));
                    tableCost.AddCell(ToolsPdf.DataCellMoney(cost.Amount * cost.Quantity, ToolsPdf.LayoutFonts.Times));
                    tableCost.AddCell(ToolsPdf.DataCell(cost.Responsible.FullName, ToolsPdf.LayoutFonts.Times));

                    costTotal += cost.Amount * cost.Quantity;
                    cont++;
                }

                tableCost.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_RegisterCount"].ToUpperInvariant() + ": " + cont.ToString(), ToolsPdf.LayoutFonts.Times))
                {
                    Border  = ToolsPdf.BorderTop,
                    Colspan = 2,
                    Padding = 8f
                });

                tableCost.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(dictionary["Common_Total"].ToUpperInvariant() + ":", ToolsPdf.LayoutFonts.Times))
                {
                    Border              = ToolsPdf.BorderTop,
                    Colspan             = 1,
                    Padding             = 8f,
                    HorizontalAlignment = alignRight
                });

                tableCost.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(Tools.PdfMoneyFormat(costTotal), ToolsPdf.LayoutFonts.Times))
                {
                    Border              = ToolsPdf.BorderTop,
                    Colspan             = 1,
                    Padding             = 8f,
                    HorizontalAlignment = alignRight
                });



                tableCost.AddCell(new iTSpdf.PdfPCell(new iTS.Phrase(string.Empty, ToolsPdf.LayoutFonts.Times))
                {
                    Border              = ToolsPdf.BorderTop,
                    Colspan             = 1,
                    Padding             = 8f,
                    HorizontalAlignment = alignRight
                });

                document.Add(tableCost);
            }

            #endregion
        }

        document.Close();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "inline;filename=outfile.pdf");
        Response.ContentType = "application/pdf";
        Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName);
        Response.Flush();
        Response.Clear();
    }
        private static void HeaderGeneration(PdfPTable table, DateTime d)
        {
            string date = d.Date.ToString("dd-MMM-yyyy", CultureInfo.InvariantCulture);
            Font verdana2 = FontFactory.GetFont("Verdana", 12, Font.BOLD);

            d = d.Date;
            PdfPCell dateCell = new PdfPCell(new Phrase("Date: " + date));
            dateCell.Colspan = 5;
            dateCell.BackgroundColor = new BaseColor(242, 242, 242);
            table.AddCell(dateCell);

            BaseColor color = new BaseColor(217, 217, 217);

            PdfPCell product = new PdfPCell(new Phrase("Product", verdana2));
            product.BackgroundColor = color;
            table.AddCell(product);

            PdfPCell quantity = new PdfPCell(new Phrase("Quantity", verdana2));
            quantity.BackgroundColor = color;
            table.AddCell(quantity);

            PdfPCell unitPrice = new PdfPCell(new Phrase("Unit Price", verdana2));
            unitPrice.BackgroundColor = color;
            table.AddCell(unitPrice);

            PdfPCell location = new PdfPCell(new Phrase("Location", verdana2));
            location.BackgroundColor = color;
            table.AddCell(location);

            PdfPCell sum = new PdfPCell(new Phrase("Sum", verdana2));
            sum.BackgroundColor = color;
            table.AddCell(sum);
        }
        public override void OnStartPage(PdfWriter writer, iTextSharp.text.Document document)
        {
            iTextSharp.text.Image header = iTextSharp.text.Image.GetInstance(PathResolver.MapPath("images/ADB_Logo.gif"));

            PdfPTable tableHeader = new PdfPTable(2);
            tableHeader.WidthPercentage = 100;

            PdfPCell imageHeaderCell = new PdfPCell(header);
            imageHeaderCell.Rowspan = 2;
            imageHeaderCell.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
            imageHeaderCell.Border = 0;
            imageHeaderCell.PaddingBottom = 3;
            tableHeader.AddCell(imageHeaderCell);

            Font helvetica20 = FontFactory.GetFont(FontFactory.HELVETICA, 16);
            PdfPCell typeNameCell = new PdfPCell(new Phrase(TypesReader.GetDiagramName(this.type), helvetica20));
            typeNameCell.HorizontalAlignment = 2;
            typeNameCell.Border = 0;
            tableHeader.AddCell(typeNameCell);

            PdfPCell adbCell = new PdfPCell(new Phrase(GlobalStringResource.ADB, helvetica20));
            adbCell.HorizontalAlignment = 2;
            adbCell.Border = 0;
            tableHeader.AddCell(adbCell);

            PdfPCell lineCell = new PdfPCell();
            lineCell.Colspan = 2;
            lineCell.Border = 1;
            lineCell.PaddingBottom = 5;
            tableHeader.AddCell(lineCell);

            document.Add(tableHeader);
        }
Example #58
-1
        public Chapter SectionFour(StudentData sd)
        {
            Chapter chapter = ExamAnalysiseReportFormat.InsertChapterParagraph("均衡性分析", 4);

            var dt = sd.SectionFourDt();
            PdfPTable systemRankTable = ExamAnalysiseReportFormat.CreatePdfTable(dt, "test4", 0);
            chapter.Add(ExamAnalysiseReportFormat.InsertTableParagraph(systemRankTable));

            var value1 = "";
            var value2 = "";
            var strDataName = "";
            for (var i = 0; i < dt.Columns.Count-1; i++)
            {
                var row = dt.Rows;
                strDataName += dt.Columns[i] + "\t";
                value1 += "0\t";
                value2 += row[dt.Rows.Count-1][i] + "\t";
            }
            value1 += "0";
            value2 += dt.Rows[dt.Rows.Count - 1][dt.Rows.Count - 1];

            var imagePath = img.ChartTypeRadarLine(strDataName, value1, value2);
            var image = Image.GetInstance(imagePath);
            var pdfTable1 = new PdfPTable(2);

            var cell1 = new PdfPCell(ExamAnalysiseReportFormat.InsertSectionContent(sd.SfExplain, 12, true, 2)) { BorderWidth = 0 };
            cell1.SetLeading(1,2);
            var cell2 = new PdfPCell(ExamAnalysiseReportFormat.InsertImageParagraph(image)) { BorderWidth = 0 };
            pdfTable1.AddCell(cell2);
            pdfTable1.AddCell(cell1);
            chapter.Add(ExamAnalysiseReportFormat.InsertTableParagraph(pdfTable1));

            chapter.Add(ExamAnalysiseReportFormat.InsertExplainContent("图表说明:",8));
            return chapter;
        }
Example #59
-1
// ---------------------------------------------------------------------------
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document(PageSize.A5.Rotate())) {
        // step 2
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        writer.PdfVersion = PdfWriter.VERSION_1_5;
        writer.ViewerPreferences = PdfWriter.PageModeFullScreen;
        writer.PageEvent = new TransitionDuration();        
        // step 3
        document.Open();
        // step 4
        IEnumerable<Movie> movies = PojoFactory.GetMovies();
        Image img;
        PdfPCell cell;
        PdfPTable table = new PdfPTable(6);
        string RESOURCE = Utility.ResourcePosters;
        foreach (Movie movie in movies) {
          img = Image.GetInstance(Path.Combine(RESOURCE, movie.Imdb + ".jpg"));
          cell = new PdfPCell(img, true);
          cell.Border = PdfPCell.NO_BORDER;
          table.AddCell(cell);
        }
        document.Add(table);
      }
    }
Example #60
-6
// ---------------------------------------------------------------------------    
    /**
     * Manipulates a PDF file src with the file dest as result
     * @param src the original PDF
     */
    public byte[] ManipulatePdf(byte[] src) {
    // Create a table with named actions
      Font symbol = new Font(Font.FontFamily.SYMBOL, 20);
      PdfPTable table = new PdfPTable(4);
      table.DefaultCell.Border = Rectangle.NO_BORDER;
      table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
      Chunk first = new Chunk( ((char)220).ToString() , symbol);
      first.SetAction(new PdfAction(PdfAction.FIRSTPAGE));
      table.AddCell(new Phrase(first));
      Chunk previous = new Chunk( ((char)172).ToString(), symbol);
      previous.SetAction(new PdfAction(PdfAction.PREVPAGE));
      table.AddCell(new Phrase(previous));
      Chunk next = new Chunk( ((char)174).ToString(), symbol);
      next.SetAction(new PdfAction(PdfAction.NEXTPAGE));
      table.AddCell(new Phrase(next));
      Chunk last = new Chunk( ((char)222).ToString(), symbol);
      last.SetAction(new PdfAction(PdfAction.LASTPAGE));
      table.AddCell(new Phrase(last));
      table.TotalWidth = 120;
      
      // Create a reader
      PdfReader reader = new PdfReader(src);
      using (MemoryStream ms = new MemoryStream()) {
        // Create a stamper
        using (PdfStamper stamper = new PdfStamper(reader, ms)) {
          // Add the table to each page
          PdfContentByte canvas;
          for (int i = 0; i < reader.NumberOfPages; ) {
            canvas = stamper.GetOverContent(++i);
            table.WriteSelectedRows(0, -1, 696, 36, canvas);
          }
        }
        return ms.ToArray();
      }    
    }