コード例 #1
0
        public void PrintExportIO(invoiceoutheader ioh, List <invoiceoutdetail> IODetails, string taxStr, string podocID)
        {
            try
            {
                Dictionary <string, string> companyInfo = getCompanyInformation();
                string[] pos        = ioh.TrackingNos.Split(';');
                int      b          = 0;
                int[]    a          = (from s in pos where int.TryParse(s, out b) select b).ToArray();
                int      min        = a.Min();
                string[] dates      = ioh.TrackingDates.Split(';');
                string   poStr      = "";
                string   billingAdd = "";
                //StringBuilder sb = new StringBuilder();
                for (int i = 0; i < pos.Length - 1; i++)
                {
                    string   custPOStr = POPIHeaderDB.getCustomerPOAndDateForInvoiceOut(Convert.ToInt32(pos[i]), Convert.ToDateTime(dates[i]), podocID);
                    string[] custPO    = custPOStr.Split(Main.delimiter1);
                    if (Convert.ToInt32(pos[i]) == min)
                    {
                        billingAdd = custPO[2];
                    }
                    poStr = poStr + custPO[0] + " dated " + custPO[1] + "\n";
                }
                companybank   cb      = CompanyBankDB.getCompBankDetailForIOPrint(ioh.BankAcReference);
                CompanyDataDB datadb  = new CompanyDataDB();
                string        ieccode = "";
                cmpnydata     cdata   = datadb.getData("1").FirstOrDefault(c => c.DataID == "ImportExportCode");
                if (cdata != null)
                {
                    ieccode = cdata.DataValue;
                }

                customer custDetail        = CustomerDB.getCustomerDetailForPO(ioh.ConsigneeID);
                string[] companyBillingAdd = CompanyAddressDB.getCompTopBillingAdd(Login.companyID);
                string   ConsgAdd          = "Consignee:\n" + custDetail.name + Main.delimiter2 + "\n" + ioh.DeliveryAddress + "\n";
                string   buyer             = "Buyer:\n" + custDetail.name + Main.delimiter2 + "\n" + billingAdd + "\n";
                if (custDetail.StateName.ToString().Length != 0)
                {
                    ConsgAdd = ConsgAdd + "Sate Name:" + custDetail.StateName;
                    buyer    = buyer + "Sate Name:" + custDetail.StateName;
                    if (custDetail.StateCode.ToString().Length != 0)
                    {
                        ConsgAdd = ConsgAdd + " ,\nState Code:" + custDetail.StateCode;
                        buyer    = buyer + " ,\nState Code:" + custDetail.StateCode;
                    }
                }
                else
                {
                    if (custDetail.StateCode.ToString().Length != 0)
                    {
                        ConsgAdd = ConsgAdd + "\nState Code:" + custDetail.StateCode;
                        buyer    = buyer + "\nState Code:" + custDetail.StateCode;
                    }
                }
                //string buyer =
                if (custDetail.OfficeName.ToString().Length != 0)
                {
                    ConsgAdd = ConsgAdd + "\nGST:" + custDetail.OfficeName; // For GST Code
                    buyer    = buyer + "\nGST:" + custDetail.OfficeName;    // For GST Code
                }
                if (CustomerDB.getCustomerPANForInvoicePrint(ioh.ConsigneeID).Length != 0)
                {
                    ConsgAdd = ConsgAdd + "\nPAN:" + custDetail.OfficeName; // For PAN Code
                    buyer    = buyer + "\nPAN:" + custDetail.OfficeName;    // For PAN Code
                }

                string HeaderString = companyBillingAdd[0] + Main.delimiter2 + "\n" + companyBillingAdd[1] + "\nGST:" + companyInfo["GST"] + "\nCIN:" + companyInfo["CIN"] + "\nPAN:" + companyInfo["PAN"] +

                                      Main.delimiter1 + "Invoice No : " + ioh.InvoiceNo + ", Date : " + ioh.InvoiceDate.ToString("dd-MM-yyyy") +
                                      Main.delimiter1 + "Reference : " + poStr +
                                      Main.delimiter1 + "IEC Code : " + ieccode +
                                      Main.delimiter1 + "AD Code : " + ioh.ADCode + Main.delimiter1 +

                                      ConsgAdd +

                                      Main.delimiter1 + "Country of origin of goods : " + ioh.OriginCountryName +
                                      Main.delimiter1 + "Country of final destination : " + ioh.FinalDestinatoinCountryName +
                                      Main.delimiter1 + "Pre-Carriage by : " + ioh.PreCarriageTransportationName +
                                      Main.delimiter1 + "Place of Receipt by pre-carrier : " + ioh.PreCarrierReceiptPlace +
                                      Main.delimiter1 + "Port of Loading : " + ioh.ExitPort + Main.delimiter1 +

                                      buyer +

                                      Main.delimiter1 + "Port of Discharge : " + ioh.EntryPort +
                                      Main.delimiter1 + "Final Destination : " + ioh.FinalDestinationPlace +
                                      Main.delimiter1 + "Terms of Delivery : " + ioh.TermsOfDelivery +
                                      Main.delimiter1 + ioh.SpecialNote;


                string footer1   = "Amount In Words\n\n";
                string ColHeader = "SI No.;Description of Goods;HSN;Quantity;Unit;Unit Rate;Amount";
                string footer2   = "\n\nBank : " + cb.BankName + "\nBranch : " + cb.BranchName + "\nAC Type : " + cb.AccountType + "\nAC No : " +
                                   cb.AccountCode + "\nSWIFT Code : " + cb.CompanyID + "\nIFSC Code : " + cb.CreateUser;
                string footer3 = "For Cellcomm Solutions Limited;Authorised Signatory";
                //string termsAndCond = getTCString(poh.TermsAndCondition);
                double totQuant        = 0.00;
                double totAmnt         = 0.00;
                int    n               = 1;
                string ColDetailString = "";
                var    count           = IODetails.Count();
                ////string HSNCode = "";

                foreach (invoiceoutdetail iod in IODetails)
                {
                    ////if ((ioh.DocumentID == "SERVICEINVOICEOUT") || (ioh.DocumentID == "SERVICEEXPORTINVOICEOUT"))
                    ////{
                    ////    HSNCode = ServiceHSNMappingDB.getHSNCode(iod.StockItemID);
                    ////}
                    ////else
                    ////{
                    ////    HSNCode = ProductHSNMappingDB.getHSNCode(iod.StockItemID, iod.ModelNo);
                    ////}
                    //+ : main.delimiter1
                    if (n == count)
                    {
                        //ColDetailString = ColDetailString + n + "+" + iod.CustomerItemDescription + "+" + HSNCode + "+" + iod.Quantity + "+"
                        //                  + iod.Unit + "+" + iod.Price + "+" + (iod.Quantity * iod.Price);
                        ColDetailString = ColDetailString + n + Main.delimiter1 + iod.CustomerItemDescription + Main.delimiter1 + iod.HSNCode + Main.delimiter1 + iod.Quantity + Main.delimiter1
                                          + iod.Unit + Main.delimiter1 + iod.Price + Main.delimiter1 + (iod.Quantity * iod.Price);
                        if (iod.Tax != 0)
                        {
                            //ColDetailString = ColDetailString + Main.delimiter2 + "" + "+" + iod.TaxCode + "+" + "" + "+"
                            //              + "" + "+" + "" + "+" + "" + "+" + iod.Tax;
                            ColDetailString = ColDetailString + Main.delimiter2 + "" + Main.delimiter1 + iod.TaxCode + Main.delimiter1 + "" + Main.delimiter1
                                              + "" + Main.delimiter1 + "" + Main.delimiter1 + "" + Main.delimiter1 + iod.Tax;
                        }
                    }
                    else
                    {
                        ColDetailString = ColDetailString + n + Main.delimiter1 + iod.CustomerItemDescription + Main.delimiter1 + iod.HSNCode + Main.delimiter1 + iod.Quantity + Main.delimiter1
                                          + iod.Unit + Main.delimiter1 + iod.Price + Main.delimiter1 + (iod.Quantity * iod.Price) + Main.delimiter2;
                        if (iod.Tax != 0)
                        {
                            //ColDetailString = ColDetailString + "" + "+" + iod.TaxCode + "+" + "" + "+"
                            //              + "" + "+" + "" + "+" + "" + "+" + iod.Tax + Main.delimiter2;
                            ColDetailString = ColDetailString + "" + Main.delimiter1 + iod.TaxCode + Main.delimiter1 + "" + Main.delimiter1
                                              + "" + Main.delimiter1 + "" + Main.delimiter1 + "" + Main.delimiter1 + iod.Tax + Main.delimiter2;
                        }
                    }
                    totQuant = totQuant + iod.Quantity;
                    totAmnt  = totAmnt + (iod.Quantity * iod.Price);
                    n++;
                }

                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Title            = "Save As PDF";
                sfd.Filter           = "Pdf files (*.Pdf)|*.pdf";
                sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                sfd.FileName         = ioh.DocumentID + "-" + ioh.InvoiceNo;

                if (sfd.ShowDialog() == DialogResult.Cancel || sfd.FileName == "")
                {
                    return;
                }
                FileStream fs  = new FileStream(sfd.FileName, FileMode.Create, FileAccess.Write);
                Rectangle  rec = new Rectangle(PageSize.A4);
                iTextSharp.text.Document doc = new iTextSharp.text.Document(rec);
                PdfWriter writer             = PdfWriter.GetInstance(doc, fs);
                MyEvent   evnt = new MyEvent();
                writer.PageEvent = evnt;

                doc.Open();
                Font   font1 = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
                Font   font2 = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
                Font   font3 = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.ITALIC, BaseColor.BLACK);
                Font   font4 = FontFactory.GetFont("Arial", 5, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
                String URL   = "Cellcomm2.JPG";
                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(URL);
                img.Alignment = Element.ALIGN_LEFT;

                PdfPTable tableMain = new PdfPTable(2);

                tableMain.WidthPercentage = 100;
                PdfPCell  cellImg = new PdfPCell();
                Paragraph pp      = new Paragraph();
                pp.Add(new Chunk(img, 0, 0));
                cellImg.AddElement(pp);
                cellImg.Border = 0;
                tableMain.AddCell(cellImg);

                PdfPCell        cellAdd = new PdfPCell();
                Paragraph       ourAddr = new Paragraph();
                CompanyDetailDB compDB  = new CompanyDetailDB();
                cmpnydetails    det     = compDB.getdetails().FirstOrDefault(comp => comp.companyID == 1);
                if (det != null)
                {
                    //string addr = det.companyname + "\n" + det.companyAddress;
                    ourAddr.Add(new Chunk(det.companyname + "\n", font2));
                    ourAddr.Add(new Chunk(det.companyAddress + "\n", font4));
                    ourAddr.SetLeading(0.0f, 1.5f);
                    //ourAddr = new Paragraph(new Phrase(addr, font2));
                    ourAddr.Alignment = Element.ALIGN_RIGHT;
                }
                cellAdd.AddElement(ourAddr);
                cellAdd.Border = 0;
                tableMain.AddCell(cellAdd);

                Paragraph paragraph = new Paragraph(new Phrase("Invoice", font2));
                paragraph.Alignment = Element.ALIGN_CENTER;

                PrintPurchaseOrder prog      = new PrintPurchaseOrder();
                string[]           HeaderStr = HeaderString.Split(Main.delimiter1);

                PdfPTable table = new PdfPTable(7);

                table.SpacingBefore   = 20f;
                table.WidthPercentage = 100;
                float[] HWidths = new float[] { 0.5f, 8f, 1.5f, 2f, 1.5f, 2f, 3f };
                table.SetWidths(HWidths);
                PdfPCell cell;
                int[]    arr = { 3, 7, 9, 10 };
                float    wid = 0;
                for (int i = 0; i < HeaderStr.Length; i++)
                {
                    if (i == 0 || i == 5 || i == 11)
                    {
                        string[] format = HeaderStr[i].Split(Main.delimiter2);
                        Phrase   phr    = new Phrase();
                        phr.Add(new Chunk(format[0], font2));
                        phr.Add(new Chunk(format[1], font1));
                        cell = new PdfPCell(phr);
                        if (i == 5)
                        {
                            cell.Rowspan = 5;
                        }
                        else
                        {
                            cell.Rowspan = 4;
                        }
                        cell.Colspan             = 2;
                        cell.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
                        table.AddCell(cell);
                    }
                    //else if (arr.Contains(i))
                    //{
                    //    cell = new PdfPCell(new Phrase(HeaderStr[i].Trim(), font1));
                    //    cell.Colspan = 5;
                    //    cell.MinimumHeight = wid;
                    //    table.AddCell(cell);
                    //}
                    else
                    {
                        cell         = new PdfPCell(new Phrase(HeaderStr[i].Trim(), font1));
                        cell.Colspan = 5;
                        //if (i % 2 != 0)
                        //    cell.Colspan = 3;
                        //else
                        //    cell.Colspan = 2;
                        table.AddCell(cell);
                    }
                }
                string[] ColHeaderStr = ColHeader.Split(';');

                PdfPTable table1 = new PdfPTable(7);
                table1.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                table1.WidthPercentage = 100;
                float[] width = new float[] { 0.5f, 8f, 1.5f, 2f, 1.5f, 2f, 3f };
                table1.SetWidths(width);

                for (int i = 0; i < ColHeaderStr.Length; i++)
                {
                    if (i == 5 || i == 6)
                    {
                        PdfPCell hcell = new PdfPCell(new Phrase(ColHeaderStr[i].Trim() + "\n(" + ioh.CurrencyID + ")", font2));
                        hcell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                        table1.AddCell(hcell);
                    }
                    else
                    {
                        PdfPCell hcell = new PdfPCell(new Phrase(ColHeaderStr[i].Trim(), font2));
                        hcell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                        table1.AddCell(hcell);
                    }
                }
                //---
                PdfPCell foot = new PdfPCell(new Phrase(""));
                foot.Colspan        = 7;
                foot.BorderWidthTop = 0;
                foot.MinimumHeight  = 0.5f;
                table1.AddCell(foot);

                table1.HeaderRows = 2;
                table1.FooterRows = 1;

                table1.SkipFirstHeader = false;
                table1.SkipLastFooter  = true;
                //---
                int     track = 0;
                decimal dc1   = 0;
                decimal dc2   = 0;

                string[] DetailStr = ColDetailString.Split(Main.delimiter2);
                float    hg        = 0f;
                for (int i = 0; i < DetailStr.Length; i++)
                {
                    track = 0;
                    hg    = table1.GetRowHeight(i + 1);
                    string[] str = DetailStr[i].Split(Main.delimiter1);
                    for (int j = 0; j < str.Length; j++)
                    {
                        PdfPCell pcell;
                        if (j == 3 || j == 5 || j == 6)
                        {
                            decimal p = 1;
                            if (Decimal.TryParse(str[j], out p))
                            {
                                pcell = new PdfPCell(new Phrase(String.Format("{0:0.00}", Convert.ToDecimal(str[j])), font1));
                            }
                            else
                            {
                                pcell = new PdfPCell(new Phrase(""));
                            }
                            pcell.Border = 0;
                            if (j == 6)
                            {
                                if (str[0].Length == 0)
                                {
                                    pcell.BorderWidthBottom = 0.01f;
                                    track = 1;
                                    dc2   = Convert.ToDecimal(str[j]);
                                }
                                else
                                {
                                    dc1 = Convert.ToDecimal(str[j]);
                                }
                            }
                        }
                        else
                        {
                            if (j == 2)
                            {
                                if (str[j].Trim().Length == 0)
                                {
                                    pcell = new PdfPCell(new Phrase("", font1));
                                }
                                else
                                {
                                    pcell = new PdfPCell(new Phrase(str[j], font1));
                                }
                            }
                            else if (j == 4)
                            {
                                int m = 1;
                                if (Int32.TryParse(str[j], out m) == true)
                                {
                                    if (Convert.ToInt32(str[j]) == 0)
                                    {
                                        pcell = new PdfPCell(new Phrase("", font1));
                                    }
                                    else
                                    {
                                        pcell = new PdfPCell(new Phrase(str[j], font1));
                                    }
                                }
                                else
                                {
                                    pcell = new PdfPCell(new Phrase(str[j], font1));
                                }
                            }
                            else
                            {
                                pcell = new PdfPCell(new Phrase(str[j], font1));
                            }
                            pcell.Border = 0;
                        }
                        //pcell.Border = 0;
                        //if (i == DetailStr.Length - 1)
                        //{
                        //    pcell.MinimumHeight = 50;
                        //}
                        //else
                        pcell.MinimumHeight = 10;
                        //pcell.MinimumHeight = 20;
                        if (j == 1)
                        {
                            pcell.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                        }
                        else
                        {
                            pcell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                        }
                        pcell.BorderWidthLeft  = 0.01f;
                        pcell.BorderWidthRight = 0.01f;
                        table1.AddCell(pcell);
                    }
                    if (track == 1)
                    {
                        for (int j = 0; j < 7; j++)
                        {
                            PdfPCell pcell1;

                            if (j == 6)
                            {
                                pcell1                   = new PdfPCell(new Phrase(String.Format("{0:0.00}", Convert.ToDecimal(dc1 + dc2)), font1));
                                pcell1.Border            = 0;
                                pcell1.BorderWidthBottom = 0.01f;
                            }
                            else
                            {
                                pcell1        = new PdfPCell(new Phrase(""));
                                pcell1.Border = 0;
                            }
                            pcell1.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                            pcell1.BorderWidthLeft     = 0.01f;
                            pcell1.BorderWidthRight    = 0.01f;
                            table1.AddCell(pcell1);
                        }
                    }
                }

                double roundedAmt = Math.Round(ioh.InvoiceAmount, 0);
                double diffAmount = roundedAmt - ioh.InvoiceAmount;

                if (diffAmount != 0)
                {
                    table1.AddCell("");
                    table1.AddCell("");
                    PdfPCell cellRound = new PdfPCell(new Phrase("Round off Adj.", font1));
                    cellRound.Colspan             = 4;
                    cellRound.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                    table1.AddCell(cellRound);
                    table1.AddCell(new Phrase(String.Format("{0:0.00}", diffAmount), font1));
                    //table1.AddCell("");
                }


                table1.AddCell("");
                table1.AddCell("");
                PdfPCell cellRoundTot = new PdfPCell(new Phrase("Total", font1));
                cellRoundTot.Colspan             = 4;
                cellRoundTot.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                table1.AddCell(cellRoundTot);

                PdfPCell roundTot = new PdfPCell(new Phrase(String.Format("{0:0.00}", roundedAmt), font1));
                roundTot.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                table1.AddCell(roundTot);

                string   total  = footer1 + NumberToString.convertFC(roundedAmt.ToString(), ioh.CurrencyID).Replace("INR", ioh.CurrencyID) + "\n\n";
                PdfPCell fcell1 = new PdfPCell(new Phrase((total), font1));
                fcell1.Colspan = 6;
                //fcell1.MinimumHeight = 30;
                fcell1.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                fcell1.BorderWidthBottom   = 0;
                fcell1.BorderWidthRight    = 0;
                fcell1.BorderWidthTop      = 0;
                table1.AddCell(fcell1);

                PdfPCell fcell4 = new PdfPCell(new Phrase("E. & O.E", font1));
                //fcell4.MinimumHeight = 50;
                fcell4.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
                fcell4.BorderWidthBottom   = 0;
                //fcell4.BorderWidthRight = 0;
                fcell4.BorderWidthLeft = 0;
                fcell4.BorderWidthTop  = 0;
                table1.AddCell(fcell4);

                //if (ioh.SpecialNote.Trim().Length != 0)
                //{
                //    PdfPCell SplNote = new PdfPCell(new Phrase(("Note:\n" + ioh.SpecialNote.Trim() + "\n"), font1));
                //    SplNote.Colspan = 5;
                //    SplNote.MinimumHeight = 50;
                //    SplNote.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                //    SplNote.BorderWidthBottom = 0;
                //    SplNote.BorderWidthRight = 0;
                //    SplNote.BorderWidthTop = 0;
                //    table1.AddCell(SplNote);

                //    PdfPCell temp1 = new PdfPCell(new Phrase(""));
                //    temp1.Colspan = 2;
                //    temp1.MinimumHeight = 50;
                //    temp1.HorizontalAlignment = PdfPCell.ALIGN_LEFT;
                //    temp1.BorderWidthBottom = 0;
                //    temp1.BorderWidthLeft = 0;
                //    temp1.BorderWidthTop = 0;
                //    table1.AddCell(temp1);
                //    //table1.AddCell("");
                //}


                PdfPCell pcelNo = new PdfPCell(new Phrase("", font1));
                pcelNo.BorderWidthTop   = 0;
                pcelNo.BorderWidthRight = 0;
                table1.AddCell(pcelNo);

                Phrase phrs = new Phrase();
                phrs.Add(new Chunk("Bank Details", font2));

                phrs.Add(new Chunk(footer2, font1));
                //PdfPCell fcell2 = new PdfPCell(new Phrase(footer2, font1));

                PdfPCell fcell2 = new PdfPCell(phrs);
                fcell2.HorizontalAlignment = PdfPCell.ALIGN_MIDDLE;
                //fcell2.BorderWidthTop = 0;
                //fcell2.BorderWidthRight = 0;
                table1.AddCell(fcell2);

                PdfPCell pcelMid = new PdfPCell(new Phrase("", font1));
                pcelMid.Colspan = 3;
                //pcelMid.Border = 0;
                pcelMid.BorderWidthTop   = 0;
                pcelMid.BorderWidthLeft  = 0;
                pcelMid.BorderWidthRight = 0;
                table1.AddCell(pcelMid);

                string[] ft = footer3.Split(';');

                PdfPCell fcell3 = new PdfPCell();
                Chunk    ch1    = new Chunk(ft[0], font1);
                Chunk    ch2    = new Chunk(ft[1], font1);
                Phrase   phrase = new Phrase();
                phrase.Add(ch1);
                for (int i = 0; i < 3; i++)
                {
                    phrase.Add(Chunk.NEWLINE);
                }
                phrase.Add(ch2);

                Paragraph para = new Paragraph();
                para.Add(phrase);
                para.Alignment = Element.ALIGN_RIGHT;
                fcell3.AddElement(para);
                fcell3.Border            = 0;
                fcell3.Colspan           = 3;
                fcell3.BorderWidthTop    = 0f;
                fcell3.BorderWidthLeft   = 0f;
                fcell3.BorderWidthRight  = 0.5f;
                fcell3.BorderWidthBottom = 0.5f;
                fcell3.MinimumHeight     = 50;
                table1.AddCell(fcell3);
                table1.KeepRowsTogether(table1.Rows.Count - 4, table1.Rows.Count);
                //-------------------------
                double    dd     = 0;
                PdfPTable taxTab = new PdfPTable(3);
                taxTab.WidthPercentage = 100;

                float[] twidth = new float[] { 3f, 3f, 10f };
                taxTab.SetWidths(twidth);
                if (ioh.TaxAmount != 0)
                {
                    PdfPCell pcell;
                    pcell = new PdfPCell(new Phrase("Tax Details", font2));
                    taxTab.AddCell(pcell);
                    PdfPCell pcellc = new PdfPCell(new Phrase("Amount(" + ioh.CurrencyID + ")", font2));
                    taxTab.AddCell(pcellc);
                    PdfPCell pcelllst = new PdfPCell(new Phrase("", font1));
                    pcelllst.Border = 0;
                    taxTab.AddCell(pcelllst);

                    string[] tax = taxStr.Split(Main.delimiter2);
                    for (int i = 0; i < tax.Length - 1; i++)
                    {
                        string[] subtax = tax[i].Split(Main.delimiter1);
                        PdfPCell pcell1;
                        pcell1 = new PdfPCell(new Phrase(subtax[0], font1));
                        PdfPCell pcell2;
                        pcell2 = new PdfPCell(new Phrase(String.Format("{0:0.00}", Convert.ToDecimal(subtax[1])), font1));
                        PdfPCell pcell3 = new PdfPCell(new Phrase("", font1));
                        pcell3.Border = 0;
                        taxTab.AddCell(pcell1);
                        taxTab.AddCell(pcell2);
                        taxTab.AddCell(pcell3);
                    }
                    taxTab.AddCell(new Phrase("Total Tax Amount", font2));
                    taxTab.AddCell(new Phrase(String.Format("{0:0.00}", Convert.ToDecimal(ioh.TaxAmount)), font2));
                    PdfPCell pcellt = new PdfPCell(new Phrase("", font1));
                    pcellt.Border = 0;
                    taxTab.AddCell(pcellt);
                    taxTab.KeepTogether  = true;
                    taxTab.SpacingAfter  = 2f;
                    taxTab.SpacingBefore = 3f;
                }
                //PdfPTable TCTab = new PdfPTable(2); ;
                //if (poh.TermsAndCondition.Trim().Length != 0)
                //{
                //    Chunk TCchunk = new Chunk("Terms And Conditions:\n", font2);
                //    TCchunk.SetUnderline(0.2f, -2f);
                //    TCTab = new PdfPTable(2);
                //    TCTab.WidthPercentage = 100;
                //    PdfPCell TCCell = new PdfPCell();
                //    TCCell.Colspan = 2;
                //    TCCell.Border = 0;
                //    TCCell.AddElement(TCchunk);
                //    TCTab.AddCell(TCCell);
                //    try
                //    {
                //        string[] ParaTC = termsAndCond.Split(Main.delimiter2);
                //        for (int i = 0; i < ParaTC.Length - 1; i++)
                //        {
                //            TCCell = new PdfPCell();
                //            TCCell.Colspan = 2;
                //            TCCell.Border = 0;
                //            Paragraph header = new Paragraph();
                //            Paragraph details = new Paragraph();
                //            details.IndentationLeft = 12f;
                //            details.IndentationRight = 12f;
                //            string paraHeaderStr = (i + 1) + ". " + ParaTC[i].Substring(0, ParaTC[i].IndexOf(Main.delimiter1)) + ":";
                //            string paraFooterStr = ParaTC[i].Substring(ParaTC[i].IndexOf(Main.delimiter1) + 1);
                //            header.Add(new Phrase(paraHeaderStr, font2));
                //            details.Add(new Phrase(paraFooterStr, font1));
                //            TCCell.AddElement(header);
                //            TCCell.AddElement(details);
                //            TCTab.AddCell(TCCell);
                //        }
                //    }
                //    catch (Exception ex)
                //    {
                //        MessageBox.Show(this.ToString() + "-" + System.Reflection.MethodBase.GetCurrentMethod().Name + "() : Error-" + ex.ToString());
                //    }
                //    try
                //    {
                //        if (TCTab.Rows.Count >= 3)
                //        {
                //            TCTab.KeepRowsTogether(0, 3);
                //        }
                //    }
                //    catch (Exception ex)
                //    {
                //        MessageBox.Show(this.ToString() + "-" + System.Reflection.MethodBase.GetCurrentMethod().Name + "() : Error-" + ex.ToString());
                //    }
                //}
                //doc.Add(jpg);
                doc.Add(tableMain);
                doc.Add(paragraph);
                doc.Add(table);
                doc.Add(table1);
                if (ioh.TaxAmount != 0)
                {
                    doc.Add(taxTab);
                }
                //if(poh.TermsAndCondition.Trim().Length != 0)
                //    doc.Add(TCTab);
                doc.Close();
                MessageBox.Show("Document Saved");
                //-----watermark
                String wmurl = "";
                if (ioh.status == 98)
                {
                    //cancelled
                    wmurl = "003.png";
                }
                else
                {
                    //approved
                    wmurl = "001.png";
                }

                ////String wmurl = "napproved-1.jpg";
                iTextSharp.text.Image wmimg = iTextSharp.text.Image.GetInstance(URL);
                PrintWaterMark.PdfStampWithNewFile(wmurl, sfd.FileName);
                //-----
            }
            catch (Exception ex)
            {
                MessageBox.Show(this.ToString() + "-" + System.Reflection.MethodBase.GetCurrentMethod().Name + "() : Error-" + ex.ToString());
                MessageBox.Show("Failed TO Save");
            }
        }
コード例 #2
0
        private static PdfPTable studentList(List <Student> students, string grade)
        {
            int       numColumns = 5;
            PdfPTable returnMe   = new PdfPTable(numColumns);

            returnMe.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
            returnMe.TotalWidth          = 500f;
            returnMe.LockedWidth         = true;
            returnMe.SpacingAfter        = 10;

            // Headings
            PdfPCell cell_grade = new PdfPCell(new Phrase("Grade: " + grade, font_large_bold));

            cell_grade.Border      = 0;
            cell_grade.Padding     = 3;
            cell_grade.Colspan     = numColumns;
            cell_grade.PaddingLeft = 0;
            returnMe.AddCell(cell_grade);

            PdfPCell cell_count = new PdfPCell(new Phrase("Students: " + students.Count, font_small));

            cell_count.Border        = 0;
            cell_count.Padding       = 3;
            cell_count.PaddingBottom = 10;
            cell_count.Colspan       = numColumns;
            returnMe.AddCell(cell_count);


            PdfPCell cell_id = new PdfPCell(new Phrase("Student ID", font_body_bold));

            cell_id.Border = 0;
            returnMe.AddCell(cell_id);

            PdfPCell cell_firstname = new PdfPCell(new Phrase("First Name", font_body_bold));

            cell_firstname.Border = 0;
            returnMe.AddCell(cell_firstname);

            PdfPCell cell_lastname = new PdfPCell(new Phrase("Last Name", font_body_bold));

            cell_lastname.Border = 0;
            returnMe.AddCell(cell_lastname);


            PdfPCell cell_homeroom = new PdfPCell(new Phrase("Home Room", font_body_bold));

            cell_homeroom.Border = 0;
            returnMe.AddCell(cell_homeroom);

            PdfPCell cell_gender = new PdfPCell(new Phrase("Gender", font_body_bold));

            cell_gender.Border = 0;
            cell_gender.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
            returnMe.AddCell(cell_gender);

            BaseColor borderColor   = BaseColor.LIGHT_GRAY;
            int       bottomPadding = 5;

            // Student data
            foreach (Student student in students)
            {
                PdfPCell cell_id_value = new PdfPCell(new Phrase(student.getStudentID(), font_body));
                cell_id_value.Border        = Rectangle.TOP_BORDER;
                cell_id_value.BorderColor   = borderColor;
                cell_id_value.PaddingBottom = bottomPadding;
                returnMe.AddCell(cell_id_value);

                string firstNameString = student.getFirstName();
                if (student.getFirstName() != student.getLegalFirstName())
                {
                    firstNameString += " (" + student.getLegalFirstName() + ")";
                }

                string lastNameString = student.getLastName();
                if (student.getLastName() != student.getLegalLastName())
                {
                    lastNameString += " (" + student.getLegalLastName() + ")";
                }


                PdfPCell cell_firstname_value = new PdfPCell(new Phrase(firstNameString, font_body));
                cell_firstname_value.Border        = Rectangle.TOP_BORDER;
                cell_firstname_value.BorderColor   = borderColor;
                cell_firstname_value.PaddingBottom = bottomPadding;
                returnMe.AddCell(cell_firstname_value);

                PdfPCell cell_lastname_value = new PdfPCell(new Phrase(lastNameString, font_body));
                cell_lastname_value.Border        = Rectangle.TOP_BORDER;
                cell_lastname_value.BorderColor   = borderColor;
                cell_lastname_value.PaddingBottom = bottomPadding;
                returnMe.AddCell(cell_lastname_value);

                PdfPCell cell_homeroom_value = new PdfPCell(new Phrase(student.getHomeRoom(), font_body));
                cell_homeroom_value.Border        = Rectangle.TOP_BORDER;
                cell_homeroom_value.BorderColor   = borderColor;
                cell_homeroom_value.PaddingBottom = bottomPadding;
                returnMe.AddCell(cell_homeroom_value);

                PdfPCell cell_gender_value = new PdfPCell(new Phrase(student.getGenderInitial(), font_body));
                cell_gender_value.Border              = Rectangle.TOP_BORDER;
                cell_gender_value.BorderColor         = borderColor;
                cell_gender_value.PaddingBottom       = bottomPadding;
                cell_gender_value.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                returnMe.AddCell(cell_gender_value);
            }

            return(returnMe);
        }
