2013-02-13 56 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(); 
    } 
} 
相關問題