public virtual void CreatePdf(String dest)
        {
            PdfDocument pdf  = new PdfDocument(new PdfWriter(dest));
            PdfPage     page = pdf.AddNewPage();

            page.SetPageLabel(PageLabelNumberingStyle.LOWERCASE_ROMAN_NUMERALS, null);
            Document document = new Document(pdf);

            document.Add(new Paragraph().Add("Page left blank intentionally"));
            document.Add(new AreaBreak());
            document.Add(new Paragraph().Add("Page left blank intentionally"));
            document.Add(new AreaBreak());
            document.Add(new Paragraph().Add("Page left blank intentionally"));
            document.Add(new AreaBreak());
            page = pdf.GetLastPage();
            page.SetPageLabel(PageLabelNumberingStyle.DECIMAL_ARABIC_NUMERALS, null, 1);
            PdfFont font = PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN);
            PdfFont bold = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);

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

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

            tabstops.Add(new TabStop(580, TabAlignment.RIGHT, new DottedLine()));
            foreach (Util.Pair <String, Util.Pair <String, int> > entry in toc)
            {
                Util.Pair <String, int> text = entry.Value;
                p = new Paragraph().AddTabStops(tabstops).Add(text.Key).Add(new Tab()).Add(text.Value.ToString()).SetAction
                        (PdfAction.CreateGoTo(entry.Key));
                document.Add(p);
            }
            document.Close();
        }
        public virtual void CreatePdf(String dest)
        {
            //Initialize PDF document
            PdfDocument pdf = new PdfDocument(new PdfWriter(dest, new WriterProperties().SetFullCompressionMode(true))
                                              );

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

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

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

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

            tabstops.Add(new TabStop(580, TabAlignment.RIGHT, new DottedLine()));
            foreach (Util.Pair <String, Util.Pair <String, int> > entry in toc)
            {
                Util.Pair <String, int> text = entry.Value;
                p = new Paragraph().AddTabStops(tabstops).Add(text.Key).Add(new Tab()).Add(text.Value.ToString()).SetAction
                        (PdfAction.CreateGoTo(entry.Key));
                document.Add(p);
            }
            //Close document
            document.Close();
        }
Exemple #3
0
        private void AddCheckBox(PdfDocument pdfDoc, float fontSize, float yPos, float checkBoxW, PdfFormField checkBox
                                 )
        {
            PdfPage     page = pdfDoc.GetFirstPage();
            PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true);

            if (fontSize >= 0)
            {
                checkBox.SetFontSize(fontSize);
            }
            checkBox.SetBorderWidth(1);
            checkBox.SetBorderColor(ColorConstants.BLACK);
            form.AddField(checkBox, page);
            PdfCanvas canvas = new PdfCanvas(page);

            canvas.SaveState().BeginText().MoveText(50 + checkBoxW + 10, yPos).SetFontAndSize(PdfFontFactory.CreateFont
                                                                                                  (), 12).ShowText("okay?").EndText().RestoreState();
        }
        //static private ResumeData data;
        public DocumentBuilder()//ResumeData import)
        {
            //data = import;

            String    docname = "Test";
            PdfWriter writer  = null;
            bool      read    = false;

            try  // Try writing to file
            {
                writer = new PdfWriter(docname + ".pdf");
                read   = true;
            }
            catch  // Catch if file is open and display message to user
            {
                string            message = "Please close the open PDF or save using a different name.";
                string            caption = "Active PDF Open in Another Window";
                MessageBoxButtons buttons = MessageBoxButtons.OK;
                DialogResult      msg;
                msg = MessageBox.Show(message, caption, buttons);
                Console.WriteLine("Please close the pdf file that is open");
            }
            if (read)
            {
                PdfDocument pdf = new PdfDocument(writer);
                Document    doc = new Document(pdf);

                /* Import Data */
                JSONHandler jhandle = new JSONHandler();
                ResumeData  data    = jhandle.ReadFromJSON();


                /*---------------------------           Writing to doc            ------------------------------------*/



                /* Register Fonts */
                PdfFontFactory.RegisterDirectory("C:\\Windows\\Fonts");
                PdfFont Courier = PdfFontFactory.CreateRegisteredFont("Courier New");
                PdfFont Gothic  = PdfFontFactory.CreateRegisteredFont("Century Gothic");

                /* Create Content */
                Paragraph Name = new Paragraph(data.Name)
                                 .SetTextAlignment(TextAlignment.CENTER)
                                 .SetFont(Courier)
                                 .SetFontSize(34);

                Paragraph Bio = new Paragraph(data.Email + " | " + data.Phone + " | " + data.Address1)
                                .SetTextAlignment(TextAlignment.CENTER)
                                .SetFont(Gothic)
                                .SetFontSize(9);

                Paragraph Site = new Paragraph()
                                 .Add(new Link("Barnes7619.com", PdfAction.CreateURI("https://Barnes7619.com")).SetUnderline())
                                 .SetTextAlignment(TextAlignment.CENTER)
                                 .SetFont(Gothic)
                                 .SetFontSize(9);


                Table SummaryHead = CreateSeparator("Summary", Courier);

                Table EducationHead = CreateSeparator("Education & Training", Courier);

                Table SoftwareHead = CreateSeparator("Software Experience", Courier);

                Table ExperienceHead = CreateSeparator("Experience", Courier);

                Table SkillsHead = CreateSeparator("Skills", Courier);



                ///* Formatting */
                //Name.Alignment = Element.ALIGN_CENTER;
                //Bio.Alignment = Element.ALIGN_CENTER;
                //Site.Alignment = Element.ALIGN_CENTER;

                /* Add Content to Document */
                doc.Add(Name);
                doc.Add(Bio);
                doc.Add(Site);
                doc.Add(SummaryHead);
                doc.Add(EducationHead);
                doc.Add(SoftwareHead);
                doc.Add(ExperienceHead);
                doc.Add(SkillsHead);

                /* Close Document */
                doc.Close();



                /* -------------------------  Completed Message  --------------------------- */
                string            message = "Resume Generated!";
                string            caption = "Finished";
                MessageBoxButtons buttons = MessageBoxButtons.OK;
                DialogResult      msg;
                msg = MessageBox.Show(message, caption, buttons);
            }
        }
