Ejemplo n.º 1
0
        private void Start_Click(object sender, RoutedEventArgs e)
        {
            if (OutputFilePath == null || OutputFilePath.Length <= 0)
            {
                MessageBox.Show("Please provide a file path before attempting to generate output.", "", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            Logger.Log(Severity.INFO, LogCategory.APP, "Job started (engine PDF)");
            var stopWatch = Stopwatch.StartNew();

            Common.Logging.LogManager.Adapter = new ITextLoggingShimAdapter();
            try {
                using (PdfWriter writer = new PdfWriter(OutputFilePath)) {
                    PdfDocument pdf = new PdfDocument(writer);
                    pdf.AddEventHandler(PdfDocumentEvent.START_PAGE, new PageStartEventHandler(DocTemplate));
                    Document document = null;
                    foreach (var page in DocTemplate)
                    {
                        var pageSize = new iText.Kernel.Geom.PageSize(
                            page.PageWidth.ToITextPoint(),
                            page.PageHeight.ToITextPoint()
                            );

                        if (document == null)
                        {
                            document = new Document(pdf, pageSize);
                            document.SetMargins(0, 0, 0, 0);
                        }
                        else
                        {
                            document.Add(new iText.Layout.Element.AreaBreak(pageSize));
                        }


                        foreach (var canvasCtrl in page.CanvasControls)
                        {
                            var elements = new List <iText.Layout.Element.IElement>();
                            elements = canvasCtrl.ToIText();
                            foreach (var element in elements)
                            {
                                if (element is iText.Layout.Element.Paragraph paragraph)
                                {
                                    document.Add(paragraph);
                                }
                                else if (element is iText.Layout.Element.Image image)
                                {
                                    document.Add(image);
                                }
                            }
                        }
                    }
                    document.Close();
                    pdf.Close();
                }
            }
            catch (Exception err) {
                Logger.Log(Severity.ERROR, LogCategory.APP, err.Message);
            }
            stopWatch.Stop();
            Logger.Log(Severity.INFO, LogCategory.APP, String.Format("Job finished (duration {0})", stopWatch.Elapsed.ToString("hh':'mm':'ss':'fff")));
        }
Ejemplo n.º 2
0
        public byte[] TasksByProjectAsPdf(SqlContext context, int projectId, User currentUser, string taskGroupScope)
        {
            var buffer       = new byte[0];
            var stream       = new MemoryStream();
            var timeZone     = DateTimeZoneProviders.Tzdb.GetZoneOrNull(currentUser.TimeZone);
            var nowInstant   = SystemClock.Instance.GetCurrentInstant();
            var nowLocal     = nowInstant.InZone(timeZone);
            var nowDateTime  = nowLocal.LocalDateTime.ToDateTimeUnspecified();
            var organization = context.Organizations.Find(currentUser.OrganizationId);

            var project = context.Jobs
                          .Include("Customer")
                          .Where(p => p.Id == projectId)
                          .FirstOrDefault();

            var writer   = new PdfWriter(stream);
            var pdf      = new PdfDocument(writer);
            var document = new Document(pdf);

            // Define document properties.
            var info = pdf.GetDocumentInfo();

            info.SetTitle($"Barcodes for Project {project.Number} - {project.Name}");
            info.SetAuthor(currentUser.Name);
            info.SetCreator("BRIZBEE");

            // Page formatting.
            document.SetMargins(30, 30, 30, 30);

            // Set page header and footer.
            pdf.AddEventHandler(PdfDocumentEvent.END_PAGE, new MyEventHandler(organization.Name));

            var generatedParagraph = new Paragraph($"GENERATED {nowDateTime.ToString("ddd, MMM d, yyyy h:mm:ss tt").ToUpper()}");

            generatedParagraph.SetFont(fontP);
            generatedParagraph.SetFontSize(8);
            generatedParagraph.SetHorizontalAlignment(HorizontalAlignment.RIGHT);
            generatedParagraph.SetTextAlignment(TextAlignment.RIGHT);
            generatedParagraph.SetPaddingBottom(5);
            document.Add(generatedParagraph);

            var table = new Table(UnitValue.CreatePercentArray(new float[] { 50, 50 }))
                        .UseAllAvailableWidth();

            // Project details are at the top of the table.
            var detailsCell = new Cell(0, 2);

            detailsCell.SetPadding(20);

            var customerParagraph = new Paragraph();

            customerParagraph.SetFont(fontH1);
            customerParagraph.SetPaddingBottom(0);

            if (organization.ShowCustomerNumber)
            {
                customerParagraph.Add($"CUSTOMER: {project.Customer.Number} - {project.Customer.Name.ToUpper()}");
            }
            else
            {
                customerParagraph.Add($"CUSTOMER: {project.Customer.Name.ToUpper()}");
            }

            var projectParagraph = new Paragraph();

            projectParagraph.SetFont(fontH1);
            projectParagraph.SetPaddingBottom(10);

            if (organization.ShowProjectNumber)
            {
                projectParagraph.Add($"PROJECT: {project.Number} - {project.Name.ToUpper()}");
            }
            else
            {
                projectParagraph.Add($"PROJECT: {project.Name.ToUpper()}");
            }

            var descriptionParagraph = new Paragraph($"DESCRIPTION: {project.Description}");

            descriptionParagraph.SetFont(fontP);
            descriptionParagraph.SetFontSize(9);

            detailsCell.Add(customerParagraph);
            detailsCell.Add(projectParagraph);
            detailsCell.Add(descriptionParagraph);
            table.AddCell(detailsCell);

            var tasks = new List <Brizbee.Core.Models.Task>(0);

            if (string.IsNullOrEmpty(taskGroupScope) || taskGroupScope == "Unspecified")
            {
                tasks = context.Tasks
                        .Where(t => t.JobId == projectId)
                        .ToList();
            }
            else
            {
                tasks = context.Tasks
                        .Where(t => t.JobId == projectId)
                        .Where(t => t.Group == taskGroupScope)
                        .ToList();
            }

            foreach (var task in tasks)
            {
                try
                {
                    // Generate a barcode.
                    Barcode128 barCode = new Barcode128(pdf);
                    barCode.SetTextAlignment(Barcode128.ALIGN_CENTER);
                    barCode.SetCode(task.Number);
                    barCode.SetStartStopText(false);
                    barCode.SetCodeType(Barcode128.CODE128);
                    barCode.SetExtended(true);
                    barCode.SetAltText("");
                    barCode.SetBarHeight(50);

                    var barCodeCell = new Cell();
                    barCodeCell.SetPadding(20);
                    barCodeCell.SetHorizontalAlignment(HorizontalAlignment.CENTER);

                    var barCodeParagraph = new Paragraph();
                    barCodeParagraph.SetTextAlignment(TextAlignment.CENTER);
                    barCodeParagraph.Add(new Image(barCode.CreateFormXObject(pdf)));

                    barCodeCell.Add(barCodeParagraph);

                    var subtitleParagraph = new Paragraph();
                    subtitleParagraph.SetFont(fontSubtitle);
                    subtitleParagraph.SetTextAlignment(TextAlignment.CENTER);
                    subtitleParagraph.Add($"{task.Number} - {task.Name.ToUpper()}");

                    barCodeCell.Add(subtitleParagraph);

                    table.AddCell(barCodeCell);
                }
                catch (Exception ex)
                {
                    Trace.TraceError(ex.ToString());
                }
            }

            if (tasks.Count % 2 != 0)
            {
                // Add a blank cell to balance the columns.
                var blankCell = new Cell();
                table.AddCell(blankCell);
            }

            document.Add(table);

            for (int i = 0; i <= pdf.GetNumberOfPages(); i++)
            {
            }

            document.Close();

            buffer = stream.ToArray();

            return(buffer);
        }
Ejemplo n.º 3
0
        public ActionResult Get(string token)
        {
            MemoryStream ms = new MemoryStream();

            PdfWriter   pw          = new PdfWriter(ms);
            PdfDocument pdfDocument = new PdfDocument(pw);
            Document    doc         = new Document(pdfDocument, PageSize.LETTER);

            doc.SetMargins(75, 35, 70, 35);

            string pathLogo = Server.MapPath("~/Content/logo.jpg");
            Image  img      = new Image(ImageDataFactory.Create(pathLogo));

            pdfDocument.AddEventHandler(PdfDocumentEvent.START_PAGE, new HeaderEventHandler(img));
            pdfDocument.AddEventHandler(PdfDocumentEvent.END_PAGE, new FooterEventHandler());


            Table table = new Table(1).UseAllAvailableWidth();
            Cell  cell  = new Cell().Add(new Paragraph("INVOICE").SetFontSize(14)).SetTextAlignment(TextAlignment.CENTER).SetBorder(Border.NO_BORDER);

            table.AddCell(cell);

            doc.Add(table);

            Table _table = new Table(1).UseAllAvailableWidth();

            _table.AddCell(new Cell().Add(new Paragraph("For,")).SetTextAlignment(TextAlignment.RIGHT).SetBorder(Border.NO_BORDER));
            _table.AddCell(new Cell().Add(new Paragraph("Aditya Gaikwad")).SetTextAlignment(TextAlignment.RIGHT).SetBorder(Border.NO_BORDER));
            _table.AddCell(new Cell().Add(new Paragraph("Akurdi, Pune")).SetTextAlignment(TextAlignment.RIGHT).SetBorder(Border.NO_BORDER));


            doc.Add(_table);

            Style styleCell = new Style().SetBackgroundColor(ColorConstants.LIGHT_GRAY).SetTextAlignment(TextAlignment.CENTER);

            _table = new Table(5).UseAllAvailableWidth();
            Cell _cell = new Cell().Add(new Paragraph("#")).SetBorder(Border.NO_BORDER).SetBorderBottom(new SolidBorder(ColorConstants.BLACK, 1)).SetBorderTop(new SolidBorder(ColorConstants.BLACK, 1));

            _table.AddHeaderCell(_cell.AddStyle(styleCell));
            _cell = new Cell().Add(new Paragraph("Book Name")).SetBorder(Border.NO_BORDER).SetBorderBottom(new SolidBorder(ColorConstants.BLACK, 1)).SetBorderTop(new SolidBorder(ColorConstants.BLACK, 1));
            _table.AddHeaderCell(_cell.AddStyle(styleCell));
            _cell = new Cell().Add(new Paragraph("Quantity")).SetBorder(Border.NO_BORDER).SetBorderBottom(new SolidBorder(ColorConstants.BLACK, 1)).SetBorderTop(new SolidBorder(ColorConstants.BLACK, 1));
            _table.AddHeaderCell(_cell.AddStyle(styleCell));
            _cell = new Cell().Add(new Paragraph("Price")).SetBorder(Border.NO_BORDER).SetBorderBottom(new SolidBorder(ColorConstants.BLACK, 1)).SetBorderTop(new SolidBorder(ColorConstants.BLACK, 1));
            _table.AddHeaderCell(_cell.AddStyle(styleCell));
            _cell = new Cell().Add(new Paragraph("Total")).SetBorder(Border.NO_BORDER).SetBorderBottom(new SolidBorder(ColorConstants.BLACK, 1)).SetBorderTop(new SolidBorder(ColorConstants.BLACK, 1));
            _table.AddHeaderCell(_cell.AddStyle(styleCell));

            Customer          customer = (Customer)this.Session["user"];
            List <OrderBooks> books    = BussinessManager.getOrderBooks(token, customer.customerid);

            int    x     = 0;
            double total = 0;

            foreach (OrderBooks book in books)
            {
                x++;
                _cell = new Cell().Add(new Paragraph(x.ToString())).SetBorder(Border.NO_BORDER);
                _table.AddCell(_cell);
                _cell = new Cell().Add(new Paragraph(book.book_name)).SetBorder(Border.NO_BORDER);
                _table.AddCell(_cell);
                _cell = new Cell().Add(new Paragraph(book.quantity.ToString()).SetTextAlignment(TextAlignment.RIGHT)).SetBorder(Border.NO_BORDER);
                _table.AddCell(_cell);
                _cell = new Cell().Add(new Paragraph("₹ " + book.price.ToString()).SetTextAlignment(TextAlignment.RIGHT)).SetBorder(Border.NO_BORDER);
                _table.AddCell(_cell);
                _cell = new Cell().Add(new Paragraph("₹ " + (book.price * book.quantity)).SetTextAlignment(TextAlignment.RIGHT)).SetBorder(Border.NO_BORDER);
                _table.AddCell(_cell);
                total += book.price * book.quantity;
            }

            doc.Add(_table);

            _table = new Table(1).UseAllAvailableWidth();
            _table.AddCell(new Cell().Add(new Paragraph("Total: " + total)).SetTextAlignment(TextAlignment.RIGHT).SetBorder(Border.NO_BORDER).SetBorderBottom(new SolidBorder(ColorConstants.BLACK, 1)).SetBorderTop(new SolidBorder(ColorConstants.BLACK, 1)));

            doc.Add(_table);

            doc.Close();

            byte[] byteStream = ms.ToArray();
            ms = new MemoryStream();
            ms.Write(byteStream, 0, byteStream.Length);
            ms.Position = 0;

            return(new FileStreamResult(ms, "application/pdf"));
        }
Ejemplo n.º 4
0
        public virtual void CreatePdf(String dest)
        {
            //Initialize PDF document
            PdfDocument pdf = new PdfDocument(new PdfWriter(dest, new WriterProperties().SetFullCompressionMode(true))
                                              );

            iText.Layout.Element.Image img = new Image(ImageDataFactory.Create(IMG));
            IEventHandler handler          = new C07E13_Compressed.TransparentImage(img);

            pdf.AddEventHandler(PdfDocumentEvent.START_PAGE, handler);
            // Initialize document
            Document document = new Document(pdf);
            PdfFont  bold     = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);

            document.SetTextAlignment(TextAlignment.JUSTIFIED).SetHyphenation(new HyphenationConfig("en", "uk", 3, 3));
            StreamReader sr = File.OpenText(SRC);
            String       name;
            String       line;
            Paragraph    p;
            bool         title   = true;
            int          counter = 0;
            IList <Util.Pair <String, Util.Pair <String, int> > > toc = new List <Util.Pair
                                                                                  <String, Util.Pair <String, int> > >();

            while ((line = sr.ReadLine()) != null)
            {
                p = new Paragraph(line);
                p.SetKeepTogether(true);
                if (title)
                {
                    name = String.Format("title{0:00}", counter++);
                    p.SetFont(bold).SetFontSize(12).SetKeepWithNext(true).SetDestination(name);
                    title = false;
                    document.Add(p);
                    toc.Add(new Util.Pair <string, Util.Pair <string, int> >(name, new Util.Pair <string, int>(line, pdf.GetNumberOfPages())));
                }
                else
                {
                    p.SetFirstLineIndent(36);
                    if (String.IsNullOrEmpty(line))
                    {
                        p.SetMarginBottom(12);
                        title = true;
                    }
                    else
                    {
                        p.SetMarginBottom(0);
                    }
                    document.Add(p);
                }
            }
            pdf.RemoveEventHandler(PdfDocumentEvent.START_PAGE, handler);
            document.Add(new AreaBreak(AreaBreakType.NEXT_PAGE));
            p = new Paragraph().SetFont(bold).Add("Table of Contents").SetDestination("toc");
            document.Add(p);
            toc.RemoveAt(0);
            IList <TabStop> tabstops = new List <TabStop>();

            tabstops.Add(new TabStop(580, TabAlignment.RIGHT, new DottedLine()));
            foreach (Util.Pair <String, Util.Pair <String, int> > entry in toc)
            {
                Util.Pair <String, int> text = entry.Value;
                p = new Paragraph().AddTabStops(tabstops).Add(text.Key).Add(new Tab()).Add(text.Value.ToString()).SetAction
                        (PdfAction.CreateGoTo(entry.Key));
                document.Add(p);
            }
            //Close document
            document.Close();
        }
        private void SaveAsPdf(Dictionary <string, List <CardHolderReportInfo> > data, string heading)
        {
            Cursor currentCursor = Cursor.Current;

            try
            {
                Cursor.Current = Cursors.WaitCursor;
                if (data != null)
                {
                    using (PdfWriter pdfWriter = new PdfWriter(this.saveFileDialog1.FileName))
                    {
                        using (PdfDocument pdfDocument = new PdfDocument(pdfWriter))
                        {
                            using (Document doc = new Document(pdfDocument))
                            {
                                doc.SetFont(PdfFontFactory.CreateFont("Fonts/SEGOEUIL.TTF"));
                                string headerLeftText  = "Alarmed List Report";
                                string headerRightText = string.Empty;
                                string footerLeftText  = "This is computer generated report.";
                                string footerRightText = "Report generated on: " + DateTime.Now.ToString();

                                pdfDocument.AddEventHandler(PdfDocumentEvent.START_PAGE, new PdfHeaderAndFooter(doc, true, headerLeftText, headerRightText));
                                pdfDocument.AddEventHandler(PdfDocumentEvent.END_PAGE, new PdfHeaderAndFooter(doc, false, footerLeftText, footerRightText));

                                //pdfDocument.SetDefaultPageSize(new iText.Kernel.Geom.PageSize(1000F, 1000F));
                                //Table table = new Table((new List<float>() { 100F, 100F, 100F, 200F, 70F,70F,100F, 100F, 100F, 70F, 200F, 100F, 70F, 60F }).ToArray());
                                pdfDocument.SetDefaultPageSize(new iText.Kernel.Geom.PageSize(1080F, 842F));
                                Table table = new Table((new List <float>()
                                {
                                    90F, 140F, 250F, 120F, 240F, 120F
                                }).ToArray());

                                table.SetWidth(980F);
                                table.SetFixedLayout();

                                //Table table = new Table((new List<float>() { 8F, 100F, 150F, 225F, 60F, 40F, 100F, 125F, 150F }).ToArray());

                                this.AddMainHeading(table, heading);

                                this.AddNewEmptyRow(table);
                                //this.AddNewEmptyRow(table);

                                //Sections and Data


                                foreach (KeyValuePair <string, List <CardHolderReportInfo> > category in data)
                                {
                                    if (category.Value == null)
                                    {
                                        continue;
                                    }

                                    //Cadre
                                    this.AddCategoryRow(table, category.Key);

                                    //Data
                                    //this.AddNewEmptyRow(table, false);

                                    this.AddTableHeaderRow(table);

                                    for (int i = 0; i < category.Value.Count; i++)
                                    {
                                        CardHolderReportInfo chl = category.Value[i];
                                        this.AddTableDataRow(table, chl, i % 2 == 0);
                                    }

                                    this.AddNewEmptyRow(table);
                                }



                                doc.Add(table);

                                doc.Close();
                            }
                        }

                        System.Diagnostics.Process.Start(this.saveFileDialog1.FileName);
                    }
                }
                Cursor.Current = currentCursor;
            }
            catch (Exception exp)
            {
                Cursor.Current = currentCursor;
                if (exp.HResult == -2147024864)
                {
                    MessageBox.Show(this, "\"" + this.saveFileDialog1.FileName + "\" is already is use.\n\nPlease close it and generate report again.");
                }
                else
                if (exp.HResult == -2147024891)
                {
                    MessageBox.Show(this, "You did not have rights to save file on selected location.\n\nPlease run as administrator.");
                }
                else
                {
                    MessageBox.Show(this, exp.Message);
                }
            }
        }
Ejemplo n.º 6
0
        public IActionResult Create(string pdfHtmlString, string saveName = null)
        {
            #region Parameters
            // Global Config
            string fontFamily = Configuration["PdfConfig:GlobalConfig:FontFamily"];
            // Path Config
            string descPath = Configuration["PdfConfig:PathConfig:DescPath"];
            string logPath  = Configuration["PdfConfig:PathConfig:LogPath"];
            // MetaData Config
            string title    = Configuration["PdfConfig:MetaData:Title"];
            string author   = Configuration["PdfConfig:MetaData:Author"];
            string creator  = Configuration["PdfConfig:MetaData:Creator"];
            string keywords = Configuration["PdfConfig:MetaData:Keywords"];
            string subject  = Configuration["PdfConfig:MetaData:Subject"];
            // Header Config
            string headerText           = Configuration["PdfConfig:Header:Text"];
            float  headerFontSize       = Convert.ToSingle(Configuration["PdfConfig:Header:FontSize"]);
            string headerFontColor      = Configuration["PdfConfig:Header:FontColor"];
            string headerImageSource    = Configuration["PdfConfig:Header:Image:Source"];
            float  headerImageWidth     = Convert.ToSingle(Configuration["PdfConfig:Header:Image:Width"]);
            float  headerImagePositionX = Convert.ToSingle(Configuration["PdfConfig:Header:Image:Position:Left"]);
            float  headerImagePositionY = Convert.ToSingle(Configuration["PdfConfig:Header:Image:Position:Top"]);
            // Footer Config
            string footerText           = Configuration["PdfConfig:Footer:Text"];
            double footerFontSize       = Convert.ToDouble(Configuration["PdfConfig:Footer:FontSize"]);
            string footerFontColor      = Configuration["PdfConfig:Footer:FontColor"];
            string footerImageSource    = Configuration["PdfConfig:Footer:Image:Source"];
            float  footerImageWidth     = Convert.ToSingle(Configuration["PdfConfig:Footer:Image:Width"]);
            float  footerImagePositionX = Convert.ToSingle(Configuration["PdfConfig:Footer:Image:Position:Left"]);
            float  footerImagePositionY = Convert.ToSingle(Configuration["PdfConfig:Footer:Image:Position:Top"]);
            #endregion

            #region Properties & Setting
            // Configure properties for converter | 配置转换器
            ConverterProperties properties = new ConverterProperties();
            // Resources path, store images/fonts for example | 资源路径, 存放如图片/字体等资源
            string resources = Host.WebRootPath + (osInfo.Platform == PlatformID.Unix ? "/src/font/" : "\\src\\font\\");
            // PDF saved path | 生成的PDF文件存放路径
            string desc = string.Empty;
            if (osInfo.Platform == PlatformID.Unix)
            {
                if (!Directory.Exists(descPath))
                {
                    Directory.CreateDirectory(descPath);
                }
                desc = descPath + (saveName ?? DateTime.Now.ToString("yyyyMMdd-hhmmss-ffff")) + ".pdf";
            }
            else
            {
                descPath = "D:\\Pdf\\";
                if (!Directory.Exists(descPath))
                {
                    Directory.CreateDirectory(descPath);
                }
                desc = descPath + (saveName ?? DateTime.Now.ToString("yyyyMMdd-hhmmss-ffff")) + ".pdf";
            }

            FontProvider fp = new FontProvider();
            // Add Standard fonts libs without chinese support | 添加标准字体库
            // fp.AddStandardPdfFonts();
            fp.AddDirectory(resources);
            properties.SetFontProvider(fp);
            // Set base uri to resource folder | 设置基础uri
            properties.SetBaseUri(resources);

            PdfWriter   writer = new PdfWriter(desc);
            PdfDocument pdfDoc = new PdfDocument(writer);
            // Set PageSize | 设置页面大小
            pdfDoc.SetDefaultPageSize(PageSize.A4);
            // Set Encoding | 设置文本编码方式
            pdfDoc.GetCatalog().SetLang(new PdfString("UTF-8"));

            //Set the document to be tagged | 展示文档标签树
            pdfDoc.SetTagged();
            pdfDoc.GetCatalog().SetViewerPreferences(new PdfViewerPreferences().SetDisplayDocTitle(true));

            //https://developers.itextpdf.com/content/itext-7-examples/converting-html-pdf/pdfhtml-header-and-footer-example
            // create pdf font using custom resources | 自定义字体
            PdfFont sourcehansanscn = PdfFontFactory.CreateFont(resources + fontFamily, PdfEncodings.IDENTITY_H);

            Dictionary <string, object> header = new Dictionary <string, object>()
            {
                { "text", headerText },
                { "fontSize", headerFontSize },
                { "fontColor", headerFontColor },
                { "source", Host.WebRootPath + headerImageSource },
                { "width", headerImageWidth },
                { "left", headerImagePositionX },
                { "top", headerImagePositionY }
            };
            Dictionary <string, object> footer = new Dictionary <string, object>()
            {
                { "text", footerText },
                { "fontSize", footerFontSize },
                { "fontColor", footerFontColor },
                { "source", Host.WebRootPath + footerImageSource },
                { "width", footerImageWidth },
                { "left", footerImagePositionX },
                { "top", footerImagePositionY }
            };
            // Header handler | 页头处理
            PdfHeader headerHandler = new PdfHeader(header, sourcehansanscn);
            // Footer handler | 页脚处理
            PdfFooter footerHandler = new PdfFooter(footer, sourcehansanscn);

            // Assign event-handlers
            pdfDoc.AddEventHandler(PdfDocumentEvent.START_PAGE, headerHandler);
            pdfDoc.AddEventHandler(PdfDocumentEvent.END_PAGE, footerHandler);

            // Setup custom tagworker factory for better tagging of headers | 设置标签处理器
            DefaultTagWorkerFactory tagWorkerFactory = new DefaultTagWorkerFactory();
            properties.SetTagWorkerFactory(tagWorkerFactory);

            // Setup default outline(bookmark) handler | 设置默认大纲(书签)处理器
            // We used the createStandardHandler() method to create a standard handler.
            // This means that pdfHTML will look for <h1>, <h2>, <h3>, <h4>, <h5>, and <h6>.
            // The bookmarks will be created based on the hierarchy of those tags in the HTML file.
            // To enable other tags, read the folllowing article for more details.
            // https://developers.itextpdf.com/content/itext-7-converting-html-pdf-pdfhtml/chapter-4-creating-reports-using-pdfhtml
            OutlineHandler outlineHandler = OutlineHandler.CreateStandardHandler();
            properties.SetOutlineHandler(outlineHandler);

            // Bookmark | 书签
            // https://developers.itextpdf.com/content/itext-7-examples/itext-7-bookmarks-tocs/toc-first-page
            // https://developers.itextpdf.com/content/best-itext-questions-stackoverview/actions-and-annotations/itext7-how-create-hierarchical-bookmarks
            // https://developers.itextpdf.com/content/itext-7-building-blocks/chapter-6-creating-actions-destinations-and-bookmarks
            // https://developers.itextpdf.com/examples/actions-and-annotations/clone-named-destinations
            // PdfOutline outline = null;
            // outline = CreateOutline(outline, pdfDoc, "bookmark", "bookmark");

            // Meta tags | 文档属性标签
            PdfDocumentInfo pdfMetaData = pdfDoc.GetDocumentInfo();
            pdfMetaData.SetTitle(title);
            pdfMetaData.SetAuthor(author);
            pdfMetaData.AddCreationDate();
            pdfMetaData.GetProducer();
            pdfMetaData.SetCreator(creator);
            pdfMetaData.SetKeywords(keywords);
            pdfMetaData.SetSubject(subject);
            #endregion

            // Start convertion | 开始转化
            //Document document =
            //    HtmlConverter.ConvertToDocument(pdfHtmlString, pdfDoc, properties);

            IList <IElement>   elements        = HtmlConverter.ConvertToElements(pdfHtmlString, properties);
            Document           document        = new Document(pdfDoc);
            CJKSplitCharacters splitCharacters = new CJKSplitCharacters();
            document.SetFontProvider(fp);
            document.SetSplitCharacters(splitCharacters);
            document.SetProperty(Property.SPLIT_CHARACTERS, splitCharacters);
            foreach (IElement e in elements)
            {
                try
                {
                    document.Add((AreaBreak)e);
                }
                catch
                {
                    document.Add((IBlockElement)e);
                }
            }

            // Close and release document | 关闭并释放文档资源
            document.Close();

            return(Content("SUCCESS"));
        }
Ejemplo n.º 7
0
        public static void Write()
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter("D:\\output.pdf"));
            Document    doc    = new Document(pdfDoc, PageSize.A4);

            doc.SetMargins(CentimeterToPoint(10f), CentimeterToPoint(0.8f), CentimeterToPoint(1f), CentimeterToPoint(1.2f));
            PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.IDENTITY_H, false);

            PageXofY e = new PageXofY(pdfDoc);

            pdfDoc.AddEventHandler(PdfDocumentEvent.END_PAGE, e);



            Paragraph title = new Paragraph("设计成果交接单");

            title.SetWidth(CentimeterToPoint(19f));
            title.SetFont(font);
            title.SetTextAlignment(TextAlignment.CENTER);
            doc.Add(title);

            Paragraph p = new Paragraph();

            p.SetWidth(CentimeterToPoint(19f));
            p.SetFont(font);
            p.SetTextAlignment(TextAlignment.JUSTIFIED);

            Text t1 = new Text("编号:");

            t1.SetTextAlignment(TextAlignment.LEFT);

            TabStop tab = new TabStop(12f, TabAlignment.RIGHT);

            Text t2 = new Text("日期:" + DateTime.Now.ToString("yyyy年MM月dd日"));

            t2.SetTextAlignment(TextAlignment.RIGHT);

            p.Add(t1);
            p.AddTabStops(tab);
            p.Add(t2);
            doc.Add(p);

            Table table1 = new Table(new float[] {
                CentimeterToPoint(2.35f),
                CentimeterToPoint(4f),
                CentimeterToPoint(2.35f),
                CentimeterToPoint(4f),
                CentimeterToPoint(2.3f),
                CentimeterToPoint(4f)
            });

            table1.SetWidth(CentimeterToPoint(19f));

            Cell cell1 = new Cell();

            cell1.SetFont(font);
            cell1.Add(new Paragraph("项目名称"));
            table1.AddCell(cell1);

            Cell cell2 = new Cell(1, 5);

            cell2.SetFont(font);
            table1.AddCell(cell2);

            Cell cell3 = new Cell();

            cell3.SetFont(font);
            cell3.Add(new Paragraph("建设单位"));
            table1.AddCell(cell3);

            Cell cell4 = new Cell(1, 5);

            cell4.SetFont(font);
            table1.AddCell(cell4);

            Cell cell5 = new Cell();

            cell5.SetFont(font);
            cell5.Add(new Paragraph("设计部门"));
            table1.AddCell(cell5);

            Cell cel6 = new Cell();

            cel6.SetFont(font);
            table1.AddCell(cel6);

            Cell cel7 = new Cell();

            cel7.SetFont(font);
            cel7.Add(new Paragraph("设计号"));
            table1.AddCell(cel7);

            Cell cel8 = new Cell();

            cel8.SetFont(font);
            table1.AddCell(cel8);


            Cell cel9 = new Cell();

            cel9.SetFont(font);
            cel9.Add(new Paragraph("项目负责人"));
            table1.AddCell(cel9);

            Cell cel10 = new Cell();

            cel10.SetFont(font);
            table1.AddCell(cel10);

            Cell cell = new Cell(1, 6);

            cell.Add(new Paragraph("成果类别及数量"));
            cell.SetFont(font);
            cell.SetTextAlignment(TextAlignment.CENTER);
            table1.AddCell(cell);

            doc.Add(table1);

            Table table = new Table(new float[] {
                CentimeterToPoint(1.5f),
                CentimeterToPoint(4f),
                CentimeterToPoint(3f),
                CentimeterToPoint(1f),
                CentimeterToPoint(1f),
                CentimeterToPoint(1f),
                CentimeterToPoint(1f),
                CentimeterToPoint(1f),
                CentimeterToPoint(1.5f),
                CentimeterToPoint(4f)
            });

            table.SetWidth(CentimeterToPoint(19f));


            Cell seq = new Cell();

            seq.SetFont(font);
            seq.SetTextAlignment(TextAlignment.CENTER);
            seq.Add(new Paragraph("序号"));
            table.AddHeaderCell(seq);

            Cell name = new Cell();

            name.SetFont(font);
            name.SetTextAlignment(TextAlignment.CENTER);
            name.Add(new Paragraph("名称"));
            table.AddHeaderCell(name);

            Cell subject = new Cell();

            subject.SetFont(font);
            subject.SetTextAlignment(TextAlignment.CENTER);
            subject.Add(new Paragraph("专业"));
            table.AddHeaderCell(subject);

            Cell A0 = new Cell();

            A0.SetFont(font);
            A0.SetTextAlignment(TextAlignment.CENTER);
            A0.Add(new Paragraph("A0"));
            table.AddHeaderCell(A0);

            Cell A1 = new Cell();

            A1.SetFont(font);
            A1.SetTextAlignment(TextAlignment.CENTER);
            A1.Add(new Paragraph("A1"));
            table.AddHeaderCell(A1);

            Cell A2 = new Cell();

            A2.SetFont(font);
            A2.SetTextAlignment(TextAlignment.CENTER);
            A2.Add(new Paragraph("A2"));
            table.AddHeaderCell(A2);

            Cell A3 = new Cell();

            A3.SetFont(font);
            A3.SetTextAlignment(TextAlignment.CENTER);
            A3.Add(new Paragraph("A3"));
            table.AddHeaderCell(A3);

            Cell A4 = new Cell();

            A4.SetFont(font);
            A4.SetTextAlignment(TextAlignment.CENTER);
            A4.Add(new Paragraph("A4"));
            table.AddHeaderCell(A4);

            Cell Copies = new Cell();

            Copies.SetFont(font);
            Copies.SetTextAlignment(TextAlignment.CENTER);
            Copies.Add(new Paragraph("份数"));
            table.AddHeaderCell(Copies);

            Cell comments = new Cell();

            comments.SetFont(font);
            comments.SetTextAlignment(TextAlignment.CENTER);
            comments.Add(new Paragraph("备注"));
            table.AddHeaderCell(comments);


            for (int i = 1; i < 101; i++)
            {
                table.AddCell(i.ToString());
                table.AddCell(string.Empty);
                table.AddCell(string.Empty);
                table.AddCell(string.Empty);
                table.AddCell(string.Empty);
                table.AddCell(string.Empty);
                table.AddCell(string.Empty);
                table.AddCell(string.Empty);
                table.AddCell(string.Empty);
                table.AddCell(string.Empty);
            }
            doc.Add(table);

            e.WriteTotal(pdfDoc);


            doc.Close();

            //pdfDoc.GetWriter().GetOutputStream().
            //PrintQueue queue = LocalPrintServer.GetDefaultPrintQueue();
            //using (PrintSystemJobInfo job = queue.AddJob())
            //{
            //    using (Stream stream = job.JobStream)
            //    {
            //        stream.Write()
            //    }
            //}
        }
        protected void btnGenerarReporte_Click(object sender, EventArgs e)
        {
            MemoryStream ms = new MemoryStream();

            PdfWriter   pw  = new PdfWriter(ms);
            PdfDocument pdf = new PdfDocument(pw);
            Document    doc = new Document(pdf, PageSize.A4);

            doc.SetMargins(75, 35, 70, 35);
            string pathLogo = Server.MapPath("../Imagenes/Care Monitor.jpg");

            iText.Layout.Element.Image img = new iText.Layout.Element.Image(iText.IO.Image.ImageDataFactory.Create(pathLogo));

            pdf.AddEventHandler(PdfDocumentEvent.START_PAGE, new HeaderEventHandler(img));

            BE.Usuario usu = (BE.Usuario)Session["UsuarioEnSesion"];

            iText.Layout.Element.Table tabla = new iText.Layout.Element.Table(1).UseAllAvailableWidth();
            Cell cell = new Cell().Add(new Paragraph("Mediciones de " + usu.Nombre + " " + usu.Apellido).SetFontSize(14)
                                       .SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER)
                                       .SetBorder(Border.NO_BORDER));

            tabla.AddCell(cell);

            doc.Add(tabla);

            iText.Layout.Style styleCell = new iText.Layout.Style()
                                           .SetBackgroundColor(ColorConstants.LIGHT_GRAY)
                                           .SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER);

            iText.Layout.Element.Table _tabla = new iText.Layout.Element.Table(5).UseAllAvailableWidth();
            Cell _cell = new Cell().Add(new Paragraph("Fecha"));

            _tabla.AddHeaderCell(_cell.AddStyle(styleCell));
            _cell = new Cell().Add(new Paragraph("Tipo"));
            _tabla.AddHeaderCell(_cell.AddStyle(styleCell));
            _cell = new Cell().Add(new Paragraph("Valor"));
            _tabla.AddHeaderCell(_cell.AddStyle(styleCell));
            _cell = new Cell().Add(new Paragraph("Máximo"));
            _tabla.AddHeaderCell(_cell.AddStyle(styleCell));
            _cell = new Cell().Add(new Paragraph("Mínimo"));
            _tabla.AddHeaderCell(_cell.AddStyle(styleCell));



            foreach (BE.Medicion bit in ListaMediciones)
            {
                _cell = new Cell().Add(new Paragraph(bit.Fecha.ToString("g")));
                _tabla.AddCell(_cell);
                _cell = new Cell().Add(new Paragraph(bit.Tipo.Nombre));
                _tabla.AddCell(_cell);
                if (bit.Valor < bit.Tipo.MinimoMasculino || bit.Valor > bit.Tipo.MaximoMasculino)
                {
                    _cell = new Cell().Add(new Paragraph(bit.Valor.ToString()));
                    _tabla.AddCell(_cell.SetBackgroundColor(ColorConstants.RED));
                }
                else
                {
                    _cell = new Cell().Add(new Paragraph(bit.Valor.ToString()));
                    _tabla.AddCell(_cell);
                }

                _cell = new Cell().Add(new Paragraph(bit.Tipo.MaximoMasculino.ToString()));
                _tabla.AddCell(_cell);
                _cell = new Cell().Add(new Paragraph(bit.Tipo.MinimoMasculino.ToString()));
                _tabla.AddCell(_cell);
            }

            doc.Add(_tabla);

            doc.Close();

            byte[] bytesStream = ms.ToArray();
            ms = new MemoryStream();
            ms.Write(bytesStream, 0, bytesStream.Length);
            ms.Position = 0;

            Response.AddHeader("content-disposition", "inline;filename=Reporte.pdf");
            Response.ContentType = "application/octectstream";
            Response.BinaryWrite(bytesStream);
            Response.End();
        }
        protected void btnGenerarReporte2_Click(object sender, EventArgs e)
        {
            MemoryStream ms = new MemoryStream();

            PdfWriter   pw  = new PdfWriter(ms);
            PdfDocument pdf = new PdfDocument(pw);
            Document    doc = new Document(pdf, PageSize.A4);

            doc.SetMargins(75, 35, 70, 35);
            string pathLogo = Server.MapPath("../Imagenes/Care Monitor.jpg");

            iText.Layout.Element.Image img = new iText.Layout.Element.Image(iText.IO.Image.ImageDataFactory.Create(pathLogo));

            pdf.AddEventHandler(PdfDocumentEvent.START_PAGE, new HeaderEventHandler(img));


            iText.Layout.Element.Table tabla = new iText.Layout.Element.Table(1).UseAllAvailableWidth();
            Cell cell = new Cell().Add(new Paragraph("Servicios Cerrados").SetFontSize(14)
                                       .SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER)
                                       .SetBorder(Border.NO_BORDER));

            tabla.AddCell(cell);

            doc.Add(tabla);

            iText.Layout.Style styleCell = new iText.Layout.Style()
                                           .SetBackgroundColor(ColorConstants.LIGHT_GRAY)
                                           .SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER);

            iText.Layout.Element.Table _tabla = new iText.Layout.Element.Table(7).UseAllAvailableWidth();
            Cell _cell = new Cell().Add(new Paragraph("Usuario"));

            _tabla.AddHeaderCell(_cell.AddStyle(styleCell));
            _cell = new Cell().Add(new Paragraph("Nombre"));
            _tabla.AddHeaderCell(_cell.AddStyle(styleCell));
            _cell = new Cell().Add(new Paragraph("Fecha"));
            _tabla.AddHeaderCell(_cell.AddStyle(styleCell));
            _cell = new Cell().Add(new Paragraph("Fecha Cierre"));
            _tabla.AddHeaderCell(_cell.AddStyle(styleCell));
            _cell = new Cell().Add(new Paragraph("Dirección"));
            _tabla.AddHeaderCell(_cell.AddStyle(styleCell));
            _cell = new Cell().Add(new Paragraph("Tiempo Estimado"));
            _tabla.AddHeaderCell(_cell.AddStyle(styleCell));
            _cell = new Cell().Add(new Paragraph("Tiempo de Servicio"));
            _tabla.AddHeaderCell(_cell.AddStyle(styleCell));



            List <BE.Servicio_Cerrado> listaServicio = (List <BE.Servicio_Cerrado>)Session["ListaServiciosCerrados"];

            foreach (BE.Servicio_Cerrado bit in listaServicio)
            {
                _cell = new Cell().Add(new Paragraph(bit.Usuario.Nombre + " " + bit.Usuario.Apellido));
                _tabla.AddCell(_cell);
                _cell = new Cell().Add(new Paragraph(bit.TipoServicio.Nombre));
                _tabla.AddCell(_cell);
                _cell = new Cell().Add(new Paragraph(bit.FechaServicio.ToShortDateString()));
                _tabla.AddCell(_cell);
                _cell = new Cell().Add(new Paragraph(bit.FechaCierre.ToShortDateString()));
                _tabla.AddCell(_cell);
                _cell = new Cell().Add(new Paragraph(bit.Usuario.Direccion));
                _tabla.AddCell(_cell);
                _cell = new Cell().Add(new Paragraph(bit.TipoServicio.TiempoMedio.ToString()));
                _tabla.AddCell(_cell);

                if (bit.TiempoServicio > bit.TipoServicio.TiempoMedio)
                {
                    _cell = new Cell().Add(new Paragraph(bit.TiempoServicio.ToString()));
                    _tabla.AddCell(_cell.SetBackgroundColor(ColorConstants.RED));
                }
                else
                {
                    _cell = new Cell().Add(new Paragraph(bit.TiempoServicio.ToString()));
                    _tabla.AddCell(_cell);
                }
            }

            doc.Add(_tabla);

            doc.Close();

            byte[] bytesStream = ms.ToArray();
            ms = new MemoryStream();
            ms.Write(bytesStream, 0, bytesStream.Length);
            ms.Position = 0;

            Response.AddHeader("content-disposition", "inline;filename=Reporte.pdf");
            Response.ContentType = "application/octectstream";
            Response.BinaryWrite(bytesStream);
            Response.End();
        }
