Domanda

my application first load the text file in richtextbox whitout any problem :

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

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

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

after that , i want to export the text of richtextbox to pdf format using itextsharp :

      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();

i have used backgroundworker but it did not help me :

     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();   
}

the test.txt is about 2 mb size , it loads very fast in richtextbox1 but when i want to

convert it to pdf, it takes very time and the application hangs.

what should i do for optimization?

thanks for any help.

È stato utile?

Soluzione

The solution is simple: read the text.txt file line by line, create a Paragraph for each line and add each Paragraph object to the document as soon as possible.

Why is this the solution?

Your code is flawed by design: it consumes an enormous amount of memory: first you load 2 MByte in the richtextbox1 object. Then you load the same 2 MByte into the Paragraph object. The original 2 MByte is still in memory, but Paragraph starts allocating memory to process the text. Then you add the Paragraph to the document. Memory is released on a page per page basis (iText flushes content as soon as a page is full), but the processing still requires plenty of memory. When your computer "hangs", he's probably swapping memory.

I see that your nickname is Smart Man, but I guess you're a Young Man. If you were as old as I am, you'd have known the days when memory was expensive and one couldn't afford wasting memory by design ;-)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top