I have to print a string that can vary in size. What I need is if this string does not fit on the page the remaining text is printed on another. I know for this I need to do something using e.HasMorePages
but I do not know how. I've been researching but I do not find anything relevant. Take a look at some of the code that appears in the event printPage
:
string textoFinal = "\n\n\n\n\n\n\n\n\n\n\n" + cabInf + cab + sb.ToString() + soma + stringObs + final + final2;
StringFormat alinhar = new StringFormat(StringFormatFlags.NoClip);
alinhar.Alignment = StringAlignment.Near;
e.Graphics.DrawString(textoFinal, Fonte, Brushes.Black, e.MarginBounds, alinhar);
e.HasMorePages = false;
If I go to true
o e.HasMorePages
when printing I get a page count loop. I need something to check if the string has exceeded the page limit, and if it passed, the text that did not fit should be printed on another page.
EDIT
I have this code to print:
string textoFinal;
string stringCopia;
internal void Imprimir()
{
Cliente cliente = Clientes[listaClientes.SelectedIndex];
StringBuilder sb = new StringBuilder();
foreach (var cli in cliente.Produtos)
{
sb.AppendFormat("\n\n{0}.....................Valor: R${1} - Data: {2}", cli.NomeProduto, cli.ValorProduto, cli.DataCompra);
}
textoFinal = sb.ToString();
stringCopia = textoFinal;
printDocumento.PrintPage += printDocumento_PrintPage;
Margins margem = new Margins(20, 20, 20, 20);
printDocumento.DefaultPageSettings.Margins = margem;
printPrevisao.ShowDialog();
}
In event printPage
consists:
int caracteresNaPagina = 0;
int linhasPorPagina = 0;
var Fonte = new Font("Arial", 9);
e.Graphics.DrawImage(Properties.Resources.logoI, 20, 20);
StringFormat alinhar = new StringFormat(StringFormatFlags.NoClip);
alinhar.Alignment = StringAlignment.Near;
e.Graphics.MeasureString(stringCopia, Fonte, e.MarginBounds.Size, alinhar, out caracteresNaPagina, out linhasPorPagina);
e.Graphics.DrawString(stringCopia, Fonte, Brushes.Black, e.MarginBounds, alinhar);
stringCopia = stringCopia.Substring(caracteresNaPagina);
e.HasMorePages = stringCopia.Length > 0;
if (!e.HasMorePages)
stringCopia = textoFinal;
In this way the rest of the text that did not fit the page is being written at the beginning of the same page, shuffling the texts instead of moving to another page.
PROBLEM SOLVING Home It worked perfectly after removing the lineprintDocumento.PrintPage += printDocumento_PrintPage;
Why? Because I'm developing this in winforms and I already had this method pointing to the event. In this way, the text was written twice in the print document and shuffled.