Saltar al contenido

Imprimir en C # (wpf)

Solución:

Imprimir en WPF es simple y no tan simple.

Comienza básicamente con una o dos líneas de código que ya está imprimiendo.

private void PrintBtn_Click(object sender, RoutedEventArgs e)
{
    PrintDialog printDialog = new PrintDialog();
    if (printDialog.ShowDialog() == true)
    {
    printDialog.PrintVisual(grid, "My First Print Job");
    }
}

Sin embargo, la paginación en WPF no se realiza con una sola línea de código. Luego ingresa a FlowDocuments y temas similares más avanzados.

Si está creando una herramienta no comercial para usted, considere iTextSharp, que también es muy buena.

Si desea imprimir todos los registros de la cuadrícula de datos en WPF. En el que he creado un documento de flujo utilizando código, puede comprender la lógica y hacerlo de acuerdo con sus propios requisitos. Después de mucho trabajo. He hecho código recientemente. Es código probado. Imprimirá cada cuadrícula de datos con todos los registros. Es un código fácil y simple. Usted agregaría una clase. Si desea decorar una cuadrícula de datos, vaya a la clase PrintDG y luego decórelo de acuerdo con sus propios requisitos.
Sigue estos pasos.
Paso 1: agregue estas referencias en la parte superior.

 using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;

Paso 2: agregue la clase PrintDG.cs.

  public  class PrintDG
{
         public void printDG(DataGrid dataGrid, string title)
    {



        PrintDialog printDialog = new PrintDialog();
        if (printDialog.ShowDialog() == true)
        {
            FlowDocument fd = new FlowDocument();

            Paragraph p = new Paragraph(new Run(title));
            p.FontStyle = dataGrid.FontStyle;
            p.FontFamily = dataGrid.FontFamily;
            p.FontSize = 18;
            fd.Blocks.Add(p);

            Table table = new Table();
            TableRowGroup tableRowGroup = new TableRowGroup();
            TableRow r = new TableRow();
            fd.PageWidth = printDialog.PrintableAreaWidth;
            fd.PageHeight = printDialog.PrintableAreaHeight;
            fd.BringIntoView();

            fd.TextAlignment = TextAlignment.Center;
            fd.ColumnWidth = 500;
            table.CellSpacing = 0;

            var headerList = dataGrid.Columns.Select(e => e.Header.ToString()).ToList();


            for (int j = 0; j < headerList.Count; j++)
            {

                r.Cells.Add(new TableCell(new Paragraph(new Run(headerList[j]))));
                r.Cells[j].ColumnSpan = 4;
                r.Cells[j].Padding = new Thickness(4);

                r.Cells[j].BorderBrush = Brushes.Black;
                r.Cells[j].FontWeight = FontWeights.Bold;
                r.Cells[j].Background = Brushes.DarkGray;
                r.Cells[j].Foreground = Brushes.White;
                r.Cells[j].BorderThickness = new Thickness(1, 1, 1, 1);
            }
            tableRowGroup.Rows.Add(r);
            table.RowGroups.Add(tableRowGroup);
            for (int i = 0; i < dataGrid.Items.Count; i++)
            {

                DataRowView row = (DataRowView)dataGrid.Items.GetItemAt(i);

                table.BorderBrush = Brushes.Gray;
                table.BorderThickness = new Thickness(1, 1, 0, 0);
                table.FontStyle = dataGrid.FontStyle;
                table.FontFamily = dataGrid.FontFamily;
                table.FontSize = 13;
                tableRowGroup = new TableRowGroup();
                r = new TableRow();
                for (int j = 0; j < row.Row.ItemArray.Count(); j++)
                {

                    r.Cells.Add(new TableCell(new Paragraph(new Run(row.Row.ItemArray[j].ToString()))));
                    r.Cells[j].ColumnSpan = 4;
                    r.Cells[j].Padding = new Thickness(4);

                    r.Cells[j].BorderBrush = Brushes.DarkGray;
                    r.Cells[j].BorderThickness = new Thickness(0, 0, 1, 1);
                }

                tableRowGroup.Rows.Add(r);
                table.RowGroups.Add(tableRowGroup);

            }
            fd.Blocks.Add(table);

            printDialog.PrintDocument(((IDocumentPaginatorSource)fd).DocumentPaginator, "");

        }
    }

}

Paso 2: Luego vaya al evento de clic del botón de impresión y cree el objeto de la clase PrintDG, luego llame a printDG y le pase dos parámetros datagridname y title.
Igual que :

private void print_button_Click(object sender, RoutedEventArgs e)
    {
            PrintDG print = new PrintDG();

 print.printDG(datagridName, "Title");
}

Si ocurre algún error durante la ejecución, dígame que lo resolveré. Se está ejecutando el código que solo usted copia y pega.

Estos enlaces pueden ayudarlo a comprender cómo funciona la impresión y qué utilizar exactamente:

http://www.charlespetzold.com/blog/2006/02/201111.html

http://msdn.microsoft.com/en-us/library/ms742418(v=vs.100).aspx

http://www.switchonthecode.com/tutorials/printing-in-wpf

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *