Exemplo n.º 1
0
        public void ImprimeReporte()
        {
            string id, usuario, usuario_aplic, fecha_sol, fecha_apli, origen, destino, motivo, observaciones, estatus;

            id            = txtId.Text;
            usuario       = txtUsuario.Text;
            origen        = txtOrigen.Text;
            destino       = txtDestino.Text;
            fecha_sol     = txtFecha.Text;
            fecha_apli    = lblFechaAplicacion.Text;
            motivo        = txtMotivo.Text;
            estatus       = txtEstatus.Text;
            usuario_aplic = lblUsuarioAplica.Text;

            observaciones = txtObservaciones.Text;
            try
            {
                Document  doc      = new Document(PageSize.A4);
                string    filename = "TraspasosPDF\\TRASPASO " + id + " " + origen + ".pdf";
                PdfWriter writer   = PdfWriter.GetInstance(doc, new FileStream(@filename, FileMode.Create));

                doc.AddTitle("Prueba DaNxD");
                doc.AddCreator("DaN");

                // Abrimos el archivo
                doc.Open();

                iTextSharp.text.Font _standardFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

                //######################################## ENCABEZADO ################################################################

                // Escribimos el encabezamiento en el documento
                Paragraph parrafoEnc = new Paragraph();
                parrafoEnc.Alignment = Element.ALIGN_CENTER;
                //parrafoEnc.Font = FontFactory.GetFont("Arial",14);
                parrafoEnc.Font = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 16);

                Paragraph parrafo = new Paragraph();
                //parrafoEnc.Alignment = Element.ALIGN_CENTER;
                //parrafoEnc.Font = FontFactory.GetFont("Arial", 14);
                var normal   = FontFactory.GetFont(FontFactory.HELVETICA, 10);
                var negritas = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12);



                parrafoEnc.Add("Traspaso de " + origen + " N. " + id);
                doc.Add(parrafoEnc);
                parrafoEnc.Clear();

                doc.Add(Chunk.NEWLINE);
                doc.Add(Chunk.NEWLINE);

                parrafo.Add(new Chunk("ID Traspaso: ", negritas));
                parrafo.Add(new Chunk(id, normal));
                doc.Add(parrafo);

                parrafo.Clear();


                parrafo.Add(new Chunk("Fecha de Creacion: ", negritas));
                parrafo.Add(new Chunk(fecha_sol, normal));
                doc.Add(parrafo);

                parrafo.Clear();

                parrafo.Add(new Chunk("Fecha de Aplicacion: ", negritas));
                parrafo.Add(new Chunk(fecha_apli, normal));
                doc.Add(parrafo);

                parrafo.Clear();

                parrafo.Add(new Chunk("Solicito: ", negritas));
                parrafo.Add(new Chunk(usuario, normal));
                doc.Add(parrafo);

                parrafo.Clear();

                parrafo.Add(new Chunk("Origen: ", negritas));
                parrafo.Add(new Chunk(origen, normal));

                parrafo.Add("         ");
                parrafo.Add(new Chunk("Destino: ", negritas));
                parrafo.Add(new Chunk(destino, normal));

                doc.Add(parrafo);

                parrafo.Clear();

                parrafo.Add(new Chunk("Motivo: ", negritas));
                parrafo.Add(new Chunk(motivo, normal));
                doc.Add(parrafo);

                parrafo.Clear();

                parrafo.Add(new Chunk("Aplico: ", negritas));
                parrafo.Add(new Chunk(lblUsuarioAplica.Text, normal));
                doc.Add(parrafo);

                parrafo.Clear();

                parrafo.Add(new Chunk("Observaciones: ", negritas));
                parrafo.Add(new Chunk(observaciones, normal));
                doc.Add(parrafo);

                parrafo.Clear();

                parrafo.Add(new Chunk("Estado: ", negritas));
                parrafo.Add(new Chunk(estatus, normal));
                doc.Add(parrafo);

                parrafo.Clear();

                doc.Add(Chunk.NEWLINE);
                doc.Add(Chunk.NEWLINE);

                parrafoEnc.Font = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12);
                parrafoEnc.Add("ARTICULOS DEL TRASPASO");
                doc.Add(parrafoEnc);
                doc.Add(Chunk.NEWLINE);
                // PRUEBA DAN
                PdfPTable table = new PdfPTable(dgvItem.Columns.Count);

                table.WidthPercentage = 100;
                float[] widths = new float[] { 30f, 100f, 30f };
                table.SetWidths(widths);
                table.SkipLastFooter = true;
                table.SpacingAfter   = 10;


                //Encabezados
                for (int j = 0; j < dgvItem.Columns.Count; j++)
                {
                    table.AddCell(new Phrase(dgvItem.Columns[j].HeaderText));
                }

                //flag the first row as a header
                table.HeaderRows = 1;

                for (int i = 0; i < dgvItem.Rows.Count; i++)
                {
                    for (int k = 0; k < dgvItem.Columns.Count; k++)
                    {
                        if (dgvItem[k, i].Value != null)
                        {
                            table.AddCell(new Phrase(dgvItem[k, i].Value.ToString()));
                        }
                    }
                }

                doc.Add(table);


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

                Process prc = new System.Diagnostics.Process();
                prc.StartInfo.FileName = filename;
                prc.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error al generar archivo PDF o el archivo ya esta abierto.");
            }
        }
        public ActionResult ReceivingReceipt(Int32 RRId)
        {
            // ==============================
            // PDF Settings and Customization
            // ==============================
            MemoryStream workStream = new MemoryStream();
            Rectangle    rectangle  = new Rectangle(PageSize.A3);
            Document     document   = new Document(rectangle, 72, 72, 72, 72);

            document.SetMargins(30f, 30f, 30f, 30f);
            PdfWriter.GetInstance(document, workStream).CloseStream = false;

            document.Open();

            // =====
            // Fonts
            // =====
            Font fontArial17Bold = FontFactory.GetFont("Arial", 17, Font.BOLD);
            Font fontArial11     = FontFactory.GetFont("Arial", 11);
            Font fontArial9Bold  = FontFactory.GetFont("Arial", 9, Font.BOLD);
            Font fontArial9      = FontFactory.GetFont("Arial", 9);
            Font fontArial10Bold = FontFactory.GetFont("Arial", 10, Font.BOLD);
            Font fontArial10     = FontFactory.GetFont("Arial", 10);
            Font fontArial11Bold = FontFactory.GetFont("Arial", 11, Font.BOLD);
            Font fontArial12Bold = FontFactory.GetFont("Arial", 12, Font.BOLD);
            Font fontArial13Bold = FontFactory.GetFont("Arial", 13, Font.BOLD);

            Paragraph line = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 4.5F)));

            var identityUserId   = User.Identity.GetUserId();
            var currentUser      = from d in db.MstUsers where d.UserId == identityUserId select d;
            var currentCompanyId = currentUser.FirstOrDefault().CompanyId;
            var currentBranchId  = currentUser.FirstOrDefault().BranchId;

            // ==============
            // Company Detail
            // ==============
            var companyName = (from d in db.MstCompanies where d.Id == Convert.ToInt32(currentCompanyId) select d.Company).FirstOrDefault();
            var address     = (from d in db.MstCompanies where d.Id == Convert.ToInt32(currentCompanyId) select d.Address).FirstOrDefault();
            var contactNo   = (from d in db.MstCompanies where d.Id == Convert.ToInt32(currentCompanyId) select d.ContactNumber).FirstOrDefault();
            var branch      = (from d in db.MstBranches where d.Id == Convert.ToInt32(currentBranchId) select d.Branch).FirstOrDefault();

            // ===========
            // Header Page
            // ===========
            PdfPTable headerPage = new PdfPTable(2);

            float[] widthsCellsHeaderPage = new float[] { 100f, 75f };
            headerPage.SetWidths(widthsCellsHeaderPage);
            headerPage.WidthPercentage = 100;
            headerPage.AddCell(new PdfPCell(new Phrase(companyName, fontArial17Bold))
            {
                Border = 0
            });
            headerPage.AddCell(new PdfPCell(new Phrase("Receiving Receipt", fontArial17Bold))
            {
                Border = 0, HorizontalAlignment = 2
            });
            headerPage.AddCell(new PdfPCell(new Phrase(address, fontArial11))
            {
                Border = 0, PaddingTop = 5f
            });
            headerPage.AddCell(new PdfPCell(new Phrase(branch, fontArial11))
            {
                Border = 0, PaddingTop = 5f, HorizontalAlignment = 2
            });
            headerPage.AddCell(new PdfPCell(new Phrase(contactNo, fontArial11))
            {
                Border = 0, PaddingTop = 5f
            });
            headerPage.AddCell(new PdfPCell(new Phrase("Printed " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToString("hh:mm:ss tt"), fontArial11))
            {
                Border = 0, PaddingTop = 5f, HorizontalAlignment = 2
            });
            document.Add(headerPage);

            // =====
            // Space
            // =====
            PdfPTable spaceTable = new PdfPTable(1);

            float[] widthCellsSpaceTable = new float[] { 100f };
            spaceTable.SetWidths(widthCellsSpaceTable);
            spaceTable.WidthPercentage = 100;
            spaceTable.AddCell(new PdfPCell(new Phrase(" ", fontArial10Bold))
            {
                Border = 0, PaddingTop = 5f
            });

            document.Add(line);

            // =====================
            // Get Receiving Receipt
            // =====================
            var receivingReceipt = from d in db.TrnReceivingReceipts
                                   where d.Id == RRId &&
                                   d.IsLocked == true
                                   select d;

            if (receivingReceipt.Any())
            {
                String supplier    = receivingReceipt.FirstOrDefault().MstArticle.Article;
                String term        = receivingReceipt.FirstOrDefault().MstTerm.Term;
                String dueDate     = receivingReceipt.FirstOrDefault().RRDate.AddDays(Convert.ToInt32(receivingReceipt.FirstOrDefault().MstTerm.NumberOfDays)).ToString("MM-dd-yyyy", CultureInfo.InvariantCulture);
                String remarks     = receivingReceipt.FirstOrDefault().Remarks;
                String RRNumber    = receivingReceipt.FirstOrDefault().RRNumber;
                String RRDate      = receivingReceipt.FirstOrDefault().RRDate.ToString("MM-dd-yyyy", CultureInfo.InvariantCulture);
                String documentRef = receivingReceipt.FirstOrDefault().DocumentReference;
                String preparedBy  = receivingReceipt.FirstOrDefault().MstUser3.FullName;
                String checkedBy   = receivingReceipt.FirstOrDefault().MstUser1.FullName;
                String approvedBy  = receivingReceipt.FirstOrDefault().MstUser.FullName;
                String receivedBy  = receivingReceipt.FirstOrDefault().MstUser4.FullName;

                PdfPTable tableReceivingReceipt            = new PdfPTable(4);
                float[]   widthscellsTableReceivingReceipt = new float[] { 40f, 150f, 70f, 50f };
                tableReceivingReceipt.SetWidths(widthscellsTableReceivingReceipt);
                tableReceivingReceipt.WidthPercentage = 100;
                tableReceivingReceipt.AddCell(new PdfPCell(new Phrase("Customer ", fontArial11Bold))
                {
                    Border = 0, PaddingTop = 10f, PaddingLeft = 5f, PaddingRight = 5f
                });
                tableReceivingReceipt.AddCell(new PdfPCell(new Phrase(supplier, fontArial11))
                {
                    Border = 0, PaddingTop = 10f, PaddingLeft = 5f, PaddingRight = 5f
                });
                tableReceivingReceipt.AddCell(new PdfPCell(new Phrase("No.", fontArial11Bold))
                {
                    Border = 0, PaddingTop = 10f, PaddingLeft = 5f, PaddingRight = 5f, HorizontalAlignment = 2
                });
                tableReceivingReceipt.AddCell(new PdfPCell(new Phrase(RRNumber, fontArial11))
                {
                    Border = 0, PaddingTop = 10f, PaddingLeft = 5f, PaddingRight = 5f, HorizontalAlignment = 2
                });
                tableReceivingReceipt.AddCell(new PdfPCell(new Phrase("Term ", fontArial11Bold))
                {
                    Border = 0, PaddingTop = 5f, PaddingLeft = 5f, PaddingRight = 5f
                });
                tableReceivingReceipt.AddCell(new PdfPCell(new Phrase(term, fontArial11))
                {
                    Border = 0, PaddingTop = 5f, PaddingLeft = 5f, PaddingRight = 5f
                });
                tableReceivingReceipt.AddCell(new PdfPCell(new Phrase("Date ", fontArial11Bold))
                {
                    Border = 0, PaddingTop = 5f, PaddingLeft = 5f, PaddingRight = 5f, HorizontalAlignment = 2
                });
                tableReceivingReceipt.AddCell(new PdfPCell(new Phrase(RRDate, fontArial11))
                {
                    Border = 0, PaddingTop = 5f, PaddingLeft = 5f, PaddingRight = 5f, HorizontalAlignment = 2
                });
                tableReceivingReceipt.AddCell(new PdfPCell(new Phrase("Due Date ", fontArial11Bold))
                {
                    Border = 0, PaddingTop = 5f, PaddingLeft = 5f, PaddingRight = 5f
                });
                tableReceivingReceipt.AddCell(new PdfPCell(new Phrase(dueDate, fontArial11))
                {
                    Border = 0, PaddingTop = 5f, PaddingLeft = 5f, PaddingRight = 5f
                });
                tableReceivingReceipt.AddCell(new PdfPCell(new Phrase("Document Ref ", fontArial11Bold))
                {
                    Border = 0, PaddingTop = 5f, PaddingLeft = 5f, PaddingRight = 5f, HorizontalAlignment = 2
                });
                tableReceivingReceipt.AddCell(new PdfPCell(new Phrase(documentRef, fontArial11))
                {
                    Border = 0, PaddingTop = 5f, PaddingLeft = 5f, PaddingRight = 5f, HorizontalAlignment = 2
                });
                tableReceivingReceipt.AddCell(new PdfPCell(new Phrase("Remarks ", fontArial11Bold))
                {
                    Border = 0, PaddingTop = 5f, PaddingLeft = 5f, PaddingRight = 5f
                });
                tableReceivingReceipt.AddCell(new PdfPCell(new Phrase(remarks, fontArial11))
                {
                    Border = 0, PaddingTop = 5f, PaddingLeft = 5f, PaddingRight = 5f
                });
                tableReceivingReceipt.AddCell(new PdfPCell(new Phrase(" ", fontArial11))
                {
                    Colspan = 2, Border = 0, PaddingTop = 5f, PaddingLeft = 5f, PaddingRight = 5f
                });
                document.Add(tableReceivingReceipt);

                document.Add(spaceTable);

                var receivingReceiptItems = from d in db.TrnReceivingReceiptItems
                                            where d.RRId == RRId &&
                                            d.TrnReceivingReceipt.IsLocked == true
                                            select new
                {
                    Id             = d.Id,
                    RRId           = d.RRId,
                    RR             = d.TrnReceivingReceipt.RRNumber,
                    POId           = d.POId,
                    PO             = d.TrnPurchaseOrder.PONumber,
                    ItemId         = d.ItemId,
                    Item           = d.MstArticle.Article,
                    ItemCode       = d.MstArticle.ManualArticleCode,
                    Particulars    = d.Particulars,
                    UnitId         = d.UnitId,
                    Unit           = d.MstUnit.Unit,
                    Quantity       = d.Quantity,
                    Cost           = d.Cost,
                    Amount         = d.Amount,
                    VATId          = d.VATId,
                    VAT            = d.MstTaxType.TaxType,
                    VATPercentage  = d.VATPercentage,
                    VATAmount      = d.VATAmount,
                    WTAXId         = d.WTAXId,
                    WTAX           = d.MstTaxType1.TaxType,
                    WTAXPercentage = d.WTAXPercentage,
                    WTAXAmount     = d.WTAXAmount,
                    BranchId       = d.BranchId,
                    Branch         = d.MstBranch.Branch,
                    BaseUnitId     = d.BaseUnitId,
                    BaseUnit       = d.MstUnit1.Unit,
                    BaseQuantity   = d.BaseQuantity,
                    BaseCost       = d.BaseCost
                };

                if (receivingReceiptItems.Any())
                {
                    PdfPTable tableReceivingReceiptItems       = new PdfPTable(7);
                    float[]   widthsCellsReceivingReceiptItems = new float[] { 50f, 100f, 70f, 200f, 200f, 100f, 100f };
                    tableReceivingReceiptItems.SetWidths(widthsCellsReceivingReceiptItems);
                    tableReceivingReceiptItems.WidthPercentage = 100;
                    tableReceivingReceiptItems.AddCell(new PdfPCell(new Phrase("No.", fontArial11Bold))
                    {
                        HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 7f
                    });
                    tableReceivingReceiptItems.AddCell(new PdfPCell(new Phrase("Quantity", fontArial11Bold))
                    {
                        HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 7f
                    });
                    tableReceivingReceiptItems.AddCell(new PdfPCell(new Phrase("Unit", fontArial11Bold))
                    {
                        HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 7f
                    });
                    tableReceivingReceiptItems.AddCell(new PdfPCell(new Phrase("Item", fontArial11Bold))
                    {
                        HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 7f
                    });
                    tableReceivingReceiptItems.AddCell(new PdfPCell(new Phrase("Branch", fontArial11Bold))
                    {
                        HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 7f
                    });
                    tableReceivingReceiptItems.AddCell(new PdfPCell(new Phrase("Price", fontArial11Bold))
                    {
                        HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 7f
                    });
                    tableReceivingReceiptItems.AddCell(new PdfPCell(new Phrase("Amount", fontArial11Bold))
                    {
                        HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 7f
                    });

                    Decimal totalAmount = 0;
                    Decimal count       = 0;

                    foreach (var receivingReceiptItem in receivingReceiptItems)
                    {
                        count       += 1;
                        totalAmount += receivingReceiptItem.Amount;

                        tableReceivingReceiptItems.AddCell(new PdfPCell(new Phrase(count.ToString("#,##0"), fontArial11))
                        {
                            HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 7f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        tableReceivingReceiptItems.AddCell(new PdfPCell(new Phrase(receivingReceiptItem.Quantity.ToString("#,##0.00"), fontArial11))
                        {
                            HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 7f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        tableReceivingReceiptItems.AddCell(new PdfPCell(new Phrase(receivingReceiptItem.Unit, fontArial11))
                        {
                            HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 7f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        tableReceivingReceiptItems.AddCell(new PdfPCell(new Phrase(receivingReceiptItem.Item, fontArial11))
                        {
                            HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 7f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        tableReceivingReceiptItems.AddCell(new PdfPCell(new Phrase(receivingReceiptItem.Branch, fontArial11))
                        {
                            HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 7f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        tableReceivingReceiptItems.AddCell(new PdfPCell(new Phrase(receivingReceiptItem.Cost.ToString("#,##0.00"), fontArial11))
                        {
                            HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 7f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        tableReceivingReceiptItems.AddCell(new PdfPCell(new Phrase(receivingReceiptItem.Amount.ToString("#,##0.00"), fontArial11))
                        {
                            HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 7f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                    }

                    tableReceivingReceiptItems.AddCell(new PdfPCell(new Phrase("Total", fontArial11Bold))
                    {
                        Colspan = 6, HorizontalAlignment = 2, PaddingTop = 5f, PaddingBottom = 9f, PaddingLeft = 5f, PaddingRight = 5f
                    });
                    tableReceivingReceiptItems.AddCell(new PdfPCell(new Phrase(totalAmount.ToString("#,##0.00"), fontArial11Bold))
                    {
                        HorizontalAlignment = 2, PaddingTop = 5f, PaddingBottom = 9f, PaddingLeft = 5f, PaddingRight = 5f
                    });
                    document.Add(tableReceivingReceiptItems);

                    document.Add(spaceTable);
                }

                // ============
                // VAT Analysis
                // ============
                var VATItems = from d in receivingReceiptItems
                               group d by new
                {
                    VAT  = d.VAT,
                    WTAX = d.WTAX
                } into g
                    select new
                {
                    VAT        = g.Key.VAT,
                    Amount     = g.Sum(d => d.Amount),
                    VATAmount  = g.Sum(d => d.VATAmount),
                    WTAXAmount = g.Sum(d => d.WTAXAmount)
                };

                if (VATItems.Any())
                {
                    PdfPTable tableVATAnalysis    = new PdfPTable(4);
                    float[]   widthsCellsVATItems = new float[] { 200f, 100f, 100f, 100f };
                    tableVATAnalysis.SetWidths(widthsCellsVATItems);
                    tableVATAnalysis.HorizontalAlignment = Element.ALIGN_LEFT;
                    tableVATAnalysis.WidthPercentage     = 50;
                    tableVATAnalysis.AddCell(new PdfPCell(new Phrase("VAT", fontArial9Bold))
                    {
                        HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 7f
                    });
                    tableVATAnalysis.AddCell(new PdfPCell(new Phrase("Amount", fontArial9Bold))
                    {
                        HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 7f
                    });
                    tableVATAnalysis.AddCell(new PdfPCell(new Phrase("VAT Amount", fontArial9Bold))
                    {
                        HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 7f
                    });
                    tableVATAnalysis.AddCell(new PdfPCell(new Phrase("WTAX Amount", fontArial9Bold))
                    {
                        HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 7f
                    });

                    Decimal totalVATAmount = 0;
                    Decimal totalVAT       = 0;
                    Decimal totalWTAX      = 0;

                    foreach (var VATItem in VATItems)
                    {
                        tableVATAnalysis.AddCell(new PdfPCell(new Phrase(VATItem.VAT, fontArial9))
                        {
                            HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 7f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        tableVATAnalysis.AddCell(new PdfPCell(new Phrase(VATItem.Amount.ToString("#,##0.00"), fontArial9))
                        {
                            HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 7f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        tableVATAnalysis.AddCell(new PdfPCell(new Phrase(VATItem.VATAmount.ToString("#,##0.00"), fontArial9))
                        {
                            HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 7f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        tableVATAnalysis.AddCell(new PdfPCell(new Phrase(VATItem.WTAXAmount.ToString("#,##0.00"), fontArial9))
                        {
                            HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 7f, PaddingLeft = 5f, PaddingRight = 5f
                        });

                        totalVATAmount += VATItem.Amount;
                        totalVAT       += VATItem.VATAmount;
                        totalWTAX      += VATItem.WTAXAmount;
                    }

                    tableVATAnalysis.AddCell(new PdfPCell(new Phrase("Total", fontArial9Bold))
                    {
                        HorizontalAlignment = 2, PaddingTop = 5f, PaddingBottom = 9f, PaddingLeft = 5f, PaddingRight = 5f
                    });
                    tableVATAnalysis.AddCell(new PdfPCell(new Phrase(totalVATAmount.ToString("#,##0.00"), fontArial9Bold))
                    {
                        HorizontalAlignment = 2, PaddingTop = 5f, PaddingBottom = 9f, PaddingLeft = 5f, PaddingRight = 5f
                    });
                    tableVATAnalysis.AddCell(new PdfPCell(new Phrase(totalVAT.ToString("#,##0.00"), fontArial9Bold))
                    {
                        HorizontalAlignment = 2, PaddingTop = 5f, PaddingBottom = 9f, PaddingLeft = 5f, PaddingRight = 5f
                    });
                    tableVATAnalysis.AddCell(new PdfPCell(new Phrase(totalWTAX.ToString("#,##0.00"), fontArial9Bold))
                    {
                        HorizontalAlignment = 2, PaddingTop = 5f, PaddingBottom = 9f, PaddingLeft = 5f, PaddingRight = 5f
                    });

                    // TODO: Option Settings for VAT Analysis Table
                    //document.Add(tableVATAnalysis);

                    //document.Add(spaceTable);
                }

                // ==============
                // User Signature
                // ==============
                PdfPTable tableUsers            = new PdfPTable(4);
                float[]   widthsCellsTableUsers = new float[] { 100f, 100f, 100f, 100f };
                tableUsers.WidthPercentage = 100;
                tableUsers.SetWidths(widthsCellsTableUsers);
                tableUsers.AddCell(new PdfPCell(new Phrase("Prepared by", fontArial11Bold))
                {
                    PaddingTop = 5f, PaddingBottom = 9f, PaddingLeft = 5f, PaddingRight = 5f
                });
                tableUsers.AddCell(new PdfPCell(new Phrase("Checked by", fontArial11Bold))
                {
                    PaddingTop = 5f, PaddingBottom = 9f, PaddingLeft = 5f, PaddingRight = 5f
                });
                tableUsers.AddCell(new PdfPCell(new Phrase("Approved by", fontArial11Bold))
                {
                    PaddingTop = 5f, PaddingBottom = 9f, PaddingLeft = 5f, PaddingRight = 5f
                });
                tableUsers.AddCell(new PdfPCell(new Phrase("Received by", fontArial11Bold))
                {
                    PaddingTop = 5f, PaddingBottom = 9f, PaddingLeft = 5f, PaddingRight = 5f
                });
                tableUsers.AddCell(new PdfPCell(new Phrase(" "))
                {
                    PaddingBottom = 50f
                });
                tableUsers.AddCell(new PdfPCell(new Phrase(" "))
                {
                    PaddingBottom = 50f
                });
                tableUsers.AddCell(new PdfPCell(new Phrase(" "))
                {
                    PaddingBottom = 50f
                });
                tableUsers.AddCell(new PdfPCell(new Phrase(" "))
                {
                    PaddingBottom = 50f
                });
                tableUsers.AddCell(new PdfPCell(new Phrase(preparedBy, fontArial11))
                {
                    HorizontalAlignment = 1, PaddingTop = 5f, PaddingBottom = 9f, PaddingLeft = 5f, PaddingRight = 5f
                });
                tableUsers.AddCell(new PdfPCell(new Phrase(checkedBy, fontArial11))
                {
                    HorizontalAlignment = 1, PaddingTop = 5f, PaddingBottom = 9f, PaddingLeft = 5f, PaddingRight = 5f
                });
                tableUsers.AddCell(new PdfPCell(new Phrase(approvedBy, fontArial11))
                {
                    HorizontalAlignment = 1, PaddingTop = 5f, PaddingBottom = 9f, PaddingLeft = 5f, PaddingRight = 5f
                });
                tableUsers.AddCell(new PdfPCell(new Phrase(receivedBy, fontArial11))
                {
                    HorizontalAlignment = 1, PaddingTop = 5f, PaddingBottom = 9f, PaddingLeft = 5f, PaddingRight = 5f
                });
                document.Add(tableUsers);
            }

            document.Close();

            byte[] byteInfo = workStream.ToArray();
            workStream.Write(byteInfo, 0, byteInfo.Length);
            workStream.Position = 0;

            return(new FileStreamResult(workStream, "application/pdf"));
        }
Exemplo n.º 3
0
        public override void Generate()
        {
            var font        = FontFactory.GetFont("Times New Roman", 10);
            var sectionFont = FontFactory.GetFont("Times New Roman", 16, Font.BOLD);

            base.Generate();

            var table = new AttachmentTable();

            foreach (var attachment in Settings.Attachments)
            {
                string attachmentName = null;
                if (attachment.IsSection)
                {
                    if (table.Rows.Any() && table.Complete)
                    {
                        FormatTableCells(table, 20);
                        Document.Add(table);
                        Document.NewPage();
                        table = new AttachmentTable();
                    }
                    var sectionHeader = MakeCell(attachment.SectionHeader, sectionFont);
                    sectionHeader.Colspan = 2;
                    table.AddCell(sectionHeader);
                }
                if (attachment.HasAttachment)
                {
                    attachmentName = Path.GetFileName(attachment.AttachmentPath);
                    var fileSpec = PdfFileSpecification.FileEmbedded(Writer, attachment.AttachmentPath,
                                                                     attachmentName, null);
                    fileSpec.AddDescription(attachmentName, false);
                    Writer.AddFileAttachment(fileSpec);
                }
                if (attachment.HasThumbnail)
                {
                    var image = Image.GetInstance(attachment.ThumbnailPath, true);
                    var cell  = new PdfPCell(image)
                    {
                        HorizontalAlignment = Element.ALIGN_CENTER,
                        VerticalAlignment   = Element.ALIGN_MIDDLE
                    };
                    if (attachment.HasAttachment)
                    {
                        cell.CellEvent = new ThumbnailLayoutHandler(attachmentName, Writer);
                    }
                    if (!attachment.HasDescriptiveText)
                    {
                        cell.Colspan = 2;
                    }
                    table.AddCell(cell);
                }

                if (!attachment.HasDescriptiveText)
                {
                    continue;
                }

                var description = MakeCell(attachment.DescriptiveText, font);
                description.VerticalAlignment = Element.ALIGN_MIDDLE;
                if (!attachment.HasThumbnail)
                {
                    description.Colspan = 2;
                }

                table.AddCell(description);
            }

            FormatTableCells(table, 20);
            Document.Add(table);
        }
    public Boolean PDFUpload(Int64 PurchaseOrderId)
    {
        string finalResult = string.Empty;
        bool   flag        = true;

        Int64 inid = 0;

        try
        {
            //string query = "Select POH.*,CONVERT(nvarchar, POH.OrderDate,103) + ' '+REPLACE(REPLACE(CONVERT(varchar(15), CAST(POH.OrderDate AS TIME), 100), 'P', ' P'), 'A', ' A') as OrderDate1, POD.*, PM.ProdName as ProdName , VM.*, BM.BrandName as Brand, SM.Size as Size from [DoctorDiagnosisNew].[PurchaseOrderHeader] POH ,[DoctorDiagnosisNew].[PurchaseOrderDetails] POD ,[dbo].[VendorMaster] VM ,[dbo].[BrandMaster] BM ,[dbo].[SizeMaster] SM ,[dbo].[ProductMaster] PM where POH.isdeleted=0 AND POH.[PurchaseOrderId] = " + CategoryId + " AND POH.[VendorId] = VM.[VendorId] AND POH.[PurchaseOrderId] = POD.[PurchaseOrderId] AND POD.[BrandId] = BM.[BrandId] AND POD.[SizeId] = SM.[SizeId] AND POD.[ProdId] = PM.[ProdId] ORDER BY ProdName DESC";
            DataSet ds = new DataSet();

            SqlCommand cmd = new SqlCommand();

            cmd.CommandText = "PurchaseOrderHeader_SelectById";
            cmd.Parameters.AddWithValue("@id", PurchaseOrderId);
            //cmd.Parameters.AddWithValue("@password", password);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter sda = new SqlDataAdapter();
            cmd.Connection    = con;
            sda.SelectCommand = cmd;



            //SqlDataAdapter da = new SqlDataAdapter(query, con);
            sda.Fill(ds);
            String       po      = ds.Tables[0].Rows[0]["PONo"].ToString();
            Document     pdfDoc  = new Document(PageSize.A4, 10, 10, 10, 10);
            MemoryStream PDFData = new MemoryStream();
            //PdfWriter pw = PdfWriter.GetInstance(
            //PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream(Context.Server.MapPath("~/uploads/PurchaseOrders/") + po + ".pdf", FileMode.Create));
            PdfWriter writer = PdfWriter.GetInstance(pdfDoc, PDFData);

            var titleFont      = FontFactory.GetFont("Arial", 6, Font.NORMAL);
            var titleFontBlue  = FontFactory.GetFont("Arial", 14, Font.NORMAL, Color.BLUE);
            var boldTableFont  = FontFactory.GetFont("Arial", 8, Font.BOLD);              //8
            var boldTableFont1 = FontFactory.GetFont("Arial", 8, Font.BOLD);              //8
            var bodyFont       = FontFactory.GetFont("Arial", 7, Font.NORMAL);            //8
            var EmailFont      = FontFactory.GetFont("Arial", 8, Font.BOLD, Color.BLACK); //8
            var HeaderFont     = FontFactory.GetFont("Arial", 10, Font.BOLD, Color.BLACK);

            var   footerfont = FontFactory.GetFont("Arial", 6, Font.NORMAL, Color.BLACK);//8
            Color TabelHeaderBackGroundColor = WebColors.GetRGBColor("#EEEEEE");

            Rectangle pageSize = writer.PageSize;
            // Open the Document for writing
            pdfDoc.Open();
            //Add elements to the document here

            #region Top table
            // Create the header table
            PdfPTable headertable = new PdfPTable(3);
            headertable.HorizontalAlignment = 0;
            headertable.WidthPercentage     = 100;
            headertable.SetWidths(new float[] { 100f, 320f, 220f }); // then set the column's __relative__ widths
            headertable.DefaultCell.Border = Rectangle.NO_BORDER;
            headertable.DefaultCell.Border = Rectangle.BOX;          //for testing



            // invoice rperte

            PdfPTable Invoicetable2 = new PdfPTable(1);
            Invoicetable2.HorizontalAlignment = 0;
            Invoicetable2.WidthPercentage     = 100;
            Invoicetable2.SetWidths(new float[] { 500f });  // then set the column's __relative__ widths
            Invoicetable2.DefaultCell.Border = Rectangle.NO_BORDER;

            {
                PdfPTable mainN = new PdfPTable(1);
                // tablenew.HorizontalAlignment = 1;
                //PdfPCell cellnew = new PdfPCell(new Phrase("PURCHASE ORDER"),EmailFont);
                PdfPCell cellN = new PdfPCell(new Phrase("Morya Tools \n\n 22, Pradhan Park, M.G Road, Nashik, Maharashtra, India 422001 "
                                                         + "\n\nPhone: (0253) 3014578 Email: [email protected]", HeaderFont));
                cellN.PaddingTop        = 15f;
                cellN.PaddingBottom     = 15f;
                cellN.VerticalAlignment = 1;
                //cellnew.Colspan = 2;
                cellN.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
                mainN.AddCell(cellN);
                PdfPCell nesthousingnn = new PdfPCell(mainN);

                PdfPTable tablenew = new PdfPTable(1);
                // tablenew.HorizontalAlignment = 1;
                //PdfPCell cellnew = new PdfPCell(new Phrase("PURCHASE ORDER"),EmailFont);
                PdfPCell cellnew = new PdfPCell(new Phrase("PURCHASE ORDER", EmailFont));
                cellnew.PaddingTop        = 15f;
                cellnew.PaddingBottom     = 15f;
                cellnew.VerticalAlignment = 1;
                //cellnew.Colspan = 2;
                cellnew.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
                tablenew.AddCell(cellnew);
                PdfPCell nesthousingn = new PdfPCell(tablenew);



                PdfPTable tablenew1 = new PdfPTable(2);

                // tablenew1.DefaultCell.FixedHeight = 100f;
                PdfPCell cellnew4 = new PdfPCell(new Phrase("PO No :    " + ds.Tables[0].Rows[0]["PONo"].ToString(), EmailFont));
                cellnew4.FixedHeight         = 30f;
                cellnew4.HorizontalAlignment = 1;
                cellnew4.PaddingTop          = 15f;
                cellnew4.PaddingBottom       = 15f;
                PdfPCell cellnew5 = new PdfPCell(new Phrase("PO Date :  " + ds.Tables[0].Rows[0]["OrderDate1"].ToString(), EmailFont));
                cellnew5.HorizontalAlignment = 1;
                cellnew5.PaddingTop          = 15f;
                cellnew5.PaddingBottom       = 15f;

                tablenew1.AddCell(cellnew4);

                tablenew1.AddCell(cellnew5);



                PdfPTable tablevendor = new PdfPTable(2);

                PdfPCell suppliername = new PdfPCell(new Phrase("VENDOR NAME :    " + ds.Tables[0].Rows[0]["vendorName"].ToString(), EmailFont));
                suppliername.MinimumHeight = 80f;
                suppliername.PaddingTop    = 10f;
                PdfPCell supplierdetails = new PdfPCell(new Phrase("VENDOR DETAILS:  \n\n\t Contact Person : " + ds.Tables[0].Rows[0]["vendorName"].ToString() + "\n\n\t Mobile No : " + ds.Tables[0].Rows[0]["MobileNo1"].ToString() + "\n\n\t Email : " + ds.Tables[0].Rows[0]["email"].ToString(), EmailFont));
                supplierdetails.PaddingTop = 10f;
                // PdfPCell termsnconditions = new PdfPCell(new Phrase("Terms & Conditions:    ", EmailFont));

                tablevendor.AddCell(suppliername);
                tablevendor.AddCell(supplierdetails);
                //tablevendor.AddCell(termsnconditions);



                PdfPCell nesthousingn1 = new PdfPCell(tablenew1);
                PdfPCell nesthousingn2 = new PdfPCell(tablevendor);
                // nesthousingn2.Height = 10f;
                //PdfPCell nesthousingn3 = new PdfPCell(tablenew3);


                nesthousingn.Border = Rectangle.NO_BORDER;

                //nesthousingn.PaddingBottom = 10f;
                Invoicetable2.AddCell(nesthousingnn);
                Invoicetable2.AddCell(nesthousingn);
                Invoicetable2.AddCell(nesthousingn1);
                Invoicetable2.AddCell(nesthousingn2);
                //Invoicetable2.AddCell(nesthousingn3);
            }
            //invoice repeat

            // Invoicetable2.AddCell(headertable);
            Invoicetable2.SpacingBefore = 3f;
            //  Invoicetable. = 10f;

            // pdfDoc.Add(Invoicetable);



            #endregion

            #region Items Table
            //Create body table
            PdfPTable itemTable = new PdfPTable(2);

            itemTable.HorizontalAlignment = 0;
            itemTable.WidthPercentage     = 100;
            // itemTable.SetWidths(new float[] { });  // then set the column's __relative__ widths
            //itemTable.SetWidths(new float[] { 4, 30, 6, 6, 6 });
            itemTable.SpacingAfter = 10;

            //itemTable.DefaultCell.Border = Rectangle.BOX;



            PdfPCell cell1 = new PdfPCell(new Phrase("PRODUCT", boldTableFont));
            //cell1.BackgroundColor = TabelHeaderBackGroundColor;
            cell1.HorizontalAlignment = Element.ALIGN_CENTER;
            itemTable.AddCell(cell1);

            /*
             * PdfPCell cell2 = new PdfPCell(new Phrase("BRAND", boldTableFont));
             * //cell2.BackgroundColor = TabelHeaderBackGroundColor;
             * cell2.HorizontalAlignment = 1;
             * itemTable.AddCell(cell2);
             *
             *
             *
             * PdfPCell cell3 = new PdfPCell(new Phrase("SIZE", boldTableFont));
             * //cell4.BackgroundColor = TabelHeaderBackGroundColor;
             * cell3.HorizontalAlignment = 1;
             * itemTable.AddCell(cell3);
             */

            PdfPCell cell4 = new PdfPCell(new Phrase("QUANTITY", boldTableFont));
            //cell5.BackgroundColor = TabelHeaderBackGroundColor;
            cell4.HorizontalAlignment = 1;
            itemTable.AddCell(cell4);


            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                PdfPCell cell1i = new PdfPCell(new Phrase(ds.Tables[0].Rows[i]["ProdName"].ToString(), bodyFont));
                //cell1.BackgroundColor = TabelHeaderBackGroundColor;
                cell1i.HorizontalAlignment = Element.ALIGN_CENTER;
                itemTable.AddCell(cell1i);

                /*
                 * PdfPCell cell2i = new PdfPCell(new Phrase(ds.Tables[0].Rows[i]["Brand"].ToString(), bodyFont));
                 * //cell2.BackgroundColor = TabelHeaderBackGroundColor;
                 * cell2i.HorizontalAlignment = 1;
                 * itemTable.AddCell(cell2i);
                 *
                 *
                 *
                 * PdfPCell cell4i = new PdfPCell(new Phrase(ds.Tables[0].Rows[i]["Size"].ToString(), bodyFont));
                 * //cell4.BackgroundColor = TabelHeaderBackGroundColor;
                 * cell4i.HorizontalAlignment = 1;
                 * itemTable.AddCell(cell4i);
                 */

                PdfPCell cell5i = new PdfPCell(new Phrase(ds.Tables[0].Rows[i]["Quantity1"].ToString(), bodyFont));
                //cell5.BackgroundColor = TabelHeaderBackGroundColor;
                cell5i.HorizontalAlignment = 1;
                itemTable.AddCell(cell5i);

                //    PdfPCell cell3i = new PdfPCell(new Phrase("" + dtOrderProducts.Rows[i]["Amount"], bodyFont));
                //    //cell3.BackgroundColor = TabelHeaderBackGroundColor;
                //    cell3i.HorizontalAlignment = 1;
                //    itemTable.AddCell(cell3i);
            }



            PdfPCell nesthousingn3 = new PdfPCell(itemTable);
            //  PdfPCell nesthousingn4 = new PdfPCell(totalTable);


            //nesthousingn.Border = Rectangle.NO_BORDER;

            //nesthousingn.PaddingBottom = 10f;
            Invoicetable2.AddCell(nesthousingn3);
            // Invoicetable2.AddCell(nesthousingn4);
            // pdfDoc.Add(Invoicetable2);
            #endregion



            PdfPTable noTable1 = new PdfPTable(2);

            noTable1.HorizontalAlignment = 0;
            noTable1.WidthPercentage     = 100;
            // itemTable.SetWidths(new float[] {2,30,6,6,6,6,6,6,6,6,6,4,4,7 });  // then set the column's __relative__ widths
            //amtTable.SetWidths(new float[] { 4, 30});
            // amtTable.SpacingAfter = 10;

            noTable1.DefaultCell.Border = 0;


            PdfPCell cellnote1 = new PdfPCell(new Phrase("PREPARED BY\nNAME : " + "\nSIGNATURE : " + "\nDATE & TIME : ", EmailFont));
            cellnote1.Border = 0;
            cellnote1.HorizontalAlignment = 0;//0=Left, 1=Centre, 2=Right


            noTable1.AddCell(cellnote1);



            PdfPCell cellnote3 = new PdfPCell(new Phrase("FOR MORYA TOOLS\n\n\n\nAUTHORIZED SIGNATORY", EmailFont));
            cellnote3.Border = 0;
            cellnote3.HorizontalAlignment = 2;//0=Left, 1=Centre, 2=Right


            noTable1.AddCell(cellnote3);



            PdfPCell nesthousingn5 = new PdfPCell(noTable1);
            Invoicetable2.AddCell(nesthousingn5);



            pdfDoc.Add(Invoicetable2);
            pdfDoc.Close();



            DownloadPDF(PDFData, po);



            Context.Response.Clear();
            Context.Response.ContentType = "application/json";
            Context.Response.Flush();
            Context.Response.Write(finalResult);
            Context.Response.End();



            //}
        }
        catch { }
        finally { con.Close(); }

        return(flag);
    }
Exemplo n.º 5
0
        public ActionResult CashFlowIndirect(String StartDate, String EndDate, Int32 CompanyId)
        {
            // ============
            // PDF Settings
            // ============
            MemoryStream workStream = new MemoryStream();
            Rectangle    rectangle  = new Rectangle(PageSize.A3);
            Document     document   = new Document(rectangle, 72, 72, 72, 72);

            document.SetMargins(30f, 30f, 30f, 30f);
            PdfWriter.GetInstance(document, workStream).CloseStream = false;

            document.Open();

            // ===================
            // Fonts Customization
            // ===================
            Font fontArial17Bold = FontFactory.GetFont("Arial", 17, Font.BOLD);
            Font fontArial11     = FontFactory.GetFont("Arial", 11);
            Font fontArial10Bold = FontFactory.GetFont("Arial", 10, Font.BOLD);
            Font fontArial10     = FontFactory.GetFont("Arial", 10);
            Font fontArial11Bold = FontFactory.GetFont("Arial", 11, Font.BOLD);

            Paragraph line = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 4.5F)));

            // ==============
            // Company Detail
            // ==============
            var companyName = (from d in db.MstCompanies where d.Id == CompanyId select d.Company).SingleOrDefault();
            var address     = (from d in db.MstCompanies where d.Id == CompanyId select d.Address).SingleOrDefault();
            var contactNo   = (from d in db.MstCompanies where d.Id == CompanyId select d.ContactNumber).SingleOrDefault();

            // ======
            // Header
            // ======
            PdfPTable header = new PdfPTable(2);

            float[] widthsCellsHeader = new float[] { 100f, 75f };
            header.SetWidths(widthsCellsHeader);
            header.WidthPercentage = 100;
            header.AddCell(new PdfPCell(new Phrase(companyName, fontArial17Bold))
            {
                Border = 0
            });
            header.AddCell(new PdfPCell(new Phrase("Cash Flow (Indirect)", fontArial17Bold))
            {
                Border = 0, HorizontalAlignment = 2
            });
            header.AddCell(new PdfPCell(new Phrase(address, fontArial11))
            {
                Border = 0, PaddingTop = 5f
            });
            header.AddCell(new PdfPCell(new Phrase("Date From " + Convert.ToDateTime(StartDate).ToString("MM-dd-yyyy", CultureInfo.InvariantCulture) + " to " + Convert.ToDateTime(EndDate).ToString("MM-dd-yyyy", CultureInfo.InvariantCulture), fontArial11))
            {
                Border = 0, PaddingTop = 5f, HorizontalAlignment = 2,
            });
            header.AddCell(new PdfPCell(new Phrase(contactNo, fontArial11))
            {
                Border = 0, PaddingTop = 5f
            });
            header.AddCell(new PdfPCell(new Phrase("Date Printed: " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToString("hh:mm:ss tt"), fontArial11))
            {
                Border = 0, PaddingTop = 5f, HorizontalAlignment = 2
            });
            document.Add(header);
            document.Add(line);

            // =====
            // Space
            // =====
            PdfPTable spaceTable = new PdfPTable(1);

            float[] widthCellsSpaceTable = new float[] { 100f };
            spaceTable.SetWidths(widthCellsSpaceTable);
            spaceTable.WidthPercentage = 100;
            spaceTable.AddCell(new PdfPCell(new Phrase(" ", fontArial10Bold))
            {
                Border = 0, PaddingTop = 5f
            });
            document.Add(spaceTable);

            // ======================
            // Default Income Account
            // ======================
            var identityUserId = User.Identity.GetUserId();
            var mstUserId      = from d in db.MstUsers where d.UserId == identityUserId select d;
            var incomeAccount  = from d in db.MstAccounts where d.Id == mstUserId.FirstOrDefault().IncomeAccountId select d;

            // ================
            // Cash Flow Income
            // ================
            var cashFlowIncome = from d in db.TrnJournals
                                 where d.MstBranch.CompanyId == CompanyId &&
                                 d.JournalDate >= Convert.ToDateTime(StartDate) &&
                                 d.JournalDate <= Convert.ToDateTime(EndDate) &&
                                 (d.MstAccount.MstAccountType.AccountCategoryId == 5 || d.MstAccount.MstAccountType.AccountCategoryId == 6)
                                 select new
            {
                AccountCashFlowCode = d.MstAccount.MstAccountCashFlow.AccountCashFlowCode,
                AccountCashFlow     = d.MstAccount.MstAccountCashFlow.AccountCashFlow,
                AccountTypeCode     = d.MstAccount.MstAccountType.AccountTypeCode,
                AccountType         = d.MstAccount.MstAccountType.AccountType,
                AccountCode         = d.MstAccount.AccountCode,
                Account             = d.MstAccount.Account,
                DebitAmount         = d.DebitAmount,
                CreditAmount        = d.CreditAmount
            };

            // =======================
            // Cash Flow Balance Sheet
            // =======================
            var cashFlowBalanceSheet = from d in db.TrnJournals
                                       where d.MstBranch.CompanyId == CompanyId &&
                                       d.JournalDate >= Convert.ToDateTime(StartDate) &&
                                       d.JournalDate <= Convert.ToDateTime(EndDate) &&
                                       d.MstAccount.MstAccountType.AccountCategoryId < 5 &&
                                       d.MstAccount.AccountCashFlowId <= 3
                                       select new
            {
                AccountCashFlowCode = d.MstAccount.MstAccountCashFlow.AccountCashFlowCode,
                AccountCashFlow     = d.MstAccount.MstAccountCashFlow.AccountCashFlow,
                AccountTypeCode     = d.MstAccount.MstAccountType.AccountTypeCode,
                AccountType         = d.MstAccount.MstAccountType.AccountType,
                AccountCode         = d.MstAccount.AccountCode,
                Account             = d.MstAccount.Account,
                DebitAmount         = d.DebitAmount,
                CreditAmount        = d.CreditAmount
            };

            // ==========
            // Cash Flows
            // ==========
            var groupedCashFlowIncome = from d in cashFlowIncome
                                        group d by new
            {
                AccountCashFlowCode = d.AccountCashFlowCode,
                AccountCashFlow     = d.AccountCashFlow
            } into g
                select new
            {
                AccountCashFlowCode = g.Key.AccountCashFlowCode,
                AccountCashFlow     = g.Key.AccountCashFlow
            };

            var groupedCashFlowBalanceSheet = from d in cashFlowBalanceSheet
                                              group d by new
            {
                AccountCashFlowCode = d.AccountCashFlowCode,
                AccountCashFlow     = d.AccountCashFlow
            } into g
                select new
            {
                AccountCashFlowCode = g.Key.AccountCashFlowCode,
                AccountCashFlow     = g.Key.AccountCashFlow
            };

            // ================
            // Union Cash Flows
            // ================
            var unionCashFlows = groupedCashFlowIncome.Union(groupedCashFlowBalanceSheet).OrderBy(d => d.AccountCashFlowCode);

            if (unionCashFlows.Any())
            {
                Decimal totalCashFlowOfAllBranches = 0;

                foreach (var unionCashFlow in unionCashFlows)
                {
                    PdfPTable tableCashFlow           = new PdfPTable(3);
                    float[]   widthCellsTableCashFlow = new float[] { 50f, 100f, 50f };
                    tableCashFlow.SetWidths(widthCellsTableCashFlow);
                    tableCashFlow.WidthPercentage = 100;
                    tableCashFlow.AddCell(new PdfPCell(new Phrase(unionCashFlow.AccountCashFlow, fontArial10Bold))
                    {
                        Colspan = 3, Border = 0, HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 6f, PaddingLeft = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                    });
                    document.Add(tableCashFlow);

                    // =============
                    // Account Types
                    // =============
                    var groupedAccountTypesIncome = from d in cashFlowIncome
                                                    group d by new
                    {
                        AccountCashFlowCode = d.AccountCashFlowCode,
                        AccountCashFlow     = d.AccountCashFlow,
                        AccountTypeCode     = incomeAccount.FirstOrDefault().MstAccountType.AccountTypeCode,
                        AccountType         = incomeAccount.FirstOrDefault().MstAccountType.AccountType,
                        AccountCode         = "0000",
                        Account             = incomeAccount.FirstOrDefault().Account,
                    } into g
                        select new
                    {
                        AccountCashFlowCode = g.Key.AccountCashFlowCode,
                        AccountCashFlow     = g.Key.AccountCashFlow,
                        AccountTypeCode     = g.Key.AccountTypeCode,
                        AccountType         = g.Key.AccountType,
                        AccountCode         = g.Key.AccountCode,
                        Account             = g.Key.Account,
                        DebitAmount         = g.Sum(d => d.DebitAmount),
                        CreditAmount        = g.Sum(d => d.CreditAmount),
                        Balance             = g.Sum(d => d.CreditAmount - d.DebitAmount)
                    };

                    var groupedAccountTypesBalanceSheet = from d in cashFlowBalanceSheet
                                                          group d by new
                    {
                        AccountCashFlowCode = d.AccountCashFlowCode,
                        AccountCashFlow     = d.AccountCashFlow,
                        AccountTypeCode     = d.AccountTypeCode,
                        AccountType         = d.AccountType,
                        AccountCode         = d.AccountCode,
                        Account             = d.Account
                    } into g
                        select new
                    {
                        AccountCashFlowCode = g.Key.AccountCashFlowCode,
                        AccountCashFlow     = g.Key.AccountCashFlow,
                        AccountTypeCode     = g.Key.AccountTypeCode,
                        AccountType         = g.Key.AccountType,
                        AccountCode         = g.Key.AccountCode,
                        Account             = g.Key.Account,
                        DebitAmount         = g.Sum(d => d.DebitAmount),
                        CreditAmount        = g.Sum(d => d.CreditAmount),
                        Balance             = g.Sum(d => d.CreditAmount - d.DebitAmount)
                    };

                    var unionAccountTypes = groupedAccountTypesIncome.Union(groupedAccountTypesBalanceSheet).Where(d => d.AccountCashFlow.Equals(unionCashFlow.AccountCashFlow)).OrderBy(d => d.AccountCode);

                    if (unionAccountTypes.Any())
                    {
                        Decimal totalCashFlow = 0;

                        foreach (var unionAccountType in unionAccountTypes)
                        {
                            PdfPTable tableAccountType           = new PdfPTable(3);
                            float[]   widthCellsTableAccountType = new float[] { 50f, 100f, 50f };
                            tableAccountType.SetWidths(widthCellsTableAccountType);
                            tableAccountType.WidthPercentage = 100;
                            tableAccountType.AddCell(new PdfPCell(new Phrase(unionAccountType.AccountType, fontArial10Bold))
                            {
                                Colspan = 3, Border = 0, HorizontalAlignment = 0, PaddingTop = 10f, PaddingBottom = 5f, PaddingLeft = 25f
                            });
                            document.Add(tableAccountType);

                            // ========
                            // Accounts
                            // ========
                            var groupedAccountIncome = from d in groupedAccountTypesIncome
                                                       where d.AccountCode.Equals(unionAccountType.AccountCode)
                                                       group d by new
                            {
                                AccountCashFlowCode = d.AccountCashFlowCode,
                                AccountCashFlow     = d.AccountCashFlow,
                                AccountTypeCode     = incomeAccount.FirstOrDefault().MstAccountType.AccountTypeCode,
                                AccountType         = incomeAccount.FirstOrDefault().MstAccountType.AccountType,
                                AccountCode         = "0000",
                                Account             = incomeAccount.FirstOrDefault().Account,
                            } into g
                                select new
                            {
                                AccountCashFlowCode = g.Key.AccountCashFlowCode,
                                AccountCashFlow     = g.Key.AccountCashFlow,
                                AccountTypeCode     = g.Key.AccountTypeCode,
                                AccountType         = g.Key.AccountType,
                                AccountCode         = g.Key.AccountCode,
                                Account             = g.Key.Account,
                                DebitAmount         = g.Sum(d => d.DebitAmount),
                                CreditAmount        = g.Sum(d => d.CreditAmount),
                                Balance             = g.Sum(d => d.CreditAmount - d.DebitAmount)
                            };

                            var groupedAccountBalanceSheet = from d in groupedAccountTypesBalanceSheet
                                                             where d.AccountCode.Equals(unionAccountType.AccountCode)
                                                             group d by new
                            {
                                AccountCashFlowCode = d.AccountCashFlowCode,
                                AccountCashFlow     = d.AccountCashFlow,
                                AccountTypeCode     = d.AccountTypeCode,
                                AccountType         = d.AccountType,
                                AccountCode         = d.AccountCode,
                                Account             = d.Account
                            } into g
                                select new
                            {
                                AccountCashFlowCode = g.Key.AccountCashFlowCode,
                                AccountCashFlow     = g.Key.AccountCashFlow,
                                AccountTypeCode     = g.Key.AccountTypeCode,
                                AccountType         = g.Key.AccountType,
                                AccountCode         = g.Key.AccountCode,
                                Account             = g.Key.Account,
                                DebitAmount         = g.Sum(d => d.DebitAmount),
                                CreditAmount        = g.Sum(d => d.CreditAmount),
                                Balance             = g.Sum(d => d.CreditAmount - d.DebitAmount)
                            };

                            var unionAccountGroups = groupedAccountIncome.Union(groupedAccountBalanceSheet).OrderBy(d => d.AccountCode);

                            if (unionAccountGroups.Any())
                            {
                                foreach (var unionAccountGroup in unionAccountGroups)
                                {
                                    PdfPTable tableAccount           = new PdfPTable(3);
                                    float[]   widthCellsTableAccount = new float[] { 50f, 100f, 50f };
                                    tableAccount.SetWidths(widthCellsTableAccount);
                                    tableAccount.WidthPercentage = 100;
                                    tableAccount.AddCell(new PdfPCell(new Phrase(unionAccountGroup.AccountCode, fontArial10))
                                    {
                                        Border = 0, HorizontalAlignment = 0, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f, PaddingLeft = 50f
                                    });
                                    tableAccount.AddCell(new PdfPCell(new Phrase(unionAccountGroup.Account, fontArial10))
                                    {
                                        Border = 0, HorizontalAlignment = 0, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f, PaddingLeft = 20f
                                    });
                                    tableAccount.AddCell(new PdfPCell(new Phrase(unionAccountGroup.Balance.ToString("#,##0.00"), fontArial10))
                                    {
                                        Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                                    });
                                    document.Add(tableAccount);

                                    totalCashFlow += unionAccountGroup.Balance;
                                }
                            }
                        }

                        // ===============
                        // Total Cash Flow
                        // ===============
                        document.Add(line);

                        PdfPTable tableTotalCashFlow           = new PdfPTable(5);
                        float[]   widthCellsTableTotalCashFlow = new float[] { 50f, 70f, 100f, 100f, 60f };
                        tableTotalCashFlow.SetWidths(widthCellsTableTotalCashFlow);
                        tableTotalCashFlow.WidthPercentage = 100;
                        tableTotalCashFlow.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                        {
                            Border = 0, HorizontalAlignment = 0, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f, PaddingLeft = 50f
                        });
                        tableTotalCashFlow.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                        {
                            Border = 0, HorizontalAlignment = 0, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f, PaddingLeft = 50f
                        });
                        tableTotalCashFlow.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                        {
                            Border = 0, HorizontalAlignment = 0, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f, PaddingLeft = 50f
                        });
                        tableTotalCashFlow.AddCell(new PdfPCell(new Phrase("Total " + unionCashFlow.AccountCashFlow, fontArial10Bold))
                        {
                            Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f, PaddingLeft = 20f
                        });
                        tableTotalCashFlow.AddCell(new PdfPCell(new Phrase(totalCashFlow.ToString("#,##0.00"), fontArial10Bold))
                        {
                            Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f
                        });
                        document.Add(tableTotalCashFlow);
                        document.Add(Chunk.NEWLINE);

                        totalCashFlowOfAllBranches = totalCashFlowOfAllBranches + totalCashFlow;
                    }
                }

                // ===============================
                // Total Cash Flow of All Branches
                // ===============================
                document.Add(line);

                PdfPTable tableCashFlowTotalAllBranches           = new PdfPTable(5);
                float[]   widthCellsTableCashFlowTotalAllBranches = new float[] { 50f, 70f, 100f, 100f, 60f };
                tableCashFlowTotalAllBranches.SetWidths(widthCellsTableCashFlowTotalAllBranches);
                tableCashFlowTotalAllBranches.WidthPercentage = 100;
                tableCashFlowTotalAllBranches.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                {
                    Border = 0, HorizontalAlignment = 0, Rowspan = 2, PaddingTop = 5f, PaddingBottom = 5f, PaddingLeft = 50f
                });
                tableCashFlowTotalAllBranches.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                {
                    Border = 0, HorizontalAlignment = 0, Rowspan = 2, PaddingTop = 5f, PaddingBottom = 5f, PaddingLeft = 50f
                });
                tableCashFlowTotalAllBranches.AddCell(new PdfPCell(new Phrase("", fontArial10Bold))
                {
                    Border = 0, HorizontalAlignment = 0, Rowspan = 2, PaddingTop = 5f, PaddingBottom = 5f, PaddingLeft = 50f
                });
                tableCashFlowTotalAllBranches.AddCell(new PdfPCell(new Phrase("All Branches Cash Balance ", fontArial10Bold))
                {
                    Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 5f, PaddingBottom = 5f, PaddingLeft = 20f
                });
                tableCashFlowTotalAllBranches.AddCell(new PdfPCell(new Phrase(totalCashFlowOfAllBranches.ToString("#,##0.00"), fontArial10Bold))
                {
                    Border = 0, HorizontalAlignment = 2, Rowspan = 2, PaddingTop = 5f, PaddingBottom = 5f
                });
                document.Add(tableCashFlowTotalAllBranches);
            }

            document.Close();

            byte[] byteInfo = workStream.ToArray();
            workStream.Write(byteInfo, 0, byteInfo.Length);
            workStream.Position = 0;

            return(new FileStreamResult(workStream, "application/pdf"));
        }
Exemplo n.º 6
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            //Creating iTextSharp Table from the DataTable data
            PdfPTable pdfTable = new PdfPTable(dgvSickChrt.ColumnCount - 3); //avoiding unnessary column

            pdfTable.DefaultCell.Padding     = 3;
            pdfTable.WidthPercentage         = 95;
            pdfTable.HorizontalAlignment     = Element.ALIGN_RIGHT;
            pdfTable.DefaultCell.BorderWidth = 1;

            //Adding Topic on top of pdf
            string    header = @"       Sick Chart";
            Paragraph p0     = new Paragraph();

            p0.Font = FontFactory.GetFont(FontFactory.HELVETICA, 25f, BaseColor.BLUE);
            p0.Add(header);

            string    header1 = @"                          Issue Date  :" + DateTime.Now.ToString();
            Paragraph p1      = new Paragraph();

            p1.Font = FontFactory.GetFont(FontFactory.HELVETICA, 8f, BaseColor.BLUE);
            p1.Add(header1);

            Paragraph p5 = new Paragraph(" ");

            p5.Font = FontFactory.GetFont(FontFactory.HELVETICA, 15f, BaseColor.BLACK);

            //Add Header row by avoiding unnessary column
            for (int j = 3; j < dgvSickChrt.Columns.Count; j++)
            {
                PdfPCell cell = new PdfPCell(new Phrase(dgvSickChrt.Columns[j].HeaderText));
                cell.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240);
                pdfTable.AddCell(cell);
            }

            //Adding DataRow
            foreach (DataGridViewRow row in dgvSickChrt.Rows)
            {
                for (int j = 3; j < dgvSickChrt.Columns.Count; j++)
                {
                    pdfTable.AddCell(row.Cells[j].Value.ToString());
                }
            }

            //Exporting to PDF
            string folderPath = "";
            FolderBrowserDialog directchoosedlg = new FolderBrowserDialog();

            if (directchoosedlg.ShowDialog() == DialogResult.OK)
            {
                folderPath = directchoosedlg.SelectedPath;
            }
            ///////////
            if (!(folderPath.Equals("")))
            {
                try
                {                                                                                                             //Add what we created things into document is defined pdfDoc
                    String   date   = DateTime.Now.ToString().Replace(" ", String.Empty).Replace(":", "_").Replace("/", "_"); //Covert to date string as a valid pdf name
                    Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
                    PdfWriter.GetInstance(pdfDoc, new FileStream(folderPath + "/" + "PDF_" + date + ".pdf", FileMode.Create));
                    pdfDoc.Open();
                    pdfDoc.Add(p0);
                    pdfDoc.Add(p1);
                    pdfDoc.Add(p5);
                    pdfDoc.Add(pdfTable);
                    pdfDoc.Close();

                    MessageBox.Show("Successfully saved ");
                }
                catch (IOException)
                {
                    MessageBox.Show("Pdf file already exist same name(Please Delete it or Select another path)");
                }
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// (non-Javadoc)
        /// @see com.lowagie.text.rtf.parser.properties.RtfPropertyListener#beforeChange(java.lang.String)
        /// </summary>
        public void BeforePropertyChange(string propertyName)
        {
            // do we have any text to do anything with?
            // if not, then just return without action.
            if (_buffer.Length == 0)
            {
                return;
            }

            if (propertyName.StartsWith(RtfProperty.CHARACTER))
            {
                // this is a character change,
                // add a new chunck to the current paragraph using current character settings.
                var chunk = new Chunk();
                chunk.Append(_buffer.ToString());
                _buffer = new StringBuilder(255);
                var charProperties = RtfParser.GetState().Properties.GetProperties(RtfProperty.CHARACTER);
                var defFont        = (string)charProperties[RtfProperty.CHARACTER_FONT];
                if (defFont == null)
                {
                    defFont = "0";
                }

                var fontTable = (RtfDestinationFontTable)RtfParser.GetDestination("fonttbl");
                var currFont  = fontTable.GetFont(defFont);
                var fs        = Font.NORMAL;
                if (charProperties.ContainsKey(RtfProperty.CHARACTER_BOLD))
                {
                    fs |= Font.BOLD;
                }

                if (charProperties.ContainsKey(RtfProperty.CHARACTER_ITALIC))
                {
                    fs |= Font.ITALIC;
                }

                if (charProperties.ContainsKey(RtfProperty.CHARACTER_UNDERLINE))
                {
                    fs |= Font.UNDERLINE;
                }

                var useFont = FontFactory.GetFont(currFont.Familyname, 12, fs, new BaseColor(0, 0, 0));

                chunk.Font = useFont;
                if (_iTextParagraph == null)
                {
                    _iTextParagraph = new Paragraph();
                }

                _iTextParagraph.Add(chunk);
            }
            else
            {
                if (propertyName.StartsWith(RtfProperty.PARAGRAPH))
                {
                    // this is a paragraph change. what do we do?
                }
                else
                {
                    if (propertyName.StartsWith(RtfProperty.SECTION))
                    {
                    }
                    else
                    {
                        if (propertyName.StartsWith(RtfProperty.DOCUMENT))
                        {
                        }
                    }
                }
            }
        }
Exemplo n.º 8
0
        public ActionResult ChartOfAccounts()
        {
            // ============
            // PDF Settings
            // ============
            MemoryStream workStream = new MemoryStream();
            Rectangle    rectangle  = new Rectangle(PageSize.A3);
            Document     document   = new Document(rectangle, 72, 72, 72, 72);

            document.SetMargins(30f, 30f, 30f, 30f);
            PdfWriter.GetInstance(document, workStream).CloseStream = false;

            document.Open();

            // ===================
            // Fonts Customization
            // ===================
            Font fontArial17Bold = FontFactory.GetFont("Arial", 17, Font.BOLD);
            Font fontArial11     = FontFactory.GetFont("Arial", 11);
            Font fontArial10Bold = FontFactory.GetFont("Arial", 10, Font.BOLD);
            Font fontArial10     = FontFactory.GetFont("Arial", 10);
            Font fontArial11Bold = FontFactory.GetFont("Arial", 11, Font.BOLD);
            Font fontArial12Bold = FontFactory.GetFont("Arial", 12, Font.BOLD);

            Paragraph line = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 4.5F)));

            var identityUserId  = User.Identity.GetUserId();
            var currentUser     = from d in db.MstUsers where d.UserId == identityUserId select d;
            var currentBranchId = currentUser.FirstOrDefault().BranchId;

            // ==============
            // Company Detail
            // ==============
            var companyName = (from d in db.MstBranches where d.Id == currentBranchId select d.MstCompany.Company).SingleOrDefault();
            var address     = (from d in db.MstBranches where d.Id == currentBranchId select d.MstCompany.Address).SingleOrDefault();
            var contactNo   = (from d in db.MstBranches where d.Id == currentBranchId select d.MstCompany.ContactNumber).SingleOrDefault();
            var branch      = (from d in db.MstBranches where d.Id == currentBranchId select d.Branch).SingleOrDefault();

            // ===========
            // Header Page
            // ===========
            PdfPTable headerPage = new PdfPTable(2);

            float[] widthsCellsHeaderPage = new float[] { 100f, 75f };
            headerPage.SetWidths(widthsCellsHeaderPage);
            headerPage.WidthPercentage = 100;
            headerPage.AddCell(new PdfPCell(new Phrase(companyName, fontArial17Bold))
            {
                Border = 0
            });
            headerPage.AddCell(new PdfPCell(new Phrase("Chart of Accounts", fontArial17Bold))
            {
                Border = 0, HorizontalAlignment = 2
            });
            headerPage.AddCell(new PdfPCell(new Phrase(address, fontArial11))
            {
                Border = 0, PaddingTop = 5f
            });
            headerPage.AddCell(new PdfPCell(new Phrase(branch, fontArial11))
            {
                Border = 0, PaddingTop = 5f, HorizontalAlignment = 2
            });
            headerPage.AddCell(new PdfPCell(new Phrase(contactNo, fontArial11))
            {
                Border = 0, PaddingTop = 5f
            });
            headerPage.AddCell(new PdfPCell(new Phrase("Date Printed: " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToString("hh:mm:ss tt"), fontArial11))
            {
                Border = 0, PaddingTop = 5f, HorizontalAlignment = 2
            });
            document.Add(headerPage);
            document.Add(line);

            // =====
            // Space
            // =====
            PdfPTable spaceTable = new PdfPTable(1);

            float[] widthCellsSpaceTable = new float[] { 100f };
            spaceTable.SetWidths(widthCellsSpaceTable);
            spaceTable.WidthPercentage = 100;
            spaceTable.AddCell(new PdfPCell(new Phrase(" ", fontArial10Bold))
            {
                Border = 0, PaddingTop = 5f
            });
            document.Add(spaceTable);

            // ==================
            // Account Categories
            // ==================
            var accountCategories = from d in db.MstAccountCategories
                                    group d by new
            {
                AccountCategoryCode = d.AccountCategoryCode,
                AccountCategory     = d.AccountCategory
            } into g
                select new
            {
                AccountCategoryCode = g.Key.AccountCategoryCode,
                AccountCategory     = g.Key.AccountCategory
            };

            if (accountCategories.Any())
            {
                foreach (var accountCategory in accountCategories)
                {
                    PdfPTable tableAccountCategory            = new PdfPTable(1);
                    float[]   widthscellsTableAccountCategory = new float[] { 100f };
                    tableAccountCategory.SetWidths(widthscellsTableAccountCategory);
                    tableAccountCategory.WidthPercentage = 100;
                    tableAccountCategory.AddCell(new PdfPCell(new Phrase(accountCategory.AccountCategory, fontArial11))
                    {
                        HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, Border = 0, BackgroundColor = BaseColor.LIGHT_GRAY
                    });
                    document.Add(tableAccountCategory);

                    // ======================
                    // Account Sub Categories
                    // ======================
                    var accountSubCategories = from d in db.MstAccountTypes
                                               where d.MstAccountCategory.AccountCategory.Equals(accountCategory.AccountCategory)
                                               group d by new
                    {
                        SubCategoryDescription = d.SubCategoryDescription
                    } into g
                        select new
                    {
                        SubCategoryDescription = g.Key.SubCategoryDescription
                    };

                    if (accountSubCategories.Any())
                    {
                        foreach (var accountSubCategory in accountSubCategories)
                        {
                            PdfPTable tableSubAccountCategory            = new PdfPTable(1);
                            float[]   widthscellsTableSubAccountCategory = new float[] { 100f };
                            tableSubAccountCategory.SetWidths(widthscellsTableSubAccountCategory);
                            tableSubAccountCategory.WidthPercentage = 100;
                            tableSubAccountCategory.AddCell(new PdfPCell(new Phrase(accountSubCategory.SubCategoryDescription, fontArial11))
                            {
                                HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingLeft = 20f, Border = 0
                            });
                            document.Add(tableSubAccountCategory);

                            // =============
                            // Account Types
                            // =============
                            var accountTypes = from d in db.MstAccountTypes
                                               where d.SubCategoryDescription.Equals(accountSubCategory.SubCategoryDescription)
                                               group d by new
                            {
                                AccountType = d.AccountType
                            } into g
                                select new
                            {
                                AccountType = g.Key.AccountType
                            };

                            if (accountTypes.Any())
                            {
                                foreach (var accountType in accountTypes)
                                {
                                    PdfPTable tableAccountType            = new PdfPTable(1);
                                    float[]   widthscellsTableAccountType = new float[] { 100f };
                                    tableAccountType.SetWidths(widthscellsTableAccountType);
                                    tableAccountType.WidthPercentage = 100;
                                    tableAccountType.AddCell(new PdfPCell(new Phrase(accountType.AccountType, fontArial11))
                                    {
                                        HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingLeft = 40f, Border = 0
                                    });
                                    document.Add(tableAccountType);

                                    // ========
                                    // Accounts
                                    // ========
                                    var accounts = from d in db.MstAccounts
                                                   where d.MstAccountType.AccountType.Equals(accountType.AccountType)
                                                   select new
                                    {
                                        AccountCode = d.AccountCode,
                                        Account     = d.Account
                                    };

                                    if (accounts.Any())
                                    {
                                        foreach (var account in accounts)
                                        {
                                            PdfPTable tableAccount            = new PdfPTable(2);
                                            float[]   widthscellsTableAccount = new float[] { 20f, 100f };
                                            tableAccount.SetWidths(widthscellsTableAccount);
                                            tableAccount.WidthPercentage = 100;
                                            tableAccount.AddCell(new PdfPCell(new Phrase(account.AccountCode, fontArial11))
                                            {
                                                HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 5f, PaddingLeft = 60f, Border = 0
                                            });
                                            tableAccount.AddCell(new PdfPCell(new Phrase(account.Account, fontArial11))
                                            {
                                                HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingLeft = 10f, Border = 0
                                            });
                                            document.Add(tableAccount);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            document.Close();

            byte[] byteInfo = workStream.ToArray();
            workStream.Write(byteInfo, 0, byteInfo.Length);
            workStream.Position = 0;

            return(new FileStreamResult(workStream, "application/pdf"));
        }
        public ActionResult StockInBook(String StartDate, String EndDate, Int32 CompanyId, Int32 BranchId)
        {
            // ============
            // PDF Settings
            // ============
            MemoryStream workStream = new MemoryStream();
            Rectangle    rectangle  = new Rectangle(PageSize.A3);
            Document     document   = new Document(rectangle, 72, 72, 72, 72);

            document.SetMargins(30f, 30f, 30f, 30f);
            PdfWriter.GetInstance(document, workStream).CloseStream = false;

            document.Open();

            // ===================
            // Fonts Customization
            // ===================
            Font fontArial17Bold = FontFactory.GetFont("Arial", 17, Font.BOLD);
            Font fontArial11     = FontFactory.GetFont("Arial", 11);
            Font fontArial10Bold = FontFactory.GetFont("Arial", 10, Font.BOLD);
            Font fontArial10     = FontFactory.GetFont("Arial", 10);
            Font fontArial11Bold = FontFactory.GetFont("Arial", 11, Font.BOLD);
            Font fontArial12Bold = FontFactory.GetFont("Arial", 12, Font.BOLD);

            Paragraph line = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 4.5F)));

            // ==============
            // Company Detail
            // ==============
            var companyName = (from d in db.MstBranches where d.Id == Convert.ToInt32(BranchId) select d.MstCompany.Company).FirstOrDefault();
            var address     = (from d in db.MstBranches where d.Id == Convert.ToInt32(BranchId) select d.MstCompany.Address).FirstOrDefault();
            var contactNo   = (from d in db.MstBranches where d.Id == Convert.ToInt32(BranchId) select d.MstCompany.ContactNumber).FirstOrDefault();
            var branch      = (from d in db.MstBranches where d.Id == Convert.ToInt32(BranchId) select d.Branch).FirstOrDefault();

            // ===========
            // Header Page
            // ===========
            PdfPTable headerPage = new PdfPTable(2);

            float[] widthsCellsHeaderPage = new float[] { 100f, 75f };
            headerPage.SetWidths(widthsCellsHeaderPage);
            headerPage.WidthPercentage = 100;
            headerPage.AddCell(new PdfPCell(new Phrase(companyName, fontArial17Bold))
            {
                Border = 0
            });
            headerPage.AddCell(new PdfPCell(new Phrase("Stock-In Book", fontArial17Bold))
            {
                Border = 0, HorizontalAlignment = 2
            });
            headerPage.AddCell(new PdfPCell(new Phrase(address, fontArial11))
            {
                Border = 0, PaddingTop = 5f
            });
            headerPage.AddCell(new PdfPCell(new Phrase("Date From " + Convert.ToDateTime(StartDate).ToString("MM-dd-yyyy", CultureInfo.InvariantCulture) + " to " + Convert.ToDateTime(EndDate).ToString("MM-dd-yyyy", CultureInfo.InvariantCulture), fontArial11))
            {
                Border = 0, PaddingTop = 5f, HorizontalAlignment = 2
            });
            headerPage.AddCell(new PdfPCell(new Phrase(contactNo, fontArial11))
            {
                Border = 0, PaddingTop = 5f
            });
            headerPage.AddCell(new PdfPCell(new Phrase("Date Printed: " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToString("hh:mm:ss tt"), fontArial11))
            {
                Border = 0, PaddingTop = 5f, HorizontalAlignment = 2
            });
            document.Add(headerPage);
            document.Add(line);

            // ========
            // Get Data
            // ========
            var journals = from d in db.TrnJournals
                           where d.JournalDate >= Convert.ToDateTime(StartDate) &&
                           d.JournalDate <= Convert.ToDateTime(EndDate) &&
                           d.MstBranch.CompanyId == CompanyId &&
                           d.BranchId == BranchId &&
                           d.INId != null
                           select new
            {
                DocumentReference = d.DocumentReference,
                AccountCode       = d.MstAccount.AccountCode,
                Account           = d.MstAccount.Account,
                Article           = d.MstArticle.Article,
                Particulars       = d.Particulars,
                DebitAmount       = d.DebitAmount,
                CreditAmount      = d.CreditAmount
            };

            if (journals.Any())
            {
                // ==================
                // Document Reference
                // ==================
                var documentReferences = from d in journals
                                         group d by new
                {
                    d.DocumentReference
                } into g
                    select new
                {
                    DocumentReference = g.Key.DocumentReference
                };

                if (documentReferences.Any())
                {
                    // ============
                    // Branch Title
                    // ============
                    PdfPTable branchTitle           = new PdfPTable(1);
                    float[]   widthCellsBranchTitle = new float[] { 100f };
                    branchTitle.SetWidths(widthCellsBranchTitle);
                    branchTitle.WidthPercentage = 100;
                    PdfPCell branchHeaderColspan = (new PdfPCell(new Phrase(branch, fontArial12Bold))
                    {
                        Border = 0, HorizontalAlignment = 0, PaddingTop = 10f
                    });
                    branchTitle.AddCell(branchHeaderColspan);
                    document.Add(branchTitle);

                    Decimal totalDebitAmount  = 0;
                    Decimal totalCreditAmount = 0;
                    Decimal totalBalance      = 0;

                    foreach (var documentReference in documentReferences)
                    {
                        PdfPTable tableDocumentReference           = new PdfPTable(1);
                        float[]   widthCellsTableDocumentReference = new float[] { 100f };
                        tableDocumentReference.SetWidths(widthCellsTableDocumentReference);
                        tableDocumentReference.WidthPercentage = 100;
                        tableDocumentReference.AddCell(new PdfPCell(new Phrase(documentReference.DocumentReference, fontArial11Bold))
                        {
                            HorizontalAlignment = 0, PaddingTop = 10f, PaddingBottom = 9f, Border = 0
                        });
                        document.Add(tableDocumentReference);

                        // ====
                        // Data
                        // ====
                        var journalDatas = from d in journals
                                           where d.DocumentReference.Equals(documentReference.DocumentReference)
                                           select new
                        {
                            DocumentReference = d.DocumentReference,
                            AccountCode       = d.AccountCode,
                            Account           = d.Account,
                            Article           = d.Article,
                            Particulars       = d.Particulars,
                            DebitAmount       = d.DebitAmount,
                            CreditAmount      = d.CreditAmount
                        };

                        if (journalDatas.Any())
                        {
                            PdfPTable tableJournalData            = new PdfPTable(6);
                            float[]   widthsCellsTableJournalData = new float[] { 80f, 130f, 150f, 100f, 100f, 100f };
                            tableJournalData.SetWidths(widthsCellsTableJournalData);
                            tableJournalData.WidthPercentage = 100;
                            tableJournalData.AddCell(new PdfPCell(new Phrase("Code", fontArial11Bold))
                            {
                                HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                            });
                            tableJournalData.AddCell(new PdfPCell(new Phrase("Account", fontArial11Bold))
                            {
                                HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                            });
                            tableJournalData.AddCell(new PdfPCell(new Phrase("Article", fontArial11Bold))
                            {
                                HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                            });
                            tableJournalData.AddCell(new PdfPCell(new Phrase("Debit", fontArial11Bold))
                            {
                                HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                            });
                            tableJournalData.AddCell(new PdfPCell(new Phrase("Credit", fontArial11Bold))
                            {
                                HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                            });
                            tableJournalData.AddCell(new PdfPCell(new Phrase("Balance", fontArial11Bold))
                            {
                                HorizontalAlignment = 1, Rowspan = 2, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                            });

                            Decimal subTotalDebitAmount  = 0;
                            Decimal subTotalCreditAmount = 0;
                            Decimal subTotalBalance      = 0;

                            foreach (var journalData in journalDatas)
                            {
                                Decimal balance = journalData.DebitAmount - journalData.CreditAmount;

                                tableJournalData.AddCell(new PdfPCell(new Phrase(journalData.AccountCode, fontArial10))
                                {
                                    HorizontalAlignment = 0, PaddingBottom = 5f, PaddingLeft = 5f, PaddingRight = 5f
                                });
                                tableJournalData.AddCell(new PdfPCell(new Phrase(journalData.Account, fontArial10))
                                {
                                    HorizontalAlignment = 0, PaddingBottom = 5f, PaddingLeft = 5f, PaddingRight = 5f
                                });
                                tableJournalData.AddCell(new PdfPCell(new Phrase(journalData.Article, fontArial10))
                                {
                                    HorizontalAlignment = 0, PaddingBottom = 5f, PaddingLeft = 5f, PaddingRight = 5f
                                });
                                tableJournalData.AddCell(new PdfPCell(new Phrase(journalData.DebitAmount.ToString("#,##0.00"), fontArial10))
                                {
                                    HorizontalAlignment = 2, PaddingBottom = 5f, PaddingLeft = 5f, PaddingRight = 5f
                                });
                                tableJournalData.AddCell(new PdfPCell(new Phrase(journalData.CreditAmount.ToString("#,##0.00"), fontArial10))
                                {
                                    HorizontalAlignment = 2, PaddingBottom = 5f, PaddingLeft = 5f, PaddingRight = 5f
                                });
                                tableJournalData.AddCell(new PdfPCell(new Phrase(balance.ToString("#,##0.00"), fontArial10))
                                {
                                    HorizontalAlignment = 2, PaddingBottom = 5f, PaddingLeft = 5f, PaddingRight = 5f
                                });

                                subTotalDebitAmount  += journalData.DebitAmount;
                                subTotalCreditAmount += journalData.CreditAmount;
                                subTotalBalance      += balance;
                            }

                            tableJournalData.AddCell(new PdfPCell(new Phrase("Sub Total", fontArial10Bold))
                            {
                                Colspan = 3, HorizontalAlignment = 2, PaddingBottom = 5f, PaddingLeft = 5f, PaddingRight = 5f
                            });
                            tableJournalData.AddCell(new PdfPCell(new Phrase(subTotalDebitAmount.ToString("#,##0.00"), fontArial10Bold))
                            {
                                HorizontalAlignment = 2, PaddingBottom = 5f, PaddingLeft = 5f, PaddingRight = 5f
                            });
                            tableJournalData.AddCell(new PdfPCell(new Phrase(subTotalCreditAmount.ToString("#,##0.00"), fontArial10Bold))
                            {
                                HorizontalAlignment = 2, PaddingBottom = 5f, PaddingLeft = 5f, PaddingRight = 5f
                            });
                            tableJournalData.AddCell(new PdfPCell(new Phrase(subTotalBalance.ToString("#,##0.00"), fontArial10Bold))
                            {
                                HorizontalAlignment = 2, PaddingBottom = 5f, PaddingLeft = 5f, PaddingRight = 5f
                            });
                            document.Add(tableJournalData);

                            totalDebitAmount  += subTotalDebitAmount;
                            totalCreditAmount += subTotalCreditAmount;
                            totalBalance      += subTotalBalance;
                        }
                    }

                    document.Add(line);

                    // =====
                    // Total
                    // =====
                    PdfPTable tableTotalFooter           = new PdfPTable(6);
                    float[]   widthCellstableTotalFooter = new float[] { 80f, 130f, 150f, 100f, 100f, 100f };
                    tableTotalFooter.SetWidths(widthCellstableTotalFooter);
                    tableTotalFooter.WidthPercentage = 100;
                    tableTotalFooter.AddCell(new PdfPCell(new Phrase("Total", fontArial10Bold))
                    {
                        Colspan = 3, HorizontalAlignment = 2, Border = 0, PaddingTop = 5f, PaddingBottom = 5f, PaddingLeft = 25f
                    });
                    tableTotalFooter.AddCell(new PdfPCell(new Phrase(totalDebitAmount.ToString("#,##0.00"), fontArial10Bold))
                    {
                        HorizontalAlignment = 2, Border = 0, PaddingTop = 5f, PaddingBottom = 5f
                    });
                    tableTotalFooter.AddCell(new PdfPCell(new Phrase(totalCreditAmount.ToString("#,##0.00"), fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 2, PaddingTop = 5f, PaddingBottom = 5f, PaddingLeft = 50f
                    });
                    tableTotalFooter.AddCell(new PdfPCell(new Phrase(totalBalance.ToString("#,##0.00"), fontArial10Bold))
                    {
                        Border = 0, HorizontalAlignment = 2, PaddingTop = 5f, PaddingBottom = 5f
                    });
                    document.Add(tableTotalFooter);
                }
            }

            // Document End
            document.Close();

            byte[] byteInfo = workStream.ToArray();
            workStream.Write(byteInfo, 0, byteInfo.Length);
            workStream.Position = 0;

            return(new FileStreamResult(workStream, "application/pdf"));
        }
        private void ExportDataTableToPdf(DataTable dt, DateTime setDate, string fileName, string reportName, string logoPath)
        {
            Rectangle rec = new Rectangle(PageSize.A4);

            rec.BackgroundColor = new BaseColor(System.Drawing.Color.Olive);
            Document doc = new Document(rec);

            doc.SetPageSize(PageSize.A4.Rotate());
            PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);

            doc.Open();

            PdfPTable table = new PdfPTable(2);

            table.TotalWidth      = 700f;
            table.WidthPercentage = 100;
            table.LockedWidth     = true;
            table.SetWidths(new float[] { 1f, 2f });
            ////table.SpacingAfter = 20f;
            ////Company Logo
            var cell2 = ImageCell(logoPath, 75f, Element.ALIGN_LEFT, true);

            table.AddCell(cell2);
            doc.Add(table);
            ////Company Name and Address

            var phrase = new Phrase();

            phrase.Add(new Chunk("Xpress Payments\n".ToUpper(), FontFactory.GetFont("Calibri", 16, Font.BOLD, BaseColor.BLACK)));
            phrase.Add(new Chunk(reportName.ToUpper(), FontFactory.GetFont("Calibri", 14, Font.BOLD, BaseColor.BLACK)));

            cell2 = PhraseCell(phrase, Element.ALIGN_CENTER);
            cell2.VerticalAlignment = Element.ALIGN_MIDDLE;
            table.AddCell(cell2);
            doc.Add(table);
            //Creating paragraph for header

            BaseFont bfntHead = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Font     fntHead  = new iTextSharp.text.Font(bfntHead, 16, 1, iTextSharp.text.BaseColor.ORANGE);
            //Paragraph prgHeading = new Paragraph();
            //prgHeading.Alignment = Element.ALIGN_CENTER;
            //prgHeading.Add(new Chunk(logoPath, fntHead));
            //prgHeading.Add(new Chunk("Xpress Payments".ToUpper(), fntHead));
            //doc.Add(prgHeading);

            //Creating sub title
            //iTextSharp.text.Font fntSubTitle = new iTextSharp.text.Font(bfntHead, 12, 1, iTextSharp.text.BaseColor.ORANGE);
            //Paragraph prgSubTitle = new Paragraph();
            //prgSubTitle.Alignment = Element.ALIGN_CENTER;
            //prgSubTitle.Add(new Chunk(reportName.ToUpper(), fntSubTitle));
            //doc.Add(prgSubTitle);

            //Adding paragraph for report generated by
            Paragraph prgGeneratedBY = new Paragraph();
            BaseFont  btnAuthor      = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

            iTextSharp.text.Font fntAuthor = new iTextSharp.text.Font(btnAuthor, 8, 2, iTextSharp.text.BaseColor.BLUE);
            prgGeneratedBY.Alignment = Element.ALIGN_RIGHT;
            //prgGeneratedBY.Add(new Chunk("Report Generated by : ASPArticles", fntAuthor));
            prgGeneratedBY.Add(new Chunk("\nSettlement Date : " + setDate.ToShortDateString(), fntAuthor));
            doc.Add(prgGeneratedBY);

            //Adding a line
            Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, iTextSharp.text.BaseColor.BLACK, Element.ALIGN_LEFT, 1)));

            doc.Add(p);

            //Adding line break
            doc.Add(new Chunk("\n", fntHead));

            //Adding  PdfPTable
            table = new PdfPTable(dt.Columns.Count);
            table.WidthPercentage = 100.0f;
            // Options: Element.ALIGN_LEFT (or 0), Element.ALIGN_CENTER (1), Element.ALIGN_RIGHT (2).
            table.HorizontalAlignment = Element.ALIGN_LEFT;

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                string   cellText = Server.HtmlDecode(dt.Columns[i].ColumnName);
                PdfPCell cell     = new PdfPCell();
                cell.Phrase          = new Phrase(cellText, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 8, 1, new BaseColor(System.Drawing.ColorTranslator.FromHtml("#000000"))));
                cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#ff9800"));
                //cell.Phrase = new Phrase(cellText, new Font(Font.FontFamily.TIMES_ROMAN, 10, 1, new BaseColor(grdStudent.HeaderStyle.ForeColor)));
                //cell.BackgroundColor = new BaseColor(grdStudent.HeaderStyle.BackColor);
                cell.HorizontalAlignment = Element.ALIGN_LEFT;
                //cell.PaddingBottom = 5;
                table.AddCell(cell);
            }

            //writing table Data
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    string   cellText = "";
                    PdfPCell cell     = new PdfPCell();
                    if (dt.Rows[i][j].GetType() == typeof(decimal))
                    {
                        decimal value;
                        var     suc = decimal.TryParse(dt.Rows[i][j].ToString(), out value);
                        if (suc)
                        {
                            cellText = SmartObj.FormatMoney(value.ToString("F"));
                            cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        }
                        else
                        {
                            cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                        }
                    }
                    else if (dt.Rows[i][j].GetType() == typeof(DateTime))
                    {
                        DateTime date;
                        var      suc = DateTime.TryParse(dt.Rows[i][j].ToString(), out date);
                        if (suc)
                        {
                            cellText = date.ToString("dd-MM-yyyy");
                            cell.HorizontalAlignment = Element.ALIGN_LEFT;
                        }
                        else
                        {
                            cell.HorizontalAlignment = Element.ALIGN_LEFT;
                        }
                    }
                    else
                    {
                        cellText = dt.Rows[i][j].ToString();
                        cell.HorizontalAlignment = Element.ALIGN_LEFT;
                    }



                    // cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#ff9800"));
                    //cell.Phrase = new Phrase(cellText, new Font(Font.FontFamily.TIMES_ROMAN, 10, 1, new BaseColor(grdStudent.HeaderStyle.ForeColor)));
                    //cell.BackgroundColor = new BaseColor(grdStudent.HeaderStyle.BackColor);
                    cell.Phrase = new Phrase(cellText, new Font(Font.FontFamily.TIMES_ROMAN, 8, 1, new BaseColor(System.Drawing.ColorTranslator.FromHtml("#000000"))));

                    table.AddCell(cell);
                }
            }

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

            writer.Close();
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;" + string.Format("filename={0}.pdf", fileName));
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Write(doc);
            Response.End();
            //File(doc, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        }
Exemplo n.º 11
0
        public MemoryStream GeneratePdfTemplate(ExpeditionViewModel viewModel, IServiceProvider serviceProvider, int clientTimeZoneOffset /*, IGarmentDeliveryOrderFacade DOfacad*/)
        {
            Font header_font  = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 18);
            Font normal_font  = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 9);
            Font normal_font1 = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);
            Font bold_font    = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 20);
            Font bold_font1   = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);

            Document document = new Document(PageSize.A4, 40, 40, 40, 40);

            document.AddHeader("Header", viewModel.code);
            MemoryStream stream = new MemoryStream();
            PdfWriter    writer = PdfWriter.GetInstance(document, stream);

            writer.PageEvent = new PDFPages();
            document.Open();


            PdfPCell cellLeftNoBorder = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
            };
            PdfPCell cellRightNoBorder = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
            };

            Chunk        chkHeader = new Chunk(" ");
            Phrase       pheader   = new Phrase(chkHeader);
            HeaderFooter header    = new HeaderFooter(pheader, false);

            header.Border    = Rectangle.NO_BORDER;
            header.Alignment = Element.ALIGN_RIGHT;
            document.Header  = header;

            #region Header

            string    titleString = "BON PENGELUARAN BARANG\n\n";
            Paragraph title       = new Paragraph(titleString, bold_font)
            {
                Alignment = Element.ALIGN_CENTER
            };
            document.Add(title);
            bold_font.SetStyle(Font.NORMAL);

            //string addressString = "PT DAN LIRIS" + "\n" + "JL. Merapi No.23" + "\n" + "Banaran, Grogol, Kab. Sukoharjo" + "\n" + "Jawa Tengah 57552 - INDONESIA" + "\n" + "PO.BOX 166 Solo 57100" + "\n" + "Telp. (0271) 740888, 714400" + "\n" + "Fax. (0271) 735222, 740777";
            //Paragraph address = new Paragraph(addressString, bold_font) { Alignment = Element.ALIGN_LEFT };
            //document.Add(address);
            //bold_font.SetStyle(Font.NORMAL);



            PdfPTable tableInternNoteHeader = new PdfPTable(2);
            tableInternNoteHeader.SetWidths(new float[] { 7.5f, 4.5f });
            PdfPCell cellInternNoteHeaderLeft = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
            };
            PdfPCell cellInternNoteHeaderRight = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
            };

            cellInternNoteHeaderLeft.Phrase = new Phrase("PT. MAJOR MINOR KREASI NUSANTARA", bold_font1);
            tableInternNoteHeader.AddCell(cellInternNoteHeaderLeft);

            cellInternNoteHeaderLeft.Phrase = new Phrase("No. Bon" + "       : " + viewModel.code, normal_font);
            tableInternNoteHeader.AddCell(cellInternNoteHeaderLeft);

            cellInternNoteHeaderRight.Phrase = new Phrase("Equity Tower 15th Floor Suite C, SCBD Lot 9, Jl. Jenderal Sudirman Kav 52-53 Jakarta 12190, Indonesia", normal_font);
            tableInternNoteHeader.AddCell(cellInternNoteHeaderRight);

            //cellInternNoteHeaderLeft.Phrase = new Phrase("Password" + "                 : " + viewModel.password, normal_font);
            //tableInternNoteHeader.AddCell(cellInternNoteHeaderLeft);

            //cellInternNoteHeaderRight.Phrase = new Phrase("", normal_font);
            //tableInternNoteHeader.AddCell(cellInternNoteHeaderRight);

            cellInternNoteHeaderLeft.Phrase = new Phrase("Tanggal" + "       : " + viewModel.CreatedUtc.ToString("dd MMMM yyyy", new CultureInfo("id-ID")) + "\n\n\n", normal_font);
            tableInternNoteHeader.AddCell(cellInternNoteHeaderLeft);

            //cellInternNoteHeaderRight.Phrase = new Phrase("Dari" + "                           : " + viewModel.source.name, normal_font);
            //tableInternNoteHeader.AddCell(cellInternNoteHeaderRight);

            //cellInternNoteHeaderLeft.Phrase = new Phrase("", normal_font);
            //tableInternNoteHeader.AddCell(cellInternNoteHeaderLeft);

            string destination = "";
            foreach (var i in viewModel.items)
            {
                destination = i.spkDocsViewModel.destination.name;
            }

            cellInternNoteHeaderRight.Phrase = new Phrase("Tujuan" + "                      : " + destination, normal_font);
            tableInternNoteHeader.AddCell(cellInternNoteHeaderRight);

            cellInternNoteHeaderLeft.Phrase = new Phrase("", normal_font);
            tableInternNoteHeader.AddCell(cellInternNoteHeaderLeft);

            cellInternNoteHeaderRight.Phrase = new Phrase("Ekspedisi" + "                  : " + viewModel.expeditionService.name, normal_font);
            tableInternNoteHeader.AddCell(cellInternNoteHeaderRight);

            cellInternNoteHeaderLeft.Phrase = new Phrase("", normal_font);
            tableInternNoteHeader.AddCell(cellInternNoteHeaderLeft);

            cellInternNoteHeaderRight.Phrase = new Phrase("Total Berat (Kg)" + "        : " + viewModel.weight, normal_font);
            tableInternNoteHeader.AddCell(cellInternNoteHeaderRight);

            cellInternNoteHeaderLeft.Phrase = new Phrase("", normal_font);
            tableInternNoteHeader.AddCell(cellInternNoteHeaderLeft);

            //cellInternNoteHeaderRight.Phrase = new Phrase("Keterangan" + "      : " + "" + "\n\n", normal_font);
            //tableInternNoteHeader.AddCell(cellInternNoteHeaderRight);



            PdfPCell cellInternNoteHeader = new PdfPCell(tableInternNoteHeader); // dont remove
            tableInternNoteHeader.ExtendLastRow = false;
            tableInternNoteHeader.SpacingAfter  = 10f;
            document.Add(tableInternNoteHeader);
            #endregion

            #region Table_Of_Content
            PdfPCell cellCenter = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 5
            };
            PdfPCell cellRight = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 5
            };
            PdfPCell cellLeft = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 5
            };

            PdfPTable tableContent = new PdfPTable(5);
            tableContent.SetWidths(new float[] { 2f, 4f, 5f, 6.5f, 5.5f });
            cellCenter.Phrase = new Phrase("No", bold_font1);
            tableContent.AddCell(cellCenter);
            cellCenter.Phrase = new Phrase("Packing List", bold_font1);
            tableContent.AddCell(cellCenter);
            cellCenter.Phrase = new Phrase("Password", bold_font1);
            tableContent.AddCell(cellCenter);
            cellCenter.Phrase = new Phrase("Berat (Kg)", bold_font1);
            tableContent.AddCell(cellCenter);
            cellCenter.Phrase = new Phrase("Total Barang", bold_font1);
            tableContent.AddCell(cellCenter);


            //double totalPriceTotal = 0;
            double total = 0;



            List <TableContent> TableContents = new List <TableContent>();
            int index = 1;
            foreach (ExpeditionItemViewModel item in viewModel.items)
            {
                foreach (ExpeditionDetailViewModel detail in item.details)
                {
                    total += detail.sendQuantity;
                }

                TableContents.Add(new TableContent
                {
                    No          = index++,
                    PackingList = item.spkDocsViewModel.packingList,
                    Password    = item.spkDocsViewModel.password,
                    Weight      = item.weight,
                    Total       = total.ToString()
                });
                //totalPriceTotal += item.quantity * item.item.domesticSale;
                //total += item.quantity;
            }

            foreach (TableContent c in TableContents.OrderBy(o => o.No))
            {
                cellCenter.Phrase = new Phrase(c.No.ToString(), normal_font1);
                tableContent.AddCell(cellCenter);

                cellCenter.Phrase = new Phrase(c.PackingList, normal_font1);
                tableContent.AddCell(cellCenter);

                cellCenter.Phrase = new Phrase(c.Password, normal_font1);
                tableContent.AddCell(cellCenter);

                cellCenter.Phrase = new Phrase(c.Weight.ToString(), normal_font1);
                tableContent.AddCell(cellCenter);

                cellCenter.Phrase = new Phrase(c.Total, normal_font1);
                tableContent.AddCell(cellCenter);
            }

            PdfPCell cellContent = new PdfPCell(tableContent); // dont remove
            tableContent.ExtendLastRow = false;
            tableContent.SpacingAfter  = 20f;
            document.Add(tableContent);
            #endregion
            #region Total
            PdfPTable tabletotal = new PdfPTable(2);
            tabletotal.SetWidths(new float[] { 17.5f, 5.5f });
            PdfPCell cellTotalContent = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER
            };
            cellTotalContent.Phrase = new Phrase("Total", normal_font1);
            tabletotal.AddCell(cellTotalContent);
            //cellTotalContent.Phrase = new Phrase("" + total, normal_font1);
            //tabletotal.AddCell(cellTotalContent);
            cellTotalContent.Phrase = new Phrase("" + String.Format("{0:n}", total), normal_font1);
            tabletotal.AddCell(cellTotalContent);
            PdfPCell cellTotal = new PdfPCell(tabletotal); // dont remove
            tabletotal.ExtendLastRow = false;
            tabletotal.SpacingBefore = 20f;
            tabletotal.SpacingAfter  = 20f;
            document.Add(tabletotal);
            #endregion
            //PdfPTable tableContent2 = new PdfPTable(3);
            //tableContent2.SetWidths(new float[] { 13f, 4.5f, 5.5f });
            //List<TableContent2> tableContents2 = new List<TableContent2>();
            //tableContents2.Add(new TableContent2
            //{
            //    Total = "Total",
            //    QtyTotal = total.ToString(),
            //    PriceTotal = String.Format("{0:n}", totalPriceTotal.ToString())
            //});
            //foreach (TableContent2 c in tableContents2)
            //{
            //    cellLeft.Phrase = new Phrase(c.Total, normal_font1);
            //    tableContent.AddCell(cellLeft);

            //    cellLeft.Phrase = new Phrase(c.QtyTotal, normal_font1);
            //    tableContent.AddCell(cellLeft);

            //    cellLeft.Phrase = new Phrase(c.PriceTotal, normal_font1);
            //    tableContent.AddCell(cellLeft);
            //}
            //PdfPCell cellContent2 = new PdfPCell(tableContent2); // dont remove
            //tableContent.ExtendLastRow = false;
            //tableContent.SpacingAfter = 20f;
            //document.Add(tableContent);

            //#region Footer

            //PdfPTable tableFooter = new PdfPTable(2);
            //tableFooter.SetWidths(new float[] { 1f, 1f });

            //PdfPTable tableFooterLeft = new PdfPTable(2);
            //tableFooterLeft.SetWidths(new float[] { 3f, 5f });

            //PdfPCell cellInternNoteFooterLeft = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT };
            //PdfPCell cellInternNoteFooterRight = new PdfPCell() { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT };
            ////foreach (var unit in units)
            ////{
            ////    if (unit.Value == 0)
            ////    {

            ////        cellLeftNoBorder.Phrase = new Phrase($"Total {unit.Key}", normal_font);
            ////        tableFooterLeft.AddCell(cellLeftNoBorder);
            ////        cellLeftNoBorder.Phrase = new Phrase($":   -", normal_font);
            ////        tableFooterLeft.AddCell(cellLeftNoBorder);
            ////    }
            ////    else
            ////    {
            ////        cellLeftNoBorder.Phrase = new Phrase($"Total {unit.Key}", normal_font);
            ////        tableFooterLeft.AddCell(cellLeftNoBorder);
            ////        cellLeftNoBorder.Phrase = new Phrase($":   {unit.Value.ToString("n", new CultureInfo("id-ID"))}", normal_font);
            ////        tableFooterLeft.AddCell(cellLeftNoBorder);
            ////    }
            ////}

            //PdfPTable tableFooterRight = new PdfPTable(2);
            //tableFooterRight.SetWidths(new float[] { 5f, 5f });

            ////cellLeftNoBorder.Phrase = new Phrase($"Total Harga Pokok (DPP)", normal_font);
            ////tableFooterRight.AddCell(cellLeftNoBorder);

            ////cellLeftNoBorder.Phrase = new Phrase($": " + totalPriceTotal.ToString("N", new CultureInfo("id-ID")), normal_font);
            ////tableFooterRight.AddCell(cellLeftNoBorder);

            ////cellLeftNoBorder.Phrase = new Phrase("Mata Uang", normal_font);
            ////tableFooterRight.AddCell(cellLeftNoBorder);

            ////cellLeftNoBorder.Phrase = new Phrase($": " + viewModel.currency.Code, normal_font);
            ////tableFooterRight.AddCell(cellLeftNoBorder);

            ////cellLeftNoBorder.Phrase = new Phrase("Total Harga Pokok (Rp)", normal_font);
            ////tableFooterRight.AddCell(cellLeftNoBorder);

            ////cellLeftNoBorder.Phrase = new Phrase($": " + total.ToString("N", new CultureInfo("id-ID")), normal_font);
            ////tableFooterRight.AddCell(cellLeftNoBorder);

            ////cellLeftNoBorder.Phrase = new Phrase("Total Nota Koreksi", normal_font);
            ////tableFooterRight.AddCell(cellLeftNoBorder);

            ////if (correctionNote != null)
            ////{
            ////    cellLeftNoBorder.Phrase = new Phrase($": " + totalcorrection.ToString("N", new CultureInfo("id-ID")), normal_font);
            ////    tableFooterRight.AddCell(cellLeftNoBorder);
            ////}
            ////else
            ////{
            ////    cellLeftNoBorder.Phrase = new Phrase($": " + 0, normal_font);
            ////    tableFooterRight.AddCell(cellLeftNoBorder);
            ////}

            ////cellLeftNoBorder.Phrase = new Phrase("Total Nota PPn", normal_font);
            ////tableFooterRight.AddCell(cellLeftNoBorder);

            ////cellLeftNoBorder.Phrase = new Phrase($": " + ppn.ToString("N", new CultureInfo("id-ID")), normal_font);
            ////tableFooterRight.AddCell(cellLeftNoBorder);

            ////cellLeftNoBorder.Phrase = new Phrase("Total Nota PPh", normal_font);
            ////tableFooterRight.AddCell(cellLeftNoBorder);

            ////cellLeftNoBorder.Phrase = new Phrase($": " + pph.ToString("N", new CultureInfo("id-ID")), normal_font);
            ////tableFooterRight.AddCell(cellLeftNoBorder);

            ////cellLeftNoBorder.Phrase = new Phrase("Total yang Harus Dibayar", normal_font);
            ////tableFooterRight.AddCell(cellLeftNoBorder);

            ////cellLeftNoBorder.Phrase = new Phrase($": " + maxtotal.ToString("N", new CultureInfo("id-ID")), normal_font);
            ////tableFooterRight.AddCell(cellLeftNoBorder);

            //PdfPCell cellFooterLeft = new PdfPCell(tableFooterLeft) { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER };
            //tableFooter.AddCell(cellFooterLeft);
            //PdfPCell cellFooterRight = new PdfPCell(tableFooterRight) { Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER };
            //tableFooter.AddCell(cellFooterRight);


            //PdfPCell cellFooter = new PdfPCell(tableFooter); // dont remove
            //tableFooter.ExtendLastRow = false;
            //tableFooter.SpacingAfter = 20f;
            //document.Add(tableFooter);

            //#endregion

            #region TableSignature

            PdfPTable tableSignature = new PdfPTable(3);

            PdfPCell cellSignatureContent = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER
            };

            cellSignatureContent.Phrase = new Phrase("Penerima/Pembeli\n\n\n\n\n\n\n(________________________________)", bold_font1);
            tableSignature.AddCell(cellSignatureContent);
            cellSignatureContent.Phrase = new Phrase("Bagian Pengiriman\n\n\n\n\n\n\n(________________________________)", bold_font1);
            tableSignature.AddCell(cellSignatureContent);
            cellSignatureContent.Phrase = new Phrase("Yang Membuat\n\n\n\n\n\n\n(________________________________)", bold_font1);
            tableSignature.AddCell(cellSignatureContent);


            PdfPCell cellSignature = new PdfPCell(tableSignature); // dont remove
            tableSignature.ExtendLastRow = false;
            tableSignature.SpacingBefore = 20f;
            tableSignature.SpacingAfter  = 20f;
            document.Add(tableSignature);

            #endregion

            document.Close();
            byte[] byteInfo = stream.ToArray();
            stream.Write(byteInfo, 0, byteInfo.Length);
            stream.Position = 0;

            return(stream);
        }