Ejemplo n.º 10
0
        public static void MakePDF(Project project, string pdfLocation)
        {
            if (project == null)
            {
                MessageBox.Show("Obiekt projektu jest wartością NULL.", "Błąd", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            if (string.IsNullOrEmpty(pdfLocation))
            {
                MessageBox.Show("Ciąg pliku wyjściowego jest błędny", "Błąd", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            PdfProgress progressWindow = new PdfProgress();

            progressWindow.Show();

            using (var writer = new PdfWriter(File.Open(pdfLocation, FileMode.OpenOrCreate)))
            {
                using (var pdf = new PdfDocument(writer))
                {
                    pdf.AddEventHandler(PdfDocumentEvent.END_PAGE, new HeaderHendler());
                    pdf.AddEventHandler(PdfDocumentEvent.END_PAGE, new FooterHendler());
                    using (var document = new Document(pdf))
                    {
                        document.SetTopMargin(65);
                        document.SetBottomMargin(30);
                        var font     = PdfFontFactory.CreateFont(StandardFonts.HELVETICA, PdfEncodings.CP1250, true);
                        var h1Font   = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD, PdfEncodings.CP1250, true);
                        var boldFont = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD, PdfEncodings.CP1250, true);

                        document.SetFontSize(8);

                        document.SetTextAlignment(iText.Layout.Properties.TextAlignment.RIGHT);
                        document.Add(new Paragraph($"Data dokumentu {project.DocumentDate.ToShortDateString()}")
                                     .SetFont(font));

                        document.SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER);
                        document.Add(new Paragraph($"Protokół nr {project.ProtocolNumber}")
                                     .SetFont(h1Font)
                                     .SetFontSize(12));

                        document.SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER);
                        document.Add(new Paragraph("z pomiaru bilansu mocy lini światłowodowej")
                                     .SetFont(boldFont));

                        document.SetTextAlignment(iText.Layout.Properties.TextAlignment.LEFT);
                        document.Add(new Paragraph("1. Zleceniodawca")
                                     .SetFont(boldFont)
                                     .Add(new Text('\n' + project.CustomerInfo ?? " ")
                                          .SetFont(font)));

                        document.Add(new Paragraph("2. Obiekt")
                                     .SetFont(boldFont)
                                     .Add(new Text('\n' + project.ObjectInfo ?? " ")
                                          .SetFont(font)));

                        document.Add(new Paragraph($"3. Data badania: {project.MesurementDate?.ToShortDateString() ?? " "}")
                                     .SetFont(boldFont));

                        document.Add(new Paragraph("4. Przyrządy pomiarowe")
                                     .SetFont(boldFont)
                                     .Add(new Text($"\n1. {project.GaugeInfo ?? " "}\n2. {project.LightSourceInfo ?? " "}")
                                          .SetFont(font)));

                        document.Add(new Paragraph("5. Wyniki pomiarów tłumienności")
                                     .SetFont(boldFont));

                        progressWindow.SetProgress(30);

                        Table mesurements = new Table(new float[] { 1, 4, 4, 2, 4, 3, 3, 3, 3, 4 });
                        mesurements.SetFontSize(7);
                        mesurements.SetWidth(UnitValue.CreatePercentValue(100));
                        mesurements.AddHeaderCell(new Cell().Add(new Paragraph("Lp.").SetFont(boldFont).SetTextAlignment(TextAlignment.CENTER)).SetVerticalAlignment(VerticalAlignment.MIDDLE));
                        mesurements.AddHeaderCell(new Cell().Add(new Paragraph("Źródło").SetFont(boldFont).SetTextAlignment(TextAlignment.CENTER)).SetVerticalAlignment(VerticalAlignment.MIDDLE));
                        mesurements.AddHeaderCell(new Cell().Add(new Paragraph("Koniec").SetFont(boldFont).SetTextAlignment(TextAlignment.CENTER)).SetVerticalAlignment(VerticalAlignment.MIDDLE));
                        mesurements.AddHeaderCell(new Cell().Add(new Paragraph("Numer włókna").SetFont(boldFont).SetTextAlignment(TextAlignment.CENTER)).SetVerticalAlignment(VerticalAlignment.MIDDLE));
                        mesurements.AddHeaderCell(new Cell().Add(new Paragraph("Typ włókna").SetFont(boldFont).SetTextAlignment(TextAlignment.CENTER)).SetVerticalAlignment(VerticalAlignment.MIDDLE));
                        mesurements.AddHeaderCell(new Cell().Add(new Paragraph("Długość [km]").SetFont(boldFont).SetTextAlignment(TextAlignment.CENTER)).SetVerticalAlignment(VerticalAlignment.MIDDLE));
                        mesurements.AddHeaderCell(new Cell().Add(new Paragraph("Ilość spawów [szt]").SetFont(boldFont).SetTextAlignment(TextAlignment.CENTER)).SetVerticalAlignment(VerticalAlignment.MIDDLE));
                        mesurements.AddHeaderCell(new Cell().Add(new Paragraph("Rmax [dB]").SetFont(boldFont).SetTextAlignment(TextAlignment.CENTER)).SetVerticalAlignment(VerticalAlignment.MIDDLE));
                        mesurements.AddHeaderCell(new Cell().Add(new Paragraph("R [dB]").SetFont(boldFont).SetTextAlignment(TextAlignment.CENTER)).SetVerticalAlignment(VerticalAlignment.MIDDLE));
                        mesurements.AddHeaderCell(new Cell().Add(new Paragraph("Ocena pomiaru").SetFont(boldFont).SetTextAlignment(TextAlignment.CENTER)).SetVerticalAlignment(VerticalAlignment.MIDDLE));

                        progressWindow.SetProgress(40);

                        foreach (var mesure in project.Mesurements)
                        {
                            mesurements.AddCell(new Cell().Add(new Paragraph(mesure.Number?.ToString() ?? " ").SetFont(font).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE)));
                            if (mesure.Number == null)
                            {
                                mesurements.AddCell(new Cell(1, 9).Add(new Paragraph(mesure.Source ?? " ").SetFont(boldFont).SetTextAlignment(TextAlignment.LEFT).SetVerticalAlignment(VerticalAlignment.MIDDLE)));
                                continue;
                            }
                            mesurements.AddCell(new Cell().Add(new Paragraph(mesure.Source ?? " ").SetFont(font).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE)));
                            mesurements.AddCell(new Cell().Add(new Paragraph(mesure.Destination ?? " ").SetFont(font).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE)));
                            mesurements.AddCell(new Cell().Add(new Paragraph(mesure.NumberOfWire?.ToString() ?? " ").SetFont(font).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE)));
                            mesurements.AddCell(new Cell().Add(new Paragraph(mesure.Type?.Name?.ToString() ?? " ").SetFont(font).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE)));
                            mesurements.AddCell(new Cell().Add(new Paragraph(mesure.Distance?.ToString() ?? " ").SetFont(font).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE)));
                            mesurements.AddCell(new Cell().Add(new Paragraph(mesure.CountOfWeld?.ToString() ?? " ").SetFont(font).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE)));
                            mesurements.AddCell(new Cell().Add(new Paragraph(mesure.MaxAttenuation?.ToString() ?? " ").SetFont(font).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE)));
                            mesurements.AddCell(new Cell().Add(new Paragraph(mesure.RealAttenuation?.ToString() ?? " ").SetFont(font).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE)));
                            mesurements.AddCell(new Cell().Add(new Paragraph(mesure.PropperValue == true ? "Pozytywna" : "Negatywna" ?? " ").SetFont(font).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE)));
                        }
                        document.Add(mesurements);
                        document.Add(new Paragraph("Oznaczenia: ").SetFont(boldFont).SetFontSize(5).Add(new Text("Lp - liczba porządkowa, R - tłumienność zmierzona, Rmax - obliczona tłumienność maksymalna").SetFont(font)));

                        progressWindow.SetProgress(80);

                        document.Add(new Paragraph("6. Uwagi i wnioski\n")
                                     .SetFont(boldFont)
                                     .Add(new Text($"{project.Conclusions ?? " "}")
                                          .SetFont(font)));

                        document.Add(new Paragraph("7. Orzeczenie\n")
                                     .SetFont(boldFont)
                                     .Add(new Text($"{project.Opinion ?? " "}")
                                          .SetFont(font)));

                        document.Add(new Paragraph("8. Wykowanca pomiarów")
                                     .SetFont(boldFont));

                        progressWindow.SetProgress(90);

                        Table tab = new Table(2);
                        tab.SetBorder(Border.NO_BORDER);
                        tab.SetWidth(UnitValue.CreatePercentValue(100));
                        tab.AddHeaderCell(new Cell().Add(new Paragraph("Wykonał:").SetFont(font)).SetBorder(Border.NO_BORDER));
                        tab.AddHeaderCell(new Cell().Add(new Paragraph("Sprawdził:").SetFont(font)).SetBorder(Border.NO_BORDER));
                        tab.AddCell(new Cell().Add(new Paragraph(project.DoingPerson ?? " ").SetFont(font)).SetBorder(Border.NO_BORDER));
                        tab.AddCell(new Cell().Add(new Paragraph(project.VeryfingPerson ?? " ").SetFont(font)).SetBorder(Border.NO_BORDER));
                        document.Add(tab);

                        document.Close();
                        progressWindow.SetProgress(100);
                    }
                }
            }
            progressWindow.Close();
            MessageBox.Show("Plik został utworzony!", "Zakończone", MessageBoxButton.OK, MessageBoxImage.Information);
        }