Exemple #5
0
        static void Main(string[] args)
        {
            //Initialization
            //retrieve input file lines on console input
            string input = Console.ReadLine();

            string[] lines = File.ReadAllLines(input);
            //retrieve input file name
            string file_name = input.Substring(input.LastIndexOf("\\")).Split('.')[0];
            //create output pdf file in the same folder with same name
            string    output = input.Substring(0, input.LastIndexOf("\\") + 1) + file_name + ".pdf";
            PdfWriter writer = new PdfWriter(new FileStream(output, FileMode.Create));
            //create objects to write in the pdf file
            PdfDocument pdf      = new PdfDocument(writer);
            Document    document = new Document(pdf);
            Paragraph   par      = new Paragraph();
            PdfFont     font     = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);
            Text        text     = new Text("");

            //Processing
            //Loop for each input line
            Boolean firstCommand = true;

            foreach (string line in lines)
            {
                if (line[0] == '.')   //if this line is a command
                {
                    if (firstCommand) //make sure it's not the second command in a row before appending previous text from the previous loop to the file
                    {
                        firstCommand = false;
                        par.Add(text);
                    }
                    switch (line)
                    { //apply changes to paragraph or text according to the command
                    case ".large":
                        document.Add(par);
                        par  = new Paragraph();
                        text = new Text("");
                        text.SetFontSize(30.0f);
                        break;

                    case ".normal":
                    case ".regular":
                        text = new Text("");
                        break;

                    case ".paragraph":
                        document.Add(par);
                        par = new Paragraph();
                        break;

                    case ".fill":
                        document.Add(par);
                        par = new Paragraph();
                        par.SetTextAlignment(TextAlignment.JUSTIFIED);
                        break;

                    case ".nofill":
                        document.Add(par);
                        par = new Paragraph();
                        par.SetTextAlignment(TextAlignment.LEFT);
                        break;

                    case ".italic":
                        text = new Text("");
                        text.SetItalic();
                        break;

                    case ".bold":
                        text = new Text("");
                        text.SetBold();
                        break;

                    default:
                        if (line.Split(' ')[0].Equals(".indent"))
                        {
                            par.SetMarginLeft(float.Parse(line.Split(' ')[1]) * 10.0f);
                        }
                        else
                        {
                            Debug.WriteLine("Met unknown command : " + line);
                        }
                        break;
                    }
                }
                else
                {
                    text.SetText(line);     //if not a command, set this line as text
                    firstCommand = true;
                }
            }
            //Last step : append the previous text and close file
            par.Add(text);
            document.Add(par);
            document.Close();
        }
        public Task <byte[]> ManipulatePdf(
            StampSimpleDto fileSource)
        {
            using MemoryStream pdfDest   = new MemoryStream();
            using MemoryStream pdfStream = new MemoryStream(fileSource.ImageSource);
            var pdfDoc = new PdfDocument(new PdfReader(pdfStream), new PdfWriter(pdfDest));
            var doc    = new Document(pdfDoc);

            foreach (TextPropertiesDto text in fileSource.Texts)
            {
                //var font = PdfFontFactory.CreateFont(FontProgramFactory.CreateFont(text.FontName));

                iText.Kernel.Colors.Color fontColor = iText.Kernel.Colors.ColorConstants.CYAN;
                switch (text.Color)
                {
                case "WHITE": fontColor = iText.Kernel.Colors.ColorConstants.WHITE; break;

                case "BLACK": fontColor = iText.Kernel.Colors.ColorConstants.BLACK; break;

                case "BLUE": fontColor = iText.Kernel.Colors.ColorConstants.BLUE; break;

                case "DARKGRAY": fontColor = iText.Kernel.Colors.ColorConstants.DARK_GRAY; break;

                case "GRAY": fontColor = iText.Kernel.Colors.ColorConstants.GRAY; break;

                case "GREEN": fontColor = iText.Kernel.Colors.ColorConstants.GREEN; break;

                case "MAGENTA": fontColor = iText.Kernel.Colors.ColorConstants.MAGENTA; break;

                case "ORANGE": fontColor = iText.Kernel.Colors.ColorConstants.ORANGE; break;

                case "PINK": fontColor = iText.Kernel.Colors.ColorConstants.PINK; break;

                case "RED": fontColor = iText.Kernel.Colors.ColorConstants.RED; break;

                case "YELLOW": fontColor = iText.Kernel.Colors.ColorConstants.YELLOW; break;
                }

                PdfFont fonte = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);
                try
                {
                    fonte = PdfFontFactory.CreateFont(text.FontName);
                }
                catch
                {
                    fonte = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);
                }
                var paragraph = new Paragraph(text.Text).SetFont(fonte).SetFontSize(text.FontSize).SetFontColor(fontColor);

                var gs1 = new PdfExtGState().SetFillOpacity(text.Opacity);

                for (int i = 1; i <= pdfDoc.GetNumberOfPages(); i++)
                {
                    PdfPage   pdfPage  = pdfDoc.GetPage(i);
                    Rectangle pageSize = pdfPage.GetPageSize();
                    float     x        = (pageSize.GetLeft() + pageSize.GetRight()) / 2;
                    float     y        = (pageSize.GetTop() + pageSize.GetBottom()) / 2;
                    var       over     = new PdfCanvas(pdfPage);
                    over.SaveState();
                    over.SetExtGState(gs1);

                    doc.ShowTextAligned(paragraph, text.PosX, text.PosY, i, TextAlignment.CENTER, VerticalAlignment.TOP, text.Radio);
                    over.RestoreState();
                }
            }

            doc.Close();

            return(Task.FromResult(pdfDest.ToArray()));
        }
        private void CrearPDF()
        {
            PdfWriter   pdfWriter = new PdfWriter("Reporte.pdf");
            PdfDocument pdf       = new PdfDocument(pdfWriter);
            Document    document  = new Document(pdf, PageSize.LETTER);

            document.SetMargins(60, 20, 55, 20);
            //var parrafo = new Paragraph("Hola mundo");
            //document.Add(parrafo);

            PdfFont fontColumnas  = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);
            PdfFont fontContenido = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);

            string[] columnas = { "Numero de ingreso", "Usuario", "Fecha y Hora" };//Id_Bitacora,Id_Usr,HORA
            float[]  tamanos  = { 4, 4, 4 };
            Table    tabla    = new Table(UnitValue.CreatePercentArray(tamanos));

            tabla.SetWidth(UnitValue.CreatePercentValue(100));
            foreach (string columna in columnas)
            {
                tabla.AddHeaderCell(new Cell().Add(new Paragraph(columna).SetFont(fontColumnas)));
            }
            string sql = "SELECT p.Id_Bitacora,p.Id_Usuario,p.HORA FROM bitacora AS p ";

            cn.Open();
            MySqlCommand    comando = new MySqlCommand(sql, cn);
            MySqlDataReader reader  = comando.ExecuteReader();

            while (reader.Read())
            {
                //for(int x = 1; x < 100; x++) {
                tabla.AddCell(new Cell().Add(new Paragraph(reader["Id_Bitacora"].ToString()).SetFont(fontContenido)));
                tabla.AddCell(new Cell().Add(new Paragraph(reader["Id_Usuario"].ToString()).SetFont(fontContenido)));
                tabla.AddCell(new Cell().Add(new Paragraph(reader["HORA"].ToString()).SetFont(fontContenido)));
                //}
            }
            document.Add(tabla);
            document.Close();
            var logo   = new iText.Layout.Element.Image(ImageDataFactory.Create("logo.png")).SetWidth(50);
            var plogo  = new Paragraph("").Add(logo);
            var titulo = new Paragraph("Reporte de ingresos al sistema");

            titulo.SetTextAlignment(TextAlignment.CENTER);
            titulo.SetFontSize(14);
            var dfecha = DateTime.Now.ToString("dd-MM-yyyy");
            var dhora  = DateTime.Now.ToString("hh:mm:ss");
            var fecha  = new Paragraph("Fecha: " + dfecha + " Hora: " + dhora);

            fecha.SetFontSize(8);
            PdfDocument pdfDoc  = new PdfDocument(new PdfReader("Reporte.pdf"), new PdfWriter("Reportefechado.pdf"));
            Document    doc     = new Document(pdfDoc);
            int         numeros = pdfDoc.GetNumberOfPages();

            for (int i = 1; i <= numeros; i++)
            {
                PdfPage pagina = pdfDoc.GetPage(i);
                float   y      = (pdfDoc.GetPage(i).GetPageSize().GetTop() - 15);
                doc.ShowTextAligned(plogo, 40, y, i, TextAlignment.CENTER, VerticalAlignment.TOP, 0);
                doc.ShowTextAligned(titulo, 150, y, i, TextAlignment.CENTER, VerticalAlignment.TOP, 0);
                doc.ShowTextAligned(fecha, 520, y, i, TextAlignment.CENTER, VerticalAlignment.TOP, 0);
                doc.ShowTextAligned(new Paragraph(String.Format("Página {0} de {1}", i, numeros)), pdfDoc.GetPage(i).GetPageSize().GetWidth() / 2, pdfDoc.GetPage(i).GetPageSize().GetBottom() + 30, i, TextAlignment.CENTER, VerticalAlignment.TOP, 0);
            }
            doc.Close();
        }
        public static PdfFont GetSystemFont()
        {
            string path = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "msjhbd.ttc,0");

            return(PdfFontFactory.CreateFont(path, PdfEncodings.IDENTITY_H, true));
        }
        //微軟正黑體 itext 7.1.5修改字體功能正常
        public static PdfFont GetMsjhbdFont()
        {
            string path = System.IO.Path.Combine(Constant.FONT_FOLDER, "msjhbd.ttc,0");

            return(PdfFontFactory.CreateFont(path, PdfEncodings.IDENTITY_H, true));
        }
        private Table consultamaterial(int valor)
        {
            //estilo titulo tabla
            Style   titulo = new Style();
            PdfFont f      = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLDOBLIQUE);

            titulo.SetFont(f).SetFontSize(16).SetTextAlignment(TextAlignment.CENTER);

            //estilo encabezado
            Style   encabezado = new Style();
            PdfFont f1         = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);

            encabezado.SetFont(f1).SetFontSize(12).SetTextAlignment(TextAlignment.LEFT);

            //estilo cuerpo general
            Style   cuerpogeneral = new Style();
            PdfFont f2            = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);

            cuerpogeneral.SetFont(f2).SetFontSize(12).SetTextAlignment(TextAlignment.LEFT);

            //estilo totales
            Style   cuerpototal = new Style();
            PdfFont f3          = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);

            cuerpototal.SetFont(f3).SetFontSize(12).SetTextAlignment(TextAlignment.LEFT);

            //creacion de la tabla
            Table table = new Table(new float[9]).UseAllAvailableWidth();

            table.SetMarginTop(0);
            table.SetMarginBottom(0);
            Cell cell = new Cell(1, 9);

            // first row
            if (valor == 1)
            {
                cell.Add(new Paragraph("Reporte del dia " + DateTime.Now.ToShortDateString()));
            }
            else if (valor == 2)
            {
                cell.Add(new Paragraph("Reporte del Mes de " + CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.Now.Month)));
            }
            else
            {
                cell.Add(new Paragraph("Reporte del año " + DateTime.Now.Year.ToString()));
            }

            cell.AddStyle(titulo);
            cell.SetTextAlignment(TextAlignment.CENTER);
            cell.SetPadding(3);
            cell.SetBackgroundColor(new DeviceRgb(140, 221, 8));
            table.AddCell(cell);

            table.AddCell("Material").AddStyle(encabezado);
            table.AddCell("Producccion en flex").AddStyle(encabezado);
            table.AddCell("Produccion en Speed").AddStyle(encabezado);
            table.AddCell("Produccion en 360").AddStyle(encabezado);
            table.AddCell("Usado en flex").AddStyle(encabezado);
            table.AddCell("Usado en speed").AddStyle(encabezado);
            table.AddCell("Usado en 360").AddStyle(encabezado);
            table.AddCell("Fecha de registro").AddStyle(encabezado);
            table.AddCell("Registrado por").AddStyle(encabezado);

            int    anio = DateTime.Now.Year;
            string mes;

            if (DateTime.Now.Month < 10)
            {
                mes = "0" + DateTime.Now.Month.ToString();
            }
            else
            {
                mes = DateTime.Now.Month.ToString();
            }
            int    dia = DateTime.Now.Day;
            string Query, Query2;

            //del dia
            if (valor == 1)
            {
                Query  = "SELECT nombre,prod_flex,prod_speed,prod_360,material_flex,material_speed,material_360,fecha_produccion,usuario FROM inventarioprograma.materialregistro where fecha_produccion >= ('" + anio + "-" + mes + "-" + dia + " 00:00:00') and fecha_produccion < ('" + anio + "-" + mes + "-" + (dia + 1) + " 00:00:00') order by fecha_produccion";
                Query2 = "SELECT nombre,sum(prod_flex),sum(prod_speed),sum(prod_360),sum(material_flex),sum(material_speed),sum(material_360) FROM inventarioprograma.materialregistro where fecha_produccion >= ('" + anio + "-" + mes + "-" + dia + " 00:00:00') and fecha_produccion < ('" + anio + "-" + mes + "-" + (dia + 1) + " 00:00:00') group by nombre;";
            }
            //del mes
            else if (valor == 2)
            {
                Query  = "SELECT nombre,prod_flex,prod_speed,prod_360,material_flex,material_speed,material_360,fecha_produccion,usuario FROM inventarioprograma.materialregistro where fecha_produccion like ('" + anio + "-" + mes + "%') order by fecha_produccion";
                Query2 = "SELECT nombre,sum(prod_flex),sum(prod_speed),sum(prod_360),sum(material_flex),sum(material_speed),sum(material_360) FROM inventarioprograma.materialregistro where fecha_produccion like ('" + anio + "-" + mes + "%') group by nombre;";
            }
            //anual
            else
            {
                Query  = "SELECT nombre,prod_flex,prod_speed,prod_360,material_flex,material_speed,material_360,fecha_produccion,usuario FROM inventarioprograma.materialregistro where fecha_produccion like ('" + DateTime.Now.Year + "%') order by fecha_produccion";
                Query2 = "SELECT nombre,sum(prod_flex),sum(prod_speed),sum(prod_360),sum(material_flex),sum(material_speed),sum(material_360) FROM inventarioprograma.materialregistro where fecha_produccion like ('" + DateTime.Now.Year + "%') group by nombre;";
            }

            MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
            var             cmd     = new MySqlCommand(Query, MyConn2);

            MyConn2.Open();
            MySqlDataReader rdr = cmd.ExecuteReader();

            while (rdr.Read())
            {
                table.AddCell(new Paragraph(rdr.GetString(0)).AddStyle(cuerpogeneral));
                table.AddCell(new Paragraph(rdr.GetString(1)).AddStyle(cuerpogeneral));
                table.AddCell(new Paragraph(rdr.GetString(2)).AddStyle(cuerpogeneral));
                table.AddCell(new Paragraph(rdr.GetString(3)).AddStyle(cuerpogeneral));
                table.AddCell(new Paragraph(rdr.GetString(4)).AddStyle(cuerpogeneral));
                table.AddCell(new Paragraph(rdr.GetString(5)).AddStyle(cuerpogeneral));
                table.AddCell(new Paragraph(rdr.GetString(6)).AddStyle(cuerpogeneral));
                table.AddCell(new Paragraph(rdr.GetString(7)).AddStyle(cuerpogeneral));
                table.AddCell(new Paragraph(rdr.GetString(8)).AddStyle(cuerpogeneral));
            }
            MyConn2.Close();

            cell.AddStyle(cuerpototal);
            //totales
            var cmd2 = new MySqlCommand(Query2, MyConn2);

            MyConn2.Open();
            MySqlDataReader rdr2 = cmd2.ExecuteReader();

            while (rdr2.Read())
            {
                table.AddCell(new Paragraph(rdr2.GetString(0)));
                table.AddCell(new Paragraph(rdr2.GetString(1)));
                table.AddCell(new Paragraph(rdr2.GetString(2)));
                table.AddCell(new Paragraph(rdr2.GetString(3)));
                table.AddCell(new Paragraph(rdr2.GetString(4)));
                table.AddCell(new Paragraph(rdr2.GetString(5)));
                table.AddCell(new Paragraph(rdr2.GetString(6)));
                table.AddCell(new Paragraph("----------"));
                table.AddCell(new Paragraph("----------"));
            }
            MyConn2.Close();

            return(table);
        }
