Beispiel #1
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            string tableExtension = DropDownList1.SelectedValue.ToLower();

            //for show data
            con.Open();
            string sql = "SELECT * FROM apply" + tableExtension + " inner join dbbl,student  where apply" + tableExtension + ".mobile_no = dbbl.mobile_no and apply" + tableExtension + ".tx_id = dbbl.tx_id  and student.ROLL_NO=dbbl.hsc_roll";

            //SELECT * FROM `student` WHERE `BOARD_NAME`='RAJSHAHI' and `ROLL_NO`= '135323' and `PASS_YEAR`='2011'
            MySqlCommand cmd = new MySqlCommand(sql, con);


            MySqlDataReader reader = cmd.ExecuteReader();


            //intialize page size
            //  var doc1 = new Document(PageSize.A4);
            var doc1 = new Document(new Rectangle(595f, 250f));

            // var doc1 = new Document(new iTextSharp.text.PageSize.LETTER, 20f, 20f,0,0);


            // Setting Document properties e.g.
            // 1. Title
            // 2. Subject
            // 3. Keywords
            // 4. Creator
            // 5. Author
            // 6. Header
            doc1.AddTitle("Admit Card for Admission Test.");
            doc1.AddSubject("This is an Example Admit Card for Admission Test.");
            doc1.AddKeywords("Metadata, iTextSharp 5.4.4, Admit Card, JU");
            doc1.AddCreator("Proshanti Solution Ltd.");
            doc1.AddAuthor("Sayed Mohsin Reza");
            doc1.AddHeader("Nothing", "No Header");



            //use a variable to let my code fit across the page...

            string path = Server.MapPath("PDFs");

            PdfWriter writer = PdfWriter.GetInstance(doc1, new FileStream(path + "/Doc2.pdf", FileMode.Create));

            //calling watermarks

            /* for (int i = 5; i >= 0; i--)
             * {
             *   writer.PageEvent = new PDFWriterEvents("Institute of Information Technology, Jahangirnagar University", 10f, (i*100f), (i*75f), 30f);
             *
             * }
             */
            for (int i = 5; i >= 0; i--)
            {
                writer.PageEvent = new PDFWriterEvents("Institute of Information Technology, Jahangirnagar University", 10f, (i * 100f), 100, 30f);
            }


            // calling PDFFooter class to Include in document
            // writer.PageEvent = new PDFFooter();
            doc1.Open();
            while (reader.Read())
            {
                string serial   = reader.GetString(0).ToString();
                string name     = reader.GetString(12).ToString();
                string fname    = reader.GetString(13).ToString();
                string mname    = reader.GetString(14).ToString();
                string hsc_roll = reader.GetString(17).ToString();
                string imgpath  = reader.GetString(1).ToString() + "_" + reader.GetString(2).ToString() + ".jpg";



                //for image
                iTextSharp.text.Image gif = iTextSharp.text.Image.GetInstance(Server.MapPath("~/img/") + "julogo.GIF");
                gif.ScaleToFit(24f, 32f);
                gif.Alignment        = iTextSharp.text.Image.ALIGN_LEFT | iTextSharp.text.Image.TEXTWRAP;
                gif.IndentationRight = 9f;
                gif.SpacingAfter     = 9f;
                gif.Border           = Rectangle.BOX;

                gif.BorderColor = iTextSharp.text.BaseColor.YELLOW;

                gif.BorderWidth = 5f;

                doc1.Add(gif);
                //end of image


                // string fontpath = Environment.GetEnvironmentVariable("SystemRoot") + "\\fonts\\KINDEL.TTF";
                //for font
                string   fontpath = Server.MapPath("~/font/") + "times.ttf";
                BaseFont basefont = BaseFont.CreateFont(fontpath, BaseFont.IDENTITY_H, true);
                //for end of font
                //set font size

                Font font4     = new iTextSharp.text.Font(basefont, 4, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
                Font font4bold = new iTextSharp.text.Font(basefont, 4, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);

                Font font10bold = new iTextSharp.text.Font(basefont, 10, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);

                Font font8     = new iTextSharp.text.Font(basefont, 8, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
                Font font8bold = new iTextSharp.text.Font(basefont, 8, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);
                Font font6     = new iTextSharp.text.Font(basefont, 6, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
                Font font6bold = new iTextSharp.text.Font(basefont, 6, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLUE);

                Paragraph p  = new Paragraph("Jahangirnagar University", font10bold);
                Paragraph pe = new Paragraph("Admission Test 2013-14.", font8);

                doc1.Add(p);
                doc1.Add(pe);


                //setting unit Name A -Unit
                Paragraph p1 = new Paragraph(DropDownList1.SelectedValue + " - UNIT Admit Card", font8bold);
                p1.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
                doc1.Add(p1);


                //string date = DateTime.Now.Day.ToString();

                //for student image
                //Server.MapPath("~/Images/") +
                if (File.Exists(Server.MapPath("~/Images/") + imgpath))
                {
                    iTextSharp.text.Image studentpic = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Images/") + imgpath);
                    studentpic.ScaleToFit(80f, 60f);
                    studentpic.Alignment = iTextSharp.text.Image.ALIGN_RIGHT | iTextSharp.text.Image.TEXTWRAP;
                    //studentpic.IndentationLeft = 9f;
                    //studentpic.SpacingAfter = 9f;
                    studentpic.Border = Rectangle.BOX;

                    studentpic.BorderColor = iTextSharp.text.BaseColor.YELLOW;

                    studentpic.BorderWidth = 5f;

                    doc1.Add(studentpic);
                }
                else
                {
                    iTextSharp.text.Image studentpic = iTextSharp.text.Image.GetInstance(Server.MapPath("~/img/") + "defaultpic.png");
                    studentpic.ScaleToFit(80f, 60f);
                    studentpic.Alignment = iTextSharp.text.Image.ALIGN_RIGHT | iTextSharp.text.Image.TEXTWRAP;
                    //studentpic.IndentationLeft = 9f;
                    //studentpic.SpacingAfter = 9f;
                    studentpic.Border = Rectangle.BOX;

                    studentpic.BorderColor = iTextSharp.text.BaseColor.YELLOW;

                    studentpic.BorderWidth = 5f;

                    doc1.Add(studentpic);
                }

                //end of image



                Paragraph p3 = new Paragraph("Admission Test Roll No: " + serial, font6);
                p3.Alignment = iTextSharp.text.Image.ALIGN_LEFT;


                doc1.Add(p3);



                Paragraph p4 = new Paragraph("\nName :" + name.ToUpper() + " \nFather Name :" + fname.ToUpper() + " \nMother Name :" + mname.ToUpper(), font6);
                p4.Alignment = iTextSharp.text.Image.ALIGN_LEFT;
                doc1.Add(p4);

                string date = DateTime.Now.Day.ToString();

                /*
                 *          Paragraph p5 = new Paragraph(DateTime.Now.ToString(),font6bold);
                 *          p5.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
                 *          doc1.Add(p5);
                 */



                Paragraph p6 = new Paragraph("\nNotice : \n1. To give admission exam, An examiner will be take the following things.\n     a) Admit Card     b) HSC Admit Card     c) HSCRegistration Card\n", font6);
                p6.Alignment = iTextSharp.text.Image.ALIGN_LEFT;
                doc1.Add(p6);

                //dean sign
                iTextSharp.text.Image din = iTextSharp.text.Image.GetInstance(Server.MapPath("~/img/") + DropDownList1.SelectedValue + ".jpg");
                din.ScaleToFit(45f, 15f);
                din.Alignment = iTextSharp.text.Image.TEXTWRAP | iTextSharp.text.Image.ALIGN_RIGHT;
                //din.IndentationLeft = 15f;
                //din.SpacingAfter = 5f;
                din.Border      = Rectangle.BOX;
                din.BorderColor = iTextSharp.text.BaseColor.WHITE;

                din.BorderWidth = 6f;

                doc1.Add(din);

                //end of dean sign


                Paragraph p7 = new Paragraph("2. The Admission Exam Seat schedule will be published before exam on the following link: http://www.juniv.edu \n3. Admission Seat Schedule and Result can be found by Mobile. As Example: TYPE <JU " + DropDownList1.SelectedValue + " " + hsc_roll + "> and SEND TO <16321>\n4. There is no need to sign on this paper. ", font6);
                p7.Alignment = iTextSharp.text.Image.ALIGN_LEFT;
                doc1.Add(p7);
                //Paragraph p7 = new Paragraph("Service By: Institute of Information Technology, Jahangirnagar University.", font8);
                //p7.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
                //doc1.Add(p7);


                // Paragraph pic =new Paragraph();

                Paragraph dean = new Paragraph("\nSignature of Dean", font6);
                dean.Alignment = iTextSharp.text.Image.ALIGN_RIGHT;
                doc1.Add(dean);

                //doc1.NewPage();
            }
            reader.Close();
            con.Close();
            doc1.Close();
            //end show data
            Response.Redirect("~/PDFs/Doc2.pdf");
        }
        public MemoryStream GeneratePdfTemplate(List <MaterialDistributionNoteReportViewModel> data, DateTime date, string unitName)
        {
            BaseFont bf          = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
            BaseFont bf_bold     = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
            var      normal_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);
            var      bold_font   = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);

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

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

            cb.BeginText();

            cb.SetFontAndSize(bf, 8);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "PT DAN LIRIS", 15, 820, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "INDUSTRIAL & TRADING CO LTD", 15, 810, 0);

            cb.SetFontAndSize(bf_bold, 8);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "FM.FP-00-GG-15-002", 485, 815, 0);

            cb.SetFontAndSize(bf_bold, 14);
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "BON PENGANTAR GREIGE", 300, 785, 0);

            cb.SetFontAndSize(bf, 8);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "TANGGAL", 15, 760, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, ":", 70, 760, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, date.ToString("dd-MM-yyyy"), 80, 760, 0);

            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "BAGIAN", 15, 750, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, ":", 70, 750, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, unitName, 80, 750, 0);

            cb.EndText();

            PdfPTable table = new PdfPTable(10);
            PdfPCell  cell;

            table.TotalWidth = 565f;
            int rowsPerPage = 20;

            float[] widths = new float[] { 0.5f, 1.5f, 2f, 2f, 1.5f, 2.5f, 0.7f, 1.5f, 2f, 2.5f };
            table.SetWidths(widths);

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

            cell.Phrase = new Phrase("NO", bold_font);
            table.AddCell(cell);

            cell.Phrase = new Phrase("NO BON", bold_font);
            table.AddCell(cell);

            cell.Phrase = new Phrase("TIPE BON", bold_font);
            table.AddCell(cell);

            cell.Phrase = new Phrase("NO SPB", bold_font);
            table.AddCell(cell);

            cell.Phrase = new Phrase("NO SPP", bold_font);
            table.AddCell(cell);

            cell.Phrase = new Phrase("NAMA BARANG", bold_font);
            table.AddCell(cell);

            cell.Phrase = new Phrase("GRD", bold_font);
            table.AddCell(cell);

            cell.Phrase = new Phrase("PIECE", bold_font);
            table.AddCell(cell);

            cell.Phrase = new Phrase("METER", bold_font);
            table.AddCell(cell);

            cell.Phrase = new Phrase("ASAL", bold_font);
            table.AddCell(cell);

            int    Number = 1;
            double?TotalQuantity = 0, TotalReceivedLength = 0;

            int TotalRows = data.Count;

            foreach (var d in data)
            {
                cell = new PdfPCell()
                {
                    Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2
                };
                cell.Phrase = new Phrase(Number.ToString(), normal_font);
                table.AddCell(cell);

                cell.Phrase = new Phrase(d.No, normal_font);
                table.AddCell(cell);

                cell.Phrase = new Phrase(d.Type, normal_font);
                table.AddCell(cell);

                cell.Phrase = new Phrase(d.MaterialRequestNoteNo, normal_font);
                table.AddCell(cell);

                cell.Phrase = new Phrase(d.ProductionOrderNo, normal_font);
                table.AddCell(cell);

                cell = new PdfPCell()
                {
                    Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2
                };
                cell.Phrase = new Phrase(d.ProductName.Replace("GREIGE ", "", StringComparison.CurrentCultureIgnoreCase), normal_font);
                table.AddCell(cell);

                cell = new PdfPCell()
                {
                    Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2
                };
                cell.Phrase = new Phrase(d.Grade, normal_font);
                table.AddCell(cell);

                cell = new PdfPCell()
                {
                    Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2
                };
                cell.Phrase = new Phrase(string.Format("{0:n}", d.Quantity), normal_font);
                table.AddCell(cell);

                cell.Phrase = new Phrase(string.Format("{0:n}", d.Length), normal_font);
                table.AddCell(cell);

                cell = new PdfPCell()
                {
                    Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2
                };
                cell.Phrase = new Phrase(d.SupplierName, normal_font);
                table.AddCell(cell);

                TotalQuantity       += d.Quantity;
                TotalReceivedLength += d.Length;

                if (Number == TotalRows)
                {
                    cell = new PdfPCell()
                    {
                        Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE, Colspan = 7, Phrase = new Phrase("Jumlah", normal_font), Padding = 2
                    };
                    table.AddCell(cell);

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

                    cell.Phrase = new Phrase(string.Format("{0:n}", TotalQuantity), normal_font);
                    table.AddCell(cell);

                    cell.Phrase = new Phrase(string.Format("{0:n}", TotalReceivedLength), normal_font);
                    table.AddCell(cell);
                    table.AddCell(new Phrase("", normal_font));
                }

                if (Number % rowsPerPage == 0)
                {
                    if (Number == rowsPerPage)
                    {
                        table.WriteSelectedRows(0, -1, 15, 735, cb);
                    }
                    else
                    {
                        table.WriteSelectedRows(0, -1, 15, 815, cb);
                    }

                    for (var i = 0; i < rowsPerPage; i++)
                    {
                        table.DeleteLastRow();
                    }

                    if (Number != TotalRows)
                    {
                        document.NewPage();
                    }
                }

                Number++;
            }

            Number--;
            if (Number % rowsPerPage != 0)
            {
                if (Number < rowsPerPage)
                {
                    table.WriteSelectedRows(0, -1, 15, 735, cb);
                }
                else
                {
                    table.WriteSelectedRows(0, -1, 15, 815, cb);
                }
            }

            cb.BeginText();
            cb.SetTextMatrix(15, 23);

            cb.SetFontAndSize(bf, 8);
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Pengirim,", 130, 110, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "(.................................)", 130, 50, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Bag. Gd Material", 130, 35, 0);

            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Penerima,", 460, 110, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "(.................................)", 460, 50, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Bag. Produksi", 460, 35, 0);

            cb.EndText();

            document.Close();
            byte[] byteInfo = stream.ToArray();
            stream.Write(byteInfo, 0, byteInfo.Length);
            stream.Position = 0;
            return(stream);
        }
        private void xuatMat_xuat_Click(object sender, EventArgs e)
        {
            if (xuatMat_ten != null)
            {
                //    try
                //   {

                Document             The       = new Document(iTextSharp.text.PageSize.HALFLETTER);
                PdfWriter            TheWriter = PdfWriter.GetInstance(The, new FileStream($@"{xuatMat_duongdan.Text + xuatMat_ten.Text}.pdf", FileMode.Create));
                System.Drawing.Image img1      = global::QLDG.Properties.Resources.rsz_npl;
                System.Drawing.Image img2      = global::QLDG.Properties.Resources.Untitled;
                //System.Drawing.Image img2 = global::BM2.Properties.Resources._2x3;
                iTextSharp.text.Image text_img1 = iTextSharp.text.Image.GetInstance(img1, System.Drawing.Imaging.ImageFormat.Png);
                iTextSharp.text.Image text_img2 = iTextSharp.text.Image.GetInstance(img2, System.Drawing.Imaging.ImageFormat.Png);
                //iTextSharp.text.Image Info_img2 = iTextSharp.text.Image.GetInstance(img2, System.Drawing.Imaging.ImageFormat.Png);
                //Info_img2.SetAbsolutePosition(The.PageSize.Width - 280f - 60f,The.PageSize.Height - 40f - 190f );
                text_img1.SetAbsolutePosition(The.PageSize.Width - 280f - 60f, The.PageSize.Height - 10f - 75f);
                text_img2.SetAbsolutePosition(The.PageSize.Width - 120f - 60f, The.PageSize.Height - 290f - 75f);
                // The.Add(text_img);
                iTextSharp.text.Font f1        = FontFactory.GetFont(iTextSharp.text.Font.FontFamily.TIMES_ROMAN.ToString(), 25, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLUE);
                string               exeFile   = (new System.Uri(Assembly.GetEntryAssembly().CodeBase)).AbsolutePath;
                string               exeDir    = Path.GetDirectoryName(exeFile);
                string               fullPath0 = Path.Combine(exeDir, @"VietFontsWeb1_ttf\vuTimesBold.ttf");
                string               fullPath1 = Path.Combine(exeDir, @"VietFontsWeb1_ttf\vuTimes.ttf");
                BaseFont             bf0       = BaseFont.CreateFont(fullPath0, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                BaseFont             bf1       = BaseFont.CreateFont(fullPath1, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                iTextSharp.text.Font f2        = new iTextSharp.text.Font(bf0, 15, iTextSharp.text.Font.ITALIC, iTextSharp.text.BaseColor.RED);
                iTextSharp.text.Font f3        = new iTextSharp.text.Font(bf1, 10, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
                iTextSharp.text.Font f4        = new iTextSharp.text.Font(bf1, 8, iTextSharp.text.Font.ITALIC, iTextSharp.text.BaseColor.BLUE);
                iTextSharp.text.Font f5        = new iTextSharp.text.Font(bf1, 10, iTextSharp.text.Font.ITALIC, iTextSharp.text.BaseColor.ORANGE);
                Paragraph            p1        = new Paragraph("        LM_PROJECT.EC", f1);
                p1.Alignment = Element.ALIGN_CENTER;
                Paragraph p2 = new Paragraph($"     Họ tên độc giả: {TenDocGia}", f3);
                Paragraph p3 = new Paragraph($"     Ngày trả : {NgayGhiNhan.ToString("dd/MM/yyyy")}", f3);
                Paragraph p4 = new Paragraph($"     Tiền phạt kì này : {TienPhat.ToString()}", f3);
                Paragraph p8 = new Paragraph($"     Tổng nợ : {TongNo.ToString()}", f3);
                Paragraph p5 = new Paragraph($"Ghi chú: ", f5);
                Paragraph p6 = new Paragraph($"...................................................\n" +
                                             $"...................................................", f3);
                p2.Alignment = Element.ALIGN_LEFT;
                p3.Alignment = Element.ALIGN_LEFT;
                p4.Alignment = Element.ALIGN_LEFT;
                p8.Alignment = Element.ALIGN_LEFT;
                Paragraph Enter = new Paragraph("             ");
                Paragraph p7    = new Paragraph($"PHIẾU GHI NHẬN MẤT SÁCH - {MaDocGia}", f2);
                p7.Alignment = Element.ALIGN_CENTER;
                PdfPTable table = new PdfPTable(4);
                table.DefaultCell.Padding       = 3;
                table.DefaultCell.MinimumHeight = 20;
                table.WidthPercentage           = 100;
                table.HorizontalAlignment       = Element.ALIGN_CENTER;
                table.DefaultCell.BorderWidth   = 1;
                PdfPCell cellstt = new PdfPCell(new Phrase($"STT", f3));
                PdfPCell cellms  = new PdfPCell(new Phrase($"Mã sách", f3));
                PdfPCell cellgs  = new PdfPCell(new Phrase($"Giá sách ", f3));
                PdfPCell celltp  = new PdfPCell(new Phrase($"Tiền phạt", f3));
                cellstt.BackgroundColor = new BaseColor(178, 255, 178);
                cellms.BackgroundColor  = new BaseColor(178, 255, 178);
                cellgs.BackgroundColor  = new BaseColor(178, 255, 178);
                celltp.BackgroundColor  = new BaseColor(178, 255, 178);
                table.AddCell(cellstt);
                table.AddCell(cellms);
                table.AddCell(cellgs);
                table.AddCell(celltp);
                int i = 1;
                //  var dss = from z in qltv.MuonSaches where z.MaDocGia == MaDocGia && z.NgayMuon == NgayMuon select z;
                for (i = 1; i <= Dsss.Items.Count; i++)
                {
                    table.AddCell(new Phrase((i).ToString(), f3));
                    table.AddCell(new Phrase(Dsss.Items[i - 1].SubItems[0].Text, f3));
                    table.AddCell(new Phrase(Dsss.Items[i - 1].SubItems[1].Text, f3));
                    table.AddCell(new Phrase(Dsss.Items[i - 1].SubItems[2].Text, f3));
                }
                // MessageBox.Show($"{i.ToString()}");
                while (i < 6)
                {
                    table.AddCell(new Phrase((i).ToString(), f3));
                    table.AddCell(new Phrase("    ", f3));
                    table.AddCell(new Phrase("    ", f3));
                    table.AddCell(new Phrase("    ", f3));
                    i++;
                }
                The.Open();
                The.Add(p1);
                The.Add(text_img1);
                The.Add(p7);
                The.Add(Enter);
                The.Add(p2);
                The.Add(p3);
                The.Add(p4);
                The.Add(p8);
                The.Add(Enter);
                The.Add(table);
                The.Add(Enter);
                The.Add(p5);
                The.Add(p6);
                The.Add(text_img2);
                The.Close();
                TheWriter.Close();
                MessageBox.Show("Thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                //  }
                //   catch
                //  {
                //      MessageBox.Show("Thất bại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                // }
            }
            else
            {
                MessageBox.Show("Thất bại", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Beispiel #4
0
        public async Task <ConvertResult> Png2PdfAAsync(List <String> sources, String target)
        {
            var images = await CompressImagesAsync(sources);

            var result = this.CreateFinalTiffFile(images, target.Replace(".pdf", ".tif"));

            if (!result.Success)
            {
                _logger.LogError("create final tiff failed | {0}", result.Message);
                DeleteFiles(images);
                return(result);
            }

            var dict       = new Dictionary <String, String>();
            var compressOk = true;

            sources.ForEach(s => {
                if (images.Contains(s))
                {
                    _logger.LogError("source file not exist | {0}", s);
                    compressOk = false;
                }
            });

            images.ForEach(s => {
                var info = new FileInfo(s);
                if (!info.Exists)
                {
                    _logger.LogError("file not exist - {0}", info.FullName);
                    compressOk = false;
                }
                else if (info.Length < 0.5 * 1027)
                {
                    _logger.LogError("too small length - {0}", info.FullName);
                    compressOk = false;
                }
            });

            if (compressOk)
            {
                var document = new Document();
                document.SetMargins(0, 0, 0, 0);

                var writer = PdfAWriter.GetInstance(document, new FileStream(target, FileMode.Create), PdfAConformanceLevel.PDF_A_1B);
                writer.CreateXmpMetadata();
                document.Open();

                images.ForEach(i => {
                    // http://stackoverflow.com/questions/19256275/fitting-image-into-pdf-using-itext
                    var img = Image.GetInstance(i);
                    img.SetAbsolutePosition(0f, 0f);

                    var dpiX = img.DpiX;
                    var dpiY = img.DpiY;

                    var width  = PixelsToPoints(img.Width, dpiX);
                    var height = PixelsToPoints(img.Height, dpiY);

                    var sizeOk = document.SetPageSize(new Rectangle(0, 0, width, height));
                    if (sizeOk)
                    {
                        var scaler = (document.PageSize.Width / img.Width) * 100;
                        img.ScalePercent(scaler);
                    }

                    document.NewPage();

                    // Append ocr content first.
                    if (dict.Keys.Contains(i))
                    {
                        var value = dict[i];
                        var text  = new Chunk(value);
                        text.setLineHeight(0);
                        text.SetCharacterSpacing(0);
                        text.SetWordSpacing(0);

                        var under = writer.DirectContentUnder;
                        var cb    = new PdfContentByte(writer);
                        cb.BeginText();
                        cb.SetFontAndSize(BaseFont.CreateFont(), 8f);
                        cb.ShowText(value);
                        cb.EndText();
                        under.Add(cb);
                    }

                    // Append image above of ocr content.
                    document.Add(img);
                });

                document.Close();
                writer.Close();
                DeleteFiles(images);
                return(new ConvertResult {
                    Success = true,
                    Result = target,
                    Message = ""
                });
            }
            else
            {
                _logger.LogError("convert to pdf failed ...");
                DeleteFiles(images);
                return(new ConvertResult {
                    Success = false,
                    Result = "",
                    Message = ""
                });
            }
        }
Beispiel #5
0
        /// <summary>
        /// Generowanie testu *.pdf z pytan wczytanych z Excela
        /// </summary>
        /// <param name="listaPytan">Lista obiektow typu Pytanie wczytana z Excela</param>
        /// <param name="id">id jest wartoscia z bazy danych</param>
        /// <param name="nazwaTestu">skor dla id testu</param>
        public static void GenerateTest(List <Pytanie> listaPytan, int id, string nazwaTestu, int iloscPytan)
        {
            // moje proby i wypociny
            Document doc = new Document(PageSize.A4);

            BaseFont arial = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

            iTextSharp.text.Font f_15_bold   = new iTextSharp.text.Font(arial, 15, iTextSharp.text.Font.BOLD);
            iTextSharp.text.Font f_12_normal = new iTextSharp.text.Font(arial, 12, iTextSharp.text.Font.NORMAL);
            iTextSharp.text.Font f_12_bold   = new iTextSharp.text.Font(arial, 12, iTextSharp.text.Font.BOLD);

            FileStream os = new FileStream("..\\..\\..\\Files\\" + nazwaTestu.ToString() + '_' + id + ".pdf", FileMode.Create);

            using (os)
            {
                PdfWriter.GetInstance(doc, os);
                doc.Open();

                // Informacje o teœcie, nazwa testu, data wygenerowania testu (prawy górny róg, w ramce)
                PdfPTable table1 = new PdfPTable(1);
                PdfPCell  cel1   = new PdfPCell(new Phrase("Test: " + nazwaTestu.ToString(), f_15_bold));
                PdfPCell  cel2   = new PdfPCell(new Phrase("id Testu: " + id, f_15_bold));
                PdfPCell  cel3   = new PdfPCell(new Phrase("Data: " + DateTime.Now.ToShortDateString(), f_15_bold));
                cel1.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
                cel2.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
                cel3.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
                cel1.Border = iTextSharp.text.Rectangle.NO_BORDER;
                cel2.Border = iTextSharp.text.Rectangle.NO_BORDER;
                cel3.Border = iTextSharp.text.Rectangle.NO_BORDER;
                table1.AddCell(cel1);
                table1.AddCell(cel2);
                table1.AddCell(cel3);
                table1.SpacingAfter  = 20;
                table1.SpacingBefore = 10;
                // ¿ety to wszystko by³o ³adnie w ramce
                PdfPTable table2 = new PdfPTable(1);
                table2.AddCell(table1);
                table2.HorizontalAlignment = Element.ALIGN_RIGHT;
                table2.WidthPercentage     = 40;     // jak tytu³ testu bêdzie za du¿y to trzeba zwiêkszyæ
                //table2.WidthPercentage = 90;
                doc.Add(table2);


                Paragraph pytania = new Paragraph();
                for (int i = 0; i < iloscPytan; i++)
                {
                    pytania.Add(new Phrase(i + 1 + ". " + listaPytan[i].GetTresc().ToString() + "\n", f_12_bold)); // numer i tresc pytania

                    int unicode = 97;                                                                              // do listowania odpowiedzi a,b,d,c
                    for (int j = 0; j < listaPytan[i].listaOdpowiedzi.Count(); j++)
                    {
                        char character = (char)unicode;
                        pytania.Add(new Phrase("           " + character.ToString() + ": " + listaPytan[i].listaOdpowiedzi[j].GetTrescOdpowiedz().ToString() + "\n", f_12_normal));   // odpowiedzi
                        unicode++;
                    }
                }
                pytania.Alignment = Element.ALIGN_JUSTIFIED;
                doc.Add(pytania);

                doc.Close();

                // Open the document automatically
                //System.Diagnostics.Process.Start(@"Tescik.pdf");
                System.Diagnostics.Process.Start("..\\..\\..\\Files\\" + nazwaTestu.ToString() + '_' + id + ".pdf");
            }
        }
Beispiel #6
0
    protected void Page_Load(object sender, EventArgs e)
    {
        var incidentId = Convert.ToInt64(Request.QueryString["id"]);
        var companyId  = Convert.ToInt32(Request.QueryString["companyId"]);
        var company    = new Company(companyId);
        var res        = ActionResult.NoAction;
        var user       = HttpContext.Current.Session["User"] as ApplicationUser;
        var dictionary = HttpContext.Current.Session["Dictionary"] as Dictionary <string, string>;
        var incident   = Incident.GetById(incidentId, user.CompanyId);
        var path       = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            path = string.Format(CultureInfo.InvariantCulture, @"{0}\", path);
        }

        var formatedDescription = ToolsPdf.NormalizeFileName(incident.Description);

        var fileName = string.Format(
            CultureInfo.InvariantCulture,
            @"{0}_{1}_Data_{2:yyyyMMddhhmmss}.pdf",
            dictionary["Item_Incident"],
            formatedDescription,
            DateTime.Now);

        // FONTS
        var pathFonts = HttpContext.Current.Request.PhysicalApplicationPath;

        if (!path.EndsWith(@"\", StringComparison.OrdinalIgnoreCase))
        {
            pathFonts = string.Format(CultureInfo.InstalledUICulture, @"{0}\", pathFonts);
        }

        this.headerFont = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        this.arial      = BaseFont.CreateFont(string.Format(CultureInfo.InvariantCulture, @"{0}fonts\ARIAL.TTF", pathFonts), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

        string type         = string.Empty;
        string origin       = string.Empty;
        string originSufix  = string.Empty;
        string reporterType = string.Empty;
        string reporter     = string.Empty;

        if (incident.Origin == 1)
        {
            origin = dictionary["Item_Incident_Origin1"];
        }
        if (incident.Origin == 2)
        {
            origin = dictionary["Item_Incident_Origin2"];
        }
        if (incident.Origin == 3)
        {
            origin = dictionary["Item_Incident_Origin3"];
        }

        if (incident.Department.Id > 0)
        {
            reporterType = dictionary["Item_Incident_Origin1"];
            reporter     = Department.ById(incident.Department.Id, incident.CompanyId).Description;
        }
        else if (incident.Provider.Id > 0)
        {
            reporterType = dictionary["Item_Incident_Origin2"];
            reporter     = Provider.ById(incident.Provider.Id, incident.CompanyId).Description;
        }
        else if (incident.Customer.Id > 0)
        {
            reporterType = dictionary["Item_Incident_Origin3"];
            reporter     = Customer.ById(incident.Customer.Id, incident.CompanyId).Description;
        }

        string status = string.Empty;

        var document = new iTextSharp.text.Document(PageSize.A4, 30, 30, 65, 55);

        var writer           = PdfWriter.GetInstance(document, new FileStream(Request.PhysicalApplicationPath + "\\Temp\\" + fileName, FileMode.Create));
        var pageEventHandler = new TwoColumnHeaderFooter
        {
            CompanyLogo = string.Format(CultureInfo.InvariantCulture, @"{0}\images\logos\{1}.jpg", path, companyId),
            IssusLogo   = string.Format(CultureInfo.InvariantCulture, "{0}issus.png", path),
            Date        = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", DateTime.Now),
            CreatedBy   = user.UserName,
            CompanyId   = incident.CompanyId,
            CompanyName = company.Name,
            Title       = dictionary["Item_Incident"]
        };

        pageEventHandler.Titles = new List <string>
        {
            dictionary["Item_IncidentAction"]
        };

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

        var table = new PdfPTable(4)
        {
            WidthPercentage     = 100,
            HorizontalAlignment = 0
        };

        table.SetWidths(new float[] { 15f, 30f, 15f, 30f });

        var borderNone  = Rectangle.NO_BORDER;
        var borderSides = Rectangle.RIGHT_BORDER + Rectangle.LEFT_BORDER;
        var borderAll   = Rectangle.RIGHT_BORDER + Rectangle.TOP_BORDER + Rectangle.LEFT_BORDER + Rectangle.BOTTOM_BORDER;
        var borderTBL   = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER;
        var borderTBR   = Rectangle.TOP_BORDER + Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER;
        var borderBL    = Rectangle.BOTTOM_BORDER + Rectangle.LEFT_BORDER;
        var borderBR    = Rectangle.BOTTOM_BORDER + Rectangle.RIGHT_BORDER;

        var alignLeft  = Element.ALIGN_LEFT;
        var alignRight = Element.ALIGN_RIGHT;

        var labelFont = new Font(this.arial, 10, Font.NORMAL, BaseColor.DARK_GRAY);
        var valueFont = new Font(this.arial, 10, Font.NORMAL, BaseColor.BLACK);

        // Descripción
        table.AddCell(LabelCell(dictionary["Item_Incident"], Rectangle.NO_BORDER));
        table.AddCell(ValueCell(incident.Code.ToString() + " - " + incident.Description, borderNone, alignLeft, 3));

        // Reportador
        if (incident.Origin != 4)
        {
            table.AddCell(LabelCell(dictionary["Item_IncidentAction_Label_Reporter"], Rectangle.NO_BORDER));
            table.AddCell(ValueCell(reporterType + " (" + reporter + ")", borderNone, alignLeft, 3));
        }

        // WhatHappend
        table.AddCell(SeparationRow(4));
        table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_WhatHappened"]));
        table.AddCell(TextAreaCell(Environment.NewLine + incident.WhatHappened, borderSides, alignLeft, 4));
        table.AddCell(BlankRow(4));
        table.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + incident.WhatHappenedBy.FullName, borderBL, alignLeft, 2));
        table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_Date"], incident.WhatHappenedOn), borderBR, alignRight, 2));

        // Causes
        table.AddCell(SeparationRow(4));
        table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Causes"]));
        table.AddCell(TextAreaCell(Environment.NewLine + incident.Causes, borderSides, alignLeft, 4));
        table.AddCell(BlankRow(4));
        table.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + incident.CausesBy.FullName, borderBL, alignLeft, 2));
        table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_Date"], incident.CausesOn), borderBR, alignRight, 2));

        // Actions
        table.AddCell(SeparationRow(4));
        table.AddCell(TitleCell(dictionary["Item_Incident_Label_Actions"]));
        table.AddCell(TextAreaCell(Environment.NewLine + incident.Actions, borderSides, alignLeft, 4));
        table.AddCell(BlankRow(4));
        table.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + incident.ActionsBy.FullName, borderBL, alignLeft, 2));
        table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_DateExecution"], incident.ActionsOn), borderBR, alignRight, 2));

        // Close
        table.AddCell(SeparationRow(4));
        table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Close"]));
        table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1}", dictionary["Item_IncidentAction_Field_Responsible"], incident.ClosedBy.FullName), borderTBL, alignLeft, 2));
        table.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1:dd/MM/yyyy}", dictionary["Common_DateClose"], incident.ClosedOn), borderTBR, alignRight, 2));

        // Notes
        table.AddCell(SeparationRow(4));
        table.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Notes"]));
        table.AddCell(TextAreaCell(Environment.NewLine + incident.Notes, borderAll, alignLeft, 4));

        document.Add(table);

        if (user.HasGrantToRead(ApplicationGrant.IncidentActions))
        {
            // Añadir posible acción
            var action = IncidentAction.ByIncidentId(incident.Id, companyId);
            if (action.Id > 0)
            {
                var tableAction = new PdfPTable(4)
                {
                    WidthPercentage     = 100,
                    HorizontalAlignment = 0
                };

                tableAction.SetWidths(new float[] { 15f, 30f, 15f, 30f });

                // Descripción
                var headerFont = new Font(this.arial, 15, Font.NORMAL, BaseColor.BLACK);
                tableAction.AddCell(new PdfPCell(new Phrase(dictionary["Item_Incident_PDF_ActionPageTitle"], headerFont))
                {
                    Colspan             = 4,
                    Border              = ToolsPdf.BorderBottom,
                    HorizontalAlignment = Rectangle.ALIGN_CENTER
                });
                tableAction.AddCell(LabelCell(dictionary["Item_IncidentAction_Label_Description"], Rectangle.NO_BORDER));
                tableAction.AddCell(ValueCell(action.Description, borderNone, alignLeft, 3));

                // WhatHappend
                tableAction.AddCell(SeparationRow(4));
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_WhatHappened"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.WhatHappened, borderSides, alignLeft, 4));
                tableAction.AddCell(BlankRow(4));
                tableAction.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + action.WhatHappenedBy.FullName, borderBL, alignLeft, 2));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1:dd/MM/yyyy}", dictionary["Common_Date"], action.WhatHappenedOn), borderBR, alignRight, 2));

                // Causes
                var causesFullName = string.Empty;
                var causesDate     = string.Empty;
                if (action.CausesBy != null)
                {
                    causesFullName = action.CausesBy.FullName;
                    causesDate     = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.CausesOn);
                }

                tableAction.AddCell(SeparationRow(4));
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Causes"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Causes, borderSides, alignLeft, 4));
                tableAction.AddCell(BlankRow(4));
                tableAction.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + causesFullName, borderBL, alignLeft, 2));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1}", dictionary["Common_Date"], causesDate), borderBR, alignRight, 2));

                // Actions
                var actionFullName = string.Empty;
                var actionDate     = string.Empty;
                if (action.ActionsBy != null)
                {
                    actionFullName = action.ActionsBy.FullName;
                    actionDate     = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.ActionsOn);
                }

                tableAction.AddCell(SeparationRow(4));
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Actions"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Actions, borderSides, alignLeft, 4));
                tableAction.AddCell(BlankRow(4));
                tableAction.AddCell(TextAreaCell(dictionary["Item_IncidentAction_Field_Responsible"] + ": " + actionFullName, borderBL, alignLeft, 2));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "{0}: {1}", dictionary["Common_DateExecution"], actionDate), borderBR, alignRight, 2));

                // Monitoring
                tableAction.AddCell(SeparationRow(4));
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Monitoring"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Monitoring, borderAll, alignLeft, 4));

                // Close
                var closedFullName = string.Empty;
                var closedDate     = string.Empty;
                if (action.ClosedBy != null)
                {
                    closedFullName = action.ClosedBy.FullName;
                    closedDate     = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", action.ClosedOn);
                }

                tableAction.AddCell(SeparationRow(4));
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Close"]));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1}", dictionary["Item_IncidentAction_Field_Responsible"], closedFullName), borderTBL, alignLeft, 2));
                tableAction.AddCell(TextAreaCell(string.Format(CultureInfo.InvariantCulture, "\n{0}: {1}", dictionary["Common_DateClose"], closedDate), borderTBR, alignRight, 2));

                // Notes
                tableAction.AddCell(SeparationRow(4));
                tableAction.AddCell(TitleCell(dictionary["Item_IncidentAction_Field_Notes"]));
                tableAction.AddCell(TextAreaCell(Environment.NewLine + action.Notes, borderAll, alignLeft, 4));

                document.NewPage();
                document.Add(tableAction);
            }
        }

        // Costes
        var costs = IncidentCost.AllCosts(incidentId, companyId);

        if (costs.Count > 0)
        {
            var times           = new Font(arial, 8, Font.NORMAL, BaseColor.BLACK);
            var fontSummary     = new Font(arial, 9, Font.BOLD, BaseColor.BLACK);
            var headerFontFinal = new Font(headerFont, 9, Font.NORMAL, BaseColor.BLACK);
            var tableCosts      = new PdfPTable(5)
            {
                WidthPercentage     = 100,
                HorizontalAlignment = 1,
                SpacingBefore       = 20f,
                SpacingAfter        = 30f
            };

            tableCosts.SetWidths(new float[] { 35f, 10f, 10f, 10f, 20f });

            tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Description"]));
            tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Amount"]));
            tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Quantity"]));
            tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_Total"]));
            tableCosts.AddCell(ToolsPdf.HeaderCell(dictionary["Item_IncidentCost_Header_ReportedBy"]));

            decimal total           = 0;
            decimal totalIncidencia = 0;
            decimal totalAccion     = 0;
            int     cont            = 0;
            int     contIncidencia  = 0;
            int     contAccion      = 0;
            foreach (var cost in costs.Where(c => c.Source == "I"))
            {
                tableCosts.AddCell(ToolsPdf.DataCell(cost.Description, times));
                tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Amount, times));
                tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Quantity, times));
                tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Quantity * cost.Amount, times));
                tableCosts.AddCell(ToolsPdf.DataCellCenter(cost.Responsible.FullName, times));
                total           += cost.Amount * cost.Quantity;
                totalIncidencia += cost.Amount * cost.Quantity;
                cont++;
                contIncidencia++;
            }

            if (user.HasGrantToRead(ApplicationGrant.IncidentActions))
            {
                tableCosts.AddCell(new PdfPCell(new Phrase(string.Format(
                                                               CultureInfo.InvariantCulture,
                                                               @"{0} {2}: {1}",
                                                               dictionary["Common_RegisterCount"],
                                                               contIncidencia,
                                                               dictionary["Item_Incident"]), times))
                {
                    Border          = Rectangle.TOP_BORDER,
                    BackgroundColor = ToolsPdf.SummaryBackgroundColor,
                    Padding         = 6f,
                    PaddingTop      = 4f,
                    Colspan         = 2
                });

                tableCosts.AddCell(new PdfPCell(new Phrase(dictionary["Common_Total"], times))
                {
                    Border              = Rectangle.TOP_BORDER,
                    BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
                    Padding             = 6f,
                    PaddingTop          = 4f,
                    Colspan             = 1,
                    HorizontalAlignment = Rectangle.ALIGN_RIGHT,
                });

                tableCosts.AddCell(new PdfPCell(new Phrase(Tools.PdfMoneyFormat(totalIncidencia), times))
                {
                    Border              = Rectangle.TOP_BORDER,
                    BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
                    Padding             = 6f,
                    PaddingTop          = 4f,
                    Colspan             = 1,
                    HorizontalAlignment = Rectangle.ALIGN_RIGHT,
                });

                tableCosts.AddCell(new PdfPCell(new Phrase(string.Format(string.Empty, times)))
                {
                    Border          = Rectangle.TOP_BORDER,
                    BackgroundColor = ToolsPdf.SummaryBackgroundColor,
                    Padding         = 6f,
                    PaddingTop      = 4f,
                    Colspan         = 1
                });
            }

            if (user.HasGrantToRead(ApplicationGrant.IncidentActions))
            {
                // Acciones
                foreach (var cost in costs.Where(c => c.Source == "A"))
                {
                    tableCosts.AddCell(ToolsPdf.DataCell(cost.Description, times));
                    tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Amount, times));
                    tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Quantity, times));
                    tableCosts.AddCell(ToolsPdf.DataCellMoney(cost.Quantity * cost.Amount, times));
                    tableCosts.AddCell(ToolsPdf.DataCellCenter(cost.Responsible.FullName, times));
                    total      += cost.Amount * cost.Quantity;
                    totalAccion = cost.Amount * cost.Quantity;
                    cont++;
                    contAccion++;
                }

                tableCosts.AddCell(new PdfPCell(new Phrase(string.Format(
                                                               CultureInfo.InvariantCulture,
                                                               @"{0} {2}: {1}",
                                                               dictionary["Common_RegisterCount"],
                                                               contAccion,
                                                               dictionary["Item_IncidentAction"]), times))
                {
                    Border          = Rectangle.TOP_BORDER,
                    BackgroundColor = ToolsPdf.SummaryBackgroundColor,
                    Padding         = 6f,
                    PaddingTop      = 4f,
                    Colspan         = 2
                });

                tableCosts.AddCell(new PdfPCell(new Phrase(dictionary["Common_Total"], times))
                {
                    Border              = Rectangle.TOP_BORDER,
                    BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
                    Padding             = 6f,
                    PaddingTop          = 4f,
                    Colspan             = 1,
                    HorizontalAlignment = Rectangle.ALIGN_RIGHT
                });

                tableCosts.AddCell(new PdfPCell(new Phrase(Tools.PdfMoneyFormat(totalAccion), times))
                {
                    Border              = Rectangle.TOP_BORDER,
                    BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
                    Padding             = 6f,
                    PaddingTop          = 4f,
                    Colspan             = 1,
                    HorizontalAlignment = Rectangle.ALIGN_RIGHT,
                });

                tableCosts.AddCell(new PdfPCell(new Phrase(string.Format(string.Empty, times)))
                {
                    Border          = Rectangle.TOP_BORDER,
                    BackgroundColor = ToolsPdf.SummaryBackgroundColor,
                    Padding         = 6f,
                    PaddingTop      = 4f,
                    Colspan         = 1
                });
            }

            // resumen
            tableCosts.AddCell(new PdfPCell(new Phrase(string.Format(
                                                           CultureInfo.InvariantCulture,
                                                           @"{0}: {1}",
                                                           dictionary["Common_RegisterCount"],
                                                           cont), fontSummary))
            {
                Border          = Rectangle.TOP_BORDER,
                BackgroundColor = ToolsPdf.SummaryBackgroundColor,
                Padding         = 6f,
                PaddingTop      = 4f,
                Colspan         = 2
            });

            tableCosts.AddCell(new PdfPCell(new Phrase(dictionary["Common_Total"], fontSummary))
            {
                Border              = Rectangle.TOP_BORDER,
                BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                Colspan             = 1,
                HorizontalAlignment = Rectangle.ALIGN_RIGHT
            });

            tableCosts.AddCell(new PdfPCell(new Phrase(Tools.PdfMoneyFormat(total), fontSummary))
            {
                Border              = Rectangle.TOP_BORDER,
                BackgroundColor     = ToolsPdf.SummaryBackgroundColor,
                Padding             = 6f,
                PaddingTop          = 4f,
                Colspan             = 1,
                HorizontalAlignment = Rectangle.ALIGN_RIGHT,
            });

            tableCosts.AddCell(new PdfPCell(new Phrase(string.Format(string.Empty, fontSummary)))
            {
                Border          = Rectangle.TOP_BORDER,
                BackgroundColor = ToolsPdf.SummaryBackgroundColor,
                Padding         = 6f,
                PaddingTop      = 4f,
                Colspan         = 1
            });

            document.SetPageSize(PageSize.A4.Rotate());
            document.NewPage();
            document.Add(tableCosts);
        }

        document.Close();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("Content-Disposition", "inline;filename=Incidencia.pdf");
        Response.ContentType = "application/pdf";
        Response.WriteFile(Request.PhysicalApplicationPath + "\\Temp\\" + fileName);
        Response.Flush();
        Response.Clear();
    }