コード例 #3
0
ファイル: test.aspx.cs プロジェクト: hardikabbacus/BMBTOOLS
    private void GetTestPDF()
    {
        string         filename_temp = string.Empty;
        var            filename      = "";
        productManager objPress      = new productManager();
        DataTable      dt            = new DataTable();

        try
        {
            dt = objPress.GetAllTheProducts();

            if (string.IsNullOrEmpty(filename))
            {
                filename = DateTime.Now.ToString("_mmddyyyy_HHmmss") + ".pdf";
            }
            string strPath = Server.MapPath("~") + "/Resources/PDF/";
            if (!Directory.Exists(strPath))
            {
                Directory.CreateDirectory(strPath);
            }
            filename_temp = strPath + DateTime.Now.Ticks.ToString() + ".pdf";

            //iTextSharp.text.Document document = new iTextSharp.text.Document(new RectangleReadOnly(0f, 0f), 10f, 10f, 100f, 100f);

            //Font boldFont = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
            //Font ProductHead = new Font(Font.FontFamily.HELVETICA, 14, Font.NORMAL);

            Font boldFont    = new Font(FontFactory.GetFont("FiraSans-Light", 10, Font.BOLD));
            Font ProductHead = new Font(FontFactory.GetFont("FiraSans-Light", 14, Font.NORMAL));
            Font ContentFont = new Font(FontFactory.GetFont("FiraSans-Light", 10, Font.NORMAL));
            Font FntColor    = new Font(FontFactory.GetFont("FiraSans-Light", 10, BaseColor.WHITE));

            //Font FntColor = new Font(FontFactory.GetFont("HELVETICA", 13, BaseColor.WHITE);

            Rectangle pageSize = new Rectangle(PageSize.A4);
            pageSize.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#EFF0F1"));
            Document document = new Document(pageSize, 10, 10, 100, 100);
            //document.SetPageSize(iTextSharp.text.PageSize.A4);

            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(filename_temp, FileMode.Create));
            //PdfWriter.GetInstance(document, new FileStream(filename_temp, FileMode.Create));

            writer.PageEvent = new ITextEvents();

            document.Open();

            PdfPTable maintable = new PdfPTable(1);
            maintable.DefaultCell.Border = Rectangle.NO_BORDER;
            float[] Mainwidths = new float[] { 580f };
            maintable.SetWidthPercentage(Mainwidths, pageSize);

            PdfPTable table = new PdfPTable(3);
            table.DefaultCell.Border = Rectangle.NO_BORDER;
            float[] widths = new float[] { 10f, 35f, 70f };
            table.SetWidths(widths);
            table.DefaultCell.Padding = 5f;

            #region master product images and QR code

            PdfPCell tablecell1 = new PdfPCell();

            tablecell1               = new PdfPCell(new Phrase("Master Product Name", ProductHead));
            tablecell1.Colspan       = 3;
            tablecell1.PaddingBottom = 5f;
            tablecell1.PaddingTop    = 5f;
            tablecell1.Border        = 0;
            table.AddCell(tablecell1);

            // QR Code

            BaseColor bcolorImg = new BaseColor(255, 255, 255);

            iTextSharp.text.Image t1image = null;
            using (FileStream fs = new FileStream(Server.MapPath("~") + "/resources/PDFTEST/QR.jpg", FileMode.Open))
            {
                t1image = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromStream(fs), ImageFormat.Jpeg);
            }

            t1image.ScaleToFit(50, 50);
            t1image.Alignment = Element.ALIGN_CENTER;
            tablecell1        = new PdfPCell(t1image);
            tablecell1.HorizontalAlignment = Element.ALIGN_LEFT;
            tablecell1.VerticalAlignment   = Element.ALIGN_MIDDLE;
            tablecell1.PaddingLeft         = 10;
            tablecell1.FixedHeight         = 150f;
            tablecell1.Border            = 0;
            tablecell1.BorderColorLeft   = BaseColor.LIGHT_GRAY;
            tablecell1.BorderWidthLeft   = .5f;
            tablecell1.BorderColorTop    = BaseColor.LIGHT_GRAY;
            tablecell1.BorderWidthTop    = .5f;
            tablecell1.BorderColorBottom = BaseColor.LIGHT_GRAY;
            tablecell1.BorderWidthBottom = .5f;
            tablecell1.BackgroundColor   = bcolorImg;
            table.AddCell(tablecell1);

            // Product Image

            iTextSharp.text.Image t1image1 = null;
            using (FileStream fs = new FileStream(Server.MapPath("~") + "/resources/PDFTEST/Product.jpg", FileMode.Open))
            {
                t1image1 = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromStream(fs), ImageFormat.Jpeg);
            }

            t1image1.ScaleToFit(80, 80);
            t1image1.Alignment             = Element.ALIGN_CENTER;
            tablecell1                     = new PdfPCell(t1image1);
            tablecell1.PaddingLeft         = 51;
            tablecell1.HorizontalAlignment = Element.ALIGN_LEFT;
            tablecell1.VerticalAlignment   = Element.ALIGN_MIDDLE;
            tablecell1.PaddingRight        = 31;
            tablecell1.Border              = 0;
            tablecell1.BorderColorRight    = BaseColor.LIGHT_GRAY;
            tablecell1.BorderWidthRight    = .5f;
            tablecell1.BorderColorTop      = BaseColor.LIGHT_GRAY;
            tablecell1.BorderWidthTop      = .5f;
            tablecell1.BorderColorBottom   = BaseColor.LIGHT_GRAY;
            tablecell1.BorderWidthBottom   = .5f;
            tablecell1.BackgroundColor     = bcolorImg;
            table.AddCell(tablecell1);

            #endregion

            #region  Master products sub product details
            // master product with its product details
            BaseColor hcolor = new BaseColor(233, 82, 28);
            PdfPTable table1 = new PdfPTable(4);
            table1.DefaultCell.Border = Rectangle.NO_BORDER;

            PdfPCell cell1 = new PdfPCell();

            cell1                     = new PdfPCell(new Phrase("Item No", FntColor));
            cell1.Border              = 0;
            cell1.BackgroundColor     = hcolor;
            cell1.FixedHeight         = 25f;
            cell1.HorizontalAlignment = Element.ALIGN_CENTER;
            cell1.VerticalAlignment   = Element.ALIGN_MIDDLE;
            cell1.BorderColorLeft     = BaseColor.LIGHT_GRAY;
            cell1.BorderWidthLeft     = .5f;
            table1.AddCell(cell1);

            cell1                     = new PdfPCell(new Phrase("Varient", FntColor));
            cell1.Border              = 0;
            cell1.BackgroundColor     = hcolor;
            cell1.FixedHeight         = 25f;
            cell1.HorizontalAlignment = Element.ALIGN_CENTER;
            cell1.VerticalAlignment   = Element.ALIGN_MIDDLE;
            table1.AddCell(cell1);

            cell1                     = new PdfPCell(new Phrase("Qty.", FntColor));
            cell1.Border              = 0;
            cell1.BackgroundColor     = hcolor;
            cell1.FixedHeight         = 25f;
            cell1.HorizontalAlignment = Element.ALIGN_CENTER;
            cell1.VerticalAlignment   = Element.ALIGN_MIDDLE;
            table1.AddCell(cell1);

            cell1                     = new PdfPCell(new Phrase("Price", FntColor));
            cell1.Border              = 0;
            cell1.BackgroundColor     = hcolor;
            cell1.FixedHeight         = 25f;
            cell1.HorizontalAlignment = Element.ALIGN_CENTER;
            cell1.VerticalAlignment   = Element.ALIGN_MIDDLE;
            cell1.BorderColorRight    = BaseColor.LIGHT_GRAY;
            cell1.BorderWidthRight    = .5f;
            table1.AddCell(cell1);

            int count = 0;
            foreach (DataRow dr in dt.Rows)
            {
                BaseColor bcolor  = new BaseColor(239, 240, 241);
                BaseColor bcolor2 = new BaseColor(255, 255, 255);

                if (count == 0 || count % 2 == 0)
                {
                    cell1        = new PdfPCell(new Phrase(Convert.ToString(dr["productid"]), ContentFont));
                    cell1.Border = 0;
                    cell1.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell1.VerticalAlignment   = Element.ALIGN_MIDDLE;
                    cell1.BackgroundColor     = bcolor2;
                    cell1.FixedHeight         = 25f;
                    cell1.BorderColorLeft     = BaseColor.LIGHT_GRAY;
                    cell1.BorderWidthLeft     = .5f;
                    table1.AddCell(cell1);

                    cell1        = new PdfPCell(new Phrase(Convert.ToString(dr["productid"]), ContentFont));
                    cell1.Border = 0;
                    cell1.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell1.VerticalAlignment   = Element.ALIGN_MIDDLE;
                    cell1.BackgroundColor     = bcolor2;
                    cell1.FixedHeight         = 25f;
                    table1.AddCell(cell1);

                    cell1        = new PdfPCell(new Phrase(Convert.ToString(dr["productid"]), ContentFont));
                    cell1.Border = 0;
                    cell1.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell1.VerticalAlignment   = Element.ALIGN_MIDDLE;
                    cell1.BackgroundColor     = bcolor2;
                    cell1.FixedHeight         = 25f;
                    table1.AddCell(cell1);

                    cell1        = new PdfPCell(new Phrase(Convert.ToString(dr["productid"]), ContentFont));
                    cell1.Border = 0;
                    cell1.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell1.VerticalAlignment   = Element.ALIGN_MIDDLE;
                    cell1.BackgroundColor     = bcolor2;
                    cell1.FixedHeight         = 25f;
                    cell1.BorderColorRight    = BaseColor.LIGHT_GRAY;
                    cell1.BorderWidthRight    = .5f;
                    table1.AddCell(cell1);
                }
                else
                {
                    cell1        = new PdfPCell(new Phrase(Convert.ToString(dr["productid"]), ContentFont));
                    cell1.Border = 0;
                    cell1.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell1.VerticalAlignment   = Element.ALIGN_MIDDLE;
                    cell1.FixedHeight         = 25f;
                    cell1.BackgroundColor     = bcolor;
                    cell1.BorderColorLeft     = BaseColor.LIGHT_GRAY;
                    cell1.BorderWidthLeft     = .5f;
                    table1.AddCell(cell1);

                    cell1        = new PdfPCell(new Phrase(Convert.ToString(dr["productid"]), ContentFont));
                    cell1.Border = 0;
                    cell1.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell1.VerticalAlignment   = Element.ALIGN_MIDDLE;
                    cell1.FixedHeight         = 25f;
                    cell1.BackgroundColor     = bcolor;

                    table1.AddCell(cell1);

                    cell1        = new PdfPCell(new Phrase(Convert.ToString(dr["productid"]), ContentFont));
                    cell1.Border = 0;
                    cell1.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell1.VerticalAlignment   = Element.ALIGN_MIDDLE;
                    cell1.FixedHeight         = 25f;
                    cell1.BackgroundColor     = bcolor;

                    table1.AddCell(cell1);

                    cell1        = new PdfPCell(new Phrase(Convert.ToString(dr["productid"]), ContentFont));
                    cell1.Border = 0;
                    cell1.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell1.VerticalAlignment   = Element.ALIGN_MIDDLE;
                    cell1.FixedHeight         = 25f;
                    cell1.BackgroundColor     = bcolor;
                    cell1.BorderColorRight    = BaseColor.LIGHT_GRAY;
                    cell1.BorderWidthRight    = .5f;
                    table1.AddCell(cell1);
                }
                count++;
                if (count == 5)
                {
                    cell1                     = new PdfPCell(new Phrase("More Item here", ContentFont));
                    cell1.Colspan             = 4;
                    cell1.Border              = 0;
                    cell1.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell1.VerticalAlignment   = Element.ALIGN_MIDDLE;
                    cell1.FixedHeight         = 25f;
                    cell1.BackgroundColor     = bcolor;
                    cell1.BorderColorRight    = BaseColor.LIGHT_GRAY;
                    cell1.BorderWidthRight    = .5f;
                    cell1.BorderColorLeft     = BaseColor.LIGHT_GRAY;
                    cell1.BorderWidthLeft     = .5f;
                    cell1.BorderColorBottom   = BaseColor.LIGHT_GRAY;
                    cell1.BorderWidthBottom   = .5f;
                    table1.AddCell(cell1);

                    break;
                }
            }

            table.AddCell(table1);

            tablecell1         = new PdfPCell(new Phrase(""));
            tablecell1.Colspan = 3;
            //tablecell1.FixedHeight = 4f;
            tablecell1.Border = 0;
            table.AddCell(tablecell1);

            #endregion

            #region varient product
            // Verient product

            PdfPTable Maintable2 = new PdfPTable(1);
            Maintable2.DefaultCell.Border = Rectangle.NO_BORDER;
            PdfPCell Maincell2 = new PdfPCell();

            foreach (DataRow dr in dt.Rows)
            {
                PdfPTable table2 = new PdfPTable(3);
                table2.WidthPercentage    = 100;
                table2.DefaultCell.Border = Rectangle.NO_BORDER;
                float[] Table2widths = new float[] { 20f, 35f, 70f };
                table2.SetWidths(Table2widths);

                PdfPCell cell2 = new PdfPCell();

                BaseColor Vcolor    = new BaseColor(236, 240, 245);
                BaseColor bcolorVer = new BaseColor(255, 255, 255);
                BaseColor ctcolor   = new BaseColor(239, 240, 241);

                cell2                     = new PdfPCell(new Phrase(dr["productname"].ToString(), ProductHead));
                cell2.Border              = 0;
                cell2.Colspan             = 3;
                cell2.PaddingTop          = 10f;
                cell2.PaddingBottom       = 10f;
                cell2.PaddingLeft         = 5f;
                cell2.HorizontalAlignment = Element.ALIGN_LEFT;
                cell2.VerticalAlignment   = Element.ALIGN_MIDDLE;
                cell2.VerticalAlignment   = Element.ALIGN_MIDDLE;
                cell2.BackgroundColor     = bcolorVer;
                table2.AddCell(cell2);


                iTextSharp.text.Image t1image2 = null;
                using (FileStream fs = new FileStream(Server.MapPath("~") + "/resources/PDFTEST/QR.jpg", FileMode.Open))
                {
                    t1image2 = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromStream(fs), ImageFormat.Jpeg);
                }

                t1image2.ScaleToFit(50, 50);
                t1image2.Alignment = Element.ALIGN_CENTER;

                cell2                   = new PdfPCell(t1image2);
                cell2.Border            = 0;
                cell2.PaddingLeft       = 10;
                cell2.VerticalAlignment = Element.ALIGN_MIDDLE;
                cell2.BackgroundColor   = bcolorVer;
                table2.AddCell(cell2);

                iTextSharp.text.Image t1image3 = null;
                using (FileStream fs = new FileStream(Server.MapPath("~") + "/resources/PDFTEST/Product.jpg", FileMode.Open))
                {
                    t1image3 = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromStream(fs), ImageFormat.Jpeg);
                }

                t1image3.ScaleToFit(70, 70);
                t1image3.Alignment = Element.ALIGN_CENTER;

                cell2                   = new PdfPCell(t1image3);
                cell2.Border            = 0;
                cell2.BackgroundColor   = bcolorVer;
                cell2.VerticalAlignment = Element.ALIGN_MIDDLE;
                table2.AddCell(cell2);

                // child table

                PdfPTable table2Child = new PdfPTable(3);
                table2Child.DefaultCell.Border  = Rectangle.NO_BORDER;
                table2Child.DefaultCell.Padding = 10;
                table2Child.WidthPercentage     = 100;

                PdfPCell cell2Child = new PdfPCell();
                cell2Child                   = new PdfPCell(new Phrase("Item No.", boldFont));
                cell2Child.Border            = 0;
                cell2Child.VerticalAlignment = Element.ALIGN_MIDDLE;
                cell2Child.BackgroundColor   = ctcolor;
                table2Child.AddCell(cell2Child);

                cell2Child                   = new PdfPCell(new Phrase("Min Qty", boldFont));
                cell2Child.Border            = 0;
                cell2Child.VerticalAlignment = Element.ALIGN_MIDDLE;
                cell2Child.BackgroundColor   = ctcolor;
                table2Child.AddCell(cell2Child);

                cell2Child                   = new PdfPCell(new Phrase("price", boldFont));
                cell2Child.Border            = 0;
                cell2Child.VerticalAlignment = Element.ALIGN_MIDDLE;
                cell2Child.BackgroundColor   = ctcolor;
                table2Child.AddCell(cell2Child);

                cell2Child                   = new PdfPCell(new Phrase(Convert.ToString(dr["productid"]), ContentFont));
                cell2Child.Border            = 0;
                cell2Child.VerticalAlignment = Element.ALIGN_MIDDLE;
                cell2Child.BackgroundColor   = ctcolor;
                table2Child.AddCell(cell2Child);

                cell2Child                   = new PdfPCell(new Phrase(Convert.ToString(dr["productid"]), ContentFont));
                cell2Child.Border            = 0;
                cell2Child.VerticalAlignment = Element.ALIGN_MIDDLE;
                cell2Child.BackgroundColor   = ctcolor;
                table2Child.AddCell(cell2Child);

                cell2Child                   = new PdfPCell(new Phrase(Convert.ToString(dr["productid"]), ContentFont));
                cell2Child.Border            = 0;
                cell2Child.VerticalAlignment = Element.ALIGN_MIDDLE;
                cell2Child.BackgroundColor   = ctcolor;
                table2Child.AddCell(cell2Child);

                table2.AddCell(table2Child);

                cell2                     = new PdfPCell(new Phrase(""));
                cell2.Border              = 0;
                cell2.Colspan             = 3;
                cell2.PaddingTop          = 10f;
                cell2.PaddingBottom       = 10f;
                cell2.PaddingLeft         = 5f;
                cell2.FixedHeight         = 25f;
                cell2.HorizontalAlignment = Element.ALIGN_LEFT;
                cell2.VerticalAlignment   = Element.ALIGN_MIDDLE;
                cell2.VerticalAlignment   = Element.ALIGN_MIDDLE;
                cell2.BackgroundColor     = bcolorVer;
                table2.AddCell(cell2);

                PdfPCell cell = new PdfPCell();
                cell.AddElement(table2);
                cell.BorderWidthBottom = .5f;
                cell.BorderColorBottom = BaseColor.LIGHT_GRAY;
                cell.BorderWidthLeft   = .5f;
                cell.BorderColorLeft   = BaseColor.LIGHT_GRAY;
                cell.BorderWidthTop    = .5f;
                cell.BorderColorTop    = BaseColor.LIGHT_GRAY;
                cell.BorderWidthRight  = .5f;
                cell.BorderColorRight  = BaseColor.LIGHT_GRAY;
                PdfPTable t1 = new PdfPTable(1);
                t1.AddCell(cell);
                Maintable2.AddCell(t1);

                //space
                Maincell2             = new PdfPCell(new Phrase(""));
                Maincell2.Colspan     = 1;
                Maincell2.Border      = 0;
                Maincell2.PaddingTop  = 5f;
                Maincell2.FixedHeight = 10f;
                Maintable2.AddCell(Maincell2);
            }

            #endregion

            #region Single product and next is also single product

            // single product

            PdfPTable Outertable3     = new PdfPTable(2);
            float[]   Table3Outwidths = new float[] { 50f, 50f };
            Outertable3.SetWidths(Table3Outwidths);
            Outertable3.DefaultCell.Border  = Rectangle.NO_BORDER;
            Outertable3.DefaultCell.Padding = 5f;
            PdfPCell Outercell3 = new PdfPCell();

            int cnt = 0;
            foreach (DataRow dr in dt.Rows)
            {
                BaseColor bcolorSing = new BaseColor(255, 255, 255);
                PdfPTable table3     = new PdfPTable(3);
                table3.WidthPercentage             = 100;
                table3.DefaultCell.BackgroundColor = bcolorSing;

                float[] Table3widths = new float[] { 15f, 25f, 25f };
                table3.SetWidths(Table3widths);
                table3.DefaultCell.Border = Rectangle.NO_BORDER;
                PdfPCell cell3 = new PdfPCell();

                cell3                     = new PdfPCell(new Phrase(Convert.ToString(dr["productname"]), ProductHead));
                cell3.Colspan             = 3;
                cell3.Border              = 0;
                cell3.PaddingRight        = 5f;
                cell3.FixedHeight         = 25f;
                cell3.HorizontalAlignment = Element.ALIGN_LEFT;
                cell3.BackgroundColor     = bcolorSing;
                table3.AddCell(cell3);

                iTextSharp.text.Image t1image3 = null;
                using (FileStream fs = new FileStream(Server.MapPath("~") + "/resources/PDFTEST/QR.jpg", FileMode.Open))
                {
                    t1image3 = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromStream(fs), ImageFormat.Jpeg);
                }
                t1image3.ScaleToFit(50, 50);
                t1image3.Alignment = Element.ALIGN_CENTER;
                cell3                     = new PdfPCell(t1image3);
                cell3.PaddingLeft         = 5;
                cell3.HorizontalAlignment = Element.ALIGN_LEFT;
                cell3.VerticalAlignment   = Element.ALIGN_MIDDLE;
                cell3.BackgroundColor     = bcolorSing;
                cell3.PaddingRight        = 5;
                cell3.Border              = 0;

                table3.AddCell(cell3);

                iTextSharp.text.Image t1image4 = null;
                using (FileStream fs = new FileStream(Server.MapPath("~") + "/resources/PDFTEST/Product.jpg", FileMode.Open))
                {
                    t1image4 = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromStream(fs), ImageFormat.Jpeg);
                }
                t1image4.ScaleToFit(70, 70);
                t1image4.Alignment = Element.ALIGN_CENTER;
                cell3                     = new PdfPCell(t1image4);
                cell3.PaddingLeft         = 5;
                cell3.HorizontalAlignment = Element.ALIGN_LEFT;
                cell3.VerticalAlignment   = Element.ALIGN_MIDDLE;
                cell3.BackgroundColor     = bcolorSing;
                //cell3.PaddingRight = 5;
                cell3.Border = 0;
                table3.AddCell(cell3);

                PdfPTable table3Child = new PdfPTable(1);
                table3Child.DefaultCell.Border = Rectangle.NO_BORDER;

                PdfPCell cell1Child = new PdfPCell();
                cell1Child                 = new PdfPCell(new Phrase("Price", boldFont));
                cell1Child.Border          = 0;
                cell1Child.FixedHeight     = 25f;
                cell1Child.BackgroundColor = bcolorSing;
                table3Child.AddCell(cell1Child);

                cell1Child                 = new PdfPCell(new Phrase(Convert.ToString(dr["productid"]), ContentFont));
                cell1Child.Border          = 0;
                cell1Child.FixedHeight     = 25f;
                cell1Child.BackgroundColor = bcolorSing;
                table3Child.AddCell(cell1Child);

                cell1Child                 = new PdfPCell(new Phrase("Min Qty", boldFont));
                cell1Child.Border          = 0;
                cell1Child.FixedHeight     = 25f;
                cell1Child.BackgroundColor = bcolorSing;
                table3Child.AddCell(cell1Child);

                cell1Child                 = new PdfPCell(new Phrase(Convert.ToString(dr["productid"]), ContentFont));
                cell1Child.Border          = 0;
                cell1Child.FixedHeight     = 25f;
                cell1Child.BackgroundColor = bcolorSing;
                table3Child.AddCell(cell1Child);

                cell1Child                 = new PdfPCell(new Phrase("Item No.", boldFont));
                cell1Child.Border          = 0;
                cell1Child.FixedHeight     = 25f;
                cell1Child.BackgroundColor = bcolorSing;
                table3Child.AddCell(cell1Child);

                cell1Child                 = new PdfPCell(new Phrase(Convert.ToString(dr["productid"]), ContentFont));
                cell1Child.Border          = 0;
                cell1Child.FixedHeight     = 25f;
                cell1Child.BackgroundColor = bcolorSing;
                table3Child.AddCell(cell1Child);

                table3.AddCell(table3Child);
                cell3.AddElement(table3);
                table3.AddCell(cell3);

                PdfPCell cell = new PdfPCell();
                cell.AddElement(table3);
                cell.BorderWidthBottom = .5f;
                cell.BorderColorBottom = BaseColor.LIGHT_GRAY;
                cell.BorderWidthLeft   = .5f;
                cell.BorderColorLeft   = BaseColor.LIGHT_GRAY;
                cell.BorderWidthTop    = .5f;
                cell.BorderColorTop    = BaseColor.LIGHT_GRAY;
                cell.BorderWidthRight  = .5f;
                cell.BorderColorRight  = BaseColor.LIGHT_GRAY;
                PdfPTable t1 = new PdfPTable(1);
                t1.AddCell(cell);
                Outertable3.AddCell(t1);

                cnt++;

                if (cnt == 2)
                {
                    // space
                    Outercell3             = new PdfPCell(new Phrase(""));
                    Outercell3.Colspan     = 2;
                    Outercell3.Border      = 0;
                    Outercell3.PaddingTop  = 15f;
                    Outercell3.FixedHeight = 15;
                    Outertable3.AddCell(Outercell3);

                    cnt = 0;
                }
            }

            #endregion



            maintable.AddCell(table);
            maintable.AddCell(table);
            maintable.AddCell(table);
            maintable.AddCell(Maintable2);
            maintable.AddCell(Outertable3);

            // writer.PageEvent = new Footer(); // footer

            document.Add(maintable);

            document.Close();

            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();

            System.IO.FileInfo fileInfo = new System.IO.FileInfo(filename_temp);
            byte[]             bytes    = System.IO.File.ReadAllBytes(filename_temp);
            if (fileInfo.Exists)
            {
                this.Response.Clear();
                //this.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + hdpdfname.Value + "\"");
                this.Response.AddHeader("Content-Disposition", "attachment; filename=test.pdf");
                this.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                this.Response.ContentType = "application/pdf";
                this.Response.BinaryWrite(bytes);
                this.Response.Flush();
            }
        }
        catch (Exception ex) { throw ex; }
        finally { objPress = null; dt = null; }
    }
コード例 #4
0
ファイル: Articles.cs プロジェクト: AerreRomania/Exacta
        private void PrintArticlePDF()
        {
            //custom font
            string slnPath = Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory()));

            slnPath = slnPath + "\\Fonts\\arial.ttf";
            BaseFont arial = BaseFont.CreateFont(slnPath, BaseFont.CP1250, BaseFont.EMBEDDED);

            BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, BaseFont.EMBEDDED);

            iTextSharp.text.Font text = new iTextSharp.text.Font(arial, 10, iTextSharp.text.Font.NORMAL);

            //article table
            PdfPTable articlePdfTable = new PdfPTable(6);

            articlePdfTable.DefaultCell.Padding     = 3;
            articlePdfTable.WidthPercentage         = 100;
            articlePdfTable.HorizontalAlignment     = Element.ALIGN_LEFT;
            articlePdfTable.DefaultCell.BorderWidth = 1;
            articlePdfTable.SpacingAfter            = 30;

            foreach (DataGridViewColumn column in dgvArticles.Columns)
            {
                PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText, text));
                cell.BackgroundColor = new iTextSharp.text.BaseColor(Color.Coral);
                articlePdfTable.AddCell(cell);
            }

            Articole art = Exacta.Menu.db.GetTable <Articole>().SingleOrDefault(a => a.Id.ToString() == _selectedArticle);

            articlePdfTable.DefaultCell.BackgroundColor = new iTextSharp.text.BaseColor(Color.White);
            articlePdfTable.AddCell(new Phrase(art.Id.ToString(), text));
            articlePdfTable.AddCell(new Phrase(art.Articol, text));
            articlePdfTable.AddCell(new Phrase(art.Descriere, text));
            articlePdfTable.AddCell(new Phrase(art.Collection, text));
            articlePdfTable.AddCell(new Phrase(art.Client, text));

            //phase table
            PdfPTable phasePdfTable = new PdfPTable(3);

            phasePdfTable.DefaultCell.Padding     = 3;
            phasePdfTable.WidthPercentage         = 100;
            phasePdfTable.HorizontalAlignment     = Element.ALIGN_LEFT;
            phasePdfTable.DefaultCell.BorderWidth = 1;

            foreach (DataGridViewColumn column in dgv_FaseArticles.Columns)
            {
                PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText, text));
                cell.BackgroundColor = new iTextSharp.text.BaseColor(Color.Coral);
                phasePdfTable.AddCell(cell);
            }

            foreach (DataGridViewRow row in dgv_FaseArticles.Rows)
            {
                foreach (DataGridViewCell cell in row.Cells)
                {
                    phasePdfTable.AddCell(new Phrase(cell.Value.ToString(), text));
                }
            }

            //Main title
            iTextSharp.text.Font titleFont = new iTextSharp.text.Font(arial, 36, iTextSharp.text.Font.NORMAL);
            Paragraph            title     = new Paragraph("Article Report", titleFont);

            title.Alignment    = Element.ALIGN_CENTER;
            title.SpacingAfter = 20;

            //date
            DateTime dateTime = DateTime.Now;

            iTextSharp.text.Font dateTimeFont = new iTextSharp.text.Font(arial, 16, iTextSharp.text.Font.NORMAL);
            Paragraph            date         = new Paragraph("Date: " + dateTime.ToString("dd-MM-yyyy"), dateTimeFont);

            date.Alignment    = Element.ALIGN_RIGHT;
            date.SpacingAfter = 5;
            //dateFont.SetColor(169, 169, 169);

            //time
            Paragraph time = new Paragraph("Time: " + dateTime.ToString("HH:mm:ss"), dateTimeFont);

            time.Alignment    = Element.ALIGN_RIGHT;
            time.SpacingAfter = 30;

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

            sepLine.SpacingAfter = -10;
            Paragraph sepLine2 = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, iTextSharp.text.BaseColor.BLACK, Element.ALIGN_LEFT, 1)));

            sepLine2.SpacingAfter = 40;

            //signature
            iTextSharp.text.Font footFont  = new iTextSharp.text.Font(arial, 16, iTextSharp.text.Font.NORMAL);
            Paragraph            signature = new Paragraph("E X A C T A", footFont);

            signature.Alignment    = Element.ALIGN_LEFT;
            signature.SpacingAfter = 30;

            //title2
            iTextSharp.text.Font titFont = new iTextSharp.text.Font(arial, 26, iTextSharp.text.Font.NORMAL);
            Paragraph            tit     = new Paragraph("Phases For Current Article", titFont);

            tit.Alignment    = Element.ALIGN_CENTER;
            tit.SpacingAfter = 40;

            var sfd = new SaveFileDialog();

            sfd.FileName   = "Article" + art.Id.ToString();
            sfd.DefaultExt = ".pdf";
            sfd.Filter     = "PDF(*.pdf)|*.pdf";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                using (FileStream fs = new FileStream(sfd.FileName, FileMode.Create))
                {
                    Document doc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
                    PdfWriter.GetInstance(doc, fs);

                    doc.Open();
                    doc.Add(signature);
                    doc.Add(title);
                    doc.Add(date);
                    doc.Add(time);
                    doc.Add(sepLine);
                    doc.Add(sepLine2);
                    doc.Add(articlePdfTable);
                    doc.Add(tit);
                    doc.Add(phasePdfTable);
                    doc.Close();
                    fs.Close();
                }
                sfd.Dispose();
            }
        }