Exemple #11
0
        public virtual void CreatePdf(String dest)
        {
            //Initialize PDF document
            PdfDocument pdf = new PdfDocument(new PdfWriter(dest));

            pdf.GetCatalog().SetOpenAction(PdfDestination.MakeDestination(new PdfString("toc")));
            pdf.GetCatalog().SetAdditionalAction(PdfName.WC, PdfAction.CreateJavaScript("app.alert('Thank you for reading');"
                                                                                        ));
            pdf.AddNewPage().SetAdditionalAction(PdfName.O, PdfAction.CreateJavaScript("app.alert('This is where it starts!');"
                                                                                       ));
            // Initialize document
            Document document = new Document(pdf);
            PdfFont  font     = PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN);
            PdfFont  bold     = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);

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

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

            tabstops.Add(new TabStop(580, TabAlignment.RIGHT, new DottedLine()));
            foreach (Util.Pair <String, Util.Pair <String, int> > entry in toc)
            {
                Util.Pair <String, int> text = entry.Value;
                p = new Paragraph().AddTabStops(tabstops).Add(text.Key).Add(new Tab()).Add(text.Value.ToString()).SetAction
                        (PdfAction.CreateGoTo(entry.Key));
                document.Add(p);
            }
            PdfPage page = pdf.GetLastPage();

            page.SetAdditionalAction(PdfName.C, PdfAction.CreateJavaScript("app.alert('Goodbye last page!');"));
            //Close document
            document.Close();
        }
        public void crearpdf(int valor)
        {
            try
            {
                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.InitialDirectory = @"C:\\Users\\";
                saveFileDialog1.Title            = "Indique donde guardar el pdf";
                saveFileDialog1.DefaultExt       = "pdf";
                saveFileDialog1.Filter           = "Archivo PDF(*.pdf)|*.pdf";
                saveFileDialog1.FilterIndex      = 2;
                saveFileDialog1.RestoreDirectory = true;
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    Style   titulo = new Style();
                    PdfFont f      = PdfFontFactory.CreateFont(StandardFonts.TIMES_BOLD);
                    titulo.SetFont(f).SetFontSize(20).SetTextAlignment(TextAlignment.CENTER);
                    Style   subtitulo = new Style();
                    PdfFont f1        = PdfFontFactory.CreateFont(StandardFonts.TIMES_ITALIC);
                    subtitulo.SetFont(f1).SetFontSize(16).SetTextAlignment(TextAlignment.CENTER);
                    FileInfo file = new FileInfo(saveFileDialog1.FileName);
                    file.Directory.Create();
                    //Initialize PDF writer
                    PdfWriter writer = new PdfWriter(saveFileDialog1.FileName);
                    //Initialize PDF document
                    PdfDocument pdf = new PdfDocument(writer);
                    PageSize    ps  = PageSize.LETTER;

                    // Initialize document
                    Document document = new Document(pdf);

                    //Add paragraph to the document
                    Paragraph title = new Paragraph("Helmets & Stuff").AddStyle(titulo);
                    document.Add(title);
                    Paragraph tema;
                    if (valor > 0 && valor < 4)
                    {
                        tema = new Paragraph("Reporte de producciones").AddStyle(subtitulo);
                    }
                    else
                    {
                        tema = new Paragraph("Reporte de materiales").AddStyle(subtitulo);
                    }
                    document.Add(tema);

                    Table table = consultamaterial(valor);

                    if (valor > 0 && valor < 4)
                    {
                        table = consultamaterial(valor);
                    }
                    else if (valor == 4)
                    {
                        table = consultausado();
                    }
                    else
                    {
                        table = consultasobrante();
                    }


                    document.Add(table);
                    //Close document
                    document.Close();

                    MessageBox.Show("Documento creado", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ha sucedido un error, compruebe que el archivo no este abierto " + ex.Message, "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private Table consultasobrante()
        {
            //estilo titulo tabla
            Style   titulo = new Style();
            PdfFont f      = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLDOBLIQUE);

            titulo.SetFont(f).SetFontSize(16).SetTextAlignment(TextAlignment.CENTER);

            //estilo encabezado
            Style   encabezado = new Style();
            PdfFont f1         = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);

            encabezado.SetFont(f1).SetFontSize(12).SetTextAlignment(TextAlignment.LEFT);

            //estilo cuerpo general
            Style   cuerpogeneral = new Style();
            PdfFont f2            = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);

            cuerpogeneral.SetFont(f2).SetFontSize(12).SetTextAlignment(TextAlignment.LEFT);

            //creacion de la tabla
            Table table = new Table(new float[7]).UseAllAvailableWidth();

            table.SetMarginTop(0);
            table.SetMarginBottom(0);
            Cell cell = new Cell(1, 7);

            cell.Add(new Paragraph("Reporte de materiales sobrantes"));

            cell.AddStyle(titulo);
            cell.SetTextAlignment(TextAlignment.CENTER);
            cell.SetPadding(3);
            cell.SetBackgroundColor(new DeviceRgb(140, 221, 8));
            table.AddCell(cell);

            table.AddCell("Material").AddStyle(encabezado);
            table.AddCell("Cantidad en existencia").AddStyle(encabezado);
            table.AddCell("Cantidad para alerta").AddStyle(encabezado);
            table.AddCell("Cantidad usada en speed").AddStyle(encabezado);
            table.AddCell("Cantidad usada en flex").AddStyle(encabezado);
            table.AddCell("Cantidad usada en 360").AddStyle(encabezado);
            table.AddCell("Usuario que registro").AddStyle(encabezado);

            string Query = "SELECT nombre,cantidad_inicial,stock_alert,cant_speed,cant_flex,cant_360,usuario FROM inventarioprograma.materialusario;";

            MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
            var             cmd     = new MySqlCommand(Query, MyConn2);

            MyConn2.Open();
            MySqlDataReader rdr = cmd.ExecuteReader();

            while (rdr.Read())
            {
                table.AddCell(new Paragraph(rdr.GetString(0)).AddStyle(cuerpogeneral));
                table.AddCell(new Paragraph(rdr.GetString(1)).AddStyle(cuerpogeneral));
                table.AddCell(new Paragraph(rdr.GetString(2)).AddStyle(cuerpogeneral));
                table.AddCell(new Paragraph(rdr.GetString(3)).AddStyle(cuerpogeneral));
                table.AddCell(new Paragraph(rdr.GetString(4)).AddStyle(cuerpogeneral));
                table.AddCell(new Paragraph(rdr.GetString(5)).AddStyle(cuerpogeneral));
                table.AddCell(new Paragraph(rdr.GetString(6)).AddStyle(cuerpogeneral));
            }
            MyConn2.Close();
            return(table);
        }
        private Table consultausado()
        {
            //estilo titulo tabla
            Style   titulo = new Style();
            PdfFont f      = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLDOBLIQUE);

            titulo.SetFont(f).SetFontSize(16).SetTextAlignment(TextAlignment.CENTER);

            //estilo encabezado
            Style   encabezado = new Style();
            PdfFont f1         = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);

            encabezado.SetFont(f1).SetFontSize(12).SetTextAlignment(TextAlignment.LEFT);

            //estilo cuerpo general
            Style   cuerpogeneral = new Style();
            PdfFont f2            = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);

            cuerpogeneral.SetFont(f2).SetFontSize(12).SetTextAlignment(TextAlignment.LEFT);

            //creacion de la tabla
            Table table = new Table(new float[5]).UseAllAvailableWidth();

            table.SetMarginTop(0);
            table.SetMarginBottom(0);
            Cell cell = new Cell(1, 5);

            cell.Add(new Paragraph("Reporte de materiales utilizados"));

            cell.AddStyle(titulo);
            cell.SetTextAlignment(TextAlignment.CENTER);
            cell.SetPadding(3);
            cell.SetBackgroundColor(new DeviceRgb(140, 221, 8));
            table.AddCell(cell);

            table.AddCell("Material").AddStyle(encabezado);
            table.AddCell("Cantidad usada en flex").AddStyle(encabezado);
            table.AddCell("Cantidad usada en speed").AddStyle(encabezado);
            table.AddCell("Cantidad usada en 360").AddStyle(encabezado);
            table.AddCell("Cantidad usada en total").AddStyle(encabezado);

            string Query = "SELECT nombre,sum(material_flex),sum(material_speed),sum(material_360) FROM inventarioprograma.materialregistro group by nombre;";

            MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
            var             cmd     = new MySqlCommand(Query, MyConn2);

            MyConn2.Open();
            MySqlDataReader rdr = cmd.ExecuteReader();

            while (rdr.Read())
            {
                table.AddCell(new Paragraph(rdr.GetString(0)).AddStyle(cuerpogeneral));
                table.AddCell(new Paragraph(rdr.GetString(1)).AddStyle(cuerpogeneral));
                table.AddCell(new Paragraph(rdr.GetString(2)).AddStyle(cuerpogeneral));
                table.AddCell(new Paragraph(rdr.GetString(3)).AddStyle(cuerpogeneral));
                int total = rdr.GetInt32(1) + rdr.GetInt32(2) + rdr.GetInt32(3);
                table.AddCell(new Paragraph(total.ToString()).AddStyle(cuerpogeneral));
            }
            MyConn2.Close();
            return(table);
        }
Exemple #15
0
        /// <summary>Constructs appearance (top-level) for a signature.</summary>
        /// <remarks>
        /// Constructs appearance (top-level) for a signature.
        /// <p>
        /// Consult <A HREF="http://partners.adobe.com/asn/developer/pdfs/tn/PPKAppearances.pdf">PPKAppearances.pdf</A>
        /// for further details.
        /// </remarks>
        /// <returns>a top-level signature appearance</returns>
        /// <exception cref="System.IO.IOException"/>
        protected internal virtual PdfFormXObject GetAppearance()
        {
            PdfCanvas canvas;

            if (IsInvisible())
            {
                PdfFormXObject appearance = new PdfFormXObject(new Rectangle(0, 0));
                appearance.MakeIndirect(document);
                return(appearance);
            }
            if (n0 == null && !reuseAppearance)
            {
                CreateBlankN0();
            }
            if (n2 == null)
            {
                n2 = new PdfFormXObject(rect);
                n2.MakeIndirect(document);
                String text;
                if (layer2Text == null)
                {
                    StringBuilder buf = new StringBuilder();
                    buf.Append("Digitally signed by ");
                    String name = null;
                    CertificateInfo.X500Name x500name = CertificateInfo.GetSubjectFields((X509Certificate)signCertificate);
                    if (x500name != null)
                    {
                        name = x500name.GetField("CN");
                        if (name == null)
                        {
                            name = x500name.GetField("E");
                        }
                    }
                    if (name == null)
                    {
                        name = "";
                    }
                    buf.Append(name).Append('\n');
                    buf.Append("Date: ").Append(SignUtils.DateToString(signDate));
                    if (reason != null)
                    {
                        buf.Append('\n').Append(reasonCaption).Append(reason);
                    }
                    if (location != null)
                    {
                        buf.Append('\n').Append(locationCaption).Append(location);
                    }
                    text = buf.ToString();
                }
                else
                {
                    text = layer2Text;
                }
                if (image != null)
                {
                    if (imageScale == 0)
                    {
                        canvas = new PdfCanvas(n2, document);
                        canvas.AddImage(image, rect.GetWidth(), 0, 0, rect.GetHeight(), 0, 0);
                    }
                    else
                    {
                        float usableScale = imageScale;
                        if (imageScale < 0)
                        {
                            usableScale = Math.Min(rect.GetWidth() / image.GetWidth(), rect.GetHeight() / image.GetHeight());
                        }
                        float w = image.GetWidth() * usableScale;
                        float h = image.GetHeight() * usableScale;
                        float x = (rect.GetWidth() - w) / 2;
                        float y = (rect.GetHeight() - h) / 2;
                        canvas = new PdfCanvas(n2, document);
                        canvas.AddImage(image, w, 0, 0, h, x, y);
                    }
                }
                PdfFont font;
                if (layer2Font == null)
                {
                    font = PdfFontFactory.CreateFont();
                }
                else
                {
                    font = layer2Font;
                }
                Rectangle dataRect      = null;
                Rectangle signatureRect = null;
                if (renderingMode == PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION || renderingMode == PdfSignatureAppearance.RenderingMode
                    .GRAPHIC_AND_DESCRIPTION && this.signatureGraphic != null)
                {
                    if (rect.GetHeight() > rect.GetWidth())
                    {
                        signatureRect = new Rectangle(MARGIN, rect.GetHeight() / 2, rect.GetWidth() - 2 * MARGIN, rect.GetHeight()
                                                      / 2);
                        dataRect = new Rectangle(MARGIN, MARGIN, rect.GetWidth() - 2 * MARGIN, rect.GetHeight() / 2 - 2 * MARGIN);
                    }
                    else
                    {
                        // origin is the bottom-left
                        signatureRect = new Rectangle(MARGIN, MARGIN, rect.GetWidth() / 2 - 2 * MARGIN, rect.GetHeight() - 2 * MARGIN
                                                      );
                        dataRect = new Rectangle(rect.GetWidth() / 2 + MARGIN / 2, MARGIN, rect.GetWidth() / 2 - MARGIN, rect.GetHeight
                                                     () - 2 * MARGIN);
                    }
                }
                else
                {
                    if (renderingMode == PdfSignatureAppearance.RenderingMode.GRAPHIC)
                    {
                        if (signatureGraphic == null)
                        {
                            throw new InvalidOperationException("A signature image must be present when rendering mode is graphic. Use setSignatureGraphic()"
                                                                );
                        }
                        signatureRect = new Rectangle(MARGIN, MARGIN, rect.GetWidth() - 2 * MARGIN, rect.GetHeight() - 2 * MARGIN);
                    }
                    else
                    {
                        // take all space available
                        dataRect = new Rectangle(MARGIN, MARGIN, rect.GetWidth() - 2 * MARGIN, rect.GetHeight() * (1 - TOP_SECTION
                                                                                                                   ) - 2 * MARGIN);
                    }
                }
                switch (renderingMode)
                {
                case PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION: {
                    String signedBy = CertificateInfo.GetSubjectFields((X509Certificate)signCertificate).GetField("CN");
                    if (signedBy == null)
                    {
                        signedBy = CertificateInfo.GetSubjectFields((X509Certificate)signCertificate).GetField("E");
                    }
                    if (signedBy == null)
                    {
                        signedBy = "";
                    }
                    AddTextToCanvas(signedBy, font, signatureRect);
                    break;
                }

                case PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION: {
                    if (signatureGraphic == null)
                    {
                        throw new InvalidOperationException("A signature image must be present when rendering mode is graphic and description. Use setSignatureGraphic()"
                                                            );
                    }
                    float imgWidth = signatureGraphic.GetWidth();
                    if (imgWidth == 0)
                    {
                        imgWidth = signatureRect.GetWidth();
                    }
                    float imgHeight = signatureGraphic.GetHeight();
                    if (imgHeight == 0)
                    {
                        imgHeight = signatureRect.GetHeight();
                    }
                    float multiplierH = signatureRect.GetWidth() / signatureGraphic.GetWidth();
                    float multiplierW = signatureRect.GetHeight() / signatureGraphic.GetHeight();
                    float multiplier  = Math.Min(multiplierH, multiplierW);
                    imgWidth  *= multiplier;
                    imgHeight *= multiplier;
                    float x = signatureRect.GetRight() - imgWidth;
                    float y = signatureRect.GetBottom() + (signatureRect.GetHeight() - imgHeight) / 2;
                    canvas = new PdfCanvas(n2, document);
                    canvas.AddImage(signatureGraphic, imgWidth, 0, 0, imgHeight, x, y);
                    break;
                }

                case PdfSignatureAppearance.RenderingMode.GRAPHIC: {
                    float imgWidth_1 = signatureGraphic.GetWidth();
                    if (imgWidth_1 == 0)
                    {
                        imgWidth_1 = signatureRect.GetWidth();
                    }
                    float imgHeight_1 = signatureGraphic.GetHeight();
                    if (imgHeight_1 == 0)
                    {
                        imgHeight_1 = signatureRect.GetHeight();
                    }
                    float multiplierH_1 = signatureRect.GetWidth() / signatureGraphic.GetWidth();
                    float multiplierW_1 = signatureRect.GetHeight() / signatureGraphic.GetHeight();
                    float multiplier_1  = Math.Min(multiplierH_1, multiplierW_1);
                    imgWidth_1  *= multiplier_1;
                    imgHeight_1 *= multiplier_1;
                    float x_1 = signatureRect.GetLeft() + (signatureRect.GetWidth() - imgWidth_1) / 2;
                    float y_1 = signatureRect.GetBottom() + (signatureRect.GetHeight() - imgHeight_1) / 2;
                    canvas = new PdfCanvas(n2, document);
                    canvas.AddImage(signatureGraphic, imgWidth_1, 0, 0, imgHeight_1, x_1, y_1);
                    break;
                }
                }
                if (renderingMode != PdfSignatureAppearance.RenderingMode.GRAPHIC)
                {
                    AddTextToCanvas(text, font, dataRect);
                }
            }
            int       rotation = document.GetPage(page).GetRotation();
            Rectangle rotated  = new Rectangle(rect);

            if (topLayer == null)
            {
                topLayer = new PdfFormXObject(rotated);
                topLayer.MakeIndirect(document);
                canvas = new PdfCanvas(topLayer, document);
                if (rotation == 90)
                {
                    canvas.ConcatMatrix(0, 1, -1, 0, rect.GetHeight(), 0);
                }
                else
                {
                    if (rotation == 180)
                    {
                        canvas.ConcatMatrix(-1, 0, 0, -1, rect.GetWidth(), rect.GetHeight());
                    }
                    else
                    {
                        if (rotation == 270)
                        {
                            canvas.ConcatMatrix(0, -1, 1, 0, 0, rect.GetWidth());
                        }
                    }
                }
                if (reuseAppearance)
                {
                    PdfAcroForm    acroForm = PdfAcroForm.GetAcroForm(document, true);
                    PdfFormField   field    = acroForm.GetField(fieldName);
                    PdfStream      stream   = field.GetWidgets()[0].GetAppearanceDictionary().GetAsStream(PdfName.N);
                    PdfFormXObject xobj     = new PdfFormXObject(stream);
                    if (stream != null)
                    {
                        topLayer.GetResources().AddForm(xobj, new PdfName("n0"));
                        PdfCanvas canvas1 = new PdfCanvas(topLayer, document);
                        canvas1.AddXObject(xobj, 1, 0, 0, 1, 0, 0);
                    }
                    else
                    {
                        reuseAppearance = false;
                        if (n0 == null)
                        {
                            CreateBlankN0();
                        }
                    }
                }
                if (!reuseAppearance)
                {
                    topLayer.GetResources().AddForm(n0, new PdfName("n0"));
                    PdfCanvas canvas1 = new PdfCanvas(topLayer, document);
                    canvas1.AddXObject(n0, 1, 0, 0, 1, 0, 0);
                }
                topLayer.GetResources().AddForm(n2, new PdfName("n2"));
                PdfCanvas canvas1_1 = new PdfCanvas(topLayer, document);
                canvas1_1.AddXObject(n2, 1, 0, 0, 1, 0, 0);
            }
            PdfFormXObject napp = new PdfFormXObject(rotated);

            napp.MakeIndirect(document);
            napp.GetResources().AddForm(topLayer, new PdfName("FRM"));
            canvas = new PdfCanvas(napp, document);
            canvas.AddXObject(topLayer, 0, 0);
            return(napp);
        }
        public virtual void StructElemTest03()
        {
            FileStream fos    = new FileStream(destinationFolder + "structElemTest03.pdf", FileMode.Create);
            PdfWriter  writer = new PdfWriter(fos);

            writer.SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
            PdfDocument document = new PdfDocument(writer);

            document.SetTagged();
            document.GetStructTreeRoot().GetRoleMap().Put(new PdfName("Chunk"), PdfName.Span);
            PdfStructElem doc    = document.GetStructTreeRoot().AddKid(new PdfStructElem(document, PdfName.Document));
            PdfPage       page1  = document.AddNewPage();
            PdfCanvas     canvas = new PdfCanvas(page1);

            canvas.BeginText();
            canvas.SetFontAndSize(PdfFontFactory.CreateFont(FontConstants.COURIER), 24);
            canvas.SetTextMatrix(1, 0, 0, 1, 32, 512);
            PdfStructElem paragraph = doc.AddKid(new PdfStructElem(document, PdfName.P));
            PdfStructElem span1     = paragraph.AddKid(new PdfStructElem(document, PdfName.Span, page1));

            canvas.OpenTag(new CanvasTag(span1.AddKid(new PdfMcrNumber(page1, span1))));
            canvas.ShowText("Hello ");
            canvas.CloseTag();
            PdfStructElem span2 = paragraph.AddKid(new PdfStructElem(document, new PdfName("Chunk"), page1));

            canvas.OpenTag(new CanvasTag(span2.AddKid(new PdfMcrNumber(page1, span2))));
            canvas.ShowText("World");
            canvas.CloseTag();
            canvas.EndText();
            canvas.Release();
            PdfPage page2 = document.AddNewPage();

            canvas = new PdfCanvas(page2);
            canvas.BeginText();
            canvas.SetFontAndSize(PdfFontFactory.CreateFont(FontConstants.HELVETICA), 24);
            canvas.SetTextMatrix(1, 0, 0, 1, 32, 512);
            paragraph = doc.AddKid(new PdfStructElem(document, PdfName.P));
            span1     = paragraph.AddKid(new PdfStructElem(document, PdfName.Span, page2));
            canvas.OpenTag(new CanvasTag(span1.AddKid(new PdfMcrNumber(page2, span1))));
            canvas.ShowText("Hello ");
            canvas.CloseTag();
            span2 = paragraph.AddKid(new PdfStructElem(document, new PdfName("Chunk"), page2));
            canvas.OpenTag(new CanvasTag(span2.AddKid(new PdfMcrNumber(page2, span2))));
            canvas.ShowText("World");
            canvas.CloseTag();
            canvas.EndText();
            canvas.Release();
            page1.Flush();
            page2.Flush();
            document.Close();
            PdfReader reader = new PdfReader(new FileStream(destinationFolder + "structElemTest03.pdf", FileMode.Open,
                                                            FileAccess.Read));

            document = new PdfDocument(reader);
            NUnit.Framework.Assert.AreEqual(2, (int)document.GetNextStructParentIndex());
            PdfPage page = document.GetPage(1);

            NUnit.Framework.Assert.AreEqual(0, page.GetStructParentIndex());
            NUnit.Framework.Assert.AreEqual(2, page.GetNextMcid());
            document.Close();
        }
