Print arrays with line break

1

I want to print the various variables of a List . I am trying to use foreach but it has not worked. The variables are written one over the other instead of a line break. Look at my code in the printPage event:

        int charactersOnPage = 0;
        int linesPerPage = 0;

        var Fonte = new Font("Arial", 18);

        Cliente cliente = Clientes[listaClientes.SelectedIndex];

        foreach (var cli in cliente.Produtos)
        {
            string impressao = string.Format("Produto: {0}", cli.NomeProduto);

            e.Graphics.MeasureString(impressao, Fonte, e.MarginBounds.Size, StringFormat.GenericTypographic, out charactersOnPage, out linesPerPage);

            e.Graphics.DrawString(impressao, Fonte, Brushes.Black, e.MarginBounds, StringFormat.GenericTypographic);

            impressao = impressao.Substring(charactersOnPage);

            e.HasMorePages = false;
        }

I need to output something like:

Produto: Carro
Produto: Bicicleta

With this my code, the products are all shuffled one on top of the other.

It's the first time I'm studying printing.

    
asked by anonymous 07.11.2014 / 14:59

1 answer

2

Your problem occurs because of this piece of code:

e.Graphics.DrawString(impressao, Fonte, Brushes.Black, e.MarginBounds, StringFormat.GenericTypographic);

As is always passing the same value from e.MarginBounds to DrawString , the various strings are all drawn within the same rectangle.

One way to solve your problem would be to create the whole text before you draw:

StringBuilder sb = new StringBuilder();
foreach (var cli in cliente.Produtos)
{
    sb.AppendFormat("Produto: {0}\n", cli.NomeProduto);
}

string stringFinal = sb.ToString();

e.Graphics.MeasureString(stringFinal, Fonte, e.MarginBounds.Size, StringFormat.GenericTypographic, out charactersOnPage, out linesPerPage);

e.Graphics.DrawString(stringFinal, Fonte, Brushes.Black, e.MarginBounds, StringFormat.GenericTypographic);

e.HasMorePages = false;
    
07.11.2014 / 16:04