domenica 6 novembre 2011

Un modo per stampare un DataTable in C#

Ecco una classe che implementa una possibile soluzione al problema di stampare un datatable in C# senza l'uso di strumenti reportistici di terze parti.

Dopo aver aggiunto la classe MyDataTablePrinter al progetto ecco come utilizzarla:

1) aggiungere un componente di tipo PrintDocument
2) Aggiungere l'evento PrintPage dell'oggetto PrintDocument
private void cmdPrint_Click(object sender, EventArgs e)
{
   if (SetupThePrinting(dataTable))
       MyPrintDocument.Print();
}

private bool SetupThePrinting(DataTable ds)
{
PrintDialog MyPrintDialog = new PrintDialog();
MyPrintDialog.AllowCurrentPage = false;
MyPrintDialog.AllowPrintToFile = false;
MyPrintDialog.AllowSelection = false;
MyPrintDialog.AllowSomePages = false;
MyPrintDialog.PrintToFile = false;
MyPrintDialog.ShowHelp = false;
MyPrintDialog.ShowNetwork = false;

if (MyPrintDialog.ShowDialog() != DialogResult.OK)
    return false;

MyPrintDocument.DocumentName = "Test";
MyPrintDocument.PrinterSettings = MyPrintDialog.PrinterSettings;
MyPrintDocument.DefaultPageSettings = MyPrintDialog.PrinterSettings.DefaultPageSettings;
MyPrintDocument.DefaultPageSettings.Margins =new Margins(40, 40, 40, 40);

m_MyPrinter = new MyDataTablePrinter(ds,MyPrintDocument);

m_MyPrinter.m_FooterText = DateTime.Now.ToLongDateString() + ", Firma ______________________________________________";
m_MyPrinter.m_FooterFont = new Font("Tahoma", 10, FontStyle.Regular, GraphicsUnit.Point);
m_MyPrinter.m_FooterColor = Color.Black;

m_MyPrinter.m_TitleText = "Titolo.....";
m_MyPrinter.m_TitleFont = new Font("Tahoma", 18, FontStyle.Regular, GraphicsUnit.Point);
m_MyPrinter.m_TitleColor = Color.Black;

m_MyPrinter.m_RowFont = new Font("Tahoma", 9, FontStyle.Regular, GraphicsUnit.Point);
m_MyPrinter.m_RowBackColor = Color.White;
m_MyPrinter.m_RowColor = Color.Black;

m_MyPrinter.m_headerFont = new Font("Tahoma", 8, FontStyle.Bold, GraphicsUnit.Point);
m_MyPrinter.m_HeaderColor = Color.Black;
m_MyPrinter.m_HeaderBackGroudColor = Color.LightGray;

m_MyPrinter.m_GridColor = Color.Black;

return true;
}

private void MyPrintDocument_PrintPage(object sender, PrintPageEventArgs e)
{
bool more = m_MyPrinter.DrawDataTable(e.Graphics);
if (more == true) e.HasMorePages = true; }

Potete scaricare la classe a questo indirizzo

Nessun commento:

Posta un commento

Mi raccomando, non costringermi a censurare il tuo commento, perciò sii educato!