Beispiel #7
0
        public static void AddAddresseBlockSeqence(string file, int startBeforePage, int step, bool doublesided, List <Addressee> roll, int x, int y, bool replaceSource) //llx:345 lly:550 defaults
        {
            using (var ms = new MemoryStream())
            {
                using (var doc = new Document(iTextSharp.text.PageSize.A4))
                {
                    var reader = new PdfReader(file);
                    var writer = PdfWriter.GetInstance(doc, ms);
                    writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_5);
                    string ttf      = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "TIMES.TTF");
                    var    baseFont = BaseFont.CreateFont(ttf, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                    var    timesN   = new Font(baseFont, 9, Font.NORMAL);
                    var    timesB   = new Font(baseFont, 9, Font.BOLD);

                    doc.Open();
                    var cb = writer.DirectContent;
                    int n  = 0;
                    for (int i = startBeforePage; i <= reader.NumberOfPages; i++)
                    {
                        if (startBeforePage > 1)
                        {
                            for (int j = 1; j <= startBeforePage; j++)
                            {
                                cb.AddTemplate(writer.GetImportedPage(reader, j), 0, 0);
                                doc.NewPage();
                            }
                        }

                        if (roll[n].Barcode != null && roll[n].Barcode != "")
                        {
                            var bc = new BarcodeInter25()
                            {
                                Code = roll[n].Barcode
                            };
                            var bc_image = bc.CreateImageWithBarcode(cb, BaseColor.BLACK, BaseColor.BLACK);

                            bc_image.SetAbsolutePosition(x + 10, y + 115);
                            bc_image.ScalePercent(117F);
                            cb.AddImage(bc_image);
                        }

                        var ct = new ColumnText(cb);
                        ct.SetSimpleColumn(new Rectangle(x, y, x + 205, y + 115));
                        ct.AddElement(new Paragraph("Кому: " + roll[n].Name, timesN));
                        ct.AddElement(new Paragraph("Куда: " + roll[n].Address, timesN));
                        ct.Go();

                        cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 15); //llx:345 lly:550
                        if (roll[n].Index != 0)
                        {
                            cb.BeginText();
                            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, roll[n].Index.ToString(), x + 120, y + 130, 0);
                            cb.EndText();
                        }
                        cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 5);
                        cb.BeginText();
                        cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, (n + 1).ToString(), x + 120, y + 120, 0);
                        cb.EndText();
                        doc.NewPage();
                        if (doublesided)
                        {
                            doc.Add(new Chunk());
                            doc.NewPage();
                        }
                        for (int j = 0; j < step; j++)
                        {
                            cb.AddTemplate(writer.GetImportedPage(reader, i), 0, 0);
                            doc.NewPage();
                        }
                        n++;
                    }
                }
                ms.Flush();
                if (replaceSource)
                {
                    File.WriteAllBytes(file, ms.ToArray());
                }
                else
                {
                    File.WriteAllBytes(file.Insert(file.Length - 4, "_out"), ms.ToArray());
                }
            }
        }
