2014-02-06 176 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为您投票。 –

相关问题