コード例 #5
0
        public virtual void Rowspan_Test()
        {
            String file = "rowspantest.pdf";

            string fileE = CMP_FOLDER + file;

            Console.Write(File.Exists(fileE));
            Document  document = new Document();
            PdfWriter writer   = PdfWriter.GetInstance(document, new FileStream(OUTPUT_FOLDER + file, FileMode.Create));

            document.Open();
            PdfContentByte contentByte = writer.DirectContent;

            Rectangle rect = document.PageSize;

            PdfPTable table = new PdfPTable(4);

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

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

            table.SetWidths(widths);

            PdfPCell cell_1_1 = new PdfPCell(new Phrase("1-1"));

            cell_1_1.Colspan = 4;
            table.AddCell(cell_1_1);

            PdfPCell cell_2_1 = new PdfPCell(new Phrase("2-1"));

            cell_2_1.Rowspan = 2;
            table.AddCell(cell_2_1);

            PdfPCell cell_2_2 = new PdfPCell(new Phrase("2-2"));

            cell_2_2.Colspan = 2;
            table.AddCell(cell_2_2);

            PdfPCell cell_2_4 = new PdfPCell(new Phrase("2-4"));

            cell_2_4.Rowspan = 3;
            table.AddCell(cell_2_4);

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

            table.AddCell(cell_3_2);

            PdfPCell cell_3_3 = new PdfPCell(new Phrase("3-3"));

            table.AddCell(cell_3_3);

            PdfPCell cell_4_1 = new PdfPCell(new Phrase("4-1"));

            cell_4_1.Colspan = 3;
            table.AddCell(cell_4_1);

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

            document.Close();

            // compare
            CompareTool compareTool  = new CompareTool();
            String      errorMessage = compareTool.CompareByContent(OUTPUT_FOLDER + file, CMP_FOLDER + file, OUTPUT_FOLDER, "diff");

            if (errorMessage != null)
            {
                Assert.Fail(errorMessage);
            }
        }
