Printing in C# (wpf)

63,442

Solution 1

Printing in WPF is both simple and not so simple.

It starts with basically with one or two lines of code you are printing already.

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

However, pagination in WPF is not done with a single line of code. Then you get into FlowDocuments and similar more advanced topics.

If you are making a non-commercial tool for yourself, consider iTextSharp which is very good too.

Solution 2

If you want to print all records from Datagrid in WPF. In which I have create flow document using code you can understand logic and make it according to own requirement. After a lot of working. I have done code recently. It is tested code. It will print every datagrid with all records. It is easy and simple code. You would add a class. If you want to decorate a datagrid then go to PrintDG class then decorate it according to own requirement.
Follow these steps.
Step1:Add these references on top.

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

Step2: Add class PrintDG.cs.

public class PrintDG
{
    public 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, "");

        }
    }

}

Step2: Then go to print button click event and create object of PrintDG class then call printDG pass to It two parameters datagridname and title.
Like :

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

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

If any erorr occure during execution tell me I will solve It.The is running code only you copy and past.

Solution 3

These links may help you in understanding how printing works and what exactly to use:

http://www.charlespetzold.com/blog/2006/02/201111.html (archive.org)

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

http://www.switchonthecode.com/tutorials/printing-in-wpf (archive.org)

Share:
63,442
Sander Declerck
Author by

Sander Declerck

"Cycling Coffee loving know it all in a good way sharing is caring genius" - Laura Landuyt

Updated on July 17, 2022

Comments

  • Sander Declerck
    Sander Declerck almost 2 years

    I'm making a C# WPF program, and my program has to be able to print invoices, but I'm kinda struggling to find out how printing works in WPF... If I remember well from programming in winforms, there you'd use GDI+ to print. However, I assume that's not the case with WPF.

    I would be very happy if someone could point me in the right direction with some links to helpful documents or examples...

  • Bek Raupov
    Bek Raupov about 13 years
    not sure why it has negative rating, is it because it just had links to source and no summary?
  • honzakuzel1989
    honzakuzel1989 almost 9 years
    The last two links are not longer available.
  • Raven
    Raven almost 8 years
    @BekRaupov its frounded upon to just post links as they may become broken in the future and then the answer becomes pointless.. (as im posting this the last link is broken...)
  • maxp
    maxp over 7 years
    The historic article can be retrieved here: web.archive.org/web/20091025074908/http://www.eggheadcafe.co‌​m/… Funnily clicking the'Printer friendly version' makes it far more readable.
  • EJoshuaS - Stand with Ukraine
    EJoshuaS - Stand with Ukraine about 6 years
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review
  • Muhammad Mehdi
    Muhammad Mehdi about 6 years
    This answere is useful why you make negative ? If any eror occure during in your execution tell me i would solved it.You just copy and past.
  • Yun CHEN
    Yun CHEN over 5 years
    I like the first print job!