Exemple #17
0
 public static void InitializeFont()
 {
     pdfFont = PdfFontFactory.CreateFont();
 }
Exemple #18
0
        public void ReporteVentas2()
        {
            FileInfo file = new FileInfo(DEST);

            file.Directory.Create();

            string      dest   = "c:/temp/reporte_ventas1.pdf";
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest,
                                                               new WriterProperties().AddUAXmpMetadata().SetPdfVersion
                                                                   (PdfVersion.PDF_1_7)));
            Document document = new Document(pdfDoc, PageSize.LETTER.Rotate());

            //PDF/UA
            //Set document metadata
            pdfDoc.GetCatalog().SetViewerPreferences(new PdfViewerPreferences().SetDisplayDocTitle(true));
            pdfDoc.GetCatalog().SetLang(new PdfString("en-US"));
            PdfDocumentInfo info = pdfDoc.GetDocumentInfo();

            info.SetTitle("Reporte de Ventas de la Semana");

            float[] columnWidths = { 0.5f, 1, 5, 1 };
            Table   tabla        = new Table(UnitValue.CreatePercentArray(columnWidths));

            //tabla.SetWidth();
            tabla.UseAllAvailableWidth();
            PdfFont font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);
            // celda de encabezado

            Text txt = new Text("Reporte de Ventas Semanal")
                       .SetFontSize(20)
                       .SetBold();

            Paragraph pTitulo = new Paragraph(txt)
                                .SetTextAlignment(TextAlignment.CENTER);

            document.Add(pTitulo);

            //Cell cell = new Cell(1, 4)
            //    .Add(new Paragraph("Reporte de Ventas Semanal"))
            //    .SetFont(font)
            //    .SetFontSize(13)
            //    .SetFontColor(DeviceGray.WHITE)
            //    .SetBackgroundColor(DeviceGray.BLACK)
            //    .SetTextAlignment(TextAlignment.CENTER);

            //tabla.AddHeaderCell(cell);

            for (int i = 0; i < 2; i++)
            {
                Cell[] headerFooter =
                {
                    new Cell()
                    .SetBackgroundColor(new DeviceGray(0.75f))
                    .Add(new Paragraph("No."))
                    .SetBorder(Border.NO_BORDER),
                    new Cell()
                    .SetBackgroundColor(new DeviceGray(0.75f))
                    .Add(new Paragraph("Cant."))
                    .SetBorder(Border.NO_BORDER),
                    new Cell()
                    .SetBackgroundColor(new DeviceGray(0.75f))
                    .Add(new Paragraph("Artículo"))
                    .SetBorder(Border.NO_BORDER),
                    new Cell()
                    .SetBackgroundColor(new DeviceGray(0.75f))
                    .Add(new Paragraph("Total"))
                    .SetBorder(Border.NO_BORDER)
                };

                foreach (Cell hfCell in headerFooter)
                {
                    if (i == 0)
                    {
                        tabla.AddHeaderCell(hfCell);
                    }
                    //    else
                    //    {
                    //        tabla.AddFooterCell(hfCell);
                    //    }
                }
            }

            for (int j = 0; j < 10; j++)
            {
                tabla.AddCell(new Cell()
                              .SetTextAlignment(TextAlignment.CENTER)
                              .Add(new Paragraph((j + 1).ToString())));
                tabla.AddCell(new Cell()
                              .SetTextAlignment(TextAlignment.CENTER)
                              .Add(new Paragraph("cantidad " + (j + 1))));
                tabla.AddCell(new Cell()
                              .SetTextAlignment(TextAlignment.CENTER)
                              .Add(new Paragraph("lapiz adhesivo resistol no tóxico 100gr -- lapiz adhesivo resistol no tóxico 100gr " + (j + 1))));
                tabla.AddCell(new Cell()
                              .SetTextAlignment(TextAlignment.RIGHT)
                              .Add(new Paragraph("$100" + (j + 1))));
            }

            document.Add(tabla);
            Paragraph p = new Paragraph();

            p.SetTextAlignment(TextAlignment.RIGHT);
            p.Add("Total de la semana: $" + 10000);

            document.Add(p);

            document.Close();
        }
Exemple #19
0
        public void PublishPDF()
        {
            string    pageTitle = "Member Information";
            string    filename  = pageTitle + MemberID;
            PdfWriter writer    = new PdfWriter(Path.GetFullPath("PDF/" + filename + ".pdf"));

            PdfDocument pdf    = new PdfDocument(writer);
            Document    doc    = new Document(pdf);
            PdfFont     font   = PdfFontFactory.CreateFont(FontConstants.HELVETICA);
            PdfFont     bold   = PdfFontFactory.CreateFont(FontConstants.HELVETICA_BOLD);
            PdfFont     italic = PdfFontFactory.CreateFont(FontConstants.HELVETICA_BOLDOBLIQUE);
            Paragraph   p1     = new Paragraph("Rasulganj Multipurpose Co-operative Society Ltd").SetFont(bold).SetFontSize(15).SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER);
            Paragraph   p2     = new Paragraph(pageTitle).SetFont(bold).SetFontSize(14).SetTextAlignment(iText.Layout.Properties.TextAlignment.CENTER);

            doc.Add(p1);
            doc.Add(p2);

            Connection conn = new Connection();

            conn.OpenConection();
            string        query  = "SELECT * From Member WHERE MemberId = " + MemberID;
            SqlDataReader reader = conn.DataReader(query);

            while (reader.Read())
            {
                MemberName              = (string)reader["MemberName"];
                MemberVoterID           = (string)reader["MemberVoterId"];
                MemberFather            = (string)reader["MemberFather"];
                MemberMother            = (string)reader["MemberMother"];
                MemberDOB               = (DateTime)reader["MemberDOB"];
                MemberProfession        = (string)reader["MemberProfession"];
                MemberReligion          = (string)reader["MemberReligion"];
                MemberNationality       = (string)reader["MemberNationality"];
                MemberPresentCO         = (string)reader["MemberPresentCO"];
                MemberPresentVillage    = (string)reader["MemberPresentVillage"];
                MemberPresentPost       = (string)reader["MemberPresentPost"];
                MemberPresentThana      = (string)reader["MemberPresentThana"];
                MemberPresentDistrict   = (string)reader["MemberPresentDistrict"];
                MemberPermanentCO       = (string)reader["MemberPresentCO"];
                MemberPermanentVillage  = (string)reader["MemberPermanentVillage"];
                MemberPermanentPost     = (string)reader["MemberPermanentPost"];
                MemberPermanentThana    = (string)reader["MemberPermanentThana"];
                MemberPermanentDistrict = (string)reader["MemberPermanentDistrict"];
                MemberNominee           = (string)reader["MemberNominee"];
                MemberNomineeDOB        = (DateTime)reader["MemberNomineeDOB"];
                MemberNomineeRelation   = (string)reader["MemberNomineeRelation"];
                MemberCell              = (string)reader["MemberCell"];
                MemberPhoto             = Path.GetFullPath("Images/" + (string)reader["MemberPhoto"]);
                MemberSignature         = Path.GetFullPath("Images/" + (string)reader["MemberSignature"]);
            }

            try
            {
                Image     Photo  = new Image(ImageDataFactory.Create(MemberPhoto)).SetWidth(40).SetHeight(52);
                Paragraph imageP = new Paragraph("Member No : " + MemberID + "                                                                                                ").Add(Photo);
                doc.Add(imageP);
            }
            catch (Exception e) {
                MessageBox.Show("Member image not found. Press OK to continue.\n");
                Paragraph imageP = new Paragraph("Member No : " + MemberID);
                doc.Add(imageP);
            }
            Paragraph line0 = new Paragraph("Name : " + MemberName);

            doc.Add(line0);
            Paragraph line1 = new Paragraph("National ID : " + MemberVoterID);

            doc.Add(line1);
            Paragraph line2 = new Paragraph("Father/Husband : " + MemberFather);

            doc.Add(line2);
            Paragraph line3 = new Paragraph("Mother : " + MemberMother);

            doc.Add(line3);
            Paragraph line4 = new Paragraph("Profession : " + MemberProfession);

            doc.Add(line4);
            Paragraph line5 = new Paragraph("Nationality : " + MemberNationality);

            doc.Add(line5);
            Paragraph line6 = new Paragraph("Religion : " + MemberReligion);

            doc.Add(line6);
            Paragraph line7 = new Paragraph("Present Address : " + "C/O :" + MemberPresentCO);

            doc.Add(line7);
            Paragraph line8 = new Paragraph("|                           Village : " + MemberPresentVillage + "     Post : " + MemberPresentPost);

            doc.Add(line8);
            Paragraph line9 = new Paragraph("|                           Thana : " + MemberPresentThana + "      District : " + MemberPresentDistrict);

            doc.Add(line9);
            Paragraph line10 = new Paragraph("Permanent Address : " + "C/O : " + MemberPermanentCO);

            doc.Add(line10);
            Paragraph line11 = new Paragraph("|                          Village : " + MemberPermanentVillage + "     Post : " + MemberPermanentPost);

            doc.Add(line11);
            Paragraph line12 = new Paragraph("|                          Thana : " + MemberPermanentThana + "     District : " + MemberPermanentDistrict);

            doc.Add(line12);
            Paragraph line13 = new Paragraph("Nominee : " + MemberNominee + "             Relation :" + MemberNomineeRelation);

            doc.Add(line13);
            Paragraph line14 = new Paragraph("Cell No : " + MemberCell);

            doc.Add(line14);
            conn.CloseConnection();
            doc.Close();
        }