コード例 #6
0
        public ActionResult DisbursementSummaryReport(String StartDate, String EndDate, String CompanyId, String BranchId)
        {
            // ==============================
            // 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 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.MstCompanies where d.Id == Convert.ToInt32(CompanyId) select d.Company).FirstOrDefault();
            var address     = (from d in db.MstCompanies where d.Id == Convert.ToInt32(CompanyId) select d.Address).FirstOrDefault();
            var contactNo   = (from d in db.MstCompanies where d.Id == Convert.ToInt32(CompanyId) select d.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("Disbursement Summary Report", 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);

            // ===================
            // Data (Disbursement)
            // ===================
            var disbursements = from d in db.TrnDisbursements
                                where d.CVDate >= Convert.ToDateTime(StartDate) &&
                                d.CVDate <= Convert.ToDateTime(EndDate) &&
                                d.MstBranch.CompanyId == Convert.ToInt32(CompanyId) &&
                                d.BranchId == Convert.ToInt32(BranchId) &&
                                d.IsLocked == true
                                select new
            {
                Id          = d.Id,
                Branch      = d.MstBranch.Branch,
                CVNumber    = d.CVNumber,
                CVDate      = d.CVDate.ToString("MM-dd-yyyy", CultureInfo.InvariantCulture),
                Supplier    = d.MstArticle.Article,
                Particulars = d.Particulars,
                BankId      = d.BankId,
                Bank        = d.MstArticle1.Article,
                CheckNumber = d.CheckNumber,
                Amount      = d.Amount
            };

            if (disbursements.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))
                {
                    HorizontalAlignment = 0, PaddingTop = 10f, PaddingBottom = 14f, Border = 0
                });
                branchTitle.AddCell(branchHeaderColspan);
                document.Add(branchTitle);

                // ====
                // Data
                // ====
                PdfPTable data            = new PdfPTable(7);
                float[]   widthsCellsData = new float[] { 15f, 11f, 25f, 25f, 20f, 20f, 20f };
                data.SetWidths(widthsCellsData);
                data.WidthPercentage = 100;
                data.AddCell(new PdfPCell(new Phrase("CV Number", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                });
                data.AddCell(new PdfPCell(new Phrase("CV Date", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                });
                data.AddCell(new PdfPCell(new Phrase("Supplier", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                });
                data.AddCell(new PdfPCell(new Phrase("Particulars", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                });
                data.AddCell(new PdfPCell(new Phrase("Bank", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                });
                data.AddCell(new PdfPCell(new Phrase("CheckNumber", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                });
                data.AddCell(new PdfPCell(new Phrase("Amount", fontArial11Bold))
                {
                    HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 5f, BackgroundColor = BaseColor.LIGHT_GRAY
                });

                Decimal total = 0;
                foreach (var disbursement in disbursements)
                {
                    data.AddCell(new PdfPCell(new Phrase(disbursement.CVNumber, fontArial10))
                    {
                        HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase(disbursement.CVDate, fontArial10))
                    {
                        HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase(disbursement.Supplier, fontArial10))
                    {
                        HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase(disbursement.Particulars, fontArial10))
                    {
                        HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase(disbursement.Bank, fontArial10))
                    {
                        HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase(disbursement.CheckNumber, fontArial10))
                    {
                        HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    data.AddCell(new PdfPCell(new Phrase(disbursement.Amount.ToString("#,##0.00"), fontArial10))
                    {
                        HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 5f, PaddingLeft = 5f
                    });
                    total += disbursement.Amount;
                }

                // =====
                // Total
                // =====
                data.AddCell(new PdfPCell(new Phrase("Total", fontArial10Bold))
                {
                    Colspan = 6, HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 10f, PaddingLeft = 10f
                });
                data.AddCell(new PdfPCell(new Phrase(total.ToString("#,##0.00"), fontArial10Bold))
                {
                    HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 5f, PaddingRight = 5f, PaddingLeft = 5f
                });
                document.Add(data);
            }

            // Document End
            document.Close();

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

            return(new FileStreamResult(workStream, "application/pdf"));
        }
コード例 #7
0
        public static string CreatePDF2(DatosComprobante dt, Comprobante comprobante, string rutaPDF, string nombrePDF)
        {
            //*** Copia el recurso embebido en un directorio temporal , cuando se le envíe la plantilla del pdf en la dll
            // ContentLoading.GetPDFEmbedded();
            //*** Esto hay que activar cuando el pdf esté compilado en la librería

            try
            {
                var boldTableFont = FontFactory.GetFont("Arial", 9, iTextSharp.text.Font.BOLD);
                var bodyFont      = FontFactory.GetFont("Arial", 10, iTextSharp.text.Font.NORMAL);
                //*** Configuración de directorios para los diferentes formatos
                string carpetaPrincipal         = Properties.Settings.Default.PathDefecto;
                string carpetaFormatosFacturas  = Properties.Settings.Default.DeFacturas;
                string formatoPDFCabecera       = Properties.Settings.Default.EsteFormatoFacturaCabecera;
                string formatoPDFDetalles       = Properties.Settings.Default.EsteFormatoFacturaDetalles;
                string formatoPDFTotales        = Properties.Settings.Default.EsteFormatoFacturaTotales;
                string carpetaGeneradasFacturas = Properties.Settings.Default.FacturasGeneradas;

                string rutaCompleta   = carpetaPrincipal + carpetaFormatosFacturas + @"\" + formatoPDFCabecera;
                string rutaCompleta_1 = carpetaPrincipal + carpetaFormatosFacturas + @"\" + formatoPDFDetalles;
                string rutaCompleta_2 = carpetaPrincipal + carpetaFormatosFacturas + @"\" + formatoPDFTotales;

                string nombreFacturaGenerada = Properties.Settings.Default.ArchivoTemporal;
                string nuevaFacturaCompleta  = carpetaPrincipal + carpetaGeneradasFacturas + @"\" + nombreFacturaGenerada;
                // estos dos archivos, se eliminan al terminar el proceso
                string detalletemporal = carpetaPrincipal + carpetaGeneradasFacturas + @"\detalle_temporal.pdf";
                string totalestemporal = carpetaPrincipal + carpetaGeneradasFacturas + @"\totales_temporal.pdf";

                //*** Esto se activa cuando el pdf está dentro de la librería
                //string fileNameExisting = ContentLoading.CrearCarpetaTemporal("modelo_facturaFinal.pdf");
                //*** Va junto con la opción de arriba

                string fileNameExisting   = rutaCompleta;
                string fileNameExisting_1 = rutaCompleta_1;
                string fileNameExisting_2 = rutaCompleta_2;

                //*** Archivo resultante temporal
                string fileNameNew = nuevaFacturaCompleta;
                //*** estos dos archivos, se eliminan al terminar el proceso
                string fileNameNew_1 = detalletemporal;
                string fileNameNew_2 = totalestemporal;

                //*** Proceso de estampado de la cabecera del documento
                using (var existingFileStream = new FileStream(fileNameExisting, FileMode.Open))
                    using (var newFileStream = new FileStream(fileNameNew, FileMode.Create))
                    {
                        // Open existing PDF
                        PdfReader pdfReader = new PdfReader(existingFileStream);
                        Rectangle pagesize  = pdfReader.GetPageSize(1);
                        // PdfStamper, which will create
                        PdfStamper stamper = new PdfStamper(pdfReader, newFileStream);
                        var        form    = stamper.AcroFields;
                        //var fieldKeys = form.Fields.Keys;
                        var imagepath = comprobante.archivo;

                        using (FileStream fs = new FileStream(imagepath, FileMode.Open))
                        {
                            var png = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromStream(fs), System.Drawing.Imaging.ImageFormat.Png);
                            png.Alignment = iTextSharp.text.Image.ALIGN_RIGHT;
                            png.SetAbsolutePosition(41, 1010);
                            png.ScaleAbsoluteHeight(100);
                            png.ScaleAbsoluteWidth(365);
                            PdfContentByte over = null;
                            over = stamper.GetOverContent(1); // 1 = página
                            over.AddImage(png);
                        }

                        //*** mapeo de datos de la factura ESTAMPADO DE LOS DATOS EN LA PLANTILLA
                        //*** TECNOLOGÍA ACROFIELDS
                        form.SetField("RUC", dt.Ruc);
                        form.SetField("NROFACTURA", comprobante.codDoc);
                        form.SetField("NROAUTORIZACION", dt.numeroAutorizacion);
                        form.SetField("AMBIENTE", dt.ambiente);
                        form.SetField("EMISION", dt.estado);
                        form.SetField("CLAVEACCESONUMEROS", dt.numeroAutorizacion);

                        //***mapeo de datos de la empresa
                        form.SetField("NOMBREEMPRESA", "ComputerEC");
                        form.SetField("DIRECCION1EMPRESA", "Calle Homero Salas OE5-148 y Altar");
                        form.SetField("DIRECCION2EMPRESA", "Sector del Antiguo Aeropuerto");
                        form.SetField("DESCRIPCION1EMPRESA", "Teléfonos: 0983833901  0991324900");
                        form.SetField("DESCRIPCION2EMPRESA", "Horarios: Lun-Vie 08:00 a 18:00");

                        //***mapeo de los datos del cliente
                        //***ESTOS DATOS
                        //form.SetField("RazonSocial", comprobante.Comprobante.razonSocial);
                        //form.SetField("FechaEmision", comprobante.Comprobante.fechaEmision);
                        //form.SetField("Identificacion", comprobante.Comprobante.ruc);
                        #region Detalles


                        PdfPTable itemTable = new PdfPTable(9);
                        itemTable.HorizontalAlignment = 0;
                        itemTable.WidthPercentage     = 146;
                        itemTable.SpacingBefore       = 10f;
                        itemTable.SpacingAfter        = 10f;
                        itemTable.SetWidths(new float[] { 3f, /*3f,*/ 2f, 6f, 4f, 4f, 4f, 3f, 3f, 3f }); // then set the column's __relative__ widths
                        itemTable.DefaultCell.Border = Rectangle.BOX;


                        // VALIDACION DE LOS CAMPOS QUE SE GENERAN EN EL PDF

                        PdfPCell cell1 = new PdfPCell(new Phrase(new Chunk("Cod.Principal", boldTableFont)));
                        cell1.HorizontalAlignment = 1;
                        itemTable.AddCell(cell1);

                        //PdfPCell cell2 = new PdfPCell(new Phrase(new Chunk("Cod.Auxiliar", boldTableFont)));
                        //cell2.HorizontalAlignment = 1;
                        //itemTable.AddCell(cell2);

                        PdfPCell cell3 = new PdfPCell(new Phrase(new Chunk("Cantidad", boldTableFont)));
                        cell3.HorizontalAlignment = 1;
                        itemTable.AddCell(cell3);

                        PdfPCell cell4 = new PdfPCell(new Phrase(new Chunk("Descripcion", boldTableFont)));
                        cell4.HorizontalAlignment = 1;
                        itemTable.AddCell(cell4);

                        PdfPCell cell5 = new PdfPCell(new Phrase(new Chunk("Det.Adicional1", boldTableFont)));
                        cell5.HorizontalAlignment = 1;
                        itemTable.AddCell(cell5);

                        PdfPCell cell6 = new PdfPCell(new Phrase(new Chunk("Det.Adicional2", boldTableFont)));
                        cell6.HorizontalAlignment = 1;
                        itemTable.AddCell(cell6);


                        PdfPCell cell7 = new PdfPCell(new Phrase(new Chunk("Det.Adicional3", boldTableFont)));
                        cell7.HorizontalAlignment = 1;
                        itemTable.AddCell(cell7);

                        PdfPCell cell8 = new PdfPCell(new Phrase(new Chunk("ValorUnit", boldTableFont)));
                        cell8.HorizontalAlignment = 1;
                        itemTable.AddCell(cell8);

                        PdfPCell cell9 = new PdfPCell(new Phrase(new Chunk("Descuento", boldTableFont)));
                        cell9.HorizontalAlignment = 1;
                        itemTable.AddCell(cell9);

                        PdfPCell cell10 = new PdfPCell(new Phrase(new Chunk("PrecioTotal", boldTableFont)));
                        cell10.HorizontalAlignment = 1;
                        itemTable.AddCell(cell10);

                        itemTable.HeaderRows = 1;

                        foreach (DetalleComprobante fila in comprobante.detalles)
                        {
                            itemTable.AddCell(fila.codigoPrincipal.ToString());
                            //itemTable.AddCell(fila.codigoAuxiliar.ToString());
                            itemTable.AddCell(fila.cantidad.ToString());
                            itemTable.AddCell(fila.descripcion.ToString());
                            itemTable.AddCell(fila.detalleadicional1.ToString());
                            itemTable.AddCell(fila.detalleadicional2.ToString());
                            itemTable.AddCell(fila.detalleadicional3.ToString());
                            itemTable.AddCell(fila.precioUnitario.ToString());
                            itemTable.AddCell(fila.descuento.ToString());
                            itemTable.AddCell(fila.totalSinImpueto.ToString());
                        }

                        ColumnText column    = new ColumnText(stamper.GetOverContent(1));
                        Rectangle  rectPage1 = new Rectangle(43, 36, 559, 856); // POSICIÓN DONDE INICIA LA TABLA
                        column.SetSimpleColumn(rectPage1);
                        column.AddElement(itemTable);
                        int       pagecount = 1;
                        Rectangle rectPage2 = new Rectangle(43, 36, 559, 1000); // 1000 = POSICIÓN DEL TITULO DE LA TABLA EN CADA PÁGINA
                        int       status    = column.Go();
                        while (ColumnText.HasMoreText(status))
                        {
                            status = triggerNewPage(stamper, pagesize, column, rectPage2, ++pagecount);
                        }
                        #endregion

                        itemTable.SpacingBefore = 20;
                        altotal = itemTable.TotalHeight;

                        stamper.FormFlattening = true;
                        //stamper.FreeTextFlattening = true;
                        stamper.Close();
                        pdfReader.Close();
                    }

                //*** Proceso de estampado de los totales del documento en otro PDF
                using (var existingFileStream = new FileStream(fileNameExisting_2, FileMode.Open))
                    using (var newFileStream = new FileStream(fileNameNew_2, FileMode.Create))
                    {
                        // Open existing PDF
                        PdfReader pdfReader = new PdfReader(existingFileStream);

                        // PdfStamper, which will create
                        PdfStamper stamper = new PdfStamper(pdfReader, newFileStream);

                        var form      = stamper.AcroFields;
                        var fieldKeys = form.Fields.Keys;


                        //*** mapeo de datos de la factura
                        form.SetField("SUBTOTAL12", comprobante.totalConImpuestos.ToString());
                        form.SetField("SUBTOTALCERO", "");
                        form.SetField("SUBTOTALNOIVA", "");
                        form.SetField("SUBTOTALEXCENTO", "");
                        form.SetField("SUBTOTALSINIMPUESTOS", comprobante.totalSinImpuetos.ToString());
                        form.SetField("TOTALDESCUENTO", comprobante.totalDescuento.ToString());
                        form.SetField("ICE", "");
                        form.SetField("VALORIVA", "");
                        form.SetField("IRBPNR", "");
                        form.SetField("PROPINA", comprobante.propina.ToString());
                        form.SetField("VALORTOTAL", comprobante.importeTotal.ToString());

                        stamper.FormFlattening = true;
                        //stamper.FreeTextFlattening = true;
                        stamper.Close();
                        pdfReader.Close();
                    }

                // SE ACTIVA CUANDO SE REQUIERA HACER EL PROCESO EN MEMORIA
                //List<byte[]> fbytes = new List<byte[]>();
                //MemoryStream ms = GenerarRIDE.CreatePDF1Stream(fileNameNew);
                //ms.Position = 0;
                //fbytes.Add(ms.ToArray());
                //ms = GenerarRIDE.CreatePDF1Stream(fileNameNew_1);
                //ms.Position = 0;
                //fbytes.Add(ms.ToArray());
                //ms = GenerarRIDE.CreatePDF1Stream(fileNameNew_2);
                //ms.Position = 0;
                //fbytes.Add(ms.ToArray());

                //MemoryStream PDFData = new MemoryStream();
                ////*** Se guarda el archivo generado
                ////string fileNameNew = nuevaFacturaCompleta;
                //PDFData = new MemoryStream(concatAndAddContent(fbytes)); // une los 3 archivos
                //PDFData.Position = 0;
                ////MemoryStream ms1 = GenerarRIDE.CreatePDF1Stream(final3);
                ////ms1.Position = 0;
                //SavePDFFile(final3, PDFData);

                // Merge de archivos
                #region MergePDF
                //altotal 856
                float y = -altotal - 250;



                // obteniendo las rutas
                string src   = rutaPDF + "archivotemporal.pdf";
                string src1  = rutaPDF + "totales_temporal.pdf";
                string final = rutaPDF + nombrePDF;


                PdfReader  reader   = new PdfReader(src);
                PdfStamper stamper1 =
                    new PdfStamper(reader, new FileStream(final, FileMode.Create));

                PdfContentByte canvas = stamper1.GetUnderContent(1);

                PdfReader       r;
                PdfImportedPage page;

                PdfReader s_reader = new PdfReader(src1);
                Rectangle pageSize = reader.GetPageSize(1);

                int n = reader.NumberOfPages;

                for (int i = 1; i <= n; i++)
                {
                    r    = new PdfReader(src1);
                    page = stamper1.GetImportedPage(r, 1);
                    canvas.AddTemplate(page, 0, y); //float x   float y
                    stamper1.Writer.FreeReader(r);
                    r.Close();
                }

                stamper1.Close();
                s_reader.Close();
                reader.Close();
                return("True");

                #endregion
            }
            catch (Exception e0)
            {
                return("No se generó el PDF : " + e0.Message);
            }
        }
コード例 #8
0
        public ActionResult JournalVoucher(Int32 JVId)
        {
            // ==============================
            // 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("Journal Voucher", 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 Journal Vouchers
            // ====================
            var journalVouchers = from d in db.TrnJournalVouchers
                                  where d.Id == JVId
                                  select d;

            if (journalVouchers.Any())
            {
                String particulars = journalVouchers.FirstOrDefault().Particulars;
                String JVNumber    = journalVouchers.FirstOrDefault().JVNumber;
                String JVDate      = journalVouchers.FirstOrDefault().JVDate.ToString("MM-dd-yyyy", CultureInfo.InvariantCulture);
                String preparedBy  = journalVouchers.FirstOrDefault().MstUser.FullName;
                String checkedBy   = journalVouchers.FirstOrDefault().MstUser1.FullName;
                String approvedBy  = journalVouchers.FirstOrDefault().MstUser2.FullName;

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

                tableJournalVouchers.AddCell(new PdfPCell(new Phrase("Particulars", fontArial11Bold))
                {
                    Rowspan = 2, Border = 0, PaddingTop = 10f, PaddingLeft = 5f, PaddingRight = 5f
                });
                tableJournalVouchers.AddCell(new PdfPCell(new Phrase(particulars, fontArial11))
                {
                    Rowspan = 2, Border = 0, PaddingTop = 10f, PaddingLeft = 5f, PaddingRight = 5f
                });
                tableJournalVouchers.AddCell(new PdfPCell(new Phrase("No.", fontArial11Bold))
                {
                    Border = 0, PaddingTop = 10f, PaddingLeft = 5f, PaddingRight = 5f, HorizontalAlignment = 2
                });
                tableJournalVouchers.AddCell(new PdfPCell(new Phrase(JVNumber, fontArial11))
                {
                    Border = 0, PaddingTop = 10f, PaddingLeft = 5f, PaddingRight = 5f, HorizontalAlignment = 2
                });
                tableJournalVouchers.AddCell(new PdfPCell(new Phrase("Date", fontArial11Bold))
                {
                    Border = 0, PaddingTop = 5f, PaddingLeft = 5f, PaddingRight = 5f, HorizontalAlignment = 2
                });
                tableJournalVouchers.AddCell(new PdfPCell(new Phrase(JVDate, fontArial11))
                {
                    Border = 0, PaddingTop = 5f, PaddingLeft = 5f, PaddingRight = 5f, HorizontalAlignment = 2
                });
                document.Add(tableJournalVouchers);

                document.Add(spaceTable);

                // ============
                // Get Journals
                // ============
                var journals = from d in db.TrnJournals
                               where d.JVId == JVId
                               select new Models.TrnJournal
                {
                    Id                = d.Id,
                    JournalDate       = d.JournalDate.ToString("MM-dd-yyyy", CultureInfo.InvariantCulture),
                    BranchId          = d.BranchId,
                    Branch            = d.MstBranch.Branch,
                    BranchCode        = d.MstBranch.BranchCode,
                    AccountId         = d.AccountId,
                    Account           = d.MstAccount.Account,
                    AccountCode       = d.MstAccount.AccountCode,
                    ArticleId         = d.ArticleId,
                    Article           = d.MstArticle.Article,
                    Particulars       = d.Particulars,
                    DebitAmount       = d.DebitAmount,
                    CreditAmount      = d.CreditAmount,
                    ORId              = d.ORId,
                    CVId              = d.CVId,
                    JVId              = d.JVId,
                    RRId              = d.RRId,
                    SIId              = d.SIId,
                    INId              = d.INId,
                    OTId              = d.OTId,
                    STId              = d.STId,
                    DocumentReference = d.DocumentReference,
                    APRRId            = d.APRRId,
                    ARSIId            = d.ARSIId,
                };


                if (journals.Any())
                {
                    PdfPTable tableStockTransferItems = new PdfPTable(6);
                    float[]   widthscellsPOLines      = new float[] { 75f, 30f, 75f, 75f, 45f, 45f };
                    tableStockTransferItems.SetWidths(widthscellsPOLines);
                    tableStockTransferItems.WidthPercentage = 100;
                    tableStockTransferItems.AddCell(new PdfPCell(new Phrase("Branch", fontArial11Bold))
                    {
                        HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 7f
                    });
                    tableStockTransferItems.AddCell(new PdfPCell(new Phrase("Code", fontArial11Bold))
                    {
                        HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 7f
                    });
                    tableStockTransferItems.AddCell(new PdfPCell(new Phrase("Account", fontArial11Bold))
                    {
                        HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 7f
                    });
                    tableStockTransferItems.AddCell(new PdfPCell(new Phrase("Article", fontArial11Bold))
                    {
                        HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 7f
                    });
                    tableStockTransferItems.AddCell(new PdfPCell(new Phrase("Debit", fontArial11Bold))
                    {
                        HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 7f
                    });
                    tableStockTransferItems.AddCell(new PdfPCell(new Phrase("Credit", fontArial11Bold))
                    {
                        HorizontalAlignment = 1, PaddingTop = 3f, PaddingBottom = 7f
                    });

                    Decimal totalDebitAmount  = 0;
                    Decimal totalCreditAmount = 0;

                    foreach (var journal in journals)
                    {
                        tableStockTransferItems.AddCell(new PdfPCell(new Phrase(journal.Branch, fontArial11))
                        {
                            HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 7f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        tableStockTransferItems.AddCell(new PdfPCell(new Phrase(journal.AccountCode, fontArial11))
                        {
                            HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 7f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        tableStockTransferItems.AddCell(new PdfPCell(new Phrase(journal.Account, fontArial11))
                        {
                            HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 7f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        tableStockTransferItems.AddCell(new PdfPCell(new Phrase(journal.Article, fontArial11))
                        {
                            HorizontalAlignment = 0, PaddingTop = 3f, PaddingBottom = 7f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        tableStockTransferItems.AddCell(new PdfPCell(new Phrase(journal.DebitAmount.ToString("#,##0.00"), fontArial11))
                        {
                            HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 7f, PaddingLeft = 5f, PaddingRight = 5f
                        });
                        tableStockTransferItems.AddCell(new PdfPCell(new Phrase(journal.CreditAmount.ToString("#,##0.00"), fontArial11))
                        {
                            HorizontalAlignment = 2, PaddingTop = 3f, PaddingBottom = 7f, PaddingLeft = 5f, PaddingRight = 5f
                        });

                        totalDebitAmount  += journal.DebitAmount;
                        totalCreditAmount += journal.CreditAmount;
                    }

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

                    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 End
            document.Close();

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

            return(new FileStreamResult(workStream, "application/pdf"));
        }
コード例 #9
0
        private void btnpdf_Click(object sender, EventArgs e)
        {
            if (cmbacademicyear.Text.Trim() == "")
            {
                MessageBox.Show("Select Acadamic Year!!!");
                return;
            }
            MongoClient            client = new MongoClient("mongodb://localhost");
            MongoServer            server = client.GetServer();
            MongoDatabase          db     = server.GetDatabase("NBA");
            MongoCursor <Students> put;
            MongoCursor <Marks>    put1;
            bool   f;
            string academicyear = cmbacademicyear.Text.Trim();

            string[] yr       = new string[4];
            long[]   n1       = new long[4];
            long[]   n2       = new long[4];
            long[]   withb1   = { 0, 0, 0, 0 }, withoutb1 = { 0, 0, 0, 0 };
            long[]   withb2   = { 0, 0, 0, 0 }, withoutb2 = { 0, 0, 0, 0 };
            long[]   withb3   = { 0, 0, 0, 0 }, withoutb3 = { 0, 0, 0, 0 };
            long[]   withb4   = { 0, 0, 0, 0 }, withoutb4 = { 0, 0, 0, 0 };
            long[]   withoutb = { 0, 0, 0, 0 };
            for (int a = 0; a < 4; a++)
            {
                yr[a] = academicyear;
                put   = db.GetCollection <Students>("Students").Find(Query.And(Query.EQ("academicyear", academicyear), Query.EQ("ad_type", "F.E."), Query.EQ("migration", "No")));

                n1[a] = put.Count();
                put   = db.GetCollection <Students>("Students").Find(Query.And(Query.EQ("academicyear", academicyear), Query.EQ("ad_type", "D.S.E.")));
                n2[a] = put.Count();
                put   = db.GetCollection <Students>("Students").Find(Query.EQ("academicyear", academicyear));
                foreach (Students i in put)
                {
                    f    = false;
                    put1 = db.GetCollection <Marks>("fe_marks").Find(Query.EQ("prn", i.prn));
                    foreach (Marks j in put1)
                    {
                        if (j.sem1_grade == "A.T.K.T." || j.sem2_grade == "A.T.K.T.")
                        {
                            withb1[a]++;
                            f = true;
                        }
                        else if (j.sem1_grade != "Fail" || j.sem2_grade != "Fail")
                        {
                            withoutb1[a]++;
                        }
                    }
                    put1 = db.GetCollection <Marks>("se_marks").Find(Query.EQ("prn", i.prn));
                    foreach (Marks j in put1)
                    {
                        if (j.sem1_grade == "A.T.K.T." || j.sem2_grade == "A.T.K.T.")
                        {
                            withb2[a]++;
                            f = true;
                        }
                        else if (j.sem1_grade != "Fail" || j.sem2_grade != "Fail")
                        {
                            withoutb2[a]++;
                        }
                    }
                    put1 = db.GetCollection <Marks>("te_marks").Find(Query.EQ("prn", i.prn));
                    foreach (Marks j in put1)
                    {
                        if (j.sem1_grade == "A.T.K.T." || j.sem2_grade == "A.T.K.T.")
                        {
                            withb3[a]++;
                            f = true;
                        }
                        else if (j.sem1_grade != "Fail" || j.sem2_grade != "Fail")
                        {
                            withoutb3[a]++;
                        }
                    }
                    put1 = db.GetCollection <Marks>("be_marks").Find(Query.EQ("prn", i.prn));
                    foreach (Marks j in put1)
                    {
                        if (j.sem1_grade == "A.T.K.T." || j.sem2_grade == "A.T.K.T.")
                        {
                            withb4[a]++;
                            f = true;
                        }
                        else if (j.sem1_grade != "Fail" || j.sem2_grade != "Fail")
                        {
                            withoutb4[a]++;
                        }
                    }
                    if (!f)
                    {
                        withoutb[a]++;
                    }
                }
                academicyear = pre_academic_year(academicyear + ".");
            }



            string path;

            f = true;
            DialogResult result = folderBrowserDialog1.ShowDialog();

            if (result == DialogResult.OK)
            {
                path = folderBrowserDialog1.SelectedPath;
                string[] files = Directory.GetFiles(path);
                foreach (string i in files)
                {
                    if (i == path + "\\Report.pdf")
                    {
                        if (DialogResult.No == MessageBox.Show("Replace Existing File ?", "", MessageBoxButtons.YesNo))
                        {
                            f = false;
                        }
                    }
                }
                if (f)
                {
                    Document doc = new Document(PageSize.A4);
                    try
                    {
                        PdfWriter wr = PdfWriter.GetInstance(doc, new FileStream((path + "\\Report.pdf"), FileMode.Create));
                    }
                    catch (IOException)
                    {
                        MessageBox.Show("Close Opened Report PDF file!");
                    }
                    doc.Open();
                    iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance("NBA_logo.png");
                    img.ScaleToFit(100f, 500f);
                    img.Border      = iTextSharp.text.Rectangle.BOX;
                    img.BorderColor = iTextSharp.text.BaseColor.BLACK;
                    img.BorderWidth = 5f;
                    doc.Add(img);

                    PdfPTable table = new PdfPTable(5);
                    table.HorizontalAlignment = Element.ALIGN_LEFT;
                    table.WidthPercentage     = 90;

                    Phrase p1 = new Phrase("Students’ Performance (150) (150)");
                    doc.Add(p1);



                    table.AddCell("Item");
                    table.AddCell("CAY(" + yr[0] + ")");
                    for (int i = 1; i < 4; i++)
                    {
                        table.AddCell("CAYm" + i + "(" + yr[i] + ")");
                    }

                    table.AddCell("Sanctioned intake strength of the programme (N)");
                    table.AddCell("59");
                    table.AddCell("57");
                    table.AddCell("61");
                    table.AddCell("64");

                    table.AddCell("students admitted in first year minus number of students migrated to other programmes at the end of 1st year (N1)");
                    for (int i = 0; i < 4; i++)
                    {
                        table.AddCell(n1[i].ToString());
                    }

                    table.AddCell("Number of students admitted in 2nd year in the same batch via lateral entry (N2)");
                    for (int i = 0; i < 4; i++)
                    {
                        table.AddCell(n2[i].ToString());
                    }

                    table.AddCell("Total number of students admitted in the Programme (N1+N2)");
                    for (int i = 0; i < 4; i++)
                    {
                        table.AddCell((n1[i] + n2[i]).ToString());
                    }

                    doc.Add(table);

                    PdfPTable table2 = new PdfPTable(6);
                    table2.HorizontalAlignment = Element.ALIGN_LEFT;
                    table2.WidthPercentage     = 100;
                    table2.SpacingBefore       = 50;
                    PdfPCell cell1 = new PdfPCell(new Phrase("Year of entry(in reverse Chronological order"));
                    cell1.Rowspan = 2;
                    table2.AddCell(cell1);
                    PdfPCell cell2 = new PdfPCell(new Phrase("Number of students admitted in 1st year+ admitted via lateral entry in 2nd year (N1+N2)"));
                    cell2.Rowspan = 2;
                    table2.AddCell(cell2);
                    PdfPCell cell3 = new PdfPCell(new Phrase("Number of students who have successfully graduated*"));
                    cell3.Colspan = 4;
                    table2.AddCell(cell3);

                    table2.AddCell("I year");
                    table2.AddCell("II year");
                    table2.AddCell("III year");
                    table2.AddCell("IV year");

                    table2.AddCell("CAY");
                    table2.AddCell((n1[0] + n2[0]).ToString());
                    table2.AddCell((withb1[0] + withoutb1[0]).ToString());
                    table2.AddCell((withb2[0] + withoutb2[0]).ToString());
                    table2.AddCell((withb3[0] + withoutb3[0]).ToString());
                    table2.AddCell((withb4[0] + withoutb4[0]).ToString());

                    for (int i = 1; i < 4; i++)
                    {
                        table2.AddCell("CAYm" + i);
                        table2.AddCell((n1[i] + n2[i]).ToString());
                        table2.AddCell((withb1[i] + withoutb1[i]).ToString());
                        table2.AddCell((withb2[i] + withoutb2[i]).ToString());
                        table2.AddCell((withb3[i] + withoutb3[i]).ToString());
                        table2.AddCell((withb4[i] + withoutb4[i]).ToString());
                    }

                    /* table2.AddCell("CAYm4 (LYG)");
                     * table2.AddCell("");
                     * table2.AddCell("");
                     * table2.AddCell("");
                     * table2.AddCell("");
                     * table2.AddCell("");
                     *
                     * table2.AddCell("CAYm5 (LYGm1)");
                     * table2.AddCell("");
                     * table2.AddCell("");
                     * table2.AddCell("");
                     * table2.AddCell("");
                     * table2.AddCell("");
                     *
                     *
                     *
                     * table2.AddCell("CAYm6 (LYGm2)");
                     * table2.AddCell("");
                     * table2.AddCell("");
                     * table2.AddCell("");
                     * table2.AddCell("");
                     * table2.AddCell("");
                     */

                    doc.Add(table2);

                    doc.Add(new Paragraph("*successfully completed implies zero backlogs"));


                    doc.NewPage();
                    doc.Add(new Phrase("\n\n\n\n\n\n"));
                    PdfPTable table3 = new PdfPTable(6);
                    table3.HorizontalAlignment = Element.ALIGN_LEFT;
                    table3.WidthPercentage     = 100;
                    table3.SpacingBefore       = 50;
                    PdfPCell cell4 = new PdfPCell(new Phrase("Year of entry(in reverse Chronological order"));
                    cell4.Rowspan = 2;
                    table3.AddCell(cell4);
                    PdfPCell cell5 = new PdfPCell(new Phrase("Number of students admitted in 1st year+ admitted via lateral entry in 2nd year(N1+N2)"));
                    cell5.Rowspan = 2;
                    table3.AddCell(cell5);
                    PdfPCell cell6 = new PdfPCell(new Phrase("Number of students who have successfully graduated without backlogs in any year of study*"));
                    cell6.Colspan = 4;
                    table3.AddCell(cell6);

                    table3.AddCell("I year");
                    table3.AddCell("II year");
                    table3.AddCell("III year");
                    table3.AddCell("IV year");

                    table3.AddCell("CAY");
                    table3.AddCell((n1[0] + n2[0]).ToString());
                    table3.AddCell((withoutb1[0]).ToString());
                    table3.AddCell((withoutb2[0]).ToString());
                    table3.AddCell((withoutb3[0]).ToString());
                    table3.AddCell((withoutb4[0]).ToString());

                    for (int i = 1; i < 4; i++)
                    {
                        table3.AddCell("CAYm" + i);
                        table3.AddCell((n1[i] + n2[i]).ToString());
                        table3.AddCell((withoutb1[i]).ToString());
                        table3.AddCell((withoutb2[i]).ToString());
                        table3.AddCell((withoutb3[i]).ToString());
                        table3.AddCell((withoutb4[i]).ToString());
                    }

                    /*
                     * table3.AddCell("CAYm4 (LYG)");
                     * table3.AddCell("");
                     * table3.AddCell("");
                     * table3.AddCell("");
                     * table3.AddCell("");
                     * table3.AddCell("");
                     *
                     *
                     * table3.AddCell("CAYm5 (LYGm1)");
                     * table3.AddCell("");
                     * table3.AddCell("");
                     * table3.AddCell("");
                     * table3.AddCell("");
                     * table3.AddCell("");
                     *
                     *
                     * table3.AddCell("CAYm6 (LYGm2)");
                     * table3.AddCell("");
                     * table3.AddCell("");
                     * table3.AddCell("");
                     * table3.AddCell("");
                     * table3.AddCell("");*/
                    doc.Add(table3);

                    /*
                     * doc.Add(new Phrase("* successfully completed implies zero backlogs", FontFactory.GetFont("bookman old style", 14, BaseColor.RED)));
                     *
                     * doc.Add(new Phrase("\n 4.1. Success Rate in the stipulated period of the programme (50)(50)\n 4.1.1. Success rate without backlogs in any year of study (25) (25)", FontFactory.GetFont("bookman old style", 12)));
                     * doc.Add(new Phrase("\n SI= (Number of students who graduated from the programme without backlog)/\n (Number of students admitted in the first year of that batch and admitted in 2nd year via lateral entry) \n \n Average SI = Mean of success index (SI) for past three batches \n Success rate without backlogs in any year of study = 20 × Average SI"));
                     *
                     * doc.NewPage();
                     * doc.Add(new Phrase("\n\n\n\n\n\n"));
                     * PdfPTable table4 = new PdfPTable(4);
                     * table4.HorizontalAlignment = Element.ALIGN_LEFT;
                     * table4.WidthPercentage = 100;
                     * table4.SpacingBefore = 50;
                     * table4.AddCell("Item");
                     * table4.AddCell("Latest Year of Graduation, LYG (CAYm4)(" + yr[1] + ")");
                     * table4.AddCell("Latest Year of Graduation minus 1,LYGm1 (CAYm5) (" + yr[2] + ")");
                     * table4.AddCell("Latest Year of Graduation minus 2,LYGm2(CAYm6) (" + yr[3] + ")");
                     *
                     * table4.AddCell("Number of students admitted in the corresponding First Year + admitted via lateral entry in 2nd year");
                     * table4.AddCell("");
                     * table4.AddCell("");
                     * table4.AddCell("");
                     *
                     * table4.AddCell("Number of students who have graduated without backlogs in the stipulated period");
                     * table4.AddCell("");
                     * table4.AddCell("");
                     * table4.AddCell("");
                     *
                     * table4.AddCell("Success index (SI)");
                     * table4.AddCell("");
                     * table4.AddCell("");
                     * table4.AddCell("");
                     * doc.Add(table4);
                     *
                     * doc.NewPage();
                     * doc.Add(new Phrase("4.1.2. Success rate in stipulated period (25)(25)", FontFactory.GetFont("bookman old style", 14)));
                     * doc.Add(new Phrase("SI= (Number of students who graduated from the programme in the stipulated period of course duration)/ \n (Number of students admitted in the first year of that batch and admitted in 2nd year via lateral entry) \n Average SI = mean of success index (SI) for past three batches \n Success rate = 30 × Average SI"));
                     * PdfPTable table5 = new PdfPTable(4);
                     * table5.HorizontalAlignment = Element.ALIGN_LEFT;
                     * table5.WidthPercentage = 100;
                     *
                     * table5.AddCell("Item");
                     * table5.AddCell("Latest Year of Graduation, LYG(CAYm4)");
                     * table5.AddCell("Latest Year of Graduation minus 1,LYGm1(CAYm5)");
                     * table5.AddCell("Latest Year of Graduation minus 2,LYGm2(CAYm6)");
                     *
                     * table5.AddCell("Number of students admitted in the corresponding First Year + admitted via lateral entry in 2nd year");
                     * table5.AddCell("");
                     * table5.AddCell("");
                     * table5.AddCell("");
                     *
                     * table5.AddCell("Number of students who have graduated in the stipulated period");
                     * table5.AddCell("");
                     * table5.AddCell("");
                     * table5.AddCell("");
                     *
                     * table5.AddCell("Success index (SI)");
                     * table5.AddCell("");
                     * table5.AddCell("");
                     * table5.AddCell("");
                     * doc.Add(table5);
                     *
                     *
                     *
                     * doc.Add(new Phrase("\n \n 4.2. Academic Performance in Fourth Year (10) (10)", FontFactory.GetFont("bookman old style", 12)));
                     * doc.Add(new Phrase("Academic Performance Level = ((Mean of 4h Year Grade Point Average of all successful Students on a 10 point scale) or \n (Mean of the percentage of marks of all successful students in Fourth Year/10)) x (successful students/number of students appeared in the examination) Successful students are those who passed in all the final year courses"));
                     *
                     * PdfPTable table6 = new PdfPTable(2);
                     * table6.HorizontalAlignment = Element.ALIGN_LEFT;
                     * table6.WidthPercentage = 100;
                     * //table6.SpacingBefore = 50;
                     * table6.AddCell("Academic Performance Level");
                     * table6.AddCell("LYG(CAYm4) – IV Year No. of Students");
                     *
                     * table6.AddCell("9-10");
                     * table6.AddCell("0");
                     *
                     * table6.AddCell("8-9");
                     * table6.AddCell("");
                     *
                     * table6.AddCell("7-8");
                     * table6.AddCell("");
                     *
                     * table6.AddCell("6-7");
                     * table6.AddCell("");
                     *
                     * table6.AddCell("5-6");
                     * table6.AddCell("");
                     *
                     * table6.AddCell("OTotal");
                     * table6.AddCell("");
                     *
                     * PdfPCell cell7 = new PdfPCell(new Phrase("Approximating API by Mid-CGPA"));
                     * cell7.HorizontalAlignment = 1;
                     * cell7.Colspan = 2;
                     * table6.AddCell(cell7);
                     *
                     * table6.AddCell("Mean of CGPA/Percentage of all the students (API)");
                     * table6.AddCell("");
                     *
                     *
                     * table6.AddCell("Total no. of successful students");
                     * table6.AddCell("");
                     *
                     *
                     * table6.AddCell("Total no. of students appeared in the examination");
                     * table6.AddCell("");
                     *
                     * PdfPCell cel11 = new PdfPCell(new Phrase("Assessment", FontFactory.GetFont("bookman old style", 12, BaseColor.RED)));
                     * table6.AddCell(cel11);
                     * table6.AddCell("");
                     * doc.Add(table6);
                     *
                     * // table7
                     *
                     *
                     * PdfPTable table7 = new PdfPTable(2);
                     * table7.HorizontalAlignment = Element.ALIGN_LEFT;
                     * table7.WidthPercentage = 100;
                     * //table7.SpacingBefore = 50;
                     * doc.NewPage();
                     * doc.Add(new Phrase("\n \n 4.3. Academic Performance in Third Year (20)(20)", FontFactory.GetFont("bookman old style", 12)));
                     * doc.Add(new Phrase("Academic Performance Level = 2 * ((Mean of 3rd Year Grade Point Average of all successful Students on a 10 point scale) or (Mean of the percentage of marks of all successful students inThird Year/ 10)) x (successful students/number of students appeared in the examination)Successful students are those who are permitted to proceed to the final year"));
                     * table7.AddCell("Academic Performance Level");
                     * table7.AddCell("LYG(CAYm4) – IV Year No. of Students");
                     *
                     * table7.AddCell("9-10");
                     * table7.AddCell("0");
                     *
                     * table7.AddCell("8-9");
                     * table7.AddCell("");
                     *
                     * table7.AddCell("7-8");
                     * table7.AddCell("");
                     *
                     * table7.AddCell("6-7");
                     * table7.AddCell("");
                     *
                     * table7.AddCell("5-6");
                     * table7.AddCell("");
                     *
                     * table7.AddCell("OTotal");
                     * table7.AddCell("");
                     *
                     * PdfPCell cell8 = new PdfPCell(new Phrase("Approximating API by Mid-CGPA"));
                     * cell8.HorizontalAlignment = 1;
                     * cell8.Colspan = 2;
                     * table7.AddCell(cell8);
                     *
                     * table7.AddCell("Mean of CGPA/Percentage of all the students (API)");
                     * table7.AddCell("");
                     *
                     *
                     * table7.AddCell("Total no. of successful students");
                     * table7.AddCell("");
                     *
                     *
                     * table7.AddCell("Total no. of students appeared in the examination");
                     * table7.AddCell("");
                     *
                     * doc.Add(table7);
                     *
                     *
                     * //table 8
                     *
                     *
                     * PdfPTable table8 = new PdfPTable(2);
                     * table8.HorizontalAlignment = Element.ALIGN_LEFT;
                     * table8.WidthPercentage = 100;
                     * //table8.SpacingBefore = 50;
                     * doc.Add(new Phrase("\n \n 4.4. Academic Performance in Second Year (20)(20)", FontFactory.GetFont("bookman old style", 12)));
                     * doc.Add(new Phrase("Academic Performance Level = 2 * ((Mean of 2nd Year Grade Point Average of all successful Students on a 10 point scale) or (Mean of the percentage of marks of all successful students in Second Year / 10)) x (successful students/number of students appeared in the examination)Successful students are those who are permitted to proceed to the third year"));
                     * table8.AddCell("Academic Performance Level");
                     * table8.AddCell("LYG(CAYm4) – IV Year No. of Students");
                     *
                     * table8.AddCell("9-10");
                     * table8.AddCell("0");
                     *
                     * table8.AddCell("8-9");
                     * table8.AddCell("");
                     *
                     * table8.AddCell("7-8");
                     * table8.AddCell("");
                     *
                     * table8.AddCell("6-7");
                     * table8.AddCell("");
                     *
                     * table8.AddCell("5-6");
                     * table8.AddCell("");
                     *
                     * table8.AddCell("OTotal");
                     * table8.AddCell("");
                     *
                     * PdfPCell cell9 = new PdfPCell(new Phrase("Approximating API by Mid-CGPA"));
                     * cell9.HorizontalAlignment = 1;
                     * cell9.Colspan = 2;
                     * table8.AddCell(cell9);
                     *
                     * table8.AddCell("Mean of CGPA/Percentage of all the students (API)");
                     * table8.AddCell("");
                     *
                     *
                     * table8.AddCell("Total no. of successful students");
                     * table8.AddCell("");
                     *
                     *
                     * table8.AddCell("Total no. of students appeared in the examination");
                     * table8.AddCell("");
                     *
                     * doc.Add(table8);*/
                    doc.Close();

                    System.Diagnostics.Process.Start(path + "\\Report.pdf");
                }
            }
        }
コード例 #10
0
        public async Task <FileResult> DetailsPdf(int?id, string[] column)
        {
            var invoiceNum = await _context.InvoiceNums.SingleOrDefaultAsync(m => m.Id == id);

            var spareparts = _context.Spareparts.Include(s => s.Country).Include(s => s.Equipment).Include(s => s.Manufacturer).Include(i => i.InvoiceSparepartNums).ToList();


            // var listSparepartsInInvoiceNum = new List<Sparepart>();
            List <ViewNumSparepart> viewNumSpareparts = new List <ViewNumSparepart>();


            foreach (var sparepart in spareparts)
            {
                foreach (var item in sparepart.InvoiceSparepartNums.OrderByDescending(s => s.Num))
                {
                    if (item.InvoiceNumId == id)
                    {
                        viewNumSpareparts.Add(new ViewNumSparepart {
                            Num = item.Num, Sparepart = sparepart
                        });
                    }
                }
            }



            var ms     = new MemoryStream();
            var pdfDoc = new Document(PageSize.A4);

            PdfWriter.GetInstance(pdfDoc, ms);
            var tahomaFont     = MyPDF.GetUnicodeFont("Tahoma", MyPDF.GetTahomaFontPath(), 11, Font.NORMAL, BaseColor.Black);
            var tahomaFontBold = MyPDF.GetUnicodeFont("Tahoma", MyPDF.GetTahomaFontPath(), 13, Font.BOLD, BaseColor.Black);
            var tahomaFontRed  = MyPDF.GetUnicodeFont("Tahoma", MyPDF.GetTahomaFontPath(), 13, Font.BOLD, BaseColor.Red);

            pdfDoc.AddAuthor("FreseBel and K");
            pdfDoc.Header = new HeaderFooter(new Phrase("Invoice: " + invoiceNum.Num), false);
            pdfDoc.Open();
            string    st;
            Font      font        = tahomaFont;
            PdfPTable table       = new PdfPTable(2);
            var       pdfCellNull = new PdfPCell(new Phrase("                 ", tahomaFont))
            {
                Border = 0
            };

            table.AddCell(pdfCellNull);
            var pdfCell = new PdfPCell(new Phrase("ИНВОЙС", tahomaFontBold))
            {
                Border = 0
            };

            table.AddCell(pdfCell);
            table.AddCell(pdfCellNull);
            st      = invoiceNum.Num + " / " + invoiceNum.Date;
            pdfCell = new PdfPCell(new Phrase(@st, tahomaFontBold))
            {
                Border = 0
            };
            table.AddCell(pdfCell);
            table.AddCell(pdfCellNull);
            st      = "Отправитель: " + invoiceNum.Sender;
            pdfCell = new PdfPCell(new Phrase(@st, tahomaFont))
            {
                Border = 0
            };
            table.AddCell(pdfCell);
            table.AddCell(pdfCellNull);
            table.AddCell(pdfCellNull);
            table.AddCell(pdfCellNull);
            st      = "Получатель: " + invoiceNum.Recipient;
            pdfCell = new PdfPCell(new Phrase(@st, tahomaFont))
            {
                Border = 0,
            };
            table.AddCell(pdfCell);
            table.AddCell(pdfCellNull);
            table.AddCell(pdfCellNull);
            // Paragraph p;
            pdfDoc.Add(table);

            // Image img;
            string[] nameImg;

            int      iter        = 0;
            DateTime dateTimenow = new DateTime();

            dateTimenow = DateTime.Now;
            foreach (var item in viewNumSpareparts.OrderBy(x => x.Num))
            {
                var      tahomaBold = tahomaFontBold;
                DateTime date       = new DateTime();
                date = ParseDate(item.Sparepart.Equipment.Ps);
                if (dateTimenow > date)
                {
                    tahomaBold = tahomaFontRed;
                }
                else
                {
                    tahomaBold = tahomaFontBold;
                }
                table = new PdfPTable(2)
                {
                    KeepTogether = true
                };
                iter++;
                //p = new Paragraph("" + item.FullName, tahomaFont); pdfDoc.Add(p);
                nameImg = item.Sparepart.Image.Split("/");
                //img = Image.GetInstance(MyPDF.GetImagePath(nameImg[2]));
                //img.ScaleAbsolute(159f, 159f);
                //pdfDoc.Add(img);
                //p = new Paragraph("" + item.Description, tahomaFont); pdfDoc.Add(p);
                //p = new Paragraph("" + item.Manufacturer, tahomaFont); pdfDoc.Add(p);

                pdfCell = new PdfPCell(new Phrase("", tahomaBold))
                {
                    Border  = 0,
                    Colspan = 2
                };
                table.AddCell(pdfCell);

                pdfCell = new PdfPCell(new Phrase("", tahomaBold))
                {
                    Border  = 0,
                    Colspan = 2
                };
                table.AddCell(pdfCell);


                st = item.Num + " " + item.Sparepart.Number + " " + item.Sparepart.NameEn + " / " + item.Sparepart.NameRus + "/" + item.Sparepart.Country.Nam;

                pdfCell = new PdfPCell(new Phrase(st, tahomaBold))
                {
                    Border  = 0,
                    Colspan = 2
                };
                table.AddCell(pdfCell);



                pdfCell = new PdfPCell(new Phrase("", tahomaFont))
                {
                    Border = 0,
                    Image  = Image.GetInstance(MyPDF.GetImagePath(nameImg[2]))
                };
                table.AddCell(pdfCell);


                st = "";
                if (column.Contains("4"))
                {
                    st = st + " Описание: " + item.Sparepart.Description;
                }

                if (column.Contains("7"))
                {
                    st = st + " Используется в оборудовании: " + item.Sparepart.Equipment.Name;
                }
                if (column.Contains("8"))
                {
                    st = st + " Код: " + item.Sparepart.Equipment.Code;
                }
                if (column.Contains("9"))
                {
                    st = st + " " + item.Sparepart.Equipment.Description;
                }

                if (column.Contains("10"))
                {
                    st = st + " Рег.номер: " + item.Sparepart.Equipment.RegNumber;
                }

                if (column.Contains("11"))
                {
                    st = st + " Действительно до: " + item.Sparepart.Equipment.Ps;
                }

                pdfCell = new PdfPCell(new Phrase(st, tahomaFont))
                {
                    Border = 0,
                };
                table.AddCell(pdfCell);
                st = "";
                if (column.Contains("13"))
                {
                    st = st + "Изготовитель " + item.Sparepart.Manufacturer.NameFull + "/" + item.Sparepart.Manufacturer.NameShort;
                }
                if (column.Contains("15"))
                {
                    st = st + "Код изготовителя " + item.Sparepart.Manufacturer.Code;
                }
                if (column.Contains("16"))
                {
                    st = st + "Адрес " + item.Sparepart.Manufacturer.AdressOfDeparture;
                }
                pdfCell = new PdfPCell(new Phrase(st, tahomaFont))
                {
                    Border  = 0,
                    Colspan = 2
                };
                table.AddCell(pdfCell);
                if (column.Contains("17") && (column.Contains("12")))
                {
                    nameImg = item.Sparepart.Manufacturer.Logo.Split("/");
                    pdfCell = new PdfPCell()
                    {
                        Border = 0,
                        Image  = Image.GetInstance(MyPDF.GetImagePath(nameImg[2]))
                    };
                    table.AddCell(pdfCell);

                    nameImg = item.Sparepart.Equipment.Image.Split("/");
                    pdfCell = new PdfPCell()
                    {
                        Border = 0,
                        Image  = Image.GetInstance(MyPDF.GetImagePath(nameImg[2]))
                    };
                    table.AddCell(pdfCell);
                }
                else
                {
                    if (column.Contains("12"))
                    {
                        nameImg = item.Sparepart.Equipment.Image.Split("/");
                        pdfCell = new PdfPCell()
                        {
                            Border = 0,
                            Image  = Image.GetInstance(MyPDF.GetImagePath(nameImg[2]))
                        };
                        table.AddCell(pdfCell);
                        st      = "";
                        st      = st + item.Sparepart.Equipment.Name;
                        st      = st + " Код: " + item.Sparepart.Equipment.Code;
                        st      = st + " " + item.Sparepart.Equipment.Description;
                        st      = st + " Рег.номер: " + item.Sparepart.Equipment.RegNumber;
                        st      = st + " Действительно до: " + item.Sparepart.Equipment.Ps;
                        pdfCell = new PdfPCell(new Phrase(st, tahomaFont))
                        {
                            Border = 0
                        };
                        table.AddCell(pdfCell);
                    }
                    if (column.Contains("17"))
                    {
                        nameImg = item.Sparepart.Manufacturer.Logo.Split("/");
                        pdfCell = new PdfPCell()
                        {
                            Border = 0,
                            Image  = Image.GetInstance(MyPDF.GetImagePath(nameImg[2]))
                        };
                        table.AddCell(pdfCell);
                        st      = "";
                        st      = st + "" + item.Sparepart.Manufacturer.NameFull + "/" + item.Sparepart.Manufacturer.NameShort;
                        st      = st + "Код  " + item.Sparepart.Manufacturer.Code;
                        st      = st + " " + item.Sparepart.Manufacturer.AdressOfDeparture;
                        pdfCell = new PdfPCell(new Phrase(st, tahomaFont))
                        {
                            Border = 0
                        };
                        table.AddCell(pdfCell);
                    }
                }


                pdfDoc.Add(table);
                // if (iter%3==0) pdfDoc.NewPage();
            }
            pdfDoc.Close();
            var pdfBytes = ms.ToArray();

            ms.Dispose();
            MyPDF.VerifyPdfFileIsReadable(pdfBytes);
            string file_type = "application/pdf";
            string file_name = "Invoice" + invoiceNum.Num + invoiceNum.Date + ".pdf";

            return(File(pdfBytes, file_type, file_name));
        }
コード例 #11
0
        public void GerarPropostaPdf()
        {
            if (_oportunidade.OportunidadeProposta == null)
            {
                throw new Exception("Proposta da Oportunidade não encontrada");
            }

            HttpWebRequest wreq = (HttpWebRequest)HttpWebRequest.Create(_url);

            if (_externo == false)
            {
                var httpCookie = HttpContext.Current.Request.Cookies[".ASPXAUTH_CRM_ECOPORTO"];

                wreq.CookieContainer = new CookieContainer();
                wreq.CookieContainer.Add(new Cookie(httpCookie.Name, httpCookie.Value, httpCookie.Path, HttpContext.Current.Request.Url.Host));
            }

            HttpWebResponse wres = (HttpWebResponse)wreq.GetResponse();

            var nomeArquivo = $"{_oportunidade.Descricao}-{_oportunidade.Identificacao}";

            using (Stream s = wres.GetResponseStream())
            {
                using (StreamReader sr = new StreamReader(s))
                {
                    var conteudo = sr.ReadToEnd();

                    conteudo = $"{Regex.Replace(conteudo, @"\t|\n|\r", "")}";

                    object arquivoPdf = HttpContext.Current.Server.MapPath($"~/App_Data/{nomeArquivo.CorrigirNomeArquivo()}.pdf");

                    conteudo = Regex.Replace(conteudo, "page-break-before: always;", "");

                    MemoryStream PDFData = new MemoryStream();
                    Document     doc     = new Document(PageSize.A4);

                    doc.SetMargins(36, 36, 110, 36);

                    PdfWriter writer = PdfWriter.GetInstance(doc, PDFData);
                    writer.PageEvent = new PdfHelpers($"ECO {_oportunidade.Identificacao} {_oportunidade.TipoServico.ToName()} {_oportunidade.Referencia}");
                    doc.Open();

                    PdfPTable tab = new PdfPTable(2);

                    tab.DefaultCell.Border = Rectangle.NO_BORDER;
                    tab.TotalWidth         = 800;

                    var css = File.ReadAllText(HttpContext.Current.Server.MapPath("~/Content/css/pdf.css"));

                    using (var cssMemoryStream = new MemoryStream(Encoding.UTF8.GetBytes(css)))
                    {
                        using (var htmlMemoryStream = new MemoryStream(Encoding.UTF8.GetBytes(conteudo)))
                        {
                            XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, htmlMemoryStream, cssMemoryStream);
                        }
                    }

                    doc.Add(tab);
                    doc.Close();

                    var bytes = PDFData.ToArray();
                    if (_anexar)
                    {
                        IncluirAnexo(_oportunidade.Id, arquivoPdf.ToString(), TipoAnexo.PROPOSTA, bytes, _oportunidade.CriadoPor);
                    }

                    File.WriteAllBytes(arquivoPdf.ToString(), bytes);
                }
            }
        }
コード例 #12
0
        public MemoryStream GeneratePdfTemplate(DOReturnViewModel viewModel, int clientTimeZoneOffset)
        {
            const int MARGIN = 15;

            Font header_font      = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 12);
            Font header_bold_font = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 12);
            Font normal_font      = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);
            Font bold_font        = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);

            Document     document = new Document(PageSize.A5.Rotate(), MARGIN, MARGIN, MARGIN, MARGIN);
            MemoryStream stream   = new MemoryStream();
            PdfWriter    writer   = PdfWriter.GetInstance(document, stream);

            document.Open();

            #region Header
            PdfPTable headerTable = new PdfPTable(2);
            headerTable.SetWidths(new float[] { 10f, 10f });
            headerTable.WidthPercentage = 100;
            PdfPTable headerTable1 = new PdfPTable(1);
            PdfPTable headerTable2 = new PdfPTable(1);

            PdfPCell cellHeader1 = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            PdfPCell cellHeader2 = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            PdfPCell cellHeaderBody = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            PdfPCell cellHeaderCS2 = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, Colspan = 2
            };

            cellHeaderBody.Phrase = new Phrase("PT. DANLIRIS", header_font);
            headerTable1.AddCell(cellHeaderBody);

            cellHeaderBody.Phrase = new Phrase("", header_font);
            headerTable1.AddCell(cellHeaderBody);

            cellHeaderBody.Phrase = new Phrase($"No. {viewModel.DOReturnType}{viewModel.AutoIncreament.ToString().PadLeft(6, '0')}", bold_font);
            headerTable1.AddCell(cellHeaderBody);

            cellHeaderBody.Phrase = new Phrase("", header_font);
            headerTable1.AddCell(cellHeaderBody);

            cellHeaderBody.Phrase = new Phrase("Harap dikeluarkan barang tersebut di bawah ini : ", normal_font);
            headerTable1.AddCell(cellHeaderBody);

            cellHeader1.AddElement(headerTable1);
            headerTable.AddCell(cellHeader1);

            cellHeaderBody.Phrase = new Phrase("", normal_font);
            headerTable2.AddCell(cellHeaderBody);

            cellHeaderBody.HorizontalAlignment = Element.ALIGN_CENTER;
            cellHeaderBody.Phrase = new Phrase("Sukoharjo, " + viewModel.DOReturnDate?.AddHours(clientTimeZoneOffset).ToString("dd MMMM yyyy", new CultureInfo("id-ID")), normal_font);
            headerTable2.AddCell(cellHeaderBody);

            cellHeaderBody.HorizontalAlignment = Element.ALIGN_CENTER;
            cellHeaderBody.Phrase = new Phrase("Kepada", normal_font);
            headerTable2.AddCell(cellHeaderBody);

            cellHeaderBody.HorizontalAlignment = Element.ALIGN_CENTER;
            cellHeaderBody.Phrase = new Phrase("Yth. Bpk./Ibu. " + viewModel.HeadOfStorage, normal_font);
            headerTable2.AddCell(cellHeaderBody);

            cellHeaderBody.HorizontalAlignment = Element.ALIGN_CENTER;
            cellHeaderBody.Phrase = new Phrase("Bag. Gudang Packing Finishing/Printing", normal_font);
            headerTable2.AddCell(cellHeaderBody);

            cellHeaderBody.HorizontalAlignment = Element.ALIGN_CENTER;
            cellHeaderBody.Phrase = new Phrase("D.O. RETUR", bold_font);
            headerTable2.AddCell(cellHeaderBody);
            cellHeaderBody.Phrase = new Phrase("", normal_font);
            headerTable2.AddCell(cellHeaderBody);

            cellHeaderBody.HorizontalAlignment = Element.ALIGN_CENTER;
            cellHeaderBody.Phrase = new Phrase("Untuk melengkapi Bon No. : ......................................... ", normal_font);
            headerTable2.AddCell(cellHeaderBody);
            cellHeaderBody.Phrase = new Phrase("", normal_font);
            headerTable2.AddCell(cellHeaderBody);

            cellHeader2.AddElement(headerTable2);
            headerTable.AddCell(cellHeader2);

            cellHeaderCS2.Phrase = new Phrase("", normal_font);
            headerTable.AddCell(cellHeaderCS2);

            document.Add(headerTable);

            #endregion Header

            #region Body

            int index = 1;

            PdfPTable bodyTable = new PdfPTable(6);
            PdfPCell  bodyCell  = new PdfPCell();

            float[] widthsBody = new float[] { 3f, 13f, 7f, 7f, 7f, 7f };
            bodyTable.SetWidths(widthsBody);
            bodyTable.WidthPercentage = 100;

            bodyCell.HorizontalAlignment = Element.ALIGN_CENTER;
            bodyCell.Phrase = new Phrase("No.", bold_font);
            bodyTable.AddCell(bodyCell);

            bodyCell.Phrase = new Phrase("Nama", bold_font);
            bodyTable.AddCell(bodyCell);

            bodyCell.Phrase = new Phrase("Jenis/Code", bold_font);
            bodyTable.AddCell(bodyCell);

            bodyCell.Phrase = new Phrase("Pcs/Roll/Pt", bold_font);
            bodyTable.AddCell(bodyCell);

            bodyCell.Phrase = new Phrase("Mtr/Yds", bold_font);
            bodyTable.AddCell(bodyCell);

            bodyCell.Phrase = new Phrase("Kg/Bale", bold_font);
            bodyTable.AddCell(bodyCell);

            foreach (DOReturnDetailViewModel detail in viewModel.DOReturnDetails)
            {
                var noBon = detail.DOReturnItems.FirstOrDefault().ShipmentDocumentCode;

                foreach (DOReturnDetailItemViewModel detailItem in detail.DOReturnDetailItems)
                {
                    bodyCell.Phrase = new Phrase("", normal_font);
                    bodyTable.AddCell(bodyCell);

                    bodyCell.Phrase = new Phrase("Ex. Faktur : " + detail.SalesInvoice.SalesInvoiceNo + " \nEx. DO : " + detailItem.DOSales.DOSalesNo + "\nEx. Bon : " + noBon, bold_font);
                    bodyTable.AddCell(bodyCell);

                    bodyCell.Phrase = new Phrase("", normal_font);
                    bodyTable.AddCell(bodyCell);

                    bodyCell.Phrase = new Phrase("", normal_font);
                    bodyTable.AddCell(bodyCell);

                    bodyCell.Phrase = new Phrase("", normal_font);
                    bodyTable.AddCell(bodyCell);

                    bodyCell.Phrase = new Phrase("", normal_font);
                    bodyTable.AddCell(bodyCell);
                }

                foreach (DOReturnItemViewModel item in detail.DOReturnItems)
                {
                    bodyCell.Phrase = new Phrase((index++).ToString(), normal_font);
                    bodyTable.AddCell(bodyCell);

                    bodyCell.Phrase = new Phrase(item.ProductName, normal_font);
                    bodyTable.AddCell(bodyCell);

                    bodyCell.Phrase = new Phrase(item.ProductCode, normal_font);
                    bodyTable.AddCell(bodyCell);

                    bodyCell.Phrase = new Phrase(string.Format("{0:n0}", item.Quantity) + " " + item.PackingUom, normal_font);
                    bodyTable.AddCell(bodyCell);

                    bodyCell.Phrase = new Phrase(item.Total + " " + item.Uom.Unit, normal_font);
                    bodyTable.AddCell(bodyCell);

                    bodyCell.Phrase = new Phrase("0", normal_font);
                    bodyTable.AddCell(bodyCell);
                }
            }

            document.Add(bodyTable);

            #endregion Body

            #region Footer

            PdfPTable footerTable    = new PdfPTable(1);
            PdfPCell  cellFooterLeft = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT
            };

            float[] widthsFooter = new float[] { 10f };
            footerTable.SetWidths(widthsFooter);
            footerTable.WidthPercentage = 100;

            cellFooterLeft.Phrase = new Phrase("", normal_font);
            footerTable.AddCell(cellFooterLeft);
            cellFooterLeft.Phrase = new Phrase("", normal_font);
            footerTable.AddCell(cellFooterLeft);

            cellFooterLeft.Phrase = new Phrase("No LTKP : " + viewModel.LTKPNo, normal_font);
            footerTable.AddCell(cellFooterLeft);

            cellFooterLeft.Colspan = 3;
            cellFooterLeft.Phrase  = new Phrase("", bold_font);
            footerTable.AddCell(cellFooterLeft);

            cellFooterLeft.Colspan = 3;
            cellFooterLeft.Phrase  = new Phrase("Dari bagian / Retur dari : " + viewModel.ReturnFrom, bold_font);
            footerTable.AddCell(cellFooterLeft);

            cellFooterLeft.Colspan = 3;
            cellFooterLeft.Phrase  = new Phrase("Keterangan : " + viewModel.Remark, bold_font);
            footerTable.AddCell(cellFooterLeft);

            cellFooterLeft.Colspan = 3;
            cellFooterLeft.Phrase  = new Phrase("", bold_font);
            footerTable.AddCell(cellFooterLeft);

            PdfPTable signatureTable = new PdfPTable(3)
            {
                HorizontalAlignment = Element.ALIGN_CENTER
            };
            PdfPCell signatureCell = new PdfPCell()
            {
                HorizontalAlignment = Element.ALIGN_CENTER
            };

            float[] widthsSignanture = new float[] { 10f, 10f, 10f };
            signatureTable.SetWidths(widthsSignanture);
            signatureTable.WidthPercentage = 100;

            signatureCell.Phrase = new Phrase("Adm.Penjualan", normal_font);
            signatureTable.AddCell(signatureCell);
            signatureCell.Phrase = new Phrase("Gudang", normal_font);
            signatureTable.AddCell(signatureCell);
            signatureCell.Phrase = new Phrase("Terima kasih :\nBagian Penjualan", normal_font);
            signatureTable.AddCell(signatureCell);

            signatureTable.AddCell(new PdfPCell()
            {
                Phrase              = new Phrase("--------------------------------", normal_font),
                FixedHeight         = 40,
                VerticalAlignment   = Element.ALIGN_BOTTOM,
                HorizontalAlignment = Element.ALIGN_CENTER
            }); signatureTable.AddCell(new PdfPCell()
            {
                Phrase              = new Phrase("--------------------------------", normal_font),
                FixedHeight         = 40,
                VerticalAlignment   = Element.ALIGN_BOTTOM,
                HorizontalAlignment = Element.ALIGN_CENTER
            }); signatureTable.AddCell(new PdfPCell()
            {
                Phrase              = new Phrase("--------------------------------", normal_font),
                FixedHeight         = 40,
                VerticalAlignment   = Element.ALIGN_BOTTOM,
                HorizontalAlignment = Element.ALIGN_CENTER
            });

            footerTable.AddCell(new PdfPCell(signatureTable));

            cellFooterLeft.Phrase = new Phrase("", normal_font);
            footerTable.AddCell(cellFooterLeft);
            document.Add(footerTable);

            #endregion Footer


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

            return(stream);
        }
コード例 #13
0
        public void DownloadPDFFormat()
        {
            log4net.ILog logger = log4net.LogManager.GetLogger("File");
            try
            {
                Document pdfReport = new Document(PageSize.A4, 100, 91, 100, 93);
                System.IO.MemoryStream msReport = new System.IO.MemoryStream();
                PdfWriter writer = PdfWriter.GetInstance(pdfReport, msReport);
                pdfReport.Open();
                DBConnectionHandler1 db = new DBConnectionHandler1();
                SqlConnection        cn = db.getconnection();
                cn.Open();
                SqlCommand    cmd = new SqlCommand("select * from UploadLogo", cn);
                SqlDataReader dr  = cmd.ExecuteReader();
                if (dr.Read())
                {
                    if (dr.GetString(1).ToString() != "")
                    {
                        iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance(@dr.GetString(1).ToString().Trim());
                        image1.SetAbsolutePosition(70, 100);
                        PdfContentByte by = writer.DirectContent;
                        PdfTemplate    tp = by.CreateTemplate(170, 190);
                        tp.AddImage(image1);
                        by.AddTemplate(tp, 175, 660);
                        cn.Close();
                        dr.Close();
                    }
                }
                string datetime = string.Empty;
                datetime = Convert.ToString(System.DateTime.Now);

                string str = string.Empty;

                //if (ddlAlertType.Text != "")
                //    str = ("   Alert_Type : " + ddlAlertType.Text);
                //if (ddllocation.Text!= "")
                //    str = ("    Location_id : " + ddllocation.Text);


                //if (txtdatefrom.Text != "" && txtdateto.Text != "")
                //    str = ("   Date  From :" + txtdatefrom.Text + "      To :" + txtdateto.Text);



                Phrase headerPhrase = new Phrase("                                       Alert Report                                                       ", FontFactory.GetFont("Garamond", 14));

                headerPhrase.Add("        Generated On : ");
                headerPhrase.Add(datetime);
                //headerPhrase.Add("                                                                           Searching Parameter  : ");
                //headerPhrase.Add(str);


                HeaderFooter header = new HeaderFooter(headerPhrase, false);
                header.Border    = Rectangle.NO_BORDER;
                header.Alignment = Element.ALIGN_CENTER;
                header.Alignment = Element.ALIGN_BOTTOM;
                pdfReport.Header = header;
                pdfReport.Add(headerPhrase);


                // Creates the Table
                PdfPTable ptData = new PdfPTable(gvLoctionTable.Columns.Count - 1);
                ptData.SpacingBefore       = 8;
                ptData.DefaultCell.Padding = 1;

                float[] headerwidths = new float[gvLoctionTable.Columns.Count - 1]; // percentage


                headerwidths[0] = 3.2F;
                headerwidths[1] = 3.2F;
                headerwidths[2] = 3.2F;
                headerwidths[3] = 3.2F;
                //headerwidths[4] = 3.2F;
                //headerwidths[5] = 3.2F;
                //headerwidths[6] = 3.2F;
                //headerwidths[6] = 3.2F;

                ptData.SetWidths(headerwidths);
                ptData.WidthPercentage = 100;
                ptData.DefaultCell.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
                ptData.DefaultCell.VerticalAlignment   = Element.ALIGN_MIDDLE;

                //Insert the Table Headers
                for (int intK = 0; intK < gvLoctionTable.Columns.Count - 1; intK++)
                {
                    PdfPCell cell = new PdfPCell();
                    cell.BorderWidth     = 0.001f;
                    cell.BackgroundColor = new Color(200, 200, 200);
                    cell.BorderColor     = new Color(100, 100, 100);
                    if (gvLoctionTable.Columns[intK + 1].HeaderText.ToString() != "")
                    {
                        cell.Phrase = new Phrase(gvLoctionTable.Columns[intK + 1].HeaderText.ToString(), FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 7, Font.BOLD));
                    }
                    ptData.AddCell(cell);
                }

                ptData.HeaderRows = 1;  // this is the end of the table header

                //Insert the Table Data

                for (int intJ = 0; intJ < gvLoctionTable.Items.Count; intJ++)
                {
                    for (int intK = 0; intK < gvLoctionTable.Columns.Count - 1; intK++)
                    {
                        PdfPCell cell = new PdfPCell();
                        cell.BorderWidth     = 0.001f;
                        cell.BorderColor     = new Color(100, 100, 100);
                        cell.BackgroundColor = new Color(250, 250, 250);
                        if (gvLoctionTable.Items[intJ].Cells[intK + 3].Text.ToString() != "" && gvLoctionTable.Items[intJ].Cells[intK + 3].Text.ToString() != "&nbsp;")
                        {
                            cell.Phrase = new Phrase(gvLoctionTable.Items[intJ].Cells[intK + 3].Text.ToString(), FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 6));
                        }
                        else
                        {
                            cell.Phrase = new Phrase("", FontFactory.GetFont("TIMES_ROMAN", BaseFont.WINANSI, 6));
                        }
                        ptData.AddCell(cell);
                    }
                }

                //Insert the Table

                pdfReport.Add(ptData);

                //Closes the Report and writes to Memory Stream

                pdfReport.Close();

                //Writes the Memory Stream Data to Response Object
                Response.Clear();

                Response.AddHeader("content-disposition", string.Format("attachment;filename=AlertReport.pdf"));
                Response.Charset     = "";
                Response.ContentType = "application/pdf";
                Response.BinaryWrite(msReport.ToArray());
                Response.End();
            }
            catch (Exception ex)
            {
                logger.Info(ex.Message);
            }
        }
コード例 #14
0
        virtual public void SplitTable(PdfPTable table) {
		    foreach (IPdfPTableEvent eventa in events) {
			    if (eventa is IPdfPTableEventSplit)
                    ((IPdfPTableEventSplit)eventa).SplitTable(table);
		    }
        }
コード例 #15
0
        public void pdfstd_half_day(DateTime fromDate, DateTime toDate, string session)
        {
            using (MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString()))
            {
                MemoryStream ms = new MemoryStream();

                HttpContext.Current.Response.ContentType = "application/pdf";
                string name = "Class Student List.pdf";
                HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename=" + name);
                HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);

                //string path = "E:\\HPS" + "\\" + receipt_no.ToString()+"("+receipt_date.ToString("dd-MM-yyyy")+")"+ ".pdf";
                var doc = new Document(PageSize.A4);

                // MemoryStream stream = new MemoryStream();
                doc.SetMargins(0f, 0f, 10f, 70f);
                try
                {
                    string query = @"SELECT 
                                    a.sr_number,
                                    CONCAT(IFNULL(b.std_first_name, ''),
                                            ' ',
                                            IFNULL(b.std_last_name, '')) std_name,
                                    b.std_father_name,
                                    CONCAT('class: ',
                                            e.class_name,
                                            '  Section: ',
                                            f.section_name) class_name,
                                    COALESCE(b.std_contact,
                                            b.std_contact1,
                                            b.std_contact2) std_contact,
                                    a.reason,
                                    a.date_time
                                FROM
                                    std_halfday_log a,
                                    sr_register b,
                                    mst_std_class c,
                                    mst_std_section d,
                                    mst_class e,
                                    mst_section f
                                WHERE
                                    DATE(date_time) BETWEEN @fromDate AND @toDate
                                        AND a.session = c.session
                                        AND c.session = d.session
                                        AND d.session = e.session
                                        AND e.session = f.session
                                        AND f.session = @session
                                        AND a.sr_number = b.sr_number
                                        AND b.sr_number = c.sr_num
                                        AND c.sr_num = d.sr_num
                                        AND c.class_id = e.class_id
                                        AND d.section_id = f.section_id
                                        AND c.class_id = f.class_id";

                    var result = con.Query <std_halfday_log>(query, new { fromDate = fromDate, toDate = toDate, session = session });


                    PdfWriter.GetInstance(doc, HttpContext.Current.Response.OutputStream).PageEvent = new PDFFooter();



                    doc.Open();
                    // string imageURL = "E:\\HPS\\logo.jpg";
                    string imageURL = System.Web.Hosting.HostingEnvironment.MapPath("/images/logo.jpg");
                    Image  jpg      = Image.GetInstance(imageURL);
                    jpg.ScaleAbsolute(50f, 50f);


                    PdfPTable pt = new PdfPTable(6);


                    PdfPCell _cell;
                    Chunk    text;
                    Phrase   ph;

                    _cell                     = new PdfPCell(jpg);
                    _cell.Border              = 0;
                    _cell.Border              = Rectangle.BOTTOM_BORDER;
                    _cell.PaddingBottom       = 5;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    pt.AddCell(_cell);


                    text = new Chunk(SchoolName, FontFactory.GetFont("Areal", 24));
                    ph   = new Phrase();
                    ph.Add(text);
                    ph.Add("\n");


                    text = new Chunk("(" + Affiliation + ")", FontFactory.GetFont("Areal", 12));
                    ph.Add(text);
                    _cell                     = new PdfPCell(ph);
                    _cell.Colspan             = 5;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    _cell.Border              = Rectangle.BOTTOM_BORDER;
                    _cell.PaddingBottom       = 5;
                    //_cell.BackgroundColor = BaseColor.LIGHT_GRAY;
                    pt.AddCell(_cell);

                    doc.Add(pt);

                    int colnumber = 20;

                    pt                 = new PdfPTable(colnumber);
                    pt.HeaderRows      = 3;
                    pt.WidthPercentage = 90f;

                    text          = new Chunk("\n");
                    ph            = new Phrase(text);
                    _cell         = new PdfPCell(ph);
                    _cell.Border  = Rectangle.NO_BORDER;
                    _cell.Colspan = colnumber;
                    pt.AddCell(_cell);


                    text = new Chunk("Half Day Student list From " + fromDate.ToString("dd/MM/yyyy") + " to " + toDate.ToString("dd/MM/yyyy"), FontFactory.GetFont("Areal", 12));
                    ph   = new Phrase(text);
                    ph.Add("\n");
                    ph.Add("\n");
                    text.SetUnderline(0.1f, -2f);
                    _cell                     = new PdfPCell(ph);
                    _cell.Colspan             = colnumber;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    _cell.Border              = Rectangle.NO_BORDER;
                    pt.AddCell(_cell);



                    text  = new Chunk("Serial No.", FontFactory.GetFont("Areal", 8));
                    ph    = new Phrase(text);
                    _cell = new PdfPCell(ph);
                    _cell.BackgroundColor     = BaseColor.LIGHT_GRAY;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    pt.AddCell(_cell);

                    text  = new Chunk("Adm No.", FontFactory.GetFont("Areal", 8));
                    ph    = new Phrase(text);
                    _cell = new PdfPCell(ph);
                    _cell.BackgroundColor     = BaseColor.LIGHT_GRAY;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    pt.AddCell(_cell);

                    text                      = new Chunk("Student Name", FontFactory.GetFont("Areal", 8));
                    ph                        = new Phrase(text);
                    _cell                     = new PdfPCell(ph);
                    _cell.Colspan             = 3;
                    _cell.BackgroundColor     = BaseColor.LIGHT_GRAY;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    pt.AddCell(_cell);

                    text                      = new Chunk("Father's Name", FontFactory.GetFont("Areal", 8));
                    ph                        = new Phrase(text);
                    _cell                     = new PdfPCell(ph);
                    _cell.Colspan             = 3;
                    _cell.BackgroundColor     = BaseColor.LIGHT_GRAY;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    pt.AddCell(_cell);

                    text                      = new Chunk("Class Name", FontFactory.GetFont("Areal", 8));
                    ph                        = new Phrase(text);
                    _cell                     = new PdfPCell(ph);
                    _cell.Colspan             = 3;
                    _cell.BackgroundColor     = BaseColor.LIGHT_GRAY;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    pt.AddCell(_cell);

                    text                      = new Chunk("Contact", FontFactory.GetFont("Areal", 8));
                    ph                        = new Phrase(text);
                    _cell                     = new PdfPCell(ph);
                    _cell.Colspan             = 2;
                    _cell.BackgroundColor     = BaseColor.LIGHT_GRAY;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    pt.AddCell(_cell);

                    text                      = new Chunk("Date & Time", FontFactory.GetFont("Areal", 8));
                    ph                        = new Phrase(text);
                    _cell                     = new PdfPCell(ph);
                    _cell.Colspan             = 2;
                    _cell.BackgroundColor     = BaseColor.LIGHT_GRAY;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    pt.AddCell(_cell);

                    text                      = new Chunk("reason", FontFactory.GetFont("Areal", 8));
                    ph                        = new Phrase(text);
                    _cell                     = new PdfPCell(ph);
                    _cell.Colspan             = 5;
                    _cell.BackgroundColor     = BaseColor.LIGHT_GRAY;
                    _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    pt.AddCell(_cell);

                    int sr_no = 0;

                    int line = 1;;

                    foreach (var list in result)
                    {
                        sr_no++;
                        ph   = new Phrase();
                        text = new Chunk(sr_no.ToString(), FontFactory.GetFont("Areal", 8));
                        ph.Add(text);
                        ph.Add("\n");
                        _cell = new PdfPCell(ph);
                        if (line == 2)
                        {
                            _cell.BackgroundColor = new BaseColor(224, 224, 224);
                        }
                        _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        pt.AddCell(_cell);

                        ph   = new Phrase();
                        text = new Chunk(list.sr_number.ToString(), FontFactory.GetFont("Areal", 8));
                        ph.Add(text);
                        ph.Add("\n");
                        _cell = new PdfPCell(ph);
                        if (line == 2)
                        {
                            _cell.BackgroundColor = new BaseColor(224, 224, 224);
                        }
                        _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        pt.AddCell(_cell);

                        ph   = new Phrase();
                        text = new Chunk(list.std_name, FontFactory.GetFont("Areal", 8));
                        ph.Add(text);
                        ph.Add("\n");
                        _cell         = new PdfPCell(ph);
                        _cell.Colspan = 3;
                        if (line == 2)
                        {
                            _cell.BackgroundColor = new BaseColor(224, 224, 224);
                        }
                        _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        pt.AddCell(_cell);

                        ph   = new Phrase();
                        text = new Chunk(list.std_father_name, FontFactory.GetFont("Areal", 8));
                        ph.Add(text);
                        ph.Add("\n");
                        _cell = new PdfPCell(ph);
                        if (line == 2)
                        {
                            _cell.BackgroundColor = new BaseColor(224, 224, 224);
                        }
                        _cell.Colspan             = 3;
                        _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        pt.AddCell(_cell);

                        ph   = new Phrase();
                        text = new Chunk(list.class_name, FontFactory.GetFont("Areal", 8));
                        ph.Add(text);
                        ph.Add("\n");
                        _cell = new PdfPCell(ph);
                        if (line == 2)
                        {
                            _cell.BackgroundColor = new BaseColor(224, 224, 224);
                        }
                        _cell.Colspan             = 3;
                        _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        pt.AddCell(_cell);

                        ph   = new Phrase();
                        text = new Chunk(list.std_contact, FontFactory.GetFont("Areal", 8));
                        ph.Add(text);
                        ph.Add("\n");
                        _cell         = new PdfPCell(ph);
                        _cell.Colspan = 2;
                        if (line == 2)
                        {
                            _cell.BackgroundColor = new BaseColor(224, 224, 224);
                        }
                        _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        pt.AddCell(_cell);

                        ph   = new Phrase();
                        text = new Chunk(list.date_time.ToString(), FontFactory.GetFont("Areal", 8));
                        ph.Add(text);
                        ph.Add("\n");
                        _cell         = new PdfPCell(ph);
                        _cell.Colspan = 2;
                        if (line == 2)
                        {
                            _cell.BackgroundColor = new BaseColor(224, 224, 224);
                        }
                        _cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        pt.AddCell(_cell);

                        text          = new Chunk(list.reason, FontFactory.GetFont("Areal", 8));
                        ph            = new Phrase(text);
                        _cell         = new PdfPCell(ph);
                        _cell.Colspan = 5;
                        if (line == 2)
                        {
                            _cell.BackgroundColor = new BaseColor(224, 224, 224);
                        }
                        _cell.HorizontalAlignment = Element.ALIGN_LEFT;
                        pt.AddCell(_cell);

                        if (line == 2)
                        {
                            line = 1;
                        }
                        else
                        {
                            line++;
                        }
                    }


                    doc.Add(pt);



                    doc.Close();

                    HttpContext.Current.Response.OutputStream.Write(ms.ToArray(), 0, ms.ToArray().Length);
                    HttpContext.Current.Response.OutputStream.Flush();
                    HttpContext.Current.Response.OutputStream.Close();
                }

                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    doc.Close();
                    ms.Flush();
                }
            }
        }
コード例 #16
0
        private PdfPTable createTable2()
        {
            // Document doc = new Document(PageSize.A4, 50, 50, 80, 50); // 設定PageSize, Margin, left, right, top, bottom
            // MemoryStream ms = new MemoryStream();
            // PdfWriter pw = PdfWriter.GetInstance(doc, ms);

            ////    字型設定
            // 在PDF檔案內容中要顯示中文,最重要的是字型設定,如果沒有正確設定中文字型,會造成中文無法顯示的問題。
            // 首先設定基本字型:kaiu.ttf 是作業系統系統提供的標楷體字型,IDENTITY_H 是指編碼(The Unicode encoding with horizontal writing),及是否要將字型嵌入PDF 檔中。
            // 再來針對基本字型做變化,例如Font Size、粗體斜體以及顏色等。當然你也可以採用其他中文字體字型。
            //BaseFont bfChinese = BaseFont.CreateFont("C:\\Windows\\Fonts\\kaiu.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            PdfPCell cell = null;

            iTextSharp.text.Font ChFont       = new iTextSharp.text.Font(bfChinese, 12);
            iTextSharp.text.Font ChFont_green = new iTextSharp.text.Font(bfChinese, 40, iTextSharp.text.Font.NORMAL, BaseColor.GREEN);
            iTextSharp.text.Font ChFont_msg   = new iTextSharp.text.Font(bfChinese, 12, iTextSharp.text.Font.ITALIC, BaseColor.RED);

            iTextSharp.text.Font chHeaderBoldFont = new iTextSharp.text.Font(bfChinese, 12, iTextSharp.text.Font.BOLD);

            iTextSharp.text.Font chBodyFont = new iTextSharp.text.Font(bfChinese, 10, iTextSharp.text.Font.NORMAL);


            iTextSharp.text.Font engHeaderBoldFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12, iTextSharp.text.Font.BOLD);

            iTextSharp.text.Font engBodyFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8, iTextSharp.text.Font.NORMAL);

            BaseColor hightlightBackground = new BaseColor(203, 226, 237);

            // 產生表格 -- START
            // 建立4個欄位表格之相對寬度
            PdfPTable pt = new PdfPTable(new float[] { 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 });

            // 表格總寬
            pt.TotalWidth  = 500f;
            pt.LockedWidth = true;

            // 設定表頭
            PdfPCell header = new PdfPCell(new Phrase("Deduplication Rate", engHeaderBoldFont));

            header.Colspan             = 13;
            header.HorizontalAlignment = Element.ALIGN_CENTER;// 表頭內文置中
            header.BackgroundColor     = hightlightBackground;
            header.Padding             = 5;
            pt.AddCell(header);

            //header (1,1)
            cell = new PdfPCell(new Phrase(@"Server\Months", engHeaderBoldFont));
            cell.BackgroundColor     = hightlightBackground;
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            cell.VerticalAlignment   = Element.ALIGN_CENTER;
            pt.AddCell(cell);

            //header (1,2~12)
            for (int i = 1; i <= 12; i++)
            {
                cell = new PdfPCell(new Phrase(i.ToString(), engHeaderBoldFont));
                cell.BackgroundColor     = hightlightBackground;
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                cell.VerticalAlignment   = Element.ALIGN_CENTER;
                cell.Padding             = 5;
                pt.AddCell(cell);
            }


            foreach (KeyValuePair <string, double[]> item in tableDataSets)
            {
                //server name
                cell = new PdfPCell(new Phrase(item.Key, engBodyFont));
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                cell.VerticalAlignment   = Element.ALIGN_CENTER;
                cell.Padding             = 5;
                pt.AddCell(cell);

                //1~12 values
                for (int i = 0; i < 12; i++)
                {
                    cell = new PdfPCell(new Phrase(item.Value[i].ToString(), engBodyFont));

                    cell.HorizontalAlignment = Element.ALIGN_CENTER;
                    cell.VerticalAlignment   = Element.ALIGN_CENTER;
                    cell.Padding             = 5;
                    pt.AddCell(cell);
                }
            }



            return(pt);
        }
コード例 #17
0
        private void ExportPartiesPdf_Clicked(object sender, EventArgs e)
        {
            try
            {
                //Export party results to PDF
                BackgroundWorker exportWorker;

                //Get generation date
                DateTime generationDate = DateTime.Now;

                //Show "choose file" dialog
                SaveFileDialog savefile = new SaveFileDialog();
                savefile.FileName = "PartiesResultExport_" + generationDate.ToString("yyyy-MM-dd_HH-mm-ss") + ".pdf";
                savefile.Filter   = "PDF files (*.pdf)|*.pdf";

                if (savefile.ShowDialog() == DialogResult.OK)
                {
                    //File path OK, run exporting background worker
                    exportWorker = new BackgroundWorker();

                    _mainWindow.LoadingContainer.Visibility = Visibility.Visible;
                    _mainWindow.LoadingLabel.Foreground     = ColorHelper.HexToColorBrush("#1c9ad2");
                    _mainWindow.LoadingLabel.Content        = "Exporting data...";

                    exportWorker.DoWork += (s, ea) =>
                    {
                        try
                        {
                            Document document = new Document();

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

                            document.Open();

                            //Register font to get polish special characters
                            FontFactory.Register("C:\\Windows\\Fonts\\ARIALUNI.TTF", "arial unicode ms");

                            Font arialLarge = FontFactory.GetFont("arial unicode ms", BaseFont.CP1250, BaseFont.EMBEDDED,
                                                                  28,
                                                                  Font.NORMAL, BaseColor.BLACK);
                            Font arialSmall = FontFactory.GetFont("arial unicode ms", BaseFont.CP1250, BaseFont.EMBEDDED,
                                                                  13,
                                                                  Font.NORMAL, BaseColor.BLACK);
                            Font arialSmallWhite = FontFactory.GetFont("arial unicode ms", BaseFont.CP1250,
                                                                       BaseFont.EMBEDDED, 13, Font.NORMAL, BaseColor.WHITE);

                            Font tableHeader = FontFactory.GetFont("arial unicode ms", BaseFont.CP1250,
                                                                   BaseFont.EMBEDDED,
                                                                   13, Font.BOLD, BaseColor.WHITE);
                            Font cellTextBlue = FontFactory.GetFont("arial unicode ms", BaseFont.CP1250,
                                                                    BaseFont.EMBEDDED,
                                                                    13, Font.BOLD, new BaseColor(28, 154, 210));


                            document.Add(new Paragraph("Parties result list", arialLarge));
                            document.Add(new Paragraph("Generated " + generationDate.ToString("dd.MM.yyyy HH:mm:ss"),
                                                       arialSmall));

                            PdfPTable table = new PdfPTable(3);
                            table.SpacingBefore = 20;

                            PdfPCell cell = new PdfPCell(new Phrase("Party", tableHeader));
                            cell.BackgroundColor = new BaseColor(28, 154, 210);
                            cell.BorderWidth     = 0;
                            cell.PaddingBottom   = 6;
                            cell.PaddingLeft     = 20;

                            table.AddCell(cell);
                            cell.Phrase = new Phrase("Votes", tableHeader);
                            table.AddCell(cell);
                            cell.Phrase = new Phrase("%", tableHeader);
                            table.AddCell(cell);


                            PdfPCell partyCell = new PdfPCell(new Phrase("", arialSmall));
                            partyCell.BackgroundColor = new BaseColor(249, 249, 249);
                            partyCell.BorderWidth     = 0;
                            partyCell.PaddingBottom   = 6;
                            partyCell.PaddingLeft     = 20;

                            PdfPCell valueCell = new PdfPCell(new Phrase("", arialSmall));
                            valueCell.BackgroundColor = new BaseColor(249, 249, 249);
                            valueCell.BorderWidth     = 0;
                            valueCell.PaddingBottom   = 6;
                            valueCell.PaddingLeft     = 20;

                            int rowCounter = 0;

                            //Export parties data and votes
                            foreach (var party in _displayedParties)
                            {
                                if (_displayedParties.Last() == party)
                                {
                                    partyCell.BackgroundColor = new BaseColor(28, 154, 210);
                                    valueCell.BackgroundColor = new BaseColor(28, 154, 210);

                                    partyCell.Phrase = new Phrase(party.Name, tableHeader);
                                    table.AddCell(partyCell);

                                    valueCell.Phrase = new Phrase(party.Votes.ToString(), arialSmallWhite);
                                    table.AddCell(valueCell);
                                    valueCell.Phrase = new Phrase(party.Percentage.ToString(), arialSmallWhite);
                                    table.AddCell(valueCell);
                                }
                                else
                                {
                                    if (rowCounter % 2 == 0)
                                    {
                                        partyCell.BackgroundColor = new BaseColor(249, 249, 249);
                                        valueCell.BackgroundColor = new BaseColor(249, 249, 249);
                                    }
                                    else
                                    {
                                        partyCell.BackgroundColor = new BaseColor(239, 239, 239);
                                        valueCell.BackgroundColor = new BaseColor(239, 239, 239);
                                    }

                                    partyCell.Phrase = new Phrase(party.Name, cellTextBlue);
                                    table.AddCell(partyCell);

                                    valueCell.Phrase = new Phrase(party.Votes.ToString(), arialSmall);
                                    table.AddCell(valueCell);
                                    valueCell.Phrase = new Phrase(party.Percentage.ToString(), arialSmall);
                                    table.AddCell(valueCell);

                                    rowCounter++;
                                }
                            }

                            partyCell.BackgroundColor = new BaseColor(24, 133, 180);
                            valueCell.BackgroundColor = new BaseColor(24, 133, 180);

                            //Export totals
                            partyCell.Phrase = new Phrase("Total votes (w/o spoiled votes)", tableHeader);
                            table.AddCell(partyCell);

                            valueCell.Phrase = new Phrase(_totalVotes.ToString(), arialSmallWhite);
                            table.AddCell(valueCell);
                            valueCell.Phrase = new Phrase("", arialSmallWhite);
                            table.AddCell(valueCell);

                            partyCell.BackgroundColor = new BaseColor(28, 154, 210);
                            valueCell.BackgroundColor = new BaseColor(28, 154, 210);

                            partyCell.Phrase = new Phrase("Total votes (w/ spoiled votes)", tableHeader);
                            table.AddCell(partyCell);

                            valueCell.Phrase = new Phrase((_totalVotes + _spoiledVotes).ToString(), arialSmallWhite);
                            table.AddCell(valueCell);
                            valueCell.Phrase = new Phrase("", arialSmallWhite);
                            table.AddCell(valueCell);

                            partyCell.BackgroundColor = new BaseColor(24, 133, 180);
                            valueCell.BackgroundColor = new BaseColor(24, 133, 180);

                            partyCell.Phrase = new Phrase("Disallowed tries", tableHeader);
                            table.AddCell(partyCell);

                            valueCell.Phrase = new Phrase(_disallowedTries.ToString(), arialSmallWhite);
                            table.AddCell(valueCell);
                            valueCell.Phrase = new Phrase("", arialSmallWhite);
                            table.AddCell(valueCell);

                            document.Add(table);

                            document.Close();
                        }
                        catch (Exception)
                        {
                            MessageBox.Show(
                                "An error occurred while exporting data, please contact person responsible for managing the system",
                                "Error occured", MessageBoxButton.OK);
                            _mainWindow.Logout();
                        }
                    };

                    exportWorker.RunWorkerCompleted += (s, ea) =>
                    {
                        _mainWindow.LoadingContainer.Visibility = Visibility.Collapsed;
                    };

                    exportWorker.RunWorkerAsync();
                }
            }
            catch (Exception)
            {
                MessageBox.Show(
                    "An error occurred while exporting data, please contact person responsible for managing the system",
                    "Error occured", MessageBoxButton.OK);
                _mainWindow.Logout();
            }
        }
コード例 #18
0
ファイル: QCLogic.cs プロジェクト: JTankariya/MehulElectro
        public static string PrintQCSlip(List <BillOfMaterialLabParameters> labParam, string folderPath, int ID, string CreatedBy)
        {
            var batchDetail = BatchLogic.GetBatchByID(ID);

            bool exists = Directory.Exists(folderPath);

            if (!exists)
            {
                Directory.CreateDirectory(folderPath);
            }

            DirectoryInfo info = new DirectoryInfo(folderPath);

            FileInfo[] files = info.GetFiles().Where(p => p.CreationTime <= DateTime.Now.AddDays(-1)).ToArray();
            foreach (var file in files)
            {
                file.Delete();
            }
            var document    = new iTextSharp.text.Document(PageSize.A4, 30f, 30f, 0f, 40f);
            var pdffilename = "LabApprovalSlip" + DateTime.Now.ToString("h:mm:ss").Replace(":", "");
            var writer      = PdfWriter.GetInstance(document, new FileStream(folderPath + "/" + pdffilename + ".PDF", FileMode.Create));

            writer.PageEvent = new QCPDFFooter(CreatedBy);
            document.Open();

            var widths = new float[] { 30f, 30f };

            var table = new PdfPTable(2);

            table.HeaderRows          = 6;
            table.HorizontalAlignment = 0;
            table.TotalWidth          = document.PageSize.Width - document.LeftMargin - document.RightMargin;
            table.LockedWidth         = true;
            table.SetWidths(widths);
            table.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;

            var cell = new PdfPCell(new Phrase("MEHUL ELECTRO INSULATING INDUSTRIES", CommonFunction.fontTitle17));

            cell.HorizontalAlignment = iTextSharp.text.Rectangle.ALIGN_CENTER;
            cell.Border  = iTextSharp.text.Rectangle.NO_BORDER;
            cell.Colspan = table.NumberOfColumns;
            table.AddCell(cell);


            cell = new PdfPCell(new Phrase("2610/A, Ph-4, G.I.D.C., Vatva, Ahmedabad 382 445", CommonFunction.font10));
            cell.HorizontalAlignment = iTextSharp.text.Rectangle.ALIGN_CENTER;
            cell.Border  = iTextSharp.text.Rectangle.NO_BORDER;
            cell.Colspan = table.NumberOfColumns;
            table.AddCell(cell);

            cell = new PdfPCell(new Phrase("Phone : 2584 2331/2, Fax: 2584 0356", CommonFunction.font10));
            cell.HorizontalAlignment = iTextSharp.text.Rectangle.ALIGN_CENTER;
            cell.Border  = iTextSharp.text.Rectangle.NO_BORDER;
            cell.Colspan = table.NumberOfColumns;
            table.AddCell(cell);

            cell = new PdfPCell(new Phrase("Email : [email protected], [email protected]", CommonFunction.font10));
            cell.HorizontalAlignment = iTextSharp.text.Rectangle.ALIGN_CENTER;
            cell.Border  = iTextSharp.text.Rectangle.NO_BORDER;
            cell.Colspan = table.NumberOfColumns;
            table.AddCell(cell);

            cell = new PdfPCell(new Phrase("Lab Approval Slip", CommonFunction.fontTitle13));
            cell.HorizontalAlignment = iTextSharp.text.Rectangle.ALIGN_CENTER;
            cell.Border  = iTextSharp.text.Rectangle.NO_BORDER;
            cell.Colspan = table.NumberOfColumns;
            table.AddCell(cell);

            cell = new PdfPCell(new Phrase(" ", CommonFunction.font10));
            cell.HorizontalAlignment = iTextSharp.text.Rectangle.ALIGN_CENTER;
            cell.Border  = iTextSharp.text.Rectangle.MARKED;
            cell.Colspan = table.NumberOfColumns;
            table.AddCell(cell);

            if (batchDetail != null)
            {
                cell        = new PdfPCell(new Phrase("L.T.R. No : " + batchDetail.BatchNo, CommonFunction.fontTitle13));
                cell.Border = iTextSharp.text.Rectangle.BOX;
                cell.HorizontalAlignment = Rectangle.ALIGN_RIGHT;
                cell.Colspan             = 2;
                table.AddCell(cell);
                cell        = new PdfPCell(new Phrase("Product : " + batchDetail.ProductName, CommonFunction.fontTitle13));
                cell.Border = iTextSharp.text.Rectangle.BOX;
                table.AddCell(cell);
                cell        = new PdfPCell(new Phrase("Code : " + batchDetail.PrintName, CommonFunction.fontTitle13));
                cell.Border = iTextSharp.text.Rectangle.BOX;
                table.AddCell(cell);
                cell        = new PdfPCell(new Phrase("Shade : " + batchDetail.ShadeName, CommonFunction.fontTitle13));
                cell.Border = iTextSharp.text.Rectangle.BOX;
                table.AddCell(cell);
                cell        = new PdfPCell(new Phrase("Batch No : " + batchDetail.BatchNo, CommonFunction.fontTitle13));
                cell.Border = iTextSharp.text.Rectangle.BOX;
                table.AddCell(cell);
                cell         = new PdfPCell(new Phrase("Party : ", CommonFunction.fontTitle13));
                cell.Border  = iTextSharp.text.Rectangle.BOX;
                cell.Colspan = 2;
                table.AddCell(cell);
                cell        = new PdfPCell(new Phrase(" ", CommonFunction.fontTitle13));
                cell.Border = iTextSharp.text.Rectangle.BOX;
                table.AddCell(cell);
                cell        = new PdfPCell(new Phrase("Batch Qty : " + batchDetail.ProductionQty + " " + batchDetail.BatchUnit, CommonFunction.fontTitle13));
                cell.Border = iTextSharp.text.Rectangle.BOX;
                table.AddCell(cell);
                cell        = new PdfPCell(new Phrase(" ", CommonFunction.fontTitle13));
                cell.Border = iTextSharp.text.Rectangle.BOX;
                table.AddCell(cell);
                cell        = new PdfPCell(new Phrase("Mfg. Date : " + DateTime.Now, CommonFunction.fontTitle13));
                cell.Border = iTextSharp.text.Rectangle.BOX;
                table.AddCell(cell);
            }

            cell         = new PdfPCell(new Phrase(" ", CommonFunction.font10));
            cell.Border  = iTextSharp.text.Rectangle.NO_BORDER;
            cell.Colspan = table.NumberOfColumns;
            table.AddCell(cell);
            cell         = new PdfPCell(new Phrase(" ", CommonFunction.font10));
            cell.Border  = iTextSharp.text.Rectangle.NO_BORDER;
            cell.Colspan = table.NumberOfColumns;
            table.AddCell(cell);
            document.Add(table);
            var i           = 0;
            var batchParams = BillOfMaterialLabParametersLogic.GetLabParameterByProductAndShadeID(batchDetail.ProductID, batchDetail.ShadeID);
            var paramTable  = new PdfPTable(4);

            if (batchParams != null)
            {
                paramTable.HorizontalAlignment = iTextSharp.text.Rectangle.ALIGN_LEFT;
                paramTable.TotalWidth          = (document.PageSize.Width - document.LeftMargin - document.RightMargin);
                paramTable.LockedWidth         = true;
                paramTable.SetWidths(new float[] { 5f, 55f, 20f, 20f });
                cell        = new PdfPCell(new Phrase("No.", CommonFunction.font10));
                cell.Border = iTextSharp.text.Rectangle.BOX;
                paramTable.AddCell(cell);
                cell        = new PdfPCell(new Phrase("Perticular", CommonFunction.font10));
                cell.Border = iTextSharp.text.Rectangle.BOX;
                paramTable.AddCell(cell);
                cell        = new PdfPCell(new Phrase("Standard", CommonFunction.font10));
                cell.Border = iTextSharp.text.Rectangle.BOX;
                paramTable.AddCell(cell);
                cell        = new PdfPCell(new Phrase("Observed", CommonFunction.font10));
                cell.Border = iTextSharp.text.Rectangle.BOX;
                paramTable.AddCell(cell);
                foreach (var param in batchParams)
                {
                    i++;
                    var innercell = new PdfPCell(new Phrase(" ", CommonFunction.font8));
                    innercell = new PdfPCell(new Phrase(i.ToString(), CommonFunction.font10Normal));
                    innercell.PaddingBottom = 4;
                    innercell.Border        = iTextSharp.text.Rectangle.BOX;
                    paramTable.AddCell(innercell);

                    innercell        = new PdfPCell(new Phrase(param.LabParameterName, CommonFunction.font10Normal));
                    innercell.Border = iTextSharp.text.Rectangle.BOX;
                    paramTable.AddCell(innercell);

                    innercell = new PdfPCell(new Phrase(!string.IsNullOrEmpty(param.Standard) ? param.Standard : param.Min + " - " + param.Max + " " + param.Unit, CommonFunction.font10Normal));
                    innercell.HorizontalAlignment = iTextSharp.text.Rectangle.ALIGN_RIGHT;
                    innercell.Border = iTextSharp.text.Rectangle.BOX;
                    paramTable.AddCell(innercell);

                    var observed = labParam.FirstOrDefault(x => x.ParameterID == param.ParameterID);
                    innercell = new PdfPCell(new Phrase(observed.Standard + " " + param.Unit, CommonFunction.font10Normal));
                    innercell.HorizontalAlignment = iTextSharp.text.Rectangle.ALIGN_RIGHT;
                    innercell.Border = iTextSharp.text.Rectangle.BOX;
                    paramTable.AddCell(innercell);
                }
            }

            document.Add(paramTable);

            document.Close();
            return(pdffilename + ".PDF");
        }
コード例 #19
0
        protected void btninvproducto_Click(object sender, EventArgs e)
        {
            string   idproducto  = txtproducto.Text;
            string   niterp      = this.Session["niterp"].ToString();
            Document invproducto = new Document(PageSize.LETTER);
            // Indicamos donde vamos a guardar el documento
            PdfWriter writer = PdfWriter.GetInstance(invproducto,
                                                     new FileStream(@"C:\Users\Bark__000\Desktop\100% Barça\FIUSAC\IPC2\Proyecto\Proyecto201612151\Proyecto201612151\Reportes\ReporteProducto201612151.pdf", FileMode.Create));

            invproducto.AddTitle("Reporte de Producto");
            invproducto.AddCreator("201612151");
            invproducto.Open();

            Paragraph title = new Paragraph();

            title.Font = FontFactory.GetFont(FontFactory.TIMES, 18f, BaseColor.BLUE);
            title.Add("Reporte de Producto");
            invproducto.Add(title);

            //Mostrar los datos del producto
            Chunk c1 = new Chunk("Reporte mostrado por medio de tablas. A continuación una descripción del producto.");

            invproducto.Add(c1);
            PdfPTable tblproductos = new PdfPTable(8);

            tblproductos.WidthPercentage = 100;
            PdfPCell cell = new PdfPCell(new Phrase("Descripción de producto"));

            cell.Colspan             = 8;
            cell.HorizontalAlignment = 1;
            tblproductos.AddCell(cell);
            tblproductos.AddCell("Codigo");
            tblproductos.AddCell("Barras");
            tblproductos.AddCell("Nombre");
            tblproductos.AddCell("Desc.");
            tblproductos.AddCell("Des. Pres.");
            tblproductos.AddCell("Pres.");
            tblproductos.AddCell("Des. Clas.");
            tblproductos.AddCell("Clas.");
            Conexion      con      = new Conexion();
            string        sql      = "select * from Productos_registro where id_erp='" + niterp + "' and codigo='" + idproducto + "'";
            SqlCommand    cmd      = new SqlCommand(sql, con.getConexion());
            SqlDataReader registro = cmd.ExecuteReader();

            if (registro.Read())
            {
                tblproductos.AddCell(registro.GetString(0));
                tblproductos.AddCell(registro.GetString(1));
                tblproductos.AddCell(registro.GetString(2));
                tblproductos.AddCell(registro.GetString(3));
                tblproductos.AddCell(registro.GetString(4));
                tblproductos.AddCell(registro.GetString(5));
                tblproductos.AddCell(registro.GetString(6));
                tblproductos.AddCell(registro.GetString(7));
            }
            invproducto.Add(tblproductos);

            //Agreagar Lotesysaldos del producto
            Chunk c2 = new Chunk("Lotes o Saldos registrados para el producto. En el caso de los lotes -U corresponden a UEPS y -P a PEPS");

            invproducto.Add(c2);
            PdfPTable tbllote = new PdfPTable(5);

            tbllote.WidthPercentage = 100;
            PdfPCell cabeza1 = new PdfPCell(new Phrase("Lotes o Saldos"));

            cabeza1.Colspan             = 5;
            cabeza1.HorizontalAlignment = 1;
            tbllote.AddCell(cabeza1);
            tbllote.AddCell("Id Tipo");
            tbllote.AddCell("Cantidad");
            tbllote.AddCell("Costo Promedio");
            tbllote.AddCell("Tipo");
            tbllote.AddCell("Fecha");
            sql = "select idtipo,cantidad,costopromedio,tipo,fecha from LotesySaldos where idproducto='" + idproducto + "'";
            SqlCommand    cmdlote       = new SqlCommand(sql, con.getConexion());
            SqlDataReader registroslote = cmdlote.ExecuteReader();
            List <string> lotes         = new List <string>();

            while (registroslote.Read())
            {
                lotes.Add(Convert.ToString(registroslote.GetInt32(0)));
                tbllote.AddCell(Convert.ToString(registroslote.GetInt32(0)));
                tbllote.AddCell(Convert.ToString(registroslote.GetInt32(1)));
                tbllote.AddCell(Convert.ToString(registroslote.GetDecimal(2)));
                tbllote.AddCell(registroslote.GetString(3));
                tbllote.AddCell(Convert.ToString(registroslote.GetDateTime(4)));
            }
            invproducto.Add(tbllote);

            //Agregar ubicaciones del producto
            Chunk c3 = new Chunk("Ubicaciones de los productos");

            invproducto.Add(c3);
            PdfPTable tblubicacion = new PdfPTable(4);

            tblubicacion.WidthPercentage = 100;
            PdfPCell cabeza2 = new PdfPCell(new Phrase("Ubicaciones de los productos"));

            cabeza2.Colspan             = 4;
            cabeza2.HorizontalAlignment = 1;
            tblubicacion.AddCell(cabeza2);
            tblubicacion.AddCell("Id Ubicacion");
            tblubicacion.AddCell("Id Tipo");
            tblubicacion.AddCell("# Bodega");
            tblubicacion.AddCell("# Nivel");
            for (int i = 0; i < lotes.Count(); i++)
            {
                sql = "select * from Ubicar where idtipo=" + lotes[i];
                SqlCommand    cmdubi = new SqlCommand(sql, con.getConexion());
                SqlDataReader regubi = cmdubi.ExecuteReader();
                if (regubi.Read())
                {
                    tblubicacion.AddCell(Convert.ToString(regubi.GetInt32(0)));
                    tblubicacion.AddCell(Convert.ToString(regubi.GetInt32(1)));
                    tblubicacion.AddCell(regubi.GetString(2));
                    tblubicacion.AddCell(Convert.ToString(regubi.GetInt32(3)));
                }
            }

            invproducto.Add(tblubicacion);

            invproducto.Close();
            writer.Close();
            Response.Write("<script>alert('Documento creado con éxito, dirijase a la carpeta Reportes para verlo')</script>");
        }
コード例 #20
0
            public override void OnEndPage(PdfWriter writer, Document document)
            {
                /***** INICIO PIE DE PAGINA ******/
                int         page_count = 0;
                PdfTemplate total;
                BaseFont    helv;
                bool        settingFont = false;
                DateTime    fecha       = DateTime.Now;
                DateTime    hora        = DateTime.Now;

                total = writer.DirectContent.CreateTemplate(100, 100);

                total.BoundingBox = new Rectangle(-20, -20, 100, 100);

                helv = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);

                PdfContentByte cb = writer.DirectContent;

                cb.SaveState();

                string text     = "                                                                                                                                                                                                                                                                        Pág. " + writer.PageNumber + " de";
                string text2    = "Generado el " + fecha.ToString("dd/MM/yyyy") + ", a las: " + hora.ToString("hh:mm:ss") + ".";
                float  textBase = document.Bottom - 20;
                float  textSize = 750; //helv.GetWidthPoint(text, 12);

                cb.BeginText();
                cb.SetFontAndSize(helv, 8);

                cb.SetTextMatrix(document.Left, textBase);
                cb.ShowText(text2);
                cb.ShowText(text);

                cb.EndText();
                cb.AddTemplate(template, document.Left + textSize, textBase);
                cb.RestoreState();

                /************* FIN DE PIE DE PAGINAA **************/

                /************* INICIO CABECERA **************/
                BaseFont bftime = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
                Font     time   = new Font(bftime, 10, Font.BOLD, Color.BLACK);
                ////Phrase p1Header = new Phrase(String.Format("BlueLemonCode generated page{0}", "\n", FontFactory.GetFont("arial", 18)));
                Phrase p1Header = new Phrase(String.Format("Nº OT"), time);            //FontFactory.GetFont("arial", 10));
                Phrase p2Header = new Phrase(String.Format("Nº Guía"), time);          //FontFactory.GetFont("arial", 10));
                Phrase p3Header = new Phrase(String.Format("Nombre OT"), time);        //FontFactory.GetFont("arial", 10));
                Phrase p4Header = new Phrase(String.Format("Sucursal"), time);         //FontFactory.GetFont("arial", 10));
                Phrase p5Header = new Phrase(String.Format("Fecha Despacho"), time);   //FontFactory.GetFont("arial", 10));
                Phrase p6Header = new Phrase(String.Format("Tiraje Total"), time);     //FontFactory.GetFont("arial", 10));
                Phrase p7Header = new Phrase(String.Format("Total Despachado"), time); //FontFactory.GetFont("arial", 10));
                Phrase p8Header = new Phrase(String.Format(""), FontFactory.GetFont("arial", 10));

                iTextSharp.text.Image logoHeader = iTextSharp.text.Image.GetInstance(GetApplicationPhysicalPath() + @"\Content\images\qgLogoPDF.JPG");
                //espacio
                time = new Font(bftime, 12, Font.BOLD, Color.BLACK);
                Phrase subtitle = new Phrase(info, time);

                //Create PdfTable object
                PdfPTable pdfTab = new PdfPTable(1);
                PdfPTable pdfTa  = new PdfPTable(8);
                PdfPTable pdfT   = new PdfPTable(1);

                //Color

                pdfT.WidthPercentage = 100;
                int[] a = new int[] { 30 };
                pdfT.SetWidths(a);
                PdfPCell pdfCe1 = new PdfPCell(subtitle);

                pdfCe1.HorizontalAlignment = Element.ALIGN_CENTER;
                pdfCe1.Border = 0;
                pdfT.AddCell(pdfCe1);
                pdfTa.WidthPercentage = 100;
                int[] w = new int[] { 12, 13, 35, 60, 25, 15, 20, 2 };
                pdfTa.SetWidths(w);
                PdfPCell pdfCell1 = new PdfPCell(logoHeader);
                PdfPCell pdfCell  = new PdfPCell(p1Header);
                PdfPCell pdfCell2 = new PdfPCell(p2Header);
                PdfPCell pdfCell3 = new PdfPCell(p3Header);
                PdfPCell pdfCell4 = new PdfPCell(p4Header);
                PdfPCell pdfCell5 = new PdfPCell(p5Header);
                PdfPCell pdfCell6 = new PdfPCell(p6Header);
                PdfPCell pdfCell7 = new PdfPCell(p7Header);

                PdfPCell pdfCell8 = new PdfPCell(p8Header);

                pdfCell.BackgroundColor  = new Color(165, 165, 165);
                pdfCell2.BackgroundColor = new Color(165, 165, 165);
                pdfCell3.BackgroundColor = new Color(165, 165, 165);
                pdfCell4.BackgroundColor = new Color(165, 165, 165);
                pdfCell5.BackgroundColor = new Color(165, 165, 165);
                pdfCell6.BackgroundColor = new Color(165, 165, 165);
                pdfCell7.BackgroundColor = new Color(165, 165, 165);
                //set the alignment of all three cells and set border to 0
                pdfCell1.HorizontalAlignment = Element.ALIGN_LEFT;
                pdfCell.HorizontalAlignment  = Element.ALIGN_LEFT;

                //ubicacion orden titulos
                pdfCell.HorizontalAlignment  = Element.ALIGN_CENTER;
                pdfCell2.HorizontalAlignment = Element.ALIGN_CENTER;
                pdfCell3.HorizontalAlignment = Element.ALIGN_CENTER;
                pdfCell4.HorizontalAlignment = Element.ALIGN_CENTER;
                pdfCell5.HorizontalAlignment = Element.ALIGN_CENTER;
                pdfCell6.HorizontalAlignment = Element.ALIGN_CENTER;
                pdfCell7.HorizontalAlignment = Element.ALIGN_CENTER;



                //
                pdfCell1.Border = 0;
                pdfCell8.Border = 0;
                //add all three cells into PdfTable

                pdfTab.AddCell(pdfCell1);
                pdfTa.AddCell(pdfCell);
                pdfTa.AddCell(pdfCell2);
                pdfTa.AddCell(pdfCell3);
                pdfTa.AddCell(pdfCell4);
                pdfTa.AddCell(pdfCell5);

                pdfTa.AddCell(pdfCell6);
                pdfTa.AddCell(pdfCell7);

                pdfTa.AddCell(pdfCell8);
                pdfTab.TotalWidth = document.PageSize.Width - 50;
                pdfTa.TotalWidth  = document.PageSize.Width - 50;
                pdfT.TotalWidth   = document.PageSize.Width - 50;
                //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable
                //first param is start row. -1 indicates there is no end row and all the rows to be included to write
                //Third and fourth param is x and y position to start writing
                pdfTab.WriteSelectedRows(0, -1, 10, document.PageSize.Height - 10, writer.DirectContent);
                pdfTa.WriteSelectedRows(0, -1, 30, document.PageSize.Height - 70, writer.DirectContent);
                pdfT.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 20, writer.DirectContent);//68
                //set pdfContent value
                pdfContent = writer.DirectContent;
                //Move the pointer and draw line to separate header section from rest of page
                pdfContent.MoveTo(10, document.PageSize.Height - 120);//135
                //pdfContent.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 35);
                pdfContent.Stroke();
                /************* FIN CABECERA **************/
            }
