SetWidthPercentage() public method

public SetWidthPercentage ( float columnWidth, Rectangle pageSize ) : void
columnWidth float
pageSize Rectangle
return void
Example #1
1
        public MemoryStream CreatePDF(DataTable database, string customerName, DateTime date, string code)
        {
            Font Helvetica12B = FontFactory.GetFont(BaseFont.HELVETICA, 12, Font.BOLD);
            Font Helvetica10 = FontFactory.GetFont(BaseFont.HELVETICA, 10, Font.NORMAL);
            Font Courier12 = FontFactory.GetFont(BaseFont.COURIER, 12, Font.NORMAL);

            MemoryStream PDFData = new MemoryStream();
            Document document = new Document(PageSize.LETTER, 50, 50, 80, 60);
            PdfWriter PDFWriter = PdfWriter.GetInstance(document, PDFData);
            PDFWriter.ViewerPreferences = PdfWriter.PageModeUseOutlines;

            // Our custom Header and Footer is done using Event Handler
            HeaderFooter PageEventHandler = new HeaderFooter();
            PDFWriter.PageEvent = PageEventHandler;

            // Define the page header
            PageEventHandler.HeaderFont = FontFactory.GetFont(BaseFont.TIMES_ROMAN, 8, Font.ITALIC);
            PageEventHandler.HeaderLeft = "Ticketing system";
            PageEventHandler.HeaderRight = date.ToString("MMMM dd, yyyy HH:mm:ss");

            document.Open();

            document.Add(new Paragraph("Ticketing system", Helvetica12B));
            document.Add(new Paragraph("Orderer name: " + customerName, Helvetica10));
            document.Add(new Paragraph("Orders code: " + code, Helvetica10));
            document.Add(new Paragraph("Date: " + date.ToString("MMMM dd, yyyy HH:mm:ss"), Helvetica10));
            document.Add(new Paragraph(" ", Helvetica10));

            PdfPTable Orders = new PdfPTable(5);
            Orders.TotalWidth = document.PageSize.Width - 100;
            Orders.LockedWidth = true;
            float[] widthsTAS = { 15f, 30f, 35f, 10f, 10f };
            Orders.SetWidthPercentage(widthsTAS, document.PageSize);

            Orders.AddCell(new Paragraph("Organizer", Helvetica10));
            Orders.AddCell(new Paragraph("Date", Helvetica10));
            Orders.AddCell(new Paragraph("Title", Helvetica10));
            Orders.AddCell(new Paragraph("Row", Helvetica10));
            Orders.AddCell(new Paragraph("Number", Helvetica10));

            for (int i = 0; i < database.Rows.Count; i++)
            {
                Orders.AddCell(new Paragraph(database.Rows[i][0].ToString(), Helvetica10));
                Orders.AddCell(new Paragraph(Convert.ToDateTime(database.Rows[i][1].ToString()).ToString("MMMM dd, yyyy HH:mm"), Helvetica10));
                Orders.AddCell(new Paragraph(database.Rows[i][2].ToString(), Helvetica10));
                Orders.AddCell(new Paragraph(database.Rows[i][3].ToString(), Helvetica10));
                Orders.AddCell(new Paragraph(database.Rows[i][4].ToString(), Helvetica10));
            }

            document.Add(Orders);

            document.Close();

            return PDFData;
        }