Beispiel #8
0
        /// <summary>
        /// 如果为西文,则直接使用默认字体。
        /// </summary>
        /// <param name="style"></param>
        /// <param name="text"></param>
        /// <returns></returns>
        public static iTextSharp.text.Font GetFont(fyiReporting.RDL.StyleInfo style, string text)
        {
            string fontName = TextUtility.GetFontName(style.FontFamily);

            iTextSharp.text.Font font = null;

            if (fontName.IndexOf(".") > 0)
            {
                BaseFont baseFT = null;

                if (baseFonts.ContainsKey(fontName))
                {
                    baseFT = baseFonts[fontName];

                    if (baseFT != null)
                    {
                        font = new iTextSharp.text.Font(baseFT);
                    }
                    else
                    {
                        font = iTextSharp.text.FontFactory.GetFont("Helvetica");
                    }
                }
                else
                {
                    string windir = System.Environment.GetEnvironmentVariable("windir");
                    string path   = Path.Combine(windir, "Fonts");
                    path = Path.Combine(path, fontName);

                    if (File.Exists(path))
                    {
                        try
                        {
                            baseFT = BaseFont.CreateFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                        }
                        catch
                        {
                            //
                        }
                    }

                    if (baseFT == null)
                    {
                        try
                        {
                            baseFT = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                        }
                        catch
                        {
                        }
                    }

                    if (baseFT != null)
                    {
                        baseFonts.Add(fontName, baseFT);
                        font = new iTextSharp.text.Font(baseFT);
                    }
                    else
                    {
                        font = iTextSharp.text.FontFactory.GetFont("Helvetica");
                        baseFonts.Add(fontName, null);
                    }
                }
            }
            else
            {
                font = iTextSharp.text.FontFactory.GetFont(fontName);
            }

            font.Color = new iTextSharp.text.Color(style.Color);
            font.Size  = style.FontSize;

            if (style.IsFontBold())
            {
                font.IsBold();
            }

            if (style.FontStyle == FontStyleEnum.Italic)
            {
                font.IsItalic();
            }

            if (style.TextDecoration == TextDecorationEnum.Underline)
            {
                font.IsUnderlined();
            }

            return(font);
        }
 public static BaseFont GetBaseFont()
 {
     return(BaseFont.CreateFont(PublicMethods.map_path(FontAddress), BaseFont.IDENTITY_H, true, true));
 }