コード例 #21
0
        protected void btninvbodega_Click(object sender, EventArgs e)
        {
            string   idbodega  = txtbodega.Text;
            string   niterp    = this.Session["niterp"].ToString();
            Document invbodega = new Document(PageSize.LETTER);
            // Indicamos donde vamos a guardar el documento
            PdfWriter writer = PdfWriter.GetInstance(invbodega,
                                                     new FileStream(@"C:\Users\Bark__000\Desktop\100% Barça\FIUSAC\IPC2\Proyecto\Proyecto201612151\Proyecto201612151\Reportes\ReporteBodega201612151.pdf", FileMode.Create));

            invbodega.AddTitle("Reporte de Bodegas");
            invbodega.AddCreator("201612151");
            invbodega.Open();
            Paragraph title = new Paragraph();

            title.Font = FontFactory.GetFont(FontFactory.TIMES, 18f, BaseColor.BLUE);
            title.Add("Reporte de Bodega");
            invbodega.Add(title);
            Conexion con = new Conexion();

            //Datos de la bodega
            Chunk c = new Chunk("Descripción basica de la bodega ingresada.");

            invbodega.Add(c);
            PdfPTable tblbodega = new PdfPTable(4);

            tblbodega.WidthPercentage = 100;
            PdfPCell cabeza = new PdfPCell(new Phrase("Bodega"));

            cabeza.Colspan = 4;
            tblbodega.HorizontalAlignment = 1;
            tblbodega.AddCell(cabeza);
            tblbodega.AddCell("Id Bodega");
            tblbodega.AddCell("Nombre");
            tblbodega.AddCell("Descripción");
            tblbodega.AddCell("Dirección");
            string        sql             = "select * from Bodegas where idbodega='" + idbodega + "'";
            SqlCommand    cmdlote         = new SqlCommand(sql, con.getConexion());
            SqlDataReader registrosbodega = cmdlote.ExecuteReader();

            while (registrosbodega.Read())
            {
                tblbodega.AddCell(registrosbodega.GetString(0));
                tblbodega.AddCell(registrosbodega.GetString(1));
                tblbodega.AddCell(registrosbodega.GetString(2));
                tblbodega.AddCell(registrosbodega.GetString(3));
            }
            invbodega.Add(tblbodega);
            //Ubicación productos
            Chunk c1 = new Chunk("Descripción de los diferentes lotes ubicados en esta bodega: " + idbodega);

            invbodega.Add(c1);
            PdfPTable tblubica = new PdfPTable(4);

            tblubica.WidthPercentage = 100;
            PdfPCell cabeza1 = new PdfPCell(new Phrase("Ubicaciones registradas en esta bodega"));

            cabeza1.Colspan = 4;
            tblubica.HorizontalAlignment = 1;
            tblubica.AddCell(cabeza1);
            tblubica.AddCell("Id Ubicacion");
            tblubica.AddCell("Id Tipo Saldo/Lote");
            tblubica.AddCell("Id Bodega");
            tblubica.AddCell("Id Nivel");
            List <string> listalotes = new List <string>();

            sql = "select * from Ubicar where idbodega='" + idbodega + "'";
            SqlCommand    cmdubica = new SqlCommand(sql, con.getConexion());
            SqlDataReader regubica = cmdubica.ExecuteReader();

            while (regubica.Read())
            {
                listalotes.Add(Convert.ToString(regubica.GetInt32(1)));
                tblubica.AddCell(Convert.ToString(regubica.GetInt32(0)));
                tblubica.AddCell(Convert.ToString(regubica.GetInt32(1)));
                tblubica.AddCell(regubica.GetString(2));
                tblubica.AddCell(Convert.ToString(regubica.GetInt32(3)));
            }
            invbodega.Add(tblubica);

            //Lotes y saldos en esa bodega (costo promedio)
            Chunk c3 = new Chunk("Lotes y saldos ubicados en la bodega ingresada");

            invbodega.Add(c3);
            PdfPTable tblubicacion = new PdfPTable(6);

            tblubicacion.WidthPercentage = 100;
            PdfPCell cabeza2 = new PdfPCell(new Phrase("Ubicaciones de los productos"));

            cabeza2.Colspan             = 6;
            cabeza2.HorizontalAlignment = 1;
            tblubicacion.AddCell(cabeza2);
            tblubicacion.AddCell("Id Tipo");
            tblubicacion.AddCell("Producto");
            tblubicacion.AddCell("Cantidad");
            tblubicacion.AddCell("Costo promedio");
            tblubicacion.AddCell("Tipo");
            tblubicacion.AddCell("Fecha");
            List <string> productos = new List <string>();

            for (int i = 0; i < listalotes.Count(); i++)
            {
                sql = "select * from LotesySaldos where idtipo=" + listalotes[i];
                SqlCommand    cmdubi = new SqlCommand(sql, con.getConexion());
                SqlDataReader regubi = cmdubi.ExecuteReader();
                if (regubi.Read())
                {
                    productos.Add(regubi.GetString(1));
                    tblubicacion.AddCell(Convert.ToString(regubi.GetInt32(0)));
                    tblubicacion.AddCell(regubi.GetString(1));
                    tblubicacion.AddCell(Convert.ToString(regubi.GetInt32(2)));
                    tblubicacion.AddCell(Convert.ToString(regubi.GetDecimal(3)));
                    tblubicacion.AddCell(regubi.GetString(4));
                    tblubicacion.AddCell(Convert.ToString(regubi.GetDateTime(5)));
                }
            }
            invbodega.Add(tblubicacion);

            Chunk c4 = new Chunk("Productos guardados en esta bodega");

            invbodega.Add(c4);
            PdfPTable tblproductos = new PdfPTable(8);

            tblproductos.WidthPercentage = 100;
            PdfPCell cell = new PdfPCell(new Phrase("Descripción de producto"));

            cell.Colspan             = 8;
            cell.HorizontalAlignment = 1;
            tblproductos.AddCell(cell);
            tblproductos.AddCell("Codigo");
            tblproductos.AddCell("Barras");
            tblproductos.AddCell("Nombre");
            tblproductos.AddCell("Desc.");
            tblproductos.AddCell("Des. Pres.");
            tblproductos.AddCell("Pres.");
            tblproductos.AddCell("Des. Clas.");
            tblproductos.AddCell("Clas.");
            for (int i = 0; i < productos.Count(); i++)
            {
                sql = "select * from Productos_registro where id_erp='" + niterp + "' and codigo='" + productos[i] + "'";
                SqlCommand    cmdubi = new SqlCommand(sql, con.getConexion());
                SqlDataReader regubi = cmdubi.ExecuteReader();
                while (regubi.Read())
                {
                    tblproductos.AddCell(regubi.GetString(0));
                    tblproductos.AddCell(regubi.GetString(1));
                    tblproductos.AddCell(regubi.GetString(2));
                    tblproductos.AddCell(regubi.GetString(3));
                    tblproductos.AddCell(regubi.GetString(4));
                    tblproductos.AddCell(regubi.GetString(5));
                    tblproductos.AddCell(regubi.GetString(6));
                    tblproductos.AddCell(regubi.GetString(7));
                }
            }
            invbodega.Add(tblproductos);


            invbodega.Close();
            writer.Close();
            Response.Write("<script>alert('Documento creado con éxito, dirijase a la carpeta Reportes para verlo')</script>");
        }