Example #2
0
        protected void Unnamed1_Click1(object sender, EventArgs e)
        {
            try
            {
                string name = Guid.NewGuid().ToString() + ".pdf";
                string fileName = Server.MapPath("~/Reportes/");
                Document document = new Document(PageSize.A4, 50, 50, 25, 25);
                PdfWriter.GetInstance(document, new FileStream(fileName + name, FileMode.Create));
                document.Open();
                Paragraph parrafo = new Paragraph();
                parrafo.Alignment = Element.ALIGN_CENTER;
                parrafo.Font = FontFactory.GetFont("Arial", 24);
                parrafo.Font.SetStyle(Font.BOLD);
                parrafo.Font.SetStyle(Font.UNDERLINE);
                parrafo.Add("CENTRO DE FORMACIÓN TECNOLÓGICA\n\n\nCurso: " + cmbOpciones.SelectedItem.Text + "\n\n\nLista de alumnos inscritos:\n\n\n");
                document.Add(parrafo);
                PdfPTable unaTabla = new PdfPTable(4);
                unaTabla.SetWidthPercentage(new float[] { 200, 200, 200, 200 }, PageSize.A4);
                unaTabla.AddCell(new Paragraph("Estudiante"));
                unaTabla.AddCell(new Paragraph("Fecha de inscripción"));
                unaTabla.AddCell(new Paragraph("Curso"));
                unaTabla.AddCell(new Paragraph("Profesor"));
                foreach (PdfPCell celda in unaTabla.Rows[0].GetCells())
                {
                    celda.BackgroundColor = BaseColor.LIGHT_GRAY;
                    celda.HorizontalAlignment = 1;
                    celda.Padding = 3;
                }
                foreach (System.Web.UI.WebControls.GridViewRow row in grvInscripciones.Rows)
                {
                    PdfPCell celda1 = new PdfPCell(new Paragraph(row.Cells[0].Text, FontFactory.GetFont("Arial", 10)));
                    PdfPCell celda2 = new PdfPCell(new Paragraph(row.Cells[1].Text, FontFactory.GetFont("Arial", 10)));
                    PdfPCell celda3 = new PdfPCell(new Paragraph(row.Cells[2].Text, FontFactory.GetFont("Arial", 10)));
                    PdfPCell celda4 = new PdfPCell(new Paragraph(row.Cells[3].Text, FontFactory.GetFont("Arial", 10)));
                    unaTabla.AddCell(celda1);
                    unaTabla.AddCell(celda2);
                    unaTabla.AddCell(celda3);
                    unaTabla.AddCell(celda4);
                }
                document.Add(unaTabla);
                document.Close();
                Response.ContentType = "application/octet-stream";
                Response.AppendHeader("Content-Disposition", "attachment;filename=" + name);
                Response.TransmitFile(fileName + name);
                Response.End();

            }
            catch (Exception ex)
            {
                btnGenerar.Text = "Intentar de nuevo: " + ex.Message;
            }
        }
        public override void OnStartPage(PdfWriter writer, Document document)
        {
            base.OnStartPage(writer, document);
            Rectangle pageSize = document.PageSize;

            string imageURL = HttpContext.Current.Server.MapPath("~/Reportes/img/LogoRep.jpg");
            iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageURL);
            //Resize image depend upon your need
            jpg.ScaleToFit(100f, 100f);
            //Give space before image
            jpg.SpacingBefore = 10f;
            //Give some space after the image
            jpg.SpacingAfter = 1f;
            jpg.Alignment = Element.ALIGN_LEFT;

            PdfPTable headerTbl = new PdfPTable(1);

            headerTbl.TotalWidth = 400;

            headerTbl.HorizontalAlignment = Element.ALIGN_CENTER;

            PdfPCell cell11 = new PdfPCell(jpg);
            PdfPCell cell2 = new PdfPCell();
            cell2.Border = 0;
            cell11.Border = 0;

            cell11.PaddingLeft = 10;
            cell2.PaddingLeft = 10;
            headerTbl.AddCell(cell11);
            headerTbl.AddCell(cell2);

            headerTbl.WriteSelectedRows(0, -1, pageSize.GetLeft(40), pageSize.GetTop(10), writer.DirectContent);

            if (Title != string.Empty)
            {
                cb.BeginText();
                cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 15);
                cb.SetRGBColorFill(50, 50, 200);
                cb.SetTextMatrix(pageSize.GetLeft(250), pageSize.GetTop(95));
                cb.ShowText(Title);
                cb.EndText();
            }
            if (HeaderLeft + HeaderRight != string.Empty)
            {
                PdfPTable HeaderTable = new PdfPTable(2);
                HeaderTable.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                HeaderTable.TotalWidth = pageSize.Width - 80;
                HeaderTable.SetWidthPercentage(new float[] { 45, 45 }, pageSize);

                PdfPCell HeaderLeftCell = new PdfPCell(new Phrase(8, HeaderLeft, HeaderFont));
                HeaderLeftCell.Padding = 5;
                HeaderLeftCell.PaddingBottom = 8;
                HeaderLeftCell.BorderWidthRight = 0;
                HeaderTable.AddCell(HeaderLeftCell);
                PdfPCell HeaderRightCell = new PdfPCell(new Phrase(8, HeaderRight, HeaderFont));
                HeaderRightCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                HeaderRightCell.Padding = 5;
                HeaderRightCell.PaddingBottom = 8;
                HeaderRightCell.BorderWidthLeft = 0;
                HeaderTable.AddCell(HeaderRightCell);
                cb.SetRGBColorFill(0, 0, 0);
                HeaderTable.WriteSelectedRows(0, -1, pageSize.GetLeft(40), pageSize.GetTop(130), cb);
            }
        }
        public override void OnStartPage(PdfWriter writer, Document document)
        {
            base.OnStartPage(writer, document);
            Rectangle pageSize = document.PageSize;
            if (Title != string.Empty)
            {
                cb.BeginText();

                try
                {
                    cb.SetFontAndSize(bf, 15);
                    cb.SetRGBColorFill(50, 50, 200);
                    cb.SetTextMatrix(pageSize.GetLeft(pageSize.Width / 2), pageSize.GetTop(40));
                    cb.ShowText(Title);
                }
                catch { }

                cb.EndText();
            }
            if (HeaderLeft + HeaderRight != string.Empty)
            {
                PdfPTable HeaderTable = new PdfPTable(2);
                HeaderTable.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                HeaderTable.TotalWidth = pageSize.Width - 80;
                HeaderTable.SetWidthPercentage(new float[] { 45, 45 }, pageSize);

                PdfPCell HeaderLeftCell = new PdfPCell(new Phrase(8, HeaderLeft, HeaderFont));
                HeaderLeftCell.Padding = 5;
                HeaderLeftCell.PaddingBottom = 8;
                HeaderLeftCell.BorderWidthRight = 0;
                HeaderTable.AddCell(HeaderLeftCell);
                PdfPCell HeaderRightCell = new PdfPCell(new Phrase(8, HeaderRight, HeaderFont));
                HeaderRightCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                HeaderRightCell.Padding = 5;
                HeaderRightCell.PaddingBottom = 8;
                HeaderRightCell.BorderWidthLeft = 0;
                HeaderTable.AddCell(HeaderRightCell);
                cb.SetRGBColorFill(0, 0, 0);
                HeaderTable.WriteSelectedRows(0, -1, pageSize.GetLeft(40), pageSize.GetTop(50), cb);
            }
        }
