Stampa di grafici
Nel controllo Chart per Windows Form è possibile stampare l'immagine del grafico. A questo scopo, utilizzare la proprietà Printing del controllo Chart. Questo oggetto stampa tutti gli elementi del controllo Chart presenti nella visualizzazione corrente dei dati, con l'esclusione delle barre di scorrimento.
È possibile richiamare la finestra di dialogo Stampa oppure stampare in background. La proprietà PrintDocument dell'oggetto Printing consente di impostare le proprietà di stampa, come ad esempio i margini della pagina.
Stampa personalizzata
Per stampare l'immagine del grafico in un documento che contiene altri elementi, richiamare il metodo PrintPaint all'interno di un oggetto PrintPageEventHandler. È necessario passare la proprietà Graphics dell'oggetto PrintPageEventArgs, insieme con un oggetto Rectangle che definisce la posizione dell'immagine del grafico nel documento, come argomenti del metodo PrintPaint.
Nell'esempio di codice riportato di seguito viene illustrato come stampare un documento con una riga di testo seguita dall'immagine del grafico e da una seconda riga di testo.
' Create new PrintDocument
Dim pd As New System.Drawing.Printing.PrintDocument()
' Add the event handler, and then print
AddHandler pd.PrintPage, AddressOf pd_PrintPage
' Print the document
pd.Print()
...
Private Sub pd_PrintPage(ByVal sender As Object, ByVal ev As PrintPageEventArgs)
' Create and initialize print font
Dim printFont As New System.Drawing.Font("Arial", 10)
' Create Rectangle structure, used to set the position of the chart
Dim myRec As New System.Drawing.Rectangle(10, 30, 150, 150)
' Draw a line of text, followed by the chart, and then another line of text
ev.Graphics.DrawString("Line before chart", printFont, Brushes.Black, 10, 10)
chart1.Printing.PrintPaint (ev.Graphics, myRec)
ev.Graphics.DrawString("Line after chart", printFont, Brushes.Black, 10, 200)
End Sub
// Create new PrintDocument
System.Drawing.Printing.PrintDocument pd = new System.Drawing.Printing.PrintDocument();
// Add a PrintPageEventHandler for the document
pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
// Print the document
pd.Print();
...
private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
// Create and initialize print font
System.Drawing.Font printFont = new System.Drawing.Font("Arial", 10);
// Create Rectangle structure, used to set the position of the chart Rectangle
myRec = new System.Drawing.Rectangle(10, 30, 150, 150);
// Draw a line of text, followed by the chart, and then another line of text
ev.Graphics.DrawString("Line before chart", printFont, Brushes.Black, 10, 10);
chart1.Printing.PrintPaint (ev.Graphics, myRec);
ev.Graphics.DrawString("Line after chart", printFont, Brushes.Black, 10, 200);
}