为什么ITextSharp需要很长时间来创建pdf?

Sma*_*Man 0 c# wpf optimization itextsharp

我的应用程序首先加载文本文件在richtextbox whitout任何问题:

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

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

            richtextbox1.AppendText(str.ReadToEnd());
        }
Run Code Online (Sandbox Code Playgroud)

之后,我想使用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();
Run Code Online (Sandbox Code Playgroud)

我使用了背景工作者,但它没有帮助我:

     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();   
}
Run Code Online (Sandbox Code Playgroud)

test.txt的大小约为2 mb,它在richtextbox1中的加载速度非常快,但是当我想要的时候

将其转换为pdf,需要很长时间,应用程序挂起.

我该怎么做优化?

谢谢你的帮助.

Bru*_*gie 5

解决方案很简单:逐行读取text.txt文件,Paragraph为每一行创建一个,并Paragraph尽快将每个对象添加到文档中.

为什么这是解决方案?

您的代码在设计上存在缺陷:它占用大量内存:首先在richtextbox1对象中加载2 MByte .然后将相同的2 MByte加载到Paragraph对象中.原始的2 MByte仍然在内存中,但Paragraph开始分配内存来处理文本.然后添加Paragraph到文档.内存以页面为单位发布(iText会在页面填满后立即刷新内容),但处理仍需要大量内存.当你的电脑"挂起"时,他可能正在交换内存.

我看到你的昵称是聪明人,但我猜你是个年轻人.如果你和我一样年纪,你就会知道记忆力昂贵的日子,人们无法承受设计浪费的记忆;-)