Ejemplo n.º 11
0
        public virtual void createPdf(String dest, Image logo)
        {
            PdfWriter   writer   = new PdfWriter(dest);
            PdfDocument pdf      = new PdfDocument(writer);
            PdfFont     font     = PdfFontFactory.CreateFont(FONT, "Cp1250", true);
            Document    document = new Document(pdf);

            pdf.AddEventHandler(PdfDocumentEvent.END_PAGE, new TextFooterEventHandler(document));

            #region RentalHeaderTable

            Table rentalHeaderTable = new Table(UnitValue.CreatePercentArray(2))
                                      .UseAllAvailableWidth();

            Cell logoImage = new Cell()
                             .Add(logo)
                             .SetVerticalAlignment(VerticalAlignment.MIDDLE)
                             .SetBorder(Border.NO_BORDER);

            Cell transactionData = new Cell()
                                   .Add(new Paragraph("Data wystawienie : " + DateTime.Now).SetTextAlignment(TextAlignment.RIGHT).SetFontSize(10))
                                   .Add(new Paragraph("Data transakcji : " + _transaction.TransactionDate).SetTextAlignment(TextAlignment.RIGHT).SetFontSize(10))
                                   .Add(new Paragraph("Miejsce wystawienia : " + _settings.City).SetTextAlignment(TextAlignment.RIGHT).SetFontSize(10))
                                   .SetVerticalAlignment(VerticalAlignment.MIDDLE)
                                   .SetBorder(Border.NO_BORDER);

            rentalHeaderTable.AddCell(logoImage);
            rentalHeaderTable.AddCell(transactionData);

            #endregion

            #region UsersDataHeaderTable

            Table usersDataHeaderTable = new Table(UnitValue.CreatePercentArray(2))
                                         .UseAllAvailableWidth();

            Cell OwnerHeader = new Cell()
                               .Add(new Paragraph("Wypożyczalnia :"))
                               .SetTextAlignment(TextAlignment.LEFT)
                               .SetBorder(Border.NO_BORDER);


            Cell CustomerHeader = new Cell()
                                  .Add(new Paragraph("Wypożyczający :"))
                                  .SetTextAlignment(TextAlignment.LEFT)
                                  .SetBorder(Border.NO_BORDER);

            usersDataHeaderTable.AddCell(OwnerHeader);
            usersDataHeaderTable.AddCell(CustomerHeader);

            #endregion

            #region UserDataHeaderTable

            Table userDataHeaderTable = new Table(UnitValue.CreatePercentArray(2))
                                        .UseAllAvailableWidth()
                                        .SetBorderCollapse(BorderCollapsePropertyValue.SEPARATE)
                                        .SetHorizontalBorderSpacing(10);

            Cell OwnerData = new Cell()
                             .SetTextAlignment(TextAlignment.LEFT)
                             .SetPaddingLeft(5)
                             .SetBorderRadius(new BorderRadius(4))
                             .Add(new Paragraph(_settings.CompanyName ?? ""))
                             .Add(new Paragraph(_settings.PostalCode ?? "" + " " + _settings.City ?? ""))
                             .Add(new Paragraph(_settings.Address ?? ""))
                             .Add(new Paragraph("Email : " + _settings.Email ?? ""))
                             .Add(new Paragraph("Telefon : " + _settings.Phone ?? ""));

            Cell CustomerData = new Cell()
                                .SetTextAlignment(TextAlignment.LEFT)
                                .SetPaddingLeft(5)
                                .SetBorderRadius(new BorderRadius(4))
                                .Add(new Paragraph(_transaction.Customer.Company?.CompanyName ?? ""))
                                .Add(new Paragraph(_transaction.Customer.FullName ?? ""))
                                .Add(new Paragraph(_transaction.Customer.Company?.PostCode ?? "" + " " + _transaction.Customer.Company?.City ?? ""))
                                .Add(new Paragraph("Email : " + _transaction.Customer.Company?.Address ?? ""))
                                .Add(new Paragraph("Telefon : " + _transaction.Customer.Phone ?? ""));

            Paragraph transactionNumber = new Paragraph(_transaction.TransactionType == TransactionType.Rent ? "Wypozyczenie nr : " + _transaction.TransactionNumber.ToString() : "Zwrot nr : " + _transaction.TransactionNumber.ToString());
            transactionNumber
            .SetFontSize(20)
            .SetBold()
            .SetMarginTop(10)
            .SetTextAlignment(TextAlignment.CENTER);

            userDataHeaderTable.SetHorizontalAlignment(HorizontalAlignment.CENTER);
            userDataHeaderTable.AddCell(OwnerData);
            userDataHeaderTable.AddCell(CustomerData);

            #endregion

            #region TransactionToolsTable

            float[] columnWidths          = { 1, 4, 4, 4, 2 };
            Table   transactionToolsTable = new Table(UnitValue.CreatePercentArray(columnWidths)).UseAllAvailableWidth()
                                            .SetMarginTop(10);

            transactionToolsTable.AddHeaderCell("Lp.");
            transactionToolsTable.AddHeaderCell("Nazwa");
            transactionToolsTable.AddHeaderCell("Producent");
            transactionToolsTable.AddHeaderCell("SN");
            transactionToolsTable.AddHeaderCell("Cena r-d");
            transactionToolsTable.GetHeader()
            .SetBackgroundColor(DeviceGray.GRAY)
            .SetFontColor(DeviceRgb.WHITE)
            .SetBold();

            for (int i = 0; i < _tools.Count; i++)
            {
                transactionToolsTable.AddCell((i + 1) + ".");
                transactionToolsTable.AddCell(_tools[i].Name ?? "");
                if (_tools[i].Producer != null)
                {
                    transactionToolsTable.AddCell(_tools[i].Producer.CompanyName ?? "");
                }
                else
                {
                    transactionToolsTable.AddCell(new Paragraph(""));
                }
                transactionToolsTable.AddCell(_tools[i].Sn ?? "");
                transactionToolsTable.AddCell(_tools[i].RentalPrice + " zł");
            }

            #endregion

            #region RentalPrice

            Table value = new Table(1)
                          .SetHorizontalAlignment(HorizontalAlignment.RIGHT);
            Cell cell = new Cell()
                        .SetBorder(Border.NO_BORDER);
            Paragraph sum = new Paragraph();

            if (_transaction.TransactionType == TransactionType.Return)
            {
                foreach (var tool in _tools)
                {
                    var price  = _db.GetPriceForRent(tool.ToolId, _transaction.TransactionDate);
                    var amount = (price == 0 || tool.RentalPrice == 0) ? 0 : price / tool.RentalPrice;
                    cell.Add(new Paragraph(tool.Name + " dni: " + amount + " x cena: " + _transaction.PriceForRent + " = wartość: " + price + " zł").SetBorder(Border.NO_BORDER))
                    .SetTextAlignment(TextAlignment.RIGHT)
                    .SetBorder(Border.NO_BORDER)
                    .SetFontSize(10);
                    _suma += price;
                    value.AddCell(cell);
                }

                sum.Add("RAZEM : " + _suma + " zł")
                .SetFontSize(15)
                .SetBold()
                .SetTextAlignment(TextAlignment.RIGHT);
            }

            #endregion

            #region Condidions

            Paragraph conditionsHeader = new Paragraph()
                                         .Add("Warunki wypożyczenie :")
                                         .SetMarginTop(20)
                                         .SetBold();

            Paragraph conditions = new Paragraph()
                                   .Add(_settings.Conditions)
                                   .SetMarginTop(10)
                                   .SetItalic();

            #endregion

            #region Signature

            Table signatureTable = new Table(UnitValue.CreatePercentArray(2)).UseAllAvailableWidth();
            signatureTable.SetMarginTop(50);
            signatureTable.SetBorder(Border.NO_BORDER);

            Cell User = new Cell()
                        .Add(new Paragraph(_transaction.AppUser.FullName ?? ""))
                        .Add(new Paragraph("............................................................"))
                        .Add(new Paragraph("data i podpis wydającego"))
                        .SetTextAlignment(TextAlignment.CENTER)
                        .SetFontSize(10)
                        .SetBorder(Border.NO_BORDER);

            Cell Customer = new Cell()
                            .Add(new Paragraph(_transaction.Customer.FullName ?? ""))
                            .Add(new Paragraph("............................................................"))
                            .Add(new Paragraph("data i podpis wypożyczającego"))
                            .SetTextAlignment(TextAlignment.CENTER)
                            .SetFontSize(10)
                            .SetBorder(Border.NO_BORDER);

            signatureTable.AddCell(User);
            signatureTable.AddCell(Customer);

            #endregion

            #region CreateDocument

            document.SetFont(font);
            document.Add(rentalHeaderTable);
            document.Add(usersDataHeaderTable);
            document.Add(userDataHeaderTable);
            document.Add(transactionNumber);
            document.Add(transactionToolsTable);
            document.Add(value);
            document.Add(sum);
            document.Add(conditionsHeader);
            document.Add(conditions);
            document.Add(signatureTable);
            document.Close();

            #endregion
        }