Example #5
0
        /// <summary>
        /// Create the PDF using the defined page size, label type and content provided
        /// Ensure you have added something first using either AddImage() or AddText()
        /// </summary>
        /// <returns></returns>
        public Stream CreatePDF()
        {
            //Get the itext page size
            Rectangle pageSize;
            switch (_label.PageSize)
            {
                case Enums.PageSize.A4:
                    pageSize = iTextSharp.text.PageSize.A4;
                    break;
                default:
                    pageSize = iTextSharp.text.PageSize.A4;
                    break;
            }

            //Create a new iText document object, define the paper size and the margins required
            var doc = new Document(pageSize,
                                   _label.PageMarginLeft,
                                   _label.PageMarginRight,
                                   _label.PageMarginTop,
                                   _label.PageMarginBottom);

            //Create a stream to write the PDF to
            var output = new MemoryStream();

            //Creates the document tells the PdfWriter to use the output stream when Document.Close() is called
            var writer = PdfWriter.GetInstance(doc, output);

            //Ensure stream isn't closed when done - we need to return it
            writer.CloseStream = false;

            //Open the document to begin adding elements
            doc.Open();

            //Create a new table with label and gap columns
            var numOfCols = _label.LabelsPerRow + (_label.LabelsPerRow - 1);
            var tbl = new PdfPTable(numOfCols);

            //Build the column width array, even numbered index columns will be gap columns
            var colWidths = new List<float>();
            for (int i = 1; i <= numOfCols; i++)
            {
                if (i % 2 > 0)
                {
                    colWidths.Add(_label.Width);
                }
                else
                {
                    //Even numbered columns are gap columns
                    colWidths.Add(_label.HorizontalGapWidth);
                }
            }

            /* The next 3 lines are the key to making SetWidthPercentage work */
            /* "size" specifies the size of the page that equates to 100% - even though the values passed are absolute not relative?! */
            /* (I will never get those 3 hours back) */
            var w = iTextSharp.text.PageSize.A4.Width - (doc.LeftMargin + doc.RightMargin);
            var h = iTextSharp.text.PageSize.A4.Height - (doc.TopMargin + doc.BottomMargin);
            var size = new iTextSharp.text.Rectangle(w, h);

            //Set the column widths (in points) - take note of the size parameter mentioned above
            tbl.SetWidthPercentage(colWidths.ToArray(), size);

            //Create the rows for the table
            for (int iRow = 0; iRow < _label.LabelRowsPerPage; iRow++)
            {

                var rowCells = new List<PdfPCell>();

                //Build the row - even numbered index columns are gaps
                for (int iCol = 1; iCol <= numOfCols; iCol++)
                {
                    if (iCol % 2 > 0)
                    {

                        // Create a new Phrase and add the image to it
                        var cellContent = new Phrase();

                        foreach (var img in _images)
                        {
                            var pdfImg = iTextSharp.text.Image.GetInstance(img);
                            cellContent.Add(new Chunk(pdfImg, 0, 0));
                        }

                        foreach (var txt in _textChunks)
                        {
                            var font = FontFactory.GetFont(txt.FontName, BaseFont.CP1250, txt.EmbedFont, txt.FontSize, txt.FontStyle);
                            cellContent.Add(new Chunk("\n" + txt.Text, font));
                        }

                        //Create a new cell specifying the content
                        var cell = new PdfPCell(cellContent);

                        //Ensure our label height is adhered to
                        cell.FixedHeight = _label.Height;

                        //Centre align the content
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;

                        cell.Border = IncludeLabelBorders ? Rectangle.BOX : Rectangle.NO_BORDER;

                        //Add to the row
                        rowCells.Add(cell);
                    }
                    else
                    {
                        //Create a empty cell to use as a gap
                        var gapCell = new PdfPCell();
                        gapCell.FixedHeight = _label.Height;
                        gapCell.Border = Rectangle.NO_BORDER;
                        //Add to the row
                        rowCells.Add(gapCell);
                    }
                }

                //Add the new row to the table
                tbl.Rows.Add(new PdfPRow(rowCells.ToArray()));

                //On all but the last row, add a gap row if needed
                if ((iRow + 1) < _label.LabelRowsPerPage && _label.VerticalGapHeight > 0)
                {
                    tbl.Rows.Add(CreateGapRow(numOfCols));
                }

            }

            //Add the table to the document
            doc.Add(tbl);

            //Close the document, writing to the stream we specified earlier
            doc.Close();

            //Set the stream back to position 0 so we can use it when it's returned
            output.Position = 0;

            return output;
        }
        public BarcodeModule()
            : base("/api")
        {
            Get["/barcode/{issuedTo}/{issuedBy}/{airport}/{validFrom}/{validTo}/{count}"] = _ =>
            {
                var count = (int)_.count;
                var issuedTo = _.issuedTo;
                var validFrom = _.validFrom;
                var validTo = _.validTo;
                var airport = _.airport;

                Program.ProcessLog.Write(_.issuedBy  +" has generated " + count + " barcodes for " + issuedTo);
                var writer = new BarcodeWriter
                {
                    Format = BarcodeFormat.PDF_417,
                    Options = { Margin = 2 }
                };
                var barcodeList = new List<BarcodeGroup>();
                for (var i = 1; i <= count; i++)
                {
                   BarcodeGroup bg = Barcode.Generate(writer, airport, validFrom, validTo);
                   barcodeList.Add(bg);
                    var dateFrom = DateTime.ParseExact(validFrom, "yyyyMMdd", CultureInfo.InvariantCulture,
                        DateTimeStyles.None);
                    var dateTo = DateTime.ParseExact(validTo, "yyyyMMdd", CultureInfo.InvariantCulture,
                        DateTimeStyles.None);
                    if (!CovertBarcode.AddNew(issuedTo, _.issuedBy, bg.barcode, dateFrom, dateTo))
                    {
                        Console.WriteLine(CovertBarcode.LastError.ToString());
                    }
                    var chis = CovertBarcode.Load(bg.barcode);
                    bg.serial = chis.SerialNumber;
                    bg.from = validFrom;
                    bg.to = validTo;
                    if (!CovertBarcodeAction.AddNew(chis.RecordID, _.issuedBy))
                    {
                        Console.WriteLine(CovertBarcodeAction.LastError.ToString());
                    }
                    else
                    {
                        var caction = CovertBarcodeAction.LoadCovertBarcode(chis.RecordID);
                        if (!CovertBarcodeActionResult.AddNew(caction.RecordID))
                        {
                            Console.WriteLine(CovertBarcodeAction.LastError.ToString());
                        }
                    }

                }
                var response =
                    new Response();
                response.Headers.Add("Content-Disposition", "attachment; filename=GeneratedBarcodes" + DateTime.Now.ToString("dd MMM yyyy HH mm")+".pdf");
                var document = new Document(PageSize.A4,
                       MmToPoint(7.2),
                       MmToPoint(7.2),
                       MmToPoint(15.1),
                       MmToPoint(15.1));
                response.Contents = stream =>
                {
                    var msWriter = PdfWriter.GetInstance(document, stream);
                    document.Open();
                    var numOfCols = 5;
                    var tbl = new PdfPTable(numOfCols);
                    var colWidths = new List<float>();
                    for (var i = 1; i <= numOfCols; i++)
                    {
                        colWidths.Add(i%2 > 0 ? MmToPoint(63.5) : MmToPoint(2.5));
                    }
                    var w = PageSize.A4.Width - ( MmToPoint(7.2) +  MmToPoint(7.2));
                    var h = PageSize.A4.Height - ( MmToPoint(15.1) +  MmToPoint(15.1));
                    var size = new Rectangle(w, h);
                    tbl.SetWidthPercentage(colWidths.ToArray(), size);
                    var index = 0;
                    var div = Convert.ToDouble(count)/21.0;
                    var dbl = Math.Ceiling(div);
                    for (var i = 0; i < dbl; i++)
                    {
                         document.NewPage();
                        tbl = new PdfPTable(numOfCols);
                        tbl.SetWidthPercentage(colWidths.ToArray(), size);
                        for (var iRow = 0; iRow < 7; iRow++)
                        {
                            var rowCells = new List<PdfPCell>();
                            for (var iCol = 1; iCol <= numOfCols; iCol++)
                            {

                                if (iCol % 2 > 0)
                                {
                                    if (index < barcodeList.Count)
                                    {
                                        var cellContent = new Phrase();
                                        var img = barcodeList[index].image;
                                        var pic = Image.GetInstance(img, ImageFormat.Bmp);
                                        pic.ScaleAbsolute(MmToPoint(60), MmToPoint(24));
                                        var pdfImg = Image.GetInstance(pic);
                                        cellContent.Add(new Chunk(pdfImg, 0, -70f));
                                        cellContent.Add(new Chunk("\n"));
                                        cellContent.Add(new Chunk("\n"));
                                        cellContent.Add(new Chunk("\n"));
                                        cellContent.Add(new Chunk("\n"));
                                        cellContent.Add(new Chunk("\n"));
                                        cellContent.Add(new Chunk("\n"));
                                        var bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false);
                                        var f = new Font(bf, 5.0f, Font.NORMAL, BaseColor.BLACK);
                                        cellContent.Add(
                                            new Chunk(
                                                "\n" + barcodeList[index].serial.ToString().PadLeft(6, '0') +
                                                "                                                              " +
                                                barcodeList[index].from + " " + barcodeList[index].to, f));
                                        var cell = new PdfPCell(cellContent)
                                        {
                                            FixedHeight = MmToPoint(38.1),
                                            HorizontalAlignment = Element.ALIGN_CENTER,
                                            Border = false ? Rectangle.BOX : Rectangle.NO_BORDER
                                        };
                                        rowCells.Add(cell);
                                        index++;
                                    }
                                    else
                                    {
                                        var cellContent = new Phrase();
                                        var cell = new PdfPCell(cellContent)
                                        {
                                            FixedHeight = MmToPoint(38.1),
                                            HorizontalAlignment = Element.ALIGN_CENTER,
                                            Border = false ? Rectangle.BOX : Rectangle.NO_BORDER
                                        };
                                        rowCells.Add(cell);
                                        index++;
                                    }

                                }
                                else
                                {
                                    var gapCell = new PdfPCell
                                    {
                                        FixedHeight = MmToPoint(38.1),
                                        Border = Rectangle.NO_BORDER
                                    };
                                    rowCells.Add(gapCell);
                                }
                            }
                            tbl.Rows.Add(new PdfPRow(rowCells.ToArray()));
                        }
                          document.Add(tbl);

                    }
                    document.Close();
                };
                return response;
            };

            #region test
            //Get["/barcode/test"] = _ =>
            //{
            //    var writer = new BarcodeWriter
            //    {
            //        Format = BarcodeFormat.PDF_417,
            //        Options = { Margin = 2 }
            //    };
            //    var barcodeList = new List<BarcodeTest>();

            //    var a = new BarcodeTest
            //    {
            //        barcode = writer.Write("M1YARWOOD/A MR        E2CIPT2 MANFNCLS 0765 292Y501A0501 100"),
            //        text = "T1  LS765  09:15",
            //    };

            //    barcodeList.Add(a);
            //    var b = new BarcodeTest
            //    {
            //        barcode = writer.Write("M1A Yarwood/MR        E2AIEF2 MANFNCLS 0765 292Y502A0502 100"),
            //        text = "T1  LS765  09:15"
            //    };
            //    barcodeList.Add(b);

            //    var c = new BarcodeTest
            //    {
            //        barcode = writer.Write("M1YARWOOD/A MR        E2CIED2 MANVIELS 0959 292Y501A0501 100"),
            //        text = "T1  LS959  13:15"
            //    };
            //    barcodeList.Add(c);
            //    var d = new BarcodeTest
            //    {
            //        barcode = writer.Write("M1A Yarwood/MR        E2AIEB2 MANVIELS 0959 292Y502A0502 100"),
            //        text = "T1  LS959  13:15"
            //    };
            //    barcodeList.Add(d);

            //    var e = new BarcodeTest
            //    {
            //        barcode = writer.Write("M1YARWOOD/A MR        E2CIBA2 MANACETOM2126 292Y501A0501 100"),
            //        text = "T2  TOM2126  13:10"
            //    };
            //    barcodeList.Add(e);

            //    var j = new BarcodeTest
            //    {
            //        barcode = writer.Write("M1YARWOOD/A MR        E5CFED2 MANTFSFR 4332 292Y501A0501 100"),
            //        text = "T3  FR4332  13:10"
            //    };

            //    barcodeList.Add(j);

            //    var g = new BarcodeTest
            //    {
            //        barcode = writer.Write("M1A Yarwood/MR        E3AAEB2 MANTFSFR 4332 292Y502A0502 100"),
            //        text = "T3  FR4332  13:10"
            //    };
            //    barcodeList.Add(g);

            //    var response =
            //        new Response();
            //    response.Headers.Add("Content-Disposition", "attachment; filename=GeneratedBarcodes" + DateTime.Now.ToString("dd MMM yyyy HH mm") + ".pdf");
            //    var document = new Document(PageSize.A4,
            //           MmToPoint(7.2),
            //           MmToPoint(7.2),
            //           MmToPoint(15.1),
            //           MmToPoint(15.1));
            //    response.Contents = stream =>
            //    {
            //        var msWriter = PdfWriter.GetInstance(document, stream);
            //        document.Open();
            //        var numOfCols = 5;
            //        var tbl = new PdfPTable(numOfCols);
            //        var colWidths = new List<float>();
            //        for (var i = 1; i <= numOfCols; i++)
            //        {
            //            colWidths.Add(i % 2 > 0 ? MmToPoint(63.5) : MmToPoint(2.5));
            //        }
            //        var w = PageSize.A4.Width - (MmToPoint(7.2) + MmToPoint(7.2));
            //        var h = PageSize.A4.Height - (MmToPoint(15.1) + MmToPoint(15.1));
            //        var size = new Rectangle(w, h);
            //        tbl.SetWidthPercentage(colWidths.ToArray(), size);
            //        var index = 0;
            //        var div = Convert.ToDouble(7) / 21.0;
            //        var dbl = Math.Ceiling(div);
            //        for (var i = 0; i < dbl; i++)
            //        {
            //            document.NewPage();
            //            tbl = new PdfPTable(numOfCols);
            //            tbl.SetWidthPercentage(colWidths.ToArray(), size);
            //            for (var iRow = 0; iRow < 7; iRow++)
            //            {
            //                var rowCells = new List<PdfPCell>();
            //                for (var iCol = 1; iCol <= numOfCols; iCol++)
            //                {

            //                    if (iCol % 2 > 0)
            //                    {
            //                        if (index < barcodeList.Count)
            //                        {
            //                            var cellContent = new Phrase();
            //                            var img = barcodeList[index].barcode;
            //                            var pic = Image.GetInstance(img, ImageFormat.Bmp);
            //                            pic.ScaleAbsolute(MmToPoint(60), MmToPoint(24));
            //                            var pdfImg = Image.GetInstance(pic);
            //                            cellContent.Add(new Chunk(pdfImg, 0, -70f));
            //                            cellContent.Add(new Chunk("\n"));
            //                            cellContent.Add(new Chunk("\n"));
            //                            cellContent.Add(new Chunk("\n"));
            //                            cellContent.Add(new Chunk("\n"));
            //                            cellContent.Add(new Chunk("\n"));
            //                            cellContent.Add(new Chunk("\n"));
            //                            var bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false);
            //                            var f = new Font(bf, 3.0f, Font.NORMAL, BaseColor.BLACK);
            //                            cellContent.Add(
            //                                new Chunk(
            //                                    "\n" + barcodeList[index].text.ToString()));
            //                            var cell = new PdfPCell(cellContent)
            //                            {
            //                                FixedHeight = MmToPoint(38.1),
            //                                HorizontalAlignment = Element.ALIGN_CENTER,
            //                                Border = false ? Rectangle.BOX : Rectangle.NO_BORDER
            //                            };
            //                            rowCells.Add(cell);
            //                            index++;
            //                        }
            //                        else
            //                        {
            //                            var cellContent = new Phrase();
            //                            var cell = new PdfPCell(cellContent)
            //                            {
            //                                FixedHeight = MmToPoint(38.1),
            //                                HorizontalAlignment = Element.ALIGN_CENTER,
            //                                Border = false ? Rectangle.BOX : Rectangle.NO_BORDER
            //                            };
            //                            rowCells.Add(cell);
            //                            index++;
            //                        }

            //                    }
            //                    else
            //                    {
            //                        var gapCell = new PdfPCell
            //                        {
            //                            FixedHeight = MmToPoint(38.1),
            //                            Border = Rectangle.NO_BORDER
            //                        };
            //                        rowCells.Add(gapCell);
            //                    }
            //                }
            //                tbl.Rows.Add(new PdfPRow(rowCells.ToArray()));
            //            }
            //            document.Add(tbl);

            //        }
            //        document.Close();
            //    };
            //    return response;
            //};
            #endregion
        }
        void PrintHeader(Document document)
        {
            var headerTable = new PdfPTable (3);

            headerTable.SetWidthPercentage (new float[] { 20, 60, 20 }, document.PageSize);

            headerTable.DefaultCell.Border = Rectangle.NO_BORDER;
            headerTable.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;

            var headerLeftCell = new PdfPCell (new Phrase (8, headerLeft, font));
            headerLeftCell.Border = Rectangle.NO_BORDER;
            headerTable.AddCell (headerLeftCell);

            var headerCenterCell = new PdfPCell (new Phrase (8, header, font));
            headerCenterCell.HorizontalAlignment = Element.ALIGN_CENTER;
            headerCenterCell.Border = Rectangle.NO_BORDER;
            headerTable.AddCell (headerCenterCell);

            var headerRightCell = new PdfPCell (new Phrase (8, headerRight, font));
            headerRightCell.Border = Rectangle.NO_BORDER;
            headerRightCell.HorizontalAlignment = Element.ALIGN_RIGHT;
            headerTable.AddCell (headerRightCell);

            contentByte.MoveTo (
                document.PageSize.GetLeft (document.LeftMargin),
                document.PageSize.GetTop (document.TopMargin - 5 - (HasTitleAndSubjet ? 65 : 0))
            );
            contentByte.LineTo (
                document.PageSize.GetRight (document.RightMargin),
                document.PageSize.GetTop (document.TopMargin - 5 - (HasTitleAndSubjet ? 65 : 0))
            );
            contentByte.Stroke ();

            headerTable.WriteSelectedRows (
                0, -1,
                document.PageSize.GetLeft (document.LeftMargin),
                document.PageSize.GetTop (document.TopMargin - 20 - (HasTitleAndSubjet ? 65 : 0)),
                contentByte
            );
        }
 // ---------------------------------------------------------------------------    
 /**
  * Creates a table; widths are set with special setWidthPercentage() method.
  * @return a PdfPTable
  */
 public static PdfPTable CreateTable4()
 {
     PdfPTable table = new PdfPTable(3);
     Rectangle rect = new Rectangle(523, 770);
     table.SetWidthPercentage(new float[] { 144, 72, 72 }, rect);
     PdfPCell cell;
     cell = new PdfPCell(new Phrase("Table 4"));
     cell.Colspan = 3;
     table.AddCell(cell);
     cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
     cell.Rowspan = 2;
     table.AddCell(cell);
     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 table;
 }
        public MemoryStream GeneratePdf(MemoryStream stream, List<BarcodeGroup> barcodes, int barcodeCount)
        {
            Document document = new Document(PageSize.A4, MmToPoint(7.2), MmToPoint(7.2), MmToPoint(15.1),
                MmToPoint(15.1));

            PdfWriter msWriter = PdfWriter.GetInstance(document, stream);
            document.Open();
            int numOfCols = 5;
            PdfPTable tbl = new PdfPTable(numOfCols);
            List<float> colWidths = new List<float>();
            for (var i = 1; i <= numOfCols; i++)
            {
                colWidths.Add(i % 2 > 0 ? MmToPoint(63.5) : MmToPoint(2.5));
            }
            float w = PageSize.A4.Width - (MmToPoint(7.2) + MmToPoint(7.2));
            float h = PageSize.A4.Height - (MmToPoint(15.1) + MmToPoint(15.1));
            Rectangle size = new Rectangle(w, h);
            tbl.SetWidthPercentage(colWidths.ToArray(), size);
            int index = 0;
            double div = Convert.ToDouble(barcodeCount) / 21.0;
            double dbl = Math.Ceiling(div);
            for (var i = 0; i < dbl; i++)
            {
                document.NewPage();
                tbl = new PdfPTable(numOfCols);
                tbl.SetWidthPercentage(colWidths.ToArray(), size);
                for (var iRow = 0; iRow < 7; iRow++)
                {
                    List<PdfPCell> rowCells = new List<PdfPCell>();
                    for (var iCol = 1; iCol <= numOfCols; iCol++)
                    {
                        if (iCol % 2 > 0)
                        {
                            if (index < barcodes.Count)
                            {
                                Phrase cellContent = new Phrase();
                                var img = barcodes[index].image;
                                Image pic = Image.GetInstance(img, ImageFormat.Bmp);
                                pic.ScaleAbsolute(MmToPoint(60), MmToPoint(24));
                                Image pdfImg = Image.GetInstance(pic);
                                cellContent.Add(new Chunk(pdfImg, 0, -70f));
                                cellContent.Add(new Chunk("\n"));
                                cellContent.Add(new Chunk("\n"));
                                cellContent.Add(new Chunk("\n"));
                                cellContent.Add(new Chunk("\n"));
                                cellContent.Add(new Chunk("\n"));
                                cellContent.Add(new Chunk("\n"));
                                BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false);
                                Font f = new Font(bf, 5.0f, Font.NORMAL, BaseColor.BLACK);
                                cellContent.Add(
                                    new Chunk(
                                        "\n" + barcodes[index].serial.ToString().PadLeft(6, '0') +
                                        "                                                              " +
                                        barcodes[index].from + " " + barcodes[index].to, f));
                                PdfPCell cell = new PdfPCell(cellContent)
                                {
                                    FixedHeight = MmToPoint(38.1),
                                    HorizontalAlignment = Element.ALIGN_CENTER,
                                    Border = false ? Rectangle.BOX : Rectangle.NO_BORDER
                                };
                                rowCells.Add(cell);
                                index++;
                            }
                            else
                            {
                                Phrase cellContent = new Phrase();
                                PdfPCell cell = new PdfPCell(cellContent)
                                {
                                    FixedHeight = MmToPoint(38.1),
                                    HorizontalAlignment = Element.ALIGN_CENTER,
                                    Border = false ? Rectangle.BOX : Rectangle.NO_BORDER
                                };
                                rowCells.Add(cell);
                                index++;
                            }
                        }
                        else
                        {
                            PdfPCell gapCell = new PdfPCell
                            {
                                FixedHeight = MmToPoint(38.1),
                                Border = Rectangle.NO_BORDER
                            };
                            rowCells.Add(gapCell);
                        }
                    }
                    tbl.Rows.Add(new PdfPRow(rowCells.ToArray()));
                }
                document.Add(tbl);
            }
            document.Close();

            return stream;
        }
