Imagenes at ItexSharp

4

I'm working with Chart in C# where I do the graphing of data and when the user gives click on the report button the report pdf of% is created ItexSharp

Up there I'm fine but I'd like to make it a little bigger without distorting, covering the width and a little bit longer of the sheet. This is the code that I put for the image to grow but it does not work as I wanted:

chart_imagen.ScalePercent(100f,100f);
chart_imagen.ScaleAbsolute(500f, 500f);

And I would also like the numbering of the X axis to be 1 in 1 to the number that the user decides. How could I do it?

    
asked by karol 24.11.2016 в 20:40
source

1 answer

2

I made an example I annex the project and part of the code:

The interface was like this:

In the form:

 public Form1()
    {
        try
        {
            InitializeComponent();
            CrearGrafica();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            CrearPDF();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

    public class CambiosPrecios {
        public DateTime fecha { get; set; }
        public int idProducto { get; set; }
        public string nombreProducto { get; set; }
        public decimal precio { get; set; }
    }

    private void CrearGrafica()
    {
        try
        {
            //Lleno el objeto de CambiosPrecios
            var cambiosPrecios = new List<CambiosPrecios>();
            cambiosPrecios.Add(new CambiosPrecios { fecha = new DateTime(2016, 1, 1),idProducto = 1,  nombreProducto = "Producto 1", precio = 12.30M });
            cambiosPrecios.Add(new CambiosPrecios { fecha = new DateTime(2016, 2, 1),idProducto = 1,  nombreProducto = "Producto 1", precio = 15.30M });
            cambiosPrecios.Add(new CambiosPrecios { fecha = new DateTime(2016, 3, 1),idProducto = 1,  nombreProducto = "Producto 1", precio = 14.60M });
            cambiosPrecios.Add(new CambiosPrecios { fecha = new DateTime(2016, 4, 1),idProducto = 1,  nombreProducto = "Producto 1", precio = 12.90M });
            cambiosPrecios.Add(new CambiosPrecios { fecha = new DateTime(2016, 5, 1),idProducto = 1,  nombreProducto = "Producto 1", precio = 12.90M });
            cambiosPrecios.Add(new CambiosPrecios { fecha = new DateTime(2016, 6, 1),idProducto = 1,  nombreProducto = "Producto 1", precio = 12.90M });
            cambiosPrecios.Add(new CambiosPrecios { fecha = new DateTime(2016, 1, 1), idProducto = 2, nombreProducto = "Producto 2", precio = 18.30M });
            cambiosPrecios.Add(new CambiosPrecios { fecha = new DateTime(2016, 2, 1), idProducto = 2, nombreProducto = "Producto 2", precio = 19.30M });
            cambiosPrecios.Add(new CambiosPrecios { fecha = new DateTime(2016, 3, 1), idProducto = 2, nombreProducto = "Producto 2", precio = 30.60M });
            cambiosPrecios.Add(new CambiosPrecios { fecha = new DateTime(2016, 4, 1), idProducto = 2, nombreProducto = "Producto 2", precio = 28.90M });
            cambiosPrecios.Add(new CambiosPrecios { fecha = new DateTime(2016, 5, 1), idProducto = 2, nombreProducto = "Producto 2", precio = 25.90M });
            cambiosPrecios.Add(new CambiosPrecios { fecha = new DateTime(2016, 6, 1), idProducto = 2, nombreProducto = "Producto 2", precio = 30.90M });
            cambiosPrecios.Add(new CambiosPrecios { fecha = new DateTime(2016, 1, 1), idProducto = 3, nombreProducto = "Producto 3", precio = 13.50M });
            cambiosPrecios.Add(new CambiosPrecios { fecha = new DateTime(2016, 2, 1), idProducto = 3, nombreProducto = "Producto 3", precio = 13.55M });
            cambiosPrecios.Add(new CambiosPrecios { fecha = new DateTime(2016, 3, 1), idProducto = 3, nombreProducto = "Producto 3", precio = 14.30M });
            cambiosPrecios.Add(new CambiosPrecios { fecha = new DateTime(2016, 4, 1), idProducto = 3, nombreProducto = "Producto 3", precio = 14.30M });
            cambiosPrecios.Add(new CambiosPrecios { fecha = new DateTime(2016, 5, 1), idProducto = 3, nombreProducto = "Producto 3", precio = 14.30M });
            cambiosPrecios.Add(new CambiosPrecios { fecha = new DateTime(2016, 6, 1), idProducto = 3, nombreProducto = "Producto 3", precio = 14.30M });
            cambiosPrecios.Add(new CambiosPrecios { fecha = new DateTime(2016, 1, 1), idProducto = 4, nombreProducto = "Producto 4", precio = 11.00M });
            cambiosPrecios.Add(new CambiosPrecios { fecha = new DateTime(2016, 2, 1), idProducto = 4, nombreProducto = "Producto 4", precio = 12.00M });
            cambiosPrecios.Add(new CambiosPrecios { fecha = new DateTime(2016, 3, 1), idProducto = 4, nombreProducto = "Producto 4", precio = 13.00M });
            cambiosPrecios.Add(new CambiosPrecios { fecha = new DateTime(2016, 4, 1), idProducto = 4, nombreProducto = "Producto 4", precio = 25.00M });
            cambiosPrecios.Add(new CambiosPrecios { fecha = new DateTime(2016, 5, 1), idProducto = 4, nombreProducto = "Producto 4", precio = 25.90M });
            cambiosPrecios.Add(new CambiosPrecios { fecha = new DateTime(2016, 6, 1), idProducto = 4, nombreProducto = "Producto 4", precio = 15.90M });
            //Fin - Lleno el objeto de CambiosPrecios

            var titulo = new Title("Cambio de precios(2016)",Docking.Top,new System.Drawing.Font("Verdana",14.0f),System.Drawing.Color.BlueViolet );
            chart1.Titles.Add(titulo);
            chart1.DataSource = cambiosPrecios;

            //Titulo de la X
            chart1.ChartAreas[0].Axes[0].Title = "Mes";
            //Titulo de la Y
            chart1.ChartAreas[0].Axes[1].Title = "$ Precio";

            //Cambiar el intevalo de 1 en  1 para el eje Y
            Axis xaxis = chart1.ChartAreas[0].AxisY;
            xaxis.IntervalType = DateTimeIntervalType.Auto;
            xaxis.Interval = 2;//Numero de intervalo

            var productos = (from x in cambiosPrecios select x.nombreProducto).Distinct();//Selecciono todos los productos distintos, seran las SERIES en el chart
            foreach (var s in productos)
            {
                List<string> xvals = new List<string>();
                List<decimal> yvals = new List<decimal>();
                string serieName = s;
                chart1.Series.Add(serieName);
                //Grafica lineal
                chart1.Series[serieName].ChartType = SeriesChartType.Line;

                foreach (var v in cambiosPrecios)
                {
                    try
                    {

                        if (String.Equals(serieName, v.nombreProducto.ToString(), StringComparison.Ordinal))
                        {
                            yvals.Add(v.precio);
                            xvals.Add(v.fecha.ToString("MMM", CultureInfo.InvariantCulture));
                        }

                    }
                    catch (Exception ex)
                    {

                        throw new InvalidOperationException(ex.ToString());
                    }
                }
                try
                {
                    chart1.Series[serieName].XValueType = ChartValueType.Auto;
                    chart1.Series[serieName].YValueType = ChartValueType.Auto;
                    chart1.Series[serieName].Points.DataBindXY( xvals.ToArray(), yvals.ToArray());
                    ////Muestre el valor en le punto 
                    //foreach (var p in chart1.Series[serieName].Points) {
                    //    p.IsValueShownAsLabel = true;
                    //}
                }
                catch (Exception ex)
                {

                    throw new InvalidOperationException(ex.ToString());
                }


            }

            chart1.DataBind();
            chart1.Visible = true;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.ToString(), ex);
        }
    }

    private void CrearPDF() {
        try
        {
            Document Doc = new Document(PageSize.LETTER.Rotate(), 10f, 10f, 10f, 0f);//Horizontal
            //Document Doc = new Document(PageSize.LETTER, 10f, 10f, 10f, 0f);
            PdfWriter.GetInstance(Doc
                , new System.IO.FileStream(
                    System.IO.Directory.GetCurrentDirectory() 
                    + "\EjemploGraficas" + Guid.NewGuid() + ".pdf",
                    System.IO.FileMode.Create));

            Doc.Open();

            // Le colocamos el título y el autor
            // **Nota: Esto no será visible en el documento
            Doc.AddTitle("Reporte de ejemplo CHART");
            Doc.AddCreator("Cristina Carrasco - [email protected]");

            //Titulo del documento
            var parrafo = new Paragraph("Titulo del PDF");
            parrafo.SpacingBefore = 20;
            parrafo.SpacingAfter = 20;
            parrafo.Alignment = 1; //0-Left, 1 middle,2 Right
            Doc.Add(parrafo);
            Doc.Add(Chunk.NEWLINE);

            //Agrego la Gráfica
            using (MemoryStream memoryStream = new MemoryStream())
            {
                chart1.SaveImage(memoryStream, System.Windows.Forms.DataVisualization.Charting.ChartImageFormat.Bmp);
                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(memoryStream.GetBuffer());
                img.ScalePercent(120f);
                //img.ScaleAbsolute(500f, 300f);

                Doc.Add(img);


            }
            Doc.Close();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.ToString(),ex);
        }
    }

Your question about the interval is fixed with this code:

//Cambiar el intevalo de 1 en  1 para el eje X
Axis xaxis = chart1.ChartAreas[0].AxisX;
xaxis.IntervalType = DateTimeIntervalType.Auto;
xaxis.Interval = 1;//Numero de intervalo

For the Y axis:

//Cambiar el intevalo de 1 en  1 para el eje Y
Axis xaxis = chart1.ChartAreas[0].AxisY;
xaxis.IntervalType = DateTimeIntervalType.Auto;
xaxis.Interval = 1;//Numero de intervalo

The project can be downloaded from this league: Sample project Chart in c # Print to PDF itextSharp

The generated PDF was as follows:

I hope you find it helpful, greetings.

    
answered by 16.12.2016 / 02:04
source