2013-02-13 22 views
0

我需要通过代码动态创建文档,然后将其打印并保存到.doc文件中。到目前为止,我已经设法使用图形类来打印文档,但我不知道如何让它以.doc或任何文本格式保存文件。是否有可能做到这一点?如果是的话,该怎么办?如何使用图形类写入c#中的文本文件

+1

我不知道的.doc创作,但我的直觉告诉我,使用图形类的文件保存到磁盘是可怕的错误:■ – Nolonar 2013-02-13 07:33:51

+0

如果你是指的是['System.Drawing.Graphics'](http://msdn.microsoft.com/en-us/library/system.drawing.graphics.aspx),这是不可能的。该类的目的是在绘图表面(画布)上绘制(创建图形),将其作为屏幕上的区域,位图图像或虚拟页面模型(可以交给打印机)。它不*旨在将任何内容带入任何类型的文本文件,因为文本文件(包括doc文件)没有任何绘图表面。 – 2013-02-13 07:36:37

+0

嗯谢谢不知道这一点 – 2013-02-13 09:49:35

回答

0

我不确定这是你在找什么,但是如果你想用磁盘上的图形保存你生成的东西,你可以使用Windows图元文件(wmf)。如果g是您的Graphics情况下,这样的事情:

 IntPtr hdc = g.GetHdc(); 
     Rectangle rect = new Rectangle(0, 0, 200, 200); 
     Metafile curMetafile = new Metafile(@"c:\tmp\newFile.wmf", hdc); 
     Graphics mfG = Graphics.FromImage(curMetafile); 
     mfG.DrawString("foo", new Font("Arial", 10), Brushes.Black, new PointF(10, 10)); 
     g.ReleaseHdc(hdc); 
     mfG.Dispose(); 
0

假设你真的不意味着你要保存的图形,文本,只是想创建那么Word文档,你需要看看Microsoft.Office.Interop.Word

即从DotNetPearls

using System; 
using Microsoft.Office.Interop.Word; 

class Program 
{ 
    static void Main() 
    { 
    // Open a doc file. 
    Application application = new Application(); 
    Document document = application.Documents.Open("C:\\word.doc"); 

    // Loop through all words in the document. 
    int count = document.Words.Count; 
    for (int i = 1; i <= count; i++) 
    { 
     // Write the word. 
     string text = document.Words[i].Text; 
     Console.WriteLine("Word {0} = {1}", i, text); 
    } 
    // Close word. 
    application.Quit(); 
    } 
} 
相关问题