コード例 #22
0
ファイル: Program.cs プロジェクト: ygpark/helloworld
        static void Main(string[] args)
        {
            // 파일 IO 스트림을 취득한다.
            using (var stream = new FileStream(Environment.CurrentDirectory + "/simple.pdf", FileMode.Create, FileAccess.Write))
            {
                // Pdf형식의 document를 생성한다.
                Document document = new Document(PageSize.A4, 20, 20, 20, 20);
                // PdfWriter를 취득한다.
                PdfWriter writer = PdfWriter.GetInstance(document, stream);


                try
                {
                    //
                    // 어도비 리더앱의 속성창에서 보이는 내용
                    //
                    document.AddAuthor("박영기");
                    document.AddCreator("박영기");
                    document.AddKeywords("iTextSharp-LGPL 테스트");
                    document.AddSubject("제목");
                    document.AddTitle("제목");

                    document.Open();

                    //
                    // 제목
                    //
                    AddTitle(document, "OO결과확인서");

                    //
                    // 본문
                    //
                    document.Add(new Paragraph("Hello World"));
                    document.Add(new Paragraph(50f, "hello World with leading 50f"));

                    document.Add(Korean("ALIGN_LEFT", Element.ALIGN_LEFT));
                    document.Add(Korean("ALIGN_CENTER", Element.ALIGN_CENTER));
                    document.Add(Korean("ALIGN_RIGHT", Element.ALIGN_RIGHT));

                    AddBR(document);

                    //
                    // 테이블1
                    //
                    {
                        PdfPTable talbe = new PdfPTable(3);
                        talbe.AddCell("Row1,Col1");
                        talbe.AddCell("Row1,Col2");
                        talbe.AddCell("Row1,Col3");

                        talbe.AddCell(Korean("로우2,컬럼1"));
                        talbe.AddCell("Row2,Col2");
                        talbe.AddCell("Row2,Col3");

                        document.Add(talbe);
                    }

                    AddBR(document);
                    //
                    // 테이블2
                    //
                    {
                        PdfPTable talbe = new PdfPTable(3);
                        PdfPCell  cell  = new PdfPCell(Korean("병합셀"));
                        cell.Colspan = 3;

                        talbe.AddCell(cell);
                        talbe.AddCell("Row2,Col1");
                        talbe.AddCell("Row2,Col2");
                        talbe.AddCell("Row2,Col3");

                        document.Add(talbe);
                    }
                }
                finally
                {
                    // document Close
                    document.Close();
                }
            }
        }