Ejemplo n.º 12
0
        private void button1_Click_1(object sender, EventArgs e)
        {
            Style boldStyle     = new Style().SetTextAlignment(TextAlignment.CENTER).SetFontSize(8).SetBold();
            Style headerMusculo = new Style().SetTextAlignment(TextAlignment.LEFT).SetBold();

            Style styleDatos = new Style().SetFontSize(7);



            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Filter = "Pdf Files|*.pdf";
            saveFileDialog1.Title  = "Save an Image File";
            saveFileDialog1.ShowDialog();

            string Imagenpath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

            Image imgEjercicio = new Image(ImageDataFactory.Create(Imagenpath + "\\Resources\\Ejercicios_Fotos\\Dominadas.jpg"));
            Image logo         = new Image(ImageDataFactory.Create(Imagenpath + "\\Resources\\Icons\\OnixLogo.png"));

            string path = saveFileDialog1.FileName;


            PdfWriter   pw          = new PdfWriter(path);
            PdfDocument pdfDocument = new PdfDocument(pw);

            pdfDocument.AddEventHandler(PdfDocumentEvent.START_PAGE, new HeaderEventHandler(logo));
            Document doc = new Document(pdfDocument, PageSize.A4);

            doc.SetMargins(55, 30, 15, 30);

            Table table = new Table(1).UseAllAvailableWidth(); //USAR TODO EL ANCHO DE LA HOJA

            table.AddCell(new Cell().Add(new Paragraph("Nom:").SetFontSize(8))
                          .SetTextAlignment(TextAlignment.LEFT)
                          .SetBold().SetBorder(Border.NO_BORDER));

            doc.Add(table);


            Table _table = new Table(7).UseAllAvailableWidth();


            Cell _cell = new Cell().Add(new Paragraph("Lorena Vicente").AddStyle(styleDatos)).SetMaxHeight(20f).SetVerticalAlignment(VerticalAlignment.MIDDLE);

            _table.AddCell(_cell);

            _cell = new Cell().Add(new Paragraph("Data inici rutina")).SetBorder(Border.NO_BORDER).SetVerticalAlignment(VerticalAlignment.MIDDLE);
            _table.AddCell(_cell.AddStyle(boldStyle));

            _cell = new Cell().Add(new Paragraph(FechaTB.Text)).AddStyle(styleDatos).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE);
            _table.AddCell(_cell);

            _cell = new Cell().Add(new Paragraph("Data final rutina")).SetBorder(Border.NO_BORDER).SetVerticalAlignment(VerticalAlignment.MIDDLE);
            _table.AddCell(_cell.AddStyle(boldStyle));

            _cell = new Cell().Add(new Paragraph(FechaFinTB.Text)).AddStyle(styleDatos).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE);
            _table.AddCell(_cell);

            _cell = new Cell().Add(new Paragraph("Rutina")).SetBorder(Border.NO_BORDER).SetVerticalAlignment(VerticalAlignment.MIDDLE);
            _table.AddCell(_cell.AddStyle(boldStyle));

            _cell = new Cell().Add(new Paragraph("003").AddStyle(styleDatos).SetTextAlignment(TextAlignment.RIGHT)).SetVerticalAlignment(VerticalAlignment.MIDDLE);
            _table.AddCell(_cell);
            doc.Add(_table);


            Table tablaPrincipal = new Table(4);

            tablaPrincipal.SetHorizontalBorderSpacing(0);
            tablaPrincipal.SetVerticalBorderSpacing(0);


            for (int i = 0; i < 24; i++)
            {
                Table ejercicio = new Table(6);

                Cell celda = new Cell(1, 6).SetBorder(Border.NO_BORDER).SetBackgroundColor(ColorConstants.LIGHT_GRAY);
                ejercicio.AddCell(celda.Add(new Paragraph("DELTOIDES").SetFontSize(7).SetTextAlignment(TextAlignment.LEFT)));


                celda = new Cell(1, 6).SetHorizontalAlignment(iText.Layout.Properties.HorizontalAlignment.LEFT)
                        .Add(new Paragraph("Sentadilla_bulgara_con_mancuernas")
                             .SetFontSize(7)).SetBorder(Border.NO_BORDER);
                ejercicio.AddCell(celda);


                celda = new Cell().Add(new Paragraph("Dia").SetFontSize(7.5f)).SetBorder(Border.NO_BORDER);
                ejercicio.AddCell(celda.AddStyle(headerMusculo));

                celda = new Cell().Add(new Paragraph("A")).SetBorder(new SolidBorder(0.5f));
                ejercicio.AddCell(celda.AddStyle(styleDatos));

                celda = new Cell().Add(new Paragraph("Ser")).SetBorder(Border.NO_BORDER);
                ejercicio.AddCell(celda.AddStyle(headerMusculo).SetFontSize(7.5f));

                celda = new Cell().Add(new Paragraph("2")).SetBorder(new SolidBorder(0.5f));
                ejercicio.AddCell(celda.AddStyle(styleDatos));

                celda = new Cell().Add(new Paragraph("Rep")).SetBorder(Border.NO_BORDER);
                ejercicio.AddCell(celda.AddStyle(headerMusculo).SetFontSize(7.5f));

                celda = new Cell().Add(new Paragraph("3")).SetBorder(new SolidBorder(0.5f));
                ejercicio.AddCell(celda.AddStyle(styleDatos));

                celda = new Cell(1, 2).Add(new Paragraph("Descans").SetFontSize(8).SetBold())
                        .Add(new Paragraph("\n").SetBorder(new SolidBorder(ColorConstants.BLACK, 0.5f)).SetFontSize(8).SetTextAlignment(TextAlignment.CENTER)).SetBorder(Border.NO_BORDER);
                ejercicio.AddCell(celda);

                celda = new Cell(1, 4).Add(imgEjercicio.SetHeight(63f).SetWidth(85f)).SetBorder(Border.NO_BORDER);
                ejercicio.AddCell(celda);



                celda = new Cell(1, 6).Add(new Paragraph("Notes").AddStyle(headerMusculo).SetFontSize(7f)).SetBorder(Border.NO_BORDER);
                ejercicio.AddCell(celda);

                celda = new Cell(1, 6).Add(new Paragraph("\n").SetFontSize(7f));
                ejercicio.AddCell(celda);

                tablaPrincipal.AddCell(ejercicio);
            }

            doc.Add(tablaPrincipal);

            doc.Close();
        }