Exemple #20
0
        public void TotalVentasMesArticulo(DataTable dt)
        {
            FileInfo file = new FileInfo(DEST);

            file.Directory.Create();

            string      dest   = "c:/temp/ReporteMesArticulo1.pdf";
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest,
                                                               new WriterProperties().AddUAXmpMetadata().SetPdfVersion
                                                                   (PdfVersion.PDF_1_7)));
            Document document = new Document(pdfDoc, PageSize.LETTER.Rotate());

            //PDF/UA
            //Set document metadata
            pdfDoc.GetCatalog().SetViewerPreferences(new PdfViewerPreferences().SetDisplayDocTitle(true));
            pdfDoc.GetCatalog().SetLang(new PdfString("en-US"));
            PdfDocumentInfo info = pdfDoc.GetDocumentInfo();

            info.SetTitle("Reporte de Ventas de Artículo por Mes");

            float[] columnWidths = { 1, 5, 2 };
            Table   tabla        = new Table(UnitValue.CreatePercentArray(columnWidths));

            //tabla.SetWidth();
            tabla.UseAllAvailableWidth();
            PdfFont font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);
            // celda de encabezado

            Text txt = new Text("Reporte de Ventas Semanal")
                       .SetFontSize(20)
                       .SetBold();

            Paragraph pTitulo = new Paragraph(txt)
                                .SetTextAlignment(TextAlignment.CENTER);

            document.Add(pTitulo);

            for (int i = 0; i < 2; i++)
            {
                Cell[] headerFooter =
                {
                    new Cell()
                    .SetBackgroundColor(new DeviceGray(0.75f))
                    .Add(new Paragraph("Mes"))
                    .SetBorder(Border.NO_BORDER),
                    new Cell()
                    .SetBackgroundColor(new DeviceGray(0.75f))
                    .Add(new Paragraph("Artículo"))
                    .SetBorder(Border.NO_BORDER),
                    new Cell()
                    .SetBackgroundColor(new DeviceGray(0.75f))
                    .Add(new Paragraph("Total"))
                    .SetBorder(Border.NO_BORDER)
                };

                foreach (Cell hfCell in headerFooter)
                {
                    if (i == 0)
                    {
                        tabla.AddHeaderCell(hfCell);
                    }
                }
            }

            decimal totalMes = 0;

            Cell c_mes      = new Cell().SetTextAlignment(TextAlignment.CENTER);
            Cell c_articulo = new Cell().SetTextAlignment(TextAlignment.LEFT);
            Cell c_total    = new Cell().SetTextAlignment(TextAlignment.RIGHT);

            tabla.AddCell(c_articulo);
            tabla.AddCell(c_mes);
            tabla.AddCell(c_total);

            // ciclo para filas
            for (int j = 0; j < dt.Rows.Count; j++)
            {
                c_mes.Add(new Paragraph(dt.Rows[j][0].ToString()));
                c_articulo.Add(new Paragraph(dt.Rows[j][1].ToString()));
                c_total.Add(new Paragraph(dt.Rows[j][2].ToString()));

                totalMes += (decimal)dt.Rows[j][2];
            }

            document.Add(tabla);
            Paragraph p = new Paragraph();

            p.SetTextAlignment(TextAlignment.RIGHT);
            p.Add("Total del mes: $" + totalMes);

            document.Add(p);

            document.Close();
        }
        public virtual void StructElemTest04()
        {
            MemoryStream baos   = new MemoryStream();
            PdfWriter    writer = new PdfWriter(baos);

            writer.SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
            PdfDocument document = new PdfDocument(writer);

            document.SetTagged();
            document.GetStructTreeRoot().GetRoleMap().Put(new PdfName("Chunk"), PdfName.Span);
            PdfStructElem doc    = document.GetStructTreeRoot().AddKid(new PdfStructElem(document, PdfName.Document));
            PdfPage       page   = document.AddNewPage();
            PdfCanvas     canvas = new PdfCanvas(page);

            canvas.BeginText();
            canvas.SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.COURIER), 24);
            canvas.SetTextMatrix(1, 0, 0, 1, 32, 512);
            PdfStructElem paragraph = doc.AddKid(new PdfStructElem(document, PdfName.P));
            PdfStructElem span1     = paragraph.AddKid(new PdfStructElem(document, PdfName.Span, page));

            canvas.OpenTag(new CanvasTag(span1.AddKid(new PdfMcrNumber(page, span1))));
            canvas.ShowText("Hello ");
            canvas.CloseTag();
            PdfStructElem span2 = paragraph.AddKid(new PdfStructElem(document, new PdfName("Chunk"), page));

            canvas.OpenTag(new CanvasTag(span2.AddKid(new PdfMcrNumber(page, span2))));
            canvas.ShowText("World");
            canvas.CloseTag();
            canvas.EndText();
            canvas.Release();
            page.Flush();
            document.Close();
            byte[]    bytes  = baos.ToArray();
            PdfReader reader = new PdfReader(new MemoryStream(bytes));

            writer = new PdfWriter(destinationFolder + "structElemTest04.pdf");
            writer.SetCompressionLevel(CompressionConstants.NO_COMPRESSION);
            document = new PdfDocument(reader, writer);
            page     = document.GetPage(1);
            canvas   = new PdfCanvas(page);
            PdfStructElem p = (PdfStructElem)document.GetStructTreeRoot().GetKids()[0].GetKids()[0];

            canvas.BeginText();
            canvas.SetFontAndSize(PdfFontFactory.CreateFont(StandardFonts.COURIER), 24);
            canvas.SetTextMatrix(1, 0, 0, 1, 32, 490);
            //Inserting span between of 2 existing ones.
            span1 = p.AddKid(1, new PdfStructElem(document, PdfName.Span, page));
            canvas.OpenTag(new CanvasTag(span1.AddKid(new PdfMcrNumber(page, span1))));
            canvas.ShowText("text1");
            canvas.CloseTag();
            //Inserting span at the end.
            span1 = p.AddKid(new PdfStructElem(document, PdfName.Span, page));
            canvas.OpenTag(new CanvasTag(span1.AddKid(new PdfMcrNumber(page, span1))));
            canvas.ShowText("text2");
            canvas.CloseTag();
            canvas.EndText();
            canvas.Release();
            page.Flush();
            document.Close();
            CompareResult("structElemTest04.pdf", "cmp_structElemTest04.pdf", "diff_structElem_04_");
        }
Exemple #22
0
        //---------------------------------------------------------------------
        //
        //---------------------------------------------------------------------
        public void ManipulatePdf()
        {
            FileInfo file = new FileInfo(DEST);

            file.Directory.Create();

            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(DEST,
                                                               new WriterProperties().AddUAXmpMetadata().SetPdfVersion
                                                                   (PdfVersion.PDF_1_7)));
            Document document = new Document(pdfDoc, PageSize.A4.Rotate());

            //TAGGED PDF
            //Make document tagged
            pdfDoc.SetTagged();

            //PDF/UA
            //Set document metadata
            pdfDoc.GetCatalog().SetViewerPreferences(new PdfViewerPreferences().SetDisplayDocTitle(true));
            pdfDoc.GetCatalog().SetLang(new PdfString("en-US"));
            PdfDocumentInfo info = pdfDoc.GetDocumentInfo();

            info.SetTitle("Reporte de Ventas del Mes");

            Paragraph p = new Paragraph();

            //PDF/UA
            //Embed font
            //PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.WINANSI, true);
            //p.SetFont(font);

            PdfFont font = PdfFontFactory.CreateFont();

            p.SetFont(font);
            p.SetFontSize(26);

            p.Add("Papelería D'Loreto");

            //Image img = new Image(ImageDataFactory.Create(FOX));

            //PDF/UA
            //Set alt text
            //img.GetAccessibilityProperties().SetAlternateDescription("Fox");
            //p.Add(img);
            //p.Add(" jumps over the lazy ");

            //img = new Image(ImageDataFactory.Create(DOG));

            //PDF/UA
            //Set alt text
            //img.GetAccessibilityProperties().SetAlternateDescription("Dog");
            //p.Add(img);

            document.Add(p);

            p = new Paragraph("\n\n\n\n\n\n\n\n\n\n\n\n").SetFont(font).SetFontSize(20);
            document.Add(p);

            List list = new List().SetFont(font).SetFontSize(20);

            list.Add(new ListItem("quick"));
            list.Add(new ListItem("brown"));
            list.Add(new ListItem("fox"));
            list.Add(new ListItem("jumps"));
            list.Add(new ListItem("over"));
            list.Add(new ListItem("the"));
            list.Add(new ListItem("lazy"));
            list.Add(new ListItem("dog"));
            document.Add(list);

            document.Close();
        }
Exemple #23
0
        /// <summary>Output Text at a certain x and y coordinate.</summary>
        /// <remarks>Output Text at a certain x and y coordinate. Clipped or opaque text isn't supported as of yet.</remarks>
        /// <param name="x">x-coordinate</param>
        /// <param name="y">y-coordinate</param>
        /// <param name="flag">flag indicating clipped or opaque</param>
        /// <param name="x1">x1-coordinate of the rectangle if clipped or opaque</param>
        /// <param name="y1">y1-coordinate of the rectangle if clipped or opaque</param>
        /// <param name="x2">x2-coordinate of the rectangle if clipped or opaque</param>
        /// <param name="y2">y1-coordinate of the rectangle if clipped or opaque</param>
        /// <param name="text">text to output</param>
        public virtual void OutputText(int x, int y, int flag, int x1, int y1, int x2, int y2, String text)
        {
            MetaFont    font     = state.GetCurrentFont();
            float       refX     = state.TransformX(x);
            float       refY     = state.TransformY(y);
            float       angle    = state.TransformAngle(font.GetAngle());
            float       sin      = (float)Math.Sin(angle);
            float       cos      = (float)Math.Cos(angle);
            float       fontSize = font.GetFontSize(state);
            FontProgram fp       = font.GetFont();
            int         align    = state.GetTextAlign();
            // NOTE, MetaFont always creates with CP1252 encoding.
            int normalizedWidth = 0;

            byte[] bytes = font.encoding.ConvertToBytes(text);
            foreach (byte b in bytes)
            {
                normalizedWidth += fp.GetWidth(0xff & b);
            }
            float textWidth = fontSize / FontProgram.UNITS_NORMALIZATION * normalizedWidth;
            float tx        = 0;
            float ty        = 0;
            float descender = fp.GetFontMetrics().GetTypoDescender();
            float ury       = fp.GetFontMetrics().GetBbox()[3];

            cb.SaveState();
            cb.ConcatMatrix(cos, sin, -sin, cos, refX, refY);
            if ((align & MetaState.TA_CENTER) == MetaState.TA_CENTER)
            {
                tx = -textWidth / 2;
            }
            else
            {
                if ((align & MetaState.TA_RIGHT) == MetaState.TA_RIGHT)
                {
                    tx = -textWidth;
                }
            }
            if ((align & MetaState.TA_BASELINE) == MetaState.TA_BASELINE)
            {
                ty = 0;
            }
            else
            {
                if ((align & MetaState.TA_BOTTOM) == MetaState.TA_BOTTOM)
                {
                    ty = -descender;
                }
                else
                {
                    ty = -ury;
                }
            }
            Color textColor;

            if (state.GetBackgroundMode() == MetaState.OPAQUE)
            {
                textColor = state.GetCurrentBackgroundColor();
                cb.SetFillColor(textColor);
                cb.Rectangle(tx, ty + descender, textWidth, ury - descender);
                cb.Fill();
            }
            textColor = state.GetCurrentTextColor();
            cb.SetFillColor(textColor);
            cb.BeginText();
            cb.SetFontAndSize(PdfFontFactory.CreateFont(state.GetCurrentFont().GetFont(), PdfEncodings.CP1252, true),
                              fontSize);
            cb.SetTextMatrix(tx, ty);
            cb.ShowText(text);
            cb.EndText();
            if (font.IsUnderline())
            {
                cb.Rectangle(tx, ty - fontSize / 4, textWidth, fontSize / 15);
                cb.Fill();
            }
            if (font.IsStrikeout())
            {
                cb.Rectangle(tx, ty + fontSize / 3, textWidth, fontSize / 15);
                cb.Fill();
            }
            cb.RestoreState();
        }