コード例 #23
0
        public PDFBehozBeszallito(ObservableCollection <Szállítólevél> szallitolevel, string beszallito)
        {
            BaseFont MySpecialBaseFont = iTextSharp.text.pdf.BaseFont.CreateFont(@"C:\Windows\Fonts\Arial.ttf", iTextSharp.text.pdf.BaseFont.IDENTITY_H, iTextSharp.text.pdf.BaseFont.EMBEDDED);

            iTextSharp.text.Font MySpecialCharfont = new iTextSharp.text.Font(MySpecialBaseFont);

            Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10f, 10f, 20f, 0);

            PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream("test.pdf", System.IO.FileMode.Create));

            doc.Open();

            PdfPTable table = new PdfPTable(4);

            var header_font = FontFactory.GetFont("Times New Roman", 30, BaseColor.BLACK);
            var alap_font   = FontFactory.GetFont("Times New Roman", 12, BaseColor.BLACK);

            iTextSharp.text.Paragraph header = new iTextSharp.text.Paragraph(new Phrase("Szallitólevél", new iTextSharp.text.Font(header_font)));

            header.Alignment = 1;

            doc.Add(header);
            doc.Add(new iTextSharp.text.Paragraph(" "));

            Phrase   datum_phrase = new Phrase("Mit", MySpecialCharfont);
            PdfPCell datum_cella  = new PdfPCell(datum_phrase);

            datum_cella.HorizontalAlignment = 1;

            Phrase   nev_phrase = new Phrase("Mennyit", MySpecialCharfont);
            PdfPCell nev_cella  = new PdfPCell(nev_phrase);

            nev_cella.HorizontalAlignment = 1;

            Phrase   beszall_phrase = new Phrase("Egységár", MySpecialCharfont);
            PdfPCell beszall_cella  = new PdfPCell(beszall_phrase);

            beszall_cella.HorizontalAlignment = 1;

            Phrase   beszall2_phrase = new Phrase("Áfatartalom", MySpecialCharfont);
            PdfPCell beszall2_cella  = new PdfPCell(beszall2_phrase);

            beszall2_cella.HorizontalAlignment = 1;

            table.AddCell(datum_cella);
            table.AddCell(nev_cella);
            table.AddCell(beszall_cella);
            table.AddCell(beszall2_cella);

            int osszeg = 0;

            foreach (var item in szallitolevel)
            {
                table.AddCell(item.miből);
                table.AddCell(item.mennyit);
                table.AddCell(item.egységár);
                table.AddCell(item.áfatartalom);

                osszeg += Convert.ToInt32(item.egységár);
            }

            table.AddCell("");
            table.AddCell("");
            table.AddCell("Összesen:");
            table.AddCell(osszeg + " Ft");

            doc.Add(table);

            doc.Close();

            Process.Start("test.pdf");
        }
コード例 #24
0
ファイル: test.aspx.cs プロジェクト: hardikabbacus/BMBTOOLS
    public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)
    {
        base.OnEndPage(writer, document);
        //FiraSans-Light  fontfamily

        //iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
        //iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);
        //iTextSharp.text.Font CategoryFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.UNDEFINED, 14f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.WHITE);

        Font baseFontBig     = new Font(FontFactory.GetFont("FiraSans-Light", 12f, Font.BOLD));
        Font baseFontNormal  = new Font(FontFactory.GetFont("FiraSans-Light", 12f, Font.NORMAL));
        Font CategoryFontBig = new Font(FontFactory.GetFont("FiraSans-Light", 14, Font.NORMAL, BaseColor.WHITE));

        Phrase p1Header = new Phrase("", baseFontNormal); // sub header

        //Create PdfTable object
        PdfPTable pdfTab = new PdfPTable(3);

        //We will have to create separate cells to include image logo and 2 separate strings

        iTextSharp.text.Image t1image3 = null;
        using (FileStream fs = new FileStream(HttpContext.Current.Server.MapPath("~") + "/resources/PDFTEST/bmb_logo_pdf.png", FileMode.Open))
        {
            t1image3 = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromStream(fs), ImageFormat.Png);
        }
        t1image3.ScaleToFit(100, 100);
        //t1image3.Alignment = Element.ALIGN_LEFT;

        string CategoryName = "Category Name";

        //Row 1
        PdfPCell pdfCell1 = new PdfPCell(t1image3);
        PdfPCell pdfCell2 = new PdfPCell(p1Header);
        PdfPCell pdfCell3 = new PdfPCell(new Phrase(CategoryName, CategoryFontBig));  // set dynamic categoryname

        pdfCell3.FixedHeight         = 25f;
        pdfCell3.BackgroundColor     = BaseColor.BLACK;
        pdfCell3.HorizontalAlignment = Element.ALIGN_MIDDLE;
        pdfCell3.PaddingBottom       = 8f;
        pdfCell3.VerticalAlignment   = Element.ALIGN_MIDDLE;

        String text = "Produce by: BMB Tools      " + "Website: bmbtools.tajrapp.com      " + "Contact us: +966 11 270 9251      " + "Page ";

        //Add paging to header  uncommnet for headder pagging
        {
            //cb.BeginText();
            //cb.SetFontAndSize(bf, 12);
            //cb.SetTextMatrix(document.PageSize.GetRight(200), document.PageSize.GetTop(45));
            //cb.ShowText(text);
            //cb.EndText();
            //float len = bf.GetWidthPoint(text, 12);
            ////Adds "12" in Page 1 of 12
            //cb.AddTemplate(headerTemplate, document.PageSize.GetRight(200) + len, document.PageSize.GetTop(45));
        }
        //Add paging to footer
        {
            cb.BeginText();
            cb.SetFontAndSize(bf, 12);
            cb.SetTextMatrix(document.PageSize.GetRight(570), document.PageSize.GetBottom(30));
            cb.ShowText(text);
            cb.EndText();
            float len = bf.GetWidthPoint(text, 12);
            cb.AddTemplate(footerTemplate, document.PageSize.GetRight(570) + len, document.PageSize.GetBottom(30));
        }
        //Row 2
        PdfPCell pdfCell4 = new PdfPCell(new Phrase("", baseFontNormal)); // sub header
        //Row 3

        //PdfPCell pdfCell5 = new PdfPCell(new Phrase("Date:" + PrintTime.ToShortDateString(), baseFontBig));
        PdfPCell pdfCell5 = new PdfPCell();
        PdfPCell pdfCell6 = new PdfPCell();
        //PdfPCell pdfCell7 = new PdfPCell(new Phrase("TIME:" + string.Format("{0:t}", DateTime.Now), baseFontBig));
        PdfPCell pdfCell7 = new PdfPCell();


        //set the alignment of all three cells and set border to 0
        pdfCell1.HorizontalAlignment = Element.ALIGN_LEFT;
        pdfCell2.HorizontalAlignment = Element.ALIGN_CENTER;
        pdfCell3.HorizontalAlignment = Element.ALIGN_CENTER;
        pdfCell4.HorizontalAlignment = Element.ALIGN_CENTER;
        pdfCell5.HorizontalAlignment = Element.ALIGN_CENTER;
        pdfCell6.HorizontalAlignment = Element.ALIGN_CENTER;
        pdfCell7.HorizontalAlignment = Element.ALIGN_CENTER;


        pdfCell2.VerticalAlignment = Element.ALIGN_BOTTOM;
        pdfCell3.VerticalAlignment = Element.ALIGN_MIDDLE;
        pdfCell4.VerticalAlignment = Element.ALIGN_TOP;
        pdfCell5.VerticalAlignment = Element.ALIGN_MIDDLE;
        pdfCell6.VerticalAlignment = Element.ALIGN_MIDDLE;
        pdfCell7.VerticalAlignment = Element.ALIGN_MIDDLE;


        pdfCell4.Colspan = 3;



        pdfCell1.Border = 0;
        pdfCell2.Border = 0;
        pdfCell3.Border = 0;
        pdfCell4.Border = 0;
        pdfCell5.Border = 0;
        pdfCell6.Border = 0;
        pdfCell7.Border = 0;


        //add all three cells into PdfTable
        pdfTab.AddCell(pdfCell1);
        pdfTab.AddCell(pdfCell2);
        pdfTab.AddCell(pdfCell3);
        pdfTab.AddCell(pdfCell4);
        pdfTab.AddCell(pdfCell5);
        pdfTab.AddCell(pdfCell6);
        pdfTab.AddCell(pdfCell7);

        pdfTab.TotalWidth      = document.PageSize.Width - 0f;
        pdfTab.WidthPercentage = 100;
        //pdfTab.HorizontalAlignment = Element.ALIGN_CENTER;


        //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable
        //first param is start row. -1 indicates there is no end row and all the rows to be included to write
        //Third and fourth param is x and y position to start writing
        pdfTab.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 30, writer.DirectContent);
        //set pdfContent value

        //uncomment for header line
        ////Move the pointer and draw line to separate header section from rest of page
        //cb.MoveTo(40, document.PageSize.Height - 50); // 100
        //cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 50); // 100
        //cb.Stroke();

        // uncomment for footer line
        ////Move the pointer and draw line to separate footer section from rest of page
        //cb.MoveTo(40, document.PageSize.GetBottom(50));
        //cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50));
        //cb.Stroke();
    }
