在c#中打印图表

时间:2010-10-27 08:59:13

标签: c# printing charts

我可以使用以下方法从我的c#项目打印图表:

chart1.Printing.PrintDocument.DocumentName = "Graph of data";

但是可以为此添加标题吗?我希望文档名称可以实现这一点,但显然不是!

2 个答案:

答案 0 :(得分:3)

您可以直接在页面上打印任何内容,然后调用图表PrintPaint()。请注意,如果您不将PageUnit切换为像素,则图表缩放会变得混乱。

void PrintChart(object sender, PrintPageEventArgs ev)
    {
        using (var f = new System.Drawing.Font("Arial", 10))
        {
            var size = ev.Graphics.MeasureString(Text, f);
            ev.Graphics.DrawString("Whatever text you want", f, Brushes.Black, ev.PageBounds.X + (ev.PageBounds.Width - size.Width) / 2, ev.PageBounds.Y);
        }

        //Note, the chart printing code wants to print in pixels.
        Rectangle marginBounds = ev.MarginBounds;
        if (ev.Graphics.PageUnit != GraphicsUnit.Pixel)
        {
            ev.Graphics.PageUnit = GraphicsUnit.Pixel;
            marginBounds.X = (int)(marginBounds.X * (ev.Graphics.DpiX / 100f));
            marginBounds.Y = (int)(marginBounds.Y * (ev.Graphics.DpiY / 100f));
            marginBounds.Width = (int)(marginBounds.Width * (ev.Graphics.DpiX / 100f));
            marginBounds.Height = (int)(marginBounds.Height * (ev.Graphics.DpiY / 100f));
        }

        chart1.Printing.PrintPaint(ev.Graphics, marginBounds);
    }

此菜单处理程序打开PrintDialog()。如果您不想要对话,可以拨打pd.Print()

  private void printToolStripMenuItem_Click(object sender, EventArgs e)
    {
        var pd = new System.Drawing.Printing.PrintDocument();
        pd.PrintPage += new PrintPageEventHandler(PrintChart);

        PrintDialog pdi = new PrintDialog();
        pdi.Document = pd;
        if (pdi.ShowDialog() == DialogResult.OK)
            pdi.Document.Print();
    }

答案 1 :(得分:2)

如果您将ChartingControl放在Windows窗体上的Panel控件内,这是解决您问题的解决方法。然后,您可以在面板内打印面板,您可以将文档标题添加为标签以及您要添加的任何其他内容。

首先从工具箱中添加PrintDocument控件并将其命名为MyPrintDocument

然后添加Panel控件并将图表放入其中。

确保您已导入System.Drawing命名空间,然后您可以像这样打印面板。

    Bitmap MyChartPanel = new Bitmap(panel1.Width, panel1.Height);
    panel1.DrawToBitmap(MyChartPanel, new Rectangle(0, 0, panel1.Width, panel1.Height));

    PrintDialog MyPrintDialog = new PrintDialog();

    if (MyPrintDialog.ShowDialog() == DialogResult.OK)
    {
        System.Drawing.Printing.PrinterSettings values;
        values = MyPrintDialog.PrinterSettings;
        MyPrintDialog.Document = MyPrintDocument;
        MyPrintDocument.PrintController = new System.Drawing.Printing.StandardPrintController();
        MyPrintDocument.Print();
    }

    MyPrintDocument.Dispose();

此代码将面板转换为Bitmap,然后打印Bitmap

您可以将其压缩为如下函数:

public void PrintPanel(Panel MyPanel)
{
   // Add code from above in here, changing panel1 to MyPanel...
}