Exemple #24
0
        protected void ManipulatePdf(String dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
            Document    doc    = new Document(pdfDoc);

            // The 3rd argument indicates whether the font is to be embedded into the target document
            PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.IDENTITY_H, true);

            doc.SetFont(font);

            // The text line is "Vous êtes d'où?"
            doc.Add(new Paragraph("Vous \u00EAtes d\'o\u00F9?"));

            // The text line is "À tout à l'heure. À bientôt."
            doc.Add(new Paragraph("\u00C0 tout \u00E0 l\'heure. \u00C0 bient\u00F4t."));

            // The text line is "Je me présente."
            doc.Add(new Paragraph("Je me pr\u00E9sente."));

            // The text line is "C'est un étudiant."
            doc.Add(new Paragraph("C\'est un \u00E9tudiant."));

            // The text line is "Ça va?"
            doc.Add(new Paragraph("\u00C7a va?"));

            // The text line is "Il est ingénieur. Elle est médecin."
            doc.Add(new Paragraph("Il est ing\u00E9nieur. Elle est m\u00E9decin."));

            // The text line is "C'est une fenêtre."
            doc.Add(new Paragraph("C\'est une fen\u00EAtre."));

            // The text line is "Répétez, s'il vous plaît."
            doc.Add(new Paragraph("R\u00E9p\u00E9tez, s\'il vous pla\u00EEt."));
            doc.Add(new Paragraph("Odkud jste?"));

            // The text line is "Uvidíme se za chvilku. Měj se."
            doc.Add(new Paragraph("Uvid\u00EDme se za chvilku. M\u011Bj se."));

            // The text line is "Dovolte, abych se představil."
            doc.Add(new Paragraph("Dovolte, abych se p\u0159edstavil."));
            doc.Add(new Paragraph("To je studentka."));

            // The text line is "Všechno v pořádku?"
            doc.Add(new Paragraph("V\u0161echno v po\u0159\u00E1dku?"));

            // The text line is "On je inženýr. Ona je lékař."
            doc.Add(new Paragraph("On je in\u017Een\u00FDr. Ona je l\u00E9ka\u0159."));
            doc.Add(new Paragraph("Toto je okno."));

            // The text line is "Zopakujte to prosím"
            doc.Add(new Paragraph("Zopakujte to pros\u00EDm."));

            // The text line is "Откуда ты?"
            doc.Add(new Paragraph("\u041e\u0442\u043a\u0443\u0434\u0430 \u0442\u044b?"));

            // The text line is "Увидимся позже. Увидимся."
            doc.Add(new Paragraph("\u0423\u0432\u0438\u0434\u0438\u043c\u0441\u044f "
                                  + "\u043f\u043E\u0437\u0436\u0435. \u0423\u0432\u0438\u0434\u0438\u043c\u0441\u044f."));

            // The text line is "Позвольте мне представиться."
            doc.Add(new Paragraph("\u041f\u043e\u0437\u0432\u043e\u043b\u044c\u0442\u0435 \u043c\u043d\u0435 "
                                  + "\u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u0438\u0442\u044c\u0441\u044f."));

            // The text line is "Это студент."
            doc.Add(new Paragraph("\u042d\u0442\u043e \u0441\u0442\u0443\u0434\u0435\u043d\u0442."));

            // The text line is "Хорошо?"
            doc.Add(new Paragraph("\u0425\u043e\u0440\u043e\u0448\u043e?"));

            // The text line is "Он инженер. Она доктор."
            doc.Add(new Paragraph("\u041e\u043d \u0438\u043d\u0436\u0435\u043d\u0435\u0440. "
                                  + "\u041e\u043d\u0430 \u0434\u043e\u043a\u0442\u043e\u0440."));

            // The text line is "Это окно."
            doc.Add(new Paragraph("\u042d\u0442\u043e \u043e\u043a\u043d\u043e."));

            // The text line is "Повторите, пожалуйста."
            doc.Add(new Paragraph("\u041f\u043e\u0432\u0442\u043e\u0440\u0438\u0442\u0435, "
                                  + "\u043f\u043e\u0436\u0430\u043b\u0443\u0439\u0441\u0442\u0430."));

            doc.Close();
        }
Exemple #25
0
 private static PdfFont CreateFont(string font) =>
 PdfFontFactory.CreateFont(font, PdfEncodings.IDENTITY_H);
        public bool ConvertToPdf(FileModel file)
        {
            var    pdfOutputPath = $"{settings.PdfDownloadPath}\\Converted_{file.FileName.Split('.')[0]}.pdf";
            var    fileToConvert = file.File;
            string fileType      = fileToConvert.ContentType;

            if (file.File.Length > 0)
            {
                try
                {
                    PdfDocument       pdfDoc       = new PdfDocument(new PdfWriter(pdfOutputPath));
                    Document          document     = new Document(pdfDoc);
                    PdfFont           font         = PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN);
                    HyphenationConfig hyphenConfig = new HyphenationConfig("en", null, 3, 3);
                    document.SetTextAlignment(TextAlignment.JUSTIFIED).SetFont(font).SetFontSize(11).SetHyphenation(hyphenConfig);

                    using (FileStream fs = new FileStream(file.FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        //fileToConvert.CopyToAsync(fs);

                        string    line;
                        Paragraph p;
                        bool      title = true;
                        switch (fileType)
                        {
                        case KnownMimeTypes.Txt:
                            using (StreamReader sr = new StreamReader(fs))
                            {
                                while ((line = sr.ReadLine()) != null)
                                {
                                    p = new Paragraph(line);
                                    p.SetKeepTogether(true);
                                    if (title)
                                    {
                                        p.SetFont(PdfFontFactory.CreateFont(StandardFonts.COURIER_BOLD));
                                        title = false;
                                    }
                                    else
                                    {
                                        p.SetFirstLineIndent(36);
                                    }
                                    if (string.IsNullOrEmpty(line))
                                    {
                                        p.SetMarginBottom(12);
                                        title = true;
                                    }
                                    else
                                    {
                                        p.SetMarginBottom(0);
                                    }
                                    document.Add(p);
                                }
                            }
                            document.Close();
                            return(true);

                        case KnownMimeTypes.Html:
                            return(true);

                        case KnownMimeTypes.Img:
                            return(true);

                        default:
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"{ex.Message}");
                    throw ex;
                }
            }

            return(false);
        }
Exemple #27
0
        private IRenderer CreateListSymbolRenderer(int index, IRenderer renderer)
        {
            Object defaultListSymbol = GetListItemOrListProperty(renderer, this, Property.LIST_SYMBOL);

            if (defaultListSymbol is Text)
            {
                return(SurroundTextBullet(new TextRenderer((Text)defaultListSymbol)));
            }
            else
            {
                if (defaultListSymbol is Image)
                {
                    return(new ImageRenderer((Image)defaultListSymbol));
                }
                else
                {
                    if (defaultListSymbol is ListNumberingType)
                    {
                        ListNumberingType numberingType = (ListNumberingType)defaultListSymbol;
                        String            numberText;
                        switch (numberingType)
                        {
                        case ListNumberingType.DECIMAL: {
                            numberText = index.ToString();
                            break;
                        }

                        case ListNumberingType.DECIMAL_LEADING_ZERO: {
                            numberText = (index < 10 ? "0" : "") + index.ToString();
                            break;
                        }

                        case ListNumberingType.ROMAN_LOWER: {
                            numberText = RomanNumbering.ToRomanLowerCase(index);
                            break;
                        }

                        case ListNumberingType.ROMAN_UPPER: {
                            numberText = RomanNumbering.ToRomanUpperCase(index);
                            break;
                        }

                        case ListNumberingType.ENGLISH_LOWER: {
                            numberText = EnglishAlphabetNumbering.ToLatinAlphabetNumberLowerCase(index);
                            break;
                        }

                        case ListNumberingType.ENGLISH_UPPER: {
                            numberText = EnglishAlphabetNumbering.ToLatinAlphabetNumberUpperCase(index);
                            break;
                        }

                        case ListNumberingType.GREEK_LOWER: {
                            numberText = GreekAlphabetNumbering.ToGreekAlphabetNumber(index, false, true);
                            break;
                        }

                        case ListNumberingType.GREEK_UPPER: {
                            numberText = GreekAlphabetNumbering.ToGreekAlphabetNumber(index, true, true);
                            break;
                        }

                        case ListNumberingType.ZAPF_DINGBATS_1: {
                            numberText = JavaUtil.CharToString((char)(index + 171));
                            break;
                        }

                        case ListNumberingType.ZAPF_DINGBATS_2: {
                            numberText = JavaUtil.CharToString((char)(index + 181));
                            break;
                        }

                        case ListNumberingType.ZAPF_DINGBATS_3: {
                            numberText = JavaUtil.CharToString((char)(index + 191));
                            break;
                        }

                        case ListNumberingType.ZAPF_DINGBATS_4: {
                            numberText = JavaUtil.CharToString((char)(index + 201));
                            break;
                        }

                        default: {
                            throw new InvalidOperationException();
                        }
                        }
                        Text textElement = new Text(GetListItemOrListProperty(renderer, this, Property.LIST_SYMBOL_PRE_TEXT) + numberText
                                                    + GetListItemOrListProperty(renderer, this, Property.LIST_SYMBOL_POST_TEXT));
                        IRenderer textRenderer;
                        // Be careful. There is a workaround here. For Greek symbols we first set a dummy font with document=null
                        // in order for the metrics to be taken into account correctly during layout.
                        // Then on draw we set the correct font with actual document in order for the font objects to be created.
                        if (numberingType == ListNumberingType.GREEK_LOWER || numberingType == ListNumberingType.GREEK_UPPER || numberingType
                            == ListNumberingType.ZAPF_DINGBATS_1 || numberingType == ListNumberingType.ZAPF_DINGBATS_2 || numberingType
                            == ListNumberingType.ZAPF_DINGBATS_3 || numberingType == ListNumberingType.ZAPF_DINGBATS_4)
                        {
                            String constantFont = (numberingType == ListNumberingType.GREEK_LOWER || numberingType == ListNumberingType
                                                   .GREEK_UPPER) ? StandardFonts.SYMBOL : StandardFonts.ZAPFDINGBATS;
                            textRenderer = new _TextRenderer_210(constantFont, textElement);
                            try {
                                textRenderer.SetProperty(Property.FONT, PdfFontFactory.CreateFont(constantFont));
                            }
                            catch (System.IO.IOException) {
                            }
                        }
                        else
                        {
                            textRenderer = new TextRenderer(textElement);
                        }
                        return(SurroundTextBullet(textRenderer));
                    }
                    else
                    {
                        if (defaultListSymbol is IListSymbolFactory)
                        {
                            return(SurroundTextBullet(((IListSymbolFactory)defaultListSymbol).CreateSymbol(index, this, renderer).CreateRendererSubTree
                                                          ()));
                        }
                        else
                        {
                            if (defaultListSymbol == null)
                            {
                                return(null);
                            }
                            else
                            {
                                throw new InvalidOperationException();
                            }
                        }
                    }
                }
            }
        }
Exemple #28
0
        public void creaPdf()
        {
            DateTime fecha       = DateTime.Now;
            string   fechaActual = fecha.ToString("dd-MM-yyyy");
            //string ruta = 'C:\Users\M.ibarraO\Documents\DUOC\Aplicaciones\GeneraPDF\Listado_ClienteActual_' + fechaActual+'.pdf';

            PdfWriter pdfwriter = new PdfWriter("C:\\Listado_ClienteActual_" + fechaActual + ".pdf");
            //Crear documento
            PdfDocument pdf       = new PdfDocument(pdfwriter);
            Document    documento = new Document(pdf, PageSize.LETTER);

            documento.SetMargins(60, 20, 55, 20);

            PdfFont fontColumnas  = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_BOLD);
            PdfFont fontContenido = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);

            string[] columnas = { "nombre", "paterno", "materno", "rut", "dv", "rubro", "direccion", "codcomuna", "telefono", "mail" };
            float[]  tamanios = { 10, 10, 10, 10, 1, 10, 20, 10, 9, 20 };

            Table tabla = new Table(UnitValue.CreatePercentArray(tamanios));

            tabla.SetWidth(UnitValue.CreatePercentValue(100));

            foreach (string columna in columnas)
            {
                tabla.AddHeaderCell(new Cell().Add(new Paragraph(columna).SetFont(fontColumnas)));
            }

            /*CONSULTA SQL*/

            OracleConnection conn         = D_Conexion.conectar();
            List <eCliente>  listaCliente = new List <eCliente>();

            try
            {
                OracleCommand command = conn.CreateCommand();
                command.CommandText = "select nombre,appaterno,apmaterno,rut,dverificador,descripcionrubro,direccion,nombrecomuna,telefono,email  from cliente cl inner join comuna cm on cm.idcomuna = cl.codcomuna inner join ciudad cd on cd.idciudad = cm.idciudad inner join region rg on rg.idregion = cd.idregion inner join rubro rb on rb.idrubro = cl.idrubro";
                OracleDataReader reader = command.ExecuteReader();

                while (reader.Read())
                {
                    // tabla.AddCell(new Cell().Add(new Paragraph(reader["IDCLIENTE"].ToString())));
                    tabla.AddCell(new Cell().Add(new Paragraph(reader["NOMBRE"].ToString())));
                    tabla.AddCell(new Cell().Add(new Paragraph(reader["APPATERNO"].ToString())));
                    tabla.AddCell(new Cell().Add(new Paragraph(reader["APMATERNO"].ToString())));
                    tabla.AddCell(new Cell().Add(new Paragraph(reader["RUT"].ToString())));
                    tabla.AddCell(new Cell().Add(new Paragraph(reader["DVERIFICADOR"].ToString())));
                    tabla.AddCell(new Cell().Add(new Paragraph(reader["descripcionrubro"].ToString())));
                    tabla.AddCell(new Cell().Add(new Paragraph(reader["DIRECCION"].ToString())));
                    tabla.AddCell(new Cell().Add(new Paragraph(reader["NOMBRECOMUNA"].ToString())));
                    //tabla.AddCell(new Cell().Add(new Paragraph(reader["NOMBRECIUDAD"].ToString())));
                    //tabla.AddCell(new Cell().Add(new Paragraph(reader["NOMBREREGION"].ToString())));
                    tabla.AddCell(new Cell().Add(new Paragraph(reader["TELEFONO"].ToString())));
                    tabla.AddCell(new Cell().Add(new Paragraph(reader["EMAIL"].ToString())));
                }

                command.Dispose();
                reader.Close();
                reader.Dispose();

                //Agrega en la tablapdf
                documento.Add(tabla);
                documento.Close();
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                conn.Close();
                conn.Dispose();
            }
        }