コード例 #25
0
        public MemoryStream GeneratePdfTemplate(GarmentPackingListViewModel viewModel)
        {
            int maxSizesCount = viewModel.Items == null || viewModel.Items.Count < 1 ? 0 : viewModel.Items.Max(i => i.Details == null || i.Details.Count < 1 ? 0 : i.Details.Max(d => d.Sizes == null || d.Sizes.Count < 1 ? 0 : d.Sizes.GroupBy(g => g.Size.Id).Count()));
            int SIZES_COUNT   = maxSizesCount > 11 ? 20 : 11;

            Font header_font            = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 14);
            Font normal_font            = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);
            Font body_font              = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);
            Font normal_font_underlined = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8, Font.UNDERLINE);
            Font bold_font              = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);

            Document     document = new Document(maxSizesCount > 11 ? PageSize.A4.Rotate() : PageSize.A4, 20, 20, 70, 30);
            MemoryStream stream   = new MemoryStream();
            PdfWriter    writer   = PdfWriter.GetInstance(document, stream);

            writer.PageEvent = new GarmentPackingListDraftPDFTemplatePageEvent(_identityProvider, viewModel);

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

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

            var           cartons       = new List <GarmentPackingListDetailViewModel>();
            double        grandTotal    = 0;
            List <string> cartonNumbers = new List <string>();

            var newItems   = new List <GarmentPackingListItemViewModel>();
            var newDetails = new List <GarmentPackingListDetailViewModel>();

            foreach (var item in viewModel.Items)
            {
                foreach (var detail in item.Details)
                {
                    newDetails.Add(detail);
                }
            }
            newDetails = newDetails.OrderBy(a => a.Carton1).ToList();

            foreach (var d in newDetails)
            {
                if (newItems.Count == 0)
                {
                    var i = viewModel.Items.Single(a => a.Id == d.PackingListItemId);
                    i.Details = new List <GarmentPackingListDetailViewModel>();
                    i.Details.Add(d);
                    newItems.Add(i);
                }
                else
                {
                    if (newItems.Last().Id == d.PackingListItemId)
                    {
                        newItems.Last().Details.Add(d);
                    }
                    else
                    {
                        var y = viewModel.Items.Select(a => new GarmentPackingListItemViewModel {
                            Id      = a.Id, RONo = a.RONo, Article = a.Article, BuyerAgent = a.BuyerAgent, ComodityDescription = a.ComodityDescription,
                            OrderNo = a.OrderNo, AVG_GW = a.AVG_GW, AVG_NW = a.AVG_NW
                        })
                                .Single(a => a.Id == d.PackingListItemId);
                        y.Details = new List <GarmentPackingListDetailViewModel>();
                        y.Details.Add(d);
                        newItems.Add(y);
                    }
                }
            }

            document.Add(new Paragraph("SHIPPING METHOD : " + viewModel.ShipmentMode + "\n", normal_font));

            foreach (var item in newItems.OrderBy(a => a.RONo))
            {
                #region Item

                PdfPTable tableItem = new PdfPTable(6);
                tableItem.SetWidths(new float[] { 2f, 0.2f, 2.8f, 2f, 0.2f, 2.8f });
                PdfPCell cellItemContent = new PdfPCell()
                {
                    Border = Rectangle.NO_BORDER
                };

                cellItemContent.Phrase = new Phrase("RO No", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(":", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(item.RONo, normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase("ARTICLE", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(":", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(item.Article, normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase("BUYER", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(":", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(viewModel.BuyerAgent.Name, normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase("", normal_font);
                cellItemContent.Phrase = new Phrase("DESCRIPTION OF GOODS", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(":", normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase(item.ComodityDescription, normal_font);
                tableItem.AddCell(cellItemContent);
                cellItemContent.Phrase = new Phrase("", normal_font);
                tableItem.AddCell(cellItemContent);
                tableItem.AddCell(cellItemContent);
                tableItem.AddCell(cellItemContent);

                new PdfPCell(tableItem);
                tableItem.ExtendLastRow = false;
                document.Add(tableItem);

                #endregion

                var sizes = new Dictionary <int, string>();
                foreach (var detail in item.Details)
                {
                    foreach (var size in detail.Sizes)
                    {
                        sizes[size.Size.Id] = size.Size.Size;
                    }
                }

                PdfPTable tableDetail = new PdfPTable(SIZES_COUNT + 10);
                var       width       = new List <float> {
                    2f, 3.5f, 4f, 4f
                };
                for (int i = 0; i < SIZES_COUNT; i++)
                {
                    width.Add(1f);
                }
                width.AddRange(new List <float> {
                    1.5f, 1f, 1.5f, 1f, 1f, 1.5f
                });
                tableDetail.SetWidths(width.ToArray());

                PdfPCell cellDetailLine = new PdfPCell()
                {
                    Border = Rectangle.BOTTOM_BORDER, Colspan = 19, Padding = 0.5f, Phrase = new Phrase("")
                };
                tableDetail.AddCell(cellDetailLine);
                tableDetail.AddCell(cellDetailLine);

                cellBorderBottomRight.Phrase  = new Phrase(GetScalledChunk("CARTON NO.", normal_font, 0.75f));
                cellBorderBottomRight.Rowspan = 2;
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("COLOUR", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("STYLE", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("ORDER NO.", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase  = new Phrase(GetScalledChunk("S I Z E", normal_font, 0.75f));
                cellBorderBottomRight.Colspan = SIZES_COUNT;
                cellBorderBottomRight.Rowspan = 1;
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase  = new Phrase(GetScalledChunk("CTNS", normal_font, 0.75f));
                cellBorderBottomRight.Colspan = 1;
                cellBorderBottomRight.Rowspan = 2;
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("@\nPCS", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("QTY\nPCS", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase  = new Phrase(GetScalledChunk("GW/\nCTN", normal_font, 0.75f));
                cellBorderBottomRight.Rowspan = 2;
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("NW/\nCTN", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("NNW/\nCTN", normal_font, 0.75f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Rowspan = 1;

                for (int i = 0; i < SIZES_COUNT; i++)
                {
                    var size = sizes.OrderBy(a => a.Value).ElementAtOrDefault(i);
                    cellBorderBottomRight.Phrase  = new Phrase(GetScalledChunk(size.Key == 0 ? "" : size.Value, normal_font, 0.5f));
                    cellBorderBottomRight.Rowspan = 1;
                    tableDetail.AddCell(cellBorderBottomRight);
                }

                var    subCartons = new List <GarmentPackingListDetailViewModel>();
                double subTotal   = 0;
                var    sizeSumQty = new Dictionary <int, double>();
                foreach (var detail in item.Details)
                {
                    var ctnsQty = detail.CartonQuantity;
                    if (cartonNumbers.Contains($"{detail.Carton1}- {detail.Carton2}"))
                    {
                        ctnsQty = 0;
                    }
                    else
                    {
                        cartonNumbers.Add($"{detail.Carton1}- {detail.Carton2}");
                    }
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk($"{detail.Carton1}- {detail.Carton2}", normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(detail.Colour, normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(detail.Style, normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(item.OrderNo, normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    for (int i = 0; i < SIZES_COUNT; i++)
                    {
                        var    size     = sizes.OrderBy(a => a.Value).ElementAtOrDefault(i);
                        double quantity = 0;
                        if (size.Key != 0)
                        {
                            quantity = detail.Sizes.Where(w => w.Size.Id == size.Key).Sum(s => s.Quantity);
                        }

                        if (sizeSumQty.ContainsKey(size.Key))
                        {
                            sizeSumQty[size.Key] += quantity * detail.CartonQuantity;
                        }
                        else
                        {
                            sizeSumQty.Add(size.Key, quantity * detail.CartonQuantity);
                        }

                        cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(quantity == 0 ? "" : quantity.ToString(), normal_font, 0.6f));

                        tableDetail.AddCell(cellBorderBottomRight);
                    }
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(ctnsQty.ToString(), normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(detail.QuantityPCS.ToString(), normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    var totalQuantity = (detail.CartonQuantity * detail.QuantityPCS);
                    subTotal += totalQuantity;
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(totalQuantity.ToString(), normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(string.Format("{0:n2}", detail.GrossWeight), normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(string.Format("{0:n2}", detail.NetWeight), normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);
                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(string.Format("{0:n2}", detail.NetNetWeight), normal_font, 0.6f));
                    tableDetail.AddCell(cellBorderBottomRight);

                    if (cartons.FindIndex(c => c.Carton1 == detail.Carton1 && c.Carton2 == detail.Carton2) < 0)
                    {
                        cartons.Add(new GarmentPackingListDetailViewModel {
                            Carton1 = detail.Carton1, Carton2 = detail.Carton2, CartonQuantity = ctnsQty
                        });
                    }
                    if (subCartons.FindIndex(c => c.Carton1 == detail.Carton1 && c.Carton2 == detail.Carton2) < 0)
                    {
                        subCartons.Add(new GarmentPackingListDetailViewModel {
                            Carton1 = detail.Carton1, Carton2 = detail.Carton2, CartonQuantity = ctnsQty
                        });
                    }
                }

                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.5f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.5f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.5f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("SUMMARY", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                for (int i = 0; i < SIZES_COUNT; i++)
                {
                    var    size     = sizes.OrderBy(a => a.Value).ElementAtOrDefault(i);
                    double quantity = 0;
                    if (size.Key != 0)
                    {
                        quantity = sizeSumQty.Where(w => w.Key == size.Key).Sum(a => a.Value);
                    }

                    cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk(quantity == 0 ? "" : quantity.ToString(), normal_font, 0.5f));

                    tableDetail.AddCell(cellBorderBottomRight);
                }
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);
                cellBorderBottomRight.Phrase = new Phrase(GetScalledChunk("", normal_font, 0.6f));
                tableDetail.AddCell(cellBorderBottomRight);


                grandTotal += subTotal;

                tableDetail.AddCell(new PdfPCell()
                {
                    Border  = Rectangle.BOTTOM_BORDER,
                    Colspan = SIZES_COUNT + 6,
                    Padding = 5,
                    Phrase  = new Phrase("SUB TOTAL ....................................................................................................................................................................... ", normal_font)
                });
                cellBorderBottom.Phrase  = new Phrase(subTotal.ToString(), normal_font);
                cellBorderBottom.Colspan = 1;
                tableDetail.AddCell(cellBorderBottom);
                cellBorderBottom.Phrase  = new Phrase("", normal_font);
                cellBorderBottom.Colspan = 3;
                tableDetail.AddCell(cellBorderBottom);
                cellBorderBottom.Colspan = 1;

                var subCtns = subCartons.Sum(c => c.CartonQuantity);

                tableDetail.AddCell(new PdfPCell()
                {
                    Border  = Rectangle.BOTTOM_BORDER,
                    Colspan = SIZES_COUNT + 10,
                    Phrase  = new Phrase($"      - Sub Ctns = {subCtns}           - Sub G.W. = {item.Details.Sum(a => a.GrossWeight * a.CartonQuantity)} Kgs           - Sub N.W. = {item.Details.Sum(a => a.NetWeight * a.CartonQuantity)} Kgs            - Sub N.N.W. = {item.Details.Sum(a => a.NetNetWeight*a.CartonQuantity)} Kgs", normal_font)
                });

                new PdfPCell(tableDetail);
                tableDetail.ExtendLastRow = false;
                //tableDetail.KeepTogether = true;
                tableDetail.WidthPercentage = 95f;
                //tableDetail.HeaderRows = 3;
                document.Add(tableDetail);
            }

            #region GrandTotal

            PdfPTable tableGrandTotal = new PdfPTable(2);
            tableGrandTotal.SetWidths(new float[] { 18f + SIZES_COUNT * 1f, 3f });
            PdfPCell cellHeaderLine = new PdfPCell()
            {
                Border = Rectangle.BOTTOM_BORDER, Colspan = 2, Padding = 0.5f, Phrase = new Phrase("")
            };

            tableGrandTotal.AddCell(cellHeaderLine);
            tableGrandTotal.AddCell(new PdfPCell()
            {
                Border  = Rectangle.BOTTOM_BORDER,
                Padding = 5,
                Phrase  = new Phrase("GRAND TOTAL ...................................................................................................................................................................................", normal_font)
            });
            tableGrandTotal.AddCell(new PdfPCell()
            {
                Border              = Rectangle.BOTTOM_BORDER,
                Padding             = 5,
                HorizontalAlignment = Element.ALIGN_CENTER,
                Phrase              = new Phrase(grandTotal.ToString(), normal_font)
            });
            tableGrandTotal.AddCell(cellHeaderLine);
            var totalCtns  = cartons.Sum(c => c.CartonQuantity);
            var comodities = viewModel.Items.Select(s => s.Comodity.Name.ToUpper()).Distinct();
            tableGrandTotal.AddCell(new PdfPCell()
            {
                Border  = Rectangle.NO_BORDER,
                Colspan = 2,
                Padding = 5,
                Phrase  = new Phrase($"{totalCtns} {viewModel.SayUnit} [ {NumberToTextEN.toWords(totalCtns).Trim().ToUpper()} {viewModel.SayUnit} OF {string.Join(" AND ", comodities)}]", normal_font)
            });

            new PdfPCell(tableGrandTotal);
            tableGrandTotal.ExtendLastRow   = false;
            tableGrandTotal.WidthPercentage = 95f;
            tableGrandTotal.SpacingAfter    = 5f;
            document.Add(tableGrandTotal);

            #endregion

            #region Mark

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

            PdfPCell cellShippingMark = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            Chunk chunkShippingMark = new Chunk("SHIPPING MARKS", normal_font);
            chunkShippingMark.SetUnderline(0.5f, -1);
            Phrase phraseShippingMark = new Phrase();
            phraseShippingMark.Add(chunkShippingMark);
            phraseShippingMark.Add(new Chunk("     :", normal_font));
            cellShippingMark.AddElement(phraseShippingMark);
            cellShippingMark.AddElement(new Paragraph(viewModel.ShippingMark, normal_font));
            tableMark.AddCell(cellShippingMark);

            PdfPCell cellSideMark = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            Chunk chunkSideMark = new Chunk("SIDE MARKS", normal_font);
            chunkSideMark.SetUnderline(0.5f, -1);
            Phrase phraseSideMark = new Phrase();
            phraseSideMark.Add(chunkSideMark);
            phraseSideMark.Add(new Chunk("     :", normal_font));
            cellSideMark.AddElement(phraseSideMark);
            cellSideMark.AddElement(new Paragraph(viewModel.SideMark, normal_font)
            {
            });
            tableMark.AddCell(cellSideMark);

            byte[] shippingMarkImage;

            try
            {
                shippingMarkImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.ShippingMarkImageFile));
            }
            catch (Exception)
            {
                shippingMarkImage = Convert.FromBase64String("/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAA0NDQ0ODQ4QEA4UFhMWFB4bGRkbHi0gIiAiIC1EKjIqKjIqRDxJOzc7STxsVUtLVWx9aWNpfZeHh5e+tb75+f8BDQ0NDQ4NDhAQDhQWExYUHhsZGRseLSAiICIgLUQqMioqMipEPEk7NztJPGxVS0tVbH1pY2l9l4eHl761vvn5///CABEIAAoACgMBIgACEQEDEQH/xAAVAAEBAAAAAAAAAAAAAAAAAAAAB//aAAgBAQAAAACnD//EABQBAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIQAAAAf//EABQBAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMQAAAAf//EABQQAQAAAAAAAAAAAAAAAAAAACD/2gAIAQEAAT8AH//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIBAT8Af//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMBAT8Af//Z");
            }

            Image shipMarkImage = Image.GetInstance(imgb: shippingMarkImage);

            if (shipMarkImage.Width > 60)
            {
                float percentage = 0.0f;
                percentage = 100 / shipMarkImage.Width;
                shipMarkImage.ScalePercent(percentage * 100);
            }

            PdfPCell shipMarkImageCell = new PdfPCell(shipMarkImage);
            shipMarkImageCell.Border = Rectangle.NO_BORDER;
            tableMark.AddCell(shipMarkImageCell);

            byte[] sideMarkImage;

            try
            {
                sideMarkImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.SideMarkImageFile));
            }
            catch (Exception)
            {
                sideMarkImage = Convert.FromBase64String("/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAA0NDQ0ODQ4QEA4UFhMWFB4bGRkbHi0gIiAiIC1EKjIqKjIqRDxJOzc7STxsVUtLVWx9aWNpfZeHh5e+tb75+f8BDQ0NDQ4NDhAQDhQWExYUHhsZGRseLSAiICIgLUQqMioqMipEPEk7NztJPGxVS0tVbH1pY2l9l4eHl761vvn5///CABEIAAoACgMBIgACEQEDEQH/xAAVAAEBAAAAAAAAAAAAAAAAAAAAB//aAAgBAQAAAACnD//EABQBAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIQAAAAf//EABQBAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMQAAAAf//EABQQAQAAAAAAAAAAAAAAAAAAACD/2gAIAQEAAT8AH//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIBAT8Af//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMBAT8Af//Z");
            }

            Image _sideMarkImage = Image.GetInstance(imgb: sideMarkImage);

            if (_sideMarkImage.Width > 60)
            {
                float percentage = 0.0f;
                percentage = 100 / _sideMarkImage.Width;
                _sideMarkImage.ScalePercent(percentage * 100);
            }

            PdfPCell _sideMarkImageCell = new PdfPCell(_sideMarkImage);
            _sideMarkImageCell.Border = Rectangle.NO_BORDER;
            tableMark.AddCell(_sideMarkImageCell);

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

            #endregion

            #region Measurement

            PdfPTable tableMeasurement = new PdfPTable(3);
            tableMeasurement.SetWidths(new float[] { 2f, 0.2f, 7.8f });
            PdfPCell cellMeasurement = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };

            cellMeasurement.Phrase = new Phrase("GROSS WEIGHT", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(":", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(viewModel.GrossWeight + " KGS", normal_font);
            tableMeasurement.AddCell(cellMeasurement);

            cellMeasurement.Phrase = new Phrase("NET WEIGHT", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(":", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(viewModel.NettWeight + " KGS", normal_font);
            tableMeasurement.AddCell(cellMeasurement);

            cellMeasurement.Phrase = new Phrase("NET NET WEIGHT", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(":", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(viewModel.NetNetWeight + " KGS", normal_font);
            tableMeasurement.AddCell(cellMeasurement);

            cellMeasurement.Phrase = new Phrase("MEASUREMENT", normal_font);
            tableMeasurement.AddCell(cellMeasurement);
            cellMeasurement.Phrase = new Phrase(":", normal_font);
            tableMeasurement.AddCell(cellMeasurement);

            PdfPTable tableMeasurementDetail = new PdfPTable(5);
            tableMeasurementDetail.SetWidths(new float[] { 1f, 1f, 1f, 1.5f, 2f });
            PdfPCell cellMeasurementDetail = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT
            };
            decimal totalCbm = 0;
            foreach (var measurement in viewModel.Measurements)
            {
                cellMeasurementDetail.Phrase = new Phrase(measurement.Length + " CM X ", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                cellMeasurementDetail.Phrase = new Phrase(measurement.Width + " CM X ", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                cellMeasurementDetail.Phrase = new Phrase(measurement.Height + " CM X ", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                cellMeasurementDetail.Phrase = new Phrase(measurement.CartonsQuantity + " CTNS = ", normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
                var cbm = (decimal)measurement.Length * (decimal)measurement.Width * (decimal)measurement.Height * (decimal)measurement.CartonsQuantity / 1000000;
                totalCbm += cbm;
                cellMeasurementDetail.Phrase = new Phrase(string.Format("{0:N2} CBM", cbm), normal_font);
                tableMeasurementDetail.AddCell(cellMeasurementDetail);
            }

            cellMeasurementDetail.Border = Rectangle.TOP_BORDER;
            cellMeasurementDetail.Phrase = new Phrase("", normal_font);
            tableMeasurementDetail.AddCell(cellMeasurementDetail);
            tableMeasurementDetail.AddCell(cellMeasurementDetail);
            cellMeasurementDetail.Phrase = new Phrase("TOTAL", normal_font);
            tableMeasurementDetail.AddCell(cellMeasurementDetail);
            cellMeasurementDetail.Phrase = new Phrase(viewModel.Measurements.Sum(m => m.CartonsQuantity) + " CTNS .", normal_font);
            tableMeasurementDetail.AddCell(cellMeasurementDetail);
            cellMeasurementDetail.Phrase = new Phrase(string.Format("{0:N2} CBM", totalCbm), normal_font);
            tableMeasurementDetail.AddCell(cellMeasurementDetail);

            new PdfPCell(tableMeasurementDetail);
            tableMeasurementDetail.ExtendLastRow = false;
            tableMeasurement.AddCell(new PdfPCell(tableMeasurementDetail)
            {
                Border = Rectangle.NO_BORDER, PaddingRight = 100
            });

            tableMeasurement.AddCell(new PdfPCell
            {
                Border  = Rectangle.NO_BORDER,
                Colspan = 3,
                Phrase  = new Phrase("REMARK :", normal_font_underlined)
            });
            tableMeasurement.AddCell(new PdfPCell
            {
                Border  = Rectangle.NO_BORDER,
                Colspan = 3,
                Phrase  = new Phrase(viewModel.Remark, normal_font)
            });
            byte[] remarkImage;

            try
            {
                remarkImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.RemarkImageFile));
            }
            catch (Exception)
            {
                remarkImage = Convert.FromBase64String("/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAA0NDQ0ODQ4QEA4UFhMWFB4bGRkbHi0gIiAiIC1EKjIqKjIqRDxJOzc7STxsVUtLVWx9aWNpfZeHh5e+tb75+f8BDQ0NDQ4NDhAQDhQWExYUHhsZGRseLSAiICIgLUQqMioqMipEPEk7NztJPGxVS0tVbH1pY2l9l4eHl761vvn5///CABEIAAoACgMBIgACEQEDEQH/xAAVAAEBAAAAAAAAAAAAAAAAAAAAB//aAAgBAQAAAACnD//EABQBAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIQAAAAf//EABQBAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMQAAAAf//EABQQAQAAAAAAAAAAAAAAAAAAACD/2gAIAQEAAT8AH//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIBAT8Af//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMBAT8Af//Z");
            }

            Image images = Image.GetInstance(imgb: remarkImage);

            if (images.Width > 60)
            {
                float percentage = 0.0f;
                percentage = 100 / images.Width;
                images.ScalePercent(percentage * 100);
            }

            PdfPCell imageCell = new PdfPCell(images);
            imageCell.Border  = Rectangle.NO_BORDER;
            imageCell.Colspan = 3;
            tableMeasurement.AddCell(imageCell);

            new PdfPCell(tableMeasurement);
            tableMeasurement.ExtendLastRow = false;
            tableMeasurement.SpacingAfter  = 5f;
            document.Add(tableMeasurement);
            //document.Add(images);

            #endregion

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

            return(stream);
        }
コード例 #26
0
        /// <summary>
        /// Create the PDF using the defined page size, label type and content provided
        /// Ensure you have added something first using either AddImage() or AddText()
        /// </summary>
        /// <returns></returns>
        public Stream CreatePDF()
        {
            //Get the itext page size
            Rectangle pageSize;

            switch (_labelDefinition.PageSize)
            {
            case Enums.PageSize.A4:
                pageSize = iTextSharp.text.PageSize.A4;
                break;

            default:
                pageSize = iTextSharp.text.PageSize.A4;
                break;
            }

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

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

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

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

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

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

            //Build the column width array, even numbered index columns will be gap columns
            var colWidths = new List <float>();

            for (int i = 1; i <= numOfCols; i++)
            {
                if (i % 2 > 0)
                {
                    colWidths.Add(_labelDefinition.Width);
                }
                else
                {
                    //Even numbered columns are gap columns
                    colWidths.Add(_labelDefinition.HorizontalGapWidth);
                }
            }

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


            // loop over the labels

            var rowNumber = 0;
            var colNumber = 0;


            PdfPTable tbl = null;

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

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

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

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

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


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

                    rowNumber++;
                    colNumber = 0;
                }


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

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


                tbl.CompleteRow();
            }

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

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

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

            return(output);
        }
コード例 #27
0
        public void imprimir(Type Tipo)
        {
            PdfPTable table            = null;
            var       valorTipo        = "";
            var       porcentagem      = "";
            int       totalPessoas     = modelocrud.Modelos.OfType <Pessoa>().ToList().Count;
            int       totalMinisterios = modelocrud.Modelos.OfType <Ministerio>().ToList().Count;
            int       totalCelulas     = modelocrud.Modelos.OfType <Celula>().ToList().Count;
            var       Modelos          = modelocrud.Modelos.Where(i => i.GetType().Name == Tipo.Name ||
                                                                  i.GetType().IsSubclassOf(Tipo)).ToList();

            if (Tipo.IsSubclassOf(typeof(Pessoa)))
            {
                table = new PdfPTable(2);
                var     quant = Modelos.Count;
                decimal p     = (quant / totalPessoas);
                porcentagem = "A procentagem em relação ao total de pessoas é "
                              + p.ToString("F2") + "%. Quantidade de registros é: "
                              + quant;
            }

            if (Tipo.IsSubclassOf(typeof(Celula)))
            {
                var     quant = Modelos.Count;
                decimal p     = (quant / totalCelulas);
                porcentagem = "A procentagem em relação ao total de celulas é "
                              + p.ToString("f2") + "%. Quantidade de registros é: "
                              + quant;
            }

            if (Tipo.IsSubclassOf(typeof(Ministerio)))
            {
                var quant = modelocrud.Modelos.Where(i => i.GetType().Name == Tipo.Name ||
                                                     i.GetType().IsSubclassOf(Tipo)).ToList().Count;
                decimal p = (quant / totalMinisterios);
                porcentagem = "A procentagem em relação ao total de ministérios é "
                              + p.ToString("f2") + "%. Quantidade de registros é: "
                              + quant;
            }

            if (Tipo == typeof(Reuniao))
            {
                table = new PdfPTable(3);
            }

            if (Tipo.IsSubclassOf(typeof(Pessoa)))
            {
                table = new PdfPTable(2);
            }

            if (Tipo.IsSubclassOf(typeof(PessoaLgpd)))
            {
                table = new PdfPTable(3);
            }

            if (Tipo == typeof(Ministerio))
            {
                table = new PdfPTable(2);
            }

            if (Tipo == typeof(Celula))
            {
                table = new PdfPTable(2);
            }

            if (Tipo == typeof(MudancaEstado))
            {
                table = new PdfPTable(5);
            }

            if (Tipo == typeof(Movimentacao))
            {
                table = new PdfPTable(5);
            }

            if (Tipo == typeof(Mensagem))
            {
                table = new PdfPTable(2);
            }

            if (Tipo == typeof(Fonte))
            {
                table = new PdfPTable(2);
            }

            if (Tipo == typeof(Email))
            {
                table = new PdfPTable(3);
            }

            if (Tipo == typeof(Permissao))
            {
                table = new PdfPTable(2);
            }

            if (Tipo.IsAbstract)
            {
                valorTipo = Tipo.Name;
            }
            else
            {
                valorTipo = Tipo.Name;
            }

            Document doc = new Document(PageSize.A4);

            doc.SetMargins(40, 40, 40, 80);

            string path = Directory.GetCurrentDirectory();

            string caminho = path + @"\relatorio\" + "relatorio-" + valorTipo + "-" + DateTime.Now.ToString("dd-MM-yyyy") + ".pdf";

            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(caminho, FileMode.Create));

            doc.Open();

            Paragraph titulo = new Paragraph();

            titulo.Font      = new Font(Font.FontFamily.COURIER, 40);
            titulo.Alignment = Element.ALIGN_CENTER;
            titulo.Add("Relatório \n\n");
            doc.Add(titulo);



            Paragraph paragrafo = new Paragraph("", new Font(Font.NORMAL, 12));
            string    conteudo  = "Este é um relatório do dia " + DateTime.Now.ToString("dd/MM/yyyy") +
                                  " cujo o conteudo é referente a " + valorTipo + $". {porcentagem} \n\n";

            paragrafo.Add(conteudo);
            doc.Add(paragrafo);


            if (Tipo == typeof(Reuniao))
            {
                foreach (var item in Modelos)
                {
                    table.AddCell("Id: " + item.Id.ToString());

                    var props = item.GetType().GetProperties();

                    if (item.GetType().GetProperty("Nome") != null)
                    {
                        var p = item.GetType().GetProperty("Nome");
                        table.AddCell("Nome: " + p.GetValue(item).ToString());
                    }

                    if (item.GetType().GetProperty("Data") != null)
                    {
                        var p = item.GetType().GetProperty("Data");
                        table.AddCell("Data: " + p.GetValue(item).ToString());
                    }

                    if (item is Reuniao)
                    {
                        var m = (Reuniao)item;
                        table.AddCell("Data da reunião: " + m.Data_reuniao.ToString());
                        table.AddCell("Horario de inicio: " + m.Horario_inicio.ToString());
                    }

                    if (item is PessoaLgpd)
                    {
                        var m = (PessoaLgpd)item;
                        table.AddCell("Email: " + m.Email.ToString());
                    }

                    if (item is MudancaEstado)
                    {
                        var m = (MudancaEstado)item;
                        table.AddCell("antigo estado: " + m.velhoEstado);
                        table.AddCell("novo estado: " + m.novoEstado);
                        table.AddCell("Codigo: " + m.Codigo);
                    }

                    if (item is Movimentacao)
                    {
                        var m = (Movimentacao)item;
                        table.AddCell("Valor: " + m.Valor);
                        table.AddCell("Tipo: " + m.GetType().Name);
                    }

                    if (item is Mensagem)
                    {
                        var m = (Mensagem)item;
                        table.AddCell("Tipo: " + m.Tipo);
                    }

                    if (item is Fonte)
                    {
                        var m = (Fonte)item;
                        table.AddCell("Mensagem Id: " + m.MensagemId);
                    }

                    if (item is Email)
                    {
                        var m = (Email)item;
                        table.AddCell("Assunto: " + m.Assunto);
                    }

                    if (item is Permissao)
                    {
                        var m = (Permissao)item;
                        table.AddCell("Nome: " + m.Nome);
                    }
                }
            }

            doc.Add(table);

            string caminhoImg =
                "http://www.clickfamilia.org.br/oikos2015/wp-content/uploads/2019/07/what-is-family-ministry-lead-300x225.jpg";
            Image img = Image.GetInstance(caminhoImg);

            doc.Add(img);

            doc.Close();

            System.Diagnostics.Process.Start(caminho);
        }
コード例 #28
0
        protected void btnExportPdf_Click(object sender, EventArgs e)
        {
            gridViewDocumentos.AllowPaging = false;
            BindData();
            Document doc = new Document(PageSize.LETTER);

            doc.AddTitle("Estado de Cuenta");
            doc.AddCreator("E&E Integra");
            System.IO.MemoryStream stream = new System.IO.MemoryStream();

            iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, stream);
            doc.Open();
            // Creamos el tipo de Font que vamos utilizar
            iTextSharp.text.Font _tituloFont  = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 14, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
            iTextSharp.text.Font _tituloFont2 = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 14, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
            iTextSharp.text.Font texto        = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
            iTextSharp.text.Font _cellFont    = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
            // Escribimos el encabezamiento en el documento
            Paragraph paragraph1 = new Paragraph(@"                         LISTADO FACTURACION", _tituloFont);

            paragraph1.Alignment = Element.ALIGN_LEFT;
            doc.Add(paragraph1);
            Paragraph paragraph2 = new Paragraph(@"                                                    ", _tituloFont);

            paragraph2.Alignment = Element.ALIGN_LEFT;
            doc.Add(paragraph2);

            //Creating iTextSharp Table from the DataTable data
            PdfPTable pdfTable = new PdfPTable(7);

            pdfTable.DefaultCell.Padding     = 3;
            pdfTable.WidthPercentage         = 100;
            pdfTable.HorizontalAlignment     = Element.ALIGN_LEFT;
            pdfTable.DefaultCell.BorderWidth = 1;

            //Adding Header row
            pdfTable.AddCell("Fecha");
            pdfTable.AddCell("Cliente");
            pdfTable.AddCell("Tipo Documento");
            pdfTable.AddCell("Serie");
            pdfTable.AddCell("Nro. Serie");
            pdfTable.AddCell("Forma de Pago");
            pdfTable.AddCell("Monto Total");

            //Adding DataRow
            foreach (GridViewRow row in gridViewDocumentos.Rows)
            {
                Label lblFecha = row.FindControl("lblFecha") as Label;
                if (lblFecha != null)
                {
                    pdfTable.AddCell(new PdfPCell(new Phrase(lblFecha.Text, _cellFont)));
                }
                else
                {
                    pdfTable.AddCell(new PdfPCell(new Phrase("", _cellFont)));
                }
                Label lblCliente = row.FindControl("lblCliente") as Label;
                if (lblCliente != null)
                {
                    pdfTable.AddCell(new PdfPCell(new Phrase(lblCliente.Text, _cellFont)));
                }
                else
                {
                    pdfTable.AddCell(new PdfPCell(new Phrase("", _cellFont)));
                }
                Label lblTipoDocumento = row.FindControl("lblTipoDocumento") as Label;
                if (lblTipoDocumento != null)
                {
                    pdfTable.AddCell(new PdfPCell(new Phrase(lblTipoDocumento.Text, _cellFont)));
                }
                else
                {
                    pdfTable.AddCell(new PdfPCell(new Phrase("", _cellFont)));
                }

                Label lblSerie = row.FindControl("lblSerie") as Label;
                if (lblSerie != null)
                {
                    pdfTable.AddCell(new PdfPCell(new Phrase(lblSerie.Text, _cellFont)));
                }
                else
                {
                    pdfTable.AddCell(new PdfPCell(new Phrase("", _cellFont)));
                }
                Label lblNroSerie = row.FindControl("lblNroSerie") as Label;
                if (lblNroSerie != null)
                {
                    pdfTable.AddCell(new PdfPCell(new Phrase(lblNroSerie.Text, _cellFont)));
                }
                else
                {
                    pdfTable.AddCell(new PdfPCell(new Phrase("", _cellFont)));
                }
                Label lblFormaPago = row.FindControl("lblFormaPago") as Label;
                if (lblFormaPago != null)
                {
                    pdfTable.AddCell(new PdfPCell(new Phrase(lblFormaPago.Text, _cellFont)));
                }
                else
                {
                    pdfTable.AddCell(new PdfPCell(new Phrase("", _cellFont)));
                }
                Label lblmontoTotal = row.FindControl("lblmontoTotal") as Label;
                if (lblmontoTotal != null)
                {
                    pdfTable.AddCell(new PdfPCell(new Phrase(lblmontoTotal.Text, _cellFont)));
                }
                else
                {
                    pdfTable.AddCell(new PdfPCell(new Phrase("", _cellFont)));
                }
            }

            doc.Add(pdfTable);
            doc.Close();
            stream.Close();
            byte[] Result = stream.ToArray();
            Sistema.GetInstancia().PDFActual = Result;
            // Session["pdf"] = Result;
            gridViewDocumentos.AllowPaging = true;
            if (Sistema.GetInstancia().PDFActual != null)
            {
                Response.Redirect("VisorPDFReportes.aspx");
            }
        }
コード例 #29
0
        internal static string PrintMemberReport()
        {
            var  members    = GetYagnaMembers();
            var  folderPath = HttpContext.Current.Server.MapPath(Convert.ToString(ConfigurationManager.AppSettings["ReportFolderPath"]));
            bool exists     = Directory.Exists(folderPath);

            if (!exists)
            {
                Directory.CreateDirectory(folderPath);
            }

            DirectoryInfo info = new DirectoryInfo(folderPath);

            FileInfo[] files = info.GetFiles().Where(p => p.CreationTime <= DateTime.Now.AddDays(-1)).ToArray();
            foreach (var file in files)
            {
                file.Delete();
            }
            var document    = new iTextSharp.text.Document(PageSize.A4, 0f, 0f, 0f, 0f);
            var pdffilename = "YagnaMember" + DateTime.Now.ToString("h:mm:ss").Replace(":", "");
            var writer      = PdfWriter.GetInstance(document, new FileStream(folderPath + "/" + pdffilename + ".PDF", FileMode.Create));

            writer.PageEvent = new PDFFooter("Admin");
            document.Open();

            var       widths = new float[] { 30f, 40f, 30f };
            PdfPTable table  = new PdfPTable(3);

            table.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;
            float columnWidth = (table.TotalWidth - 10f) / 2.5f;

            float[] columnWidths = new float[3] {
                columnWidth, columnWidth, columnWidth
            };
            table.SetWidths(columnWidths);
            table.DefaultCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
            PdfPCell cell;
            Font     font8 = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 8);

            foreach (var member in members)
            {
                cell = new PdfPCell();
                cell.AddElement(new iTextSharp.text.Phrase(member.Name + "\n", font8));
                cell.AddElement(new iTextSharp.text.Phrase(member.Address + '\n', font8));
                cell.AddElement(new iTextSharp.text.Phrase(member.Mobile + '\n', font8));
                cell.HorizontalAlignment = 1;
                cell.VerticalAlignment   = 1;
                cell.MinimumHeight       = 72f;
                cell.Border = iTextSharp.text.Rectangle.NO_BORDER;
                table.AddCell(cell);
            }
            if (members.Count < 3)
            {
                cell        = new PdfPCell(new Phrase(" ", font8));
                cell.Border = iTextSharp.text.Rectangle.NO_BORDER;
                table.AddCell(cell);
            }
            document.Add(table);
            document.Close();

            return(pdffilename + ".PDF");
        }
コード例 #30
0
 /**
 * @see com.lowagie.text.pdf.PdfPTableEvent#tableLayout(com.lowagie.text.pdf.PdfPTable, float[][], float[], int, int, com.lowagie.text.pdf.PdfContentByte[])
 */
 virtual public void TableLayout(PdfPTable table, float[][] widths, float[] heights, int headerRows, int rowStart, PdfContentByte[] canvases) {
     foreach (IPdfPTableEvent eventa in events) {
         eventa.TableLayout(table, widths, heights, headerRows, rowStart, canvases);
     }
 }
コード例 #31
0
 public SummaryCell(PdfPTable table, string data)
     : base(table, data, Color.WHITE, 4)
 {
 }
コード例 #32
0
 /**
  * @see com.itextpdf.text.pdf.PdfPTableEventAfterSplit#afterSplitTable(com.itextpdf.text.pdf.PdfPTable, com.itextpdf.text.pdf.PdfPRow, int)
  * @since iText 5.4.3
  */
 virtual public void AfterSplitTable(PdfPTable table, PdfPRow startRow, int startIdx) {
     foreach (IPdfPTableEvent evente in events) {
         if (evente is IPdfPTableEventAfterSplit)
             ((IPdfPTableEventAfterSplit)evente).AfterSplitTable(table, startRow, startIdx);
     }
 }
コード例 #33
0
        private PdfPTable createTable(string serverName, double[] values)
        {
            // Document doc = new Document(PageSize.A4, 50, 50, 80, 50); // 設定PageSize, Margin, left, right, top, bottom
            // MemoryStream ms = new MemoryStream();
            // PdfWriter pw = PdfWriter.GetInstance(doc, ms);

            ////    字型設定
            // 在PDF檔案內容中要顯示中文,最重要的是字型設定,如果沒有正確設定中文字型,會造成中文無法顯示的問題。
            // 首先設定基本字型:kaiu.ttf 是作業系統系統提供的標楷體字型,IDENTITY_H 是指編碼(The Unicode encoding with horizontal writing),及是否要將字型嵌入PDF 檔中。
            // 再來針對基本字型做變化,例如Font Size、粗體斜體以及顏色等。當然你也可以採用其他中文字體字型。
            //BaseFont bfChinese = BaseFont.CreateFont("C:\\Windows\\Fonts\\kaiu.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            iTextSharp.text.Font ChFont       = new iTextSharp.text.Font(bfChinese, 12);
            iTextSharp.text.Font ChFont_green = new iTextSharp.text.Font(bfChinese, 40, iTextSharp.text.Font.NORMAL, BaseColor.GREEN);
            iTextSharp.text.Font ChFont_msg   = new iTextSharp.text.Font(bfChinese, 12, iTextSharp.text.Font.ITALIC, BaseColor.RED);



            // 產生表格 -- START
            // 建立4個欄位表格之相對寬度
            PdfPTable pt = new PdfPTable(new float[] { 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 });

            // 表格總寬
            pt.TotalWidth  = 500f;
            pt.LockedWidth = true;


            // 塞入資料 -- START
            // 設定表頭
            PdfPCell header = new PdfPCell(new Phrase(serverName, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.NORMAL)));

            header.Colspan             = 13;
            header.HorizontalAlignment = Element.ALIGN_CENTER;// 表頭內文置中
            header.BackgroundColor     = new iTextSharp.text.BaseColor(153, 217, 234);


            pt.AddCell(header);


            PdfPCell cell1 = new PdfPCell(new Phrase("Months", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.NORMAL)));

            cell1.BackgroundColor = new iTextSharp.text.BaseColor(153, 217, 234);
            pt.AddCell(cell1);


            for (int i = 1; i <= 12; i++)
            {
                PdfPCell cell = new PdfPCell(new Phrase(i.ToString(), new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10f, iTextSharp.text.Font.NORMAL)));
                cell.BackgroundColor     = new iTextSharp.text.BaseColor(153, 217, 234);
                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                pt.AddCell(cell);
            }

            pt.AddCell("Deduplication Rate");

            for (int i = 0; i < 12; i++)
            {
                PdfPCell cell = new PdfPCell(new Phrase(values[i].ToString(), new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10f, iTextSharp.text.Font.NORMAL)));

                cell.HorizontalAlignment = Element.ALIGN_CENTER;
                pt.AddCell(cell);
            }


            return(pt);
        }