Example #10
0
        //PdfContentByte cb;
        //PdfTemplate template;
        //public override void OnOpenDocument(PdfWriter writer, Document document)
        //{
        //    cb = writer.DirectContent;
        //    template = cb.CreateTemplate(50, 50);
        //}
        public override void OnStartPage(iTextSharp.text.pdf.PdfWriter writer ,iTextSharp.text.Document document )
        {
            base.OnStartPage(writer, document);
            #region ENCABEZADO
            //agregar imagen
            iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(AppDomain.CurrentDomain.BaseDirectory.ToString() + "/img/cofiño_stahl.jpg");
            //jpg.Alignment = iTextSharp.text.Image.MIDDLE_ALIGN;
            jpg.ScalePercent(25f);

            //We are going to add two strings in header. Create separate Phrase object with font setting and string to be included
            Phrase p1Header = new Phrase("Facturación Electrónica", FontFactory.GetFont("verdana", 14));
            Phrase p2Header = new Phrase(DateTime.Now.ToLongDateString(), FontFactory.GetFont("verdana", 8));

            //create iTextSharp.text Image object using local image path
            iTextSharp.text.Image imgPDF = iTextSharp.text.Image.GetInstance(HttpRuntime.AppDomainAppPath + "\\img\\cofiño_stahl.jpg");
            imgPDF.ScalePercent(25f);
            //Create PdfTable object
            PdfPTable pdfTab = new PdfPTable(3);
            //We will have to create separate cells to include image logo and 2 separate strings
            PdfPCell pdfCell1 = new PdfPCell(imgPDF);
            PdfPCell pdfCell2 = new PdfPCell(p1Header);
            PdfPCell pdfCell3 = new PdfPCell(p2Header);
            //set the alignment of all three cells and set border to 0
            pdfCell1.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfCell2.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfCell3.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfCell1.Border = 0;
            pdfCell2.Border = 0;
            pdfCell3.Border = 0;
            pdfCell2.VerticalAlignment = Element.ALIGN_MIDDLE;
            pdfCell3.VerticalAlignment = Element.ALIGN_BOTTOM;
            //establecer anchos
            float[] withsHead = new float[] { 14f, 49f, 21f };
            //add all three cells into PdfTable
            pdfTab.AddCell(pdfCell1);
            pdfTab.AddCell(pdfCell2);
            pdfTab.AddCell(pdfCell3);
            pdfTab.SetWidthPercentage(withsHead, document.PageSize);
            pdfTab.TotalWidth = document.PageSize.Width - 30;
            //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable
            //first param is start row. -1 indicates there is no end row and all the rows to be included to write
            //Third and fourth param is x and y position to start writing
            pdfTab.WriteSelectedRows(0, -1, 30, document.PageSize.Height - 15, writer.DirectContent);
            //set pdfContent value
            PdfContentByte pdfContent = writer.DirectContent;
            //Move the pointer and draw line to separate header section from rest of page
            pdfContent.MoveTo(30, document.PageSize.Height - 45);
            pdfContent.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 45);
            pdfContent.Stroke();
            document.Add(new Phrase(Chunk.NEWLINE));
            document.Add(new Phrase(Chunk.NEWLINE));
            document.Add(new Phrase(Chunk.NEWLINE));
            #endregion
        }
        /// <summary>
        /// Create the PDF using the defined page size, label type and content provided
        /// Ensure you have added something first using either AddImage() or AddText()
        /// </summary>
        /// <returns></returns>
        public Stream CreatePDF()
        {
            //Get the itext page size
            Rectangle pageSize;
            switch (_labelDefinition.PageSize)
            {
                case Enums.PageSize.A4:
                    pageSize = iTextSharp.text.PageSize.A4;
                    break;
                default:
                    pageSize = iTextSharp.text.PageSize.A4;
                    break;
            }

            //Create a new iText document object, define the paper size and the margins required
            var doc = new Document(pageSize,
                                   _labelDefinition.PageMarginLeft,
                                   _labelDefinition.PageMarginRight,
                                   _labelDefinition.PageMarginTop,
                                   _labelDefinition.PageMarginBottom);

            //Create a stream to write the PDF to
            var output = new MemoryStream();

            //Creates the document tells the PdfWriter to use the output stream when Document.Close() is called
            var writer = PdfWriter.GetInstance(doc, output);

            //Ensure stream isn't closed when done - we need to return it
            writer.CloseStream = false;

            //Open the document to begin adding elements
            doc.Open();

            //Create a new table with label and gap columns
            var numOfCols = _labelDefinition.LabelsPerRow + (_labelDefinition.LabelsPerRow - 1);
               // var tbl = new PdfPTable(numOfCols);

            //Build the column width array, even numbered index columns will be gap columns
            var colWidths = new List<float>();
            for (int i = 1; i <= numOfCols; i++)
            {
                if (i % 2 > 0)
                {
                    colWidths.Add(_labelDefinition.Width);
                }
                else
                {
                    //Even numbered columns are gap columns
                    colWidths.Add(_labelDefinition.HorizontalGapWidth);
                }
            }

            /* The next 3 lines are the key to making SetWidthPercentage work */
            /* "size" specifies the size of the page that equates to 100% - even though the values passed are absolute not relative?! */
            /* (I will never get those 3 hours back) */
            var w = iTextSharp.text.PageSize.A4.Width - (doc.LeftMargin + doc.RightMargin);
            var h = iTextSharp.text.PageSize.A4.Height - (doc.TopMargin + doc.BottomMargin);
            var size = new iTextSharp.text.Rectangle(w, h);

            // loop over the labels

            var rowNumber = 0;
            var colNumber = 0;

            PdfPTable tbl = null;
            foreach (var label in _labels)
            {
                if (rowNumber == 0)
                {
                    tbl = new PdfPTable(numOfCols);
                    tbl.SetWidthPercentage(colWidths.ToArray(), size);
                    rowNumber = 1; // so we start with row 1
                    doc.NewPage();
                }
                colNumber++; // so we start with col 1

                // add the label cell.
                var cell = FormatCell(label.GetLabelCell());

                //Add to the row
                tbl.AddCell(cell);

                //Create a empty cell to use as a gap
                if (colNumber < numOfCols)
                {
                    tbl.AddCell(CreateGapCell());
                    colNumber++; // increment for the gap row
                }

                //On all but the last row, after the last column, add a gap row if needed
                if (colNumber == numOfCols && ((rowNumber) < _labelDefinition.LabelRowsPerPage && _labelDefinition.VerticalGapHeight > 0))
                {
                    tbl.Rows.Add(CreateGapRow(numOfCols));
                }

                if (colNumber == numOfCols)
                {
                    // add the row to the table and re-initialize
                    tbl.CompleteRow();

                    rowNumber++;
                    colNumber = 0;
                }

                if (rowNumber > _labelDefinition.LabelRowsPerPage)
                {
                    //Add the table to the document
                    doc.Add(tbl);
                    rowNumber = 0;
                    colNumber = 0;
                }

            }

            if (colNumber < numOfCols)
            {
                // finish the row that was being built
                while (colNumber < numOfCols)
                {
                    if (colNumber % 2 == 1)
                    {
                        tbl.AddCell(CreateEmptyLabelCell());
                    }
                    else
                    {
                        tbl.AddCell(CreateGapCell());
                    }
                    colNumber++;
                }

                tbl.CompleteRow();
            }

            // make sure the last table gets added to the document
            if (rowNumber > 0)
            {
                //Add the table to the document
                doc.Add(tbl);
            }

            //Close the document, writing to the stream we specified earlier
            doc.Close();

            //Set the stream back to position 0 so we can use it when it's returned
            output.Position = 0;

            return output;
        }
