2014-02-06 172 views
0

我的應用程序第一次加載文本文件中的RichTextBox whitout任何問題:爲什麼ITextSharp需要很長時間才能創建pdf?

 StreamReader str = new StreamReader("C:\\test.txt"); 

     while (str.Peek() != -1) 
     { 

      richtextbox1.AppendText(str.ReadToEnd()); 
     } 

在那之後,我想用iTextSharp的RichTextBox中的至PDF格式文本導出:

 iTextSharp.text.Document doc = new iTextSharp.text.Document(); 
     iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream(filename,  FileMode.Create)); 
     doc.Open(); 
     doc.Add(new iTextSharp.text.Paragraph(richtextbox1.Text)); 
     doc.Close(); 

我已經使用的BackgroundWorker但它並沒有幫助我:

 private delegate void upme(string filenamed); 

    private void callpdf(string filename) 
    { 
     iTextSharp.text.Document doc = new iTextSharp.text.Document(); 
     iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream(filename, FileMode.Create)); 
     doc.Open(); 
     doc.Add(new iTextSharp.text.Paragraph(richtextbox1.Text)); 
     doc.Close(); 
    } 

    private void savepdfformat(string filenames) 
{ 
    BackgroundWorker bg = new BackgroundWorker(); 

    bg.DoWork += delegate(object s, DoWorkEventArgs args) 
    { 
     upme movv = new upme(callpdf); 

     richtextbox1.Dispatcher.Invoke(movv, System.Windows.Threading.DispatcherPriority.Normal, filenames); 

    }; 
    bg.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args) 
    { 
     MessageBox.Show("done"); 
    }; 

    bg.RunWorkerAsync(); 
} 

test.txt的是約2 MB的大小,它加載速度非常快的richtextbox1但當IW螞蟻到

將其轉換爲pdf,它需要很長時間,應用程序掛起。

我應該怎麼做優化?

感謝您的任何幫助。

+0

一些快速的評論:(1)你能提供一些內容rtf文件(2)如果你的應用程序掛起它,因爲你正在處理主線程。在後臺/工作線程和應用程序上的進程將繼續正常運行。 (3)「很長時間」有多久? –

+0

我已經使用了後臺工作,但沒有幫助。這需要很長時間。現在我將使用後臺工作人員更新代碼。 –

回答

3

解決方法很簡單:逐行讀取text.txt文件,爲每行創建一個Paragraph,並儘可能快地將每個Paragraph對象添加到文檔中。

爲什麼這是解決方案?

您的代碼存在設計缺陷:消耗大量內存:首先在richtextbox1對象中加載2 MByte。然後,將相同的2 MByte加載到Paragraph對象中。原來的2 MByte仍在內存中,但Paragraph開始分配內存來處理文本。然後將Paragraph添加到文檔中。內存以頁爲單位發佈(iText在頁面已滿時立即刷新內容),但處理過程仍需要大量內存。當你的電腦「掛起」時,他可能會交換內存。

我看到你的綽號是聰明人,但我想你是個年輕人。如果你和我一樣年紀,你會知道內存昂貴的時代,而且不能通過設計浪費內存;-)

+0

謝謝你的回答,我會記住它。 +1爲您投票。 –

相關問題