Exemplo n.º 12
0
        public static void CreateFichaPsicologicaGoldfields(PacientList filiationData,
                                                            List <ServiceComponentList> serviceComponent,
                                                            organizationDto infoEmpresa,
                                                            PacientList datosPac,
                                                            string filePDF, UsuarioGrabo DatosGrabo)
        {
            Document document = new Document(PageSize.A4, 30f, 30f, 42f, 41f);

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

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

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

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

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

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

            var tamaño_celda = 11f;
            #region TÍTULO

            cells = new List <PdfPCell>();

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

            var cellsTit = new List <PdfPCell>()
            {
                new PdfPCell(new Phrase("FICHA PSICOLÓGICA OCUPACIONAL", fontTitle1))
                {
                    HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 15f
                },
            };
            columnWidths = new float[] { 100f };
            table        = HandlingItextSharp.GenerateTableFromCells(cellsTit, columnWidths, null, fontTitleTable);
            document.Add(table);
            #endregion

            #region DATOS GENERALES
            string preOcp = "", Ocup = "", postOcup = "";
            if (filiationData.i_EsoTypeId == 1)
            {
                preOcp = "X";
            }
            else if (filiationData.i_EsoTypeId == 2)
            {
                Ocup = "X";
            }
            else if (filiationData.i_EsoTypeId == 3)
            {
                postOcup = "X";
            }


            string[] fechaServicio = datosPac.FechaServicio.ToString().Split(' ');

            string empresageneral     = filiationData.empresa_;
            string empresacontrata    = filiationData.contrata;
            string empresasubcontrata = filiationData.subcontrata;

            string empr_Conct = "";
            if (empresageneral != empresasubcontrata)
            {
                empr_Conct = empresacontrata + " / " + empresasubcontrata;
            }
            else
            {
                empr_Conct = empresacontrata;
            }

            cells = new List <PdfPCell>()
            {
                new PdfPCell(new Phrase("CLÍNICA:", fontColumnValueBold))
                {
                    Colspan = 5, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(infoEmpresa.v_Name, fontColumnValue))
                {
                    Colspan = 8, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },
                new PdfPCell(new Phrase("Fecha de Entrevista", fontColumnValueBold))
                {
                    Colspan = 3, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(fechaServicio[0], fontColumnValue))
                {
                    Colspan = 4, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },

                new PdfPCell(new Phrase("I. Datos Generales:", fontColumnValueBold))
                {
                    Colspan = 20, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda, BackgroundColor = BaseColor.GRAY
                },

                new PdfPCell(new Phrase("Apellidos Y Nombres", fontColumnValueBold))
                {
                    Colspan = 5, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(datosPac.v_FirstLastName + " " + datosPac.v_SecondLastName + " " + datosPac.v_FirstName, fontColumnValue))
                {
                    Colspan = 15, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },

                new PdfPCell(new Phrase("Edad", fontColumnValueBold))
                {
                    Colspan = 3, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(datosPac.Edad.ToString(), fontColumnValue))
                {
                    Colspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },
                new PdfPCell(new Phrase("Fecha de Nacimiento:", fontColumnValueBold))
                {
                    Colspan = 4, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(datosPac.d_Birthdate.ToString().Split(' ')[0], fontColumnValue))
                {
                    Colspan = 4, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },
                new PdfPCell(new Phrase("Estado Civil:", fontColumnValueBold))
                {
                    Colspan = 3, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(datosPac.v_MaritalStatus, fontColumnValue))
                {
                    Colspan = 4, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda
                },

                new PdfPCell(new Phrase("Empresa", fontColumnValueBold))
                {
                    Colspan = 3, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(empr_Conct, fontColumnValue))
                {
                    Colspan = 7, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },
                new PdfPCell(new Phrase("Cargo", fontColumnValueBold))
                {
                    Colspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(datosPac.v_CurrentOccupation, fontColumnValue))
                {
                    Colspan = 8, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },

                new PdfPCell(new Phrase("Tipo de Evaluación", fontColumnValueBold))
                {
                    Colspan = 5, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },
                new PdfPCell(new Phrase("Pre Ocupacional", fontColumnValueBold))
                {
                    Colspan = 4, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(preOcp, fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },
                new PdfPCell(new Phrase("Ocupacional", fontColumnValueBold))
                {
                    Colspan = 3, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(Ocup, fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },
                new PdfPCell(new Phrase("Post Ocupacional", fontColumnValueBold))
                {
                    Colspan = 5, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(postOcup, fontColumnValue))
                {
                    Colspan = 1, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },
            };

            columnWidths = new float[] { 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f };
            table        = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, null, fontTitleTable);
            document.Add(table);
            #endregion
            ServiceComponentList ficha_psico_goldfields = serviceComponent.Find(p => p.v_ComponentId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_OCUPACIONAL_GOLDFIELDS);

            #region DATOS OCUPACIONALES
            //var empresa_Actual = ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_EMPRESA_ACTUAL) == null ? "" : ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_EMPRESA_ACTUAL).v_Value1;
            var area_trabajo     = ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_AREA_LUGAR) == null ? "" : ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_AREA_LUGAR).v_Value1;
            var provincia_depart = ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_PROVINCIA_DEPARTAMENTO) == null ? "" : ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_PROVINCIA_DEPARTAMENTO).v_Value1;
            var tiempo_laborando = ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_TIEMPO_TOTAL_LAB) == null ? "" : ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_TIEMPO_TOTAL_LAB).v_Value1;
            var experiencia      = ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_EXPERIENCIA_PUESTO) == null ? "" : ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_EXPERIENCIA_PUESTO).v_Value1;
            var riesgos          = ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_PRINCIPALES_RIESGOS) == null ? "" : ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_PRINCIPALES_RIESGOS).v_Value1;
            var medidasSeguridad = ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_MEDIDAS_SEGURIDAD) == null ? "" : ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_MEDIDAS_SEGURIDAD).v_Value1;

            var ingreso1   = ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_FECHA_INGRESO1) == null ? "" : ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_FECHA_INGRESO1).v_Value1;
            var empresa1   = ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_NOMBRE_EMPRESA1) == null ? "" : ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_NOMBRE_EMPRESA1).v_Value1;
            var actividad1 = ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_ACTIVIDAD_EMPRESA1) == null ? "" : ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_ACTIVIDAD_EMPRESA1).v_Value1;
            var puesto1    = ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_PUESTO_EMPRESA1) == null ? "" : ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_PUESTO_EMPRESA1).v_Value1;
            var tiempo1    = ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_PERMANENCIA_TIEMPO1) == null ? "" : ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_PERMANENCIA_TIEMPO1).v_Value1;
            var salida1    = ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_PERMANENCIA_FECHA_SALIDA1) == null ? "" : ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_PERMANENCIA_FECHA_SALIDA1).v_Value1;
            var cese1      = ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_CAUSA_CESE1) == null ? "" : ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_CAUSA_CESE1).v_Value1;

            var ingreso2   = ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_FECHA_INGRESO2) == null ? "" : ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_FECHA_INGRESO2).v_Value1;
            var empresa2   = ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_NOMBRE_EMPRESA2) == null ? "" : ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_NOMBRE_EMPRESA2).v_Value1;
            var actividad2 = ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_ACTIVIDAD_EMPRESA2) == null ? "" : ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_ACTIVIDAD_EMPRESA2).v_Value1;
            var puesto2    = ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_PUESTO_EMPRESA2) == null ? "" : ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_PUESTO_EMPRESA2).v_Value1;
            var tiempo2    = ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_PERMANENCIA_TIEMPO2) == null ? "" : ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_PERMANENCIA_TIEMPO2).v_Value1;
            var salida2    = ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_PERMANENCIA_FECHA_SALIDA2) == null ? "" : ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_PERMANENCIA_FECHA_SALIDA2).v_Value1;
            var cese2      = ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_CAUSA_CESE2) == null ? "" : ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_CAUSA_CESE2).v_Value1;


            cells = new List <PdfPCell>()
            {
                new PdfPCell(new Phrase("II. Datos Ocupacionale:", fontColumnValueBold))
                {
                    Colspan = 20, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda, BackgroundColor = BaseColor.GRAY
                },

                new PdfPCell(new Phrase("2.1 Empresa Actual", fontColumnValueBold))
                {
                    Colspan = 20, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.BLACK, BorderColorRight = BaseColor.BLACK, BorderColorBottom = BaseColor.WHITE, BorderColorTop = BaseColor.BLACK
                },

                new PdfPCell(new Phrase("Área, lugar de trabajo", fontColumnValue))
                {
                    Colspan = 5, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(area_trabajo, fontColumnValue))
                {
                    Colspan = 5, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },
                new PdfPCell(new Phrase("Provincia, departamento", fontColumnValue))
                {
                    Colspan = 5, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(provincia_depart, fontColumnValue))
                {
                    Colspan = 5, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },

                new PdfPCell(new Phrase("Tiempo total laborando", fontColumnValue))
                {
                    Colspan = 5, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(tiempo_laborando, fontColumnValue))
                {
                    Colspan = 5, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },
                new PdfPCell(new Phrase("Experiencia en el puesto", fontColumnValue))
                {
                    Colspan = 5, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(experiencia, fontColumnValue))
                {
                    Colspan = 5, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },

                new PdfPCell(new Phrase("Principales riesgos", fontColumnValue))
                {
                    Colspan = 5, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(riesgos, fontColumnValue))
                {
                    Colspan = 15, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },

                new PdfPCell(new Phrase("Medidas de seguridad", fontColumnValue))
                {
                    Colspan = 5, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(medidasSeguridad, fontColumnValue))
                {
                    Colspan = 15, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },

                new PdfPCell(new Phrase("2.2 Anteriores Empresas (Experiencia Laboral): ", fontColumnValueBold))
                {
                    Colspan = 20, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.BLACK, BorderColorRight = BaseColor.BLACK, BorderColorBottom = BaseColor.WHITE, BorderColorTop = BaseColor.BLACK
                },
                new PdfPCell(new Phrase("", fontColumnValue))
                {
                    Colspan = 20, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.BLACK, BorderColorRight = BaseColor.BLACK, BorderColorBottom = BaseColor.BLACK, BorderColorTop = BaseColor.WHITE, FixedHeight = 1f
                },

                new PdfPCell(new Phrase("Fecha de ingreso", fontColumnValue))
                {
                    Colspan = 3, Rowspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda
                },
                new PdfPCell(new Phrase("Nombre de la Empresa", fontColumnValue))
                {
                    Colspan = 3, Rowspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda
                },
                new PdfPCell(new Phrase("Actividad de la Empresa", fontColumnValue))
                {
                    Colspan = 3, Rowspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda
                },
                new PdfPCell(new Phrase("Puesto", fontColumnValue))
                {
                    Colspan = 3, Rowspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda
                },
                new PdfPCell(new Phrase("Permanencia", fontColumnValue))
                {
                    Colspan = 4, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda
                },
                new PdfPCell(new Phrase("Causa de cese", fontColumnValue))
                {
                    Colspan = 4, Rowspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda
                },

                new PdfPCell(new Phrase("Tiempo", fontColumnValue))
                {
                    Colspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda
                },
                new PdfPCell(new Phrase("Fecha salida", fontColumnValue))
                {
                    Colspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda
                },

                new PdfPCell(new Phrase(ingreso1, fontColumnValue))
                {
                    Colspan = 3, Rowspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(empresa1, fontColumnValue))
                {
                    Colspan = 3, Rowspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(actividad1, fontColumnValue))
                {
                    Colspan = 3, Rowspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(puesto1, fontColumnValue))
                {
                    Colspan = 3, Rowspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(tiempo1, fontColumnValue))
                {
                    Colspan = 2, Rowspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(salida1, fontColumnValue))
                {
                    Colspan = 2, Rowspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(cese1, fontColumnValue))
                {
                    Colspan = 4, Rowspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda
                },

                new PdfPCell(new Phrase(ingreso2, fontColumnValue))
                {
                    Colspan = 3, Rowspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(empresa2, fontColumnValue))
                {
                    Colspan = 3, Rowspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(actividad2, fontColumnValue))
                {
                    Colspan = 3, Rowspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(puesto2, fontColumnValue))
                {
                    Colspan = 3, Rowspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(tiempo2, fontColumnValue))
                {
                    Colspan = 2, Rowspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(salida2, fontColumnValue))
                {
                    Colspan = 2, Rowspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda
                },
                new PdfPCell(new Phrase(cese2, fontColumnValue))
                {
                    Colspan = 4, Rowspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda
                },
            };

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

            #region HISTORIA FAMILIAR
            var historia_familiar = ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_HISTORIA_FAMILIAR) == null ? "" : ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_HISTORIA_FAMILIAR).v_Value1;
            cells = new List <PdfPCell>()
            {
                new PdfPCell(new Phrase("III. Historia Familiar (Con quien vive actualmente, pasatiempos, actividades fuera del trabajo", fontColumnValueBold))
                {
                    Colspan = 20, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda, BackgroundColor = BaseColor.GRAY
                },
                new PdfPCell(new Phrase(historia_familiar, fontColumnValue))
                {
                    Colspan = 20, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = 20
                },
            };

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

            #region HISTORIA FAMILIAR
            var enfermedades_accidentes = ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_ENFERMEDADES_ACCIDENTES) == null ? "" : ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_ENFERMEDADES_ACCIDENTES).v_Value1;
            cells = new List <PdfPCell>()
            {
                new PdfPCell(new Phrase("IV Enfermedades y accidentes (Durante el tiempo del trabajo)", fontColumnValueBold))
                {
                    Colspan = 20, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda, BackgroundColor = BaseColor.GRAY
                },
                new PdfPCell(new Phrase(enfermedades_accidentes, fontColumnValue))
                {
                    Colspan = 20, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = 20
                },
            };

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

            #region ENFERMEDADES Y ACCIDENTES
            var    enfermedad_salud_mental     = ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_ENFERMEDAD_SALUD_MENTAL) == null ? "" : ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_ENFERMEDAD_SALUD_MENTAL).v_Value1;
            string enfermedad_salud_mentalSINO = "";
            if (enfermedad_salud_mental == "1")
            {
                enfermedad_salud_mentalSINO = "SI";
            }
            if (enfermedad_salud_mental == "0")
            {
                enfermedad_salud_mentalSINO = "NO";
            }
            var descripcion_salud_mental      = ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_DESCRIPCION_SALUD_MENTAL) == null ? "" : ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_DESCRIPCION_SALUD_MENTAL).v_Value1;
            var otras_enfermedades_accidentes = ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_OTRAS_ENFEREMDADES) == null ? "" : ficha_psico_goldfields.ServiceComponentFields.Find(p => p.v_ComponentFieldsId == Sigesoft.Common.Constants.FICHA_PSICOLOGICA_GOLDFIELDS_OTRAS_ENFEREMDADES).v_Value1;

            cells = new List <PdfPCell>()
            {
                new PdfPCell(new Phrase("V. Antecedentes personales", fontColumnValueBold))
                {
                    Colspan = 20, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda, BackgroundColor = BaseColor.GRAY
                },

                new PdfPCell(new Phrase("a) Para ser llenado por el trabajador", fontColumnValueBold))
                {
                    Colspan = 20, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },

                new PdfPCell(new Phrase("Yo, " + datosPac.v_FirstLastName + " " + datosPac.v_SecondLastName + " " + datosPac.v_FirstName + "con DNI: " + datosPac.v_DocNumber + " manifiesto que " + enfermedad_salud_mentalSINO + " se me ha identificado una", fontColumnValue))
                {
                    Colspan = 20, HorizontalAlignment = iTextSharp.text.Element.ALIGN_JUSTIFIED_ALL, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.BLACK, BorderColorRight = BaseColor.BLACK, BorderColorBottom = BaseColor.WHITE, BorderColorTop = BaseColor.BLACK
                },
                new PdfPCell(new Phrase("enfermedad de salud mental, o psiquiátrica.", fontColumnValue))
                {
                    Colspan = 20, HorizontalAlignment = iTextSharp.text.Element.ALIGN_JUSTIFIED, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.BLACK, BorderColorRight = BaseColor.BLACK, BorderColorBottom = BaseColor.WHITE, BorderColorTop = BaseColor.WHITE
                },

                new PdfPCell(new Phrase("\n En el caso de marcar SI, describir en breve palabras el diagnostico de la enfermedad mental, y si recibió tratamiento;", fontColumnValueApendice))
                {
                    Colspan = 20, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20, UseVariableBorders = true, BorderColorLeft = BaseColor.BLACK, BorderColorRight = BaseColor.BLACK, BorderColorBottom = BaseColor.BLACK, BorderColorTop = BaseColor.WHITE
                },

                new PdfPCell(new Phrase("b) Otras enfermedades de salud, y/o accidentes:", fontColumnValueBold))
                {
                    Colspan = 20, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.BLACK, BorderColorRight = BaseColor.BLACK, BorderColorBottom = BaseColor.WHITE, BorderColorTop = BaseColor.BLACK
                },
                new PdfPCell(new Phrase(otras_enfermedades_accidentes, fontColumnValue))
                {
                    Colspan = 20, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = 20, UseVariableBorders = true, BorderColorLeft = BaseColor.BLACK, BorderColorRight = BaseColor.BLACK, BorderColorBottom = BaseColor.BLACK, BorderColorTop = BaseColor.WHITE
                },
            };
            columnWidths = new float[] { 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f };
            table        = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, null, fontTitleTable);
            document.Add(table);
            #endregion

            #region ENFERMEDADES Y ACCIDENTES

            cells = new List <PdfPCell>()
            {
                new PdfPCell(new Phrase("VI. Antecedentes personales", fontColumnValueBold))
                {
                    Colspan = 20, HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda, BackgroundColor = BaseColor.GRAY
                },

                new PdfPCell(new Phrase("Con la firma del presente documento, confirmo y doy fe que la información brindada sobre mi salud es completa y verdadera, haciéndome", fontColumnValue))
                {
                    Colspan = 20, HorizontalAlignment = iTextSharp.text.Element.ALIGN_JUSTIFIED_ALL, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.BLACK, BorderColorRight = BaseColor.BLACK, BorderColorBottom = BaseColor.WHITE, BorderColorTop = BaseColor.BLACK
                },
                new PdfPCell(new Phrase("\nresponsable de cualquier omisión o dato incorrecto; así mismo quedo obligado a informar toda circunstancia nueva que pueda influir", fontColumnValue))
                {
                    Colspan = 20, HorizontalAlignment = iTextSharp.text.Element.ALIGN_JUSTIFIED_ALL, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.BLACK, BorderColorRight = BaseColor.BLACK, BorderColorBottom = BaseColor.WHITE, BorderColorTop = BaseColor.WHITE
                },
                new PdfPCell(new Phrase("\no alterar esta información.", fontColumnValue))
                {
                    Colspan = 20, HorizontalAlignment = iTextSharp.text.Element.ALIGN_JUSTIFIED, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda, UseVariableBorders = true, BorderColorLeft = BaseColor.BLACK, BorderColorRight = BaseColor.BLACK, BorderColorBottom = BaseColor.BLACK, BorderColorTop = BaseColor.WHITE
                },
            };
            columnWidths = new float[] { 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f, 5f };
            table        = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, null, fontTitleTable);
            document.Add(table);
            #endregion
            //var psico = serviceComponent.Find(p => p.i_CategoryId == (int)Sigesoft.Common.Consultorio.Psicología);

            #region Firma

            #region Creando celdas de tipo Imagen y validando nulls
            PdfPCell cellFirmaTrabajador  = null;
            PdfPCell cellHuellaTrabajador = null;
            PdfPCell cellFirma            = null;

            // Firma del trabajador ***************************************************


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

            cellFirmaTrabajador.HorizontalAlignment = Element.ALIGN_CENTER;
            cellFirmaTrabajador.VerticalAlignment   = Element.ALIGN_MIDDLE;
            cellFirmaTrabajador.FixedHeight         = 50F;
            // Huella del trabajador **************************************************

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

            cellHuellaTrabajador.HorizontalAlignment = Element.ALIGN_CENTER;
            cellHuellaTrabajador.VerticalAlignment   = Element.ALIGN_MIDDLE;
            cellHuellaTrabajador.FixedHeight         = 50F;
            // Firma del doctor Auditor **************************************************
            if (DatosGrabo.Firma != null)
            {
                cellFirma = new PdfPCell(HandlingItextSharp.GetImage(DatosGrabo.Firma, null, null, 120, 50))
                {
                    HorizontalAlignment = PdfPCell.ALIGN_CENTER
                }
            }
            ;
            else
            {
                cellFirma = new PdfPCell(new Phrase(" ", fontColumnValue));
            }

            cellFirma.HorizontalAlignment = Element.ALIGN_CENTER;
            cellFirma.VerticalAlignment   = Element.ALIGN_MIDDLE;
            cellFirma.FixedHeight         = 50F;
            #endregion

            cells = new List <PdfPCell>()
            {
                new PdfPCell(cellFirmaTrabajador)
                {
                    HorizontalAlignment = PdfPCell.ALIGN_CENTER
                },
                new PdfPCell(cellHuellaTrabajador)
                {
                    HorizontalAlignment = PdfPCell.ALIGN_CENTER
                },
                new PdfPCell(new Phrase("FIRMA Y SELLO DEL PSICÓLOGO", fontColumnValueBold))
                {
                    Rowspan = 3, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, MinimumHeight = tamaño_celda
                },
                new PdfPCell(cellFirma)
                {
                    Rowspan = 3, HorizontalAlignment = PdfPCell.ALIGN_CENTER
                },

                new PdfPCell(new Phrase("FIRMA DEL EXAMINADO", fontColumnValueBold))
                {
                    HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = 12f
                },
                new PdfPCell(new Phrase("HUELLA DEL EXAMINADO", fontColumnValueBold))
                {
                    HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = 12f
                },

                new PdfPCell(new Phrase("CON LA CUAL DECLARA QUE LA INFORMACIÓN DECLARADA ES VERAZ", fontColumnValueBold))
                {
                    Colspan = 2, HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER, VerticalAlignment = iTextSharp.text.Element.ALIGN_MIDDLE, FixedHeight = tamaño_celda
                },
            };
            columnWidths = new float[] { 25f, 25f, 25f, 25f };

            filiationWorker = HandlingItextSharp.GenerateTableFromCells(cells, columnWidths, null, fontTitleTable);

            document.Add(filiationWorker);

            #endregion

            document.Close();
            writer.Close();
            writer.Dispose();
        }
        public ActionResult BIRCASSalesJournal(String StartDate, String EndDate, String CompanyId, String BranchId, String DocumentReference)
        {
            // ==============================
            // PDF Settings and Customization
            // ==============================
            MemoryStream workStream = new MemoryStream();
            Rectangle    rectangle  = new Rectangle(PageSize.A3.Rotate());
            Document     document   = new Document(rectangle, 72, 72, 72, 72);

            document.SetMargins(30f, 30f, 30f, 30f);
            PdfWriter.GetInstance(document, workStream).CloseStream = false;

            // =============
            // Document Open
            // =============
            document.Open();

            // ============
            // Fonts Styles
            // ============
            Font fontArial9       = FontFactory.GetFont("Arial", 9);
            Font fontArial9Bold   = FontFactory.GetFont("Arial", 9, Font.BOLD);
            Font fontArial9Italic = FontFactory.GetFont("Arial", 9, Font.ITALIC);
            Font fontArial17Bold  = FontFactory.GetFont("Arial", 17, Font.BOLD);
            Font fontArial12Bold  = FontFactory.GetFont("Arial", 12, Font.BOLD);
            Font fontArial12      = FontFactory.GetFont("Arial", 12);
            Font fontArial10Bold  = FontFactory.GetFont("Arial", 10, Font.BOLD);
            Font fontArial10      = FontFactory.GetFont("Arial", 10);

            // ====
            // Line
            // ====
            Paragraph line = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 4.5F)));

            // ==============
            // Company Detail
            // ==============
            var company = from d in db.MstCompanies where d.Id == Convert.ToInt32(CompanyId) select d;

            var branchName = "All Branches";

            if (Convert.ToInt32(BranchId) != 0)
            {
                var branch = from d in db.MstBranches where d.Id == Convert.ToInt32(BranchId) select d;
                branchName = branch.FirstOrDefault().Branch;
            }

            var identityUserId = User.Identity.GetUserId();
            var currentUser    = from d in db.MstUsers where d.UserId == identityUserId select d;

            // ===========
            // Header Page
            // ===========
            PdfPTable header = new PdfPTable(2);

            header.SetWidths(new float[] { 100f, 75f });
            header.WidthPercentage = 100;
            header.AddCell(new PdfPCell(new Phrase(company.FirstOrDefault().Company, fontArial17Bold))
            {
                Border = 0
            });
            header.AddCell(new PdfPCell(new Phrase("Sales Journal", fontArial17Bold))
            {
                Border = 0, HorizontalAlignment = 2
            });
            header.AddCell(new PdfPCell(new Phrase(company.FirstOrDefault().Address, fontArial10))
            {
                Border = 0, PaddingTop = 5f
            });
            header.AddCell(new PdfPCell(new Phrase(branchName, fontArial10))
            {
                Border = 0, PaddingTop = 5f, HorizontalAlignment = 2
            });
            header.AddCell(new PdfPCell(new Phrase(company.FirstOrDefault().ContactNumber, fontArial10))
            {
                Border = 0, PaddingTop = 5f
            });
            header.AddCell(new PdfPCell(new Phrase("Date Printed: " + DateTime.Now.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture) + " " + DateTime.Now.ToString("hh:mm:ss tt"), fontArial10))
            {
                Border = 0, PaddingTop = 5f, HorizontalAlignment = 2
            });
            header.AddCell(new PdfPCell(new Phrase("TIN: " + company.FirstOrDefault().TaxNumber, fontArial10))
            {
                Border = 0, PaddingTop = 5f
            });
            header.AddCell(new PdfPCell(new Phrase(Settings.SoftwareVersion + " (" + currentUser.FirstOrDefault().UserName + ")", fontArial10))
            {
                Border = 0, PaddingTop = 5f, HorizontalAlignment = 2
            });
            document.Add(header);
            document.Add(line);

            // ==================
            // Date Range Filters
            // ==================
            PdfPTable dateRangeFilters = new PdfPTable(1);

            dateRangeFilters.SetWidths(new float[] { 100f });
            dateRangeFilters.WidthPercentage = 100;
            dateRangeFilters.AddCell(new PdfPCell(new Phrase("Document Reference:  " + DocumentReference, fontArial10))
            {
                Border = 0, HorizontalAlignment = 0, PaddingTop = 8f
            });
            dateRangeFilters.AddCell(new PdfPCell(new Phrase("Date Start:  " + Convert.ToDateTime(StartDate).ToString("MM/dd/yyyy", CultureInfo.InvariantCulture), fontArial10))
            {
                Border = 0, HorizontalAlignment = 0, PaddingTop = 5f
            });
            dateRangeFilters.AddCell(new PdfPCell(new Phrase("Date End:   " + Convert.ToDateTime(EndDate).ToString("MM/dd/yyyy", CultureInfo.InvariantCulture), fontArial10))
            {
                Border = 0, HorizontalAlignment = 0, PaddingTop = 5f
            });
            document.Add(dateRangeFilters);

            // =====
            // Space
            // =====
            PdfPTable space = new PdfPTable(1);

            space.SetWidths(new float[] { 100f });
            space.WidthPercentage = 100;
            space.AddCell(new PdfPCell(new Phrase(" ", fontArial10))
            {
                Border = 0, PaddingTop = 7f
            });
            document.Add(space);

            String documentReferenceString = DocumentReference;

            if (DocumentReference.Equals("ALL"))
            {
                documentReferenceString = "";
            }

            // ====
            // Data
            // ====
            IQueryable <Data.TrnSalesInvoiceItem> salesInvoiceItems;

            if (Convert.ToInt32(BranchId) != 0)
            {
                salesInvoiceItems = from d in db.TrnSalesInvoiceItems.OrderBy(d => d.TrnSalesInvoice.SINumber)
                                    where d.TrnSalesInvoice.MstBranch.CompanyId == Convert.ToInt32(CompanyId) &&
                                    d.TrnSalesInvoice.BranchId == Convert.ToInt32(BranchId) &&
                                    d.TrnSalesInvoice.SIDate >= Convert.ToDateTime(StartDate) &&
                                    d.TrnSalesInvoice.SIDate <= Convert.ToDateTime(EndDate) &&
                                    (d.TrnSalesInvoice.DocumentReference.Contains(documentReferenceString) || d.TrnSalesInvoice.ManualSINumber.Contains(documentReferenceString))
                                    select d;
            }
            else
            {
                salesInvoiceItems = from d in db.TrnSalesInvoiceItems.OrderBy(d => d.TrnSalesInvoice.SINumber)
                                    where d.TrnSalesInvoice.MstBranch.CompanyId == Convert.ToInt32(CompanyId) &&
                                    d.TrnSalesInvoice.SIDate >= Convert.ToDateTime(StartDate) &&
                                    d.TrnSalesInvoice.SIDate <= Convert.ToDateTime(EndDate) &&
                                    (d.TrnSalesInvoice.DocumentReference.Contains(documentReferenceString) || d.TrnSalesInvoice.ManualSINumber.Contains(documentReferenceString))
                                    select d;
            }

            if (salesInvoiceItems.Any())
            {
                var groupedBranches = from d in salesInvoiceItems
                                      group d by new
                {
                    d.TrnSalesInvoice.BranchId,
                    d.TrnSalesInvoice.MstBranch.Branch
                } into g
                select g;

                if (groupedBranches.Any())
                {
                    Decimal overAllTotalGrossAmount          = 0;
                    Decimal overAllTotalVATableSalesAmount   = 0;
                    Decimal overAllTotalVATExemptSalesAmount = 0;
                    Decimal overAllTotalZeroRatedSalesAmount = 0;
                    Decimal overAllTotalVATAmount            = 0;
                    Decimal overAllTotalDiscountAmount       = 0;
                    Decimal overAllTotalNetSales             = 0;

                    foreach (var groupedBranch in groupedBranches)
                    {
                        PdfPTable branchTitle = new PdfPTable(1);
                        branchTitle.SetWidths(new float[] { 100f });
                        branchTitle.WidthPercentage = 100;
                        branchTitle.AddCell(new PdfPCell(new Phrase(groupedBranch.Key.Branch, fontArial12Bold))
                        {
                            Border = 0, HorizontalAlignment = 0, PaddingBottom = 5f
                        });
                        document.Add(branchTitle);

                        PdfPTable data = new PdfPTable(15);
                        data.SetWidths(new float[] { 40f, 65f, 60f, 50f, 50f, 55f, 55f, 55f, 50f, 50f, 50f, 50f, 50f, 50f, 50f });
                        data.WidthPercentage = 100;
                        data.AddCell(new PdfPCell(new Phrase("Date", fontArial10Bold))
                        {
                            HorizontalAlignment = 1, PaddingTop = 4f, PaddingBottom = 8f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        data.AddCell(new PdfPCell(new Phrase("Tx No.", fontArial10Bold))
                        {
                            HorizontalAlignment = 1, PaddingTop = 4f, PaddingBottom = 8f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        data.AddCell(new PdfPCell(new Phrase("Customer", fontArial10Bold))
                        {
                            HorizontalAlignment = 1, PaddingTop = 4f, PaddingBottom = 8f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        data.AddCell(new PdfPCell(new Phrase("TIN", fontArial10Bold))
                        {
                            HorizontalAlignment = 1, PaddingTop = 4f, PaddingBottom = 8f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        data.AddCell(new PdfPCell(new Phrase("Address", fontArial10Bold))
                        {
                            HorizontalAlignment = 1, PaddingTop = 4f, PaddingBottom = 8f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        data.AddCell(new PdfPCell(new Phrase("Doc. Ref. No.", fontArial10Bold))
                        {
                            HorizontalAlignment = 1, PaddingTop = 4f, PaddingBottom = 8f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        data.AddCell(new PdfPCell(new Phrase("SI Ref. No.", fontArial10Bold))
                        {
                            HorizontalAlignment = 1, PaddingTop = 4f, PaddingBottom = 8f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        data.AddCell(new PdfPCell(new Phrase("Item Code", fontArial10Bold))
                        {
                            HorizontalAlignment = 1, PaddingTop = 4f, PaddingBottom = 8f, PaddingLeft = 5f, PaddingRight = 5f
                        });

                        data.AddCell(new PdfPCell(new Phrase("Gross Amount", fontArial10Bold))
                        {
                            HorizontalAlignment = 1, PaddingTop = 4f, PaddingBottom = 8f, PaddingLeft = 5f, PaddingRight = 5f
                        });

                        data.AddCell(new PdfPCell(new Phrase("VATable Sales", fontArial10Bold))
                        {
                            HorizontalAlignment = 1, PaddingTop = 4f, PaddingBottom = 8f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        data.AddCell(new PdfPCell(new Phrase("VAT Exempt Sales", fontArial10Bold))
                        {
                            HorizontalAlignment = 1, PaddingTop = 4f, PaddingBottom = 8f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        data.AddCell(new PdfPCell(new Phrase("Zero Rated Sales", fontArial10Bold))
                        {
                            HorizontalAlignment = 1, PaddingTop = 4f, PaddingBottom = 8f, PaddingLeft = 5f, PaddingRight = 5f
                        });

                        data.AddCell(new PdfPCell(new Phrase("VAT Amount", fontArial10Bold))
                        {
                            HorizontalAlignment = 1, PaddingTop = 4f, PaddingBottom = 8f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        data.AddCell(new PdfPCell(new Phrase("Discount", fontArial10Bold))
                        {
                            HorizontalAlignment = 1, PaddingTop = 4f, PaddingBottom = 8f, PaddingLeft = 5f, PaddingRight = 5f
                        });

                        data.AddCell(new PdfPCell(new Phrase("Net Sales", fontArial10Bold))
                        {
                            HorizontalAlignment = 1, PaddingTop = 4f, PaddingBottom = 8f, PaddingLeft = 5f, PaddingRight = 5f
                        });

                        var salesInvoiceItemPerBranch = from d in salesInvoiceItems
                                                        where d.TrnSalesInvoice.BranchId == groupedBranch.Key.BranchId
                                                        select d;

                        if (salesInvoiceItemPerBranch.Any())
                        {
                            Decimal totalGrossAmount = 0;

                            Decimal totalVATableSalesAmount   = 0;
                            Decimal totalVATExemptSalesAmount = 0;
                            Decimal totalZeroRatedSalesAmount = 0;
                            Decimal totalVATAmount            = 0;

                            Decimal totalDiscountAmount = 0;
                            Decimal totalNetSales       = 0;

                            foreach (var salesInvoiceItem in salesInvoiceItemPerBranch)
                            {
                                totalGrossAmount += salesInvoiceItem.Amount + salesInvoiceItem.DiscountAmount + salesInvoiceItem.VATAmount;

                                totalVATableSalesAmount   += ComputeVATableSales(salesInvoiceItem.MstTaxType.TaxType, salesInvoiceItem.Amount);
                                totalVATExemptSalesAmount += ComputeVATExemptSales(salesInvoiceItem.MstTaxType.TaxType, salesInvoiceItem.MstTaxType.TaxRate, salesInvoiceItem.MstDiscount.Discount, salesInvoiceItem.Price, salesInvoiceItem.Quantity, salesInvoiceItem.Amount);
                                totalZeroRatedSalesAmount += ComputeZeroRatedSales(salesInvoiceItem.MstTaxType.TaxType, salesInvoiceItem.Amount);
                                totalVATAmount            += salesInvoiceItem.VATAmount;

                                totalDiscountAmount += salesInvoiceItem.DiscountAmount;
                                totalNetSales       += salesInvoiceItem.Amount;

                                data.AddCell(new PdfPCell(new Phrase(salesInvoiceItem.TrnSalesInvoice.SIDate.ToShortDateString(), fontArial10))
                                {
                                    HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 6f, PaddingLeft = 5f, PaddingRight = 5f
                                });
                                data.AddCell(new PdfPCell(new Phrase("SI-" + salesInvoiceItem.TrnSalesInvoice.MstBranch.BranchCode + "-" + salesInvoiceItem.TrnSalesInvoice.SINumber, fontArial10))
                                {
                                    HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 6f, PaddingLeft = 5f, PaddingRight = 5f
                                });
                                data.AddCell(new PdfPCell(new Phrase(salesInvoiceItem.TrnSalesInvoice.MstArticle.Article, fontArial10))
                                {
                                    HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 6f, PaddingLeft = 5f, PaddingRight = 5f
                                });
                                data.AddCell(new PdfPCell(new Phrase(salesInvoiceItem.TrnSalesInvoice.MstArticle.TaxNumber, fontArial10))
                                {
                                    HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 6f, PaddingLeft = 5f, PaddingRight = 5f
                                });
                                data.AddCell(new PdfPCell(new Phrase(salesInvoiceItem.TrnSalesInvoice.MstArticle.Address, fontArial10))
                                {
                                    HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 6f, PaddingLeft = 5f, PaddingRight = 5f
                                });
                                data.AddCell(new PdfPCell(new Phrase(salesInvoiceItem.TrnSalesInvoice.DocumentReference, fontArial10))
                                {
                                    HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 6f, PaddingLeft = 5f, PaddingRight = 5f
                                });
                                data.AddCell(new PdfPCell(new Phrase(salesInvoiceItem.TrnSalesInvoice.ManualSINumber, fontArial10))
                                {
                                    HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 6f, PaddingLeft = 5f, PaddingRight = 5f
                                });
                                data.AddCell(new PdfPCell(new Phrase(salesInvoiceItem.MstArticle.ManualArticleCode, fontArial10))
                                {
                                    HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 6f, PaddingLeft = 5f, PaddingRight = 5f
                                });

                                data.AddCell(new PdfPCell(new Phrase((salesInvoiceItem.Amount + salesInvoiceItem.DiscountAmount + salesInvoiceItem.VATAmount).ToString("#,##0.00"), fontArial10))
                                {
                                    HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 6f, PaddingLeft = 5f, PaddingRight = 5f
                                });

                                data.AddCell(new PdfPCell(new Phrase(ComputeVATableSales(salesInvoiceItem.MstTaxType.TaxType, salesInvoiceItem.Amount).ToString("#,##0.00"), fontArial10))
                                {
                                    HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 6f, PaddingLeft = 5f, PaddingRight = 5f
                                });
                                data.AddCell(new PdfPCell(new Phrase(ComputeVATExemptSales(salesInvoiceItem.MstTaxType.TaxType, salesInvoiceItem.MstTaxType.TaxRate, salesInvoiceItem.MstDiscount.Discount, salesInvoiceItem.Price, salesInvoiceItem.Quantity, salesInvoiceItem.Amount).ToString("#,##0.00"), fontArial10))
                                {
                                    HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 6f, PaddingLeft = 5f, PaddingRight = 5f
                                });
                                data.AddCell(new PdfPCell(new Phrase(ComputeZeroRatedSales(salesInvoiceItem.MstTaxType.TaxType, salesInvoiceItem.Amount).ToString("#,##0.00"), fontArial10))
                                {
                                    HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 6f, PaddingLeft = 5f, PaddingRight = 5f
                                });
                                data.AddCell(new PdfPCell(new Phrase(salesInvoiceItem.VATAmount.ToString("#,##0.00"), fontArial10))
                                {
                                    HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 6f, PaddingLeft = 5f, PaddingRight = 5f
                                });

                                data.AddCell(new PdfPCell(new Phrase(salesInvoiceItem.DiscountAmount.ToString("#,##0.00"), fontArial10))
                                {
                                    HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 6f, PaddingLeft = 5f, PaddingRight = 5f
                                });
                                data.AddCell(new PdfPCell(new Phrase(salesInvoiceItem.Amount.ToString("#,##0.00"), fontArial10))
                                {
                                    HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 6f, PaddingLeft = 5f, PaddingRight = 5f
                                });
                            }

                            data.AddCell(new PdfPCell(new Phrase("TOTAL", fontArial10Bold))
                            {
                                Colspan = 8, HorizontalAlignment = 2, PaddingTop = 4f, PaddingBottom = 8f, PaddingRight = 5f, PaddingLeft = 5f
                            });

                            data.AddCell(new PdfPCell(new Phrase(totalGrossAmount.ToString("#,##0.00"), fontArial10Bold))
                            {
                                HorizontalAlignment = 2, PaddingTop = 4f, PaddingBottom = 8f, PaddingRight = 5f, PaddingLeft = 5f
                            });

                            data.AddCell(new PdfPCell(new Phrase(totalVATableSalesAmount.ToString("#,##0.00"), fontArial10Bold))
                            {
                                HorizontalAlignment = 2, PaddingTop = 4f, PaddingBottom = 8f, PaddingRight = 5f, PaddingLeft = 5f
                            });
                            data.AddCell(new PdfPCell(new Phrase(totalVATExemptSalesAmount.ToString("#,##0.00"), fontArial10Bold))
                            {
                                HorizontalAlignment = 2, PaddingTop = 4f, PaddingBottom = 8f, PaddingRight = 5f, PaddingLeft = 5f
                            });
                            data.AddCell(new PdfPCell(new Phrase(totalZeroRatedSalesAmount.ToString("#,##0.00"), fontArial10Bold))
                            {
                                HorizontalAlignment = 2, PaddingTop = 4f, PaddingBottom = 8f, PaddingRight = 5f, PaddingLeft = 5f
                            });
                            data.AddCell(new PdfPCell(new Phrase(totalVATAmount.ToString("#,##0.00"), fontArial10Bold))
                            {
                                HorizontalAlignment = 2, PaddingTop = 4f, PaddingBottom = 8f, PaddingRight = 5f, PaddingLeft = 5f
                            });

                            data.AddCell(new PdfPCell(new Phrase(totalDiscountAmount.ToString("#,##0.00"), fontArial10Bold))
                            {
                                HorizontalAlignment = 2, PaddingTop = 4f, PaddingBottom = 8f, PaddingRight = 5f, PaddingLeft = 5f
                            });
                            data.AddCell(new PdfPCell(new Phrase(totalNetSales.ToString("#,##0.00"), fontArial10Bold))
                            {
                                HorizontalAlignment = 2, PaddingTop = 4f, PaddingBottom = 8f, PaddingRight = 5f, PaddingLeft = 5f
                            });

                            document.Add(data);

                            overAllTotalGrossAmount += totalGrossAmount;

                            overAllTotalVATableSalesAmount   += totalVATableSalesAmount;
                            overAllTotalVATExemptSalesAmount += totalVATExemptSalesAmount;
                            overAllTotalZeroRatedSalesAmount += totalZeroRatedSalesAmount;
                            overAllTotalVATAmount            += totalVATAmount;

                            overAllTotalDiscountAmount += totalDiscountAmount;
                            overAllTotalNetSales       += totalNetSales;
                        }

                        document.Add(space);
                    }

                    PdfPTable overallTotalData = new PdfPTable(15);
                    overallTotalData.SetWidths(new float[] { 40f, 65f, 60f, 50f, 50f, 55f, 55f, 55f, 50f, 50f, 50f, 50f, 50f, 50f, 50f });
                    overallTotalData.WidthPercentage = 100;
                    overallTotalData.AddCell(new PdfPCell(new Phrase("OVERALL TOTAL", fontArial10Bold))
                    {
                        Colspan = 8, HorizontalAlignment = 2, PaddingTop = 4f, PaddingBottom = 8f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    overallTotalData.AddCell(new PdfPCell(new Phrase(overAllTotalGrossAmount.ToString("#,##0.00"), fontArial10Bold))
                    {
                        HorizontalAlignment = 2, PaddingTop = 4f, PaddingBottom = 8f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    overallTotalData.AddCell(new PdfPCell(new Phrase(overAllTotalVATableSalesAmount.ToString("#,##0.00"), fontArial10Bold))
                    {
                        HorizontalAlignment = 2, PaddingTop = 4f, PaddingBottom = 8f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    overallTotalData.AddCell(new PdfPCell(new Phrase(overAllTotalVATExemptSalesAmount.ToString("#,##0.00"), fontArial10Bold))
                    {
                        HorizontalAlignment = 2, PaddingTop = 4f, PaddingBottom = 8f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    overallTotalData.AddCell(new PdfPCell(new Phrase(overAllTotalZeroRatedSalesAmount.ToString("#,##0.00"), fontArial10Bold))
                    {
                        HorizontalAlignment = 2, PaddingTop = 4f, PaddingBottom = 8f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    overallTotalData.AddCell(new PdfPCell(new Phrase(overAllTotalVATAmount.ToString("#,##0.00"), fontArial10Bold))
                    {
                        HorizontalAlignment = 2, PaddingTop = 4f, PaddingBottom = 8f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    overallTotalData.AddCell(new PdfPCell(new Phrase(overAllTotalDiscountAmount.ToString("#,##0.00"), fontArial10Bold))
                    {
                        HorizontalAlignment = 2, PaddingTop = 4f, PaddingBottom = 8f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    overallTotalData.AddCell(new PdfPCell(new Phrase(overAllTotalNetSales.ToString("#,##0.00"), fontArial10Bold))
                    {
                        HorizontalAlignment = 2, PaddingTop = 4f, PaddingBottom = 8f, PaddingRight = 5f, PaddingLeft = 5f
                    });

                    document.Add(overallTotalData);
                }
            }

            // ======
            // Footer
            // ======
            PdfPTable tblFooter = new PdfPTable(1);

            tblFooter.SetWidths(new float[] { 100f });
            tblFooter.WidthPercentage = 100;
            tblFooter.AddCell(new PdfPCell(new Phrase("Software Provider Name: Cebu Innosoft Solutions VAT REG TIN:261-481-387-000 Address: Y & S Bldg. V Rama Guadalupe Cebu \nPTU No.: XXX-XXX-XXXX Date Issued: XX/XX/XXXX Valid Until: XX/XX/XXXX", fontArial9Italic))
            {
                Border = 0, PaddingTop = 10f, HorizontalAlignment = 1
            });

            document.Add(tblFooter);

            // ==============
            // Document Close
            // ==============
            document.Close();

            // ================
            // Byte File Stream
            // ================
            byte[] byteInfo = workStream.ToArray();
            workStream.Write(byteInfo, 0, byteInfo.Length);
            workStream.Position = 0;

            return(new FileStreamResult(workStream, "application/pdf"));
        }
Exemplo n.º 14
0
        public ActionResult StockOut(Int32 StockOutId)
        {
            // ==============================
            // PDF Settings and Customization
            // ==============================
            MemoryStream workStream = new MemoryStream();
            Rectangle    rectangle  = new Rectangle(PageSize.A3);
            Document     document   = new Document(rectangle, 72, 72, 72, 72);

            document.SetMargins(30f, 30f, 30f, 30f);
            PdfWriter.GetInstance(document, workStream).CloseStream = false;

            document.Open();

            // =====
            // Fonts
            // =====
            Font fontArial17Bold = FontFactory.GetFont("Arial", 17, Font.BOLD);
            Font fontArial11     = FontFactory.GetFont("Arial", 11);
            Font fontArial9Bold  = FontFactory.GetFont("Arial", 9, Font.BOLD);
            Font fontArial9      = FontFactory.GetFont("Arial", 9);
            Font fontArial10Bold = FontFactory.GetFont("Arial", 10, Font.BOLD);
            Font fontArial10     = FontFactory.GetFont("Arial", 10);
            Font fontArial11Bold = FontFactory.GetFont("Arial", 11, Font.BOLD);
            Font fontArial12Bold = FontFactory.GetFont("Arial", 12, Font.BOLD);
            Font fontArial13Bold = FontFactory.GetFont("Arial", 13, Font.BOLD);

            Paragraph line = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 4.5F)));

            var identityUserId   = User.Identity.GetUserId();
            var currentUser      = from d in db.MstUsers where d.UserId == identityUserId select d;
            var currentCompanyId = currentUser.FirstOrDefault().CompanyId;
            var currentBranchId  = currentUser.FirstOrDefault().BranchId;

            // ==============
            // Company Detail
            // ==============
            var companyName = (from d in db.MstCompanies where d.Id == Convert.ToInt32(currentCompanyId) select d.Company).FirstOrDefault();
            var address     = (from d in db.MstCompanies where d.Id == Convert.ToInt32(currentCompanyId) select d.Address).FirstOrDefault();
            var contactNo   = (from d in db.MstCompanies where d.Id == Convert.ToInt32(currentCompanyId) select d.ContactNumber).FirstOrDefault();
            var branch      = (from d in db.MstBranches where d.Id == Convert.ToInt32(currentBranchId) select d.Branch).FirstOrDefault();

            // ===========
            // Header Page
            // ===========
            PdfPTable headerPage = new PdfPTable(2);

            float[] widthsCellsHeaderPage = new float[] { 100f, 75f };
            headerPage.SetWidths(widthsCellsHeaderPage);
            headerPage.WidthPercentage = 100;
            headerPage.AddCell(new PdfPCell(new Phrase(companyName, fontArial17Bold))
            {
                Border = 0
            });
            headerPage.AddCell(new PdfPCell(new Phrase("Stock Out", fontArial17Bold))
            {
                Border = 0, HorizontalAlignment = 2
            });
            headerPage.AddCell(new PdfPCell(new Phrase(address, fontArial11))
            {
                Border = 0, PaddingTop = 5f
            });
            headerPage.AddCell(new PdfPCell(new Phrase(branch, fontArial11))
            {
                Border = 0, PaddingTop = 5f, HorizontalAlignment = 2
            });
            headerPage.AddCell(new PdfPCell(new Phrase(contactNo, fontArial11))
            {
                Border = 0, PaddingTop = 5f
            });
            headerPage.AddCell(new PdfPCell(new Phrase("Printed " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToString("hh:mm:ss tt"), fontArial11))
            {
                Border = 0, PaddingTop = 5f, HorizontalAlignment = 2
            });
            document.Add(headerPage);

            // =====
            // Space
            // =====
            PdfPTable spaceTable = new PdfPTable(1);

            float[] widthCellsSpaceTable = new float[] { 100f };
            spaceTable.SetWidths(widthCellsSpaceTable);
            spaceTable.WidthPercentage = 100;
            spaceTable.AddCell(new PdfPCell(new Phrase(" ", fontArial10Bold))
            {
                Border = 0, PaddingTop = 5f
            });

            document.Add(line);

            var stockOuts = from d in db.TrnStockOuts
                            where d.Id == StockOutId &&
                            d.IsLocked == true
                            select d;

            if (stockOuts.Any())
            {
                String account     = stockOuts.FirstOrDefault().MstAccount.Account;
                String particulars = stockOuts.FirstOrDefault().Particulars;
                String OUTNumber   = stockOuts.FirstOrDefault().OTNumber;
                String OUTDate     = stockOuts.FirstOrDefault().OTDate.ToString("MM-dd-yyyy", CultureInfo.InvariantCulture);;
                String preparedBy  = stockOuts.FirstOrDefault().MstUser3.FullName;
                String checkedBy   = stockOuts.FirstOrDefault().MstUser1.FullName;
                String approvedBy  = stockOuts.FirstOrDefault().MstUser.FullName;

                PdfPTable tableStockOuts = new PdfPTable(4);
                float[]   widthscellsTablePurchaseOrder = new float[] { 40f, 150f, 70f, 50f };
                tableStockOuts.SetWidths(widthscellsTablePurchaseOrder);
                tableStockOuts.WidthPercentage = 100;

                tableStockOuts.AddCell(new PdfPCell(new Phrase("Account", fontArial11Bold))
                {
                    Border = 0, PaddingTop = 10f, PaddingLeft = 5f, PaddingRight = 5f
                });
                tableStockOuts.AddCell(new PdfPCell(new Phrase(account, fontArial11))
                {
                    Border = 0, PaddingTop = 10f, PaddingLeft = 5f, PaddingRight = 5f
                });
                tableStockOuts.AddCell(new PdfPCell(new Phrase("No.", fontArial11Bold))
                {
                    Border = 0, PaddingTop = 10f, PaddingLeft = 5f, PaddingRight = 5f, HorizontalAlignment = 2
                });
                tableStockOuts.AddCell(new PdfPCell(new Phrase(OUTNumber, fontArial11))
                {
                    Border = 0, PaddingTop = 10f, PaddingLeft = 5f, PaddingRight = 5f, HorizontalAlignment = 2
                });
                tableStockOuts.AddCell(new PdfPCell(new Phrase("Particulars", fontArial11Bold))
                {
                    Border = 0, PaddingTop = 5f, PaddingLeft = 5f, PaddingRight = 5f
                });
                tableStockOuts.AddCell(new PdfPCell(new Phrase(particulars, fontArial11))
                {
                    Border = 0, PaddingTop = 5f, PaddingLeft = 5f, PaddingRight = 5f
                });
                tableStockOuts.AddCell(new PdfPCell(new Phrase("Date", fontArial11Bold))
                {
                    Border = 0, PaddingTop = 5f, PaddingLeft = 5f, PaddingRight = 5f, HorizontalAlignment = 2
                });
                tableStockOuts.AddCell(new PdfPCell(new Phrase(OUTDate, fontArial11))
                {
                    Border = 0, PaddingTop = 5f, PaddingLeft = 5f, PaddingRight = 5f, HorizontalAlignment = 2
                });
                document.Add(tableStockOuts);

                document.Add(spaceTable);

                // ===================
                // Get Stock Out Items
                // ===================
                var stockOutItems = from d in db.TrnStockOutItems
                                    where d.OTId == StockOutId &&
                                    d.TrnStockOut.IsLocked == true
                                    select new
                {
                    Id               = d.Id,
                    OTId             = d.OTId,
                    OT               = d.TrnStockOut.OTNumber,
                    ExpenseAccountId = d.ExpenseAccountId,
                    ExpenseAccount   = d.MstAccount.Account,
                    ItemId           = d.ItemId,
                    ItemCode         = d.MstArticle.ManualArticleCode,
                    Item             = d.MstArticle.Article,
                    ItemInventoryId  = d.ItemInventoryId,
                    ItemInventory    = d.MstArticleInventory.InventoryCode,
                    Particulars      = d.Particulars,
                    UnitId           = d.UnitId,
                    Unit             = d.MstUnit.Unit,
                    Quantity         = d.Quantity,
                    Cost             = d.Cost,
                    Amount           = d.Amount,
                    BaseUnitId       = d.BaseUnitId,
                    BaseUnit         = d.MstUnit1.Unit,
                    BaseQuantity     = d.BaseQuantity,
                    BaseCost         = d.BaseCost
                };

                if (stockOutItems.Any())
                {
                    PdfPTable tableStockOutItems = new PdfPTable(6);
                    float[]   widthscellsPOLines = new float[] { 100f, 70f, 150f, 200f, 100f, 100f };
                    tableStockOutItems.SetWidths(widthscellsPOLines);
                    tableStockOutItems.WidthPercentage = 100;
                    tableStockOutItems.AddCell(new PdfPCell(new Phrase("Quantity", fontArial11Bold))
                    {
                        HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 7f
                    });
                    tableStockOutItems.AddCell(new PdfPCell(new Phrase("Unit", fontArial11Bold))
                    {
                        HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 7f
                    });
                    tableStockOutItems.AddCell(new PdfPCell(new Phrase("Code", fontArial11Bold))
                    {
                        HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 7f
                    });
                    tableStockOutItems.AddCell(new PdfPCell(new Phrase("Item", fontArial11Bold))
                    {
                        HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 7f
                    });
                    tableStockOutItems.AddCell(new PdfPCell(new Phrase("Cost", fontArial11Bold))
                    {
                        HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 7f
                    });
                    tableStockOutItems.AddCell(new PdfPCell(new Phrase("Amount", fontArial11Bold))
                    {
                        HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 7f
                    });

                    Decimal totalAmount = 0;

                    foreach (var stockOutItem in stockOutItems)
                    {
                        tableStockOutItems.AddCell(new PdfPCell(new Phrase(stockOutItem.Quantity.ToString("#,##0.00"), fontArial11))
                        {
                            HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 7f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        tableStockOutItems.AddCell(new PdfPCell(new Phrase(stockOutItem.Unit, fontArial11))
                        {
                            HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 7f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        tableStockOutItems.AddCell(new PdfPCell(new Phrase(stockOutItem.ItemCode, fontArial11))
                        {
                            HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 7f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        tableStockOutItems.AddCell(new PdfPCell(new Phrase(stockOutItem.Item, fontArial11))
                        {
                            HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 7f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        tableStockOutItems.AddCell(new PdfPCell(new Phrase(stockOutItem.Cost.ToString("#,##0.00"), fontArial11))
                        {
                            HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 7f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        tableStockOutItems.AddCell(new PdfPCell(new Phrase(stockOutItem.Amount.ToString("#,##0.00"), fontArial11))
                        {
                            HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 7f, PaddingLeft = 5f, PaddingRight = 5f
                        });

                        totalAmount += stockOutItem.Amount;
                    }

                    tableStockOutItems.AddCell(new PdfPCell(new Phrase("Total", fontArial11Bold))
                    {
                        Colspan = 5, HorizontalAlignment = 2, PaddingTop = 5f, PaddingBottom = 9f, PaddingLeft = 5f, PaddingRight = 5f
                    });
                    tableStockOutItems.AddCell(new PdfPCell(new Phrase(totalAmount.ToString("#,##0.00"), fontArial11Bold))
                    {
                        HorizontalAlignment = 2, PaddingTop = 5f, PaddingBottom = 9f, PaddingLeft = 5f, PaddingRight = 5f
                    });
                    document.Add(tableStockOutItems);

                    document.Add(spaceTable);
                }

                // ==============
                // User Signature
                // ==============
                PdfPTable tableUsers            = new PdfPTable(3);
                float[]   widthsCellsTableUsers = new float[] { 100f, 100f, 100f };
                tableUsers.WidthPercentage = 100;
                tableUsers.SetWidths(widthsCellsTableUsers);
                tableUsers.AddCell(new PdfPCell(new Phrase("Prepared by", fontArial11Bold))
                {
                    PaddingTop = 5f, PaddingBottom = 9f, PaddingLeft = 5f, PaddingRight = 5f
                });
                tableUsers.AddCell(new PdfPCell(new Phrase("Checked by", fontArial11Bold))
                {
                    PaddingTop = 5f, PaddingBottom = 9f, PaddingLeft = 5f, PaddingRight = 5f
                });
                tableUsers.AddCell(new PdfPCell(new Phrase("Approved by", fontArial11Bold))
                {
                    PaddingTop = 5f, PaddingBottom = 9f, PaddingLeft = 5f, PaddingRight = 5f
                });
                tableUsers.AddCell(new PdfPCell(new Phrase(" "))
                {
                    PaddingBottom = 50f
                });
                tableUsers.AddCell(new PdfPCell(new Phrase(" "))
                {
                    PaddingBottom = 50f
                });
                tableUsers.AddCell(new PdfPCell(new Phrase(" "))
                {
                    PaddingBottom = 50f
                });
                tableUsers.AddCell(new PdfPCell(new Phrase(preparedBy, fontArial11))
                {
                    HorizontalAlignment = 1, PaddingTop = 5f, PaddingBottom = 9f, PaddingLeft = 5f, PaddingRight = 5f
                });
                tableUsers.AddCell(new PdfPCell(new Phrase(checkedBy, fontArial11))
                {
                    HorizontalAlignment = 1, PaddingTop = 5f, PaddingBottom = 9f, PaddingLeft = 5f, PaddingRight = 5f
                });
                tableUsers.AddCell(new PdfPCell(new Phrase(approvedBy, fontArial11))
                {
                    HorizontalAlignment = 1, PaddingTop = 5f, PaddingBottom = 9f, PaddingLeft = 5f, PaddingRight = 5f
                });
                document.Add(tableUsers);
            }

            document.Close();

            byte[] byteInfo = workStream.ToArray();
            workStream.Write(byteInfo, 0, byteInfo.Length);
            workStream.Position = 0;

            return(new FileStreamResult(workStream, "application/pdf"));
        }
        public static Chunk GetChunk(Properties attributes)
        {
            Chunk chunk = new Chunk();

            chunk.Font = FontFactory.GetFont(attributes);
            String value;

            value = attributes[ElementTags.ITEXT];
            if (value != null)
            {
                chunk.Append(value);
            }
            value = attributes[ElementTags.LOCALGOTO];
            if (value != null)
            {
                chunk.SetLocalGoto(value);
            }
            value = attributes[ElementTags.REMOTEGOTO];
            if (value != null)
            {
                String page = attributes[ElementTags.PAGE];
                if (page != null)
                {
                    chunk.SetRemoteGoto(value, int.Parse(page));
                }
                else
                {
                    String destination = attributes[ElementTags.DESTINATION];
                    if (destination != null)
                    {
                        chunk.SetRemoteGoto(value, destination);
                    }
                }
            }
            value = attributes[ElementTags.LOCALDESTINATION];
            if (value != null)
            {
                chunk.SetLocalDestination(value);
            }
            value = attributes[ElementTags.SUBSUPSCRIPT];
            if (value != null)
            {
                chunk.SetTextRise(float.Parse(value, System.Globalization.NumberFormatInfo.InvariantInfo));
            }
            value = attributes[Markup.CSS_KEY_VERTICALALIGN];
            if (value != null && value.EndsWith("%"))
            {
                float p = float.Parse(value.Substring(0, value.Length - 1), System.Globalization.NumberFormatInfo.InvariantInfo) / 100f;
                chunk.SetTextRise(p * chunk.Font.Size);
            }
            value = attributes[ElementTags.GENERICTAG];
            if (value != null)
            {
                chunk.SetGenericTag(value);
            }
            value = attributes[ElementTags.BACKGROUNDCOLOR];
            if (value != null)
            {
                chunk.SetBackground(Markup.DecodeColor(value));
            }
            return(chunk);
        }
Exemplo n.º 16
0
        public Chap0403()
        {
            Console.WriteLine("Chapter 4 example 3: Chapters and Sections");

            // step 1: creation of a document-object
            Document document = new Document(PageSize.A4, 50, 50, 50, 50);

            try
            {
                // step 2: we create a writer that listens to the document
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("Chap0403.pdf", FileMode.Create));
                // step 3: we open the document
                document.Open();
                // step 4: we Add content to the document
                Paragraph title1   = new Paragraph("This is Chapter 1", FontFactory.GetFont(FontFactory.HELVETICA, 18, Font.BOLDITALIC, new Color(0, 0, 255)));
                Chapter   chapter1 = new Chapter(title1, 2);
                chapter1.NumberDepth = 0;
                Paragraph someText = new Paragraph("This is some text");
                chapter1.Add(someText);
                Paragraph title11         = new Paragraph("This is Section 1 in Chapter 1", FontFactory.GetFont(FontFactory.HELVETICA, 16, Font.BOLD, new Color(255, 0, 0)));
                Section   section1        = chapter1.AddSection(title11);
                Paragraph someSectionText = new Paragraph("This is some silly paragraph in a chapter and/or section. It contains some text to test the functionality of Chapters and Section.");
                section1.Add(someSectionText);
                document.Add(chapter1);

                Paragraph title2   = new Paragraph("This is Chapter 2", FontFactory.GetFont(FontFactory.HELVETICA, 18, Font.BOLDITALIC, new Color(0, 0, 255)));
                Chapter   chapter2 = new Chapter(title2, 2);
                chapter2.NumberDepth = 0;
                chapter2.Add(someText);
                Paragraph title21  = new Paragraph("This is Section 1 in Chapter 2", FontFactory.GetFont(FontFactory.HELVETICA, 16, Font.BOLD, new Color(255, 0, 0)));
                Section   section2 = chapter2.AddSection(title21);
                section2.Add(someSectionText);
                chapter2.BookmarkOpen = false;
                document.Add(chapter2);
            }
            catch (Exception de)
            {
                Console.Error.WriteLine(de.StackTrace);
            }
            // step 5: we close the document
            document.Close();
        }
Exemplo n.º 17
0
        private void dgvSickChrt_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                ID = dgvSickChrt.Rows[e.RowIndex].Cells["ColumnID"].Value.ToString();
            }
            catch (ArgumentOutOfRangeException)
            {
                Console.WriteLine(e);
            }
            if (e.ColumnIndex == dgvSickChrt.Columns["ColumnDelete"].Index)
            {
                if (MessageBox.Show("Delete selected Job Post?", "Confirm!", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
                {
                    if (ob.deleteSickChrt(ID))
                    {
                        MessageBox.Show("Successfully Deleted");
                        Clear();
                        FillGrid();
                    }
                    else
                    {
                        MessageBox.Show("Error occured while deleting");
                    }
                }
            }
            if (e.ColumnIndex == dgvSickChrt.Columns["ColumnView"].Index)
            {
                FormImgViewer form = new FormImgViewer(ob.getSickImg(ID));
                form.ShowDialog();
            }

            if (e.ColumnIndex == dgvSickChrt.Columns["ColumnSave"].Index)
            {
                string folderPath = "";
                FolderBrowserDialog directchoosedlg = new FolderBrowserDialog();
                if (directchoosedlg.ShowDialog() == DialogResult.OK)
                {
                    folderPath = directchoosedlg.SelectedPath;
                }
                //If User select the path....
                if (!(folderPath.Equals("")))
                {
                    SNO = dgvSickChrt.Rows[e.RowIndex].Cells["dgvSNO"].Value.ToString();
                    CheckvalidSNO(SNO);

                    Document document = new Document();
                    try
                    {
                        PdfWriter.GetInstance(document, new FileStream(folderPath + "/" + SNO + "_" + (++x) + ".pdf", FileMode.Create));
                        document.Open();

                        string    header = @"Sick Chart";
                        Paragraph p0     = new Paragraph();
                        p0.Font = FontFactory.GetFont(FontFactory.HELVETICA, 20f, BaseColor.BLUE);
                        p0.Add(header);
                        document.Add(p0);

                        string    header1 = @"Issue Date  :" + DateTime.Now.ToString();
                        Paragraph p1      = new Paragraph();
                        p1.Font = FontFactory.GetFont(FontFactory.HELVETICA, 8f, BaseColor.BLUE);
                        p1.Add(header1);
                        document.Add(p1);

                        Paragraph p2 = new Paragraph("SNO        :" + SNO);
                        p2.Font = FontFactory.GetFont(FontFactory.HELVETICA, 15f, BaseColor.BLACK);
                        document.Add(p2);

                        Paragraph p3 = new Paragraph("Name      :" + name);
                        p3.Font = FontFactory.GetFont(FontFactory.HELVETICA, 15f, BaseColor.BLACK);
                        document.Add(p3);

                        Paragraph p4 = new Paragraph("Intake     :" + intake);
                        p4.Font = FontFactory.GetFont(FontFactory.HELVETICA, 15f, BaseColor.BLACK);
                        document.Add(p4);

                        Paragraph p5 = new Paragraph(" ");
                        p5.Font = FontFactory.GetFont(FontFactory.HELVETICA, 15f, BaseColor.BLACK);
                        document.Add(p5);

                        //Read all data of DataGridView
                        for (int j = 4; j < dgvSickChrt.Columns.Count; j++)
                        {
                            Paragraph p = new Paragraph(dgvSickChrt.Columns[j].HeaderText + "     :" + dgvSickChrt.Rows[e.RowIndex].Cells[j].Value);
                            p.Font = FontFactory.GetFont(FontFactory.HELVETICA, 12f, BaseColor.BLACK);
                            document.Add(p);
                        }

                        document.Close();
                        MessageBox.Show("Successfully saved ");
                    }
                    catch (IOException)
                    {
                        MessageBox.Show("Pdf file already exist with " + SNO + " SNO  (Please Delete it or Select another path)");
                    }
                }
            }
        }
Exemplo n.º 18
0
        //makes the invoice and deactivates the job
        private void btnMakeInvoice_Click_1(object sender, EventArgs e)
        {
            if (MessageBox.Show("Once you complete the invoice, you can no longer make changes to it. Are you sure you would like to complete?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                //will save invoice on the path of the id
                string inString = "";
                int    invoice  = 0;

                for (int i = 0; i < service_names.Count; i++)
                {
                    string  sentence = service_sentences[i];
                    decimal total    = service_totals[i];

                    inString += sentence + ": $" + string.Format("{0:#,0.00}", total) + "\n";
                }
                string SetInvoiceSQL = "INSERT INTO INVOICE_TABLE (JOB_ID, AMOUNT_OWED, AMOUNT_PAID, INVOICE_TEXT, FILE_PATH, DATE_SENT) " +
                                       "OUTPUT INSERTED.INVOICE_ID " +
                                       "VALUES (@JOB_ID, @OWED, @PAID, @TEXT, @PATH, @DATE); ";


                //sets the path of the file
                filePath = "C:/Invoices/" + clientFirstName + clientLastName + clientID + "/" + jobID + clientLastName + DateTime.Now.Year.ToString() + ".pdf";
                if (isBusiness)
                {
                    filePath = "C:/Invoices/" + clientCompany + clientID + "/" + jobID + clientCompany + DateTime.Now.Year.ToString() + ".pdf";
                }

                connectionString = Properties.Settings.Default.GrenciDBConnectionString;
                try
                {
                    connection = new SqlConnection(connectionString);
                    command    = new SqlCommand(SetInvoiceSQL, connection);
                    //Open the connection
                    connection.Open();


                    command.Parameters.AddWithValue("@JOB_ID", jobID);
                    command.Parameters.AddWithValue("@OWED", finalTotal);
                    command.Parameters.AddWithValue("@PAID", 0);
                    command.Parameters.AddWithValue("@TEXT", inString);
                    command.Parameters.AddWithValue("@PATH", filePath);
                    command.Parameters.AddWithValue("@DATE", DateTime.Now);



                    var lastID = command.ExecuteScalar(); //this gets the data of the client that was just added into the system
                    invoice = Convert.ToInt32(lastID);


                    connection.Close();
                    // Once this button is clicked, it will generated a new pdf and save it to the user's computer, in case they want to print it out or
                    // save it for later on

                    command = new SqlCommand("UPDATE JOB_TABLE SET JOB_ACTIVE = @active WHERE JOB_ID = " + jobID + ";", connection);

                    connection.Open();
                    command.Parameters.AddWithValue("@JOB_ACTIVE", 0);

                    connection.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Could not make invoice! \nError: " + ex.Message);
                    return;//stops the creation of an invoice file if it fails
                }


                //makes the pdf document with the information on the datagridview
                Document document = new Document();

                Directory.CreateDirectory(Path.GetDirectoryName(filePath));

                PdfWriter.GetInstance(document, new FileStream(@filePath, FileMode.Create));
                document.Open();
                iTextSharp.text.Image img  = iTextSharp.text.Image.GetInstance(@"GrenciHeader.jpg");
                iTextSharp.text.Image img2 = iTextSharp.text.Image.GetInstance(@"GrenciFooter.jpg");
                img.Alignment  = Element.ALIGN_JUSTIFIED;
                img2.Alignment = Element.ALIGN_JUSTIFIED;
                img.ScaleToFit(550f, 1500f);
                img2.ScaleToFit(550f, 1500f);
                document.Add(img);
                var normalFont = FontFactory.GetFont(FontFactory.COURIER, 12);
                var boldFont   = FontFactory.GetFont(FontFactory.COURIER_BOLD, 12);
                var moneyFont  = FontFactory.GetFont(FontFactory.COURIER_BOLD, 10);
                var h1         = new Paragraph();
                h1.Alignment = Element.ALIGN_CENTER;
                h1.Add(new Chunk("\n" + "\n" + "INVOICE " + "\n", boldFont));
                Paragraph date = new Paragraph(DateTime.Now.ToLongDateString(), normalFont);
                Paragraph p1;
                if (clientLastName != "")
                {
                    p1 = new Paragraph("\n" + txtName.Text, normalFont);
                }
                else
                {
                    p1 = new Paragraph("\n" + clientCompany, normalFont);
                }
                Paragraph p2 = new Paragraph(clientAddress, normalFont);
                Paragraph p3 = new Paragraph(clientCity + ", " + clientState + " " + clientZip + "\n\n", normalFont);
                document.Add(h1);
                document.Add(date);
                document.Add(p1);
                document.Add(p2);
                document.Add(p3);
                Paragraph p4;
                //Paragraph p4h;//4 and a half basically, cannot have both run off of same paragraph
                for (int i = 0; i < dgvInvoice.Rows.Count; i++)
                {
                    string  sentence = dgvInvoice.Rows[i].Cells[0].Value.ToString();
                    decimal total    = decimal.Parse(dgvInvoice.Rows[i].Cells[1].Value.ToString());
                    cumulativeTotal = total + cumulativeTotal;
                    //p4 = new Paragraph(sentence , normalFont);
                    //document.Add(p4);
                    //p4h = new Paragraph(".......................$" + string.Format("{0:#,0.00}", total) , moneyFont);
                    //p4h.Alignment = Element.ALIGN_RIGHT;
                    Chunk glue = new Chunk(new VerticalPositionMark());
                    p4 = new Paragraph(sentence, normalFont);
                    p4.Add(new Chunk(glue));
                    p4.Add(new Chunk(".....$" + string.Format("{0:#,0.00}", total) + '\n', moneyFont));

                    document.Add(p4);
                }
                //Comes from the sum of the job
                Paragraph p5 = new Paragraph("\n" + "Total Amount Due: $" + string.Format("{0:#,0.00}", finalTotal), boldFont);
                Paragraph p6 = new Paragraph("\n\n" + "Thank you for your business!" + "\n\n", normalFont);
                document.Add(p5);
                document.Add(p6);
                document.Add(img2);
                document.Close();

                btnMakeInvoice.Text = "Invoice made";

                btnMakeInvoice.Enabled = false;
                btnEmail.Enabled       = true;
                btnPrint.Enabled       = true;



                string setPaymentSQL = "UPDATE JOB_TABLE SET JOB_ACTIVE = 0  WHERE JOB_ID = " + jobID + ";";
                //we are going through and updating the prices that we need to pull

                //Pulled from App.config
                connectionString = Properties.Settings.Default.GrenciDBConnectionString;
                try
                {
                    connection = new SqlConnection(connectionString);
                    command    = new SqlCommand(setPaymentSQL, connection);
                    //Open the connection
                    connection.Open();
                    command.ExecuteNonQuery();//tells ya if it worked

                    connection.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Could not deactivate job \nError: " + ex.Message);
                }


                setPaymentSQL = "UPDATE CLIENT_TABLE SET OWED_BALANCE = @BAL WHERE CLIENT_ID = " + clientID + ";";
                //we are going through and updating the prices that we need to pull

                //Pulled from App.config
                connectionString = Properties.Settings.Default.GrenciDBConnectionString;
                try
                {
                    connection = new SqlConnection(connectionString);
                    command    = new SqlCommand(setPaymentSQL, connection);
                    //Open the connection
                    connection.Open();
                    ClientsObj.Balance += finalTotal;

                    command.Parameters.AddWithValue("@BAL", ClientsObj.Balance);
                    command.ExecuteNonQuery();//tells ya if it worked

                    connection.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Could not deactivate job \nError: " + ex.Message);
                }


                btnClose.Text = "Close";
            }
        }
Exemplo n.º 19
0
        private void ReportBody()
        {
            fontStyle = FontFactory.GetFont("Calibri", 9f, 1);
            var _fontStyle = FontFactory.GetFont("Calibri", 9f, 0);

            #region Table Header
            pdfCell = new PdfPCell(new Phrase("ID", fontStyle));
            pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfCell.VerticalAlignment   = Element.ALIGN_LEFT;
            pdfCell.Border            = 1;
            pdfCell.BorderColorTop    = BaseColor.Black;
            pdfCell.BorderColorBottom = BaseColor.Black;
            pdfCell.BackgroundColor   = BaseColor.LightGray;
            pdfTable.AddCell(pdfCell);

            pdfCell = new PdfPCell(new Phrase("Fecha", fontStyle));
            pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfCell.VerticalAlignment   = Element.ALIGN_LEFT;
            pdfCell.Border            = 1;
            pdfCell.BorderColorTop    = BaseColor.Black;
            pdfCell.BorderColorBottom = BaseColor.Black;
            pdfCell.BackgroundColor   = BaseColor.LightGray;
            pdfTable.AddCell(pdfCell);

            pdfCell = new PdfPCell(new Phrase("Nombres", fontStyle));
            pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfCell.VerticalAlignment   = Element.ALIGN_LEFT;
            pdfCell.Border            = 1;
            pdfCell.BorderColorTop    = BaseColor.Black;
            pdfCell.BorderColorBottom = BaseColor.Black;
            pdfCell.BackgroundColor   = BaseColor.LightGray;
            pdfTable.AddCell(pdfCell);

            pdfCell = new PdfPCell(new Phrase("Apellidos", fontStyle));
            pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfCell.VerticalAlignment   = Element.ALIGN_LEFT;
            pdfCell.Border            = 1;
            pdfCell.BorderColorTop    = BaseColor.Black;
            pdfCell.BorderColorBottom = BaseColor.Black;
            pdfCell.BackgroundColor   = BaseColor.LightGray;
            pdfTable.AddCell(pdfCell);

            pdfCell = new PdfPCell(new Phrase("Cédula", fontStyle));
            pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfCell.VerticalAlignment   = Element.ALIGN_LEFT;
            pdfCell.Border            = 1;
            pdfCell.BorderColorTop    = BaseColor.Black;
            pdfCell.BorderColorBottom = BaseColor.Black;
            pdfCell.BackgroundColor   = BaseColor.LightGray;
            pdfTable.AddCell(pdfCell);

            pdfCell = new PdfPCell(new Phrase("Celular", fontStyle));
            pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfCell.VerticalAlignment   = Element.ALIGN_LEFT;
            pdfCell.Border            = 1;
            pdfCell.BorderColorTop    = BaseColor.Black;
            pdfCell.BorderColorBottom = BaseColor.Black;
            pdfCell.BackgroundColor   = BaseColor.LightGray;
            pdfTable.AddCell(pdfCell);

            pdfCell = new PdfPCell(new Phrase("Usuario", fontStyle));
            pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfCell.VerticalAlignment   = Element.ALIGN_LEFT;
            pdfCell.Border            = 1;
            pdfCell.BorderColorTop    = BaseColor.Black;
            pdfCell.BorderColorBottom = BaseColor.Black;
            pdfCell.BackgroundColor   = BaseColor.LightGray;
            pdfTable.AddCell(pdfCell);

            pdfCell = new PdfPCell(new Phrase("Crédito", fontStyle));
            pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfCell.VerticalAlignment   = Element.ALIGN_LEFT;
            pdfCell.Border            = 1;
            pdfCell.BorderColorTop    = BaseColor.Black;
            pdfCell.BorderColorBottom = BaseColor.Black;
            pdfCell.BackgroundColor   = BaseColor.LightGray;
            pdfTable.AddCell(pdfCell);

            pdfCell = new PdfPCell(new Phrase("Balance", fontStyle));
            pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfCell.VerticalAlignment   = Element.ALIGN_LEFT;
            pdfCell.Border            = 1;
            pdfCell.BorderColorTop    = BaseColor.Black;
            pdfCell.BorderColorBottom = BaseColor.Black;
            pdfCell.BackgroundColor   = BaseColor.LightGray;
            pdfTable.AddCell(pdfCell);

            pdfTable.CompleteRow();
            #endregion

            #region Table Body
            int     num          = 0;
            decimal totalBalance = 0;

            foreach (var item in listaClientes)
            {
                num++;
                pdfCell = new PdfPCell(new Phrase(item.ClienteId.ToString(), _fontStyle));
                pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
                pdfCell.VerticalAlignment   = Element.ALIGN_LEFT;
                pdfCell.Border            = 1;
                pdfCell.BorderColorBottom = BaseColor.Black;
                pdfTable.AddCell(pdfCell);

                pdfCell = new PdfPCell(new Phrase(item.Fecha.ToString("dd/MM/yyyy"), _fontStyle));
                pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
                pdfCell.VerticalAlignment   = Element.ALIGN_LEFT;
                pdfCell.Border            = 1;
                pdfCell.BorderColorBottom = BaseColor.Black;
                pdfTable.AddCell(pdfCell);

                pdfCell = new PdfPCell(new Phrase(item.Nombres, _fontStyle));
                pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
                pdfCell.VerticalAlignment   = Element.ALIGN_LEFT;
                pdfCell.Border            = 1;
                pdfCell.BorderColorBottom = BaseColor.Black;
                pdfTable.AddCell(pdfCell);

                pdfCell = new PdfPCell(new Phrase(item.Apellidos, _fontStyle));
                pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
                pdfCell.VerticalAlignment   = Element.ALIGN_LEFT;
                pdfCell.Border            = 1;
                pdfCell.BorderColorBottom = BaseColor.Black;
                pdfTable.AddCell(pdfCell);

                pdfCell = new PdfPCell(new Phrase(item.Cedula, _fontStyle));
                pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
                pdfCell.VerticalAlignment   = Element.ALIGN_LEFT;
                pdfCell.Border            = 1;
                pdfCell.BorderColorBottom = BaseColor.Black;
                pdfTable.AddCell(pdfCell);

                pdfCell = new PdfPCell(new Phrase(item.Celular, _fontStyle));
                pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
                pdfCell.VerticalAlignment   = Element.ALIGN_LEFT;
                pdfCell.Border            = 1;
                pdfCell.BorderColorBottom = BaseColor.Black;
                pdfTable.AddCell(pdfCell);

                pdfCell = new PdfPCell(new Phrase(repositorio.Buscar(item.UsuarioId).NombreUsuario, _fontStyle));
                pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
                pdfCell.VerticalAlignment   = Element.ALIGN_LEFT;
                pdfCell.Border            = 1;
                pdfCell.BorderColorBottom = BaseColor.Black;
                pdfTable.AddCell(pdfCell);

                pdfCell = new PdfPCell(new Phrase(item.LimiteCredito.ToString("N2"), _fontStyle));
                pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
                pdfCell.VerticalAlignment   = Element.ALIGN_LEFT;
                pdfCell.Border            = 1;
                pdfCell.BorderColorBottom = BaseColor.Black;
                pdfTable.AddCell(pdfCell);

                pdfCell = new PdfPCell(new Phrase(item.Balance.ToString("N2"), _fontStyle));
                pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
                pdfCell.VerticalAlignment   = Element.ALIGN_LEFT;
                pdfCell.Border            = 1;
                pdfCell.BorderColorBottom = BaseColor.Black;
                pdfTable.AddCell(pdfCell);

                totalBalance += item.Balance;

                pdfTable.CompleteRow();
            }

            pdfCell = new PdfPCell(new Phrase(("Total de registros: " + (num++.ToString())), fontStyle));
            pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfCell.VerticalAlignment   = Element.ALIGN_BOTTOM;
            pdfCell.Border            = 1;
            pdfCell.BorderColorBottom = BaseColor.Black;
            pdfTable.AddCell(pdfCell);

            pdfCell = new PdfPCell(new Phrase(" ", fontStyle));
            pdfCell.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell.VerticalAlignment   = Element.ALIGN_MIDDLE;
            pdfCell.BackgroundColor     = BaseColor.White;
            pdfCell.Border            = 1;
            pdfCell.BorderColorBottom = BaseColor.Black;
            pdfTable.AddCell(pdfCell);

            pdfCell = new PdfPCell(new Phrase(" ", fontStyle));
            pdfCell.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell.VerticalAlignment   = Element.ALIGN_MIDDLE;
            pdfCell.BackgroundColor     = BaseColor.White;
            pdfCell.Border            = 1;
            pdfCell.BorderColorBottom = BaseColor.Black;
            pdfTable.AddCell(pdfCell);

            pdfCell = new PdfPCell(new Phrase(" ", fontStyle));
            pdfCell.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell.VerticalAlignment   = Element.ALIGN_MIDDLE;
            pdfCell.BackgroundColor     = BaseColor.White;
            pdfCell.Border            = 1;
            pdfCell.BorderColorBottom = BaseColor.Black;
            pdfTable.AddCell(pdfCell);

            pdfCell = new PdfPCell(new Phrase(" ", fontStyle));
            pdfCell.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell.VerticalAlignment   = Element.ALIGN_MIDDLE;
            pdfCell.BackgroundColor     = BaseColor.White;
            pdfCell.Border            = 1;
            pdfCell.BorderColorBottom = BaseColor.Black;
            pdfTable.AddCell(pdfCell);

            pdfCell = new PdfPCell(new Phrase(" ", fontStyle));
            pdfCell.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell.VerticalAlignment   = Element.ALIGN_MIDDLE;
            pdfCell.BackgroundColor     = BaseColor.White;
            pdfCell.Border            = 1;
            pdfCell.BorderColorBottom = BaseColor.Black;
            pdfTable.AddCell(pdfCell);

            pdfCell = new PdfPCell(new Phrase(" ", fontStyle));
            pdfCell.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell.VerticalAlignment   = Element.ALIGN_MIDDLE;
            pdfCell.BackgroundColor     = BaseColor.White;
            pdfCell.Border            = 1;
            pdfCell.BorderColorBottom = BaseColor.Black;
            pdfTable.AddCell(pdfCell);

            pdfCell = new PdfPCell(new Phrase(" ", fontStyle));
            pdfCell.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell.VerticalAlignment   = Element.ALIGN_MIDDLE;
            pdfCell.BackgroundColor     = BaseColor.White;
            pdfCell.Border            = 1;
            pdfCell.BorderColorBottom = BaseColor.Black;
            pdfTable.AddCell(pdfCell);

            pdfCell = new PdfPCell(new Phrase(("Total: " + (totalBalance.ToString())), fontStyle));
            pdfCell.HorizontalAlignment = Element.ALIGN_LEFT;
            pdfCell.VerticalAlignment   = Element.ALIGN_BOTTOM;
            pdfCell.Border            = 1;
            pdfCell.BorderColorBottom = BaseColor.Black;
            pdfTable.AddCell(pdfCell);

            pdfTable.CompleteRow();
            #endregion
        }
Exemplo n.º 20
0
        public MemoryStream GeneratePdfTemplate(CostCalculationGarmentViewModel viewModel)
        {
            BaseFont bf          = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
            BaseFont bf_bold     = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
            Font     normal_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 7);
            Font     bold_font   = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 7);
            DateTime now         = DateTime.Now;

            Document     document = new Document(PageSize.A4, 10, 10, 10, 10);
            MemoryStream stream   = new MemoryStream();
            PdfWriter    writer   = PdfWriter.GetInstance(document, stream);

            writer.CloseStream = false;
            document.Open();
            PdfContentByte cb = writer.DirectContent;

            float    margin          = 10;
            float    printedOnHeight = 10;
            float    startY          = 840 - margin;
            PdfPCell cell_colon      = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, Phrase = new Phrase(":", normal_font)
            };

            #region Header
            cb.BeginText();
            cb.SetFontAndSize(bf, 10);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "PT. EFRATA RETAILINDO", 10, 820, 0);
            cb.SetFontAndSize(bf_bold, 12);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "BUDGET PRODUCTION", 10, 805, 0);
            cb.EndText();
            #endregion

            #region Detail 1 (Top)
            PdfPTable table_detail1 = new PdfPTable(9);
            table_detail1.TotalWidth = 570f;

            float[] detail1_widths = new float[] { 1f, 0.1f, 2f, 1f, 0.1f, 2f, 1.5f, 0.1f, 2f };
            table_detail1.SetWidths(detail1_widths);

            PdfPCell cell_detail1 = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 1, PaddingBottom = 2, PaddingTop = 2
            };

            cell_detail1.Phrase = new Phrase("RO", normal_font);
            table_detail1.AddCell(cell_detail1);
            table_detail1.AddCell(cell_colon);
            cell_detail1.Phrase = new Phrase($"{viewModel.RO}", normal_font);
            table_detail1.AddCell(cell_detail1);
            cell_detail1.Phrase = new Phrase("SECTION", normal_font);
            table_detail1.AddCell(cell_detail1);
            table_detail1.AddCell(cell_colon);
            cell_detail1.Phrase = new Phrase($"{viewModel.Section}", normal_font);
            table_detail1.AddCell(cell_detail1);
            cell_detail1.Phrase = new Phrase("CONFIRM ORDER", normal_font);
            table_detail1.AddCell(cell_detail1);
            table_detail1.AddCell(cell_colon);
            cell_detail1.Phrase = new Phrase($"{viewModel.ConfirmDate.ToString("dd/MM/yyyy")}", normal_font);
            table_detail1.AddCell(cell_detail1);
            #endregion

            #region Draw Detail 1
            float row1Y = 800;
            table_detail1.WriteSelectedRows(0, -1, 10, row1Y, cb);
            #endregion

            bool isDollar = viewModel.Rate.Id != 0;

            #region Detail 2 (Bottom, Column 1)
            PdfPTable table_detail2 = new PdfPTable(2);
            table_detail2.TotalWidth = 230f;

            float[] detail2_widths = new float[] { 2f, 5f };
            table_detail2.SetWidths(detail2_widths);

            PdfPCell cell_detail2 = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 2, PaddingBottom = 7, PaddingLeft = 2, PaddingTop = 7
            };

            cell_detail2.Phrase = new Phrase("BUYER", normal_font);
            table_detail2.AddCell(cell_detail2);
            cell_detail2.Phrase = new Phrase($"{viewModel.Buyer.Name}", normal_font);
            table_detail2.AddCell(cell_detail2);

            cell_detail2.Phrase = new Phrase("ARTICLE", normal_font);
            table_detail2.AddCell(cell_detail2);
            cell_detail2.Phrase = new Phrase($"{viewModel.Article}", normal_font);
            table_detail2.AddCell(cell_detail2);

            cell_detail2.Phrase = new Phrase("DESCRIPTION", normal_font);
            table_detail2.AddCell(cell_detail2);
            cell_detail2.Phrase = new Phrase($"{viewModel.Description}", normal_font);
            table_detail2.AddCell(cell_detail2);

            cell_detail2.Phrase = new Phrase("QTY", normal_font);
            table_detail2.AddCell(cell_detail2);
            cell_detail2.Phrase = new Phrase($"{viewModel.Quantity} PCS", normal_font);
            table_detail2.AddCell(cell_detail2);

            cell_detail2.Phrase = new Phrase("DELIVERY", normal_font);
            table_detail2.AddCell(cell_detail2);
            cell_detail2.Phrase = new Phrase($"{viewModel.DeliveryDate.ToString("dd/MM/yyyy")}", normal_font);
            table_detail2.AddCell(cell_detail2);
            #endregion

            #region Signature
            PdfPTable table_signature = new PdfPTable(5);
            table_signature.TotalWidth = 570f;

            float[] signature_widths = new float[] { 1f, 1f, 1f, 1f, 1f };
            table_signature.SetWidths(signature_widths);

            PdfPCell cell_signature = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2
            };

            cell_signature.Phrase = new Phrase("Membuat,", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Mengetahui,", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Menyetujui,", normal_font);
            table_signature.AddCell(cell_signature);

            string signatureArea = string.Empty;
            for (int i = 0; i < 4; i++)
            {
                signatureArea += Environment.NewLine;
            }

            cell_signature.Phrase = new Phrase(signatureArea, normal_font);
            table_signature.AddCell(cell_signature);
            table_signature.AddCell(cell_signature);
            table_signature.AddCell(cell_signature);
            table_signature.AddCell(cell_signature);
            table_signature.AddCell(cell_signature);

            cell_signature.Phrase = new Phrase("(                           )", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("(                           )", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("(                           )", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("(                           )", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("(Haenis Gunarto)", normal_font);
            table_signature.AddCell(cell_signature);

            cell_signature.Phrase = new Phrase("Merchandiser", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Ka. Sie IE", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Ka. Sie Merchandiser", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Ka. Sie Pembelian", normal_font);
            table_signature.AddCell(cell_signature);

            cell_signature.Phrase = new Phrase("Direktur Penjualan", normal_font);
            table_signature.AddCell(cell_signature);
            #endregion

            #region Cost Calculation Material
            PdfPTable table_ccm = new PdfPTable(10);
            table_ccm.TotalWidth = 570f;

            float[] ccm_widths = new float[] { 1f, 3f, 4f, 6f, 2f, 3f, 3f, 2f, 3f, 3f };
            table_ccm.SetWidths(ccm_widths);

            PdfPCell cell_ccm = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2
            };

            cell_ccm.Phrase = new Phrase("NO", bold_font);
            table_ccm.AddCell(cell_ccm);
            cell_ccm.Phrase = new Phrase("CATEGORIES", bold_font);
            table_ccm.AddCell(cell_ccm);
            cell_ccm.Phrase = new Phrase("MATERIALS", bold_font);
            table_ccm.AddCell(cell_ccm);
            cell_ccm.Phrase = new Phrase("DESCRIPTION", bold_font);
            table_ccm.AddCell(cell_ccm);
            cell_ccm.Phrase = new Phrase("USAGE", bold_font);
            table_ccm.AddCell(cell_ccm);
            cell_ccm.Phrase = new Phrase("PRICE", bold_font);
            table_ccm.AddCell(cell_ccm);
            cell_ccm.Phrase = new Phrase("QUANTITY", bold_font);
            table_ccm.AddCell(cell_ccm);
            cell_ccm.Phrase = new Phrase("UNIT", bold_font);
            table_ccm.AddCell(cell_ccm);
            cell_ccm.Phrase = new Phrase("AMOUNT", bold_font);
            table_ccm.AddCell(cell_ccm);
            cell_ccm.Phrase = new Phrase("PO NUMBER", bold_font);
            table_ccm.AddCell(cell_ccm);

            float  row2Y               = row1Y - table_detail1.TotalHeight - 10;
            float  row3Height          = table_detail2.TotalHeight;
            float  row2RemainingHeight = row2Y - 10 - row3Height - printedOnHeight - margin;
            float  row2AllowedHeight   = row2Y - printedOnHeight - margin;
            double totalBudget         = 0;

            #region Process Cost
            double processCost = viewModel.ProductionCost;
            #endregion

            for (int i = 0; i < viewModel.CostCalculationGarment_Materials.Count; i++)
            {
                cell_ccm.Phrase = new Phrase((i + 1).ToString(), normal_font);
                table_ccm.AddCell(cell_ccm);

                cell_ccm.HorizontalAlignment = Element.ALIGN_LEFT;

                cell_ccm.Phrase = new Phrase(viewModel.CostCalculationGarment_Materials[i].Category.SubCategory != null ? String.Format("{0} - {1}", viewModel.CostCalculationGarment_Materials[i].Category.Name, viewModel.CostCalculationGarment_Materials[i].Category.SubCategory) : viewModel.CostCalculationGarment_Materials[i].Category.Name, normal_font);
                table_ccm.AddCell(cell_ccm);

                cell_ccm.Phrase = new Phrase(viewModel.CostCalculationGarment_Materials[i].Material.Name, normal_font);
                table_ccm.AddCell(cell_ccm);

                cell_ccm.Phrase = new Phrase(viewModel.CostCalculationGarment_Materials[i].Description, normal_font);
                table_ccm.AddCell(cell_ccm);

                cell_ccm.HorizontalAlignment = Element.ALIGN_RIGHT;

                double usage = viewModel.CostCalculationGarment_Materials[i].Quantity ?? 0;
                cell_ccm.Phrase = new Phrase(usage.ToString(), normal_font);
                table_ccm.AddCell(cell_ccm);

                double price = viewModel.CostCalculationGarment_Materials[i].Price ?? 0;
                cell_ccm.Phrase = new Phrase(String.Format("{0}/{1}", Number.ToRupiahWithoutSymbol(price), viewModel.CostCalculationGarment_Materials[i].UOMPrice.Name), normal_font);
                table_ccm.AddCell(cell_ccm);

                double factor;
                if (viewModel.CostCalculationGarment_Materials[i].Category.Name == "ACC")
                {
                    factor = viewModel.AccessoriesAllowance ?? 0;
                }
                else
                {
                    factor = viewModel.FabricAllowance ?? 0;
                }
                double totalQuantity   = viewModel.Quantity ?? 0;
                double conversion      = (double)viewModel.CostCalculationGarment_Materials[i].Conversion;
                double usageConversion = usage / conversion;
                double quantity        = (100 + factor) / 100 * usageConversion * totalQuantity;

                quantity = Math.Ceiling(quantity);

                cell_ccm.Phrase = new Phrase(quantity.ToString(), normal_font);
                table_ccm.AddCell(cell_ccm);

                cell_ccm.HorizontalAlignment = Element.ALIGN_CENTER;
                cell_ccm.Phrase = new Phrase(viewModel.CostCalculationGarment_Materials[i].UOMQuantity.Name, normal_font);
                table_ccm.AddCell(cell_ccm);

                cell_ccm.HorizontalAlignment = Element.ALIGN_RIGHT;
                double amount = quantity * price;
                cell_ccm.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(amount), normal_font);
                table_ccm.AddCell(cell_ccm);

                cell_ccm.HorizontalAlignment = Element.ALIGN_CENTER;
                cell_ccm.Phrase = new Phrase(viewModel.CostCalculationGarment_Materials[i].PO, normal_font);
                table_ccm.AddCell(cell_ccm);

                totalBudget += amount;
                float currentHeight = table_ccm.TotalHeight;
                if (currentHeight / row2RemainingHeight > 1)
                {
                    if (currentHeight / row2AllowedHeight > 1)
                    {
                        PdfPRow headerRow = table_ccm.GetRow(0);
                        PdfPRow lastRow   = table_ccm.GetRow(table_ccm.Rows.Count - 1);
                        table_ccm.DeleteLastRow();
                        table_ccm.WriteSelectedRows(0, -1, 10, row2Y, cb);
                        table_ccm.DeleteBodyRows();
                        this.DrawPrintedOn(now, bf, cb);
                        document.NewPage();
                        table_ccm.Rows.Add(headerRow);
                        table_ccm.Rows.Add(lastRow);
                        table_ccm.CalculateHeights();
                        row2Y = startY;
                        row2RemainingHeight = row2Y - 10 - row3Height - printedOnHeight - margin;
                        row2AllowedHeight   = row2Y - printedOnHeight - margin;
                    }
                }
            }
            #endregion

            #region Detail 3 (Bottom, Column 2)
            PdfPTable table_detail3 = new PdfPTable(8);
            table_detail3.TotalWidth = 330f;

            float[] detail3_widths = new float[] { 3.25f, 4.75f, 1.9f, 0.2f, 1.9f, 1.9f, 0.2f, 1.9f };
            table_detail3.SetWidths(detail3_widths);

            //double budgetCost = isDollar ? viewModel.ConfirmPrice * viewModel.Rate.Value ?? 0 : viewModel.ConfirmPrice ?? 0;
            double totalProcessCost = processCost * (double)viewModel.Quantity;
            double budgetCost       = totalBudget / (double)viewModel.Quantity;

            PdfPCell cell_detail3 = new PdfPCell()
            {
                HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 2, PaddingBottom = 7, PaddingLeft = 2, PaddingTop = 7
            };
            PdfPCell cell_detail3_right = new PdfPCell()
            {
                HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 2, PaddingBottom = 7, PaddingLeft = 2, PaddingTop = 7
            };
            PdfPCell cell_detail3_colspan6 = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 2, PaddingBottom = 7, PaddingLeft = 2, PaddingTop = 7, Colspan = 6
            };
            PdfPCell cell_detail3_colspan8 = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 2, PaddingBottom = 7, PaddingLeft = 2, PaddingTop = 7, Colspan = 8
            };

            cell_detail3.Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER;
            cell_detail3.Phrase = new Phrase("TOTAL BUDGET", normal_font);
            table_detail3.AddCell(cell_detail3);
            cell_detail3.Border = Rectangle.TOP_BORDER | Rectangle.RIGHT_BORDER;
            cell_detail3.Phrase = new Phrase($"{Number.ToRupiah(totalBudget)}", normal_font);
            table_detail3.AddCell(cell_detail3);
            cell_detail3_colspan6.Phrase = new Phrase("STANDARD HOURS", normal_font);
            table_detail3.AddCell(cell_detail3_colspan6);

            double freightCost = 0;
            foreach (CostCalculationGarment_MaterialViewModel item in viewModel.CostCalculationGarment_Materials)
            {
                freightCost += item.TotalShippingFee;
            }

            cell_detail3.Border = Rectangle.LEFT_BORDER;
            cell_detail3.Phrase = new Phrase("BEA ANGKUT", normal_font);
            table_detail3.AddCell(cell_detail3);
            cell_detail3.Border = Rectangle.RIGHT_BORDER;
            cell_detail3.Phrase = new Phrase($"{Number.ToRupiah(freightCost)}", normal_font);
            table_detail3.AddCell(cell_detail3);
            cell_detail3.Border = Rectangle.LEFT_BORDER;
            cell_detail3.Phrase = new Phrase("SMV. CUT", normal_font);
            table_detail3.AddCell(cell_detail3);
            table_detail3.AddCell(cell_colon);
            cell_detail3.Border = Rectangle.NO_BORDER;
            cell_detail3.Phrase = new Phrase($"{viewModel.SMV_Cutting}", normal_font);
            table_detail3.AddCell(cell_detail3);
            cell_detail3.Border = Rectangle.NO_BORDER;
            cell_detail3.Phrase = new Phrase("SMV. SEW", normal_font);
            table_detail3.AddCell(cell_detail3);
            table_detail3.AddCell(cell_colon);
            cell_detail3.Border = Rectangle.RIGHT_BORDER;
            cell_detail3.Phrase = new Phrase($"{viewModel.SMV_Sewing}", normal_font);
            table_detail3.AddCell(cell_detail3);

            cell_detail3.Border = Rectangle.BOTTOM_BORDER | Rectangle.LEFT_BORDER;
            cell_detail3.Phrase = new Phrase("", normal_font);
            table_detail3.AddCell(cell_detail3);
            cell_detail3.Border = Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER;
            cell_detail3.Phrase = new Phrase("", normal_font);
            table_detail3.AddCell(cell_detail3);
            cell_detail3.Border = Rectangle.BOTTOM_BORDER | Rectangle.LEFT_BORDER;
            cell_detail3.Phrase = new Phrase("SMV. FIN", normal_font);
            table_detail3.AddCell(cell_detail3);
            table_detail3.AddCell(cell_colon);
            cell_detail3.Border = Rectangle.BOTTOM_BORDER;
            cell_detail3.Phrase = new Phrase($"{viewModel.SMV_Finishing}", normal_font);
            table_detail3.AddCell(cell_detail3);
            cell_detail3.Border = Rectangle.BOTTOM_BORDER;
            cell_detail3.Phrase = new Phrase("SMV. TOT", normal_font);
            table_detail3.AddCell(cell_detail3);
            table_detail3.AddCell(cell_colon);
            cell_detail3.Border = Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER;
            cell_detail3.Phrase = new Phrase($"{viewModel.SMV_Total}", normal_font);
            table_detail3.AddCell(cell_detail3);


            //cell_detail3_colspan8.Phrase = new Phrase("BUDGET COST / PCS" + "".PadRight(5) + $"{Number.ToRupiah(budgetCost)}", normal_font);
            //table_detail3.AddCell(cell_detail3_colspan8);
            cell_detail3_colspan8.Phrase = new Phrase("PROCESS COST" + "".PadRight(5) + $"{Number.ToRupiah(processCost)}", normal_font);
            table_detail3.AddCell(cell_detail3_colspan8);
            //cell_detail3_colspan8.Phrase = new Phrase("TOTAL PROCESS COST" + "".PadRight(5) + $"{Number.ToRupiah(totalProcessCost)}", normal_font);
            //table_detail3.AddCell(cell_detail3_colspan8);

            //double rateValue = (double)viewModel.Rate.Value;
            //double confirmPrice = (double)viewModel.ConfirmPrice;

            //cell_detail3_colspan8.Phrase = isDollar ? new Phrase($"US$ 1 = {Number.ToRupiah(rateValue)}" + "".PadRight(10) + $"CONFIRM PRICE : {Number.ToDollar(confirmPrice)} / PCS", normal_font) : new Phrase($"CONFIRM PRICE : {Number.ToRupiah(confirmPrice)} / PCS", normal_font);
            //table_detail3.AddCell(cell_detail3_colspan8);
            cell_detail3_colspan8.Border = Rectangle.NO_BORDER;
            cell_detail3_colspan8.HorizontalAlignment = Element.ALIGN_CENTER;
            cell_detail3_colspan8.Phrase = new Phrase($"ALLOWANCE >> FAB = {viewModel.FabricAllowance}%, ACC = {viewModel.AccessoriesAllowance}%", normal_font);
            table_detail3.AddCell(cell_detail3_colspan8);
            #endregion

            #region Draw Others
            table_ccm.WriteSelectedRows(0, -1, 10, row2Y, cb);

            float row3Y = row2Y - table_ccm.TotalHeight - 10;
            float row3RemainigHeight = row3Y - printedOnHeight - margin;
            if (row3RemainigHeight < row3Height)
            {
                this.DrawPrintedOn(now, bf, cb);
                row3Y = startY;
                document.NewPage();
            }

            table_detail2.WriteSelectedRows(0, -1, margin, row3Y, cb);

            table_detail3.WriteSelectedRows(0, -1, margin + table_detail2.TotalWidth + 10, row3Y, cb);

            float signatureY = row3Y - row3Height - 10;
            signatureY = signatureY - 50;
            float signatureRemainingHeight = signatureY - printedOnHeight - margin;
            if (signatureRemainingHeight < table_signature.TotalHeight)
            {
                this.DrawPrintedOn(now, bf, cb);
                signatureY = startY;
                document.NewPage();
            }
            table_signature.WriteSelectedRows(0, -1, margin, signatureY, cb);

            this.DrawPrintedOn(now, bf, cb);
            #endregion

            document.Close();

            byte[] byteInfo = stream.ToArray();
            stream.Write(byteInfo, 0, byteInfo.Length);
            stream.Position = 0;

            return(stream);
        }
    protected void btnDownload_Click(object sender, EventArgs e)
    {
        string finalResult = string.Empty;



        Button button = (sender as Button);
        //Get the command argument
        Int64   PurchaseOrderId = Convert.ToInt64(button.CommandArgument.ToString());
        DataSet ds = new DataSet();

        SqlCommand cmd = new SqlCommand();

        cmd.CommandText = "PurchaseOrderHeader_SelectById";
        cmd.Parameters.AddWithValue("@id", PurchaseOrderId);
        //cmd.Parameters.AddWithValue("@password", password);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter sda = new SqlDataAdapter();

        cmd.Connection    = con;
        sda.SelectCommand = cmd;



        //SqlDataAdapter da = new SqlDataAdapter(query, con);
        sda.Fill(ds);
        String       po      = ds.Tables[0].Rows[0]["PONo"].ToString();
        Document     pdfDoc  = new Document(PageSize.A4, 10, 10, 10, 10);
        MemoryStream PDFData = new MemoryStream();
        //PdfWriter pw = PdfWriter.GetInstance(
        //PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream(Context.Server.MapPath("~/uploads/PurchaseOrders/") + po + ".pdf", FileMode.Create));
        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, PDFData);

        var titleFont      = FontFactory.GetFont("Arial", 6, Font.NORMAL);
        var titleFontBlue  = FontFactory.GetFont("Arial", 14, Font.NORMAL, Color.BLUE);
        var boldTableFont  = FontFactory.GetFont("Arial", 8, Font.BOLD);              //8
        var boldTableFont1 = FontFactory.GetFont("Arial", 8, Font.BOLD);              //8
        var bodyFont       = FontFactory.GetFont("Arial", 7, Font.NORMAL);            //8
        var EmailFont      = FontFactory.GetFont("Arial", 8, Font.BOLD, Color.BLACK); //8
        var HeaderFont     = FontFactory.GetFont("Arial", 10, Font.BOLD, Color.BLACK);

        var   footerfont = FontFactory.GetFont("Arial", 6, Font.NORMAL, Color.BLACK);//8
        Color TabelHeaderBackGroundColor = WebColors.GetRGBColor("#EEEEEE");

        Rectangle pageSize = writer.PageSize;

        // Open the Document for writing
        pdfDoc.Open();
        //Add elements to the document here

        #region Top table
        // Create the header table
        PdfPTable headertable = new PdfPTable(3);
        headertable.HorizontalAlignment = 0;
        headertable.WidthPercentage     = 100;
        headertable.SetWidths(new float[] { 100f, 320f, 220f }); // then set the column's __relative__ widths
        headertable.DefaultCell.Border = Rectangle.NO_BORDER;
        headertable.DefaultCell.Border = Rectangle.BOX;          //for testing



        // invoice rperte

        PdfPTable Invoicetable2 = new PdfPTable(1);
        Invoicetable2.HorizontalAlignment = 0;
        Invoicetable2.WidthPercentage     = 100;
        Invoicetable2.SetWidths(new float[] { 500f });  // then set the column's __relative__ widths
        Invoicetable2.DefaultCell.Border = Rectangle.NO_BORDER;

        {
            PdfPTable mainN = new PdfPTable(1);
            // tablenew.HorizontalAlignment = 1;
            //PdfPCell cellnew = new PdfPCell(new Phrase("PURCHASE ORDER"),EmailFont);
            //    PdfPCell cellN = new PdfPCell(new Phrase("Trimurti Diagnostics \n\n Home/Clinic Collection No : 7777 8866 04/05, 9766 6600 83 | 0253 2376062 "
            //+ "\n\n28, Purab Paschim Plaza, Divya Adlabs Building, Trimurti Chowk, CIDCO, Nashik - 422008", HeaderFont)); ;
            PdfPCell cellN = new PdfPCell(new Phrase("Morya Tools \n\n 22, Pradhan Park, M.G Road, Nashik, Maharashtra, India 422001 "
                                                     + "\n\nPhone: (0253) 3014578 Email: [email protected]", HeaderFont));
            cellN.PaddingTop        = 15f;
            cellN.PaddingBottom     = 15f;
            cellN.VerticalAlignment = 1;
            //cellnew.Colspan = 2;
            cellN.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
            mainN.AddCell(cellN);
            PdfPCell nesthousingnn = new PdfPCell(mainN);

            PdfPTable tablenew = new PdfPTable(1);
            // tablenew.HorizontalAlignment = 1;
            //PdfPCell cellnew = new PdfPCell(new Phrase("PURCHASE ORDER"),EmailFont);
            PdfPCell cellnew = new PdfPCell(new Phrase("PURCHASE ORDER", EmailFont));
            cellnew.PaddingTop        = 15f;
            cellnew.PaddingBottom     = 15f;
            cellnew.VerticalAlignment = 1;
            //cellnew.Colspan = 2;
            cellnew.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
            tablenew.AddCell(cellnew);
            PdfPCell nesthousingn = new PdfPCell(tablenew);



            PdfPTable tablenew1 = new PdfPTable(2);

            // tablenew1.DefaultCell.FixedHeight = 100f;
            PdfPCell cellnew4 = new PdfPCell(new Phrase("PO No :    " + ds.Tables[0].Rows[0]["PONo"].ToString(), EmailFont));
            cellnew4.FixedHeight         = 30f;
            cellnew4.HorizontalAlignment = 1;
            cellnew4.PaddingTop          = 15f;
            cellnew4.PaddingBottom       = 15f;
            PdfPCell cellnew5 = new PdfPCell(new Phrase("PO Date :  " + ds.Tables[0].Rows[0]["OrderDate1"].ToString(), EmailFont));
            cellnew5.HorizontalAlignment = 1;
            cellnew5.PaddingTop          = 15f;
            cellnew5.PaddingBottom       = 15f;

            tablenew1.AddCell(cellnew4);

            tablenew1.AddCell(cellnew5);



            PdfPTable tablevendor = new PdfPTable(2);

            PdfPCell suppliername = new PdfPCell(new Phrase("VENDOR NAME :    " + ds.Tables[0].Rows[0]["vendorName"].ToString(), EmailFont));
            suppliername.MinimumHeight = 80f;
            suppliername.PaddingTop    = 10f;
            PdfPCell supplierdetails = new PdfPCell(new Phrase("VENDOR DETAILS:  \n\n\t Contact Person : " + ds.Tables[0].Rows[0]["vendorName"].ToString() + "\n\n\t Mobile No : " + ds.Tables[0].Rows[0]["MobileNo1"].ToString() + "\n\n\t Email : " + ds.Tables[0].Rows[0]["email"].ToString(), EmailFont));
            supplierdetails.PaddingTop = 10f;
            // PdfPCell termsnconditions = new PdfPCell(new Phrase("Terms & Conditions:    ", EmailFont));

            tablevendor.AddCell(suppliername);
            tablevendor.AddCell(supplierdetails);
            //tablevendor.AddCell(termsnconditions);



            PdfPCell nesthousingn1 = new PdfPCell(tablenew1);
            PdfPCell nesthousingn2 = new PdfPCell(tablevendor);
            // nesthousingn2.Height = 10f;
            //PdfPCell nesthousingn3 = new PdfPCell(tablenew3);


            nesthousingn.Border = Rectangle.NO_BORDER;

            //nesthousingn.PaddingBottom = 10f;
            Invoicetable2.AddCell(nesthousingnn);
            Invoicetable2.AddCell(nesthousingn);
            Invoicetable2.AddCell(nesthousingn1);
            Invoicetable2.AddCell(nesthousingn2);
            //Invoicetable2.AddCell(nesthousingn3);
        }
        //invoice repeat

        // Invoicetable2.AddCell(headertable);
        Invoicetable2.SpacingBefore = 3f;
        //  Invoicetable. = 10f;

        // pdfDoc.Add(Invoicetable);



        #endregion

        #region Items Table
        //Create body table
        PdfPTable itemTable = new PdfPTable(3);

        itemTable.HorizontalAlignment = 0;
        itemTable.WidthPercentage     = 100;
        // itemTable.SetWidths(new float[] { });  // then set the column's __relative__ widths
        //itemTable.SetWidths(new float[] { 4, 30, 6, 6, 6 });
        itemTable.SpacingAfter = 10;

        //itemTable.DefaultCell.Border = Rectangle.BOX;



        PdfPCell cell1 = new PdfPCell(new Phrase("PRODUCT", boldTableFont));
        //cell1.BackgroundColor = TabelHeaderBackGroundColor;
        cell1.HorizontalAlignment = Element.ALIGN_CENTER;
        itemTable.AddCell(cell1);

        PdfPCell cell2 = new PdfPCell(new Phrase("IMAGE", boldTableFont));
        //cell2.BackgroundColor = TabelHeaderBackGroundColor;
        cell2.HorizontalAlignment = 1;
        itemTable.AddCell(cell2);

        /*
         * PdfPCell cell2 = new PdfPCell(new Phrase("BRAND", boldTableFont));
         * //cell2.BackgroundColor = TabelHeaderBackGroundColor;
         * cell2.HorizontalAlignment = 1;
         * itemTable.AddCell(cell2);
         *
         *
         *
         * PdfPCell cell3 = new PdfPCell(new Phrase("SIZE", boldTableFont));
         * //cell4.BackgroundColor = TabelHeaderBackGroundColor;
         * cell3.HorizontalAlignment = 1;
         * itemTable.AddCell(cell3);
         */

        PdfPCell cell4 = new PdfPCell(new Phrase("QUANTITY", boldTableFont));
        //cell5.BackgroundColor = TabelHeaderBackGroundColor;
        cell4.HorizontalAlignment = 1;
        itemTable.AddCell(cell4);


        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            PdfPCell cell1i = new PdfPCell(new Phrase(ds.Tables[0].Rows[i]["ProdName"].ToString(), bodyFont));
            //cell1.BackgroundColor = TabelHeaderBackGroundColor;
            cell1i.HorizontalAlignment = Element.ALIGN_CENTER;
            itemTable.AddCell(cell1i);


            if (!String.IsNullOrEmpty(ds.Tables[0].Rows[i]["imagename"].ToString()))
            {
                iTextSharp.text.Image myImage = iTextSharp.text.Image.GetInstance(Server.MapPath("uploads/product/" + ds.Tables[0].Rows[i]["imagename"].ToString()));
                myImage.ScaleAbsolute(20f, 20f);
                PdfPCell cell2i = new PdfPCell(myImage);
                //cell2.BackgroundColor = TabelHeaderBackGroundColor;
                cell2i.HorizontalAlignment = 1;
                itemTable.AddCell(cell2i);
            }
            else
            {
                iTextSharp.text.Image myImage = iTextSharp.text.Image.GetInstance(Server.MapPath("uploads/ImageNotFound.png"));
                myImage.ScaleAbsolute(20f, 20f);
                PdfPCell cell2i = new PdfPCell(myImage);
                //cell2.BackgroundColor = TabelHeaderBackGroundColor;
                cell2i.HorizontalAlignment = 1;
                itemTable.AddCell(cell2i);
            }

            /*
             * PdfPCell cell2i = new PdfPCell(new Phrase(ds.Tables[0].Rows[i]["Brand"].ToString(), bodyFont));
             * //cell2.BackgroundColor = TabelHeaderBackGroundColor;
             * cell2i.HorizontalAlignment = 1;
             * itemTable.AddCell(cell2i);
             *
             *
             *
             * PdfPCell cell4i = new PdfPCell(new Phrase(ds.Tables[0].Rows[i]["Size"].ToString(), bodyFont));
             * //cell4.BackgroundColor = TabelHeaderBackGroundColor;
             * cell4i.HorizontalAlignment = 1;
             * itemTable.AddCell(cell4i);
             */

            PdfPCell cell5i = new PdfPCell(new Phrase(ds.Tables[0].Rows[i]["Quantity1"].ToString(), bodyFont));
            //cell5.BackgroundColor = TabelHeaderBackGroundColor;
            cell5i.HorizontalAlignment = 1;
            itemTable.AddCell(cell5i);

            //    PdfPCell cell3i = new PdfPCell(new Phrase("" + dtOrderProducts.Rows[i]["Amount"], bodyFont));
            //    //cell3.BackgroundColor = TabelHeaderBackGroundColor;
            //    cell3i.HorizontalAlignment = 1;
            //    itemTable.AddCell(cell3i);
        }



        PdfPCell nesthousingn3 = new PdfPCell(itemTable);
        //  PdfPCell nesthousingn4 = new PdfPCell(totalTable);


        //nesthousingn.Border = Rectangle.NO_BORDER;

        //nesthousingn.PaddingBottom = 10f;
        Invoicetable2.AddCell(nesthousingn3);
        // Invoicetable2.AddCell(nesthousingn4);
        // pdfDoc.Add(Invoicetable2);
        #endregion



        PdfPTable noTable1 = new PdfPTable(2);

        noTable1.HorizontalAlignment = 0;
        noTable1.WidthPercentage     = 100;
        // itemTable.SetWidths(new float[] {2,30,6,6,6,6,6,6,6,6,6,4,4,7 });  // then set the column's __relative__ widths
        //amtTable.SetWidths(new float[] { 4, 30});
        // amtTable.SpacingAfter = 10;

        noTable1.DefaultCell.Border = 0;


        PdfPCell cellnote1 = new PdfPCell(new Phrase("PREPARED BY\nNAME : " + "\nSIGNATURE : " + "\nDATE & TIME : ", EmailFont));
        cellnote1.Border = 0;
        cellnote1.HorizontalAlignment = 0;//0=Left, 1=Centre, 2=Right


        noTable1.AddCell(cellnote1);



        PdfPCell cellnote3 = new PdfPCell(new Phrase("FOR MORYA TOOLS\n\n\n\nAUTHORIZED SIGNATORY", EmailFont));
        cellnote3.Border = 0;
        cellnote3.HorizontalAlignment = 2;//0=Left, 1=Centre, 2=Right


        noTable1.AddCell(cellnote3);



        PdfPCell nesthousingn5 = new PdfPCell(noTable1);
        Invoicetable2.AddCell(nesthousingn5);



        pdfDoc.Add(Invoicetable2);
        pdfDoc.Close();



        DownloadPDF(PDFData, po);



        Context.Response.Clear();
        Context.Response.ContentType = "application/json";
        Context.Response.Flush();
        Context.Response.Write(finalResult);
        Context.Response.End();
    }
Exemplo n.º 22
0
        /// <summary>
        /// Builds report summary.
        /// </summary>
        private void BuildSummary()
        {
            Document.NewPage();
            int testCount, testsPassed, testsFailed;

            testCount = Log.TestResults.Count;

            testsPassed =
                Log.TestResults.Where(KV => KV.Value.Log.TestStatus == TestStatus.Passed).Count();

            testsFailed = Log.TestResults.Where(KV => KV.Value.Log.TestStatus == TestStatus.Failed).Count();

            Paragraph p0 = new Paragraph(new Chunk("\n", FontFactory.GetFont(FontFactory.TIMES, 16)));

            p0.Add("ONVIF Test Summary\n");
            p0.Alignment = Element.ALIGN_CENTER;
            Document.Add(p0);


            Paragraph p2 = new Paragraph(new Chunk("\n", FontFactory.GetFont(FontFactory.TIMES, 12)));

            p2.Add(String.Format("Tests Executed: {0}\n", testCount));
            p2.Add(String.Format("Tests Passed:  {0}\n", testsPassed));
            p2.Add(String.Format("Tests Failed:  {0}\n", testsFailed));
            p2.Add("\n");
            Document.Add(p2);


            // Features
            Document.Add(new Chunk(Environment.NewLine));
            PrintFetures(FontFactory.GetFont(FontFactory.TIMES, 12)
                         , FontFactory.GetFont(FontFactory.TIMES, 10));

            //
            // Settings:
            //

            Paragraph pTimeouts = new Paragraph(new Chunk("\n", FontFactory.GetFont(FontFactory.TIMES, 12)));

            pTimeouts.Add("Timeouts (ms): \n");
            pTimeouts.Add(string.Format("Message Timeout: {0}\n", Log.DeviceEnvironment.Timeouts.Message));
            pTimeouts.Add(string.Format("Reboot Timeout: {0}\n", Log.DeviceEnvironment.Timeouts.Reboot));
            pTimeouts.Add(string.Format("Time between Tests: {0}\n", Log.DeviceEnvironment.Timeouts.InterTests));
            pTimeouts.Add(string.Format("Time between Requests: {0}\n", Log.DeviceEnvironment.TestSettings.RecoveryDelay));
            pTimeouts.Add(string.Format("Operation Delay: {0}\n", Log.DeviceEnvironment.TestSettings.OperationDelay));
            Document.Add(pTimeouts);

            Paragraph pRealTimeouts = new Paragraph(new Chunk("\n", FontFactory.GetFont(FontFactory.TIMES, 12)));

            pRealTimeouts.Add("Real Timeouts (ms): \n");
            pRealTimeouts.Add(string.Format("Maximum Timeout: {0}\n", Log.Timeouts.Maximum));
            pRealTimeouts.Add(string.Format("Median Timeout: {0}\n", Log.Timeouts.Median));
            pRealTimeouts.Add(string.Format("Average Timeout: {0}\n", Log.Timeouts.Average));
            Document.Add(pRealTimeouts);

            Paragraph pAccount = new Paragraph(new Chunk("\n", FontFactory.GetFont(FontFactory.TIMES, 12)));

            pAccount.Add(string.Format("Account: {0}", Log.DeviceEnvironment.Credentials.UserName));
            Document.Add(pAccount);

            bool passed = (testsFailed == 0);

            // Summary
            Paragraph p6 = new Paragraph(new Chunk("\n", FontFactory.GetFont(FontFactory.TIMES, 16)));

            if (passed)
            {
                p6.Add("TEST PASSED\n");
            }
            else
            {
                p6.Add("TEST FAILED\n");
            }
            p6.Alignment = Element.ALIGN_CENTER;
            Document.Add(p6);

            AddFeaturesDefinitionLog();

            ListFailedTests();
        }
Exemplo n.º 23
0
        private void AddHeaderAndFooter(CSVData csvData, InputRow row, Document doc, System.Drawing.Image image)
        {
            string headerFooterString = row.HeaderFooterMetadata;

            var       pageSize = doc.PageSize;
            PdfPTable table    = new PdfPTable(3);

            table.WidthPercentage = 100;

            var fontRegular = FontFactory.GetFont("Arial", 7);

            if (csvData.HeaderLeft)
            {
                AddTextCell(table, headerFooterString, fontRegular, PdfPCell.ALIGN_LEFT);
            }
            else
            {
                AddEmptyCell(table);
            }

            if (csvData.HeaderCenter)
            {
                AddTextCell(table, headerFooterString, fontRegular);
            }
            else
            {
                AddEmptyCell(table);
            }

            if (csvData.HeaderRight)
            {
                AddTextCell(table, headerFooterString, fontRegular, PdfPCell.ALIGN_RIGHT);
            }
            else
            {
                AddEmptyCell(table);
            }

            doc.Add(table);

            table = new PdfPTable(1);
            table.WidthPercentage = 100;
            PdfPCell rightCell = new PdfPCell(new iTextSharp.text.Phrase("CERTIFIED TRUE COPY of Document held by Wencor QA", fontRegular));

            rightCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
            rightCell.Border = 0;
            table.AddCell(rightCell);
            doc.Add(table);

            table = new PdfPTable(1);
            table.DefaultCell.Border = 0;
            table.WidthPercentage    = 100;

            var imageCell = Image.GetInstance(image, (BaseColor)null);

            //imageCell.SpacingAfter = 50;
            table.AddCell(imageCell);
            table.SpacingAfter  = 20;
            table.SpacingBefore = 20;
            doc.Add(table);

            table = new PdfPTable(1);
            table.WidthPercentage         = 100;
            rightCell                     = new PdfPCell(new iTextSharp.text.Phrase("CERTIFIED TRUE COPY of Document held by Wencor QA", fontRegular));
            rightCell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
            rightCell.Border              = 0;
            table.AddCell(rightCell);
            doc.Add(table);

            table = new PdfPTable(3);
            table.WidthPercentage = 100;

            if (csvData.FooterLeft)
            {
                AddTextCell(table, headerFooterString, fontRegular, PdfPCell.ALIGN_LEFT);
            }
            else
            {
                AddEmptyCell(table);
            }

            if (csvData.FooterCenter)
            {
                AddTextCell(table, headerFooterString, fontRegular);
            }
            else
            {
                AddEmptyCell(table);
            }

            if (csvData.FooterRight)
            {
                AddTextCell(table, headerFooterString, fontRegular, PdfPCell.ALIGN_RIGHT);
            }
            else
            {
                AddEmptyCell(table);
            }

            doc.Add(table);
        }
Exemplo n.º 24
0
        private void ListFailedTests()
        {
            Document.NewPage();

            Paragraph p1 = new Paragraph(new Chunk("The following tests were FAILED:\n", FontFactory.GetFont(FontFactory.TIMES, 16)));

            p1.Alignment = Element.ALIGN_CENTER;
            Document.Add(p1);

            foreach (KeyValuePair <TestInfo, Data.TestResult> testInfo in
                     Log.TestResults.Where(tr => tr.Value.Log.TestStatus == TestStatus.Failed).OrderBy(T => T.Key.Category).ThenBy(T => T.Key.Order))
            {
                Paragraph p = new Paragraph(new Chunk(testInfo.Key.Name,
                                                      FontFactory.GetFont(FontFactory.TIMES, 12)));
                Document.Add(p);
            }
        }
Exemplo n.º 25
0
        public MemoryStream GeneratePdfTemplate(GarmentShippingCreditNoteViewModel viewModel)
        {
            Font normal_font     = FontFactory.GetFont(BaseFont.COURIER, 10, Font.NORMAL);
            Font underlined_font = FontFactory.GetFont(BaseFont.COURIER, 10, Font.UNDERLINE);
            Font big_font        = FontFactory.GetFont(BaseFont.COURIER, 16, Font.BOLD);

            Document     document = new Document(PageSize.A4, 20, 20, 20, 20);
            MemoryStream stream   = new MemoryStream();
            PdfWriter    writer   = PdfWriter.GetInstance(document, stream);

            document.Open();

            var chunkHeader = new Chunk("PT. DAN LIRIS", big_font);

            chunkHeader.SetHorizontalScaling(1.5f);
            document.Add(new Paragraph(chunkHeader));

            PdfPTable tableHeadOffice = new PdfPTable(2);

            tableHeadOffice.SetWidths(new float[] { 1.5f, 6.5f });

            PdfPCell cellHeadOffice = new PdfPCell {
                Border = Rectangle.NO_BORDER
            };

            cellHeadOffice.Phrase = new Phrase("Head Office : ", normal_font);
            tableHeadOffice.AddCell(cellHeadOffice);
            cellHeadOffice.Phrase = new Phrase("Jl. Merapi No. 23, Kel. Banaran Kec. Grogol Kab. Sukoharjo\nTelp.(0271)714400, Fax.(0271)735222\ne-Mail:", normal_font);
            cellHeadOffice.Phrase.Add(new Chunk("*****@*****.**", underlined_font));
            tableHeadOffice.AddCell(cellHeadOffice);
            Chunk chunkAddress = new Chunk("MESSRS :\n" + viewModel.buyer.Name + "\n" + viewModel.buyer.Address, normal_font);

            chunkAddress.SetHorizontalScaling(0.8f);
            Phrase phraseBuyerHeader = new Phrase(chunkAddress);

            //phraseBuyerHeader.Add(new Chunk(new VerticalPositionMark()));
            //phraseBuyerHeader.Add(new Chunk("CREDIT NOTE", normal_font));

            phraseBuyerHeader.Add(new Chunk(new VerticalPositionMark()));
            phraseBuyerHeader.Add(new Chunk("DATE : " + viewModel.date.GetValueOrDefault().ToString("MMMM dd, yyyy"), normal_font));

            tableHeadOffice.AddCell(new PdfPCell
            {
                Border      = Rectangle.NO_BORDER,
                Colspan     = 2,
                PaddingLeft = 10f,
                Phrase      = phraseBuyerHeader
            });

            new PdfPCell(tableHeadOffice);
            tableHeadOffice.ExtendLastRow = false;
            tableHeadOffice.SpacingAfter  = 5f;
            document.Add(tableHeadOffice);

            document.Add(new Paragraph("CREDIT NOTE", big_font)
            {
                Alignment = Element.ALIGN_CENTER, SpacingAfter = 5f
            });

            document.Add(new Paragraph(viewModel.noteNo, big_font)
            {
                Alignment = Element.ALIGN_RIGHT, SpacingAfter = 5f
            });

            PdfPTable tableItems = new PdfPTable(2);

            tableItems.SetWidths(new float[] { 3f, 1f });

            tableItems.AddCell(new PdfPCell
            {
                Border = Rectangle.TOP_BORDER | Rectangle.BOTTOM_BORDER,
                HorizontalAlignment = Element.ALIGN_CENTER,
                Phrase = new Phrase("D e s c r i p t i o n", normal_font)
            });
            tableItems.AddCell(new PdfPCell
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER,
                HorizontalAlignment = Element.ALIGN_CENTER,
                Phrase = new Phrase("Amount", normal_font)
            });

            PdfPTable tableItemsContent = new PdfPTable(2);

            tableItemsContent.SetWidths(new float[] { 3f, 1f });

            foreach (var item in viewModel.items)
            {
                tableItemsContent.AddCell(new PdfPCell
                {
                    Border = Rectangle.NO_BORDER,
                    Phrase = new Phrase(item.description, normal_font)
                });
                Phrase phraseAmount = new Phrase();
                phraseAmount.Add(new Chunk("US$", normal_font));
                phraseAmount.Add(new Chunk(new VerticalPositionMark()));
                phraseAmount.Add(new Chunk(item.amount.ToString("n"), normal_font));
                tableItemsContent.AddCell(new PdfPCell
                {
                    Border = Rectangle.LEFT_BORDER,
                    Phrase = phraseAmount
                });
            }

            PdfPCell pdfPCellItemsContent = new PdfPCell
            {
                Colspan       = 2,
                Padding       = 0,
                Border        = Rectangle.NO_BORDER,
                MinimumHeight = 500
            };

            new PdfPCell(tableItemsContent);
            pdfPCellItemsContent.AddElement(tableItemsContent);
            tableItems.AddCell(pdfPCellItemsContent);

            tableItems.AddCell(new PdfPCell
            {
                Border = Rectangle.TOP_BORDER,
                HorizontalAlignment = Element.ALIGN_RIGHT,
                PaddingRight        = 10,
                Phrase = new Phrase("TOTAL", normal_font)
            });
            Phrase phraseTotalAmount = new Phrase();

            phraseTotalAmount.Add(new Chunk("US$", normal_font));
            phraseTotalAmount.Add(new Chunk(new VerticalPositionMark()));
            phraseTotalAmount.Add(new Chunk(viewModel.totalAmount.ToString("n"), normal_font));
            tableItems.AddCell(new PdfPCell
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER,
                Phrase = phraseTotalAmount
            });
            tableItems.AddCell(new PdfPCell
            {
                Colspan       = 2,
                PaddingBottom = 10f,
                Border        = Rectangle.NO_BORDER,
                Phrase        = new Phrase("SAY : US DOLLARS " + NumberToTextEN.toWords(viewModel.totalAmount).Trim().ToUpper() + " ONLY ///", normal_font)
            });

            tableItems.AddCell(new PdfPCell
            {
                Border       = Rectangle.NO_BORDER,
                PaddingRight = 10f,
                Phrase       = new Phrase(" ", normal_font)
            });
            Phrase phraseSign = new Phrase();

            phraseSign.Add(new Chunk("S.E. & O\n" + viewModel.date.GetValueOrDefault().ToString("MMMM dd, yyyy") + "\n\n\n\n", normal_font));
            Chunk chunkSignName = new Chunk("A M U M P U N I", normal_font);

            chunkSignName.SetUnderline(1, -1);
            phraseSign.Add(chunkSignName);
            phraseSign.Add(new Chunk("\nAUTHORIZED SIGNATURE", normal_font));
            tableItems.AddCell(new PdfPCell
            {
                Border = Rectangle.NO_BORDER,
                HorizontalAlignment = Element.ALIGN_CENTER,
                Phrase = phraseSign
            });

            new PdfPCell(tableItems);
            tableItems.ExtendLastRow = false;
            tableItems.SpacingAfter  = 5f;
            document.Add(tableItems);

            document.Close();
            byte[] byteInfo = stream.ToArray();
            stream.Write(byteInfo, 0, byteInfo.Length);
            stream.Position = 0;

            return(stream);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Adds test group info.
        /// </summary>
        private void AddTestGroupInfo()
        {
            Document.NewPage();

            Paragraph title   = new Paragraph("ONVIF TEST", FontFactory.GetFont(FontFactory.TIMES, 18));
            Chapter   chapter = new Chapter(title, 2);

            chapter.NumberDepth = 0;
            Paragraph empty = new Paragraph("\n\n");

            chapter.Add(empty);

            string  lastGroup = string.Empty;
            Section section   = null;

            foreach (TestInfo info in Log.TestResults.Keys.OrderBy(T => T.Category).ThenBy(TI => TI.Order))
            {
                string group = info.Group.Split('\\')[0];
                if (lastGroup != group)
                {
                    Paragraph groupTitle = new Paragraph(string.Format("\n\n{0}", group), FontFactory.GetFont(FontFactory.TIMES, 18));
                    section             = chapter.AddSection(groupTitle);
                    section.NumberDepth = 0;
                    Paragraph someSectionText = new Paragraph("\n");
                    section.Add(someSectionText);
                    lastGroup = group;
                }

                Paragraph testTitle = new Paragraph();
                Anchor    ancor     = new Anchor(info.Name);
                ancor.Name = info.Name;
                testTitle.Add(ancor);
                Section testSection = section.AddSection(testTitle);
                testSection.NumberDepth = 0;

                if (info.RequirementLevel == RequirementLevel.Optional)
                {
                    Paragraph optional = new Paragraph("* Optional Test");
                    testSection.Add(optional);
                }

                string testDescription = string.Empty;

                if (Log.TestResults.ContainsKey(info))
                {
                    testDescription = string.Format("\nTestResult\n{0}\n", Log.TestResults[info].ShortTextLog);
                    testDescription = testDescription.Replace(string.Format("{0}\r\n", info.Name), "");
                }
                else
                {
                    testDescription = "Test not run\n\n";
                }

                Paragraph sectionText = new Paragraph(testDescription, FontFactory.GetFont(FontFactory.TIMES, 10));
                testSection.Add(sectionText);
            }

            Document.Add(chapter);
        }
Exemplo n.º 27
0
        protected override void CreateTitlePage()
        {
            var titleFont = FontFactory.GetFont("Calibri", 20);
            var caseFont  = FontFactory.GetFont("Cambria", 16);
            var font      = FontFactory.GetFont("Calibri", 14);

            var outerTable = new PdfPTable(1)
            {
                WidthPercentage = 100f
            };
            var outerTableCell = new PdfPCell
            {
                MinimumHeight     = Document.PageSize.Height - (Document.TopMargin + Document.BottomMargin),
                VerticalAlignment = Element.ALIGN_MIDDLE,
                Border            = Rectangle.NO_BORDER
            };

            var table = new PdfPTable(2)
            {
                WidthPercentage     = 100,
                HorizontalAlignment = Element.ALIGN_CENTER
            };

            table.DefaultCell.Border = Rectangle.NO_BORDER; // TODO: Doesn't seem to work

            table.AddCell(new PdfPCell());
            var greenLine     = new Chunk(new LineSeparator(6f, 100f, new BaseColor(51, 153, 102), Element.ALIGN_CENTER, 0f));
            var greenLineCell = new PdfPCell {
                VerticalAlignment = Element.ALIGN_MIDDLE
            };

            greenLineCell.AddElement(greenLine);
            table.AddCell(greenLineCell);

            table.AddCell(new PdfPCell());
            var caseNumberCell = MakeCell(Settings.CaseNumber, caseFont, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE);

            caseNumberCell.FixedHeight = 20f;
            table.AddCell(caseNumberCell);

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

            table.AddCell(new PdfPCell());
            var reportTitleCell = MakeCell(Settings.ReportTitle, titleFont, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE);

            reportTitleCell.FixedHeight = 40f;
            table.AddCell(reportTitleCell);

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

            table.AddCell(new PdfPCell());
            table.AddCell(MakeCell(Settings.Agency, font));

            table.AddCell(new PdfPCell());
            table.AddCell(MakeCell(Settings.AgencyInfo, font));

            table.AddCell(new PdfPCell());
            table.AddCell(MakeCell(Settings.UnitName, font));

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

            table.AddCell(new PdfPCell());
            table.AddCell(MakeCell(Settings.NameTitlePin, font));

            table.AddCell(new PdfPCell());
            var additionalNames = new Phrase {
                Font = font
            };

            for (var i = 0; i < Settings.AdditionalNames.Count; i++)
            {
                var separator = i < Settings.AdditionalNames.Count - 1 ? ", " : "";
                additionalNames.Add($"{Settings.AdditionalNames[i]}{separator}");
            }
            var additionalNamesCell = new PdfPCell {
                Border = Rectangle.NO_BORDER
            };

            additionalNamesCell.AddElement(additionalNames);
            table.AddCell(additionalNamesCell);

            table.AddCell(new PdfPCell());
            table.AddCell(MakeCell(Settings.AdditionalInfo, font));

            table.AddCell(new PdfPCell());
            table.AddCell(MakeCell(Settings.Date.ToLongDateString(), font));

            FormatTableCells(table, null);

            outerTableCell.AddElement(table);
            outerTable.AddCell(outerTableCell);
            Document.Add(outerTable);
        }
Exemplo n.º 28
0
        /// <summary>
        /// Builds cover page with logo and general information.
        /// </summary>
        private void BuildCoverPage()
        {
            //Add logo
            Stream imgStream = null;

            // get a reference to the current assembly
            Assembly assembly = Assembly.GetExecutingAssembly();

            // get a list of resource names from the manifest
            string[] resNames = assembly.GetManifestResourceNames();

            // look for the logo
            foreach (string s in resNames)
            {
                // locate the logo.gif in the assembly
                if (s.EndsWith("logo.gif"))
                {
                    // attach to stream to the resource in the manifest
                    imgStream = assembly.GetManifestResourceStream(s);
                    break;
                }
            }
            if (imgStream != null)
            {
                Image logo = Image.GetInstance(imgStream);
                logo.Alignment = Element.ALIGN_CENTER;
                Document.Add(logo);
            }

            //
            Document.Add(new Paragraph(Environment.NewLine));
            Document.Add(new Paragraph(Environment.NewLine));
            Document.Add(new Paragraph(Environment.NewLine));

            //
            Paragraph p0 = new Paragraph(new Chunk("\n", FontFactory.GetFont(FontFactory.TIMES, 12)));

            p0.Add(new Chunk("ONVIF Conformance Test", FontFactory.GetFont(FontFactory.TIMES_BOLD, 20)));
            p0.Add("\n\n");

            p0.Add(new Chunk("Performed by", FontFactory.GetFont(FontFactory.TIMES, 16)));
            p0.Add("\n\n");

            p0.Add(String.Format("Operator - {0}\n", Log.TesterInfo.Operator));
            p0.Add(String.Format("Organization - {0}\n", Log.TesterInfo.Organization));
            p0.Add(String.Format("Address - {0}\n", Log.TesterInfo.Address));

            //add empty lines
            p0.Add(Environment.NewLine);
            p0.Add(Environment.NewLine);

            p0.Add(new Chunk("Device Under Test", FontFactory.GetFont(FontFactory.TIMES, 16)));
            p0.Add("\n\n");
            p0.Add(String.Format("Product Name - {0}\n", Log.ProductName));
            p0.Add(String.Format("Brand - {0}\n", Log.DeviceInformation.Manufacturer));
            p0.Add(String.Format("Model - {0}\n", Log.DeviceInformation.Model));
            p0.Add(String.Format("Product Type - {0}\n", Log.ProductTypes));
            p0.Add(String.Format("Serial Number - {0}\n", Log.DeviceInformation.SerialNumber));
            p0.Add(String.Format("Firmware Version - {0}\n", Log.DeviceInformation.FirmwareVersion));
            p0.Add(String.Format("Other - {0}\n", Log.OtherInformation));

            p0.Add(Environment.NewLine);
            p0.Add(Environment.NewLine);
            p0.Add(Environment.NewLine);

            // add the ONVIF information

            p0.Add(String.Format("{0}", Log.Application.ToolVersionFull));
            //p0.Add(Environment.NewLine);
            //p0.Add(String.Format("{0}", Log.Application.TestSpecification));
            p0.Alignment = Element.ALIGN_CENTER;
            p0.Add(Environment.NewLine);
            p0.Add(Environment.NewLine);
            p0.Add(Environment.NewLine);

            p0.Add(string.Format("Test Date and Time - {0} @ {1}", Log.TestExecutionTime.ToShortDateString(), Log.TestExecutionTime.ToLongTimeString()));

            Document.Add(p0);
        }
Exemplo n.º 29
0
        public Document FeesPrinting(List <TermRegistration> registration, ref StringWriter sw, ref Document itextDoc)
        {
            PdfPTable table3 = new PdfPTable(2);

            table3.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
            iTextSharp.text.Image imgPDF = iTextSharp.text.Image.GetInstance(HttpRuntime.AppDomainAppPath + "\\Images\\wexford.jpg");
            imgPDF.ScaleToFit(128, 100);
            // imgPDF.ScaleToFit(200, 200);
            PdfPCell theImage = new PdfPCell(imgPDF);

            theImage.Border = iTextSharp.text.Rectangle.NO_BORDER;
            table3.AddCell(theImage);

            iTextSharp.text.Font font_heading_1 = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12, iTextSharp.text.Font.BOLD);

            iTextSharp.text.Font font_heading_2 = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 11, iTextSharp.text.Font.BOLD);
            //  iTextSharp.text.Font font_heading_3 = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 10, iTextSharp.text.Font.BOLD);

            PdfPTable theSchoolNameTable = new PdfPTable(1);

            PdfPCell theWexFord = new PdfPCell(new Paragraph("WEXFORD COLLEGE", font_heading_1));

            theWexFord.Border = iTextSharp.text.Rectangle.NO_BORDER;
            // theWexFord.w

            PdfPCell theWexFordFirstGate = new PdfPCell(new Paragraph(new Paragraph("FIRST GATE OBA ILE HOUSING ESTATE, AKURE, AKURE NORTH L.G.A,   ", font_heading_1)));

            theWexFordFirstGate.Border = iTextSharp.text.Rectangle.NO_BORDER;

            PdfPCell theWexFordMoto = new PdfPCell(new Paragraph("MOTTO: INTELLIGENCE, INTEGRITY & INDUSTRY", font_heading_1));

            theWexFordMoto.Border = iTextSharp.text.Rectangle.NO_BORDER;

            theSchoolNameTable.AddCell(theWexFord);
            theSchoolNameTable.AddCell(theWexFordFirstGate);
            theSchoolNameTable.AddCell(theWexFordMoto);
            table3.AddCell(theSchoolNameTable);



            itextDoc.Add(table3);

            itextDoc.Add(new Paragraph("  "));

            itextDoc.Add(new Paragraph("  "));

            iTextSharp.text.Font font_heading_3 = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 10, iTextSharp.text.Font.BOLD);

            PdfPTable table4 = new PdfPTable(8);


            table4.AddCell((new Paragraph("S/N", font_heading_3)));
            table4.AddCell((new Paragraph("Name", font_heading_3)));
            table4.AddCell((new Paragraph("Sex", font_heading_3)));
            table4.AddCell((new Paragraph("Class", font_heading_3)));
            table4.AddCell((new Paragraph("Session", font_heading_3)));
            table4.AddCell((new Paragraph("School Fees Category", font_heading_3)));
            table4.AddCell((new Paragraph("School Fees  (NGN)", font_heading_3)));
            table4.AddCell((new Paragraph("Owing  (NGN)", font_heading_3)));

            int counter = 1;

            foreach (var s in registration)
            {
                // s.

                //PdfPTable table = new PdfPTable(2);
                List <SchoolFeePayment> theStudentPayments = new List <SchoolFeePayment>();
                theStudentPayments = work.SchoolFeePaymentRepository.Get(a => a.StudentID == s.StudentID).ToList();
                SchoolFeePayment theStudentPayment = new SchoolFeePayment();
                // theStudentPayment.Owing = 0;
                if (theStudentPayments.Count > 0)
                {
                    theStudentPayment = theStudentPayments.OrderByDescending(a => a.DatePaid).First();
                    // theStudentPayment.Owing = 0;
                }
                table4.DefaultCell.Border = iTextSharp.text.Rectangle.BOX;
                decimal toTalDeduction = 0;
                /// toTalDeduction = Convert.ToDecimal(s.TotalLatenessDeduction) + toTalDeduction;
                // toTalDeduction = Convert.ToDecimal(s.TotalLoan) + toTalDeduction;
                // toTalDeduction = Convert.ToDecimal(s.TotalAbscentDeduction) + toTalDeduction;

                table4.AddCell(new Paragraph(Convert.ToString(counter), font_heading_3));

                table4.AddCell(new Paragraph(s.LastName + " " + s.FirstName, font_heading_3));
                table4.AddCell(new Paragraph(s.Sex, font_heading_2));
                table4.AddCell(new Paragraph(s.Level, font_heading_2));
                table4.AddCell(new Paragraph(s.Session, font_heading_2));
                table4.AddCell(new Paragraph(s.SchoolFeesKind, font_heading_2));
                table4.AddCell(new Paragraph(Convert.ToString(s.Cost), font_heading_2));
                table4.AddCell(new Paragraph(Convert.ToString(theStudentPayment.Owing), font_heading_2));


                counter = counter + 1;
            }
            itextDoc.Add(table4);
            return(itextDoc);
        }
Exemplo n.º 30
0
        private void metroButton1_Click(object sender, EventArgs e)
        {
            d = new Document(iTextSharp.text.PageSize.A4, 10, 10, 60, 30);
            PdfWriter wri = PdfWriter.GetInstance(d, new FileStream("test.pdf", FileMode.Create));

            d.Open();
            iTextSharp.text.Font f1 = FontFactory.GetFont("Lucida Sans", "122", Font.Underline);
            PdfPTable            m  = new PdfPTable(1);



            m.AddCell(new PdfPCell()
            {
                HorizontalAlignment = PdfPCell.ALIGN_CENTER, Phrase = new Phrase("JAI MAA VAISHNO DEVI \n"), BorderColor = BaseColor.WHITE, BorderWidth = 0
            });
            d.Add(m);

            PdfPTable m2 = new PdfPTable(1);

            m2.AddCell(new PdfPCell()
            {
                HorizontalAlignment = PdfPCell.ALIGN_CENTER, Phrase = new Phrase("JAI MAA JHANDEWALI \n"), BorderColor = BaseColor.WHITE, BorderWidth = 0
            });
            d.Add(m2);

            PdfPTable m3 = new PdfPTable(1);

            m3.AddCell(new PdfPCell()
            {
                HorizontalAlignment = PdfPCell.ALIGN_CENTER, Phrase = new Phrase("JAI OM SHANKAR BHAGWAN \n"), BorderColor = BaseColor.WHITE, BorderWidth = 0
            });
            d.Add(m3);
            PdfPTable m4 = new PdfPTable(1);

            m4.AddCell(new PdfPCell()
            {
                HorizontalAlignment = PdfPCell.ALIGN_CENTER, Phrase = new Phrase("Sunita Seth's Law Firm \n"), BorderColor = BaseColor.WHITE, BorderWidth = 0
            });
            d.Add(m4);

            PdfPTable m5 = new PdfPTable(1);

            m5.AddCell(new PdfPCell()
            {
                HorizontalAlignment = PdfPCell.ALIGN_LEFT, Phrase = new Phrase("Jatin seth \n"), BorderColor = BaseColor.WHITE, BorderWidth = 0
            });
            d.Add(m5);

            PdfPTable m6 = new PdfPTable(1);

            m6.AddCell(new PdfPCell()
            {
                HorizontalAlignment = PdfPCell.ALIGN_LEFT, Phrase = new Phrase("Advocate \n"), BorderColor = BaseColor.WHITE, BorderWidth = 0
            });
            d.Add(m6);

            PdfPTable m7 = new PdfPTable(1);

            m7.AddCell(new PdfPCell()
            {
                HorizontalAlignment = PdfPCell.ALIGN_LEFT, Phrase = new Phrase("Mob : 9599696060 \n\n\n"), BorderColor = BaseColor.WHITE, BorderWidth = 0
            });
            d.Add(m7);


            PdfPTable m8 = new PdfPTable(1);

            m8.AddCell(new PdfPCell()
            {
                HorizontalAlignment = PdfPCell.ALIGN_LEFT, Phrase = new Phrase("Dwarka\n"), BorderColor = BaseColor.WHITE, BorderWidth = 0
            });
            d.Add(m8);

            m.DefaultCell.HasBorder(iTextSharp.text.Rectangle.NO_BORDER);

            PdfPTable p = new PdfPTable(dataGridView1.Columns.Count);

            //   p.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
            for (int j = 0; j < dataGridView1.Columns.Count; j++)
            {
                p.AddCell(new Phrase(dataGridView1.Columns[j].HeaderText));
            }
            p.HeaderRows = 1;
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                for (int k = 0; k < dataGridView1.Columns.Count; k++)
                {
                    if (dataGridView1[k, i].Value != null)
                    {
                        p.AddCell(new Phrase(dataGridView1[k, i].Value.ToString()));
                    }
                }
            }
            d.Add(p);


            PdfPTable m9 = new PdfPTable(1);

            m9.AddCell(new PdfPCell()
            {
                HorizontalAlignment = PdfPCell.ALIGN_LEFT, Phrase = new Phrase("High court\n"), BorderColor = BaseColor.WHITE, BorderWidth = 0
            });
            d.Add(m9);

            m.DefaultCell.HasBorder(iTextSharp.text.Rectangle.NO_BORDER);

            PdfPTable p2 = new PdfPTable(dataGridView1.Columns.Count);

            for (int j = 0; j < dataGridView2.Columns.Count; j++)
            {
                p2.AddCell(new Phrase(dataGridView2.Columns[j].HeaderText));
            }
            p2.HeaderRows = 1;
            for (int i = 0; i < dataGridView2.Rows.Count; i++)
            {
                for (int k = 0; k < dataGridView2.Columns.Count; k++)
                {
                    if (dataGridView2[k, i].Value != null)
                    {
                        p2.AddCell(new Phrase(dataGridView2[k, i].Value.ToString()));
                    }
                }
            }
            d.Add(p2);


            PdfPTable m10 = new PdfPTable(1);

            m10.AddCell(new PdfPCell()
            {
                HorizontalAlignment = PdfPCell.ALIGN_LEFT, Phrase = new Phrase("Saket\n"), BorderColor = BaseColor.WHITE, BorderWidth = 0
            });
            d.Add(m10);

            m.DefaultCell.HasBorder(iTextSharp.text.Rectangle.NO_BORDER);

            PdfPTable p3 = new PdfPTable(dataGridView3.Columns.Count);

            for (int j = 0; j < dataGridView3.Columns.Count; j++)
            {
                p3.AddCell(new Phrase(dataGridView3.Columns[j].HeaderText));
            }
            p3.HeaderRows = 1;
            for (int i = 0; i < dataGridView3.Rows.Count; i++)
            {
                for (int k = 0; k < dataGridView3.Columns.Count; k++)
                {
                    if (dataGridView3[k, i].Value != null)
                    {
                        p3.AddCell(new Phrase(dataGridView3[k, i].Value.ToString()));
                    }
                }
            }
            d.Add(p3);


            PdfPTable m11 = new PdfPTable(1);

            m11.AddCell(new PdfPCell()
            {
                HorizontalAlignment = PdfPCell.ALIGN_LEFT, Phrase = new Phrase("Tees hazari\n"), BorderColor = BaseColor.WHITE, BorderWidth = 0
            });
            d.Add(m11);

            m.DefaultCell.HasBorder(iTextSharp.text.Rectangle.NO_BORDER);

            PdfPTable p4 = new PdfPTable(dataGridView4.Columns.Count);

            for (int j = 0; j < dataGridView4.Columns.Count; j++)
            {
                p4.AddCell(new Phrase(dataGridView4.Columns[j].HeaderText));
            }
            p4.HeaderRows = 1;
            for (int i = 0; i < dataGridView4.Rows.Count; i++)
            {
                for (int k = 0; k < dataGridView4.Columns.Count; k++)
                {
                    if (dataGridView4[k, i].Value != null)
                    {
                        p4.AddCell(new Phrase(dataGridView4[k, i].Value.ToString()));
                    }
                }
            }
            d.Add(p4);


            PdfPTable m12 = new PdfPTable(1);

            m12.AddCell(new PdfPCell()
            {
                HorizontalAlignment = PdfPCell.ALIGN_LEFT, Phrase = new Phrase("Rohini\n"), BorderColor = BaseColor.WHITE, BorderWidth = 0
            });
            d.Add(m12);

            m.DefaultCell.HasBorder(iTextSharp.text.Rectangle.NO_BORDER);

            PdfPTable p5 = new PdfPTable(dataGridView5.Columns.Count);

            for (int j = 0; j < dataGridView5.Columns.Count; j++)
            {
                p5.AddCell(new Phrase(dataGridView5.Columns[j].HeaderText));
            }
            p5.HeaderRows = 1;
            for (int i = 0; i < dataGridView5.Rows.Count; i++)
            {
                for (int k = 0; k < dataGridView5.Columns.Count; k++)
                {
                    if (dataGridView5[k, i].Value != null)
                    {
                        p5.AddCell(new Phrase(dataGridView5[k, i].Value.ToString()));
                    }
                }
            }
            d.Add(p5);


            PdfPTable m13 = new PdfPTable(1);

            m13.AddCell(new PdfPCell()
            {
                HorizontalAlignment = PdfPCell.ALIGN_LEFT, Phrase = new Phrase("Patiala House\n"), BorderColor = BaseColor.WHITE, BorderWidth = 0
            });
            d.Add(m13);

            m.DefaultCell.HasBorder(iTextSharp.text.Rectangle.NO_BORDER);

            PdfPTable p6 = new PdfPTable(dataGridView1.Columns.Count);

            for (int j = 0; j < dataGridView6.Columns.Count; j++)
            {
                p6.AddCell(new Phrase(dataGridView6.Columns[j].HeaderText));
            }
            p6.HeaderRows = 1;
            for (int i = 0; i < dataGridView6.Rows.Count; i++)
            {
                for (int k = 0; k < dataGridView6.Columns.Count; k++)
                {
                    if (dataGridView6[k, i].Value != null)
                    {
                        p6.AddCell(new Phrase(dataGridView6[k, i].Value.ToString()));
                    }
                }
            }
            d.Add(p6);


            PdfPTable m14 = new PdfPTable(1);

            m14.AddCell(new PdfPCell()
            {
                HorizontalAlignment = PdfPCell.ALIGN_LEFT, Phrase = new Phrase("Karkardooma\n"), BorderColor = BaseColor.WHITE, BorderWidth = 0
            });
            d.Add(m14);

            m.DefaultCell.HasBorder(iTextSharp.text.Rectangle.NO_BORDER);

            PdfPTable p7 = new PdfPTable(dataGridView7.Columns.Count);

            for (int j = 0; j < dataGridView7.Columns.Count; j++)
            {
                p7.AddCell(new Phrase(dataGridView7.Columns[j].HeaderText));
            }
            p7.HeaderRows = 1;
            for (int i = 0; i < dataGridView7.Rows.Count; i++)
            {
                for (int k = 0; k < dataGridView7.Columns.Count; k++)
                {
                    if (dataGridView7[k, i].Value != null)
                    {
                        p7.AddCell(new Phrase(dataGridView7[k, i].Value.ToString()));
                    }
                }
            }
            d.Add(p7);
            d.Close();
            wri.Close();
            SendToPrinter();
        }