Exemple #29
0
        private void Print <T>(bool isRaw, List <T> selectedPersons, int rawpagesCount = 0) where T : IPerson
        {
            var filePath = Path.Combine(Constants.WorkingDirectory, typeof(T) == typeof(Rozhodci) ? "vyplatni-listina-rozhodci.pdf" : "vyplatni-listina-ceta.pdf");

            using (var writer = new PdfWriter(filePath))
            {
                using (var pdf = new PdfDocument(writer))
                {
                    var doc = new Document(pdf, PageSize.A4.Rotate());
                    doc.SetMargins(23, 38, 20, 38);
                    var pagesCount = (int)Math.Ceiling((double)selectedPersons.Count / 10);
                    if (pagesCount == 0)
                    {
                        pagesCount = 1;
                    }
                    if (isRaw)
                    {
                        pagesCount = rawpagesCount;
                    }

                    var font = PdfFontFactory.CreateFont(iText.IO.Font.Constants.StandardFonts.HELVETICA, PdfEncodings.CP1250);
                    var bold = PdfFontFactory.CreateFont(iText.IO.Font.Constants.StandardFonts.HELVETICA_BOLD, PdfEncodings.CP1250);

                    var mainHeaderTitle    = _settings.IsClubNameEnabled ? _settings.ClubName : new string('.', 80);
                    var documentMainHeader = new Paragraph($"TJ, Sportovní klub, Atletický oddíl, Atletický klub: {mainHeaderTitle}")
                                             .SetFont(bold).SetFontSize(16).SetTextAlignment(TextAlignment.CENTER);
                    var listinaHeadText = "VÝPLATNÍ LISTINA ODMĚN ";
                    listinaHeadText += typeof(T) == typeof(Rozhodci) ? "ROZHODČÍCH" : "TECHNICKÉ ČETY";
                    var vyplatniListinaHead = new Paragraph(listinaHeadText)
                                              .SetFont(bold).SetFontSize(16).SetTextAlignment(TextAlignment.CENTER).SetMarginTop(-3);
                    var rules = new Paragraph(
                        "Níže podepsaní účastníci soutěže souhlasili s uvedením svých osobních údajů na této výplatní listině (jméno, příjmení, datum narození a adresa).")
                                .SetFont(font).SetFontSize(9).SetTextAlignment(TextAlignment.CENTER).SetMarginTop(-1).SetMarginBottom(1);
                    var evidenceText =
                        new Paragraph(
                            $"Tyto údaje budou součástí evidence {new string('.', 123)} a budou jen pro vnitřní potřebu.")
                        .SetFont(font).SetFontSize(9).SetTextAlignment(TextAlignment.CENTER).SetMarginTop(-1);

                    var aboutcompetition = new Table(UnitValue.CreatePercentArray(new[] { 52.15f, 47.85f })).SetMarginTop(1).UseAllAvailableWidth();
                    aboutcompetition.AddCell(_settings.IsCompetitionNameEnabled
                                                ? AboutCompetitionCell($"Název soutěže: {_settings.CompetitionName}", bold)
                                                : AboutCompetitionCell($"Název soutěže {new string('.', 89)}", bold));

                    if (_settings.IsCompetitionDateEnabled)
                    {
                        if (_settings.CompetitionStartDate.HasValue && _settings.CompetitionEndDate == null)
                        {
                            aboutcompetition.AddCell(
                                AboutCompetitionCell($"Datum konání soutěže: {_settings.CompetitionStartDate.Value:dd.MM.yyyy}", bold));
                        }
                        else if (_settings.CompetitionStartDate.HasValue && _settings.CompetitionEndDate.HasValue)
                        {
                            aboutcompetition.AddCell(AboutCompetitionCell(
                                                         $"Datum konání soutěže: {_settings.CompetitionStartDate.Value:dd.MM.yyyy} - {_settings.CompetitionEndDate.Value:dd.MM.yyyy}",
                                                         bold));
                        }
                        else
                        {
                            aboutcompetition.AddCell(AboutCompetitionCell($"Datum konání soutěže {new string('.', 70)}", bold));
                        }
                    }
                    else
                    {
                        aboutcompetition.AddCell(AboutCompetitionCell($"Datum konání soutěže {new string('.', 70)}", bold));
                    }

                    var aboutcompetition2 = new Table(UnitValue.CreatePercentArray(new[] { 52.15f, 47.85f })).SetMarginTop(3).UseAllAvailableWidth();
                    if (_settings.IsCompetitionTimeEnabled)
                    {
                        if (_settings.CompetitionStartTime.HasValue && _settings.CompetitionEndTime == null)
                        {
                            aboutcompetition2.AddCell(
                                AboutCompetitionCell($"Doba konání soutěže: {_settings.CompetitionStartTime.Value:HH:mm} - ", bold));
                        }
                        else if (_settings.CompetitionStartTime.HasValue && _settings.CompetitionEndTime.HasValue)
                        {
                            aboutcompetition2.AddCell(AboutCompetitionCell(
                                                          $"Doba konání soutěže: {_settings.CompetitionStartTime.Value:HH:mm} - {_settings.CompetitionEndTime.Value:HH:mm}",
                                                          bold));
                        }
                        else
                        {
                            aboutcompetition2.AddCell(AboutCompetitionCell($"Doba konání soutěže {new string('.', 78)}", bold));
                        }
                    }
                    else
                    {
                        aboutcompetition2.AddCell(AboutCompetitionCell($"Doba konání soutěže {new string('.', 78)}", bold));
                    }

                    aboutcompetition2.AddCell(_settings.IsCompetitionPlaceEnabled
                                                ? AboutCompetitionCell($"Místo konání soutěže: {_settings.CompetitionPlace}", bold)
                                                : AboutCompetitionCell($"Místo konání soutěže {new string('.', 72)}", bold));

                    #region TableHead

                    var pdfNumber = new Cell(2, 1).SetTextAlignment(TextAlignment.CENTER)
                                    .SetVerticalAlignment(VerticalAlignment.MIDDLE)
                                    .SetFont(font)
                                    .SetPadding(0)
                                    .SetBorder(new SolidBorder(1));
                    pdfNumber.Add(new Paragraph("Pořadové"));
                    pdfNumber.Add(new Paragraph("číslo"));

                    var nameCell = new Cell().SetTextAlignment(TextAlignment.LEFT)
                                   .SetVerticalAlignment(VerticalAlignment.MIDDLE)
                                   .SetFont(font)
                                   .SetHeight(17)
                                   .SetBorder(new SolidBorder(1.2f))
                                   .SetBorderBottom(new GrooveBorder(DeviceCmyk.BLACK, 1, 0.5f))
                                   .SetPadding(0);
                    nameCell.Add(new Paragraph("Jméno a příjmení")).SetPaddingLeft(17);
                    var addressCell = new Cell().SetTextAlignment(TextAlignment.LEFT)
                                      .SetVerticalAlignment(VerticalAlignment.MIDDLE)
                                      .SetFont(font)
                                      .SetHeight(17)
                                      .SetBorder(new SolidBorder(1.2f))
                                      .SetBorderTop(Border.NO_BORDER)
                                      .SetPadding(0);
                    addressCell.Add(new Paragraph("Přesná adresa")).SetPaddingLeft(17);

                    var birthDate = new Cell(2, 1).SetTextAlignment(TextAlignment.CENTER)
                                    .SetVerticalAlignment(VerticalAlignment.MIDDLE)
                                    .SetFont(font)
                                    .SetPadding(0);
                    birthDate.Add(new Paragraph("Datum"));
                    birthDate.Add(new Paragraph("narození"));

                    var awardCell = new Cell(2, 1).SetTextAlignment(TextAlignment.CENTER)
                                    .SetVerticalAlignment(VerticalAlignment.MIDDLE)
                                    .SetFont(font)
                                    .SetPadding(0);
                    awardCell.Add(new Paragraph("Odměna"));
                    awardCell.Add(new Paragraph("Kč"));

                    var signCell = new Cell(2, 1).SetTextAlignment(TextAlignment.CENTER)
                                   .SetVerticalAlignment(VerticalAlignment.MIDDLE)
                                   .SetFont(font)
                                   .SetPadding(0);
                    signCell.Add(new Paragraph("Potvrzení o přijetí odměny"));
                    signCell.Add(new Paragraph("Podpis"));

                    #endregion

                    #region Tabulka Bottom

                    var emptyCell = new Cell().SetBorder(Border.NO_BORDER).SetPadding(0f);

                    var sumtextCell = new Cell(1, 2).SetFont(bold).SetFontSize(15).SetTextAlignment(TextAlignment.RIGHT)
                                      .SetBackgroundColor(ColorConstants.LIGHT_GRAY).SetPadding(0);
                    sumtextCell.Add(new Paragraph("CELKEM VYPLACENO: ")).SetPaddingRight(2);

                    var last = new Paragraph(
                        "Vyplatil...............................................     Dne...............................................     Podpis...............................................")
                               .SetFont(font)
                               .SetFontSize(12)
                               .SetMarginTop(8);

                    #endregion

                    for (int i = 0; i < pagesCount; i++)
                    {
                        doc.Add(documentMainHeader);
                        doc.Add(vyplatniListinaHead);
                        doc.Add(rules);
                        doc.Add(evidenceText);
                        doc.Add(aboutcompetition);
                        doc.Add(aboutcompetition2);

                        #region Table

                        var rozhodciTable = new Table(new float[] { 65, 355, 100, 80, 170 })
                                            .UseAllAvailableWidth()
                                            .SetMarginTop(6f)
                                            .SetFontSize(FontSize);

                        rozhodciTable.SetWidth(765f);
                        rozhodciTable.SetBorder(Border.NO_BORDER);
                        rozhodciTable.AddCell(pdfNumber);
                        rozhodciTable.AddCell(nameCell);
                        rozhodciTable.AddCell(birthDate);
                        rozhodciTable.AddCell(awardCell);
                        rozhodciTable.AddCell(signCell);
                        rozhodciTable.AddCell(addressCell);

                        for (int j = 0; j < 10; j++)
                        {
                            var index         = j + i * 10;
                            var pdfNumberData = new Cell(2, 1).SetTextAlignment(TextAlignment.CENTER)
                                                .SetVerticalAlignment(VerticalAlignment.MIDDLE)
                                                .SetFont(font)
                                                .SetFontSize(15)
                                                .SetHeight(30)
                                                .SetPadding(0)
                                                .SetBorder(new SolidBorder(1))
                                                .SetBorderLeft(new SolidBorder(1));
                            pdfNumberData.Add(new Paragraph((j + 1).ToString()));

                            var nameCellData = new Cell().SetTextAlignment(TextAlignment.LEFT)
                                               .SetFont(font)
                                               .SetHeight(15)
                                               .SetBorder(new SolidBorder(1.2f))
                                               .SetBorderBottom(new GrooveBorder(DeviceCmyk.BLACK, 1, 0.5f))
                                               .SetPadding(0);

                            var addressCellData = new Cell().SetTextAlignment(TextAlignment.LEFT)
                                                  .SetFont(font)
                                                  .SetHeight(15)
                                                  .SetBorder(new SolidBorder(1.2f))
                                                  .SetBorderTop(Border.NO_BORDER)
                                                  .SetPadding(0);

                            var birthDateData = new Cell(2, 1).SetTextAlignment(TextAlignment.CENTER)
                                                .SetVerticalAlignment(VerticalAlignment.MIDDLE)
                                                .SetFont(font)
                                                .SetPadding(0)
                                                .SetHeight(30);

                            var awardCellData = new Cell(2, 1).SetTextAlignment(TextAlignment.CENTER)
                                                .SetVerticalAlignment(VerticalAlignment.MIDDLE)
                                                .SetFont(font)
                                                .SetPadding(0)
                                                .SetHeight(30);

                            var signCellData = new Cell(2, 1).SetTextAlignment(TextAlignment.CENTER)
                                               .SetVerticalAlignment(VerticalAlignment.MIDDLE)
                                               .SetFont(font)
                                               .SetPadding(0)
                                               .SetHeight(30);
                            signCellData.Add(new Paragraph(""));

                            if (!isRaw && selectedPersons.Count > index)
                            {
                                nameCellData.Add(new Paragraph(selectedPersons[index].FullName)).SetPaddingLeft(17);
                                addressCellData.Add(new Paragraph($"{selectedPersons[index].Address}, {selectedPersons[index].City}"))
                                .SetPaddingLeft(17);
                                birthDateData.Add(new Paragraph(selectedPersons[index].BirthDate.ToShortDateString()));
                                awardCellData.Add(new Paragraph(selectedPersons[index].Reward.HasValue
                                                                        ? selectedPersons[index].Reward.Value.ToString()
                                                                        : ""));
                            }
                            else
                            {
                                nameCellData.Add(new Paragraph("")).SetPaddingLeft(17);
                                addressCellData.Add(new Paragraph("")).SetPaddingLeft(17);
                                birthDateData.Add(new Paragraph(""));
                                awardCellData.Add(new Paragraph(""));
                            }


                            rozhodciTable.AddCell(pdfNumberData);
                            rozhodciTable.AddCell(nameCellData);
                            rozhodciTable.AddCell(birthDateData);
                            rozhodciTable.AddCell(awardCellData);
                            rozhodciTable.AddCell(signCellData);
                            rozhodciTable.AddCell(addressCellData);
                        }

                        #endregion

                        var sumCell = new Cell().SetBackgroundColor(ColorConstants.LIGHT_GRAY)
                                      .SetPadding(0)
                                      .SetFont(bold)
                                      .SetFontSize(15)
                                      .SetTextAlignment(TextAlignment.CENTER)
                                      .SetVerticalAlignment(VerticalAlignment.MIDDLE);
                        sumCell.Add(selectedPersons.Count <= i * 10 + 10
                                                        ? new Paragraph(!isRaw ? CountSum(selectedPersons.GetRange(i * 10, selectedPersons.Count - i * 10)) : "")
                                                        : new Paragraph(!isRaw ? CountSum(selectedPersons.GetRange(i * 10, 10)) : ""));

                        rozhodciTable.AddCell(emptyCell);
                        rozhodciTable.AddCell(sumtextCell);
                        rozhodciTable.AddCell(sumCell);
                        rozhodciTable.AddCell(emptyCell);
                        doc.Add(rozhodciTable);

                        doc.Add(last);
                    }

                    doc.Close();
                }
            }

            Browser.OpenLink(filePath);
        }
