主要的功能就是使用C#画矢量图,然后导出到Word、Excel、Powerpoint中,并且能够再次被编辑。以下是解决过程:
首先应该确定在Office文档中可编辑图形使用的格式;学习了相关资料,了解到Office文档主要支持三种矢量图的格式:1、VML图形,2、WMF文件格式,3、EMF文件格式。由于VML图开一般使用HTML语言进行描述,不便于进行操作,因此决定采用WMF和EMF文件格式。
接下来的工作就是要让C#根据提供的数据生成WMF或EMF格式的矢量图形;学习了C#提供的GDI+绘图类库,GDI+可以绘制矢量图形,代码示例如下:
/// <summary>
/// 导出为 Emf 或 Wmf 文件
/// </summary>
/// <param name="filePath">文件路径</param>
/// <returns>是否成功</returns>
private bool Export(string filePath)
{
try
{
Bitmap bmp = new Bitmap(220,220);
Graphics gs = Graphics.FromImage(bmp);
Metafile mf = new Metafile(filePath,gs.GetHdc());
Graphics g = Graphics.FromImage(mf);
Draw(g);
g.Save();
g.Dispose();
mf.Dispose();
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 绘制图形
/// </summary>
/// <param name="g">用于绘图的Graphics对象</param>
private void Draw(Graphics g)
{
HatchBrush hb = new HatchBrush(HatchStyle.LightUpwardDiagonal, Color.Black, Color.White);
g.FillEllipse(Brushes.Gray,10f,10f,200,200);
g.DrawEllipse(new Pen(Color.Black,1f),10f,10f,200,200);
g.FillEllipse(hb,30f,95f,30,30);
g.DrawEllipse(new Pen(Color.Black,1f),30f,95f,30,30);
g.FillEllipse(hb,160f,95f,30,30);
g.DrawEllipse(new Pen(Color.Black,1f),160f,95f,30,30);
g.FillEllipse(hb,95f,30f,30,30);
g.DrawEllipse(new Pen(Color.Black,1f),95f,30f,30,30);
g.FillEllipse(hb,95f,160f,30,30);
g.DrawEllipse(new Pen(Color.Black,1f),95f,160f,30,30);
g.FillEllipse(Brushes.Blue,60f,60f,100,100);
g.DrawEllipse(new Pen(Color.Black,1f),60f,60f,100,100);
g.FillEllipse(Brushes.BlanchedAlmond,95f,95f,30,30);
g.DrawEllipse(new Pen(Color.Black,1f),95f,95f,30,30);
g.DrawRectangle(new Pen(System.Drawing.Brushes.Blue,0.1f),6,6,208,208);
g.DrawLine(new Pen(Color.Black,0.1f),110f,110f,220f,25f);
g.DrawString("剖面图",new Font("宋体",9f),Brushes.Green,220f,20f);
}
产生的图形如下:
放大后效果: