Set margins and paper size with PrintDocument

1

I need to print labels and I'm using PrintDocument , but there's a problem I do not know how I create the page for printing.

Ex. my tag has 4cm height and 10cm wide with margins of 0.2cm . How can I configure these

private void btnImprimir_Click(object sender, EventArgs e)
    {
       for (int i = 0; i < iQuantidadeVolumes; i++)
        {
            var volumeUnico = (i + 1).ToString();

            for (int ii = 0; ii < ListaConteudoImpressao.Count; ii++)
            {
                if (ListaConteudoImpressao[ii].Contains("VOLUME : "))
                {
                    ListaConteudoImpressao[ii] = sTextoNF +  "VOLUME : " + volumeUnico + "/" + iQuantidadeVolumes.ToString();                     
                    Documento.PrinterSettings.PrinterName = sNomeImpressora; 
                    Documento.DefaultPageSettings.Landscape = true;
                    Documento.Print();

                } 
            }
        }
    }

    private void Documeto_PrintPage(object sender, PrintPageEventArgs e)
    {
        string texto = "";
        Font letra = new Font("Aerial", 23, FontStyle.Bold, GraphicsUnit.Pixel);
        SolidBrush cor = new SolidBrush(Color.Black);
        Rectangle retangulo = new Rectangle(0, 100, largura, 30);
        StringFormat alinhamento = new StringFormat();
        alinhamento.Alignment = StringAlignment.Center;
        alinhamento.LineAlignment = StringAlignment.Center;
        e.Graphics.DrawString(texto.ToUpper(), letra, cor, retangulo, alinhamento);

        int y = 170;
        foreach (string frase in ListaConteudoImpressao)
        {
            e.Graphics.DrawString(frase, letra, cor, new Point(20, y));
            y += 40;
        }

    }
  }
}
    
asked by anonymous 26.01.2017 / 23:10

1 answer

0

You can do this as follows:

private void btnImprimir_Click(object sender, EventArgs e)
{
    // ...

    Documento.DefaultPageSettings.Landscape = true;

    // Para configurar as margens
    int margemIn = CentimetrosParaCentesimasPolegada(0.2); // https://msdn.microsoft.com/pt-br/library/system.drawing.printing.pagesettings.margins(v=vs.110).aspx
    Documento.DefaultPageSettings.Margins = new Margins(margemIn, margemIn, margemIn, margemIn);

    // Para configurar o tamanho do papel a ser usado
    int larguraIn = CentimetrosParaCentesimasPolegada(10);
    int alturaIn = CentimetrosParaCentesimasPolegada(4);
    PaperSize paperSize = new PaperSize("MeuTipo", larguraIn, alturaIn);
    Documento.DefaultPageSettings.PaperSize = paperSize;
    Documento.PrinterSettings.DefaultPageSettings.PaperSize = paperSize;

    // ...
}

Note that the measures used by PrintDocument are hundredths of inches, so you need a method that converts your values into centimeters:

private static int CentimetrosParaCentesimasPolegada(double cm)
{
    return (int) Math.Round(cm / 0.393701 * 100, MidpointRounding.AwayFromZero);
}
    
27.01.2017 / 10:00