Beispiel #10
0
        public void ExportToBoxSheet(string path, Dictionary <string, List <ComboBox> > cb_dic, List <CheckBox> cb_list, CheckBox WASH_cb, List <CheckBox> gradreq_cbs)
        {
            PdfReader  reader  = new PdfReader("boxsheet_flat.pdf");
            PdfStamper stamper = new PdfStamper(reader, new FileStream(path, FileMode.Create));

            BaseFont       bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
            PdfContentByte cb = stamper.GetOverContent(1);

            cb.SetColorFill(BaseColor.DARK_GRAY);

            Font font = new Font(bf, 7);

            //All of the text boxes
            ColumnText ct;

            foreach (string key in cb_dic.Keys)
            {
                if (box_locs.Keys.Contains(key))
                {
                    for (int i = 0; i < cb_dic[key].Count; i++)
                    {
                        ct = new ColumnText(cb);
                        ct.SetSimpleColumn(
                            new Phrase(cb_dic[key][i].Text, font),
                            box_locs[key][i, 0], box_locs[key][i, 1], box_locs[key][i, 2], box_locs[key][i, 3], 8, key.Equals("PP") ? Element.ALIGN_LEFT : Element.ALIGN_CENTER);
                        ct.Go();
                    }
                }
            }

            font = new Font(bf, 26);

            //The "check" boxes
            //Had to use x instead of ✓ because it's a unicode character and this is easier

            //Washington State History checkbox
            if (WASH_cb.Checked)
            {
                ct = new ColumnText(cb);
                ct.SetSimpleColumn(
                    new Phrase("x", font),
                    535, 549, 580, 568, 8, Element.ALIGN_CENTER);
                ct.Go();
            }

            //CTE checkboxes
            for (int i = 0; i < 2; i++)
            {
                if (cb_list[i].Checked)
                {
                    ct = new ColumnText(cb);
                    ct.SetSimpleColumn(
                        new Phrase("x", font),
                        140 + (i * 55), 409, 185 + (i * 55), 522, 8, Element.ALIGN_CENTER);
                    ct.Go();
                }
            }

            //Additionaly high school graduation requirements checkboxes
            for (int i = 0; i < 3; i++)
            {
                if (gradreq_cbs[i].Checked)
                {
                    ct = new ColumnText(cb);
                    ct.SetSimpleColumn(
                        new Phrase("x", font),
                        205 + (i * 114), 25, 230 + (i * 114), 42, 8, Element.ALIGN_CENTER);
                    ct.Go();
                }
            }

            stamper.Close();
            reader.Close();
        }
        protected void BtnImprimir_Click(object sender, EventArgs e)
        {
            string nomfile = "GUIARECEPCION" + DateTime.Now.ToShortDateString() + ".pdf";

            Response.Clear();
            Response.Buffer      = true;
            Response.Charset     = "";
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=" + nomfile);

            //Document doc = new Document(PageSize.A4, 0.0F, 0.0F, 20.0F, 0.0F);
            Document doc = new Document(PageSize.A4.Rotate(), 10, 20, 20, 10);

            PdfWriter.GetInstance(doc, Response.OutputStream);
            doc.Open();

            BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);

            iTextSharp.text.Font Negrita = new iTextSharp.text.Font(bfTimes, 16, iTextSharp.text.Font.BOLD, BaseColor.BLACK);

            iTextSharp.text.Font Negrita2  = new iTextSharp.text.Font(bfTimes, 12, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
            iTextSharp.text.Font Negrita10 = new iTextSharp.text.Font(bfTimes, 10, iTextSharp.text.Font.BOLD, BaseColor.BLACK);

            iTextSharp.text.Font Formato = new iTextSharp.text.Font(bfTimes, 10, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

            //iTextSharp.text.Font font = new iTextSharp.text.Font(BaseFont.TIMES_ROMAN, 6, font.BaseFont );
            BaseColor colorh = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#A9D0F5"));

            // Escribimos el encabezamiento en el documento
            //     doc.Add(Chunk.NEWLINE);

            PdfPTable tblcabecera_1 = new PdfPTable(1);
            //imagen

            Paragraph paragraph = new Paragraph("Getting Started ITextSharp.");

            //////string imageURL = Server.MapPath(".") + "/logo.jpg";
            //////iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance(imageURL);

            //////imagen.ScalePercent(50f);
            //////imagen.Alignment = Element.ALIGN_LEFT;
            //////doc.Add(imagen);
            //cabecera
            PdfPTable tblcabecera = new PdfPTable(3);

            tblcabecera.WidthPercentage = 100;
            float[] medidaCabecera = { 10f, 10f, 10f };
            tblcabecera.SetWidths(medidaCabecera);

            //fila1 y 2
            string imageURL = Server.MapPath(".") + "/Iconos/logo.jpg";

            iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageURL);
            jpg.ScalePercent(35f);
            PdfPCell imageCell = new PdfPCell(jpg);

            imageCell.Colspan = 2; // either 1 if you need to insert one cell
            imageCell.Border  = 0;
            imageCell.Rowspan = 2;
            // imageCell.Padding=(10f);
            imageCell.HorizontalAlignment = (Element.ALIGN_CENTER);

            tblcabecera.AddCell(imageCell);

            // tblcabecera.AddCell(cllogo);

            PdfPCell clruc = new PdfPCell(new Phrase("R.U.C. 20504653570", Negrita));

            clruc.BorderWidth         = 1;
            clruc.Rowspan             = 2;
            clruc.HorizontalAlignment = Element.ALIGN_CENTER;
            tblcabecera.AddCell(clruc);

            //FILA3
            PdfPCell clasoc = new PdfPCell(new Phrase("ASOCIACION CULTURAL SUDAMERICANA", Negrita10));

            clasoc.BorderWidth         = 0;
            clasoc.Colspan             = 2;
            clasoc.HorizontalAlignment = Element.ALIGN_CENTER;
            tblcabecera.AddCell(clasoc);

            PdfPCell clguia = new PdfPCell(new Phrase("GUIA DE REMISION", Negrita));

            clguia.BorderWidth         = 1;
            clguia.Rowspan             = 2;
            clguia.HorizontalAlignment = Element.ALIGN_CENTER;
            tblcabecera.AddCell(clguia);

            //FILA4
            PdfPCell clSede1 = new PdfPCell(new Phrase("Sede San Miguel: Av. La Marina 1429 - San Miguel - Lima - Lima / Telefonos: 263-0269 / 500-4600", Formato));

            clSede1.BorderWidth         = 0;
            clSede1.Colspan             = 2;
            clSede1.HorizontalAlignment = Element.ALIGN_CENTER;
            tblcabecera.AddCell(clSede1);


            //FILA5
            PdfPCell clSede2 = new PdfPCell(new Phrase("Sede Comas: Av. Universitaria 1250 - Comas - Lima - Lima / Telefonos: 537-6090", Formato));

            clSede2.BorderWidth         = 0;
            clSede2.Colspan             = 2;
            clSede2.HorizontalAlignment = Element.ALIGN_CENTER;
            tblcabecera.AddCell(clSede2);

            PdfPCell clnum = new PdfPCell(new Phrase("Nª" + " " + xidGuia, Negrita));

            clnum.BorderWidth         = 1;
            clnum.Rowspan             = 2;
            clnum.HorizontalAlignment = Element.ALIGN_CENTER;
            tblcabecera.AddCell(clnum);

            //FILA6
            PdfPCell clSede3 = new PdfPCell(new Phrase("Sede Puente Piedra: Calle La Victoria 509 - Puente Piedra - Lima - Lima / Telefonos: 586-7283", Formato));

            clSede3.BorderWidth         = 0;
            clSede3.Colspan             = 2;
            clSede3.HorizontalAlignment = Element.ALIGN_CENTER;
            tblcabecera.AddCell(clSede3);

            PdfPCell clespacio = new PdfPCell(new Phrase(" ", Formato));

            clespacio.BorderWidth         = 0;
            clespacio.Colspan             = 3;
            clespacio.HorizontalAlignment = Element.ALIGN_CENTER;
            tblcabecera.AddCell(clespacio);

            doc.Add(tblcabecera);

            PdfPTable tblFecha = new PdfPTable(2);

            tblFecha.WidthPercentage = 100;
            //dar tamaño a la celda
            float[] medidaCeldasx = { 10f, 10f };
            tblFecha.SetWidths(medidaCeldasx);
            //capturar valores de Guia Cabecera
            GuiaCabeceraN objBuscar    = new GuiaCabeceraN();
            DataTable     DTILogistica = objBuscar.BuscarGuiaCabecera(xidGuia);
            DataRow       row          = DTILogistica.Rows[0];

            string   usu           = row["Usuario que Envia"].ToString();
            string   trans         = row["Transportista"].ToString();
            string   traslado      = row["Motivo Traslado"].ToString();
            string   PPARTIDA      = row["SedePartida"].ToString();
            string   PLLEGADA      = row["SedeLlegada"].ToString();
            string   UsuRecepciona = row["Usuario que Recepciona"].ToString();
            string   FecRecepciona = row["Fecha Recepcion"].ToString();
            DateTime fecenvio      = DateTime.Parse(row["Fecha de Envio"].ToString());
            int      estado        = int.Parse(row["Activo"].ToString());
            ////Feha
            DateTime fecRecibido = Convert.ToDateTime(DateTime.Now.ToString());

            PdfPCell clfecha = new PdfPCell(new Phrase("Fecha Envío:" + " " + fecenvio, Negrita2));

            clfecha.BorderWidth = 0;

            clfecha.HorizontalAlignment = Element.ALIGN_LEFT;
            tblFecha.AddCell(clfecha);

            string   usuario   = Session["Usuario"].ToString().ToUpper();
            PdfPCell clUsuario = new PdfPCell(new Phrase("Usuario:" + " " + usu, Negrita2));

            clUsuario.BorderWidth = 0;

            clUsuario.HorizontalAlignment = Element.ALIGN_RIGHT;
            tblFecha.AddCell(clUsuario);

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

            PdfPTable tblTabla1 = new PdfPTable(4);

            tblTabla1.WidthPercentage = 100;
            //dar tamaño a la celda

            float[] medidaCeldas = { 1.7f, 4.2f, 4f, 4.2f };
            tblTabla1.SetWidths(medidaCeldas);


            //FILA1
            PdfPCell clespacio2 = new PdfPCell(new Phrase(" ", Negrita2));

            clespacio2.BorderWidth         = 0;
            clespacio2.Colspan             = 4;
            clespacio2.HorizontalAlignment = Element.ALIGN_CENTER;

            PdfPCell clTrasportista = new PdfPCell(new Phrase("Transportista:", Negrita2));

            clTrasportista.BorderWidth         = 0;
            clTrasportista.HorizontalAlignment = Element.ALIGN_CENTER;

            PdfPCell clTrasportista1 = new PdfPCell(new Phrase(trans.ToUpper(), Formato));

            clTrasportista1.BorderWidth         = 0;
            clTrasportista1.HorizontalAlignment = Element.ALIGN_CENTER;

            PdfPCell clMotivo = new PdfPCell(new Phrase("Motivo de Traslado:", Negrita2));

            clMotivo.BorderWidth         = 0;
            clMotivo.HorizontalAlignment = Element.ALIGN_CENTER;

            PdfPCell clMotivo1 = new PdfPCell(new Phrase(traslado.ToString(), Formato));

            clMotivo1.BorderWidth         = 0;
            clMotivo1.HorizontalAlignment = Element.ALIGN_CENTER;

            PdfPCell clPuntoPartida = new PdfPCell(new Phrase("Punto de Partida:", Negrita2));

            //clS1.BorderWidth = 1;
            clPuntoPartida.HorizontalAlignment = Element.ALIGN_CENTER;
            clPuntoPartida.BorderWidth         = 0;

            PdfPCell clPuntoPartida1 = new PdfPCell(new Phrase(PPARTIDA, Formato));

            //clS1.BorderWidth = 1;
            clPuntoPartida1.HorizontalAlignment = Element.ALIGN_CENTER;
            clPuntoPartida1.BorderWidth         = 0;

            PdfPCell clPuntoLlegada = new PdfPCell(new Phrase("Punto de Llegada:", Negrita2));

            //clS1.BorderWidth = 1;
            clPuntoLlegada.HorizontalAlignment = Element.ALIGN_CENTER;
            clPuntoLlegada.BorderWidth         = 0;

            PdfPCell clPuntoLlegada1 = new PdfPCell(new Phrase(PLLEGADA, Formato));

            //clS1.BorderWidth = 1;
            clPuntoLlegada1.HorizontalAlignment = Element.ALIGN_CENTER;
            clPuntoLlegada1.BorderWidth         = 0;

            PdfPCell clUsuRecepciona = new PdfPCell(new Phrase("Usuario que Recepciona:", Negrita2));

            //clS1.BorderWidth = 1;
            clUsuRecepciona.HorizontalAlignment = Element.ALIGN_CENTER;
            clUsuRecepciona.BorderWidth         = 0;

            PdfPCell clUsuRecepciona1 = new PdfPCell(new Phrase(UsuRecepciona, Formato));

            //clS1.BorderWidth = 1;
            clUsuRecepciona1.HorizontalAlignment = Element.ALIGN_CENTER;
            clUsuRecepciona1.BorderWidth         = 0;

            PdfPCell clFecRecepciona = new PdfPCell(new Phrase("Fecha de Recepción:", Negrita2));

            //clS1.BorderWidth = 1;
            clFecRecepciona.HorizontalAlignment = Element.ALIGN_CENTER;
            clFecRecepciona.BorderWidth         = 0;

            PdfPCell clFecRecepciona1 = new PdfPCell(new Phrase(FecRecepciona, Formato));

            //clS1.BorderWidth = 1;
            clFecRecepciona1.HorizontalAlignment = Element.ALIGN_CENTER;
            clFecRecepciona1.BorderWidth         = 0;

            PdfPCell clvacio = new PdfPCell(new Phrase(" ", Formato));

            //clS1.BorderWidth = 1;
            clvacio.HorizontalAlignment = Element.ALIGN_CENTER;
            clvacio.BorderWidth         = 0;
            clvacio.Colspan             = 4;

            //FILA1
            tblTabla1.AddCell(clespacio2);
            tblTabla1.AddCell(clTrasportista);
            tblTabla1.AddCell(clTrasportista1);
            tblTabla1.AddCell(clMotivo);
            tblTabla1.AddCell(clMotivo1);
            tblTabla1.AddCell(clPuntoPartida);
            tblTabla1.AddCell(clPuntoPartida1);
            tblTabla1.AddCell(clPuntoLlegada);
            tblTabla1.AddCell(clPuntoLlegada1);
            tblTabla1.AddCell(clUsuRecepciona);
            tblTabla1.AddCell(clUsuRecepciona1);
            tblTabla1.AddCell(clFecRecepciona);
            tblTabla1.AddCell(clFecRecepciona1);
            tblTabla1.AddCell(clvacio);

            doc.Add(tblTabla1);

            doc.Add(Chunk.NEWLINE);


            if (estado == 1) // si es detalle activo
            {
                ///tabla
                PdfPTable tblTabla = new PdfPTable(6);
                tblTabla.WidthPercentage = 100;
                //dar tamaño a la celda

                float[] medidaCeldas1 = { 2f, 4.2f, 6f, 6f, 2f, 2f };
                tblTabla.SetWidths(medidaCeldas1);

                ////////////////////////////////////////////////////////////////////////////////////////

                //FILA1
                PdfPCell clCodigo = new PdfPCell(new Phrase("Código", Negrita2));

                clCodigo.BorderWidth         = 1;
                clCodigo.HorizontalAlignment = Element.ALIGN_CENTER;

                PdfPCell clDescripcion = new PdfPCell(new Phrase("Descripción", Negrita2));

                clDescripcion.BorderWidth         = 1;
                clDescripcion.HorizontalAlignment = Element.ALIGN_CENTER;

                PdfPCell clOrigen = new PdfPCell(new Phrase("Origen", Negrita2));
                clOrigen.BorderWidth         = 1;
                clOrigen.HorizontalAlignment = Element.ALIGN_CENTER;

                PdfPCell clDetalle = new PdfPCell(new Phrase("Detalle", Negrita2));
                clDetalle.BorderWidth         = 1;
                clDetalle.HorizontalAlignment = Element.ALIGN_CENTER;

                PdfPCell clCondicion = new PdfPCell(new Phrase("Condición", Negrita2));
                //clS1.BorderWidth = 1;
                clCondicion.HorizontalAlignment = Element.ALIGN_CENTER;
                clCondicion.BorderWidth         = 1;

                PdfPCell clUnidadMedida = new PdfPCell(new Phrase("Unidad Medida", Negrita2));
                //clS1.BorderWidth = 1;
                clUnidadMedida.HorizontalAlignment = Element.ALIGN_CENTER;
                clUnidadMedida.BorderWidth         = 1;

                //FILA1
                tblTabla.AddCell(clCodigo);
                tblTabla.AddCell(clDescripcion);
                tblTabla.AddCell(clOrigen);
                tblTabla.AddCell(clDetalle);
                tblTabla.AddCell(clCondicion);
                tblTabla.AddCell(clUnidadMedida);

                ReportesN objGuiaDetalle = new ReportesN();//**//
                DataTable DTDetalle      = objGuiaDetalle.ReporteGuiaDetalle(xidGuia, 1);
                gvDetalle.DataSource = DTDetalle;
                gvDetalle.DataBind();

                for (int i = 0; i < gvRepara.Rows.Count; i++)
                {
                    ////clNro = new PdfPCell(new Phrase(Convert.ToString(i + 1), Formato));
                    ////clNro.HorizontalAlignment = Element.ALIGN_CENTER;
                    ////clNro.BorderWidth = 1;

                    clCodigo                     = new PdfPCell(new Phrase(gvRepara.Rows[i].Cells[0].Text, Formato));
                    clCodigo.BorderWidth         = 1;
                    clCodigo.HorizontalAlignment = Element.ALIGN_CENTER;

                    clDescripcion                     = new PdfPCell(new Phrase(gvRepara.Rows[i].Cells[1].Text, Formato));
                    clDescripcion.BorderWidth         = 1;
                    clDescripcion.HorizontalAlignment = Element.ALIGN_CENTER;

                    clOrigen                     = new PdfPCell(new Phrase(gvDetalle.Rows[i].Cells[3].Text, Formato));///***///
                    clOrigen.BorderWidth         = 1;
                    clOrigen.HorizontalAlignment = Element.ALIGN_CENTER;

                    //clOrigen = new PdfPCell(new Phrase(gvRepara.Rows[i].Cells[3].Text, Formato));
                    //clOrigen.BorderWidth = 1;
                    //clOrigen.HorizontalAlignment = Element.ALIGN_CENTER;

                    clDetalle                     = new PdfPCell(new Phrase(gvRepara.Rows[i].Cells[2].Text, Formato));
                    clDetalle.BorderWidth         = 1;
                    clDetalle.HorizontalAlignment = Element.ALIGN_CENTER;

                    clCondicion                     = new PdfPCell(new Phrase(gvDetalle.Rows[i].Cells[5].Text, Formato));//**//
                    clCondicion.BorderWidth         = 1;
                    clCondicion.HorizontalAlignment = Element.ALIGN_CENTER;

                    clUnidadMedida                     = new PdfPCell(new Phrase(gvDetalle.Rows[i].Cells[6].Text, Formato));//**//
                    clUnidadMedida.BorderWidth         = 1;
                    clUnidadMedida.HorizontalAlignment = Element.ALIGN_CENTER;

                    //clCondicion = new PdfPCell(new Phrase(gvRepara.Rows[i].Cells[5].Text, Formato));
                    //clCondicion.BorderWidth = 1;
                    //clCondicion.HorizontalAlignment = Element.ALIGN_CENTER;

                    //clUnidadMedida = new PdfPCell(new Phrase(gvRepara.Rows[i].Cells[6].Text, Formato));
                    //clUnidadMedida.BorderWidth = 1;
                    //clUnidadMedida.HorizontalAlignment = Element.ALIGN_CENTER;

                    tblTabla.AddCell(clCodigo);
                    tblTabla.AddCell(clDescripcion);
                    tblTabla.AddCell(clOrigen);
                    tblTabla.AddCell(clDetalle);
                    tblTabla.AddCell(clCondicion);
                    tblTabla.AddCell(clUnidadMedida);
                }
                doc.Add(tblTabla);
            }

            if (estado == 0)
            {
                ///tabla
                PdfPTable tblTablaBi = new PdfPTable(3);
                tblTablaBi.WidthPercentage = 100;
                //dar tamaño a la celda

                float[] medidaCeldas2 = { 1.7f, 4.2f, 4.2f };
                tblTablaBi.SetWidths(medidaCeldas2);

                ////////////////////////////////////////////////////////////////////////////////////////

                //FILA1
                PdfPCell clCant = new PdfPCell(new Phrase("Cantidad", Negrita2));

                clCant.BorderWidth         = 1;
                clCant.HorizontalAlignment = Element.ALIGN_CENTER;

                PdfPCell clDescrip = new PdfPCell(new Phrase("Descripción", Negrita2));

                clDescrip.BorderWidth         = 1;
                clDescrip.HorizontalAlignment = Element.ALIGN_CENTER;

                PdfPCell clUnidadMe = new PdfPCell(new Phrase("Unidad de Medida:", Negrita2));
                //clS1.BorderWidth = 1;
                clUnidadMe.HorizontalAlignment = Element.ALIGN_CENTER;
                clUnidadMe.BorderWidth         = 1;

                //FILA1

                tblTablaBi.AddCell(clCant);
                tblTablaBi.AddCell(clDescrip);
                tblTablaBi.AddCell(clUnidadMe);

                for (int i = 0; i < gvRepara.Rows.Count; i++)
                {
                    ////clNro = new PdfPCell(new Phrase(Convert.ToString(i + 1), Formato));
                    ////clNro.HorizontalAlignment = Element.ALIGN_CENTER;
                    ////clNro.BorderWidth = 1;

                    clCant                     = new PdfPCell(new Phrase(gvRepara.Rows[i].Cells[0].Text.ToString(), Formato));
                    clCant.BorderWidth         = 1;
                    clCant.HorizontalAlignment = Element.ALIGN_CENTER;

                    clDescrip                     = new PdfPCell(new Phrase(gvRepara.Rows[i].Cells[1].Text, Formato));
                    clDescrip.BorderWidth         = 1;
                    clDescrip.HorizontalAlignment = Element.ALIGN_CENTER;

                    clUnidadMe                     = new PdfPCell(new Phrase(gvRepara.Rows[i].Cells[2].Text, Formato));
                    clUnidadMe.BorderWidth         = 1;
                    clUnidadMe.HorizontalAlignment = Element.ALIGN_CENTER;

                    tblTablaBi.AddCell(clCant);
                    tblTablaBi.AddCell(clDescrip);
                    tblTablaBi.AddCell(clUnidadMe);
                    // doc.Add(tblTablaBi);
                }
                doc.Add(tblTablaBi);
            }

            ///////////////////////////////////////////////////////

            doc.Close();
        }
        public MemoryStream GeneratePdfTemplate(CostCalculationRetailViewModel viewModel)
        {
            BaseFont bf          = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
            BaseFont bf_bold     = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
            Font     normal_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 7);
            Font     bold_font   = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 7);
            Font     bold_font_8 = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);
            Font     font_9      = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 9);
            DateTime now         = DateTime.Now;

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

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

            float margin          = 10;
            float printedOnHeight = 10;
            float startY          = 840 - margin;

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

            #region Top
            PdfPTable table_top = new PdfPTable(9);
            table_top.TotalWidth = 500f;

            float[] top_widths = new float[] { 1f, 0.1f, 2f, 1f, 0.1f, 2f, 1f, 0.1f, 2f };
            table_top.SetWidths(top_widths);

            PdfPCell cell_top = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 1, PaddingBottom = 2, PaddingTop = 2
            };
            PdfPCell cell_colon = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE
            };
            PdfPCell cell_top_keterangan = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 1, PaddingBottom = 2, PaddingTop = 2, Colspan = 7
            };
            cell_colon.Phrase = new Phrase(":", normal_font);

            cell_top.Phrase = new Phrase("RO", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.RO}", normal_font);
            table_top.AddCell(cell_top);
            cell_top.Phrase = new Phrase("BUYER", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.Buyer.Name}", normal_font);
            table_top.AddCell(cell_top);
            cell_top.Phrase = new Phrase("OL", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            double OLValue = viewModel.OL.Value ?? 0;
            string OL      = OLValue > 0 ? OLValue.ToString() + " menit" : OLValue.ToString();
            cell_top.Phrase = new Phrase($"{OL}", normal_font);
            table_top.AddCell(cell_top);

            cell_top.Phrase = new Phrase("ARTICLE", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.Article}", normal_font);
            table_top.AddCell(cell_top);
            cell_top.Phrase = new Phrase("DELIVERY", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.DeliveryDate.ToString("dd MMMM yyyy")}", normal_font);
            table_top.AddCell(cell_top);
            cell_top.Phrase = new Phrase("OTL 1", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            double OTL1Value = viewModel.OTL1.Value ?? 0;
            string OTL1      = OTL1Value > 0 ? OTL1Value.ToString() + " detik" : OTL1Value.ToString();
            cell_top.Phrase = new Phrase($"{OTL1}", normal_font);
            table_top.AddCell(cell_top);

            cell_top.Phrase = new Phrase("STYLE", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.Style.name}", normal_font);
            table_top.AddCell(cell_top);
            cell_top.Phrase = new Phrase("SIZE RANGE", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.SizeRange.Name}", normal_font);
            table_top.AddCell(cell_top);
            cell_top.Phrase = new Phrase("OTL 2", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            double OTL2Value = viewModel.OTL2.Value ?? 0;
            string OTL2      = OTL2Value > 0 ? OTL2Value.ToString() + " detik" : OTL2Value.ToString();
            cell_top.Phrase = new Phrase($"{OTL2}", normal_font);
            table_top.AddCell(cell_top);

            cell_top.Phrase = new Phrase("SEASON", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.Season.name}", normal_font);
            table_top.AddCell(cell_top);
            cell_top.Phrase = new Phrase("EFFICIENCY", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.Efficiency.Value}%", normal_font);
            table_top.AddCell(cell_top);
            cell_top.Phrase = new Phrase("OTL 3", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            double OTL3Value = viewModel.OTL3.Value ?? 0;
            string OTL3      = OTL3Value > 0 ? OTL3Value.ToString() + " detik" : OTL3Value.ToString();
            cell_top.Phrase = new Phrase($"{OTL3}", normal_font);
            table_top.AddCell(cell_top);

            cell_top.Phrase = new Phrase("COUNTER", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.Counter.name}", normal_font);
            table_top.AddCell(cell_top);
            cell_top.Phrase = new Phrase("RISK", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.Risk}%", normal_font);
            table_top.AddCell(cell_top);
            cell_top.Phrase = new Phrase("TOTAL SMV", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            double STD_HourValue = viewModel.SH_Cutting.Value + viewModel.SH_Finishing.Value + viewModel.SH_Sewing.Value;
            string STD_Hour      = STD_HourValue > 0 ? STD_HourValue.ToString() : STD_HourValue.ToString();
            cell_top.Phrase = new Phrase($"{STD_Hour}", normal_font);
            table_top.AddCell(cell_top);

            cell_top.Phrase = new Phrase("KETERANGAN", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top_keterangan.Phrase = new Phrase($"{viewModel.Description}", normal_font);
            table_top.AddCell(cell_top_keterangan);
            #endregion

            #region Draw Image
            float imageHeight;
            try
            {
                byte[] imageByte = Convert.FromBase64String(Base64.GetBase64File(viewModel.ImageFile));
                Image  image     = Image.GetInstance(imgb: imageByte);
                if (image.Width > 60)
                {
                    float percentage = 0.0f;
                    percentage = 60 / image.Width;
                    image.ScalePercent(percentage * 100);
                }
                imageHeight = image.ScaledHeight;
                float imageY = 800 - imageHeight;
                image.SetAbsolutePosition(520, imageY);
                cb.AddImage(image, inlineImage: true);
            }
            catch (Exception)
            {
                imageHeight = 0;
            }
            #endregion

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

            #region Detail (Bottom, Column 1.2)
            PdfPTable table_detail = new PdfPTable(2);
            table_detail.TotalWidth = 280f;

            float[] detail_widths = new float[] { 1f, 1f };
            table_detail.SetWidths(detail_widths);

            PdfPCell cell_detail = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 5, Rowspan = 4
            };

            double total = Convert.ToDouble(viewModel.OL.CalculatedValue + viewModel.OTL1.CalculatedValue + viewModel.OTL2.CalculatedValue + viewModel.OTL3.CalculatedValue);
            cell_detail.Phrase = new Phrase(
                "OL".PadRight(22) + ": " + viewModel.OL.CalculatedValue + Environment.NewLine + Environment.NewLine +
                "OTL 1".PadRight(20) + ": " + viewModel.OTL1.CalculatedValue + Environment.NewLine + Environment.NewLine +
                "OTL 2".PadRight(20) + ": " + viewModel.OTL2.CalculatedValue + Environment.NewLine + Environment.NewLine +
                "OTL 3".PadRight(20) + ": " + viewModel.OTL3.CalculatedValue + Environment.NewLine + Environment.NewLine +
                "Total".PadRight(22) + ": " + total + Environment.NewLine
                , normal_font);
            table_detail.AddCell(cell_detail);

            cell_detail = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_BOTTOM, Padding = 5
            };
            cell_detail.Phrase = new Phrase("HPP", normal_font);
            table_detail.AddCell(cell_detail);
            cell_detail = new PdfPCell()
            {
                Border = Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_TOP, Padding = 5
            };
            cell_detail.Phrase = new Phrase(Number.ToRupiah(viewModel.HPP), font_9);
            table_detail.AddCell(cell_detail);
            cell_detail = new PdfPCell()
            {
                Border = Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_BOTTOM, Padding = 5
            };
            cell_detail.Phrase = new Phrase("Wholesale Price: HPP X 2.20", normal_font);
            table_detail.AddCell(cell_detail);
            cell_detail = new PdfPCell()
            {
                Border = Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_TOP, Padding = 5
            };
            cell_detail.Phrase = new Phrase(Number.ToRupiah(viewModel.WholesalePrice), font_9);
            table_detail.AddCell(cell_detail);
            #endregion

            #region Signature (Bottom, Column 1.2)
            PdfPTable table_signature = new PdfPTable(3);
            table_signature.TotalWidth = 280f;

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

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

            cell_signature.Phrase = new Phrase("Mengetahui,", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Menyetujui,", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("VVIP Marketing", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Creative Director", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Marketing Director", normal_font);
            table_signature.AddCell(cell_signature);

            string signatureArea = string.Empty;
            for (int i = 0; i < 5; i++)
            {
                signatureArea += Environment.NewLine;
            }
            cell_signature.Phrase = new Phrase(signatureArea, normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase(signatureArea, normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase(signatureArea, normal_font);
            table_signature.AddCell(cell_signature);

            cell_signature.Phrase = new Phrase("Puspa Dwi Hartika", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Ari Seputra", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Haenis Gunarto", normal_font);
            table_signature.AddCell(cell_signature);
            #endregion

            #region Price (Bottom, Column 2)
            PdfPTable table_price = new PdfPTable(5);
            table_price.TotalWidth = 280f;

            float[] price_widths = new float[] { 1.6f, 3f, 3f, 4f, 1f };
            table_price.SetWidths(price_widths);

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

            cell_price_center.Phrase = new Phrase("KET (X)", bold_font);
            table_price.AddCell(cell_price_center);
            cell_price_center.Phrase = new Phrase("HARGA (Rp)", bold_font);
            table_price.AddCell(cell_price_center);
            cell_price_center.Phrase = new Phrase("PEMBULATAN HARGA (Rp)", bold_font);
            table_price.AddCell(cell_price_center);
            cell_price_center.Phrase = new Phrase("KETERANGAN", bold_font);
            table_price.AddCell(cell_price_center);
            cell_price_center.Phrase = new Phrase("", bold_font);
            table_price.AddCell(cell_price_center);

            cell_price_left.Phrase = new Phrase("2", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed20), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding20), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_left.Phrase = new Phrase("", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding20") ? "*" : "", normal_font);
            table_price.AddCell(cell_price_center);

            cell_price_left.Phrase = new Phrase("2.1", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed21), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding21), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_left.Phrase = new Phrase("", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding21") ? "*" : "", normal_font);
            table_price.AddCell(cell_price_center);

            cell_price_left.Phrase = new Phrase("2.2", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed22), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding22), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_left.Phrase = new Phrase("", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding22") ? "*" : "", normal_font);
            table_price.AddCell(cell_price_center);

            cell_price_left.Phrase = new Phrase("2.3", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed23), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding23), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_left.Phrase = new Phrase("", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding23") ? "*" : "", normal_font);
            table_price.AddCell(cell_price_center);

            cell_price_left.Phrase = new Phrase("2.4", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed24), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding24), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_left.Phrase = new Phrase("", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding24") ? "*" : "", normal_font);
            table_price.AddCell(cell_price_center);

            cell_price_left.Phrase = new Phrase("2.5", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed25), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding25), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_left.Phrase = new Phrase("", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding25") ? "*" : "", normal_font);
            table_price.AddCell(cell_price_center);

            cell_price_left.Phrase = new Phrase("2.6", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed26), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding26), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_left.Phrase = new Phrase("", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding26") ? "*" : "", normal_font);
            table_price.AddCell(cell_price_center);

            cell_price_left.Phrase = new Phrase("2.7", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed27), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding27), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_left.Phrase = new Phrase("", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding27") ? "*" : "", normal_font);
            table_price.AddCell(cell_price_center);

            cell_price_left.Phrase = new Phrase("2.8", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed28), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding28), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_left.Phrase = new Phrase("", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding28") ? "*" : "", normal_font);
            table_price.AddCell(cell_price_center);

            cell_price_left.Phrase = new Phrase("2.9", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed29), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding29), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_left.Phrase = new Phrase("", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding29") ? "*" : "", normal_font);
            table_price.AddCell(cell_price_center);

            cell_price_left.Phrase = new Phrase("3.0", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Proposed30), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.Rounding30), normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_left.Phrase = new Phrase("", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("Rounding30") ? "*" : "", normal_font);
            table_price.AddCell(cell_price_center);

            cell_price_left.Phrase = new Phrase("Others", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_right.Phrase = new Phrase("", normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_right.Phrase = new Phrase(viewModel.RoundingOthers > 0 ? Number.ToRupiahWithoutSymbol(viewModel.RoundingOthers) : "", normal_font);
            table_price.AddCell(cell_price_right);
            cell_price_left.Phrase = new Phrase("", normal_font);
            table_price.AddCell(cell_price_left);
            cell_price_center.Phrase = new Phrase(viewModel.SelectedRounding.ToString().Equals("RoundingOthers") ? "*" : "", normal_font);
            table_price.AddCell(cell_price_center);
            #endregion

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

            float[] ccm_widths = new float[] { 1.25f, 3.5f, 4f, 9f, 3f, 4f, 4f };
            table_ccm.SetWidths(ccm_widths);

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

            cell_ccm_center.Phrase = new Phrase("NO", bold_font);
            table_ccm.AddCell(cell_ccm_center);

            cell_ccm_center.Phrase = new Phrase("CATEGORIES", bold_font);
            table_ccm.AddCell(cell_ccm_center);

            cell_ccm_center.Phrase = new Phrase("MATERIALS", bold_font);
            table_ccm.AddCell(cell_ccm_center);

            cell_ccm_center.Phrase = new Phrase("DESCRIPTION", bold_font);
            table_ccm.AddCell(cell_ccm_center);

            cell_ccm_center.Phrase = new Phrase("QUANTITY", bold_font);
            table_ccm.AddCell(cell_ccm_center);

            cell_ccm_center.Phrase = new Phrase("RP. PTC/PC", bold_font);
            table_ccm.AddCell(cell_ccm_center);

            cell_ccm_center.Phrase = new Phrase("RP. TOTAL", bold_font);
            table_ccm.AddCell(cell_ccm_center);

            double Total               = 0;
            float  row1Height          = imageHeight > table_top.TotalHeight ? imageHeight : table_top.TotalHeight;
            float  row2Y               = row1Y - row1Height - 10;
            float  calculatedHppHeight = 7;
            float  row3LeftHeight      = table_detail.TotalHeight + 5 + table_signature.TotalHeight;
            float  row3RightHeight     = table_price.TotalHeight;
            float  row3Height          = row3LeftHeight > row3RightHeight ? row3LeftHeight : row3RightHeight;
            float  remainingRow2Height = row2Y - 10 - row3Height - printedOnHeight - margin;
            float  allowedRow2Height   = row2Y - printedOnHeight - margin;
            for (int i = 0; i < viewModel.CostCalculationRetail_Materials.Count; i++)
            {
                cell_ccm_center.Phrase = new Phrase((i + 1).ToString(), normal_font);
                table_ccm.AddCell(cell_ccm_center);

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

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

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

                cell_ccm_right.Phrase = new Phrase(String.Format("{0} {1}", viewModel.CostCalculationRetail_Materials[i].Quantity, viewModel.CostCalculationRetail_Materials[i].UOMQuantity.Name), normal_font);
                table_ccm.AddCell(cell_ccm_right);

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

                cell_ccm_right.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(viewModel.CostCalculationRetail_Materials[i].Total), normal_font);
                table_ccm.AddCell(cell_ccm_right);
                Total += viewModel.CostCalculationRetail_Materials[i].Total;

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

            cell_ccm_right = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2, Colspan = 6
            };
            cell_ccm_right.Phrase = new Phrase("TOTAL", bold_font_8);
            table_ccm.AddCell(cell_ccm_right);
            cell_ccm_right = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE, Padding = 2
            };
            cell_ccm_right.Phrase = new Phrase(Number.ToRupiah(Total), bold_font_8);
            table_ccm.AddCell(cell_ccm_right);
            #endregion

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

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

            #region Calculated HPP
            float calculatedHppY = row3Y - calculatedHppHeight;
            cb.BeginText();
            cb.SetFontAndSize(bf, 8);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "KALKULASI HPP: (OL + OTL1 + OTL2 + FABRIC + ACC) + ((OL + OTL1 + OTL2 + FABRIC + ACC) * Risk)", 10, calculatedHppY, 0);
            cb.EndText();
            #endregion

            float table_detailY = calculatedHppY - 5;
            table_detail.WriteSelectedRows(0, -1, 10, table_detailY, cb);

            float table_signatureY = table_detailY - row3Height + table_signature.TotalHeight;
            table_signature.WriteSelectedRows(0, -1, 10, table_signatureY, cb);

            table_price.WriteSelectedRows(0, -1, 300, table_detailY, cb);

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

            document.Close();

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

            return(stream);
        }
Beispiel #13
0
        public static void GetPdf()
        {
            string path = @"Zapisi";
            if (!Directory.Exists(path))
            {
                DirectoryInfo di = Directory.CreateDirectory(path);
            }
            
            string nameRacunara = ComputerName.Replace('\\', '_');
            fileName = "Zapis_" + nameRacunara + "_" + unixTimestamp + ".pdf";
            fullPath = path + "/"+fileName;

            Document document = new Document(iTextSharp.text.PageSize.A4, 30, 10, 42, 35);
            PdfWriter wri = PdfWriter.GetInstance(document, new FileStream(fullPath, FileMode.Create));
            document.Open();          
            Paragraph text = new Paragraph();
            text.Add("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur pulvinar risus at lobortis mattis. Pellentesque euismod blandit arcu quis sagittis. Sed pretium eu nisi vel porta. Donec ac magna nisl. Duis at mi ac est imperdiet placerat tempus sit amet eros. Maecenas nec auctor dolor. Aenean quis dolor non purus volutpat egestas at ac est. Morbi in nulla ut neque egestas maximus. Quisque nibh eros, bibendum nec ante vitae, viverra commodo leo. Praesent vitae scelerisque justo. Mauris diam libero, bibendum ac fermentum a, gravida ");
            text.IndentationLeft = 55;
            text.IndentationRight = 50;
            
            document.Add(text);

            //---------------------------------------TABLE
            //---------------------------------------Specification table
 
            Paragraph line = new Paragraph(" ");
            document.Add(line);
            PdfPTable table = new PdfPTable(2);
            BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
            Font times = new Font(bfTimes, 14, Font.BOLD, BaseColor.BLACK);
            Font times2 = new Font(bfTimes, 10, Font.NORMAL, BaseColor.BLACK);
            PdfPCell cell = new PdfPCell(new Phrase("Specifikacija:", times));
            cell.Colspan = 2;           
            cell.HorizontalAlignment = Element.ALIGN_LEFT;
            table.AddCell(cell);

            table.AddCell("OS: ");
            table.AddCell(OS);

            table.AddCell("Computer name: ");
            table.AddCell(ComputerName);

            document.Add(table);

            //------------------------------------------HARDWARE table
            
            document.Add(line);
            document.Add(line);

            PdfPTable table2 = new PdfPTable(2);

            PdfPCell cell2 = new PdfPCell(new Phrase("Hardver: ", times));
            cell2.Colspan = 2;
            cell2.HorizontalAlignment = Element.ALIGN_LEFT;
            table2.AddCell(cell2);

            table2.AddCell("CPU: ");
            table2.AddCell(CPU);

            table2.AddCell("RAM: ");
            table2.AddCell(RAM);

            table2.AddCell("Motherboard: ");
            table2.AddCell(Motherboard);

            table2.AddCell("GPU: ");
            table2.AddCell(GPU);

            table2.AddCell("HDD: ");
            var p = new Paragraph();
            foreach (var item in HDDList)
            {
                p.Add(item + "\n");
            }
            table2.AddCell(p);

            document.Add(table2);

            //-------------------------------------SOFTWARE table

            Paragraph line2 = new Paragraph(" ");
            document.Add(line2);
            document.Add(line2);

            PdfPTable table3 = new PdfPTable(1);
          
            PdfPCell cell3 = new PdfPCell(new Phrase("Softver: ", times));
            cell3.Colspan = 2;
            cell3.HorizontalAlignment = Element.ALIGN_LEFT;
            table3.AddCell(cell3);

            foreach (var soft in SoftwareList)
            {
                table3.AddCell(new PdfPCell(new Phrase(soft, times2)));
            }

            document.Add(table3);
            Paragraph instp = new Paragraph("Number of installed programs:   " + count);
            instp.IndentationLeft = 56;
            
            document.Add(instp);

            Paragraph text2 = new Paragraph();
            text2.Add("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur pulvinar risus at lobortis mattis. Pellentesque euismod blandit arcu quis sagittis. Sed pretium eu nisi vel porta. Donec ac magna nisl. Duis at mi ac est imperdiet placerat tempus sit amet eros. Maecenas nec auctor dolor. Aenean quis dolor non purus volutpat egestas at ac est. Morbi in nulla ut neque egestas maximus. Quisque nibh eros, bibendum nec ante vitae, viverra commodo leo. Praesent vitae scelerisque justo. Mauris diam libero, bibendum ac fermentum a, gravida ");
            text2.IndentationLeft = 55;
            text2.IndentationRight = 50;
            text2.SpacingBefore = 20;
            document.Add(text2);

            //----------------------------------underlines

            Paragraph paraLevo = new Paragraph();
            paraLevo.Add("U Novom Sadu,  ");
            paraLevo.Add("\n"+ now.ToShortDateString());
            paraLevo.Alignment = (Element.ALIGN_LEFT + Convert.ToInt32(200));
            paraLevo.SpacingBefore = 120;
            paraLevo.IndentationLeft = 55;
         
            document.Add(paraLevo);

            Paragraph paraDesno = new Paragraph();
            paraDesno.Add(name);
            paraDesno.Add("\n______________\nPotpis");
            paraDesno.Alignment = Element.ALIGN_RIGHT;
            paraDesno.SpacingBefore = -50;
            paraDesno.IndentationRight = 50;
            document.Add(paraDesno);
            document.Close();
        }
Beispiel #14
0
 public override void OnOpenDocument(PdfWriter writer, Document document)
 {
     bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
     templateNumPage = writer.DirectContent.CreateTemplate(50, 50);
     cb = writer.DirectContent;
 }
Beispiel #15
0
        public string CreatePDF(string projectID)
        {
            //get data
            DataTable dt           = ClassConfig.GetDataSQL("exec dbo.get_AppendixA '" + projectID + "'");
            string    projectName  = dt.Rows[0]["projectname"] == null ? "" : dt.Rows[0]["projectname"].ToString();
            string    homeType     = dt.Rows[0]["hometype"] == null ? "" : dt.Rows[0]["hometype"].ToString();
            string    customerName = dt.Rows[0]["customername"] == null ? "" : dt.Rows[0]["customername"].ToString();
            string    name         = dt.Rows[0]["name"] == null ? "" : dt.Rows[0]["name"].ToString();
            string    company      = dt.Rows[0]["company"] == null ? "" : dt.Rows[0]["company"].ToString();
            string    area         = dt.Rows[0]["numMM"] == null ? "" : dt.Rows[0]["numMM"].ToString();
            string    start        = dt.Rows[0]["start"] == null ? "" : Convert.ToDateTime(dt.Rows[0]["start"]).ToString();
            string    stop         = dt.Rows[0]["stop"] == null ? "" : Convert.ToDateTime(dt.Rows[0]["stop"]).ToString();
            string    month        = dt.Rows[0]["Month"] == null ? "" : dt.Rows[0]["Month"].ToString();
            string    total        = dt.Rows[0]["Total"] == null ? "" : dt.Rows[0]["Total"].ToString();
            string    step1        = dt.Rows[0]["step01"] == null ? "" : dt.Rows[0]["step01"].ToString();
            string    step2        = dt.Rows[0]["step02"] == null ? "" : dt.Rows[0]["step02"].ToString();
            string    step3        = dt.Rows[0]["step03"] == null ? "" : dt.Rows[0]["step03"].ToString();
            string    step4        = dt.Rows[0]["step04"] == null ? "" : dt.Rows[0]["step04"].ToString();
            string    step5        = dt.Rows[0]["step05"] == null ? "" : dt.Rows[0]["step05"].ToString();
            string    step6        = dt.Rows[0]["step06"] == null ? "" : dt.Rows[0]["step06"].ToString();
            string    step7        = dt.Rows[0]["step07"] == null ? "" : dt.Rows[0]["step07"].ToString();
            string    step8        = dt.Rows[0]["step08"] == null ? "" : dt.Rows[0]["step08"].ToString();
            string    step9        = dt.Rows[0]["step09"] == null ? "" : dt.Rows[0]["step09"].ToString();
            string    step10       = dt.Rows[0]["step10"] == null ? "" : dt.Rows[0]["step10"].ToString();

            BaseFont bf_normal = BaseFont.CreateFont(HttpContext.Current.Server.MapPath("fonts/THSarabunNew.ttf"), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

            string   fileName             = string.Empty;
            DateTime fileCreationDatetime = DateTime.Now;

            fileName = string.Format("appendix_a_{0}.pdf", fileCreationDatetime.ToString(@"yyyyMMdd") + "_" + fileCreationDatetime.ToString(@"HHmmss"));
            string pdfPath = page.Server.MapPath(@"~\PDFs\") + fileName;

            using (FileStream msReport = new FileStream(pdfPath, FileMode.Create))
            {
                //step 1
                using (Document pdfDoc = new Document(PageSize.A4, 50f, 50f, 100f, 100f))
                {
                    try
                    {
                        // step 2
                        PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, msReport);
                        pdfWriter.PageEvent = new ITextEvents();

                        //open the stream
                        pdfDoc.Open();

                        Paragraph para = new Paragraph("ภาคผนวก ก: การชำระเงินค่าก่อสร้าง", new Font(bf_normal, 22));
                        para.Alignment = Element.ALIGN_CENTER;
                        pdfDoc.Add(para);

                        para                 = new Paragraph(@"เงื่อนไขการชำระเงินค่าก่อสร้าง [projecttype] พื้นที่ใช้สอย [area] ตารางเมตร".Replace("[projecttype]", homeType).Replace("[area]", area), new Font(bf_normal, 18));
                        para.Alignment       = Element.ALIGN_JUSTIFIED;
                        para.FirstLineIndent = 50f;
                        pdfDoc.Add(para);

                        para                 = new Paragraph(@"ทั้ง ""ผู้ว่าจ้าง"" และ ""ผู้รับจ้าง"" ได้ตกลงราคาค่าก่อสร้าง รวมทั้งค่าวัสดุ อุปกรณ์ และค่าแรงทั้งหมด", new Font(bf_normal, 18));
                        para.Alignment       = Element.ALIGN_JUSTIFIED;
                        para.FirstLineIndent = 50f;
                        pdfDoc.Add(para);

                        para           = new Paragraph(@"เป็นจำนวนเงินทั้งสิ้น [amount] บาท [amount_txt]".Replace("[amount]", total).Replace("[amount_txt]", ThaiBaht(total)), new Font(bf_normal, 18));
                        para.Alignment = Element.ALIGN_JUSTIFIED;
                        //para.FirstLineIndent = 50f;
                        pdfDoc.Add(para);

                        para                 = new Paragraph(@"โดย ""ผู้ว่าจ้าง"" ตกลงแบ่งชำระเงินค่าก่อสร้าง เป็นงวดๆ ดังนี้" + Environment.NewLine, new Font(bf_normal, 18));
                        para.Alignment       = Element.ALIGN_JUSTIFIED;
                        para.FirstLineIndent = 50f;
                        pdfDoc.Add(para);

                        // collection of table row
                        Dictionary <string, string> pdfTableRows = new Dictionary <string, string>();
                        pdfTableRows.Add("งวดที่ 1 20% ของค่าก่อสร้างทั้งหมด เป็นจำนวนเงิน", "[term1] บาท".Replace("[term1]", step1));
                        pdfTableRows.Add("เซ็นสัญญาว่าจ้างก่อสร้าง", "([term1str])".Replace("[term1str]", ThaiBaht(step1)));
                        pdfTableRows.Add("งวดที่ 2 15% ของค่าก่อสร้างทั้งหมด เป็นจำนวนเงิน", "[term2] บาท".Replace("[term2]", step2));
                        pdfTableRows.Add("ฐานรากงานคานคอดินแล้วเสร็จ", "([term2str]".Replace("[term2str]", ThaiBaht(step2)));
                        pdfTableRows.Add("งวดที่ 3 10% ของค่าก่อสร้างทั้งหมด เป็นจำนวนเงิน", "[term3] บาท".Replace("[term3]", step3));
                        pdfTableRows.Add("งานโครงสร้างทั้งหมดแล้วเสร็จ", "([term3str])".Replace("[term3str]", ThaiBaht(step3)));
                        pdfTableRows.Add("งวดที่ 4 10% ของค่าก่อสร้างทั้งหมด เป็นจำนวนเงิน", "[term4] บาท".Replace("[term4]", step4));
                        pdfTableRows.Add("งานโครงหลังคา/ยิงไม้เชิงชาย/งานพื้นคสลแล้วเสร็จ", "([term4str])".Replace("[term4str]", ThaiBaht(step4)));
                        pdfTableRows.Add("งวดที่ 5 5% ของค่าก่อสร้างทั้งหมด เป็นจำนวนเงิน", "[term5] บาท".Replace("[term5]", step5));
                        pdfTableRows.Add("งานก่อผนัง/วางระบบไฟ/วางระบบน้ำแล้วเสร็จ", "([terem5str])".Replace("[term5str]", ThaiBaht(step5)));
                        pdfTableRows.Add("งวดที่ 6 5% ของค่าก่อสร้างทั้งหมด เป็นจำนวนเงิน", "[term6] บาท".Replace("[term6]", step6));
                        pdfTableRows.Add("งานฉาบผนัง/งานมุงหลังคาแล้วเสร็จ", "([term6str])".Replace("[term6str]", ThaiBaht(step6)));
                        pdfTableRows.Add("งวดที่ 7 10% ของค่าก่อสร้างทั้งหมด เป็นจำนวนเงิน", "[term7] บาท".Replace("[term7]", step7));
                        pdfTableRows.Add("งานสีรองพื้น/งานโครงฝ้า/ร้อยสายไฟ/วางระบบประปาแล้วเสร็จ", "([term7str])".Replace("[term7str]", ThaiBaht(step7)));
                        pdfTableRows.Add("งวดที่ 8 5% ของค่าก่อสร้างทั้งหมด เป็นจำนวนเงิน", "[term8] บาท".Replace("[term8]", step8));
                        pdfTableRows.Add("งานกระเบื้องแล้วเสร็จ/งานประตูหน้าต่างแล้วเสร็จ/งานฝ้าแล้วเสร็จ", "([term8str])".Replace("[term8str]", ThaiBaht(step8)));
                        pdfTableRows.Add("งวดที่ 9 15% ของค่าก่อสร้างทั้งหมด เป็นจำนวนเงิน", "[term9] บาท".Replace("[term9]", step9));
                        pdfTableRows.Add("งานสี/งานไฟ/งานสุขภัณฑ์/และงานอื่นๆ แล้วเสร็จ", "([term9str])".Replace("[term9str]", ThaiBaht(step9)));
                        pdfTableRows.Add("งวดที่ 10 5% ของค่าก่อสร้างทั้งหมด เป็นจำนวนเงิน", "[term10] บาท".Replace("[term10]", step10));
                        pdfTableRows.Add("งานเก็บรายละเอียดส่งงาน", "([term10str])".Replace("[term10str]", ThaiBaht(step10)));

                        PdfPTable table = new PdfPTable(2);
                        foreach (var item in pdfTableRows)
                        {
                            PdfPCell cell1 = new PdfPCell(new Phrase(item.Key, new Font(bf_normal, 18)));
                            PdfPCell cell2 = new PdfPCell(new Phrase(item.Value, new Font(bf_normal, 18)));
                            //cell.HorizontalAlignment = Element.ALIGN_CENTER;
                            cell1.Border = 0;
                            cell2.Border = 0;
                            table.AddCell(cell1);
                            table.AddCell(cell2);
                        }

                        table.WidthPercentage = 100;

                        //table.TotalWidth = pdfDoc.PageSize.Width;
                        pdfDoc.Add(table);

                        para                 = new Paragraph(@"""ผู้รับจ้าง"" ตกลงเริ่มทำการก่อสร้างในวันที่ [start] และจะดำเนินการให้แล้วเสร็จสมบูรณ์ภายในวันที่ [end] (เป็นระยะเวลา 6 เดือน)", new Font(bf_normal, 18));
                        para.Alignment       = Element.ALIGN_JUSTIFIED;
                        para.FirstLineIndent = 50f;
                        pdfDoc.Add(para);

                        para                 = new Paragraph(@"**บริษัทฯ ขอสงวนสิทธิ์ในการเปลี่ยนแปลงเงื่อนไขการชำระเงินได้ตามความเหมาะสม", new Font(bf_normal, 18));
                        para.Alignment       = Element.ALIGN_JUSTIFIED;
                        para.FirstLineIndent = 50f;
                        pdfDoc.Add(para);


                        table = new PdfPTable(2);
                        PdfPCell cell1_1 = new PdfPCell(new Phrase(Environment.NewLine + Environment.NewLine + @"ลงชื่อ ...................................... ผู้ว่าจ้าง" + Environment.NewLine
                                                                   + @" ([customer])", new Font(bf_normal, 18)));
                        PdfPCell cell1_2 = new PdfPCell(new Phrase(Environment.NewLine + Environment.NewLine + @"ลงชื่อ ...................................... ผู้รับจ้าง" + Environment.NewLine
                                                                   + @"([vendorname])" + Environment.NewLine
                                                                   + @"[companyname]", new Font(bf_normal, 18)));
                        cell1_1.HorizontalAlignment = Element.ALIGN_CENTER;
                        cell1_2.HorizontalAlignment = Element.ALIGN_CENTER;

                        cell1_1.Border = 0;
                        cell1_2.Border = 0;

                        table.AddCell(cell1_1);
                        table.AddCell(cell1_2);

                        table.WidthPercentage = 100;

                        //table.TotalWidth = pdfDoc.PageSize.Width;
                        pdfDoc.Add(table);


                        pdfDoc.Close();
                    }
                    catch (Exception ex)
                    {
                        //handle exception
                    }
                    finally
                    {
                    }
                }
            }
            return(fileName);
        }
Beispiel #16
0
        // ---------------------------------------------------------------------------

        /**
         * Creates a PDF document for PdfReader.
         */
        public byte[] CreatePdf()
        {
            // step 1
            using (MemoryStream ms = new MemoryStream())
            {
                using (Document document = new Document(PageSize.POSTCARD, 30, 30, 30, 30))
                {
                    // step 2
                    PdfWriter writer = PdfWriter.GetInstance(document, ms);
                    // step 3
                    document.Open();
                    // step 4
                    PdfContentByte under = writer.DirectContentUnder;
                    // Page 1: a rectangle
                    DrawRectangle(
                        under, PageSize.POSTCARD.Width, PageSize.POSTCARD.Height
                        );
                    under.SetRGBColorFill(0xFF, 0xD7, 0x00);
                    under.Rectangle(
                        5, 5, PageSize.POSTCARD.Width - 10, PageSize.POSTCARD.Height - 10
                        );
                    under.Fill();
                    document.NewPage();
                    // Page 2: an image
                    DrawRectangle(
                        under, PageSize.POSTCARD.Width, PageSize.POSTCARD.Height
                        );
                    Image img = Image.GetInstance(Path.Combine(
                                                      Utility.ResourceImage, "loa.jpg"
                                                      ));
                    img.SetAbsolutePosition(
                        (PageSize.POSTCARD.Width - img.ScaledWidth) / 2,
                        (PageSize.POSTCARD.Height - img.ScaledHeight) / 2
                        );
                    document.Add(img);
                    document.NewPage();
                    // Page 3: the words "Foobar Film Festival"
                    DrawRectangle(
                        under, PageSize.POSTCARD.Width, PageSize.POSTCARD.Height
                        );
                    Paragraph p = new Paragraph(
                        "Foobar Film Festival", new Font(Font.FontFamily.HELVETICA, 22)
                        );
                    p.Alignment = Element.ALIGN_CENTER;
                    document.Add(p);
                    document.NewPage();
                    // Page 4: the words "SOLD OUT"
                    DrawRectangle(under, PageSize.POSTCARD.Width, PageSize.POSTCARD.Height);
                    PdfContentByte over = writer.DirectContent;
                    over.SaveState();
                    float    sinus   = (float)Math.Sin(Math.PI / 60);
                    float    cosinus = (float)Math.Cos(Math.PI / 60);
                    BaseFont bf      = BaseFont.CreateFont();
                    over.BeginText();
                    over.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
                    over.SetLineWidth(1.5f);
                    over.SetRGBColorStroke(0xFF, 0x00, 0x00);
                    over.SetRGBColorFill(0xFF, 0xFF, 0xFF);
                    over.SetFontAndSize(bf, 36);
                    over.SetTextMatrix(cosinus, sinus, -sinus, cosinus, 50, 324);
                    over.ShowText("SOLD OUT");
                    over.SetTextMatrix(0, 0);
                    over.EndText();
                    over.RestoreState();
                }
                return(ms.ToArray());
            }
        }
Beispiel #17
0
        public override void OnStartPage(PdfWriter writer, Document document)
        {
            PdfContentByte cb = writer.DirectContent;

            cb.BeginText();
            Font     normal_font            = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 7);
            Font     big_font               = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 14, Font.BOLD);
            BaseFont bf                     = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
            Font     normal_font_underlined = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 7, Font.UNDERLINE);

            float height = writer.PageSize.Height, width = writer.PageSize.Width;
            float marginLeft = document.LeftMargin - 10, marginTop = document.TopMargin, marginRight = document.RightMargin - 10;

            cb.SetFontAndSize(bf, 7);

            #region LOGODL

            byte[] imageByteDL = Convert.FromBase64String(Base64ImageStrings.LOGO_DANLIRIS_58_58);
            Image  imageDL     = Image.GetInstance(imageByteDL);
            if (imageDL.Width > 60)
            {
                float percentage = 0.0f;
                percentage = 60 / imageDL.Width;
                imageDL.ScalePercent(percentage * 100);
            }
            imageDL.SetAbsolutePosition(marginLeft, height - imageDL.ScaledHeight - marginTop + 60);
            cb.AddImage(imageDL, inlineImage: true);

            #endregion

            #region ADDRESS

            var headOfficeX = width / 2 + 30;
            var headOfficeY = height - marginTop + 45;

            var branchOfficeY = height - marginTop + 50;

            byte[] imageByte = Convert.FromBase64String(Base64ImageStrings.LOGO_NAME);
            Image  image1    = Image.GetInstance(imageByte);
            if (image1.Width > 100)
            {
                float percentage = 0.0f;
                percentage = 100 / image1.Width;
                image1.ScalePercent(percentage * 100);
            }
            image1.SetAbsolutePosition(marginLeft + 80, height - image1.ScaledHeight - marginTop + 75);
            cb.AddImage(image1, inlineImage: true);

            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "Head Office : Jl. Merapi No. 23", marginLeft + 80, branchOfficeY, 0);
            string[] branchOffices =
            {
                "Banaran, Grogol, Sukoharjo 57552",
                "Central Java, Indonesia",
                "Tel. : (+62-271) 740888, 714400",
                "Fax. : (+62-271) 740777, 735222",
                "PO BOX 166 Solo, 57100",
                "Website : www.danliris.com",
            };
            for (int i = 0; i < branchOffices.Length; i++)
            {
                cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, branchOffices[i], marginLeft + 80, branchOfficeY - 10 - (i * 10), 0);
            }

            #endregion

            #region LOGOISO

            byte[] imageByteIso = Convert.FromBase64String(Base64ImageStrings.ISO);
            Image  imageIso     = Image.GetInstance(imageByteIso);
            if (imageIso.Width > 100)
            {
                float percentage = 0.0f;
                percentage = 100 / imageIso.Width;
                imageIso.ScalePercent(percentage * 100);
            }
            imageIso.SetAbsolutePosition(width - imageIso.ScaledWidth - marginRight, height - imageIso.ScaledHeight - marginTop + 60);
            cb.AddImage(imageIso, inlineImage: true);
            //cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "CERTIFICATE ID09 / 01238", width - (imageIso.ScaledWidth / 2) - marginRight, height - imageIso.ScaledHeight - marginTop + 60 - 5, 0);

            #endregion

            #region LINE

            cb.MoveTo(marginLeft, height - marginTop - 15);
            cb.LineTo(width - marginRight, height - marginTop - 15);
            cb.Stroke();

            cb.MoveTo(marginLeft, height - marginTop - 18);
            cb.LineTo(width - marginRight, height - marginTop - 18);
            cb.Stroke();

            #endregion

            #region Table
            PdfPTable table = new PdfPTable(1);

            table.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin; //this centers [table]

            PdfPTable tabledetailOrders = new PdfPTable(3);
            tabledetailOrders.SetWidths(new float[] { 0.6f, 1.4f, 2f });

            PdfPCell cellDetailContentLeft = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER
            };
            PdfPCell cellDetailContentRight = new PdfPCell()
            {
                Border = Rectangle.BOTTOM_BORDER
            };
            PdfPCell cellDetailContentRight2 = new PdfPCell()
            {
                Border = Rectangle.BOTTOM_BORDER
            };
            PdfPCell cellDetailContentCenter = new PdfPCell()
            {
                Border = Rectangle.RIGHT_BORDER | Rectangle.BOTTOM_BORDER
            };
            PdfPCell cellDetailContentCenter2 = new PdfPCell()
            {
                Border = Rectangle.RIGHT_BORDER | Rectangle.BOTTOM_BORDER
            };

            PdfPCell cellHeaderContentLeft = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            cellHeaderContentLeft.AddElement(new Phrase("                                                  COMMERCIAL INVOICE", big_font));
            cellHeaderContentLeft.AddElement(new Phrase("\n", normal_font));
            cellHeaderContentLeft.AddElement(new Phrase("\n", normal_font));
            cellHeaderContentLeft.AddElement(new Phrase("Invoice No.  :  " + viewModel.InvoiceNo + "                                                                                Date  :  " + viewModel.InvoiceDate.ToOffset(new TimeSpan(timeoffset, 0, 0)).ToString("MMM dd, yyyy.", new System.Globalization.CultureInfo("en-EN")) + "                                                                                                      Page  : " + (writer.PageNumber), normal_font));
            cellHeaderContentLeft.AddElement(new Phrase("\n", normal_font));
            cellHeaderContentLeft.Colspan = 3;
            tabledetailOrders.AddCell(cellHeaderContentLeft);

            cellDetailContentLeft.Phrase  = new Phrase("SOLD BY ORDERS AND FOR ACCOUNT AND RISK OF", normal_font);
            cellDetailContentLeft.Colspan = 2;
            cellDetailContentLeft.Border  = Rectangle.LEFT_BORDER | Rectangle.TOP_BORDER;
            tabledetailOrders.AddCell(cellDetailContentLeft);


            PdfPTable tabledetailOrders2 = new PdfPTable(3);
            tabledetailOrders2.SetWidths(new float[] { 1.5f, 0.2f, 1.5f });

            cellDetailContentLeft.Phrase  = new Phrase("CO NO.", normal_font);
            cellDetailContentLeft.Colspan = 1;
            cellDetailContentLeft.Border  = Rectangle.LEFT_BORDER | Rectangle.TOP_BORDER;
            tabledetailOrders2.AddCell(cellDetailContentLeft);

            cellDetailContentLeft.Phrase  = new Phrase(":", normal_font);
            cellDetailContentLeft.Colspan = 1;
            cellDetailContentLeft.Border  = Rectangle.TOP_BORDER;
            tabledetailOrders2.AddCell(cellDetailContentLeft);

            cellDetailContentLeft.Phrase  = new Phrase(viewModel.CO, normal_font);
            cellDetailContentLeft.Colspan = 1;
            cellDetailContentLeft.Border  = Rectangle.TOP_BORDER;
            tabledetailOrders2.AddCell(cellDetailContentLeft);

            cellDetailContentLeft.Phrase  = new Phrase("CONFIRMATION OF ORDER NO.", normal_font);
            cellDetailContentLeft.Colspan = 1;
            cellDetailContentLeft.Border  = Rectangle.LEFT_BORDER;
            tabledetailOrders2.AddCell(cellDetailContentLeft);

            cellDetailContentLeft.Phrase  = new Phrase(":", normal_font);
            cellDetailContentLeft.Colspan = 1;
            cellDetailContentLeft.Border  = Rectangle.NO_BORDER;
            tabledetailOrders2.AddCell(cellDetailContentLeft);

            cellDetailContentLeft.Phrase  = new Phrase(viewModel.ConfirmationOfOrderNo, normal_font);
            cellDetailContentLeft.Colspan = 1;
            cellDetailContentLeft.Border  = Rectangle.NO_BORDER;
            tabledetailOrders2.AddCell(cellDetailContentLeft);

            cellDetailContentLeft.Phrase  = new Phrase("SHIPPED PER", normal_font);
            cellDetailContentLeft.Colspan = 1;
            cellDetailContentLeft.Border  = Rectangle.LEFT_BORDER;
            tabledetailOrders2.AddCell(cellDetailContentLeft);

            cellDetailContentLeft.Phrase  = new Phrase(":", normal_font);
            cellDetailContentLeft.Colspan = 1;
            cellDetailContentLeft.Border  = Rectangle.NO_BORDER;
            tabledetailOrders2.AddCell(cellDetailContentLeft);

            cellDetailContentLeft.Phrase  = new Phrase(viewModel.ShippingPer, normal_font);
            cellDetailContentLeft.Colspan = 1;
            cellDetailContentLeft.Border  = Rectangle.NO_BORDER;
            tabledetailOrders2.AddCell(cellDetailContentLeft);


            cellDetailContentLeft.Phrase  = new Phrase("SAILING ON OR ABOUT", normal_font);
            cellDetailContentLeft.Colspan = 1;
            cellDetailContentLeft.Border  = Rectangle.LEFT_BORDER;
            tabledetailOrders2.AddCell(cellDetailContentLeft);

            cellDetailContentLeft.Phrase  = new Phrase(":", normal_font);
            cellDetailContentLeft.Colspan = 1;
            cellDetailContentLeft.Border  = Rectangle.NO_BORDER;
            tabledetailOrders2.AddCell(cellDetailContentLeft);

            cellDetailContentLeft.Phrase  = new Phrase(viewModel.SailingDate.ToOffset(new TimeSpan(timeoffset, 0, 0)).ToString("dd MMMM yyyy", new System.Globalization.CultureInfo("en-EN")), normal_font);
            cellDetailContentLeft.Colspan = 1;
            cellDetailContentLeft.Border  = Rectangle.NO_BORDER;
            tabledetailOrders2.AddCell(cellDetailContentLeft);


            cellDetailContentLeft.Phrase  = new Phrase("FROM", normal_font);
            cellDetailContentLeft.Colspan = 1;
            cellDetailContentLeft.Border  = Rectangle.LEFT_BORDER;
            tabledetailOrders2.AddCell(cellDetailContentLeft);

            cellDetailContentLeft.Phrase  = new Phrase(":", normal_font);
            cellDetailContentLeft.Colspan = 1;
            cellDetailContentLeft.Border  = Rectangle.NO_BORDER;
            tabledetailOrders2.AddCell(cellDetailContentLeft);

            cellDetailContentLeft.Phrase  = new Phrase(viewModel.From, normal_font);
            cellDetailContentLeft.Colspan = 1;
            cellDetailContentLeft.Border  = Rectangle.NO_BORDER;
            tabledetailOrders2.AddCell(cellDetailContentLeft);

            cellDetailContentLeft.Phrase  = new Phrase("TO", normal_font);
            cellDetailContentLeft.Colspan = 1;
            cellDetailContentLeft.Border  = Rectangle.LEFT_BORDER;
            tabledetailOrders2.AddCell(cellDetailContentLeft);

            cellDetailContentLeft.Phrase  = new Phrase(":", normal_font);
            cellDetailContentLeft.Colspan = 1;
            cellDetailContentLeft.Border  = Rectangle.NO_BORDER;
            tabledetailOrders2.AddCell(cellDetailContentLeft);

            cellDetailContentLeft.Phrase  = new Phrase(viewModel.To, normal_font);
            cellDetailContentLeft.Colspan = 1;
            cellDetailContentLeft.Border  = Rectangle.NO_BORDER;
            tabledetailOrders2.AddCell(cellDetailContentLeft);

            PdfPCell c2 = new PdfPCell(tabledetailOrders2);//this line made the difference
            c2.Rowspan = 3;
            tabledetailOrders.AddCell(c2);

            cellDetailContentRight.AddElement(new Phrase("MESSRS      : ", normal_font));
            cellDetailContentRight.Border = Rectangle.LEFT_BORDER;
            tabledetailOrders.AddCell(cellDetailContentRight);

            if (viewModel.InvoiceNo.Substring(0, 2) == "SM" || viewModel.InvoiceNo.Substring(0, 2) == "DS" || viewModel.InvoiceNo.Substring(0, 3) == "DLR")
            {
                cellDetailContentCenter.AddElement(new Phrase(viewModel.Consignee, normal_font));
            }
            else
            {
                cellDetailContentCenter.AddElement(new Phrase(viewModel.BuyerAgent.Name, normal_font));
            }
            cellDetailContentCenter.AddElement(new Phrase(viewModel.ConsigneeAddress, normal_font));
            cellDetailContentCenter.Border = Rectangle.NO_BORDER;
            tabledetailOrders.AddCell(cellDetailContentCenter);

            cellDetailContentRight2.AddElement(new Phrase("DELIVERED TO : ", normal_font));
            cellDetailContentRight2.Border = Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER;
            tabledetailOrders.AddCell(cellDetailContentRight2);

            cellDetailContentCenter2.AddElement(new Phrase(viewModel.DeliverTo, normal_font));
            cellDetailContentCenter2.Border = Rectangle.BOTTOM_BORDER;
            tabledetailOrders.AddCell(cellDetailContentCenter2);

            cellDetailContentRight2.Phrase = new Phrase("\n", normal_font);
            cellDetailContentRight2.Border = Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER;
            tabledetailOrders.AddCell(cellDetailContentRight2);

            PdfPCell cellDetail = new PdfPCell(tabledetailOrders);
            cellDetail.Border = Rectangle.NO_BORDER;
            table.AddCell(cellDetail);

            table.WriteSelectedRows(0, -1, document.LeftMargin, height - marginTop + tabledetailOrders.TotalHeight - 205, writer.DirectContent);
            #endregion

            #region START
            PdfPTable tableStart = new PdfPTable(1);
            tableStart.SetWidths(new float[] { 8f });

            PdfPCell cellHeaderContentStart = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER
            };
            cellHeaderContentStart.AddElement(new Phrase("\n", normal_font));
            cellHeaderContentStart.AddElement(new Phrase("\n", normal_font));
            cellHeaderContentStart.AddElement(new Phrase("\n", normal_font));
            cellHeaderContentStart.AddElement(new Phrase("\n", normal_font));
            cellHeaderContentStart.AddElement(new Phrase("\n", normal_font));
            cellHeaderContentStart.AddElement(new Phrase("\n", normal_font));
            cellHeaderContentStart.AddElement(new Phrase("\n", normal_font));
            cellHeaderContentStart.AddElement(new Phrase("\n", normal_font));
            cellHeaderContentStart.AddElement(new Phrase("\n", normal_font));
            cellHeaderContentStart.AddElement(new Phrase("\n", normal_font));
            cellHeaderContentStart.AddElement(new Phrase("\n", normal_font));
            cellHeaderContentStart.AddElement(new Phrase("\n", normal_font));
            cellHeaderContentStart.AddElement(new Phrase("\n", normal_font));
            cellHeaderContentStart.AddElement(new Phrase("\n", normal_font));
            cellHeaderContentStart.AddElement(new Phrase("\n", normal_font));

            tableStart.AddCell(cellHeaderContentStart);
            tableStart.SpacingAfter = 50f;
            document.Add(tableStart);
            #endregion

            #region SIGNATURE
            var printY = document.BottomMargin - 20;
            var signX  = document.RightMargin + 500;
            var signY  = printY + 20;
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "( MRS. ADRIYANA DAMAYANTI )", document.RightMargin + 500, signY + 5, 0);
            cb.MoveTo(signX - 60, signY - 2);
            cb.LineTo(signX + 45, signY - 2);
            cb.Stroke();
            cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "AUTHORIZED SIGNATURE", document.RightMargin + 500, signY - 105, 0);

            #endregion

            #region FOOTER

            var printY1 = document.BottomMargin - 30;
            var signX1  = document.LeftMargin + 20;
            var signY1  = printY1 + 20;
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "The shippers accept no responsibility for the arrival of goods at destination or for loss or damage in transit after goods were shipped in good order and condition.", document.LeftMargin, 40, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "The  goods  supplied  under  this  invoice  remain  our  property  until  the  invoice  has been credited into  one or our Bank account  mentioned above in full and without restriction.", document.LeftMargin, 30, 0);
            //cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "without restriction.", document.LeftMargin, 30, 0);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "______________________________________________________________________________________________________________________________________________", document.LeftMargin, 20, 0);

            #endregion

            cb.EndText();
        }
Beispiel #18
0
        private void BtnExportPdf_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveDialog = new SaveFileDialog();

            saveDialog.Filter   = "PDF FIle(*.pdf)|*.pdf";
            saveDialog.FileName = "";
            if (saveDialog.ShowDialog() == true)
            {
                // PDF 변환
                try
                {
                    // 0. PDF에 사용할 폰트 설정
                    string nanumPath = Path.Combine(Environment.CurrentDirectory, @"NanumGothic.ttf"); // 폰트 경로 지정
                    // Combine은 문자열 결함 함수, Environment.CurrentDirectory 현재 작업 폴더에서 프로그램 실행

                    BaseFont nanumBase = BaseFont.CreateFont(nanumPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

                    var nanumTitle = new iTextSharp.text.Font(nanumBase, 18f);   // 사이즈 20짜리 타이틀용 나눔폰트 생성

                    var nanumContent = new iTextSharp.text.Font(nanumBase, 12f); // 사이즈 12짜리 내용에쓰는 나눔폰트 생성

                    // iTextSharp.text.Font font = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 14);
                    string pdfFilePath = saveDialog.FileName;
                    iTextSharp.text.Document pdfDoc = new Document(PageSize.A4);


                    // 1. PDF 객체 생성
                    PdfPTable pdfTable = new PdfPTable(GrdData.Columns.Count);
                    pdfTable.WidthPercentage = 100;   // 전체 사이즈 다 쓰는거


                    // 2. PDF 내용 만들기
                    Paragraph title    = new Paragraph("부경대 재고 관리 시스템(Stock Management System)\n", nanumTitle);
                    Paragraph subTitle = new Paragraph($"exported : {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}\n\n", nanumContent);

                    // 그리드 헤더 작업
                    foreach (DataGridColumn column in GrdData.Columns)
                    {
                        PdfPCell cell = new PdfPCell(new Phrase(column.Header.ToString(), nanumContent));
                        cell.HorizontalAlignment = Element.ALIGN_CENTER;
                        pdfTable.AddCell(cell);
                    }

                    // 각 셀 사이즈 조정
                    float[] columnsWidth = new float[] { 8f, 25f, 10f, 15f, 32f, 14f, 12f };
                    pdfTable.SetWidths(columnsWidth);

                    // 그리드 Row작업
                    foreach (var item in GrdData.Items)
                    {
                        if (item is Model.User)
                        {
                            var temp = item as Model.User;

                            // UserID
                            PdfPCell cell = new PdfPCell(new Phrase(temp.UserID.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_RIGHT;
                            pdfTable.AddCell(cell);

                            // UserIdentityNumber
                            cell = new PdfPCell(new Phrase(temp.UserIdentityNumber.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            pdfTable.AddCell(cell);

                            // UserSurname
                            cell = new PdfPCell(new Phrase(temp.UserSurname.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            pdfTable.AddCell(cell);

                            // UserName
                            cell = new PdfPCell(new Phrase(temp.UserName.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            pdfTable.AddCell(cell);

                            // UserEmail
                            cell = new PdfPCell(new Phrase(temp.UserEmail.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            pdfTable.AddCell(cell);

                            // UserAdmin
                            cell = new PdfPCell(new Phrase(temp.UserAdmin.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            pdfTable.AddCell(cell);

                            // UserActivated
                            cell = new PdfPCell(new Phrase(temp.UserActivated.ToString(), nanumContent));
                            cell.HorizontalAlignment = Element.ALIGN_LEFT;
                            pdfTable.AddCell(cell);
                        }
                    }



                    // 3. 실제 PDF 파일생성
                    using (FileStream stream = new FileStream(pdfFilePath, FileMode.OpenOrCreate))
                    {
                        PdfWriter.GetInstance(pdfDoc, stream);
                        pdfDoc.Open();

                        // 2.에서 만든 내용을 추가
                        pdfDoc.Add(title);
                        pdfDoc.Add(subTitle);
                        pdfDoc.Add(pdfTable);
                        pdfDoc.Close();
                        stream.Close();  // 옵션인데 일단 넣음
                    }

                    Commons.ShowMessageAsync("PDF변환", "PDF 익스포트 성공했습니다.");
                }
                catch (Exception ex)
                {
                    Commons.LOGGER.Error($"예외발생 BtnExportPdf_Click : {ex}");
                }
            }
        }
Beispiel #19
0
        public static void AddAddresseBlock(string file, int beforePage, bool doublesided, Addressee person, int x, int y, bool replaceSource)
        {
            using (var ms = new MemoryStream())
            {
                using (var doc = new Document(iTextSharp.text.PageSize.A4))
                {
                    var reader = new PdfReader(file);
                    var writer = PdfWriter.GetInstance(doc, ms);
                    writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_7);
                    writer.CompressionLevel = PdfStream.NO_COMPRESSION;
                    string ttf      = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "TIMES.TTF");
                    var    baseFont = BaseFont.CreateFont(ttf, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                    var    timesN   = new Font(baseFont, 9, Font.NORMAL);
                    var    timesB   = new Font(baseFont, 9, Font.BOLD);

                    doc.Open();
                    var cb = writer.DirectContent;
                    int n  = 1;
                    if (beforePage > 1)
                    {
                        for (; n <= beforePage; n++)
                        {
                            cb.AddTemplate(writer.GetImportedPage(reader, n), 0, 0);
                            doc.NewPage();
                        }
                    }

                    if (person.Barcode != null)
                    {
                        var bc = new BarcodeInter25()
                        {
                            Code = person.Barcode
                        };
                        var bc_image = bc.CreateImageWithBarcode(cb, BaseColor.BLACK, BaseColor.BLACK);

                        bc_image.SetAbsolutePosition(355, 665);
                        bc_image.ScalePercent(117F);
                        cb.AddImage(bc_image);
                    }
                    var ct = new ColumnText(cb);
                    ct.SetSimpleColumn(new Rectangle(345, 550, 550, 665));

                    if (person.Name != null)
                    {
                        ct.AddElement(new Paragraph("Кому: " + person.Name, timesN));
                    }
                    if (person.Address != null)
                    {
                        ct.AddElement(new Paragraph("Куда: " + person.Address, timesN));
                    }
                    ct.Go();

                    if (person.Index != 0)
                    {
                        cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 15);
                        cb.BeginText();
                        cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, person.Index.ToString(), 465, 680, 0);
                        cb.EndText();
                    }
                    doc.NewPage();
                    if (doublesided)
                    {
                        doc.Add(new Chunk());
                        doc.NewPage();
                    }
                    for (; n <= reader.NumberOfPages; n++)
                    {
                        cb.AddTemplate(writer.GetImportedPage(reader, n), 0, 0);
                        doc.NewPage();
                    }
                }
                ms.Flush();
                if (replaceSource)
                {
                    File.WriteAllBytes(file, ms.ToArray());
                }
                else
                {
                    File.WriteAllBytes(file.Insert(file.Length - 4, "_out"), ms.ToArray());
                }
            }
        }
Beispiel #20
0
        private void btnTulosta_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();

            sfd.Filter   = "PDF (*.pdf)|*.pdf";
            sfd.FileName = "Lasku.pdf";
            bool fileError = false;

            iTextSharp.text.Font f    = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN);
            Document             pdfD = new Document(PageSize.A4);

            pdfD.SetMargins(70, 70, 110, 110);
            Paragraph prg = new Paragraph("Lasku, Newbie Village" + Chunk.NEWLINE + Chunk.NEWLINE, f);

            for (int i = 0; i < dgvAsiakas.Columns.Count; i++)
            {
                string str = dgvAsiakas.Rows[0].Cells[i].Value.ToString();
                prg.Add(str + Chunk.NEWLINE);
            }

            prg.Add(Chunk.NEWLINE);
            prg.Add(Chunk.NEWLINE);
            prg.Add("Mökki");
            prg.Add(Chunk.NEWLINE);
            prg.Add(Chunk.NEWLINE);


            Paragraph prg2 = new Paragraph(Chunk.NEWLINE + "Varauksen tiedot" + Chunk.NEWLINE + Chunk.NEWLINE, f);

            Paragraph prg3 = new Paragraph(Chunk.NEWLINE + "Ostetut palvelut: " + Chunk.NEWLINE, f);

            prg3.Add(Chunk.NEWLINE);



            Paragraph prg4 = new Paragraph(Chunk.NEWLINE + "Laskun summa (sis. alv 10%) " + (double.Parse(lbSumma.Text) + double.Parse(lbPHinta.Text)) + " €", f);



            if (dgvMokki.Rows.Count > 0)
            {
                if (sfd.ShowDialog() == DialogResult.OK)
                {   //Tarkistaa, onko saman niminen tiedosto
                    if (File.Exists(sfd.FileName))
                    {
                        try
                        {   //Jos on, yrittää poistaa vanhan
                            File.Delete(sfd.FileName);
                        }
                        catch (IOException ex)
                        {
                            fileError = true;
                            MessageBox.Show("Laskun kirjoittaminen ei onnistunut!" + ex.Message);
                        }
                    }
                    if (!fileError)
                    {
                        try
                        {
                            //Lukee Mökki-dgv:n
                            PdfPTable pdf = new PdfPTable(dgvMokki.Columns.Count);
                            pdf.DefaultCell.Padding = 3;
                            pdf.WidthPercentage     = 100;
                            pdf.HorizontalAlignment = Element.ALIGN_LEFT;

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

                            iTextSharp.text.Font text = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);
                            foreach (DataGridViewColumn column in dgvMokki.Columns)
                            {
                                PdfPCell cell = new PdfPCell(new iTextSharp.text.Phrase(column.HeaderText, text));
                                pdf.AddCell(cell);
                            }
                            string pdfcell;
                            foreach (DataGridViewRow row in dgvMokki.Rows)
                            {
                                foreach (DataGridViewCell cell in row.Cells)
                                {
                                    if (cell.Value == null)
                                    {
                                        pdfcell = null;
                                    }
                                    else
                                    {
                                        pdfcell = cell.Value.ToString();
                                        pdf.AddCell(new Phrase(pdfcell, text));
                                    }
                                }
                            }
                            //Lukee varauksen
                            BaseFont  bf2  = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, BaseFont.EMBEDDED);
                            PdfPTable pdf2 = new PdfPTable(dgvVaraus.Columns.Count);
                            pdf2.DefaultCell.Padding = 3;
                            pdf2.WidthPercentage     = 100;
                            pdf2.HorizontalAlignment = Element.ALIGN_LEFT;
                            iTextSharp.text.Font text2 = new iTextSharp.text.Font(bf2, 10, iTextSharp.text.Font.NORMAL);
                            foreach (DataGridViewColumn column in dgvVaraus.Columns)
                            {
                                PdfPCell cell = new PdfPCell(new iTextSharp.text.Phrase(column.HeaderText, text2));
                                pdf2.AddCell(cell);
                            }
                            string pdfcell2;
                            foreach (DataGridViewRow row in dgvVaraus.Rows)
                            {
                                foreach (DataGridViewCell cell in row.Cells)
                                {
                                    if (cell.Value == null)
                                    {
                                        pdfcell2 = null;
                                    }
                                    else
                                    {
                                        pdfcell2 = cell.Value.ToString();
                                        pdf2.AddCell(new Phrase(pdfcell2, text2));
                                    }
                                }
                            }

                            BaseFont  bf3  = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, BaseFont.EMBEDDED);
                            PdfPTable pdf3 = new PdfPTable(dgvPalv.Columns.Count);
                            pdf3.DefaultCell.Padding = 3;
                            pdf3.WidthPercentage     = 100;
                            pdf3.HorizontalAlignment = Element.ALIGN_LEFT;

                            if (dgvPalv.Rows.Count > 0)
                            {
                                //Lukee palvelutiedot
                                iTextSharp.text.Font text3 = new iTextSharp.text.Font(bf3, 10, iTextSharp.text.Font.NORMAL);
                                foreach (DataGridViewColumn column in dgvPalv.Columns)
                                {
                                    PdfPCell cell = new PdfPCell(new iTextSharp.text.Phrase(column.HeaderText, text3));
                                    pdf3.AddCell(cell);
                                }
                                string pdfcell3;
                                foreach (DataGridViewRow row in dgvPalv.Rows)
                                {
                                    foreach (DataGridViewCell cell in row.Cells)
                                    {
                                        if (cell.Value == null)
                                        {
                                            pdfcell3 = null;
                                        }
                                        else
                                        {
                                            pdfcell3 = cell.Value.ToString();
                                            pdf3.AddCell(new Phrase(pdfcell3, text3));
                                        }
                                    }
                                }
                            }


                            using (FileStream stream = new FileStream(sfd.FileName, FileMode.Create))
                            {
                                //Tekee pdf:n
                                PdfWriter.GetInstance(pdfD, stream);
                                pdfD.Open();
                                pdfD.Add(prg);
                                pdfD.Add(pdf);
                                pdfD.Add(prg2);
                                pdfD.Add(pdf2);
                                pdfD.Add(prg3);
                                pdfD.Add(pdf3);
                                pdfD.Add(prg4);
                                pdfD.Close();
                                stream.Close();
                            }
                            MessageBox.Show("Laskun tekeminen onnistui!", "Info");
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Error! Laskun kirjoittaminen ei onnistunut" + ex.Message);
                        }
                    }
                }
            }

            this.Close();
        }
Beispiel #21
0
        private void ToolStripButton8_Click(object sender, EventArgs e)
        {
            SaveFileDialog s = new SaveFileDialog
            {
                Filter = "pdf files (*.pdf)|*.pdf|All files (*.*)|*.*"
            };
            string path = "";

            if (s.ShowDialog() == DialogResult.OK)
            {
                path = s.FileName;
            }

            try
            {
                MySqlDataAdapter mda = new MySqlDataAdapter("SELECT Orders.Order_id, Service_type.Type_name, Services.Service_name, Orders.Order_date, Orders.Price, Status.Status_name FROM Orders INNER JOIN Services on(Services.Service_id = Orders.Service_id) INNER JOIN Service_type on(Services.Type_id = Service_type.Type_id) INNER JOIN Status on(Status.Status_id = Orders.Status_id) WHERE Orders.User_id = " + Id + Search + ";", conn);
                DataSet          ds  = new DataSet();
                mda.Fill(ds, "Orders");

                iTextSharp.text.Document doc = new iTextSharp.text.Document();

                PdfWriter.GetInstance(doc, new FileStream(path, FileMode.Create));

                doc.Open();

                BaseFont             baseFont = BaseFont.CreateFont("C:\\Windows\\Fonts\\arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                iTextSharp.text.Font font     = new iTextSharp.text.Font(baseFont, iTextSharp.text.Font.DEFAULTSIZE, iTextSharp.text.Font.NORMAL);

                PdfPTable table = new PdfPTable(ds.Tables["Orders"].Columns.Count);

                PdfPCell cell = new PdfPCell(new Phrase(" " + "Orders" + " ", font))
                {
                    Colspan             = ds.Tables["Orders"].Columns.Count,
                    HorizontalAlignment = PdfPCell.ALIGN_CENTER,
                    Border = 0
                };
                table.AddCell(cell);
                for (int j = 0; j < dataGridView1.ColumnCount; j++)
                {
                    cell = new PdfPCell(new Phrase(new Phrase(dataGridView1.Columns[j].HeaderText, font)))
                    {
                        BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY
                    };
                    table.AddCell(cell);
                }

                for (int j = 0; j < ds.Tables["Orders"].Rows.Count; j++)
                {
                    for (int k = 0; k < ds.Tables["Orders"].Columns.Count; k++)
                    {
                        table.AddCell(new Phrase(ds.Tables["Orders"].Rows[j][k].ToString(), font));
                    }
                }
                doc.Add(table);

                doc.Close();

                MessageBox.Show("Pdf-document saved!");
            }
            catch (Exception)
            {
                MessageBox.Show("Problems with saving to PDF format!");
            }
        }
        public static void tablePage()
        {
            Document     doc       = new Document(PageSize.A4.Rotate(), 15, 5, 10, 20); //A4橫式,Marginleft,Marginright,Margintop,Marginbottom
            MemoryStream Memory    = new MemoryStream();
            PdfWriter    PdfWriter = PdfWriter.GetInstance(doc, Memory);

            //字型設定(不使用BaseFont防止PDF內嵌字型導致檔案過大)
            BaseFont bfChinese = BaseFont.CreateFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            Font     FontMid   = new Font(bfChinese, 12);
            Font     FontSml   = new Font(bfChinese, 10);

            doc.Open();

            //表格
            //PdfPTable table = new PdfPTable(new float[] { 65f, 73f, 124f, 50f, 70f, 105f, 63f, 50f, 40f, 40f, 80f });
            PdfPTable table = new PdfPTable(11);

            table.TotalWidth  = 780f;
            table.LockedWidth = true;
            table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
            table.DefaultCell.VerticalAlignment   = Element.ALIGN_MIDDLE;
            table.DefaultCell.MinimumHeight       = 30f;

            table.AddCell(new Paragraph("發貨日", FontSml));
            table.AddCell(new Paragraph("發票號碼", FontSml));
            table.AddCell(new Paragraph("出貨品項", FontSml));
            table.AddCell(new Paragraph("數量", FontSml));
            table.AddCell(new Paragraph("總金額", FontSml));
            table.AddCell(new Paragraph("批號", FontSml));
            table.AddCell(new Paragraph("效期", FontSml));
            table.AddCell(new Paragraph("退(換)貨\n原因", FontSml));
            table.AddCell(new Paragraph("同意", FontSml));
            table.AddCell(new Paragraph("不同意", FontSml));
            table.AddCell(new Paragraph("原廠確認簽名", FontSml));

            PdfPCell cell = new PdfPCell();

            table.AddCell(cell.Init("C00)發票作廢、退貨", FontSml).Colspan(2));
            table.AddCell(cell.Init("C05)滯銷", FontSml).Colspan(3));
            table.AddCell(cell.Init("C10)結束營業", FontSml).Colspan(4));
            table.AddCell(cell.Init("", FontSml).Colspan(2));

            table.AddCell(cell.Init("C01)業代誤訂", FontSml).Colspan(2));
            table.AddCell(cell.Init("C06)壞損-於配送途中", FontSml).Colspan(3));
            table.AddCell(cell.Init("C99)其他", FontSml).Colspan(4));
            table.AddCell(cell.Init("", FontSml).Colspan(2));

            PdfPTable table1 = new PdfPTable(new float[] { 40f, 60f });

            table1.AddCell("C02)客戶誤訂");
            table1.AddCell("C07)壞損-客戶收貨後");
            table1.AddCell("C03)久裕誤寄");
            table1.AddCell("C08)過期");
            table.AddCell(cell.Init(table1).Colspan(5));
            table.AddCell(cell.Init("RTN_REMARK", FontSml, PdfPCell.ALIGN_CENTER, PdfPCell.ALIGN_MIDDLE).Colspan(6));

            table.AddCell(cell.Init("C04)配送公司誤送", FontSml).Colspan(2));
            table.AddCell(cell.Init("C09)短效期", FontSml).Colspan(9).Border(0));

            table.AddCell(cell.Init("列印日期:" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), FontSml).Colspan(11));

            table.WriteSelectedRows(0, -1, 30, 425, PdfWriter.DirectContent);

            doc.Close();

            using (FileStream fs = File.Create(outputFile))
            {
                fs.Write(Memory.GetBuffer(), 0, Memory.GetBuffer().Length);
            }
        }
Beispiel #23
0
        public async Task <ConvertResult> Png2PdfAsync(List <String> sources, String target)
        {
            var images = await CompressImagesAsync(sources);

            var result     = this.CreateFinalTiffFile(images, target.Replace(".pdf", ".tif"));
            var dict       = new Dictionary <String, String>();
            var compressOk = sources.All(x => !images.Contains(x));

            if (!result.Success)
            {
                DeleteFiles(images);
                return(result);
            }

            images.ForEach(s => {
                var info = new FileInfo(s);
                if (!info.Exists)
                {
                    compressOk = false;
                }
                else
                {
                    if (info.Length < 0.5 * 1027)
                    {
                        compressOk = false;
                    }
                }
            });

            if (compressOk)
            {
                var document = new Document();
                document.SetMargins(0, 0, 0, 0);

                var writer = PdfWriter.GetInstance(document, new FileStream(target, FileMode.Create));
                writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_5);
                document.Open();

                images.ForEach(i => {
                    // http://stackoverflow.com/questions/19256275/fitting-image-into-pdf-using-itext
                    var img = Image.GetInstance(i);
                    img.SetAbsolutePosition(0f, 0f);

                    var dpiX = img.DpiX == 0 ? 92 : img.DpiX;
                    var dpiY = img.DpiY == 0 ? 92 : img.DpiX;

                    var width  = PixelsToPoints(img.Width, dpiX);
                    var height = PixelsToPoints(img.Height, dpiY);
                    var sizeOk = document.SetPageSize(new Rectangle(0, 0, width, height));

                    _logger.LogInformation($"convert - {width}({dpiX}) {height}({dpiY})");

                    if (sizeOk)
                    {
                        var scaler = (document.PageSize.Width / img.Width) * 100;
                        img.ScalePercent(scaler);
                    }

                    document.NewPage();

                    // Append ocr content first.
                    if (dict.Keys.Contains(i))
                    {
                        var value = dict[i];
                        var text  = new Chunk(value);
                        text.setLineHeight(0);
                        text.SetCharacterSpacing(0);
                        text.SetWordSpacing(0);

                        var under = writer.DirectContentUnder;
                        var cb    = new PdfContentByte(writer);
                        cb.BeginText();
                        cb.SetFontAndSize(BaseFont.CreateFont(), 8f);
                        cb.ShowText(value);
                        cb.EndText();
                        under.Add(cb);
                    }
                    // Append image above of ocr content.
                    document.Add(img);
                });

                document.Close();
                writer.Close();

                DeleteFiles(images);
                return(new ConvertResult {
                    Success = true,
                    Result = target,
                    Message = ""
                });
            }
            else
            {
                DeleteFiles(images);
                return(new ConvertResult {
                    Success = false,
                    Result = "",
                    Message = ""
                });
            }
        }
        public MemoryStream GeneratePdfTemplate(CostCalculationGarmentViewModel viewModel, int timeoffset)
        {
            BaseFont bf          = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
            BaseFont bf_bold     = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
            Font     normal_font = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 7);
            Font     bold_font   = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 7);
            DateTime now         = DateTime.Now;

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

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

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

            #region Header
            cb.BeginText();
            cb.SetFontAndSize(bf, 10);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "PT. DAN LIRIS", 10, 820, 0);
            cb.SetFontAndSize(bf_bold, 12);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "BUDGET EXPORT GARMENT", 10, 805, 0);
            cb.EndText();
            #endregion

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            double   budgetCost   = isDollar ? viewModel.ConfirmPrice * viewModel.Rate.Value ?? 0 : viewModel.ConfirmPrice ?? 0;
            double   totalBudget  = budgetCost * viewModel.Quantity ?? 0;
            PdfPCell cell_detail3 = new PdfPCell()
            {
                HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 2, PaddingBottom = 7, PaddingLeft = 2, PaddingTop = 7
            };
            PdfPCell cell_detail3_right = new PdfPCell()
            {
                HorizontalAlignment = Element.ALIGN_RIGHT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 2, PaddingBottom = 7, PaddingLeft = 2, PaddingTop = 7
            };
            PdfPCell cell_detail3_colspan6 = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 2, PaddingBottom = 7, PaddingLeft = 2, PaddingTop = 7, Colspan = 6
            };
            PdfPCell cell_detail3_colspan8 = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER, HorizontalAlignment = Element.ALIGN_LEFT, VerticalAlignment = Element.ALIGN_MIDDLE, PaddingRight = 2, PaddingBottom = 7, PaddingLeft = 2, PaddingTop = 7, Colspan = 8
            };

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

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

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

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

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

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

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

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

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

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

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


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

            cell_signature.Phrase = new Phrase("Penjualan", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Ka. Sie/Ka. Bag Penjualan", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Ka. Bag Pembelian", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Ka. Div Produksi Garment", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Ka. Div Penjualan", normal_font);
            table_signature.AddCell(cell_signature);
            #endregion

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

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

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

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

            float row2Y               = row1Y - table_detail1.TotalHeight - 10;
            float row3Height          = table_detail2.TotalHeight > table_detail3.TotalHeight ? table_detail2.TotalHeight : table_detail3.TotalHeight;
            float row2RemainingHeight = row2Y - 10 - row3Height - printedOnHeight - margin;
            float row2AllowedHeight   = row2Y - printedOnHeight - margin;

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

                cell_ccm.HorizontalAlignment = Element.ALIGN_LEFT;

                //CATEGORY
                cell_ccm.Phrase = new Phrase(viewModel.CostCalculationGarment_Materials[i].Category.name, normal_font);
                table_ccm.AddCell(cell_ccm);

                //KODE PRODUK
                cell_ccm.Phrase = new Phrase(viewModel.CostCalculationGarment_Materials[i].Product.Code, normal_font);
                table_ccm.AddCell(cell_ccm);

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

                cell_ccm.HorizontalAlignment = Element.ALIGN_RIGHT;

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

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

                double factor;
                if (viewModel.CostCalculationGarment_Materials[i].Category.name == "FABRIC")
                {
                    factor = viewModel.FabricAllowance ?? 0;
                }
                else
                {
                    factor = viewModel.AccessoriesAllowance ?? 0;
                }
                double totalQuantity = viewModel.Quantity ?? 0;
                double quantity      = (100 + factor) / 100 * usage * totalQuantity;
                cell_ccm.Phrase = new Phrase(Math.Ceiling(viewModel.CostCalculationGarment_Materials[i].BudgetQuantity).ToString(), normal_font);
                table_ccm.AddCell(cell_ccm);

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

                cell_ccm.HorizontalAlignment = Element.ALIGN_RIGHT;

                if (viewModel.CostCalculationGarment_Materials[i].isFabricCM == true)
                {
                    cell_ccm.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(0), normal_font);
                    table_ccm.AddCell(cell_ccm);
                }
                else
                {
                    double amount = viewModel.CostCalculationGarment_Materials[i].BudgetQuantity * price;
                    cell_ccm.Phrase = new Phrase(Number.ToRupiahWithoutSymbol(amount), normal_font);
                    table_ccm.AddCell(cell_ccm);
                }


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

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

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

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

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

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

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

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

            document.Close();

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

            return(stream);
        }
Beispiel #25
0
// ===========================================================================
        public void Write(Stream stream)
        {
            // step 1
            using (Document document = new Document()) {
                // step 2
                PdfWriter writer = PdfWriter.GetInstance(document, stream);
                // step 3
                document.Open();
                // step 4
                PdfContentByte canvas = writer.DirectContent;
                String         text   = "AWAY again";
                BaseFont       bf     = BaseFont.CreateFont();
                canvas.BeginText();
                // line 1
                canvas.SetFontAndSize(bf, 16);
                canvas.MoveText(36, 806);
                canvas.MoveTextWithLeading(0, -24);
                canvas.ShowText(text);
                // line 2
                canvas.SetWordSpacing(20);
                canvas.NewlineShowText(text);
                // line 3
                canvas.SetCharacterSpacing(10);
                canvas.NewlineShowText(text);
                canvas.SetWordSpacing(0);
                canvas.SetCharacterSpacing(0);
                // line 4
                canvas.SetHorizontalScaling(50);
                canvas.NewlineShowText(text);
                canvas.SetHorizontalScaling(100);
                // line 5
                canvas.NewlineShowText(text);
                canvas.SetTextRise(15);
                canvas.SetFontAndSize(bf, 12);
                canvas.SetColorFill(BaseColor.RED);
                canvas.ShowText("2");
                canvas.SetColorFill(GrayColor.GRAYBLACK);
                // line 6
                canvas.SetLeading(56);
                canvas.NewlineShowText("Changing the leading: " + text);
                canvas.SetLeading(24);
                canvas.NewlineText();
                // line 7
                PdfTextArray array = new PdfTextArray("A");
                array.Add(120);
                array.Add("W");
                array.Add(120);
                array.Add("A");
                array.Add(95);
                array.Add("Y again");
                canvas.ShowText(array);
                canvas.EndText();

                canvas.SetColorFill(BaseColor.BLUE);
                canvas.BeginText();
                canvas.SetTextMatrix(360, 770);
                canvas.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL);
                canvas.SetFontAndSize(bf, 24);
                canvas.ShowText(text);
                canvas.EndText();

                canvas.BeginText();
                canvas.SetTextMatrix(360, 730);
                canvas.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_STROKE);
                canvas.SetFontAndSize(bf, 24);
                canvas.ShowText(text);
                canvas.EndText();

                canvas.BeginText();
                canvas.SetTextMatrix(360, 690);
                canvas.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
                canvas.SetFontAndSize(bf, 24);
                canvas.ShowText(text);
                canvas.EndText();

                canvas.BeginText();
                canvas.SetTextMatrix(360, 650);
                canvas.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE);
                canvas.SetFontAndSize(bf, 24);
                canvas.ShowText(text);
                canvas.EndText();

                PdfTemplate template = canvas.CreateTemplate(200, 36);
                template.SetLineWidth(2);
                for (int i = 0; i < 6; i++)
                {
                    template.MoveTo(0, i * 6);
                    template.LineTo(200, i * 6);
                }
                template.Stroke();

                canvas.SaveState();
                canvas.BeginText();
                canvas.SetTextMatrix(360, 610);
                canvas.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_CLIP);
                canvas.SetFontAndSize(bf, 24);
                canvas.ShowText(text);
                canvas.EndText();
                canvas.AddTemplate(template, 360, 610);
                canvas.RestoreState();

                canvas.SaveState();
                canvas.BeginText();
                canvas.SetTextMatrix(360, 570);
                canvas.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_STROKE_CLIP);
                canvas.SetFontAndSize(bf, 24);
                canvas.ShowText(text);
                canvas.EndText();
                canvas.AddTemplate(template, 360, 570);
                canvas.RestoreState();

                canvas.SaveState();
                canvas.BeginText();
                canvas.SetTextMatrix(360, 530);
                canvas.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE_CLIP);
                canvas.SetFontAndSize(bf, 24);
                canvas.ShowText(text);
                canvas.EndText();
                canvas.AddTemplate(template, 360, 530);
                canvas.RestoreState();

                canvas.SaveState();
                canvas.BeginText();
                canvas.SetTextMatrix(360, 490);
                canvas.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_CLIP);
                canvas.SetFontAndSize(bf, 24);
                canvas.ShowText(text);
                canvas.EndText();
                canvas.AddTemplate(template, 360, 490);
                canvas.RestoreState();
            }
        }
Beispiel #26
0
        /// <summary>
        /// Constructs a Font-object.
        /// </summary>
        /// <param name="fontname">the name of the font</param>
        /// <param name="encoding">the encoding of the font</param>
        /// <param name="embedded">true if the font is to be embedded in the PDF</param>
        /// <param name="size">the size of this font</param>
        /// <param name="style">the style of this font</param>
        /// <param name="color">the BaseColor of this font</param>
        /// <param name="cached">true if the font comes from the cache or is added to the cache if new, false if the font is always created new</param>
        /// <returns>a Font object</returns>
        public virtual Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color, bool cached)
        {
            if (fontname == null)
            {
                return(new Font(Font.FontFamily.UNDEFINED, size, style, color));
            }
            string        lowercasefontname = fontname.ToLower(CultureInfo.InvariantCulture);
            List <string> tmp;

            fontFamilies.TryGetValue(lowercasefontname, out tmp);
            if (tmp != null)
            {
                // some bugs were fixed here by Daniel Marczisovszky
                int  fs    = Font.NORMAL;
                bool found = false;
                int  s     = style == Font.UNDEFINED ? Font.NORMAL : style;
                foreach (string f in tmp)
                {
                    string lcf = f.ToLower(CultureInfo.InvariantCulture);
                    fs = Font.NORMAL;
                    if (lcf.ToLower(CultureInfo.InvariantCulture).IndexOf("bold") != -1)
                    {
                        fs |= Font.BOLD;
                    }
                    if (lcf.ToLower(CultureInfo.InvariantCulture).IndexOf("italic") != -1 || lcf.ToLower(CultureInfo.InvariantCulture).IndexOf("oblique") != -1)
                    {
                        fs |= Font.ITALIC;
                    }
                    if ((s & Font.BOLDITALIC) == fs)
                    {
                        fontname = f;
                        found    = true;
                        break;
                    }
                }
                if (style != Font.UNDEFINED && found)
                {
                    style &= ~fs;
                }
            }
            BaseFont basefont = null;

            try {
                try {
                    // the font is a type 1 font or CJK font
                    basefont = BaseFont.CreateFont(fontname, encoding, embedded, cached, null, null, true);
                }
                catch (DocumentException) {
                }
                if (basefont == null)
                {
                    // the font is a true type font or an unknown font
                    trueTypeFonts.TryGetValue(fontname.ToLower(CultureInfo.InvariantCulture), out fontname);
                    // the font is not registered as truetype font
                    if (fontname == null)
                    {
                        return(new Font(Font.FontFamily.UNDEFINED, size, style, color));
                    }
                    // the font is registered as truetype font
                    basefont = BaseFont.CreateFont(fontname, encoding, embedded, cached, null, null);
                }
            }
            catch (DocumentException de) {
                // this shouldn't happen
                throw de;
            }
            catch (System.IO.IOException) {
                // the font is registered as a true type font, but the path was wrong
                return(new Font(Font.FontFamily.UNDEFINED, size, style, color));
            }
            catch {
                // null was entered as fontname and/or encoding
                return(new Font(Font.FontFamily.UNDEFINED, size, style, color));
            }
            return(new Font(basefont, size, style, color));
        }
Beispiel #27
0
        protected void btnDownload_Click(object sender, EventArgs e)
        {
            BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, false);

            Font times = new Font(bfTimes, 12, Font.ITALIC, BaseColor.BLACK);

            //server folder path which is stored your PDF documents
            string path     = Server.MapPath("");
            string filename = path + "\\Doc1.pdf";


            var  apartments = ApartmentsManager.Get(Association.Id);
            Font boldFont   = new Font(null, 12, Font.BOLD);

            //Create new PDF document
            Document document = new Document(PageSize.A4, 80f, 80f, 20f, 20f);

            using (Document doc = new Document())
            {
                MemoryStream msPDFData = new MemoryStream();
                doc.Open();
                doc.Add(new Paragraph("I'm a pdf!"));
                byte[] pdfData = msPDFData.ToArray();
            }

            var association = Association;

            try
            {
                PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create));
                document.Open();

                foreach (var apartment in apartments)
                {
                    decimal?  sumToPay  = 0;
                    PdfPTable tblHeader = new PdfPTable(2)
                    {
                        WidthPercentage = 100
                    };
                    tblHeader.AddCell(GetCell("ASOCIATIA DE PROPRIETARI " + association.Name + ", CF " + association.FiscalCode, PdfPCell.ALIGN_LEFT));
                    tblHeader.AddCell(GetCell("CONTUL BANCAR " + association.BanckAccont, PdfPCell.ALIGN_RIGHT));
                    document.Add(tblHeader);
                    document.Add(new Phrase("\n"));

                    PdfPTable tbAp = new PdfPTable(4);
                    tbAp.WidthPercentage = 100;
                    tbAp.AddCell(GetCell("Ap.: " + apartment.Number, PdfPCell.ALIGN_CENTER));
                    tbAp.AddCell(GetCell("Nume: " + apartment.Name, PdfPCell.ALIGN_CENTER));
                    tbAp.AddCell(GetCell("Cota: " + (apartment.CotaIndiviza.HasValue ? apartment.CotaIndiviza.Value.ToString(CultureInfo.InvariantCulture) : string.Empty), PdfPCell.ALIGN_CENTER));
                    tbAp.AddCell(GetCell("Nr. Pers: " + apartment.Dependents, PdfPCell.ALIGN_CENTER));
                    document.Add(tbAp);

                    document.Add(new Phrase("\n"));

                    var associationExpensesGrouped = AssociationExpensesManager.GetByMonthAndYearNotDisabled(association.Id, GetYear(), GetMonth())
                                                     .GroupBy(ee => ee.Id_ExpenseType).OrderBy(er => er.Key);

                    foreach (var assocExpenses in associationExpensesGrouped)
                    {
                        // add header
                        document.Add(new Paragraph("Cheltuielile de tipulîățșț " + assocExpenses.FirstOrDefault().ExpenseTypes.Name, times));

                        if (assocExpenses.FirstOrDefault().Id_ExpenseType == (int)ExpenseType.PerIndex)
                        {
                            foreach (var assocExpense in assocExpenses)
                            {
                                var apExpenses = assocExpense.ApartmentExpenses.Where(w => w.Id_Tenant == apartment.Id).ToList();
                                if (apExpenses.Any())
                                {
                                    sumToPay = sumToPay + AddIndexTable(document, apExpenses, apartment, assocExpense.Id);
                                }
                            }
                        }
                        else if (assocExpenses.FirstOrDefault().Id_ExpenseType == (int)ExpenseType.PerCotaIndiviza)
                        {
                            sumToPay = sumToPay + AddCotaTable(document, assocExpenses.ToList(), apartment.Id);
                        }
                        else if (assocExpenses.FirstOrDefault().Id_ExpenseType == (int)ExpenseType.PerNrTenants)
                        {
                            sumToPay = sumToPay + AddTenantsTable(document, assocExpenses.ToList(), apartment.Id);
                        }
                        // add rows
                        // add subtotal
                    }

                    document.Add(new Paragraph("TOTAL DE PLATA: " + sumToPay, boldFont));


                    document.NewPage();
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                document.Close();
                ShowPdf(filename);
            }
        }
Beispiel #28
0
 /// <summary>
 /// Register a ttf- or a ttc-file and use an alias for the font contained in the ttf-file.
 /// </summary>
 /// <param name="path">the path to a ttf- or ttc-file</param>
 /// <param name="alias">the alias you want to use for the font</param>
 public virtual void Register(string path, string alias)
 {
     try {
         if (path.ToLower(CultureInfo.InvariantCulture).EndsWith(".ttf") || path.ToLower(CultureInfo.InvariantCulture).EndsWith(".otf") || path.ToLower(CultureInfo.InvariantCulture).IndexOf(".ttc,") > 0)
         {
             Object[] allNames = BaseFont.GetAllFontNames(path, BaseFont.WINANSI, null);
             trueTypeFonts[((string)allNames[0]).ToLower(CultureInfo.InvariantCulture)] = path;
             if (alias != null)
             {
                 trueTypeFonts[alias.ToLower(CultureInfo.InvariantCulture)] = path;
             }
             // register all the font names with all the locales
             string[][] names = (string[][])allNames[2]; //full name
             for (int i = 0; i < names.Length; i++)
             {
                 trueTypeFonts[names[i][3].ToLower(CultureInfo.InvariantCulture)] = path;
             }
             string fullName   = null;
             string familyName = null;
             names = (string[][])allNames[1]; //family name
             for (int k = 0; k < TTFamilyOrder.Length; k += 3)
             {
                 foreach (string[] name in names)
                 {
                     if (TTFamilyOrder[k].Equals(name[0]) && TTFamilyOrder[k + 1].Equals(name[1]) && TTFamilyOrder[k + 2].Equals(name[2]))
                     {
                         familyName = name[3].ToLower(CultureInfo.InvariantCulture);
                         k          = TTFamilyOrder.Length;
                         break;
                     }
                 }
             }
             if (familyName != null)
             {
                 String lastName = "";
                 names = (string[][])allNames[2]; //full name
                 foreach (string[] name in names)
                 {
                     for (int k = 0; k < TTFamilyOrder.Length; k += 3)
                     {
                         if (TTFamilyOrder[k].Equals(name[0]) && TTFamilyOrder[k + 1].Equals(name[1]) && TTFamilyOrder[k + 2].Equals(name[2]))
                         {
                             fullName = name[3];
                             if (fullName.Equals(lastName))
                             {
                                 continue;
                             }
                             lastName = fullName;
                             RegisterFamily(familyName, fullName, null);
                             break;
                         }
                     }
                 }
             }
         }
         else if (path.ToLower(CultureInfo.InvariantCulture).EndsWith(".ttc"))
         {
             if (alias != null)
             {
                 LOGGER.Error("You can't define an alias for a true type collection.");
             }
             string[] names = BaseFont.EnumerateTTCNames(path);
             for (int i = 0; i < names.Length; i++)
             {
                 Register(path + "," + i);
             }
         }
         else if (path.ToLower(CultureInfo.InvariantCulture).EndsWith(".afm") || path.ToLower(CultureInfo.InvariantCulture).EndsWith(".pfm"))
         {
             BaseFont bf         = BaseFont.CreateFont(path, BaseFont.CP1252, false);
             String   fullName   = (bf.FullFontName[0][3]).ToLower(CultureInfo.InvariantCulture);
             String   familyName = (bf.FamilyFontName[0][3]).ToLower(CultureInfo.InvariantCulture);
             String   psName     = bf.PostscriptFontName.ToLower(CultureInfo.InvariantCulture);
             RegisterFamily(familyName, fullName, null);
             trueTypeFonts[psName]   = path;
             trueTypeFonts[fullName] = path;
         }
         if (LOGGER.IsLogging(Level.TRACE))
         {
             LOGGER.Trace(String.Format("Registered {0}", path));
         }
     }
     catch (DocumentException de) {
         // this shouldn't happen
         throw de;
     }
     catch (System.IO.IOException ioe) {
         throw ioe;
     }
 }
Beispiel #29
0
 public static BaseFont GetFont(string fileName)
 {
     return(BaseFont.CreateFont(fileName, BaseFont.CP1252, BaseFont.EMBEDDED));
 }
Beispiel #30
0
        void exportDataTableToPdf(DataTable dtblTable, DataTable dtblTable6, DataTable dtblTable2, DataTable dtblTable7, DataTable dtblTable3, String strPdfPath, string strHeader, int year)
        {
            System.IO.FileStream fs       = new FileStream(strPdfPath, FileMode.Create, FileAccess.Write, FileShare.None);
            Document             document = new Document();

            document.SetPageSize(iTextSharp.text.PageSize.A4);
            PdfWriter writer = PdfWriter.GetInstance(document, fs);

            document.Open();


            //Report Header
            BaseFont  bfntHead   = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Font      fntHead    = new Font(bfntHead, 16, 1, Color.BLACK);
            Paragraph prgHeading = new Paragraph();

            prgHeading.Alignment = Element.ALIGN_CENTER;
            prgHeading.Add(new Chunk(strHeader.ToUpper(), fntHead));
            document.Add(prgHeading);

            //Author
            Paragraph prgAuthor = new Paragraph();
            BaseFont  btnAuthor = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Font      fntAuthor = new Font(btnAuthor, 8, 2, Color.BLACK);

            prgAuthor.Alignment = Element.ALIGN_RIGHT;
            prgAuthor.Add(new Chunk("Autor : Invicta Legal", fntAuthor));
            prgAuthor.Add(new Chunk("\nFecha : " + DateTime.Now.ToShortDateString(), fntAuthor));
            document.Add(prgAuthor);

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

            document.Add(p);

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


            //Write the table
            PdfPTable table = new PdfPTable(dtblTable.Columns.Count);
            // table.HorizontalAlignment = Element.ALIGN_JUSTIFIED ;

            //Table header
            BaseFont btnColumnHeader = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Font     fntColumnHeader = new Font(btnColumnHeader, 10, 1, Color.WHITE);

            for (int i = 0; i < dtblTable.Columns.Count; i++)
            {
                PdfPCell cell = new PdfPCell();
                cell.BackgroundColor = Color.GRAY;
                cell.AddElement(new Chunk(dtblTable.Columns[i].ColumnName.ToUpper(), fntColumnHeader));
                table.AddCell(cell);
            }
            //table Data
            for (int i = 0; i < dtblTable.Rows.Count; i++)
            {
                for (int j = 0; j < dtblTable.Columns.Count; j++)
                {
                    table.AddCell(dtblTable.Rows[i][j].ToString());
                }
            }

            //Write the table
            PdfPTable table6 = new PdfPTable(dtblTable6.Columns.Count);
            // table.HorizontalAlignment = Element.ALIGN_JUSTIFIED ;

            //Table header
            BaseFont btnColumnHeader6 = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Font     fntColumnHeader6 = new Font(btnColumnHeader6, 10, 1, Color.WHITE);

            for (int i = 0; i < dtblTable6.Columns.Count; i++)
            {
                PdfPCell cell = new PdfPCell();
                cell.BackgroundColor = Color.GRAY;
                cell.AddElement(new Chunk(dtblTable6.Columns[i].ColumnName.ToUpper(), fntColumnHeader));
                table6.AddCell(cell);
            }
            //table Data
            for (int i = 0; i < dtblTable6.Rows.Count; i++)
            {
                for (int j = 0; j < dtblTable6.Columns.Count; j++)
                {
                    table6.AddCell(dtblTable6.Rows[i][j].ToString());
                }
            }



            //Write the table
            PdfPTable table2 = new PdfPTable(dtblTable2.Columns.Count);
            //Table header
            BaseFont btnColumnHeader2 = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Font     fntColumnHeader2 = new Font(btnColumnHeader, 10, 1, Color.WHITE);

            for (int i = 0; i < dtblTable2.Columns.Count; i++)
            {
                PdfPCell cell = new PdfPCell();
                cell.BackgroundColor = Color.GRAY;
                cell.AddElement(new Chunk(dtblTable2.Columns[i].ColumnName.ToUpper(), fntColumnHeader));
                table2.AddCell(cell);
            }
            //table Data
            for (int i = 0; i < dtblTable2.Rows.Count; i++)
            {
                for (int j = 0; j < dtblTable2.Columns.Count; j++)
                {
                    table2.AddCell(dtblTable2.Rows[i][j].ToString());
                }
            }

            //Write the table
            PdfPTable table7 = new PdfPTable(dtblTable7.Columns.Count);
            // table.HorizontalAlignment = Element.ALIGN_JUSTIFIED ;

            //Table header
            BaseFont btnColumnHeader7 = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Font     fntColumnHeader7 = new Font(btnColumnHeader7, 10, 1, Color.WHITE);

            for (int i = 0; i < dtblTable7.Columns.Count; i++)
            {
                PdfPCell cell = new PdfPCell();
                cell.BackgroundColor = Color.GRAY;
                cell.AddElement(new Chunk(dtblTable7.Columns[i].ColumnName.ToUpper(), fntColumnHeader));
                table7.AddCell(cell);
            }
            //table Data
            for (int i = 0; i < dtblTable7.Rows.Count; i++)
            {
                for (int j = 0; j < dtblTable7.Columns.Count; j++)
                {
                    table7.AddCell(dtblTable7.Rows[i][j].ToString());
                }
            }

            //Write the table
            PdfPTable table3 = new PdfPTable(dtblTable3.Columns.Count);
            //Table header
            BaseFont btnColumnHeader3 = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Font     fntColumnHeader3 = new Font(btnColumnHeader, 10, 1, Color.WHITE);

            for (int i = 0; i < dtblTable3.Columns.Count; i++)
            {
                PdfPCell cell = new PdfPCell();
                cell.BackgroundColor = Color.GRAY;
                cell.AddElement(new Chunk(dtblTable3.Columns[i].ColumnName.ToUpper(), fntColumnHeader));
                table3.AddCell(cell);
            }
            //table Data
            for (int i = 0; i < dtblTable3.Rows.Count; i++)
            {
                for (int j = 0; j < dtblTable3.Columns.Count; j++)
                {
                    table3.AddCell(dtblTable3.Rows[i][j].ToString());
                }
            }


            //Titulo
            Paragraph prgAuthor2 = new Paragraph();
            BaseFont  btnAuthor2 = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Font      fntAuthor2 = new Font(btnAuthor2, 12, 2, Color.BLACK);

            prgAuthor2.Alignment = Element.ALIGN_LEFT;
            prgAuthor2.Add(new Chunk("Facturación Propia", fntAuthor2));

            //Titulo
            Paragraph prgAuthor3 = new Paragraph();
            BaseFont  btnAuthor3 = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Font      fntAuthor3 = new Font(btnAuthor3, 12, 2, Color.BLACK);

            prgAuthor3.Alignment = Element.ALIGN_LEFT;
            prgAuthor3.Add(new Chunk("Facturación CoNotariada", fntAuthor3));


            //Titulo
            Paragraph prgAuthor4 = new Paragraph();
            BaseFont  btnAuthor4 = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Font      fntAuthor4 = new Font(btnAuthor4, 12, 2, Color.BLACK);

            prgAuthor4.Alignment = Element.ALIGN_LEFT;
            prgAuthor4.Add(new Chunk("Resumen Periodo Fiscal " + year, fntAuthor4));



            document.Add(prgAuthor2);
            document.Add(new Chunk("\n", fntHead));
            document.Add(table);
            document.Add(table6);
            //Add line break
            document.Add(new Chunk("\n", fntHead));
            document.Add(prgAuthor3);
            document.Add(new Chunk("\n", fntHead));
            document.Add(table2);
            document.Add(table7);
            document.Add(new Chunk("\n", fntHead));
            document.Add(prgAuthor4);
            document.Add(new Chunk("\n", fntHead));
            document.Add(table3);
            document.Close();
            writer.Close();
            fs.Close();
        }