Example #12
0
        public void dataTableToPdf(System.Data.DataTable dataTable, string FilePath)
        {
            FontFactory.RegisterDirectories();
            iTextSharp.text.Font font = FontFactory.GetFont("Courier", BaseFont.IDENTITY_H, 8, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
            iTextSharp.text.Font fontMedium = FontFactory.GetFont("Courier", BaseFont.IDENTITY_H, 11, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
            Document document = new Document(PageSize.A4.Rotate(), 20f, 20f, 20f, 25f);

            PdfWriter pdfWriter = PdfWriter.GetInstance(document, new FileStream(FilePath, FileMode.Create));
            pdfWriter.PageEvent = new ItextPageEvent();

            PdfPTable pdfTable = new PdfPTable(dataTable.Columns.Count);
            pdfTable.WidthPercentage = 100f;
            pdfTable.SpacingAfter = 10;
            pdfTable.SpacingBefore = 10;

            PdfContentByte pdfContentByte = new PdfContentByte(pdfWriter);

            iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(logoPath, true);
            logo.ScaleToFit(80f, 80f);

            StringBuilder sbParagraph1, sbParagraph2, sbParagraph3, sbParagraph4, sbParagraph5, sbParagraph6;
            sbParagraph1 = new StringBuilder("");
            sbParagraph2 = new StringBuilder("");
            sbParagraph3 = new StringBuilder("");
            sbParagraph4 = new StringBuilder("");
            sbParagraph5 = new StringBuilder("");
            sbParagraph6 = new StringBuilder("");

            if (
                reportType == ReportType.HISTORICAL ||
                reportType == ReportType.RUNNING ||
                reportType == ReportType.IDLING ||
                reportType == ReportType.ACC ||
                reportType == ReportType.GEOFENCE ||
                reportType == ReportType.OVERSPEED ||
                reportType == ReportType.EXTERNAL_POWER_CUT
                ) {
                sbParagraph1.Append(
                    "Vehicle Reg\n" +
                    "Vehicle Model\n" +
                    "Owner Name\n" +
                    "Driver Name\n" +
                    "Device Imei\n"
                );
                sbParagraph2.Append(
                    ": " + reportInformation.trackerVehicleReg + "\n" +
                    ": " + reportInformation.trackerVehicleModel + "\n" +
                    ": " + reportInformation.trackerOwnerName + "\n" +
                    ": " + reportInformation.trackerDriverName + "\n" +
                    ": " + reportInformation.trackerDeviceImei + "\n"
                );
            }

            if (
                reportType == ReportType.RUNNING ||
                reportType == ReportType.IDLING ||
                reportType == ReportType.ACC ||
                reportType == ReportType.GEOFENCE ||
                reportType == ReportType.OVERSPEED ||
                reportType == ReportType.TRACKERS_GEOFENCE ||
                reportType == ReportType.EXTERNAL_POWER_CUT
               ) {

                sbParagraph3.Append(
                   "Total Distance\n" +
                   "Total Fuel\n" +
                   "Total Cost\n");

                switch (reportType) {
                    case ReportType.RUNNING:
                        sbParagraph3.Append("Total Running Time\n");
                        break;
                    case ReportType.IDLING:
                        sbParagraph3.Append("Total Idling Time\n");
                        break;
                    case ReportType.GEOFENCE:
                        sbParagraph3.Append("Total Geofence Active Time\n");
                        break;
                    case ReportType.ACC:
                        sbParagraph3.Append("Total ACC Active Time\n");
                        break;
                    case ReportType.EXTERNAL_POWER_CUT:
                        sbParagraph3.Append("Total ExternalPower Cut Time\n");
                        break;
                }

                sbParagraph4.Append(": " + reportInformation.summaryTotalDistance + "\n");
                sbParagraph4.Append(": " + reportInformation.summaryTotalFuel + "\n");
                sbParagraph4.Append(": " + reportInformation.summaryTotalCost + "\n");
                switch (reportType) {
                    case ReportType.RUNNING:
                        sbParagraph4.Append(": " + reportInformation.summaryTotalRunningTime + "\n");
                        break;
                    case ReportType.IDLING:
                        sbParagraph4.Append(": " + reportInformation.summaryTotalIdlingTime + "\n");
                        break;
                    case ReportType.GEOFENCE:
                        sbParagraph4.Append(": " + reportInformation.summaryTotalGeofenceActiveTime + "\n");
                        break;
                    case ReportType.ACC:
                        sbParagraph4.Append(": " + reportInformation.summaryTotalAccActiveTime + "\n");
                        break;
                    case ReportType.EXTERNAL_POWER_CUT:
                        sbParagraph4.Append(": " + reportInformation.summaryTotalExternalPowerCutTime + "\n");
                        break;
                }
            }

            if (
               reportType == ReportType.HISTORICAL ||
               reportType == ReportType.RUNNING ||
               reportType == ReportType.IDLING ||
               reportType == ReportType.ACC ||
               reportType == ReportType.GEOFENCE ||
               reportType == ReportType.OVERSPEED ||
                reportType == ReportType.EXTERNAL_POWER_CUT
               ) {
                sbParagraph5.Append("DateTime From\n");
                sbParagraph5.Append("DateTime To\n");
            }

            sbParagraph5.Append("Generated by\n" + "Created on\n");

            if (
               reportType == ReportType.HISTORICAL ||
               reportType == ReportType.RUNNING ||
               reportType == ReportType.IDLING ||
               reportType == ReportType.ACC ||
               reportType == ReportType.GEOFENCE ||
               reportType == ReportType.OVERSPEED ||
                reportType == ReportType.EXTERNAL_POWER_CUT

               ) {
                sbParagraph6.Append(": " + reportInformation.summaryDateTimeFrom + "\n");
                sbParagraph6.Append(": " + reportInformation.summaryDateTimeTo + "\n");
            }

            sbParagraph6.Append(": " + reportInformation.userName + "\n");
            sbParagraph6.Append(": " + DateTime.Now.ToString() + "\n");

            Paragraph paragraph0 = new Paragraph(reportInformation.companyName + "\n" + Enum.GetName(typeof(ReportType), reportType) + " Report\n" + this.title, fontMedium);
            Paragraph paragraph1 = new Paragraph(sbParagraph1.ToString(), font);
            Paragraph paragraph2 = new Paragraph(sbParagraph2.ToString(), font);
            Paragraph paragraph3 = new Paragraph(sbParagraph3.ToString(), font);
            Paragraph paragraph4 = new Paragraph(sbParagraph4.ToString(), font);
            Paragraph paragraph5 = new Paragraph(sbParagraph5.ToString(), font);
            Paragraph paragraph6 = new Paragraph(sbParagraph6.ToString(), font);

            //======================================
            PdfPTable pdfTableHeader;
            PdfPCell pdfCell;

            pdfTableHeader = new PdfPTable(8);

            pdfCell = new PdfPCell(logo, true);
            pdfCell.BorderWidth = 0;
            pdfCell.PaddingLeft = 20f;
            pdfCell.PaddingRight = 20f;
            pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfTableHeader.AddCell(pdfCell);

            pdfCell = new PdfPCell(paragraph0);
            pdfCell.BorderWidth = 0;
            pdfCell.Padding = 0;
            pdfCell.PaddingTop = 12;
            pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfTableHeader.AddCell(pdfCell);

            pdfCell = new PdfPCell(paragraph1);
            pdfCell.BorderWidth = 0;
            pdfCell.Padding = 0;
            pdfCell.PaddingTop = 12;
            pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfTableHeader.AddCell(pdfCell);

            pdfCell = new PdfPCell(paragraph2);
            pdfCell.BorderWidth = 0;
            pdfCell.Padding = 0;
            pdfCell.PaddingTop = 12;
            pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfTableHeader.AddCell(pdfCell);

            pdfCell = new PdfPCell(paragraph3);
            pdfCell.BorderWidth = 0;
            pdfCell.Padding = 0;
            pdfCell.PaddingTop = 12;
            pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfTableHeader.AddCell(pdfCell);

            pdfCell = new PdfPCell(paragraph4);
            pdfCell.BorderWidth = 0;
            pdfCell.Padding = 0;
            pdfCell.PaddingTop = 12;
            pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfTableHeader.AddCell(pdfCell);

            pdfCell = new PdfPCell(paragraph5);
            pdfCell.BorderWidth = 0;
            pdfCell.Padding = 0;
            pdfCell.PaddingTop = 12;
            pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfTableHeader.AddCell(pdfCell);

            pdfCell = new PdfPCell(paragraph6);
            pdfCell.BorderWidth = 0;
            pdfCell.Padding = 0;
            pdfCell.PaddingTop = 12;
            pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfTableHeader.AddCell(pdfCell);
            pdfTableHeader.SetWidthPercentage(new float[8] { 140f, 150f, 60f, 100f, 110f, 100f, 60f, 100f }, PageSize.A4.Rotate());
            pdfTableHeader.HorizontalAlignment = Element.ALIGN_LEFT;

            try {

                document.Open();
                document.Add(pdfTableHeader);

                for (int index = 0; index < dataTable.Columns.Count; ++index) {
                    string columnName = dataTable.Columns[index].ColumnName;
                    //columnName = columnName.Replace('[', ' ');
                    //columnName = columnName.Replace(']', ' ');
                    Phrase phrase = new Phrase(columnName, font);
                    PdfPCell cell = new PdfPCell(phrase);
                    cell.BackgroundColor = BaseColor.CYAN;
                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
                    pdfTable.AddCell(cell);
                }

                for (int i = 0; i < dataTable.Rows.Count; ++i) {
                    for (int j = 0; j < dataTable.Columns.Count; ++j) {
                        string data = dataTable.Rows[i][j].ToString();

                        if (dataTable.Rows[i][j].GetType() == typeof(DateTime)) {
                            DateTime dateTime = (DateTime)dataTable.Rows[i][j];
                            data = dateTime.ToString("yyyy/MM/dd HH:mm:ss");
                        }
                        if (dataTable.Rows[i][j].GetType() == typeof(TimeSpan)) {
                            TimeSpan timeSpan = (TimeSpan)dataTable.Rows[i][j];
                            data = timeSpan.ToString(@"dd\ hh\:mm\:ss");
                        }

                        //if (dataTable.Rows[i][j].GetType() == typeof(double)) {
                        //    double number = (double)dataTable.Rows[i][j];
                        //    data = Converter.round(number).ToString();
                        //}
                        //if (dataTable.Rows[i][j].GetType() == typeof(TimeSpan)) {
                        //    TimeSpan timeSpan = (TimeSpan)dataTable.Rows[i][j];
                        //    data = timeSpan.ToString(@"dd\ hh\:mm\:ss");
                        //}

                        Phrase phrase = new Phrase(data, font);
                        PdfPCell cell = new PdfPCell(phrase);
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
                        pdfTable.AddCell(cell);
                    }
                }
                document.Add(pdfTable);
                document.Close();
            } catch (Exception exception) {
                document.Close();
                throw exception;
            }
        }
Example #13
0
        public override void OnStartPage(PdfWriter writer, Document document)
        {
            base.OnStartPage(writer, document);

            //document.SetMargins(document.LeftMargin, document.LeftMargin, document.TopMargin, document.BottomMargin); //Mirror the horizontal margins
            //document.NewPage(); //do this otherwise the margins won't take

            Rectangle pageSize = document.PageSize;

            if (!string.IsNullOrWhiteSpace(Title))
            {
                cb.BeginText();
                cb.SetFontAndSize(bf, 15);
                cb.SetRGBColorFill(50, 50, 200);
                cb.SetTextMatrix(pageSize.GetLeft(40), pageSize.GetTop(40));
                cb.ShowText(Title);
                cb.EndText();
            }

            if ( !string.IsNullOrWhiteSpace(HeaderLeft + HeaderRight))
            {
                PdfPTable HeaderTable = new PdfPTable(2);
                HeaderTable.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                HeaderTable.TotalWidth = pageSize.Width - 80;
                HeaderTable.SetWidthPercentage(new float[] { 45, 45 }, pageSize);

                PdfPCell HeaderLeftCell = new PdfPCell(new Phrase(8, HeaderLeft, HeaderFont));
                HeaderLeftCell.Padding = 5;
                HeaderLeftCell.PaddingBottom = 8;
                HeaderLeftCell.BorderWidthRight = 0;
                HeaderTable.AddCell(HeaderLeftCell);

                PdfPCell HeaderRightCell = new PdfPCell(new Phrase(8, HeaderRight, HeaderFont));
                HeaderRightCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                HeaderRightCell.Padding = 5;
                HeaderRightCell.PaddingBottom = 8;
                HeaderRightCell.BorderWidthLeft = 0;
                HeaderTable.AddCell(HeaderRightCell);

                cb.SetRGBColorFill(0, 0, 0);
                HeaderTable.WriteSelectedRows(0, -1, pageSize.GetLeft(40), pageSize.GetTop(50), cb);
            }
        }