Exemplo n.º 1
0
        public static string Create(IEnumerable <string> headers,
                                    IEnumerable <IEnumerable <string> > items,
                                    string filePath,
                                    string fileName,
                                    string title = null)
        {
            Contract.Assert(headers != null);
            Contract.Assert(items != null);

            var headerList = headers as IList <string> ?? headers.ToList();
            var table      = new PdfPTable(headerList.Count())
            {
                RunDirection = PdfWriter.RUN_DIRECTION_RTL, WidthPercentage = 100, LockedWidth = false
            };
            var columnMaxWidths = new int[headerList.Count()];
            var _path           = string.Empty;

            for (var i = 0; i < columnMaxWidths.Length; i++)
            {
                columnMaxWidths[i] = 0;
            }
            var fontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "tahoma.ttf");
            var baseFont = BaseFont.CreateFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);


            if (string.IsNullOrEmpty(title))
            {
                var tblTitle = new PdfPCell(new Phrase(title))
                {
                    PaddingTop    = 10,
                    PaddingBottom = 10,
                    Colspan       = headerList.Count()
                };

                table.AddCell(tblTitle);
            }

            int index = 0;

            foreach (var hd in headerList)
            {
                var font = new Font(baseFont, 7f, Font.BOLD, new BaseColor(Color.White));
                var cell = new PdfPCell(new Phrase(hd, font))
                {
                    BackgroundColor     = new BaseColor(25, 121, 255, 255),
                    PaddingTop          = 5,
                    PaddingRight        = 3,
                    PaddingBottom       = 5,
                    PaddingLeft         = 2,
                    HorizontalAlignment = 1
                };
                table.AddCell(cell);
                var textWidth = font.GetCalculatedBaseFont(true).GetWidth(hd);
                columnMaxWidths[index] = columnMaxWidths[index] > textWidth ? columnMaxWidths[index] : textWidth;
                index++;
            }

            int rowNumber = 1;

            foreach (var row in items)
            {
                var bgColor = rowNumber % 2 == 0
                    ? new BaseColor(Color.FromArgb(255, 214, 215, 216))
                    : new BaseColor(Color.White);

                var index2 = 0;
                foreach (var cell in row)
                {
                    var font    = new Font(baseFont, 6f, Font.NORMAL, new BaseColor(Color.Black));
                    var newCell = new PdfPCell(new Phrase(cell, font))
                    {
                        BackgroundColor     = bgColor,
                        Padding             = 2,
                        HorizontalAlignment = 1,
                        RunDirection        = PdfWriter.RUN_DIRECTION_RTL
                    };
                    table.AddCell(newCell);
                    var textWidth = string.IsNullOrEmpty(cell) ? 6 : font.GetCalculatedBaseFont(true).GetWidth(cell);
                    columnMaxWidths[index2] = columnMaxWidths[index2] > textWidth ? columnMaxWidths[index2] : textWidth;
                    index2++;
                }
                rowNumber++;
            }

            using (var memStream = new MemoryStream())
            {
                var doc = new Document(PageSize.A4);
                doc.AddHeader("default", "Default header");
                doc.AddCreator("mdkh.ir");
                doc.AddCreationDate();
                doc.AddTitle("Default Title");
                doc.AddAuthor("mdkh");
                PdfWriter.GetInstance(doc, memStream);
                doc.SetPageSize(PageSize.A4.Rotate());
                var tableWidth     = doc.PageSize.Height - (doc.RightMargin + doc.LeftMargin);
                var total          = columnMaxWidths.Sum();
                var relativeWidths = new float[columnMaxWidths.Count()];
                for (int i = 0; i < relativeWidths.Length; i++)
                {
                    var widthShare = (columnMaxWidths[i]) / (total * 1.0f);
                    //because of rtl direction
                    relativeWidths[relativeWidths.Length - 1 - i] = Convert.ToSingle((widthShare > .35f ? .3f : widthShare) * tableWidth);
                }
                table.SetWidths(relativeWidths);

                doc.Open();
                doc.Add(table);
                var ms2 = new MemoryStream();
                memStream.CopyTo(ms2);
                doc.Close();
                var fileContent = memStream.ToArray();
                var pgNumber    = new PageNumber()
                {
                    TextTemplate  = "{{current}}/{{total}}",
                    PrintLocation = PageSection.Bottom,
                    Alignment     = Alignment.Center,
                    FontOption    = new FontOption(baseFont),
                    Direction     = Direction.LeftToRight
                };
                AddPageNumbers(fileContent, ms2, pgNumber);

                var content = ms2.ToArray();
                _path = Path.Combine(filePath, (fileName.ToLowerInvariant().EndsWith(".pdf") ? fileName : fileName + ".pdf"));
                using (var fs = File.Create(_path))
                {
                    fs.Write(content, 0, (int)content.Length);
                }
            }

            return(_path);
        }
Exemplo n.º 2
0
        protected static void AddPageNumbers(byte[] fileContent, MemoryStream memoryStream, PageNumber pagingOptions)
        {
            var reader     = new PdfReader(fileContent);
            var totalPages = reader.NumberOfPages;

            using (var stamper = new PdfStamper(reader, memoryStream))
            {
                var n = reader.NumberOfPages;
                for (var i = 1; i <= n; i++)
                {
                    ApplyLocation(stamper, pagingOptions, i, totalPages);
                }
            }
        }