Ejemplo n.º 13
0
        protected void GeneratePDF()
        {
            Style boldStyle     = new Style().SetTextAlignment(TextAlignment.CENTER).SetFontSize(8).SetBold();
            Style headerMusculo = new Style().SetTextAlignment(TextAlignment.LEFT).SetBold();

            Style styleDatos = new Style().SetFontSize(7);

            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Filter = "Pdf Files|*.pdf";
            saveFileDialog1.Title  = "Save an Image File";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string Imagenpath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

                Image logo = new Image(ImageDataFactory.Create(Imagenpath + "\\Resources\\Icons\\OnixLogo.png"));

                string path = saveFileDialog1.FileName;
                try
                {
                    PdfWriter   pw          = new PdfWriter(path);
                    PdfDocument pdfDocument = new PdfDocument(pw);

                    pdfDocument.AddEventHandler(PdfDocumentEvent.START_PAGE, new HeaderEventHandler(logo));
                    Document doc = new Document(pdfDocument, PageSize.A4);
                    doc.SetMargins(55, 30, 15, 30);

                    Table table = new Table(1).UseAllAvailableWidth(); //USAR TODO EL ANCHO DE LA HOJA

                    table.AddCell(new Cell().Add(new Paragraph("Nom:").SetFontSize(8))
                                  .SetTextAlignment(TextAlignment.LEFT)
                                  .SetBold().SetBorder(Border.NO_BORDER));

                    doc.Add(table);


                    Table _table = new Table(7).UseAllAvailableWidth();


                    Cell _cell = new Cell().Add(new Paragraph(NombreTB.Text).SetFontSize(8.5f)).SetVerticalAlignment(VerticalAlignment.MIDDLE);
                    _table.AddCell(_cell);

                    _cell = new Cell().Add(new Paragraph("Data inici rutina")).SetBorder(Border.NO_BORDER).SetVerticalAlignment(VerticalAlignment.MIDDLE);
                    _table.AddCell(_cell.AddStyle(boldStyle));

                    _cell = new Cell().Add(new Paragraph(FechaTB.Text)).SetFontSize(8.5f).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE);
                    _table.AddCell(_cell);

                    _cell = new Cell().Add(new Paragraph("Data final rutina")).SetBorder(Border.NO_BORDER).SetVerticalAlignment(VerticalAlignment.MIDDLE);
                    _table.AddCell(_cell.AddStyle(boldStyle));

                    _cell = new Cell().Add(new Paragraph(FechaFinTB.Text)).SetFontSize(8.5f).SetTextAlignment(TextAlignment.CENTER).SetVerticalAlignment(VerticalAlignment.MIDDLE);
                    _table.AddCell(_cell);

                    _cell = new Cell().Add(new Paragraph("Rutina")).SetBorder(Border.NO_BORDER).SetVerticalAlignment(VerticalAlignment.MIDDLE);
                    _table.AddCell(_cell.AddStyle(boldStyle));

                    _cell = new Cell().Add(new Paragraph(RutinaNumTB.Text).SetFontSize(8.5f).SetTextAlignment(TextAlignment.RIGHT)).SetVerticalAlignment(VerticalAlignment.MIDDLE);
                    _table.AddCell(_cell);
                    doc.Add(_table);


                    Table tablaPrincipal = new Table(4);
                    tablaPrincipal.SetHorizontalBorderSpacing(0);
                    tablaPrincipal.SetVerticalBorderSpacing(0);
                    var listaDia = ejercicios.OrderBy(x => x.Dia).ToList();


                    foreach (var item in listaDia)
                    {
                        Table ejercicio = new Table(6);

                        Cell celda = new Cell(1, 6).SetBorder(Border.NO_BORDER).SetBackgroundColor(ColorConstants.LIGHT_GRAY);
                        ejercicio.AddCell(celda.Add(new Paragraph(item.Musculo).SetBold().SetFontSize(7).SetTextAlignment(TextAlignment.LEFT)));


                        celda = new Cell(1, 6).SetHorizontalAlignment(iText.Layout.Properties.HorizontalAlignment.LEFT)
                                .Add(new Paragraph(item.Ejercicio)
                                     .SetFontSize(7)).SetBorder(Border.NO_BORDER);
                        ejercicio.AddCell(celda);


                        celda = new Cell().Add(new Paragraph("Dia").SetFontSize(7.5f)).SetBorder(Border.NO_BORDER);
                        ejercicio.AddCell(celda.AddStyle(headerMusculo));

                        celda = new Cell().Add(new Paragraph(item.Dia.ToUpper()).SetTextAlignment(TextAlignment.CENTER)).SetBorder(new SolidBorder(0.5f));
                        ejercicio.AddCell(celda.AddStyle(styleDatos));

                        celda = new Cell().Add(new Paragraph("Ser").SetTextAlignment(TextAlignment.CENTER)).SetBorder(Border.NO_BORDER);
                        ejercicio.AddCell(celda.AddStyle(headerMusculo).SetFontSize(7.5f));

                        celda = new Cell().Add(new Paragraph(item.Series.ToString()).SetTextAlignment(TextAlignment.CENTER)).SetBorder(new SolidBorder(0.5f));
                        ejercicio.AddCell(celda.AddStyle(styleDatos));

                        celda = new Cell().Add(new Paragraph("Rep").SetTextAlignment(TextAlignment.CENTER)).SetBorder(Border.NO_BORDER);
                        ejercicio.AddCell(celda.AddStyle(headerMusculo).SetFontSize(7.5f));

                        celda = new Cell().Add(new Paragraph(item.Repeticiones.ToString()).SetTextAlignment(TextAlignment.CENTER)).SetBorder(new SolidBorder(0.5f));
                        ejercicio.AddCell(celda.AddStyle(styleDatos));

                        celda = new Cell(1, 2).Add(new Paragraph("Descans").SetFontSize(8).SetBold())
                                .Add(new Paragraph(Nullable(item.Descanso)).SetBorder(new SolidBorder(ColorConstants.BLACK, 0.5f)).SetFontSize(8).SetTextAlignment(TextAlignment.CENTER)).SetBorder(Border.NO_BORDER);
                        ejercicio.AddCell(celda);

                        if (string.IsNullOrWhiteSpace(item.ImagePath))
                        {
                            MessageBox.Show("Algun ejercicio no tiene asignada ninguna foto");
                            return;
                        }
                        Image imgEjercicio = new Image(ImageDataFactory.Create(item.ImagePath));


                        celda = new Cell(1, 4).Add(imgEjercicio.SetHeight(63f).SetWidth(85f)).SetBorder(Border.NO_BORDER);
                        ejercicio.AddCell(celda);



                        celda = new Cell(1, 6).Add(new Paragraph("Notes").AddStyle(headerMusculo).SetFontSize(7f)).SetBorder(Border.NO_BORDER);
                        ejercicio.AddCell(celda);

                        celda = new Cell(1, 6).Add(new Paragraph(Nullable(item.Comentario)).SetFontSize(7f));
                        ejercicio.AddCell(celda);

                        tablaPrincipal.AddCell(ejercicio);
                    }


                    doc.Add(tablaPrincipal);

                    doc.Close();

                    MessageBox.Show("Se ha generado el pdf en la ruta: " + path);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Ha ocurrido un error en la creacion de la rutina\nFaltan datos en los ejercicio");
                    return;
                }
            }
        }