Exemple #30
0
        public MemoryStream GeneratePDF(Diploma_model diploma)
        {
            /*byte[] bytes = new byte[diploma.Name.Length * sizeof(char)];
             * System.Buffer.BlockCopy(diploma.Name.ToArray(), 0, bytes, 0, bytes.Length);
             * Encoding w1250 = Encoding.GetEncoding(1250);
             * Encoding utf8 = Encoding.GetEncoding("utf-8");
             * byte[] output = Encoding.Convert(utf8, w1250, utf8.GetBytes(diploma.Name));
             * diploma.Name = w1250.GetString(output);
             *
             * byte[] bytes1 = new byte[diploma.LastName.Length * sizeof(char)];
             * System.Buffer.BlockCopy(diploma.LastName.ToArray(), 0, bytes, 0, bytes.Length);
             * Encoding w12501 = Encoding.GetEncoding(1250);
             * Encoding utf81 = Encoding.GetEncoding("utf-8");
             * byte[] output1 = Encoding.Convert(utf81, w12501, utf81.GetBytes(diploma.LastName));
             * diploma.LastName = w1250.GetString(output1);*/

            using (MemoryStream stream = new MemoryStream())
                using (var writer = new PdfWriter(stream))
                {
                    //var writer = new PdfWriter(stream);
                    var pdf = new PdfDocument(writer);
                    //Fonts
                    PdfFont times_new_roman      = PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN, iText.IO.Font.PdfEncodings.CP1257, true);
                    PdfFont times_new_roman_bold = PdfFontFactory.CreateFont(StandardFonts.TIMES_BOLD, iText.IO.Font.PdfEncodings.CP1257, true);
                    //Text Generic
                    Text rector         = new Text($"{diploma.RectorsName} {diploma.RectorsLastName} \nRektorius \nRector").SetFont(times_new_roman);
                    Text dateofissueLT  = new Text($"Išdavimo data:           {diploma.DateOfIssue.ToString("yyyy/MM/dd")}").SetFont(times_new_roman);
                    Text dateofissueENG = new Text($"Date of issue:          {diploma.DateOfIssue.ToString("dd/MMMM/yyyy")}").SetFont(times_new_roman);
                    //Text LT (fix it later)
                    Text namepart                  = new Text($"{diploma.Name.ToUpper()} {diploma.LastName.ToUpper()} ").SetFont(times_new_roman_bold);
                    Text identitypart              = new Text($"(asmens kodas {diploma.IdentityNumber})").SetFont(times_new_roman);
                    Text partBeforeprogramme       = new Text($"{diploma.DateOfIssue.Year} metais baigė bakalauro studijų programą ").SetFont(times_new_roman);
                    Text programmepart             = new Text($"{diploma.StudiesProgramme.ToUpper()} ").SetFont(times_new_roman_bold);
                    Text programmerGovermentIDCode = new Text($"(valstybinis kodas {diploma.StudiesProgrammeGovermentCode} )").SetFont(times_new_roman);
                    Text beforedegreepart          = new Text("ir jam suteiktas").SetFont(times_new_roman);
                    Text degreepart                = new Text($"{diploma.Degree.ToUpper()} ").SetFont(times_new_roman_bold);
                    Text afterdegreepart           = new Text("laipsnis").SetFont(times_new_roman);
                    Text studiesdirectionpart      = new Text($"Studijų kryptis - {diploma.Studiesdirection.ToUpper()}").SetFont(times_new_roman);
                    //Text Eng
                    Text identitypartENG = new Text($" (personal number/code {diploma.IdentityNumber})").SetFont(times_new_roman);
                    //Text degreeENG = new Text($"BACHELORS DEGREE OF {diploma.Degree.ToUpper()} ").SetFont(times_new_roman);
                    //Text studiesdirectionENG = new Text($"IN {diploma.Studiesdirection.ToUpper()} ").SetFont(times_new_roman);
                    Text degreeENG                    = new Text($"BACHELORS DEGREE OF INFORMATICS ENGINEERING ").SetFont(times_new_roman);
                    Text studiesdirectionENG          = new Text($"IN INFORMATICS ENGINEERING ").SetFont(times_new_roman);
                    Text partBeforeprogrammeENG       = new Text($"in {diploma.DateOfIssue.Year} completed bachelors study programme ").SetFont(times_new_roman);
                    Text programmepartENG             = new Text($"INFORMATION TECHNOLOGIES").SetFont(times_new_roman_bold);
                    Text programmerGovermentIDCodeENG = new Text($"(state code {diploma.StudiesProgrammeGovermentCode} )").SetFont(times_new_roman);
                    Text beforedegreepartENG          = new Text("and has been awarded").SetFont(times_new_roman);
                    //PDF construct
                    PageSize  pageSize = PageSize.A4.Rotate();
                    var       document = new Document(pdf, pageSize);
                    PdfCanvas canvas   = new PdfCanvas(pdf.AddNewPage());
                    canvas.AddImage(ImageDataFactory.Create(imageDestination), pageSize, false);
                    //document.Add(new Paragraph(diploma.LastName).SetFont(times_new_roman).SetFontSize(50).SetTextAlignment(TextAlignment.CENTER));
                    //document.Add(new Paragraph($"{diploma.Name.ToUpper()} {diploma.LastName.ToUpper()} (asmens kodas {diploma.IdentityNumber})").SetFont(times_new_roman).SetFontSize(16).SetTextAlignment(TextAlignment.CENTER));
                    //Text spacing (fix it later)
                    document.Add(new Paragraph("\n \n \n").SetFont(times_new_roman).SetFontSize(50).SetTextAlignment(TextAlignment.CENTER).SetMultipliedLeading(1.0f));
                    document.Add(new Paragraph("\n \n").SetFont(times_new_roman).SetFontSize(25).SetTextAlignment(TextAlignment.CENTER).SetMultipliedLeading(1.0f));
                    document.Add(new Paragraph("\n").SetFont(times_new_roman).SetFontSize(15).SetTextAlignment(TextAlignment.CENTER).SetMultipliedLeading(1.0f));
                    document.SetProperty(Property.LEADING, new Leading(Leading.MULTIPLIED, 0.5f));
                    //Text construct LT part
                    document.Add(new Paragraph().Add(namepart).Add(identitypart).SetTextAlignment(TextAlignment.CENTER));
                    document.Add(new Paragraph().Add(partBeforeprogramme).Add(programmepart).Add(programmerGovermentIDCode).SetTextAlignment(TextAlignment.CENTER));
                    document.Add(new Paragraph().Add(beforedegreepart).SetTextAlignment(TextAlignment.CENTER));
                    document.Add(new Paragraph().Add(degreepart).Add(afterdegreepart).SetTextAlignment(TextAlignment.CENTER));
                    document.Add(new Paragraph().Add(studiesdirectionpart).SetTextAlignment(TextAlignment.CENTER));
                    document.Add(new Paragraph("\n").SetTextAlignment(TextAlignment.CENTER));
                    //Text construct ENG part
                    document.Add(new Paragraph().Add(namepart).Add(identitypartENG).SetTextAlignment(TextAlignment.CENTER));
                    document.Add(new Paragraph().Add(partBeforeprogrammeENG).Add(programmepartENG).Add(programmerGovermentIDCodeENG).SetTextAlignment(TextAlignment.CENTER));
                    document.Add(new Paragraph().Add(beforedegreepartENG).SetTextAlignment(TextAlignment.CENTER));
                    document.Add(new Paragraph().Add(degreeENG).SetTextAlignment(TextAlignment.CENTER));
                    document.Add(new Paragraph().Add(studiesdirectionENG).SetTextAlignment(TextAlignment.CENTER));
                    //Rector part
                    document.Add(new Paragraph().Add(rector).SetFontSize(11).SetTextAlignment(TextAlignment.LEFT).SetMultipliedLeading(1.0f));
                    //metadata part
                    //document.Add(new Paragraph().Add(dateofissueLT).SetFontSize(10).SetTextAlignment(TextAlignment.RIGHT).SetMultipliedLeading(0.8f));
                    //document.Add(new Paragraph().Add(dateofissueENG).SetFontSize(10).SetTextAlignment(TextAlignment.RIGHT).SetMultipliedLeading(0.8f));
                    Table table = new Table(2, true);
                    Style style = new Style().SetBorder(Border.NO_BORDER);
                    table.SetWidth(200);
                    table.SetHorizontalAlignment(HorizontalAlignment.RIGHT);
                    //table.AddCell(new Cell("Išdavimo data:").SetTextAlignment(TextAlignment.LEFT)).AddStyle(style);
                    //https://itextpdf.com/en/resources/faq/technical-support/itext-7/why-doesnt-getdefaultcellsetborderpdfpcellnoborder-have-any
                    //https://kodejava.org/how-do-i-create-table-cell-that-span-multiple-columns-in-itext/
                    table.AddCell(new Paragraph("Registracijos Nr").SetTextAlignment(TextAlignment.LEFT));
                    table.AddCell(new Paragraph($"{diploma.RegistrationNr}").SetTextAlignment(TextAlignment.LEFT));
                    table.AddCell(new Paragraph("Registracijos Nr").SetTextAlignment(TextAlignment.LEFT));
                    table.AddCell(new Paragraph("").SetTextAlignment(TextAlignment.LEFT));
                    table.AddCell(new Paragraph("Išdavimo data:").SetTextAlignment(TextAlignment.LEFT));
                    table.AddCell(new Paragraph(diploma.DateOfIssue.ToString("yyyy/MM/dd")).SetTextAlignment(TextAlignment.LEFT));
                    table.AddCell(new Paragraph("Date of sssue:").SetTextAlignment(TextAlignment.LEFT));
                    table.AddCell(new Paragraph(diploma.DateOfIssue.ToString("dd/MMMM/yyyy")).SetTextAlignment(TextAlignment.LEFT));
                    table.AddCell(new Paragraph("Code in system:").SetTextAlignment(TextAlignment.LEFT));
                    table.AddCell(new Paragraph(diploma.quickSearch.ToString()).SetTextAlignment(TextAlignment.LEFT));
                    document.Add(table);
                    document.Close();
                    writer.Close();
                    return(stream);
                }
            //var stream = new MemoryStream();
        }